repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/mro.rs
crates/ty_python_semantic/src/types/mro.rs
use std::collections::VecDeque; use std::ops::Deref; use indexmap::IndexMap; use rustc_hash::FxBuildHasher; use crate::Db; use crate::types::class_base::ClassBase; use crate::types::generics::Specialization; use crate::types::{ClassLiteral, ClassType, KnownClass, KnownInstanceType, SpecialFormType, Type}; /// The inferred method resolution order of a given class. /// /// An MRO cannot contain non-specialized generic classes. (This is why [`ClassBase`] contains a /// [`ClassType`], not a [`ClassLiteral`].) Any generic classes in a base class list are always /// specialized — either because the class is explicitly specialized if there is a subscript /// expression, or because we create the default specialization if there isn't. /// /// The MRO of a non-specialized generic class can contain generic classes that are specialized /// with a typevar from the inheriting class. When the inheriting class is specialized, the MRO of /// the resulting generic alias will substitute those type variables accordingly. For instance, in /// the following example, the MRO of `D[int]` includes `C[int]`, and the MRO of `D[U]` includes /// `C[U]` (which is a generic alias, not a non-specialized generic class): /// /// ```py /// class C[T]: ... /// class D[U](C[U]): ... /// ``` /// /// See [`ClassType::iter_mro`] for more details. #[derive(PartialEq, Eq, Clone, Debug, salsa::Update, get_size2::GetSize)] pub(super) struct Mro<'db>(Box<[ClassBase<'db>]>); impl<'db> Mro<'db> { /// Attempt to resolve the MRO of a given class. Because we derive the MRO from the list of /// base classes in the class definition, this operation is performed on a [class /// literal][ClassLiteral], not a [class type][ClassType]. (You can _also_ get the MRO of a /// class type, but this is done by first getting the MRO of the underlying class literal, and /// specializing each base class as needed if the class type is a generic alias.) /// /// In the event that a possible list of bases would (or could) lead to a `TypeError` being /// raised at runtime due to an unresolvable MRO, we infer the MRO of the class as being `[<the /// class in question>, Unknown, object]`. This seems most likely to reduce the possibility of /// cascading errors elsewhere. (For a generic class, the first entry in this fallback MRO uses /// the default specialization of the class's type variables.) /// /// (We emit a diagnostic warning about the runtime `TypeError` in /// [`super::infer::infer_scope_types`].) pub(super) fn of_class( db: &'db dyn Db, class_literal: ClassLiteral<'db>, specialization: Option<Specialization<'db>>, ) -> Result<Self, MroError<'db>> { let class = class_literal.apply_optional_specialization(db, specialization); // Special-case `NotImplementedType`: typeshed says that it inherits from `Any`, // but this causes more problems than it fixes. if class_literal.is_known(db, KnownClass::NotImplementedType) { return Ok(Self::from([ClassBase::Class(class), ClassBase::object(db)])); } Self::of_class_impl(db, class, class_literal.explicit_bases(db), specialization) .map_err(|err| err.into_mro_error(db, class)) } pub(super) fn from_error(db: &'db dyn Db, class: ClassType<'db>) -> Self { Self::from([ ClassBase::Class(class), ClassBase::unknown(), ClassBase::object(db), ]) } fn of_class_impl( db: &'db dyn Db, class: ClassType<'db>, original_bases: &[Type<'db>], specialization: Option<Specialization<'db>>, ) -> Result<Self, MroErrorKind<'db>> { /// Possibly add `Generic` to the resolved bases list. /// /// This function is called in two cases: /// - If we encounter a subscripted `Generic` in the original bases list /// (`Generic[T]` or similar) /// - If the class has PEP-695 type parameters, /// `Generic` is [implicitly appended] to the bases list at runtime /// /// Whether or not `Generic` is added to the bases list depends on: /// - Whether `Protocol` is present in the original bases list /// - Whether any of the bases yet to be visited in the original bases list /// is a generic alias (which would therefore have `Generic` in its MRO) /// /// This function emulates the behavior of `typing._GenericAlias.__mro_entries__` at /// <https://github.com/python/cpython/blob/ad42dc1909bdf8ec775b63fb22ed48ff42797a17/Lib/typing.py#L1487-L1500>. /// /// [implicitly inherits]: https://docs.python.org/3/reference/compound_stmts.html#generic-classes fn maybe_add_generic<'db>( resolved_bases: &mut Vec<ClassBase<'db>>, original_bases: &[Type<'db>], remaining_bases: &[Type<'db>], ) { if original_bases.contains(&Type::SpecialForm(SpecialFormType::Protocol)) { return; } if remaining_bases.iter().any(Type::is_generic_alias) { return; } resolved_bases.push(ClassBase::Generic); } match original_bases { // `builtins.object` is the special case: // the only class in Python that has an MRO with length <2 [] if class.is_object(db) => Ok(Self::from([ // object is not generic, so the default specialization should be a no-op ClassBase::Class(class), ])), // All other classes in Python have an MRO with length >=2. // Even if a class has no explicit base classes, // it will implicitly inherit from `object` at runtime; // `object` will appear in the class's `__bases__` list and `__mro__`: // // ```pycon // >>> class Foo: ... // ... // >>> Foo.__bases__ // (<class 'object'>,) // >>> Foo.__mro__ // (<class '__main__.Foo'>, <class 'object'>) // ``` [] => { // e.g. `class Foo[T]: ...` implicitly has `Generic` inserted into its bases if class.has_pep_695_type_params(db) { Ok(Self::from([ ClassBase::Class(class), ClassBase::Generic, ClassBase::object(db), ])) } else { Ok(Self::from([ClassBase::Class(class), ClassBase::object(db)])) } } // Fast path for a class that has only a single explicit base. // // This *could* theoretically be handled by the final branch below, // but it's a common case (i.e., worth optimizing for), // and the `c3_merge` function requires lots of allocations. [single_base] if !class.has_pep_695_type_params(db) && !matches!( single_base, Type::GenericAlias(_) | Type::KnownInstance( KnownInstanceType::SubscriptedGeneric(_) | KnownInstanceType::SubscriptedProtocol(_) ) ) => { ClassBase::try_from_type(db, *single_base, class.class_literal(db).0).map_or_else( || Err(MroErrorKind::InvalidBases(Box::from([(0, *single_base)]))), |single_base| { if single_base.has_cyclic_mro(db) { Err(MroErrorKind::InheritanceCycle) } else { Ok(std::iter::once(ClassBase::Class(class)) .chain(single_base.mro(db, specialization)) .collect()) } }, ) } // The class has multiple explicit bases. // // We'll fallback to a full implementation of the C3-merge algorithm to determine // what MRO Python will give this class at runtime // (if an MRO is indeed resolvable at all!) _ => { let mut resolved_bases = vec![]; let mut invalid_bases = vec![]; for (i, base) in original_bases.iter().enumerate() { // Note that we emit a diagnostic for inheriting from bare (unsubscripted) `Generic` elsewhere // (see `infer::TypeInferenceBuilder::check_class_definitions`), // which is why we only care about `KnownInstanceType::Generic(Some(_))`, // not `KnownInstanceType::Generic(None)`. if let Type::KnownInstance(KnownInstanceType::SubscriptedGeneric(_)) = base { maybe_add_generic( &mut resolved_bases, original_bases, &original_bases[i + 1..], ); } else { match ClassBase::try_from_type(db, *base, class.class_literal(db).0) { Some(valid_base) => resolved_bases.push(valid_base), None => invalid_bases.push((i, *base)), } } } if !invalid_bases.is_empty() { return Err(MroErrorKind::InvalidBases(invalid_bases.into_boxed_slice())); } // `Generic` is implicitly added to the bases list of a class that has PEP-695 type parameters // (documented at https://docs.python.org/3/reference/compound_stmts.html#generic-classes) if class.has_pep_695_type_params(db) { maybe_add_generic(&mut resolved_bases, original_bases, &[]); } let mut seqs = vec![VecDeque::from([ClassBase::Class(class)])]; for base in &resolved_bases { if base.has_cyclic_mro(db) { return Err(MroErrorKind::InheritanceCycle); } seqs.push(base.mro(db, specialization).collect()); } seqs.push( resolved_bases .iter() .map(|base| base.apply_optional_specialization(db, specialization)) .collect(), ); if let Some(mro) = c3_merge(seqs) { return Ok(mro); } // We now know that the MRO is unresolvable through the C3-merge algorithm. // The rest of this function is dedicated to figuring out the best error message // to report to the user. if class.has_pep_695_type_params(db) && original_bases.iter().any(|base| { matches!( base, Type::KnownInstance(KnownInstanceType::SubscriptedGeneric(_)) | Type::SpecialForm(SpecialFormType::Generic) ) }) { return Err(MroErrorKind::Pep695ClassWithGenericInheritance); } let mut duplicate_dynamic_bases = false; let duplicate_bases: Vec<DuplicateBaseError<'db>> = { let mut base_to_indices: IndexMap<ClassBase<'db>, Vec<usize>, FxBuildHasher> = IndexMap::default(); // We need to iterate over `original_bases` here rather than `resolved_bases` // so that we get the correct index of the duplicate bases if there were any // (`resolved_bases` may be a longer list than `original_bases`!). However, we // need to use a `ClassBase` rather than a `Type` as the key type for the // `base_to_indices` map so that a class such as // `class Foo(Protocol[T], Protocol): ...` correctly causes us to emit a // `duplicate-base` diagnostic (matching the runtime behaviour) rather than an // `inconsistent-mro` diagnostic (which would be accurate -- but not nearly as // precise!). for (index, base) in original_bases.iter().enumerate() { let Some(base) = ClassBase::try_from_type(db, *base, class.class_literal(db).0) else { continue; }; base_to_indices.entry(base).or_default().push(index); } let mut errors = vec![]; for (base, indices) in base_to_indices { let Some((first_index, later_indices)) = indices.split_first() else { continue; }; if later_indices.is_empty() { continue; } match base { ClassBase::Class(_) | ClassBase::Generic | ClassBase::Protocol | ClassBase::TypedDict => { errors.push(DuplicateBaseError { duplicate_base: base, first_index: *first_index, later_indices: later_indices.iter().copied().collect(), }); } ClassBase::Dynamic(_) => duplicate_dynamic_bases = true, } } errors }; if duplicate_bases.is_empty() { if duplicate_dynamic_bases { Ok(Mro::from_error(db, class)) } else { Err(MroErrorKind::UnresolvableMro { bases_list: original_bases.iter().copied().collect(), }) } } else { Err(MroErrorKind::DuplicateBases( duplicate_bases.into_boxed_slice(), )) } } } } } impl<'db, const N: usize> From<[ClassBase<'db>; N]> for Mro<'db> { fn from(value: [ClassBase<'db>; N]) -> Self { Self(Box::from(value)) } } impl<'db> From<Vec<ClassBase<'db>>> for Mro<'db> { fn from(value: Vec<ClassBase<'db>>) -> Self { Self(value.into_boxed_slice()) } } impl<'db> Deref for Mro<'db> { type Target = [ClassBase<'db>]; fn deref(&self) -> &Self::Target { &self.0 } } impl<'db> FromIterator<ClassBase<'db>> for Mro<'db> { fn from_iter<T: IntoIterator<Item = ClassBase<'db>>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } /// Iterator that yields elements of a class's MRO. /// /// We avoid materialising the *full* MRO unless it is actually necessary: /// - Materialising the full MRO is expensive /// - We need to do it for every class in the code that we're checking, as we need to make sure /// that there are no class definitions in the code we're checking that would cause an /// exception to be raised at runtime. But the same does *not* necessarily apply for every class /// in third-party and stdlib dependencies: we never emit diagnostics about non-first-party code. /// - However, we *do* need to resolve attribute accesses on classes/instances from /// third-party and stdlib dependencies. That requires iterating over the MRO of third-party/stdlib /// classes, but not necessarily the *whole* MRO: often just the first element is enough. /// Luckily we know that for any class `X`, the first element of `X`'s MRO will always be `X` itself. /// We can therefore avoid resolving the full MRO for many third-party/stdlib classes while still /// being faithful to the runtime semantics. /// /// Even for first-party code, where we will have to resolve the MRO for every class we encounter, /// loading the cached MRO comes with a certain amount of overhead, so it's best to avoid calling the /// Salsa-tracked [`ClassLiteral::try_mro`] method unless it's absolutely necessary. pub(super) struct MroIterator<'db> { db: &'db dyn Db, /// The class whose MRO we're iterating over class: ClassLiteral<'db>, /// The specialization to apply to each MRO element, if any specialization: Option<Specialization<'db>>, /// Whether or not we've already yielded the first element of the MRO first_element_yielded: bool, /// Iterator over all elements of the MRO except the first. /// /// The full MRO is expensive to materialize, so this field is `None` /// unless we actually *need* to iterate past the first element of the MRO, /// at which point it is lazily materialized. subsequent_elements: Option<std::slice::Iter<'db, ClassBase<'db>>>, } impl<'db> MroIterator<'db> { pub(super) fn new( db: &'db dyn Db, class: ClassLiteral<'db>, specialization: Option<Specialization<'db>>, ) -> Self { Self { db, class, specialization, first_element_yielded: false, subsequent_elements: None, } } /// Materialize the full MRO of the class. /// Return an iterator over that MRO which skips the first element of the MRO. fn full_mro_except_first_element(&mut self) -> impl Iterator<Item = ClassBase<'db>> + '_ { self.subsequent_elements .get_or_insert_with(|| { let mut full_mro_iter = match self.class.try_mro(self.db, self.specialization) { Ok(mro) => mro.iter(), Err(error) => error.fallback_mro().iter(), }; full_mro_iter.next(); full_mro_iter }) .copied() } } impl<'db> Iterator for MroIterator<'db> { type Item = ClassBase<'db>; fn next(&mut self) -> Option<Self::Item> { if !self.first_element_yielded { self.first_element_yielded = true; return Some(ClassBase::Class( self.class .apply_optional_specialization(self.db, self.specialization), )); } self.full_mro_except_first_element().next() } } impl std::iter::FusedIterator for MroIterator<'_> {} #[derive(Debug, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(super) struct MroError<'db> { kind: MroErrorKind<'db>, fallback_mro: Mro<'db>, } impl<'db> MroError<'db> { /// Construct an MRO error of kind `InheritanceCycle`. pub(super) fn cycle(db: &'db dyn Db, class: ClassType<'db>) -> Self { MroErrorKind::InheritanceCycle.into_mro_error(db, class) } pub(super) fn is_cycle(&self) -> bool { matches!(self.kind, MroErrorKind::InheritanceCycle) } /// Return an [`MroErrorKind`] variant describing why we could not resolve the MRO for this class. pub(super) fn reason(&self) -> &MroErrorKind<'db> { &self.kind } /// Return the fallback MRO we should infer for this class during type inference /// (since accurate resolution of its "true" MRO was impossible) pub(super) fn fallback_mro(&self) -> &Mro<'db> { &self.fallback_mro } } /// Possible ways in which attempting to resolve the MRO of a class might fail. #[derive(Debug, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(super) enum MroErrorKind<'db> { /// The class inherits from one or more invalid bases. /// /// To avoid excessive complexity in our implementation, /// we only permit classes to inherit from class-literal types, /// `Todo`, `Unknown` or `Any`. Anything else results in us /// emitting a diagnostic. /// /// This variant records the indices and types of class bases /// that we deem to be invalid. The indices are the indices of nodes /// in the bases list of the class's [`StmtClassDef`](ruff_python_ast::StmtClassDef) node. /// Each index is the index of a node representing an invalid base. InvalidBases(Box<[(usize, Type<'db>)]>), /// The class has one or more duplicate bases. /// See [`DuplicateBaseError`] for more details. DuplicateBases(Box<[DuplicateBaseError<'db>]>), /// The class uses PEP-695 parameters and also inherits from `Generic[]`. Pep695ClassWithGenericInheritance, /// A cycle was encountered resolving the class' bases. InheritanceCycle, /// The MRO is otherwise unresolvable through the C3-merge algorithm. /// /// See [`c3_merge`] for more details. UnresolvableMro { bases_list: Box<[Type<'db>]> }, } impl<'db> MroErrorKind<'db> { pub(super) fn into_mro_error(self, db: &'db dyn Db, class: ClassType<'db>) -> MroError<'db> { MroError { kind: self, fallback_mro: Mro::from_error(db, class), } } } /// Error recording the fact that a class definition was found to have duplicate bases. #[derive(Debug, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(super) struct DuplicateBaseError<'db> { /// The base that is duplicated in the class's bases list. pub(super) duplicate_base: ClassBase<'db>, /// The index of the first occurrence of the base in the class's bases list. pub(super) first_index: usize, /// The indices of the base's later occurrences in the class's bases list. pub(super) later_indices: Box<[usize]>, } /// Implementation of the [C3-merge algorithm] for calculating a Python class's /// [method resolution order]. /// /// [C3-merge algorithm]: https://docs.python.org/3/howto/mro.html#python-2-3-mro /// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order fn c3_merge(mut sequences: Vec<VecDeque<ClassBase>>) -> Option<Mro> { // Most MROs aren't that long... let mut mro = Vec::with_capacity(8); loop { sequences.retain(|sequence| !sequence.is_empty()); if sequences.is_empty() { return Some(Mro::from(mro)); } // If the candidate exists "deeper down" in the inheritance hierarchy, // we should refrain from adding it to the MRO for now. Add the first candidate // for which this does not hold true. If this holds true for all candidates, // return `None`; it will be impossible to find a consistent MRO for the class // with the given bases. let mro_entry = sequences.iter().find_map(|outer_sequence| { let candidate = outer_sequence[0]; let not_head = sequences .iter() .all(|sequence| sequence.iter().skip(1).all(|base| base != &candidate)); not_head.then_some(candidate) })?; mro.push(mro_entry); // Make sure we don't try to add the candidate to the MRO twice: for sequence in &mut sequences { if sequence[0] == mro_entry { sequence.pop_front(); } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/ide_support.rs
crates/ty_python_semantic/src/types/ide_support.rs
use std::collections::HashMap; use crate::FxIndexSet; use crate::place::builtins_module_scope; use crate::semantic_index::definition::Definition; use crate::semantic_index::definition::DefinitionKind; use crate::semantic_index::{attribute_scopes, global_scope, semantic_index, use_def_map}; use crate::types::call::{CallArguments, MatchedArgument}; use crate::types::signatures::{ParameterKind, Signature}; use crate::types::{ CallDunderError, CallableTypes, ClassBase, KnownUnion, Type, TypeContext, UnionType, }; use crate::{Db, DisplaySettings, HasType, SemanticModel}; use ruff_db::files::FileRange; use ruff_db::parsed::parsed_module; use ruff_python_ast::{self as ast, AnyNodeRef}; use ruff_text_size::{Ranged, TextRange}; use rustc_hash::FxHashSet; pub use resolve_definition::{ImportAliasResolution, ResolvedDefinition, map_stub_definition}; use resolve_definition::{find_symbol_in_scope, resolve_definition}; /// Get the primary definition kind for a name expression within a specific file. /// Returns the first definition kind that is reachable for this name in its scope. /// This is useful for IDE features like semantic tokens. pub fn definition_for_name<'db>( model: &SemanticModel<'db>, name: &ast::ExprName, alias_resolution: ImportAliasResolution, ) -> Option<Definition<'db>> { let definitions = definitions_for_name(model, name.id.as_str(), name.into(), alias_resolution); // Find the first valid definition and return its kind for declaration in definitions { if let Some(def) = declaration.definition() { return Some(def); } } None } /// Returns all definitions for a name. If any definitions are imports, they /// are resolved (recursively) to the original definitions or module files. pub fn definitions_for_name<'db>( model: &SemanticModel<'db>, name_str: &str, node: AnyNodeRef<'_>, alias_resolution: ImportAliasResolution, ) -> Vec<ResolvedDefinition<'db>> { let db = model.db(); let file = model.file(); let index = semantic_index(db, file); // Get the scope for this name expression let Some(file_scope) = model.scope(node) else { return vec![]; }; let mut all_definitions = FxIndexSet::default(); // Search through the scope hierarchy: start from the current scope and // traverse up through parent scopes to find definitions for (scope_id, _scope) in index.visible_ancestor_scopes(file_scope) { let place_table = index.place_table(scope_id); let Some(symbol_id) = place_table.symbol_id(name_str) else { continue; // Name not found in this scope, try parent scope }; // Check if this place is marked as global or nonlocal let place_expr = place_table.symbol(symbol_id); let is_global = place_expr.is_global(); let is_nonlocal = place_expr.is_nonlocal(); // TODO: The current algorithm doesn't return definitions or bindings // for other scopes that are outside of this scope hierarchy that target // this name using a nonlocal or global binding. The semantic analyzer // doesn't appear to track these in a way that we can easily access // them from here without walking all scopes in the module. // If marked as global, skip to global scope if is_global { let global_scope_id = global_scope(db, file); let global_place_table = crate::semantic_index::place_table(db, global_scope_id); if let Some(global_symbol_id) = global_place_table.symbol_id(name_str) { let global_use_def_map = crate::semantic_index::use_def_map(db, global_scope_id); let global_bindings = global_use_def_map.reachable_symbol_bindings(global_symbol_id); let global_declarations = global_use_def_map.reachable_symbol_declarations(global_symbol_id); for binding in global_bindings { if let Some(def) = binding.binding.definition() { all_definitions.insert(def); } } for declaration in global_declarations { if let Some(def) = declaration.declaration.definition() { all_definitions.insert(def); } } } break; } // If marked as nonlocal, skip current scope and search in ancestor scopes if is_nonlocal { // Continue searching in parent scopes, but skip the current scope continue; } let use_def_map = index.use_def_map(scope_id); // Get all definitions (both bindings and declarations) for this place let bindings = use_def_map.reachable_symbol_bindings(symbol_id); let declarations = use_def_map.reachable_symbol_declarations(symbol_id); for binding in bindings { if let Some(def) = binding.binding.definition() { all_definitions.insert(def); } } for declaration in declarations { if let Some(def) = declaration.declaration.definition() { all_definitions.insert(def); } } // If we found definitions in this scope, we can stop searching if !all_definitions.is_empty() { break; } } // Resolve import definitions to their targets let mut resolved_definitions = Vec::new(); for definition in &all_definitions { let resolved = resolve_definition(db, *definition, Some(name_str), alias_resolution); resolved_definitions.extend(resolved); } // If we didn't find any definitions in scopes, fallback to builtins if resolved_definitions.is_empty() && let Some(builtins_scope) = builtins_module_scope(db) { // Special cases for `float` and `complex` in type annotation positions. // We don't know whether we're in a type annotation position, so we'll just ask `Name`'s type, // which resolves to `int | float` or `int | float | complex` if `float` or `complex` is used in // a type annotation position and `float` or `complex` otherwise. // // https://typing.python.org/en/latest/spec/special-types.html#special-cases-for-float-and-complex if matches!(name_str, "float" | "complex") && let Some(expr) = node.expr_name() && let Some(ty) = expr.inferred_type(model) && let Some(union) = ty.as_union() && is_float_or_complex_annotation(db, union, name_str) { return union .elements(db) .iter() // Use `rev` so that `complex` and `float` come first. // This is required for hover to pick up the docstring of `complex` and `float` // instead of `int` (hover only shows the docstring of the first definition). .rev() .filter_map(|ty| ty.as_nominal_instance()) .map(|instance| { let definition = instance.class_literal(db).definition(db); ResolvedDefinition::Definition(definition) }) .collect(); } find_symbol_in_scope(db, builtins_scope, name_str) .into_iter() .filter(|def| def.is_reexported(db)) .flat_map(|def| { resolve_definition( db, def, Some(name_str), ImportAliasResolution::ResolveAliases, ) }) .collect() } else { resolved_definitions } } fn is_float_or_complex_annotation(db: &dyn Db, ty: UnionType, name: &str) -> bool { let float_or_complex_ty = match name { "float" => KnownUnion::Float.to_type(db), "complex" => KnownUnion::Complex.to_type(db), _ => return false, } .expect_union(); ty == float_or_complex_ty } /// Returns all resolved definitions for an attribute expression `x.y`. /// This function duplicates much of the functionality in the semantic /// analyzer, but it has somewhat different behavior so we've decided /// to keep it separate for now. One key difference is that this function /// doesn't model the descriptor protocol when accessing attributes. /// For "go to definition", we want to get the type of the descriptor object /// rather than "invoking" its `__get__` or `__set__` method. /// If this becomes a maintenance burden in the future, it may be worth /// changing the corresponding logic in the semantic analyzer to conditionally /// handle this case through the use of mode flags. pub fn definitions_for_attribute<'db>( model: &SemanticModel<'db>, attribute: &ast::ExprAttribute, ) -> Vec<ResolvedDefinition<'db>> { let db = model.db(); let name_str = attribute.attr.as_str(); let mut resolved = Vec::new(); // Determine the type of the LHS let Some(lhs_ty) = attribute.value.inferred_type(model) else { return resolved; }; let tys = match lhs_ty { Type::Union(union) => union.elements(model.db()).to_vec(), _ => vec![lhs_ty], }; // Expand intersections for each subtype into their components let expanded_tys = tys .into_iter() .flat_map(|ty| match ty { Type::Intersection(intersection) => intersection.positive(db).iter().copied().collect(), _ => vec![ty], }) .collect::<Vec<_>>(); for ty in expanded_tys { // Handle modules if let Type::ModuleLiteral(module_literal) = ty { if let Some(module_file) = module_literal.module(db).file(db) { let module_scope = global_scope(db, module_file); for def in find_symbol_in_scope(db, module_scope, name_str) { resolved.extend(resolve_definition( db, def, Some(name_str), ImportAliasResolution::ResolveAliases, )); } } continue; } // First, transform the type to its meta type, unless it's already a class-like type. let meta_type = match ty { Type::ClassLiteral(_) | Type::SubclassOf(_) | Type::GenericAlias(_) => ty, _ => ty.to_meta_type(db), }; let class_literal = match meta_type { Type::ClassLiteral(class_literal) => class_literal, Type::SubclassOf(subclass) => match subclass.subclass_of().into_class(db) { Some(cls) => cls.class_literal(db).0, None => continue, }, _ => continue, }; // Walk the MRO: include class and its ancestors, but stop when we find a match 'scopes: for ancestor in class_literal .iter_mro(db, None) .filter_map(ClassBase::into_class) .map(|cls| cls.class_literal(db).0) { let class_scope = ancestor.body_scope(db); let class_place_table = crate::semantic_index::place_table(db, class_scope); // Look for class-level declarations and bindings if let Some(place_id) = class_place_table.symbol_id(name_str) { let use_def = use_def_map(db, class_scope); // Check declarations first for decl in use_def.reachable_symbol_declarations(place_id) { if let Some(def) = decl.declaration.definition() { resolved.extend(resolve_definition( db, def, Some(name_str), ImportAliasResolution::ResolveAliases, )); break 'scopes; } } // If no declarations found, check bindings for binding in use_def.reachable_symbol_bindings(place_id) { if let Some(def) = binding.binding.definition() { resolved.extend(resolve_definition( db, def, Some(name_str), ImportAliasResolution::ResolveAliases, )); break 'scopes; } } } // Look for instance attributes in method scopes (e.g., self.x = 1) let file = class_scope.file(db); let index = semantic_index(db, file); for function_scope_id in attribute_scopes(db, class_scope) { if let Some(place_id) = index .place_table(function_scope_id) .member_id_by_instance_attribute_name(name_str) { let use_def = index.use_def_map(function_scope_id); // Check declarations first for decl in use_def.reachable_member_declarations(place_id) { if let Some(def) = decl.declaration.definition() { resolved.extend(resolve_definition( db, def, Some(name_str), ImportAliasResolution::ResolveAliases, )); break 'scopes; } } // If no declarations found, check bindings for binding in use_def.reachable_member_bindings(place_id) { if let Some(def) = binding.binding.definition() { resolved.extend(resolve_definition( db, def, Some(name_str), ImportAliasResolution::ResolveAliases, )); break 'scopes; } } } } // TODO: Add support for metaclass attribute lookups } } resolved } /// Returns definitions for a keyword argument in a call expression. /// This resolves the keyword argument to the corresponding parameter(s) in the callable's signature(s). pub fn definitions_for_keyword_argument<'db>( model: &SemanticModel<'db>, keyword: &ast::Keyword, call_expr: &ast::ExprCall, ) -> Vec<ResolvedDefinition<'db>> { let db = model.db(); let Some(func_type) = call_expr.func.inferred_type(model) else { return Vec::new(); }; let Some(keyword_name) = keyword.arg.as_ref() else { return Vec::new(); }; let keyword_name_str = keyword_name.as_str(); let mut resolved_definitions = Vec::new(); if let Some(callable_type) = func_type .try_upcast_to_callable(db) .and_then(CallableTypes::exactly_one) { let signatures = callable_type.signatures(db); // For each signature, find the parameter with the matching name for signature in signatures { if let Some((_param_index, _param)) = signature.parameters().keyword_by_name(keyword_name_str) { if let Some(function_definition) = signature.definition() { let function_file = function_definition.file(db); let module = parsed_module(db, function_file).load(db); let def_kind = function_definition.kind(db); if let DefinitionKind::Function(function_ast_ref) = def_kind { let function_node = function_ast_ref.node(&module); if let Some(parameter_range) = find_parameter_range(&function_node.parameters, keyword_name_str) { resolved_definitions.push(ResolvedDefinition::FileWithRange( FileRange::new(function_file, parameter_range), )); } } } } } } resolved_definitions } /// Find the definitions for a symbol imported via `from x import y as z` statement. /// This function handles the case where the cursor is on the original symbol name `y`. /// Returns the same definitions as would be found for the alias `z`. /// The `alias_resolution` parameter controls whether symbols imported with local import /// aliases (like "x" in "from a import b as x") are resolved to their targets or kept /// as aliases. pub fn definitions_for_imported_symbol<'db>( model: &SemanticModel<'db>, import_node: &ast::StmtImportFrom, symbol_name: &str, alias_resolution: ImportAliasResolution, ) -> Vec<ResolvedDefinition<'db>> { let mut visited = FxHashSet::default(); resolve_definition::resolve_from_import_definitions( model.db(), model.file(), import_node, symbol_name, &mut visited, alias_resolution, ) } /// Details about a callable signature for IDE support. #[derive(Debug, Clone)] pub struct CallSignatureDetails<'db> { /// The signature itself pub signature: Signature<'db>, /// The display label for this signature (e.g., "(param1: str, param2: int) -> str") pub label: String, /// Label offsets for each parameter in the signature string. /// Each range specifies the start position and length of a parameter label /// within the full signature string. pub parameter_label_offsets: Vec<TextRange>, /// The names of the parameters in the signature, in order. /// This provides easy access to parameter names for documentation lookup. pub parameter_names: Vec<String>, /// Parameter kinds, useful to determine correct autocomplete suggestions. pub parameter_kinds: Vec<ParameterKind<'db>>, /// Parameter kinds, useful to determine correct autocomplete suggestions. pub parameter_types: Vec<Option<Type<'db>>>, /// The definition where this callable was originally defined (useful for /// extracting docstrings). pub definition: Option<Definition<'db>>, /// Mapping from argument indices to parameter indices. This helps /// determine which parameter corresponds to which argument position. pub argument_to_parameter_mapping: Vec<MatchedArgument<'db>>, } impl CallSignatureDetails<'_> { fn get_definition_parameter_range(&self, db: &dyn Db, name: &str) -> Option<FileRange> { let definition = self.signature.definition()?; let file = definition.file(db); let module_ref = parsed_module(db, file).load(db); let parameters = match definition.kind(db) { DefinitionKind::Function(node) => &node.node(&module_ref).parameters, // TODO: lambda functions _ => return None, }; Some(FileRange::new(file, parameters.find(name)?.name().range)) } } /// Extract signature details from a function call expression. /// This function analyzes the callable being invoked and returns zero or more /// `CallSignatureDetails` objects, each representing one possible signature /// (in case of overloads or union types). pub fn call_signature_details<'db>( model: &SemanticModel<'db>, call_expr: &ast::ExprCall, ) -> Vec<CallSignatureDetails<'db>> { let Some(func_type) = call_expr.func.inferred_type(model) else { return Vec::new(); }; // Use into_callable to handle all the complex type conversions if let Some(callable_type) = func_type .try_upcast_to_callable(model.db()) .map(|callables| callables.into_type(model.db())) { let call_arguments = CallArguments::from_arguments(&call_expr.arguments, |_, splatted_value| { splatted_value .inferred_type(model) .unwrap_or(Type::unknown()) }); let bindings = callable_type .bindings(model.db()) .match_parameters(model.db(), &call_arguments); // Extract signature details from all callable bindings bindings .into_iter() .flatten() .map(|binding| { let argument_to_parameter_mapping = binding.argument_matches().to_vec(); let signature = binding.signature; let display_details = signature.display(model.db()).to_string_parts(); let parameter_label_offsets = display_details.parameter_ranges; let parameter_names = display_details.parameter_names; let (parameter_kinds, parameter_types): (Vec<ParameterKind>, Vec<Option<Type>>) = signature .parameters() .iter() .map(|param| (param.kind().clone(), param.annotated_type())) .unzip(); CallSignatureDetails { definition: signature.definition(), signature, label: display_details.label, parameter_label_offsets, parameter_names, parameter_kinds, parameter_types, argument_to_parameter_mapping, } }) .collect() } else { // Type is not callable, return empty signatures vec![] } } /// Given a call expression that has overloads, and whose overload is resolved to a /// single option by its arguments, return the type of the Signature. /// /// This is only used for simplifying complex call types, so if we ever detect that /// the given callable type *is* simple, or that our answer *won't* be simple, we /// bail at out and return None, so that the original type can be used. /// /// We do this because `Type::Signature` intentionally loses a lot of context, and /// so it has a "worse" display than say `Type::FunctionLiteral` or `Type::BoundMethod`, /// which this analysis would naturally wipe away. The contexts this function /// succeeds in are those where we would print a complicated/ugly type anyway. pub fn call_type_simplified_by_overloads( model: &SemanticModel, call_expr: &ast::ExprCall, ) -> Option<String> { let db = model.db(); let func_type = call_expr.func.inferred_type(model)?; // Use into_callable to handle all the complex type conversions let callable_type = func_type.try_upcast_to_callable(db)?.into_type(db); let bindings = callable_type.bindings(db); // If the callable is trivial this analysis is useless, bail out if let Some(binding) = bindings.single_element() && binding.overloads().len() < 2 { return None; } // Hand the overload resolution system as much type info as we have let args = CallArguments::from_arguments_typed(&call_expr.arguments, |_, splatted_value| { splatted_value .inferred_type(model) .unwrap_or(Type::unknown()) }); // Try to resolve overloads with the arguments/types we have let mut resolved = bindings .match_parameters(db, &args) .check_types(db, &args, TypeContext::default(), &[]) // Only use the Ok .iter() .flatten() .flat_map(|binding| { binding.matching_overloads().map(|(_, overload)| { overload .signature .display_with(db, DisplaySettings::default().multiline()) .to_string() }) }) .collect::<Vec<_>>(); // If at the end of this we still got multiple signatures (or no signatures), give up if resolved.len() != 1 { return None; } resolved.pop() } /// Returns the definitions of the binary operation along with its callable type. pub fn definitions_for_bin_op<'db>( model: &SemanticModel<'db>, binary_op: &ast::ExprBinOp, ) -> Option<(Vec<ResolvedDefinition<'db>>, Type<'db>)> { let left_ty = binary_op.left.inferred_type(model)?; let right_ty = binary_op.right.inferred_type(model)?; let Ok(bindings) = Type::try_call_bin_op(model.db(), left_ty, binary_op.op, right_ty) else { return None; }; let callable_type = promote_literals_for_self(model.db(), bindings.callable_type()); let definitions: Vec<_> = bindings .into_iter() .flatten() .filter_map(|binding| { Some(ResolvedDefinition::Definition( binding.signature.definition?, )) }) .collect(); Some((definitions, callable_type)) } /// Returns the definitions for an unary operator along with their callable types. pub fn definitions_for_unary_op<'db>( model: &SemanticModel<'db>, unary_op: &ast::ExprUnaryOp, ) -> Option<(Vec<ResolvedDefinition<'db>>, Type<'db>)> { let operand_ty = unary_op.operand.inferred_type(model)?; let unary_dunder_method = match unary_op.op { ast::UnaryOp::Invert => "__invert__", ast::UnaryOp::UAdd => "__pos__", ast::UnaryOp::USub => "__neg__", ast::UnaryOp::Not => "__bool__", }; let bindings = match operand_ty.try_call_dunder( model.db(), unary_dunder_method, CallArguments::none(), TypeContext::default(), ) { Ok(bindings) => bindings, Err(CallDunderError::MethodNotAvailable) if unary_op.op == ast::UnaryOp::Not => { // The runtime falls back to `__len__` for `not` if `__bool__` is not defined. match operand_ty.try_call_dunder( model.db(), "__len__", CallArguments::none(), TypeContext::default(), ) { Ok(bindings) => bindings, Err(CallDunderError::MethodNotAvailable) => return None, Err( CallDunderError::PossiblyUnbound(bindings) | CallDunderError::CallError(_, bindings), ) => *bindings, } } Err(CallDunderError::MethodNotAvailable) => return None, Err( CallDunderError::PossiblyUnbound(bindings) | CallDunderError::CallError(_, bindings), ) => *bindings, }; let callable_type = promote_literals_for_self(model.db(), bindings.callable_type()); let definitions = bindings .into_iter() .flatten() .filter_map(|binding| { Some(ResolvedDefinition::Definition( binding.signature.definition?, )) }) .collect(); Some((definitions, callable_type)) } /// Promotes literal types in `self` positions to their fallback instance types. /// /// This is so that we show e.g. `int.__add__` instead of `Literal[4].__add__`. fn promote_literals_for_self<'db>(db: &'db dyn Db, ty: Type<'db>) -> Type<'db> { match ty { Type::BoundMethod(method) => Type::BoundMethod(method.map_self_type(db, |self_ty| { self_ty.literal_fallback_instance(db).unwrap_or(self_ty) })), Type::Union(elements) => elements.map(db, |ty| match ty { Type::BoundMethod(method) => Type::BoundMethod(method.map_self_type(db, |self_ty| { self_ty.literal_fallback_instance(db).unwrap_or(self_ty) })), _ => *ty, }), ty => ty, } } /// Find the active signature index from `CallSignatureDetails`. /// The active signature is the first signature where all arguments present in the call /// have valid mappings to parameters (i.e., none of the mappings are None). pub fn find_active_signature_from_details( signature_details: &[CallSignatureDetails], ) -> Option<usize> { let first = signature_details.first()?; // If there are no arguments in the mapping, just return the first signature. if first.argument_to_parameter_mapping.is_empty() { return Some(0); } // First, try to find a signature where all arguments have valid parameter mappings. let perfect_match = signature_details.iter().position(|details| { // Check if all arguments have valid parameter mappings. details .argument_to_parameter_mapping .iter() .all(|mapping| mapping.matched) }); if let Some(index) = perfect_match { return Some(index); } // If no perfect match, find the signature with the most valid argument mappings. let (best_index, _) = signature_details .iter() .enumerate() .max_by_key(|(_, details)| { details .argument_to_parameter_mapping .iter() .filter(|mapping| mapping.matched) .count() })?; Some(best_index) } #[derive(Default)] pub struct InlayHintCallArgumentDetails { /// The position of the arguments mapped to their name and the range of the argument definition in the signature. pub argument_names: HashMap<usize, (String, Option<FileRange>)>, } pub fn inlay_hint_call_argument_details<'db>( db: &'db dyn Db, model: &SemanticModel<'db>, call_expr: &ast::ExprCall, ) -> Option<InlayHintCallArgumentDetails> { let signature_details = call_signature_details(model, call_expr); if signature_details.is_empty() { return None; } let active_signature_index = find_active_signature_from_details(&signature_details)?; let call_signature_details = signature_details.get(active_signature_index)?; let parameters = call_signature_details.signature.parameters(); let mut argument_names = HashMap::new(); for arg_index in 0..call_expr.arguments.args.len() { let Some(arg_mapping) = call_signature_details .argument_to_parameter_mapping .get(arg_index) else { continue; }; if !arg_mapping.matched { continue; } // Skip if this argument maps to multiple parameters (e.g., unpacked tuple filling // multiple slots). Showing a single parameter name would be misleading. if arg_mapping.parameters.len() > 1 { continue; } let Some(param_index) = arg_mapping.parameters.first() else { continue; }; let Some(param) = parameters.get(*param_index) else { continue; }; let parameter_label_offset = call_signature_details.get_definition_parameter_range(db, param.name()?); // Only add hints for parameters that can be specified by name if !param.is_positional_only() && !param.is_variadic() && !param.is_keyword_variadic() { let Some(name) = param.name() else { continue; }; argument_names.insert(arg_index, (name.to_string(), parameter_label_offset)); } } Some(InlayHintCallArgumentDetails { argument_names }) } /// Find the text range of a specific parameter in function parameters by name. /// Only searches for parameters that can be addressed by name in keyword arguments. fn find_parameter_range(parameters: &ast::Parameters, parameter_name: &str) -> Option<TextRange> { // Check regular positional and keyword-only parameters parameters .args .iter() .chain(&parameters.kwonlyargs) .find(|param| param.parameter.name.as_str() == parameter_name) .map(|param| param.parameter.name.range()) } mod resolve_definition { //! Resolves an Import, `ImportFrom` or `StarImport` definition to one or more //! "resolved definitions". This is done recursively to find the original //! definition targeted by the import. /// Controls whether local import aliases should be resolved to their targets or returned as-is. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ImportAliasResolution { /// Resolve import aliases to their original definitions ResolveAliases, /// Keep import aliases as-is, don't resolve to original definitions PreserveAliases, } use indexmap::IndexSet; use ruff_db::files::{File, FileRange, vendored_path_to_file}; use ruff_db::parsed::{ParsedModuleRef, parsed_module}; use ruff_db::system::SystemPath; use ruff_db::vendored::VendoredPathBuf; use ruff_python_ast as ast; use ruff_python_stdlib::sys::is_builtin_module;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/bound_super.rs
crates/ty_python_semantic/src/types/bound_super.rs
//! Logic for inferring `super()`, `super(x)` and `super(x, y)` calls. use itertools::{Either, Itertools}; use ruff_db::diagnostic::Diagnostic; use ruff_python_ast::AnyNodeRef; use crate::{ Db, DisplaySettings, place::{Place, PlaceAndQualifiers}, types::{ ClassBase, ClassType, DynamicType, IntersectionBuilder, KnownClass, MemberLookupPolicy, NominalInstanceType, NormalizedVisitor, SpecialFormType, SubclassOfInner, Type, TypeVarBoundOrConstraints, TypeVarInstance, UnionBuilder, context::InferContext, diagnostic::{INVALID_SUPER_ARGUMENT, UNAVAILABLE_IMPLICIT_SUPER_ARGUMENTS}, todo_type, visitor, }, }; /// Enumeration of ways in which a `super()` call can cause us to emit a diagnostic. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum BoundSuperError<'db> { /// The second argument to `super()` (which may have been implicitly provided by /// the Python interpreter) has an abstract or structural type. /// It's impossible to determine whether a `Callable` type or a synthesized protocol /// type is an instance or subclass of the pivot class, so these are rejected. AbstractOwnerType { owner_type: Type<'db>, pivot_class: Type<'db>, /// If `owner_type` is a type variable, this contains the type variable instance typevar_context: Option<TypeVarInstance<'db>>, }, /// The first argument to `super()` (which may have been implicitly provided by /// the Python interpreter) is not a valid class type. InvalidPivotClassType { pivot_class: Type<'db> }, /// The second argument to `super()` was not a subclass or instance of the first argument. /// (Note that both arguments may have been implicitly provided by the Python interpreter.) FailingConditionCheck { pivot_class: Type<'db>, owner: Type<'db>, /// If `owner_type` is a type variable, this contains the type variable instance typevar_context: Option<TypeVarInstance<'db>>, }, /// It was a single-argument `super()` call, but we were unable to determine /// the implicit arguments provided by the Python interpreter. UnavailableImplicitArguments, } impl<'db> BoundSuperError<'db> { pub(super) fn report_diagnostic(&self, context: &'db InferContext<'db, '_>, node: AnyNodeRef) { match self { BoundSuperError::AbstractOwnerType { owner_type, pivot_class, typevar_context, } => { if let Some(builder) = context.report_lint(&INVALID_SUPER_ARGUMENT, node) { if let Some(typevar_context) = typevar_context { let mut diagnostic = builder.into_diagnostic(format_args!( "`{owner}` is a type variable with an abstract/structural type as \ its bounds or constraints, in `super({pivot_class}, {owner})` call", pivot_class = pivot_class.display(context.db()), owner = owner_type.display(context.db()), )); Self::describe_typevar(context.db(), &mut diagnostic, *typevar_context); } else { builder.into_diagnostic(format_args!( "`{owner}` is an abstract/structural type in \ `super({pivot_class}, {owner})` call", pivot_class = pivot_class.display(context.db()), owner = owner_type.display(context.db()), )); } } } BoundSuperError::InvalidPivotClassType { pivot_class } => { if let Some(builder) = context.report_lint(&INVALID_SUPER_ARGUMENT, node) { match pivot_class { Type::GenericAlias(alias) => { builder.into_diagnostic(format_args!( "`types.GenericAlias` instance `{}` is not a valid class", alias.display_with(context.db(), DisplaySettings::default()), )); } _ => { let mut diagnostic = builder.into_diagnostic("Argument is not a valid class"); diagnostic.set_primary_message(format_args!( "Argument has type `{}`", pivot_class.display(context.db()) )); diagnostic.set_concise_message(format_args!( "`{}` is not a valid class", pivot_class.display(context.db()), )); } } } } BoundSuperError::FailingConditionCheck { pivot_class, owner, typevar_context, } => { if let Some(builder) = context.report_lint(&INVALID_SUPER_ARGUMENT, node) { let mut diagnostic = builder.into_diagnostic(format_args!( "`{owner}` is not an instance or subclass of \ `{pivot_class}` in `super({pivot_class}, {owner})` call", pivot_class = pivot_class.display(context.db()), owner = owner.display(context.db()), )); if let Some(typevar_context) = typevar_context { let bound_or_constraints_union = Self::describe_typevar(context.db(), &mut diagnostic, *typevar_context); diagnostic.info(format_args!( "`{bounds_or_constraints}` is not an instance or subclass of `{pivot_class}`", bounds_or_constraints = bound_or_constraints_union.display(context.db()), pivot_class = pivot_class.display(context.db()), )); if typevar_context.bound_or_constraints(context.db()).is_none() && !typevar_context.kind(context.db()).is_self() { diagnostic.help(format_args!( "Consider adding an upper bound to type variable `{}`", typevar_context.name(context.db()) )); } } } } BoundSuperError::UnavailableImplicitArguments => { if let Some(builder) = context.report_lint(&UNAVAILABLE_IMPLICIT_SUPER_ARGUMENTS, node) { builder.into_diagnostic(format_args!( "Cannot determine implicit arguments for 'super()' in this context", )); } } } } /// Add an `info`-level diagnostic describing the bounds or constraints, /// and return the type variable's upper bound or the union of its constraints. fn describe_typevar( db: &'db dyn Db, diagnostic: &mut Diagnostic, type_var: TypeVarInstance<'db>, ) -> Type<'db> { match type_var.bound_or_constraints(db) { Some(TypeVarBoundOrConstraints::UpperBound(bound)) => { diagnostic.info(format_args!( "Type variable `{}` has upper bound `{}`", type_var.name(db), bound.display(db) )); bound } Some(TypeVarBoundOrConstraints::Constraints(constraints)) => { diagnostic.info(format_args!( "Type variable `{}` has constraints `{}`", type_var.name(db), constraints .elements(db) .iter() .map(|c| c.display(db)) .join(", ") )); constraints.as_type(db) } None => { diagnostic.info(format_args!( "Type variable `{}` has `object` as its implicit upper bound", type_var.name(db) )); Type::object() } } } } #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, get_size2::GetSize, salsa::Update)] pub enum SuperOwnerKind<'db> { Dynamic(DynamicType<'db>), Class(ClassType<'db>), Instance(NominalInstanceType<'db>), } impl<'db> SuperOwnerKind<'db> { fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { match self { SuperOwnerKind::Dynamic(dynamic) => SuperOwnerKind::Dynamic(dynamic.normalized()), SuperOwnerKind::Class(class) => { SuperOwnerKind::Class(class.normalized_impl(db, visitor)) } SuperOwnerKind::Instance(instance) => instance .normalized_impl(db, visitor) .as_nominal_instance() .map(Self::Instance) .unwrap_or(Self::Dynamic(DynamicType::Any)), } } fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { match self { SuperOwnerKind::Dynamic(dynamic) => { Some(SuperOwnerKind::Dynamic(dynamic.recursive_type_normalized())) } SuperOwnerKind::Class(class) => Some(SuperOwnerKind::Class( class.recursive_type_normalized_impl(db, div, nested)?, )), SuperOwnerKind::Instance(instance) => Some(SuperOwnerKind::Instance( instance.recursive_type_normalized_impl(db, div, nested)?, )), } } fn iter_mro(self, db: &'db dyn Db) -> impl Iterator<Item = ClassBase<'db>> { match self { SuperOwnerKind::Dynamic(dynamic) => { Either::Left(ClassBase::Dynamic(dynamic).mro(db, None)) } SuperOwnerKind::Class(class) => Either::Right(class.iter_mro(db)), SuperOwnerKind::Instance(instance) => Either::Right(instance.class(db).iter_mro(db)), } } fn into_class(self, db: &'db dyn Db) -> Option<ClassType<'db>> { match self { SuperOwnerKind::Dynamic(_) => None, SuperOwnerKind::Class(class) => Some(class), SuperOwnerKind::Instance(instance) => Some(instance.class(db)), } } } impl<'db> From<SuperOwnerKind<'db>> for Type<'db> { fn from(owner: SuperOwnerKind<'db>) -> Self { match owner { SuperOwnerKind::Dynamic(dynamic) => Type::Dynamic(dynamic), SuperOwnerKind::Class(class) => class.into(), SuperOwnerKind::Instance(instance) => instance.into(), } } } /// Represent a bound super object like `super(PivotClass, owner)` #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] pub struct BoundSuperType<'db> { pub pivot_class: ClassBase<'db>, pub owner: SuperOwnerKind<'db>, } // The Salsa heap is tracked separately. impl get_size2::GetSize for BoundSuperType<'_> {} pub(super) fn walk_bound_super_type<'db, V: visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, bound_super: BoundSuperType<'db>, visitor: &V, ) { visitor.visit_type(db, Type::from(bound_super.pivot_class(db))); visitor.visit_type(db, Type::from(bound_super.owner(db))); } impl<'db> BoundSuperType<'db> { /// Attempts to build a `Type::BoundSuper` based on the given `pivot_class` and `owner`. /// /// This mimics the behavior of Python's built-in `super(pivot, owner)` at runtime. /// - `super(pivot, owner_class)` is valid only if `issubclass(owner_class, pivot)` /// - `super(pivot, owner_instance)` is valid only if `isinstance(owner_instance, pivot)` /// /// However, the checking is skipped when any of the arguments is a dynamic type. pub(super) fn build( db: &'db dyn Db, pivot_class_type: Type<'db>, owner_type: Type<'db>, ) -> Result<Type<'db>, BoundSuperError<'db>> { let delegate_to = |type_to_delegate_to| BoundSuperType::build(db, pivot_class_type, type_to_delegate_to); let delegate_with_error_mapped = |type_to_delegate_to, error_context: Option<TypeVarInstance<'db>>| { delegate_to(type_to_delegate_to).map_err(|err| match err { BoundSuperError::AbstractOwnerType { owner_type: _, pivot_class: _, typevar_context: _, } => BoundSuperError::AbstractOwnerType { owner_type, pivot_class: pivot_class_type, typevar_context: error_context, }, BoundSuperError::FailingConditionCheck { pivot_class, owner: _, typevar_context: _, } => BoundSuperError::FailingConditionCheck { pivot_class, owner: owner_type, typevar_context: error_context, }, BoundSuperError::InvalidPivotClassType { pivot_class } => { BoundSuperError::InvalidPivotClassType { pivot_class } } BoundSuperError::UnavailableImplicitArguments => { BoundSuperError::UnavailableImplicitArguments } }) }; let owner = match owner_type { Type::Never => SuperOwnerKind::Dynamic(DynamicType::Unknown), Type::Dynamic(dynamic) => SuperOwnerKind::Dynamic(dynamic), Type::ClassLiteral(class) => SuperOwnerKind::Class(ClassType::NonGeneric(class)), Type::SubclassOf(subclass_of_type) => { match subclass_of_type.subclass_of().with_transposed_type_var(db) { SubclassOfInner::Class(class) => SuperOwnerKind::Class(class), SubclassOfInner::Dynamic(dynamic) => SuperOwnerKind::Dynamic(dynamic), SubclassOfInner::TypeVar(bound_typevar) => { return delegate_to(Type::TypeVar(bound_typevar)); } } } Type::NominalInstance(instance) => SuperOwnerKind::Instance(instance), Type::ProtocolInstance(protocol) => { if let Some(nominal_instance) = protocol.to_nominal_instance() { SuperOwnerKind::Instance(nominal_instance) } else { return Err(BoundSuperError::AbstractOwnerType { owner_type, pivot_class: pivot_class_type, typevar_context: None, }); } } Type::Union(union) => { return Ok(union .elements(db) .iter() .try_fold(UnionBuilder::new(db), |builder, element| { delegate_to(*element).map(|ty| builder.add(ty)) })? .build()); } Type::Intersection(intersection) => { let mut builder = IntersectionBuilder::new(db); let mut one_good_element_found = false; for positive in intersection.positive(db) { if let Ok(good_element) = delegate_to(*positive) { one_good_element_found = true; builder = builder.add_positive(good_element); } } if !one_good_element_found { return Err(BoundSuperError::AbstractOwnerType { owner_type, pivot_class: pivot_class_type, typevar_context: None, }); } for negative in intersection.negative(db) { if let Ok(good_element) = delegate_to(*negative) { builder = builder.add_negative(good_element); } } return Ok(builder.build()); } Type::TypeAlias(alias) => { return delegate_with_error_mapped(alias.value_type(db), None); } Type::TypeVar(type_var) => { let type_var = type_var.typevar(db); return match type_var.bound_or_constraints(db) { Some(TypeVarBoundOrConstraints::UpperBound(bound)) => { delegate_with_error_mapped(bound, Some(type_var)) } Some(TypeVarBoundOrConstraints::Constraints(constraints)) => { delegate_with_error_mapped(constraints.as_type(db), Some(type_var)) } None => delegate_with_error_mapped(Type::object(), Some(type_var)), }; } Type::BooleanLiteral(_) | Type::TypeIs(_) | Type::TypeGuard(_) => { return delegate_to(KnownClass::Bool.to_instance(db)); } Type::IntLiteral(_) => return delegate_to(KnownClass::Int.to_instance(db)), Type::StringLiteral(_) | Type::LiteralString => { return delegate_to(KnownClass::Str.to_instance(db)); } Type::BytesLiteral(_) => { return delegate_to(KnownClass::Bytes.to_instance(db)); } Type::SpecialForm(special_form) => { return delegate_to(special_form.instance_fallback(db)); } Type::KnownInstance(instance) => { return delegate_to(instance.instance_fallback(db)); } Type::FunctionLiteral(_) | Type::DataclassDecorator(_) => { return delegate_to(KnownClass::FunctionType.to_instance(db)); } Type::WrapperDescriptor(_) => { return delegate_to(KnownClass::WrapperDescriptorType.to_instance(db)); } Type::KnownBoundMethod(method) => { return delegate_to(method.class().to_instance(db)); } Type::BoundMethod(_) => return delegate_to(KnownClass::MethodType.to_instance(db)), Type::ModuleLiteral(_) => { return delegate_to(KnownClass::ModuleType.to_instance(db)); } Type::GenericAlias(_) => return delegate_to(KnownClass::GenericAlias.to_instance(db)), Type::PropertyInstance(_) => return delegate_to(KnownClass::Property.to_instance(db)), Type::EnumLiteral(enum_literal_type) => { return delegate_to(enum_literal_type.enum_class_instance(db)); } Type::BoundSuper(_) => return delegate_to(KnownClass::Super.to_instance(db)), Type::TypedDict(td) => { // In general it isn't sound to upcast a `TypedDict` to a `dict`, // but here it seems like it's probably sound? let mut key_builder = UnionBuilder::new(db); let mut value_builder = UnionBuilder::new(db); for (name, field) in td.items(db) { key_builder = key_builder.add(Type::string_literal(db, name)); value_builder = value_builder.add(field.declared_ty); } return delegate_to( KnownClass::Dict .to_specialized_instance(db, [key_builder.build(), value_builder.build()]), ); } Type::NewTypeInstance(newtype) => { return delegate_to(newtype.concrete_base_type(db)); } Type::Callable(callable) if callable.is_function_like(db) => { return delegate_to(KnownClass::FunctionType.to_instance(db)); } Type::AlwaysFalsy | Type::AlwaysTruthy | Type::Callable(_) | Type::DataclassTransformer(_) => { return Err(BoundSuperError::AbstractOwnerType { owner_type, pivot_class: pivot_class_type, typevar_context: None, }); } }; // We don't use `Classbase::try_from_type` here because: // - There are objects that may validly be present in a class's bases list // but are not valid as pivot classes, e.g. `typing.ChainMap` // - There are objects that are not valid in a class's bases list // but are valid as pivot classes, e.g. unsubscripted `typing.Generic` let pivot_class = match pivot_class_type { Type::ClassLiteral(class) => ClassBase::Class(ClassType::NonGeneric(class)), Type::SubclassOf(subclass_of) => match subclass_of.subclass_of() { SubclassOfInner::Dynamic(dynamic) => ClassBase::Dynamic(dynamic), _ => match subclass_of.subclass_of().into_class(db) { Some(class) => ClassBase::Class(class), None => { return Err(BoundSuperError::InvalidPivotClassType { pivot_class: pivot_class_type, }); } }, }, Type::SpecialForm(SpecialFormType::Protocol) => ClassBase::Protocol, Type::SpecialForm(SpecialFormType::Generic) => ClassBase::Generic, Type::SpecialForm(SpecialFormType::TypedDict) => ClassBase::TypedDict, Type::Dynamic(dynamic) => ClassBase::Dynamic(dynamic), _ => { return Err(BoundSuperError::InvalidPivotClassType { pivot_class: pivot_class_type, }); } }; if let Some(pivot_class) = pivot_class.into_class() && let Some(owner_class) = owner.into_class(db) { let pivot_class = pivot_class.class_literal(db).0; if !owner_class.iter_mro(db).any(|superclass| match superclass { ClassBase::Dynamic(_) => true, ClassBase::Generic | ClassBase::Protocol | ClassBase::TypedDict => false, ClassBase::Class(superclass) => superclass.class_literal(db).0 == pivot_class, }) { return Err(BoundSuperError::FailingConditionCheck { pivot_class: pivot_class_type, owner: owner_type, typevar_context: None, }); } } Ok(Type::BoundSuper(BoundSuperType::new( db, pivot_class, owner, ))) } /// Skips elements in the MRO up to and including the pivot class. /// /// If the pivot class is a dynamic type, its MRO can't be determined, /// so we fall back to using the MRO of `DynamicType::Unknown`. fn skip_until_after_pivot( self, db: &'db dyn Db, mro_iter: impl Iterator<Item = ClassBase<'db>>, ) -> impl Iterator<Item = ClassBase<'db>> { let Some(pivot_class) = self.pivot_class(db).into_class() else { return Either::Left(ClassBase::Dynamic(DynamicType::Unknown).mro(db, None)); }; let mut pivot_found = false; Either::Right(mro_iter.skip_while(move |superclass| { if pivot_found { false } else if Some(pivot_class) == superclass.into_class() { pivot_found = true; true } else { true } })) } /// Tries to call `__get__` on the attribute. /// The arguments passed to `__get__` depend on whether the owner is an instance or a class. /// See the `CPython` implementation for reference: /// <https://github.com/python/cpython/blob/3b3720f1a26ab34377542b48eb6a6565f78ff892/Objects/typeobject.c#L11690-L11693> pub(super) fn try_call_dunder_get_on_attribute( self, db: &'db dyn Db, attribute: PlaceAndQualifiers<'db>, ) -> Option<PlaceAndQualifiers<'db>> { let owner = self.owner(db); match owner { // If the owner is a dynamic type, we can't tell whether it's a class or an instance. // Also, invoking a descriptor on a dynamic attribute is meaningless, so we don't handle this. SuperOwnerKind::Dynamic(_) => None, SuperOwnerKind::Class(_) => Some( Type::try_call_dunder_get_on_attribute( db, attribute, Type::none(db), Type::from(owner), ) .0, ), SuperOwnerKind::Instance(_) => { let owner = Type::from(owner); Some( Type::try_call_dunder_get_on_attribute( db, attribute, owner, owner.to_meta_type(db), ) .0, ) } } } /// Similar to `Type::find_name_in_mro_with_policy`, but performs lookup starting *after* the /// pivot class in the MRO, based on the `owner` type instead of the `super` type. pub(super) fn find_name_in_mro_after_pivot( self, db: &'db dyn Db, name: &str, policy: MemberLookupPolicy, ) -> PlaceAndQualifiers<'db> { let owner = self.owner(db); let class = match owner { SuperOwnerKind::Dynamic(dynamic) => { return Type::Dynamic(dynamic) .find_name_in_mro_with_policy(db, name, policy) .expect("Calling `find_name_in_mro` on dynamic type should return `Some`"); } SuperOwnerKind::Class(class) => class, SuperOwnerKind::Instance(instance) => instance.class(db), }; let (class_literal, _) = class.class_literal(db); // TODO properly support super() with generic types // * requires a fix for https://github.com/astral-sh/ruff/issues/17432 // * also requires understanding how we should handle cases like this: // ```python // b_int: B[int] // b_unknown: B // // super(B, b_int) // super(B[int], b_unknown) // ``` match class_literal.generic_context(db) { Some(_) => Place::bound(todo_type!("super in generic class")).into(), None => class_literal.class_member_from_mro( db, name, policy, self.skip_until_after_pivot(db, owner.iter_mro(db)), ), } } pub(super) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { Self::new( db, self.pivot_class(db).normalized_impl(db, visitor), self.owner(db).normalized_impl(db, visitor), ) } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self::new( db, self.pivot_class(db) .recursive_type_normalized_impl(db, div, nested)?, self.owner(db) .recursive_type_normalized_impl(db, div, nested)?, )) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/class.rs
crates/ty_python_semantic/src/types/class.rs
use std::cell::RefCell; use std::fmt::Write; use std::sync::{LazyLock, Mutex}; use super::TypeVarVariance; use super::{ BoundTypeVarInstance, MemberLookupPolicy, Mro, MroError, MroIterator, SpecialFormType, SubclassOfType, Truthiness, Type, TypeQualifiers, class_base::ClassBase, function::FunctionType, }; use crate::place::TypeOrigin; use crate::semantic_index::definition::{Definition, DefinitionState}; use crate::semantic_index::scope::{NodeWithScopeKind, Scope, ScopeKind}; use crate::semantic_index::symbol::Symbol; use crate::semantic_index::{ DeclarationWithConstraint, SemanticIndex, attribute_declarations, attribute_scopes, }; use crate::types::bound_super::BoundSuperError; use crate::types::constraints::{ConstraintSet, IteratorConstraintsExtension}; use crate::types::context::InferContext; use crate::types::diagnostic::{INVALID_TYPE_ALIAS_TYPE, SUPER_CALL_IN_NAMED_TUPLE_METHOD}; use crate::types::enums::{ enum_metadata, is_enum_class_by_inheritance, try_unwrap_nonmember_value, }; use crate::types::function::{ DataclassTransformerFlags, DataclassTransformerParams, KnownFunction, }; use crate::types::generics::{ GenericContext, InferableTypeVars, Specialization, walk_generic_context, walk_specialization, }; use crate::types::infer::{infer_expression_type, infer_unpack_types, nearest_enclosing_class}; use crate::types::member::{Member, class_member}; use crate::types::signatures::{CallableSignature, Parameter, Parameters, Signature}; use crate::types::tuple::{TupleSpec, TupleType}; use crate::types::typed_dict::typed_dict_params_from_class_def; use crate::types::visitor::{TypeCollector, TypeVisitor, walk_type_with_recursion_guard}; use crate::types::{ ApplyTypeMappingVisitor, Binding, BindingContext, BoundSuperType, CallableType, CallableTypeKind, CallableTypes, DATACLASS_FLAGS, DataclassFlags, DataclassParams, DeprecatedInstance, FindLegacyTypeVarsVisitor, HasRelationToVisitor, IntersectionType, IsDisjointVisitor, IsEquivalentVisitor, KnownInstanceType, ManualPEP695TypeAliasType, MaterializationKind, NormalizedVisitor, PropertyInstanceType, TypeAliasType, TypeContext, TypeMapping, TypeRelation, TypedDictParams, UnionBuilder, VarianceInferable, binding_type, declaration_type, determine_upper_bound, }; use crate::{ Db, FxIndexMap, FxIndexSet, FxOrderSet, Program, place::{ Definedness, LookupError, LookupResult, Place, PlaceAndQualifiers, Widening, known_module_symbol, place_from_bindings, place_from_declarations, }, semantic_index::{ attribute_assignments, definition::{DefinitionKind, TargetKind}, place_table, scope::ScopeId, semantic_index, use_def_map, }, types::{ CallArguments, CallError, CallErrorKind, MetaclassCandidate, UnionType, definition_expression_type, }, }; use indexmap::IndexSet; use itertools::Itertools as _; use ruff_db::diagnostic::Span; use ruff_db::files::File; use ruff_db::parsed::{ParsedModuleRef, parsed_module}; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, PythonVersion}; use ruff_text_size::{Ranged, TextRange}; use rustc_hash::FxHashSet; use ty_module_resolver::{KnownModule, file_to_module}; fn explicit_bases_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: ClassLiteral<'db>, ) -> Box<[Type<'db>]> { Box::default() } fn inheritance_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: ClassLiteral<'db>, ) -> Option<InheritanceCycle> { None } fn implicit_attribute_initial<'db>( _db: &'db dyn Db, id: salsa::Id, _class_body_scope: ScopeId<'db>, _name: String, _target_method_decorator: MethodDecorator, ) -> Member<'db> { Member { inner: Place::bound(Type::divergent(id)).into(), } } #[allow(clippy::too_many_arguments)] fn implicit_attribute_cycle_recover<'db>( db: &'db dyn Db, cycle: &salsa::Cycle, previous_member: &Member<'db>, member: Member<'db>, _class_body_scope: ScopeId<'db>, _name: String, _target_method_decorator: MethodDecorator, ) -> Member<'db> { let inner = member .inner .cycle_normalized(db, previous_member.inner, cycle); Member { inner } } fn try_mro_cycle_initial<'db>( db: &'db dyn Db, _id: salsa::Id, self_: ClassLiteral<'db>, specialization: Option<Specialization<'db>>, ) -> Result<Mro<'db>, MroError<'db>> { Err(MroError::cycle( db, self_.apply_optional_specialization(db, specialization), )) } fn is_typed_dict_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: ClassLiteral<'db>, ) -> bool { false } #[allow(clippy::unnecessary_wraps)] fn try_metaclass_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self_: ClassLiteral<'db>, ) -> Result<(Type<'db>, Option<DataclassTransformerParams<'db>>), MetaclassError<'db>> { Err(MetaclassError { kind: MetaclassErrorKind::Cycle, }) } fn decorators_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: ClassLiteral<'db>, ) -> Box<[Type<'db>]> { Box::default() } fn fields_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: ClassLiteral<'db>, _specialization: Option<Specialization<'db>>, _field_policy: CodeGeneratorKind<'db>, ) -> FxIndexMap<Name, Field<'db>> { FxIndexMap::default() } /// A category of classes with code generation capabilities (with synthesized methods). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, salsa::Update, get_size2::GetSize)] pub(crate) enum CodeGeneratorKind<'db> { /// Classes decorated with `@dataclass` or similar dataclass-like decorators DataclassLike(Option<DataclassTransformerParams<'db>>), /// Classes inheriting from `typing.NamedTuple` NamedTuple, /// Classes inheriting from `typing.TypedDict` TypedDict, } impl<'db> CodeGeneratorKind<'db> { pub(crate) fn from_class( db: &'db dyn Db, class: ClassLiteral<'db>, specialization: Option<Specialization<'db>>, ) -> Option<Self> { #[salsa::tracked(cycle_initial=code_generator_of_class_initial, heap_size=ruff_memory_usage::heap_size )] fn code_generator_of_class<'db>( db: &'db dyn Db, class: ClassLiteral<'db>, specialization: Option<Specialization<'db>>, ) -> Option<CodeGeneratorKind<'db>> { if class.dataclass_params(db).is_some() { Some(CodeGeneratorKind::DataclassLike(None)) } else if let Ok((_, Some(transformer_params))) = class.try_metaclass(db) { Some(CodeGeneratorKind::DataclassLike(Some(transformer_params))) } else if let Some(transformer_params) = class.iter_mro(db, specialization).skip(1).find_map(|base| { base.into_class().and_then(|class| { class.class_literal(db).0.dataclass_transformer_params(db) }) }) { Some(CodeGeneratorKind::DataclassLike(Some(transformer_params))) } else if class .explicit_bases(db) .contains(&Type::SpecialForm(SpecialFormType::NamedTuple)) { Some(CodeGeneratorKind::NamedTuple) } else if class.is_typed_dict(db) { Some(CodeGeneratorKind::TypedDict) } else { None } } fn code_generator_of_class_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _class: ClassLiteral<'db>, _specialization: Option<Specialization<'db>>, ) -> Option<CodeGeneratorKind<'db>> { None } code_generator_of_class(db, class, specialization) } pub(super) fn matches( self, db: &'db dyn Db, class: ClassLiteral<'db>, specialization: Option<Specialization<'db>>, ) -> bool { matches!( ( CodeGeneratorKind::from_class(db, class, specialization), self ), (Some(Self::DataclassLike(_)), Self::DataclassLike(_)) | (Some(Self::NamedTuple), Self::NamedTuple) | (Some(Self::TypedDict), Self::TypedDict) ) } pub(super) fn dataclass_transformer_params(self) -> Option<DataclassTransformerParams<'db>> { match self { Self::DataclassLike(params) => params, Self::NamedTuple | Self::TypedDict => None, } } } /// A specialization of a generic class with a particular assignment of types to typevars. /// /// # Ordering /// Ordering is based on the generic aliases's salsa-assigned id and not on its values. /// The id may change between runs, or when the alias was garbage collected and recreated. #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub struct GenericAlias<'db> { pub(crate) origin: ClassLiteral<'db>, pub(crate) specialization: Specialization<'db>, } pub(super) fn walk_generic_alias<'db, V: super::visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, alias: GenericAlias<'db>, visitor: &V, ) { walk_specialization(db, alias.specialization(db), visitor); } // The Salsa heap is tracked separately. impl get_size2::GetSize for GenericAlias<'_> {} impl<'db> GenericAlias<'db> { pub(super) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { Self::new( db, self.origin(db), self.specialization(db).normalized_impl(db, visitor), ) } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self::new( db, self.origin(db), self.specialization(db) .recursive_type_normalized_impl(db, div, nested)?, )) } pub(crate) fn definition(self, db: &'db dyn Db) -> Definition<'db> { self.origin(db).definition(db) } pub(super) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { let tcx = tcx .annotation .and_then(|ty| ty.specialization_of(db, self.origin(db))) .map(|specialization| specialization.types(db)) .unwrap_or(&[]); Self::new( db, self.origin(db), self.specialization(db) .apply_type_mapping_impl(db, type_mapping, tcx, visitor), ) } pub(super) fn find_legacy_typevars_impl( self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { self.specialization(db) .find_legacy_typevars_impl(db, binding_context, typevars, visitor); } pub(super) fn is_typed_dict(self, db: &'db dyn Db) -> bool { self.origin(db).is_typed_dict(db) } } impl<'db> From<GenericAlias<'db>> for Type<'db> { fn from(alias: GenericAlias<'db>) -> Type<'db> { Type::GenericAlias(alias) } } fn variance_of_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: GenericAlias<'db>, _typevar: BoundTypeVarInstance<'db>, ) -> TypeVarVariance { TypeVarVariance::Bivariant } #[salsa::tracked] impl<'db> VarianceInferable<'db> for GenericAlias<'db> { #[salsa::tracked(heap_size=ruff_memory_usage::heap_size, cycle_initial=variance_of_cycle_initial)] fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance { let origin = self.origin(db); let specialization = self.specialization(db); // if the class is the thing defining the variable, then it can // reference it without it being applied to the specialization std::iter::once(origin.variance_of(db, typevar)) .chain( specialization .generic_context(db) .variables(db) .zip(specialization.types(db)) .map(|(generic_typevar, ty)| { if let Some(explicit_variance) = generic_typevar.typevar(db).explicit_variance(db) { ty.with_polarity(explicit_variance).variance_of(db, typevar) } else { // `with_polarity` composes the passed variance with the // inferred one. The inference is done lazily, as we can // sometimes determine the result just from the passed // variance. This operation is commutative, so we could // infer either first. We choose to make the `ClassLiteral` // variance lazy, as it is known to be expensive, requiring // that we traverse all members. // // If salsa let us look at the cache, we could check first // to see if the class literal query was already run. let typevar_variance_in_substituted_type = ty.variance_of(db, typevar); origin .with_polarity(typevar_variance_in_substituted_type) .variance_of(db, generic_typevar) } }), ) .collect() } } /// Represents a class type, which might be a non-generic class, or a specialization of a generic /// class. #[derive( Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, salsa::Supertype, salsa::Update, get_size2::GetSize, )] pub enum ClassType<'db> { // `NonGeneric` is intended to mean that the `ClassLiteral` has no type parameters. There are // places where we currently violate this rule (e.g. so that we print `Foo` instead of // `Foo[Unknown]`), but most callers who need to make a `ClassType` from a `ClassLiteral` // should use `ClassLiteral::default_specialization` instead of assuming // `ClassType::NonGeneric`. NonGeneric(ClassLiteral<'db>), Generic(GenericAlias<'db>), } #[salsa::tracked] impl<'db> ClassType<'db> { /// Return a `ClassType` representing the class `builtins.object` pub(super) fn object(db: &'db dyn Db) -> Self { KnownClass::Object .to_class_literal(db) .to_class_type(db) .unwrap() } pub(super) const fn is_generic(self) -> bool { matches!(self, Self::Generic(_)) } pub(super) const fn into_generic_alias(self) -> Option<GenericAlias<'db>> { match self { Self::NonGeneric(_) => None, Self::Generic(generic) => Some(generic), } } pub(super) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { match self { Self::NonGeneric(_) => self, Self::Generic(generic) => Self::Generic(generic.normalized_impl(db, visitor)), } } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { match self { Self::NonGeneric(_) => Some(self), Self::Generic(generic) => Some(Self::Generic( generic.recursive_type_normalized_impl(db, div, nested)?, )), } } pub(super) fn has_pep_695_type_params(self, db: &'db dyn Db) -> bool { match self { Self::NonGeneric(class) => class.has_pep_695_type_params(db), Self::Generic(generic) => generic.origin(db).has_pep_695_type_params(db), } } /// Returns the class literal and specialization for this class. For a non-generic class, this /// is the class itself. For a generic alias, this is the alias's origin. pub(crate) fn class_literal( self, db: &'db dyn Db, ) -> (ClassLiteral<'db>, Option<Specialization<'db>>) { match self { Self::NonGeneric(non_generic) => (non_generic, None), Self::Generic(generic) => (generic.origin(db), Some(generic.specialization(db))), } } /// Returns the class literal and specialization for this class, with an additional /// specialization applied if the class is generic. pub(crate) fn class_literal_specialized( self, db: &'db dyn Db, additional_specialization: Option<Specialization<'db>>, ) -> (ClassLiteral<'db>, Option<Specialization<'db>>) { match self { Self::NonGeneric(non_generic) => (non_generic, None), Self::Generic(generic) => ( generic.origin(db), Some( generic .specialization(db) .apply_optional_specialization(db, additional_specialization), ), ), } } pub(crate) fn name(self, db: &'db dyn Db) -> &'db ast::name::Name { let (class_literal, _) = self.class_literal(db); class_literal.name(db) } pub(super) fn qualified_name(self, db: &'db dyn Db) -> QualifiedClassName<'db> { let (class_literal, _) = self.class_literal(db); class_literal.qualified_name(db) } pub(crate) fn known(self, db: &'db dyn Db) -> Option<KnownClass> { let (class_literal, _) = self.class_literal(db); class_literal.known(db) } pub(crate) fn definition(self, db: &'db dyn Db) -> Definition<'db> { let (class_literal, _) = self.class_literal(db); class_literal.definition(db) } /// Return `Some` if this class is known to be a [`DisjointBase`], or `None` if it is not. pub(super) fn as_disjoint_base(self, db: &'db dyn Db) -> Option<DisjointBase<'db>> { self.class_literal(db).0.as_disjoint_base(db) } /// Return `true` if this class represents `known_class` pub(crate) fn is_known(self, db: &'db dyn Db, known_class: KnownClass) -> bool { self.known(db) == Some(known_class) } /// Return `true` if this class represents the builtin class `object` pub(crate) fn is_object(self, db: &'db dyn Db) -> bool { self.is_known(db, KnownClass::Object) } pub(super) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { match self { Self::NonGeneric(_) => self, Self::Generic(generic) => { Self::Generic(generic.apply_type_mapping_impl(db, type_mapping, tcx, visitor)) } } } pub(super) fn find_legacy_typevars_impl( self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { match self { Self::NonGeneric(_) => {} Self::Generic(generic) => { generic.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } } } /// Iterate over the [method resolution order] ("MRO") of the class. /// /// If the MRO could not be accurately resolved, this method falls back to iterating /// over an MRO that has the class directly inheriting from `Unknown`. Use /// [`ClassLiteral::try_mro`] if you need to distinguish between the success and failure /// cases rather than simply iterating over the inferred resolution order for the class. /// /// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order pub(super) fn iter_mro(self, db: &'db dyn Db) -> MroIterator<'db> { let (class_literal, specialization) = self.class_literal(db); class_literal.iter_mro(db, specialization) } /// Iterate over the method resolution order ("MRO") of the class, optionally applying an /// additional specialization to it if the class is generic. pub(super) fn iter_mro_specialized( self, db: &'db dyn Db, additional_specialization: Option<Specialization<'db>>, ) -> MroIterator<'db> { let (class_literal, specialization) = self.class_literal_specialized(db, additional_specialization); class_literal.iter_mro(db, specialization) } /// Is this class final? pub(super) fn is_final(self, db: &'db dyn Db) -> bool { let (class_literal, _) = self.class_literal(db); class_literal.is_final(db) } /// Return `true` if `other` is present in this class's MRO. pub(super) fn is_subclass_of(self, db: &'db dyn Db, other: ClassType<'db>) -> bool { self.when_subclass_of(db, other, InferableTypeVars::None) .is_always_satisfied(db) } pub(super) fn when_subclass_of( self, db: &'db dyn Db, other: ClassType<'db>, inferable: InferableTypeVars<'_, 'db>, ) -> ConstraintSet<'db> { self.has_relation_to_impl( db, other, inferable, TypeRelation::Subtyping, &HasRelationToVisitor::default(), &IsDisjointVisitor::default(), ) } pub(super) fn has_relation_to_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { self.iter_mro(db).when_any(db, |base| { match base { ClassBase::Dynamic(_) => match relation { TypeRelation::Subtyping | TypeRelation::Redundancy | TypeRelation::SubtypingAssuming(_) => { ConstraintSet::from(other.is_object(db)) } TypeRelation::Assignability | TypeRelation::ConstraintSetAssignability => { ConstraintSet::from(!other.is_final(db)) } }, // Protocol, Generic, and TypedDict are not represented by a ClassType. ClassBase::Protocol | ClassBase::Generic | ClassBase::TypedDict => { ConstraintSet::from(false) } ClassBase::Class(base) => match (base, other) { (ClassType::NonGeneric(base), ClassType::NonGeneric(other)) => { ConstraintSet::from(base == other) } (ClassType::Generic(base), ClassType::Generic(other)) => { ConstraintSet::from(base.origin(db) == other.origin(db)).and(db, || { base.specialization(db).has_relation_to_impl( db, other.specialization(db), inferable, relation, relation_visitor, disjointness_visitor, ) }) } (ClassType::Generic(_), ClassType::NonGeneric(_)) | (ClassType::NonGeneric(_), ClassType::Generic(_)) => { ConstraintSet::from(false) } }, } }) } pub(super) fn is_equivalent_to_impl( self, db: &'db dyn Db, other: ClassType<'db>, inferable: InferableTypeVars<'_, 'db>, visitor: &IsEquivalentVisitor<'db>, ) -> ConstraintSet<'db> { if self == other { return ConstraintSet::from(true); } match (self, other) { // A non-generic class is never equivalent to a generic class. // Two non-generic classes are only equivalent if they are equal (handled above). (ClassType::NonGeneric(_), _) | (_, ClassType::NonGeneric(_)) => { ConstraintSet::from(false) } (ClassType::Generic(this), ClassType::Generic(other)) => { ConstraintSet::from(this.origin(db) == other.origin(db)).and(db, || { this.specialization(db).is_equivalent_to_impl( db, other.specialization(db), inferable, visitor, ) }) } } } /// Return the metaclass of this class, or `type[Unknown]` if the metaclass cannot be inferred. pub(super) fn metaclass(self, db: &'db dyn Db) -> Type<'db> { let (class_literal, specialization) = self.class_literal(db); class_literal .metaclass(db) .apply_optional_specialization(db, specialization) } /// Return the [`DisjointBase`] that appears first in the MRO of this class. /// /// Returns `None` if this class does not have any disjoint bases in its MRO. pub(super) fn nearest_disjoint_base(self, db: &'db dyn Db) -> Option<DisjointBase<'db>> { self.iter_mro(db) .filter_map(ClassBase::into_class) .find_map(|base| base.as_disjoint_base(db)) } /// Return `true` if this class could exist in the MRO of `other`. pub(super) fn could_exist_in_mro_of(self, db: &'db dyn Db, other: Self) -> bool { other .iter_mro(db) .filter_map(ClassBase::into_class) .any(|class| match (self, class) { (ClassType::NonGeneric(this_class), ClassType::NonGeneric(other_class)) => { this_class == other_class } (ClassType::Generic(this_alias), ClassType::Generic(other_alias)) => { this_alias.origin(db) == other_alias.origin(db) && !this_alias .specialization(db) .is_disjoint_from( db, other_alias.specialization(db), InferableTypeVars::None, ) .is_always_satisfied(db) } (ClassType::NonGeneric(_), ClassType::Generic(_)) | (ClassType::Generic(_), ClassType::NonGeneric(_)) => false, }) } /// Return `true` if this class could coexist in an MRO with `other`. /// /// For two given classes `A` and `B`, it is often possible to say for sure /// that there could never exist any class `C` that inherits from both `A` and `B`. /// In these situations, this method returns `false`; in all others, it returns `true`. pub(super) fn could_coexist_in_mro_with(self, db: &'db dyn Db, other: Self) -> bool { if self == other { return true; } if self.is_final(db) { return other.could_exist_in_mro_of(db, self); } if other.is_final(db) { return self.could_exist_in_mro_of(db, other); } // Two disjoint bases can only coexist in an MRO if one is a subclass of the other. if self .nearest_disjoint_base(db) .is_some_and(|disjoint_base_1| { other .nearest_disjoint_base(db) .is_some_and(|disjoint_base_2| { !disjoint_base_1.could_coexist_in_mro_with(db, &disjoint_base_2) }) }) { return false; } // Check to see whether the metaclasses of `self` and `other` are disjoint. // Avoid this check if the metaclass of either `self` or `other` is `type`, // however, since we end up with infinite recursion in that case due to the fact // that `type` is its own metaclass (and we know that `type` can coexist in an MRO // with any other arbitrary class, anyway). let type_class = KnownClass::Type.to_class_literal(db); let self_metaclass = self.metaclass(db); if self_metaclass == type_class { return true; } let other_metaclass = other.metaclass(db); if other_metaclass == type_class { return true; } let Some(self_metaclass_instance) = self_metaclass.to_instance(db) else { return true; }; let Some(other_metaclass_instance) = other_metaclass.to_instance(db) else { return true; }; if self_metaclass_instance.is_disjoint_from(db, other_metaclass_instance) { return false; } true } /// Return a type representing "the set of all instances of the metaclass of this class". pub(super) fn metaclass_instance_type(self, db: &'db dyn Db) -> Type<'db> { self .metaclass(db) .to_instance(db) .expect("`Type::to_instance()` should always return `Some()` when called on the type of a metaclass") } /// Returns the class member of this class named `name`. /// /// The member resolves to a member on the class itself or any of its proper superclasses. /// /// TODO: Should this be made private...? pub(super) fn class_member( self, db: &'db dyn Db, name: &str, policy: MemberLookupPolicy, ) -> PlaceAndQualifiers<'db> { let (class_literal, specialization) = self.class_literal(db); class_literal.class_member_inner(db, specialization, name, policy) } /// Returns the inferred type of the class member named `name`. Only bound members /// or those marked as `ClassVars` are considered. /// /// You must provide the `inherited_generic_context` that we should use for the `__new__` or /// `__init__` member. This is inherited from the containing class -­but importantly, from the /// class that the lookup is being performed on, and not the class containing the (possibly /// inherited) member. /// /// Returns [`Place::Undefined`] if `name` cannot be found in this class's scope /// directly. Use [`ClassType::class_member`] if you require a method that will /// traverse through the MRO until it finds the member. pub(super) fn own_class_member( self, db: &'db dyn Db, inherited_generic_context: Option<GenericContext<'db>>, name: &str, ) -> Member<'db> { fn synthesize_getitem_overload_signature<'db>( db: &'db dyn Db, index_annotation: Type<'db>, return_annotation: Type<'db>, ) -> Signature<'db> { let self_parameter = Parameter::positional_only(Some(Name::new_static("self"))); let index_parameter = Parameter::positional_only(Some(Name::new_static("index"))) .with_annotated_type(index_annotation); let parameters = Parameters::new(db, [self_parameter, index_parameter]); Signature::new(parameters, Some(return_annotation)) } let (class_literal, specialization) = self.class_literal(db); let fallback_member_lookup = || { class_literal .own_class_member(db, inherited_generic_context, specialization, name) .map_type(|ty| { let ty = ty.apply_optional_specialization(db, specialization); match specialization.map(|spec| spec.materialization_kind(db)) { Some(Some(materialization_kind)) => ty.materialize( db, materialization_kind, &ApplyTypeMappingVisitor::default(), ), _ => ty, } }) }; match name { "__len__" if class_literal.is_tuple(db) => { let return_type = specialization .and_then(|spec| spec.tuple(db))
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/overrides.rs
crates/ty_python_semantic/src/types/overrides.rs
//! Checks relating to invalid method overrides in subclasses, //! including (but not limited to) violations of the [Liskov Substitution Principle]. //! //! [Liskov Substitution Principle]: https://en.wikipedia.org/wiki/Liskov_substitution_principle use bitflags::bitflags; use ruff_db::diagnostic::Annotation; use rustc_hash::FxHashSet; use crate::{ Db, lint::LintId, place::Place, semantic_index::{ definition::DefinitionKind, place::ScopedPlaceId, place_table, scope::ScopeId, symbol::ScopedSymbolId, use_def_map, }, types::{ ClassBase, ClassLiteral, ClassType, KnownClass, Type, class::CodeGeneratorKind, context::InferContext, diagnostic::{ INVALID_EXPLICIT_OVERRIDE, INVALID_METHOD_OVERRIDE, INVALID_NAMED_TUPLE, OVERRIDE_OF_FINAL_METHOD, report_invalid_method_override, report_overridden_final_method, }, function::{FunctionDecorators, FunctionType, KnownFunction}, list_members::{Member, MemberWithDefinition, all_end_of_scope_members}, }, }; /// Prohibited `NamedTuple` attributes that cannot be overwritten. /// See <https://github.com/python/cpython/blob/main/Lib/typing.py> for the list. const PROHIBITED_NAMEDTUPLE_ATTRS: &[&str] = &[ "__new__", "__init__", "__slots__", "__getnewargs__", "_fields", "_field_defaults", "_field_types", "_make", "_replace", "_asdict", "_source", ]; pub(super) fn check_class<'db>(context: &InferContext<'db, '_>, class: ClassLiteral<'db>) { let db = context.db(); let configuration = OverrideRulesConfig::from(context); if configuration.no_rules_enabled() { return; } let class_specialized = class.identity_specialization(db); let scope = class.body_scope(db); let own_class_members: FxHashSet<_> = all_end_of_scope_members(db, scope).collect(); for member in own_class_members { check_class_declaration(context, configuration, class_specialized, scope, &member); } } fn check_class_declaration<'db>( context: &InferContext<'db, '_>, configuration: OverrideRulesConfig, class: ClassType<'db>, class_scope: ScopeId<'db>, member: &MemberWithDefinition<'db>, ) { /// Salsa-tracked query to check whether any of the definitions of a symbol /// in a superclass scope are function definitions. /// /// We need to know this for compatibility with pyright and mypy, neither of which emit an error /// on `C.f` here: /// /// ```python /// from typing import final /// /// class A: /// @final /// def f(self) -> None: ... /// /// class B: /// f = A.f /// /// class C(B): /// def f(self) -> None: ... # no error here /// ``` /// /// This is a Salsa-tracked query because it has to look at the AST node for the definition, /// which might be in a different Python module. If this weren't a tracked query, we could /// introduce cross-module dependencies and over-invalidation. #[salsa::tracked(heap_size=ruff_memory_usage::heap_size)] fn is_function_definition<'db>( db: &'db dyn Db, scope: ScopeId<'db>, symbol: ScopedSymbolId, ) -> bool { use_def_map(db, scope) .end_of_scope_symbol_bindings(symbol) .filter_map(|binding| binding.binding.definition()) .any(|definition| definition.kind(db).is_function_def()) } let db = context.db(); let MemberWithDefinition { member, first_reachable_definition, } = member; let Place::Defined(type_on_subclass_instance, _, _, _) = Type::instance(db, class).member(db, &member.name).place else { return; }; let (literal, specialization) = class.class_literal(db); let class_kind = CodeGeneratorKind::from_class(db, literal, specialization); // Check for prohibited `NamedTuple` attribute overrides. // // `NamedTuple` classes have certain synthesized attributes (like `_asdict`, `_make`, etc.) // that cannot be overwritten. Attempting to assign to these attributes (without type // annotations) or define methods with these names will raise an `AttributeError` at runtime. if class_kind == Some(CodeGeneratorKind::NamedTuple) && configuration.check_prohibited_named_tuple_attrs() && PROHIBITED_NAMEDTUPLE_ATTRS.contains(&member.name.as_str()) && let Some(symbol_id) = place_table(db, class_scope).symbol_id(&member.name) && let Some(bad_definition) = use_def_map(db, class_scope) .reachable_bindings(ScopedPlaceId::Symbol(symbol_id)) .filter_map(|binding| binding.binding.definition()) .find(|def| !matches!(def.kind(db), DefinitionKind::AnnotatedAssignment(_))) && let Some(builder) = context.report_lint( &INVALID_NAMED_TUPLE, bad_definition.focus_range(db, context.module()), ) { let mut diagnostic = builder.into_diagnostic(format_args!( "Cannot overwrite NamedTuple attribute `{}`", &member.name )); diagnostic.info("This will cause the class creation to fail at runtime"); } let mut subclass_overrides_superclass_declaration = false; let mut has_dynamic_superclass = false; let mut has_typeddict_in_mro = false; let mut liskov_diagnostic_emitted = false; let mut overridden_final_method = None; for class_base in class.iter_mro(db).skip(1) { let superclass = match class_base { ClassBase::Protocol | ClassBase::Generic => continue, ClassBase::Dynamic(_) => { has_dynamic_superclass = true; continue; } ClassBase::TypedDict => { has_typeddict_in_mro = true; continue; } ClassBase::Class(class) => class, }; let (superclass_literal, superclass_specialization) = superclass.class_literal(db); let superclass_scope = superclass_literal.body_scope(db); let superclass_symbol_table = place_table(db, superclass_scope); let superclass_symbol_id = superclass_symbol_table.symbol_id(&member.name); let mut method_kind = MethodKind::default(); // If the member is not defined on the class itself, skip it if let Some(id) = superclass_symbol_id { let superclass_symbol = superclass_symbol_table.symbol(id); if !(superclass_symbol.is_bound() || superclass_symbol.is_declared()) { continue; } } else { if superclass_literal .own_synthesized_member(db, superclass_specialization, None, &member.name) .is_none() { continue; } method_kind = CodeGeneratorKind::from_class(db, superclass_literal, superclass_specialization) .map(MethodKind::Synthesized) .unwrap_or_default(); } let Place::Defined(superclass_type, _, _, _) = Type::instance(db, superclass) .member(db, &member.name) .place else { // If not defined on any superclass, no point in continuing to walk up the MRO break; }; subclass_overrides_superclass_declaration = true; if configuration.check_final_method_overridden() { overridden_final_method = overridden_final_method.or_else(|| { let superclass_symbol_id = superclass_symbol_id?; // TODO: `@final` should be more like a type qualifier: // we should also recognise `@final`-decorated methods that don't end up // as being function- or property-types (because they're wrapped by other // decorators that transform the type into something else). let underlying_functions = extract_underlying_functions( db, superclass .own_class_member(db, None, &member.name) .ignore_possibly_undefined()?, )?; if underlying_functions .iter() .any(|function| function.has_known_decorator(db, FunctionDecorators::FINAL)) && is_function_definition(db, superclass_scope, superclass_symbol_id) { Some((superclass, underlying_functions)) } else { None } }); } // ********************************************************** // Everything below this point in the loop // is about Liskov Substitution Principle checks // ********************************************************** // Only one Liskov diagnostic should be emitted per each invalid override, // even if it overrides multiple superclasses incorrectly! if liskov_diagnostic_emitted { continue; } if !configuration.check_method_liskov_violations() { continue; } // TODO: Check Liskov on non-methods too let Type::FunctionLiteral(subclass_function) = member.ty else { continue; }; // Constructor methods are not checked for Liskov compliance if matches!( &*member.name, "__init__" | "__new__" | "__post_init__" | "__init_subclass__" ) { continue; } // Synthesized `__replace__` methods on dataclasses are not checked if &member.name == "__replace__" && matches!(class_kind, Some(CodeGeneratorKind::DataclassLike(_))) { continue; } let Some(superclass_type_as_callable) = superclass_type.try_upcast_to_callable(db) else { continue; }; if type_on_subclass_instance.is_assignable_to(db, superclass_type_as_callable.into_type(db)) { continue; } report_invalid_method_override( context, &member.name, class, *first_reachable_definition, subclass_function, superclass, superclass_type, method_kind, ); liskov_diagnostic_emitted = true; } if !subclass_overrides_superclass_declaration && !has_dynamic_superclass { if has_typeddict_in_mro { if !KnownClass::TypedDictFallback .to_instance(db) .member(db, &member.name) .place .is_undefined() { subclass_overrides_superclass_declaration = true; } } else if class_kind == Some(CodeGeneratorKind::NamedTuple) { if !KnownClass::NamedTupleFallback .to_instance(db) .member(db, &member.name) .place .is_undefined() { subclass_overrides_superclass_declaration = true; } } } if !subclass_overrides_superclass_declaration && !has_dynamic_superclass // accessing `.kind()` here is fine as `definition` // will always be a definition in the file currently being checked && first_reachable_definition.kind(db).is_function_def() { check_explicit_overrides(context, member, class); } if let Some((superclass, superclass_method)) = overridden_final_method { report_overridden_final_method( context, &member.name, *first_reachable_definition, member.ty, superclass, class, &superclass_method, ); } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub(super) enum MethodKind<'db> { Synthesized(CodeGeneratorKind<'db>), #[default] NotSynthesized, } bitflags! { /// Bitflags representing which override-related rules have been enabled. #[derive(Default, Debug, Copy, Clone)] struct OverrideRulesConfig: u8 { const LISKOV_METHODS = 1 << 0; const EXPLICIT_OVERRIDE = 1 << 1; const FINAL_METHOD_OVERRIDDEN = 1 << 2; const PROHIBITED_NAMED_TUPLE_ATTR = 1 << 3; } } impl From<&InferContext<'_, '_>> for OverrideRulesConfig { fn from(value: &InferContext<'_, '_>) -> Self { let db = value.db(); let rule_selection = db.rule_selection(value.file()); let mut config = OverrideRulesConfig::empty(); if rule_selection.is_enabled(LintId::of(&INVALID_METHOD_OVERRIDE)) { config |= OverrideRulesConfig::LISKOV_METHODS; } if rule_selection.is_enabled(LintId::of(&INVALID_EXPLICIT_OVERRIDE)) { config |= OverrideRulesConfig::EXPLICIT_OVERRIDE; } if rule_selection.is_enabled(LintId::of(&OVERRIDE_OF_FINAL_METHOD)) { config |= OverrideRulesConfig::FINAL_METHOD_OVERRIDDEN; } if rule_selection.is_enabled(LintId::of(&INVALID_NAMED_TUPLE)) { config |= OverrideRulesConfig::PROHIBITED_NAMED_TUPLE_ATTR; } config } } impl OverrideRulesConfig { const fn no_rules_enabled(self) -> bool { self.is_empty() } const fn check_method_liskov_violations(self) -> bool { self.contains(OverrideRulesConfig::LISKOV_METHODS) } const fn check_final_method_overridden(self) -> bool { self.contains(OverrideRulesConfig::FINAL_METHOD_OVERRIDDEN) } const fn check_prohibited_named_tuple_attrs(self) -> bool { self.contains(OverrideRulesConfig::PROHIBITED_NAMED_TUPLE_ATTR) } } fn check_explicit_overrides<'db>( context: &InferContext<'db, '_>, member: &Member<'db>, class: ClassType<'db>, ) { let db = context.db(); let underlying_functions = extract_underlying_functions(db, member.ty); let Some(functions) = underlying_functions else { return; }; let Some(decorated_function) = functions .iter() .find(|function| function.has_known_decorator(db, FunctionDecorators::OVERRIDE)) else { return; }; let function_literal = if context.in_stub() { decorated_function.first_overload_or_implementation(db) } else { decorated_function.literal(db).last_definition(db) }; let Some(builder) = context.report_lint( &INVALID_EXPLICIT_OVERRIDE, function_literal.focus_range(db, context.module()), ) else { return; }; let mut diagnostic = builder.into_diagnostic(format_args!( "Method `{}` is decorated with `@override` but does not override anything", member.name )); if let Some(decorator_span) = function_literal.find_known_decorator_span(db, KnownFunction::Override) { diagnostic.annotate(Annotation::secondary(decorator_span)); } diagnostic.info(format_args!( "No `{member}` definitions were found on any superclasses of `{class}`", member = &member.name, class = class.name(db) )); } fn extract_underlying_functions<'db>( db: &'db dyn Db, ty: Type<'db>, ) -> Option<smallvec::SmallVec<[FunctionType<'db>; 1]>> { match ty { Type::FunctionLiteral(function) => Some(smallvec::smallvec_inline![function]), Type::BoundMethod(method) => Some(smallvec::smallvec_inline![method.function(db)]), Type::PropertyInstance(property) => extract_underlying_functions(db, property.getter(db)?), Type::Union(union) => { let mut functions = smallvec::smallvec![]; for member in union.elements(db) { if let Some(mut member_functions) = extract_underlying_functions(db, *member) { functions.append(&mut member_functions); } } if functions.is_empty() { None } else { Some(functions) } } _ => None, } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/enums.rs
crates/ty_python_semantic/src/types/enums.rs
use ruff_python_ast::name::Name; use rustc_hash::FxHashMap; use crate::{ Db, FxIndexMap, place::{Place, PlaceAndQualifiers, place_from_bindings, place_from_declarations}, semantic_index::{place_table, use_def_map}, types::{ ClassBase, ClassLiteral, DynamicType, EnumLiteralType, KnownClass, MemberLookupPolicy, Type, TypeQualifiers, }, }; #[derive(Debug, PartialEq, Eq, salsa::Update)] pub(crate) struct EnumMetadata<'db> { pub(crate) members: FxIndexMap<Name, Type<'db>>, pub(crate) aliases: FxHashMap<Name, Name>, } impl get_size2::GetSize for EnumMetadata<'_> {} impl EnumMetadata<'_> { fn empty() -> Self { EnumMetadata { members: FxIndexMap::default(), aliases: FxHashMap::default(), } } pub(crate) fn resolve_member<'a>(&'a self, name: &'a Name) -> Option<&'a Name> { if self.members.contains_key(name) { Some(name) } else { self.aliases.get(name) } } } #[allow(clippy::unnecessary_wraps)] fn enum_metadata_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _class: ClassLiteral<'db>, ) -> Option<EnumMetadata<'db>> { Some(EnumMetadata::empty()) } /// List all members of an enum. #[allow(clippy::ref_option, clippy::unnecessary_wraps)] #[salsa::tracked(returns(as_ref), cycle_initial=enum_metadata_cycle_initial, heap_size=ruff_memory_usage::heap_size)] pub(crate) fn enum_metadata<'db>( db: &'db dyn Db, class: ClassLiteral<'db>, ) -> Option<EnumMetadata<'db>> { // This is a fast path to avoid traversing the MRO of known classes if class .known(db) .is_some_and(|known_class| !known_class.is_enum_subclass_with_members()) { return None; } if !is_enum_class_by_inheritance(db, class) { return None; } let scope_id = class.body_scope(db); let use_def_map = use_def_map(db, scope_id); let table = place_table(db, scope_id); let mut enum_values: FxHashMap<Type<'db>, Name> = FxHashMap::default(); let mut auto_counter = 0; let ignored_names: Option<Vec<&str>> = if let Some(ignore) = table.symbol_id("_ignore_") { let ignore_bindings = use_def_map.reachable_symbol_bindings(ignore); let ignore_place = place_from_bindings(db, ignore_bindings).place; match ignore_place { Place::Defined(Type::StringLiteral(ignored_names), _, _, _) => { Some(ignored_names.value(db).split_ascii_whitespace().collect()) } // TODO: support the list-variant of `_ignore_`. _ => None, } } else { None }; let mut aliases = FxHashMap::default(); let members = use_def_map .all_end_of_scope_symbol_bindings() .filter_map(|(symbol_id, bindings)| { let name = table.symbol(symbol_id).name(); if name.starts_with("__") && !name.ends_with("__") { // Skip private attributes return None; } if name == "_ignore_" || ignored_names .as_ref() .is_some_and(|names| names.contains(&name.as_str())) { // Skip ignored attributes return None; } let inferred = place_from_bindings(db, bindings).place; let value_ty = match inferred { Place::Undefined => { return None; } Place::Defined(ty, _, _, _) => { let special_case = match ty { Type::Callable(_) | Type::FunctionLiteral(_) => { // Some types are specifically disallowed for enum members. return None; } Type::NominalInstance(instance) => match instance.known_class(db) { // enum.nonmember Some(KnownClass::Nonmember) => return None, // enum.member Some(KnownClass::Member) => Some( ty.member(db, "value") .place .ignore_possibly_undefined() .unwrap_or(Type::unknown()), ), // enum.auto Some(KnownClass::Auto) => { auto_counter += 1; // `StrEnum`s have different `auto()` behaviour to enums inheriting from `(str, Enum)` let auto_value_ty = if Type::ClassLiteral(class) .is_subtype_of(db, KnownClass::StrEnum.to_subclass_of(db)) { Type::string_literal(db, &name.to_lowercase()) } else { let custom_mixins: smallvec::SmallVec<[Option<KnownClass>; 1]> = class .iter_mro(db, None) .skip(1) .filter_map(ClassBase::into_class) .filter(|class| { !Type::from(*class).is_subtype_of( db, KnownClass::Enum.to_subclass_of(db), ) }) .map(|class| class.known(db)) .filter(|class| { !matches!(class, Some(KnownClass::Object)) }) .collect(); // `IntEnum`s have the same `auto()` behaviour to enums inheriting from `(int, Enum)`, // and `IntEnum`s also have `int` in their MROs, so both cases are handled here. // // In general, the `auto()` behaviour for enums with non-`int` mixins is hard to predict, // so we fall back to `Any` in those cases. if matches!( custom_mixins.as_slice(), [] | [Some(KnownClass::Int)] ) { Type::IntLiteral(auto_counter) } else { Type::any() } }; Some(auto_value_ty) } _ => None, }, _ => None, }; if let Some(special_case) = special_case { special_case } else { let dunder_get = ty .member_lookup_with_policy( db, "__get__".into(), MemberLookupPolicy::NO_INSTANCE_FALLBACK, ) .place; match dunder_get { Place::Undefined | Place::Defined(Type::Dynamic(_), _, _, _) => ty, Place::Defined(_, _, _, _) => { // Descriptors are not considered members. return None; } } } } }; // Duplicate values are aliases that are not considered separate members. This check is only // performed if we can infer a precise literal type for the enum member. If we only get `int`, // we don't know if it's a duplicate or not. if matches!( value_ty, Type::BooleanLiteral(_) | Type::IntLiteral(_) | Type::StringLiteral(_) | Type::BytesLiteral(_) ) { if let Some(canonical) = enum_values.get(&value_ty) { // This is a duplicate value, create an alias to the canonical (first) member aliases.insert(name.clone(), canonical.clone()); return None; } // This is the first occurrence of this value, track it as the canonical member enum_values.insert(value_ty, name.clone()); } let declarations = use_def_map.end_of_scope_symbol_declarations(symbol_id); let declared = place_from_declarations(db, declarations).ignore_conflicting_declarations(); match declared { PlaceAndQualifiers { place: Place::Defined(Type::Dynamic(DynamicType::Unknown), _, _, _), qualifiers, } if qualifiers.contains(TypeQualifiers::FINAL) => {} PlaceAndQualifiers { place: Place::Undefined, .. } => { // Undeclared attributes are considered members } PlaceAndQualifiers { place: Place::Defined(Type::NominalInstance(instance), _, _, _), .. } if instance.has_known_class(db, KnownClass::Member) => { // If the attribute is specifically declared with `enum.member`, it is considered a member } _ => { // Declared attributes are considered non-members return None; } } Some((name.clone(), value_ty)) }) .collect::<FxIndexMap<_, _>>(); if members.is_empty() { // Enum subclasses without members are not considered enums. return None; } Some(EnumMetadata { members, aliases }) } pub(crate) fn enum_member_literals<'a, 'db: 'a>( db: &'db dyn Db, class: ClassLiteral<'db>, exclude_member: Option<&'a Name>, ) -> Option<impl Iterator<Item = Type<'a>> + 'a> { enum_metadata(db, class).map(|metadata| { metadata .members .keys() .filter(move |name| Some(*name) != exclude_member) .map(move |name| Type::EnumLiteral(EnumLiteralType::new(db, class, name.clone()))) }) } pub(crate) fn is_single_member_enum<'db>(db: &'db dyn Db, class: ClassLiteral<'db>) -> bool { enum_metadata(db, class).is_some_and(|metadata| metadata.members.len() == 1) } pub(crate) fn is_enum_class<'db>(db: &'db dyn Db, ty: Type<'db>) -> bool { match ty { Type::ClassLiteral(class_literal) => enum_metadata(db, class_literal).is_some(), _ => false, } } /// Checks if a class is an enum class by inheritance (either a subtype of `Enum` /// or has a metaclass that is a subtype of `EnumType`). /// /// This is a lighter-weight check than `enum_metadata`, which additionally /// verifies that the class has members. pub(crate) fn is_enum_class_by_inheritance<'db>(db: &'db dyn Db, class: ClassLiteral<'db>) -> bool { Type::ClassLiteral(class).is_subtype_of(db, KnownClass::Enum.to_subclass_of(db)) || class .metaclass(db) .is_subtype_of(db, KnownClass::EnumType.to_subclass_of(db)) } /// Extracts the inner value type from an `enum.nonmember()` wrapper. /// /// At runtime, the enum metaclass unwraps `nonmember(value)`, so accessing the attribute /// returns the inner value, not the `nonmember` wrapper. /// /// Returns `Some(value_type)` if the type is a `nonmember[T]`, otherwise `None`. pub(crate) fn try_unwrap_nonmember_value<'db>(db: &'db dyn Db, ty: Type<'db>) -> Option<Type<'db>> { match ty { Type::NominalInstance(instance) if instance.has_known_class(db, KnownClass::Nonmember) => { Some( ty.member(db, "value") .place .ignore_possibly_undefined() .unwrap_or(Type::unknown()), ) } _ => None, } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/function.rs
crates/ty_python_semantic/src/types/function.rs
//! Contains representations of function literals. There are several complicating factors: //! //! - Functions can be generic, and can have specializations applied to them. These are not the //! same thing! For instance, a method of a generic class might not itself be generic, but it can //! still have the class's specialization applied to it. //! //! - Functions can be overloaded, and each overload can be independently generic or not, with //! different sets of typevars for different generic overloads. In some cases we need to consider //! each overload separately; in others we need to consider all of the overloads (and any //! implementation) as a single collective entity. //! //! - Certain “known” functions need special treatment — for instance, inferring a special return //! type, or raising custom diagnostics. //! //! - TODO: Some functions don't correspond to a function definition in the AST, and are instead //! synthesized as we mimic the behavior of the Python interpreter. Even though they are //! synthesized, and are “implemented” as Rust code, they are still functions from the POV of the //! rest of the type system. //! //! Given these constraints, we have the following representation: a function is a list of one or //! more overloads, with zero or more specializations (more specifically, “type mappings”) applied //! to it. [`FunctionType`] is the outermost type, which is what [`Type::FunctionLiteral`] wraps. //! It contains the list of type mappings to apply. It wraps a [`FunctionLiteral`], which collects //! together all of the overloads (and implementation) of an overloaded function. An //! [`OverloadLiteral`] represents an individual function definition in the AST — that is, each //! overload (and implementation) of an overloaded function, or the single definition of a //! non-overloaded function. //! //! Technically, each `FunctionLiteral` wraps a particular overload and all _previous_ overloads. //! So it's only true that it wraps _all_ overloads if you are looking at the last definition. For //! instance, in //! //! ```py //! @overload //! def f(x: int) -> None: ... //! # <-- 1 //! //! @overload //! def f(x: str) -> None: ... //! # <-- 2 //! //! def f(x): pass //! # <-- 3 //! ``` //! //! resolving `f` at each of the three numbered positions will give you a `FunctionType`, which //! wraps a `FunctionLiteral`, which contain `OverloadLiteral`s only for the definitions that //! appear before that position. We rely on the fact that later definitions shadow earlier ones, so //! the public type of `f` is resolved at position 3, correctly giving you all of the overloads //! (and the implementation). use std::str::FromStr; use bitflags::bitflags; use ruff_db::diagnostic::{Annotation, DiagnosticId, Severity, Span}; use ruff_db::files::{File, FileRange}; use ruff_db::parsed::{ParsedModuleRef, parsed_module}; use ruff_python_ast::{self as ast, ParameterWithDefault}; use ruff_text_size::Ranged; use crate::place::{Definedness, Place, place_from_bindings}; use crate::semantic_index::ast_ids::HasScopedUseId; use crate::semantic_index::definition::Definition; use crate::semantic_index::scope::ScopeId; use crate::semantic_index::{FileScopeId, SemanticIndex, semantic_index}; use crate::types::call::{Binding, CallArguments}; use crate::types::constraints::ConstraintSet; use crate::types::context::InferContext; use crate::types::diagnostic::{ INVALID_ARGUMENT_TYPE, REDUNDANT_CAST, STATIC_ASSERT_ERROR, TYPE_ASSERTION_FAILURE, report_bad_argument_to_get_protocol_members, report_bad_argument_to_protocol_interface, report_runtime_check_against_non_runtime_checkable_protocol, }; use crate::types::display::DisplaySettings; use crate::types::generics::{GenericContext, InferableTypeVars, typing_self}; use crate::types::infer::nearest_enclosing_class; use crate::types::list_members::all_members; use crate::types::narrow::ClassInfoConstraintFunction; use crate::types::signatures::{CallableSignature, Signature}; use crate::types::visitor::any_over_type; use crate::types::{ ApplyTypeMappingVisitor, BoundMethodType, BoundTypeVarInstance, CallableType, CallableTypeKind, ClassBase, ClassLiteral, ClassType, DeprecatedInstance, DynamicType, FindLegacyTypeVarsVisitor, HasRelationToVisitor, IsDisjointVisitor, IsEquivalentVisitor, KnownClass, KnownInstanceType, NormalizedVisitor, SpecialFormType, SubclassOfInner, SubclassOfType, Truthiness, Type, TypeContext, TypeMapping, TypeRelation, TypeVarBoundOrConstraints, UnionBuilder, binding_type, definition_expression_type, infer_definition_types, walk_signature, }; use crate::{Db, FxOrderSet}; use ty_module_resolver::{KnownModule, ModuleName, file_to_module, resolve_module}; /// A collection of useful spans for annotating functions. /// /// This can be retrieved via `FunctionType::spans` or /// `Type::function_spans`. pub(crate) struct FunctionSpans { /// The span of the entire function "signature." This includes /// the name, parameter list and return type (if present). pub(crate) signature: Span, /// The span of the function name. i.e., `foo` in `def foo(): ...`. pub(crate) name: Span, /// The span of the parameter list, including the opening and /// closing parentheses. pub(crate) parameters: Span, /// The span of the annotated return type, if present. pub(crate) return_type: Option<Span>, } bitflags! { #[derive(Copy, Clone, Debug, Eq, PartialEq, Default, Hash)] pub struct FunctionDecorators: u8 { /// `@classmethod` const CLASSMETHOD = 1 << 0; /// `@typing.no_type_check` const NO_TYPE_CHECK = 1 << 1; /// `@typing.overload` const OVERLOAD = 1 << 2; /// `@abc.abstractmethod` const ABSTRACT_METHOD = 1 << 3; /// `@typing.final` const FINAL = 1 << 4; /// `@staticmethod` const STATICMETHOD = 1 << 5; /// `@typing.override` const OVERRIDE = 1 << 6; /// `@typing.type_check_only` const TYPE_CHECK_ONLY = 1 << 7; } } impl get_size2::GetSize for FunctionDecorators {} impl FunctionDecorators { pub(super) fn from_decorator_type(db: &dyn Db, decorator_type: Type) -> Self { match decorator_type { Type::FunctionLiteral(function) => match function.known(db) { Some(KnownFunction::NoTypeCheck) => FunctionDecorators::NO_TYPE_CHECK, Some(KnownFunction::Overload) => FunctionDecorators::OVERLOAD, Some(KnownFunction::AbstractMethod) => FunctionDecorators::ABSTRACT_METHOD, Some(KnownFunction::Final) => FunctionDecorators::FINAL, Some(KnownFunction::Override) => FunctionDecorators::OVERRIDE, Some(KnownFunction::TypeCheckOnly) => FunctionDecorators::TYPE_CHECK_ONLY, _ => FunctionDecorators::empty(), }, Type::ClassLiteral(class) => match class.known(db) { Some(KnownClass::Classmethod) => FunctionDecorators::CLASSMETHOD, Some(KnownClass::Staticmethod) => FunctionDecorators::STATICMETHOD, _ => FunctionDecorators::empty(), }, _ => FunctionDecorators::empty(), } } } bitflags! { /// Used for the return type of `dataclass_transform(…)` calls. Keeps track of the /// arguments that were passed in. For the precise meaning of the fields, see [1]. /// /// [1]: https://docs.python.org/3/library/typing.html#typing.dataclass_transform #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, salsa::Update)] pub struct DataclassTransformerFlags: u8 { const EQ_DEFAULT = 1 << 0; const ORDER_DEFAULT = 1 << 1; const KW_ONLY_DEFAULT = 1 << 2; const FROZEN_DEFAULT = 1 << 3; } } impl get_size2::GetSize for DataclassTransformerFlags {} impl Default for DataclassTransformerFlags { fn default() -> Self { Self::EQ_DEFAULT } } /// Metadata for a dataclass-transformer. Stored inside a `Type::DataclassTransformer(…)` /// instance that we use as the return type for `dataclass_transform(…)` calls. #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub struct DataclassTransformerParams<'db> { pub flags: DataclassTransformerFlags, #[returns(deref)] pub field_specifiers: Box<[Type<'db>]>, } impl get_size2::GetSize for DataclassTransformerParams<'_> {} /// Whether a function should implicitly be treated as a staticmethod based on its name. pub(crate) fn is_implicit_staticmethod(function_name: &str) -> bool { matches!(function_name, "__new__") } /// Whether a function should implicitly be treated as a classmethod based on its name. pub(crate) fn is_implicit_classmethod(function_name: &str) -> bool { matches!(function_name, "__init_subclass__" | "__class_getitem__") } /// Representation of a function definition in the AST: either a non-generic function, or a generic /// function that has not been specialized. /// /// If a function has multiple overloads, each overload is represented by a separate function /// definition in the AST, and is therefore a separate `OverloadLiteral` instance. /// /// # Ordering /// Ordering is based on the function's id assigned by salsa and not on the function literal's /// values. The id may change between runs, or when the function literal was garbage collected and /// recreated. #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub struct OverloadLiteral<'db> { /// Name of the function at definition. #[returns(ref)] pub name: ast::name::Name, /// Is this a function that we special-case somehow? If so, which one? pub(crate) known: Option<KnownFunction>, /// The scope that's created by the function, in which the function body is evaluated. pub(crate) body_scope: ScopeId<'db>, /// A set of special decorators that were applied to this function pub(crate) decorators: FunctionDecorators, /// If `Some` then contains the `@warnings.deprecated` pub(crate) deprecated: Option<DeprecatedInstance<'db>>, /// The arguments to `dataclass_transformer`, if this function was annotated /// with `@dataclass_transformer(...)`. pub(crate) dataclass_transformer_params: Option<DataclassTransformerParams<'db>>, } // The Salsa heap is tracked separately. impl get_size2::GetSize for OverloadLiteral<'_> {} #[salsa::tracked] impl<'db> OverloadLiteral<'db> { fn with_dataclass_transformer_params( self, db: &'db dyn Db, params: DataclassTransformerParams<'db>, ) -> Self { Self::new( db, self.name(db).clone(), self.known(db), self.body_scope(db), self.decorators(db), self.deprecated(db), Some(params), ) } fn file(self, db: &'db dyn Db) -> File { // NOTE: Do not use `self.definition(db).file(db)` here, as that could create a // cross-module dependency on the full AST. self.body_scope(db).file(db) } pub(crate) fn has_known_decorator(self, db: &dyn Db, decorator: FunctionDecorators) -> bool { self.decorators(db).contains(decorator) } pub(crate) fn is_overload(self, db: &dyn Db) -> bool { self.has_known_decorator(db, FunctionDecorators::OVERLOAD) } /// Returns true if this overload is decorated with `@staticmethod`, or if it is implicitly a /// staticmethod. pub(crate) fn is_staticmethod(self, db: &dyn Db) -> bool { self.has_known_decorator(db, FunctionDecorators::STATICMETHOD) || is_implicit_staticmethod(self.name(db)) } /// Returns true if this overload is decorated with `@classmethod`, or if it is implicitly a /// classmethod. pub(crate) fn is_classmethod(self, db: &dyn Db) -> bool { self.has_known_decorator(db, FunctionDecorators::CLASSMETHOD) || is_implicit_classmethod(self.name(db)) } pub(crate) fn node<'ast>( self, db: &dyn Db, file: File, module: &'ast ParsedModuleRef, ) -> &'ast ast::StmtFunctionDef { debug_assert_eq!( file, self.file(db), "OverloadLiteral::node() must be called with the same file as the one where \ the function is defined." ); self.body_scope(db).node(db).expect_function().node(module) } /// Iterate through the decorators on this function, returning the span of the first one /// that matches the given predicate. pub(super) fn find_decorator_span( self, db: &'db dyn Db, predicate: impl Fn(Type<'db>) -> bool, ) -> Option<Span> { let definition = self.definition(db); let file = definition.file(db); self.node(db, file, &parsed_module(db, file).load(db)) .decorator_list .iter() .find(|decorator| { predicate(definition_expression_type( db, definition, &decorator.expression, )) }) .map(|decorator| Span::from(file).with_range(decorator.range)) } /// Iterate through the decorators on this function, returning the span of the first one /// that matches the given [`KnownFunction`]. pub(super) fn find_known_decorator_span( self, db: &'db dyn Db, needle: KnownFunction, ) -> Option<Span> { self.find_decorator_span(db, |ty| { ty.as_function_literal() .is_some_and(|f| f.is_known(db, needle)) }) } /// Returns the [`FileRange`] of the function's name. pub(crate) fn focus_range(self, db: &dyn Db, module: &ParsedModuleRef) -> FileRange { FileRange::new( self.file(db), self.body_scope(db) .node(db) .expect_function() .node(module) .name .range, ) } /// Returns the [`Definition`] of this function. /// /// ## Warning /// /// This uses the semantic index to find the definition of the function. This means that if the /// calling query is not in the same file as this function is defined in, then this will create /// a cross-module dependency directly on the full AST which will lead to cache /// over-invalidation. fn definition(self, db: &'db dyn Db) -> Definition<'db> { let body_scope = self.body_scope(db); let index = semantic_index(db, body_scope.file(db)); index.expect_single_definition(body_scope.node(db).expect_function()) } /// Returns the overload immediately before this one in the AST. Returns `None` if there is no /// previous overload. fn previous_overload(self, db: &'db dyn Db) -> Option<FunctionLiteral<'db>> { // The semantic model records a use for each function on the name node. This is used // here to get the previous function definition with the same name. let scope = self.definition(db).scope(db); let module = parsed_module(db, self.file(db)).load(db); let use_def = semantic_index(db, scope.file(db)).use_def_map(scope.file_scope_id(db)); let use_id = self .body_scope(db) .node(db) .expect_function() .node(&module) .name .scoped_use_id(db, scope); let Place::Defined(Type::FunctionLiteral(previous_type), _, Definedness::AlwaysDefined, _) = place_from_bindings(db, use_def.bindings_at_use(use_id)).place else { return None; }; let previous_literal = previous_type.literal(db); let previous_overload = previous_literal.last_definition(db); if !previous_overload.is_overload(db) { return None; } Some(previous_literal) } /// Typed internally-visible signature for this function. /// /// This represents the annotations on the function itself, unmodified by decorators and /// overloads. /// /// ## Warning /// /// This uses the semantic index to find the definition of the function. This means that if the /// calling query is not in the same file as this function is defined in, then this will create /// a cross-module dependency directly on the full AST which will lead to cache /// over-invalidation. pub(crate) fn signature(self, db: &'db dyn Db) -> Signature<'db> { let mut signature = self.raw_signature(db); let scope = self.body_scope(db); let module = parsed_module(db, self.file(db)).load(db); let function_node = scope.node(db).expect_function().node(&module); let index = semantic_index(db, scope.file(db)); let file_scope_id = scope.file_scope_id(db); let is_generator = file_scope_id.is_generator_function(index); if function_node.is_async && !is_generator { signature = signature.wrap_coroutine_return_type(db); } signature } /// Typed internally-visible "raw" signature for this function. /// That is, the return types of async functions are not wrapped in `CoroutineType[...]`. /// /// ## Warning /// /// This uses the semantic index to find the definition of the function. This means that if the /// calling query is not in the same file as this function is defined in, then this will create /// a cross-module dependency directly on the full AST which will lead to cache /// over-invalidation. fn raw_signature(self, db: &'db dyn Db) -> Signature<'db> { /// `self` or `cls` can be implicitly positional-only if: /// - It is a method AND /// - No parameters in the method use PEP-570 syntax AND /// - It is not a `@staticmethod` AND /// - `self`/`cls` is not explicitly positional-only using the PEP-484 convention AND /// - Either the next parameter after `self`/`cls` uses the PEP-484 convention, /// or the enclosing class is a `Protocol` class fn has_implicitly_positional_only_first_param<'db>( db: &'db dyn Db, literal: OverloadLiteral<'db>, node: &ast::StmtFunctionDef, scope: FileScopeId, index: &SemanticIndex, ) -> bool { let parameters = &node.parameters; if !parameters.posonlyargs.is_empty() { return false; } let Some(first_param) = parameters.args.first() else { return false; }; if first_param.uses_pep_484_positional_only_convention() { return false; } if literal.is_staticmethod(db) { return false; } let Some(class_definition) = index.class_definition_of_method(scope) else { return false; }; // `self` and `cls` are always positional-only if the next parameter uses the // PEP-484 convention. if parameters .args .get(1) .is_some_and(ParameterWithDefault::uses_pep_484_positional_only_convention) { return true; } // If there isn't any parameter other than `self`/`cls`, // or there is but it isn't using the PEP-484 convention, // then `self`/`cls` are only implicitly positional-only if // it is a protocol class. let class_type = binding_type(db, class_definition); class_type .to_class_type(db) .is_some_and(|class| class.is_protocol(db)) } let scope = self.body_scope(db); let module = parsed_module(db, self.file(db)).load(db); let function_stmt_node = scope.node(db).expect_function().node(&module); let definition = self.definition(db); let index = semantic_index(db, scope.file(db)); let pep695_ctx = function_stmt_node.type_params.as_ref().map(|type_params| { GenericContext::from_type_params(db, index, definition, type_params) }); let file_scope_id = scope.file_scope_id(db); let has_implicitly_positional_first_parameter = has_implicitly_positional_only_first_param( db, self, function_stmt_node, file_scope_id, index, ); let mut raw_signature = Signature::from_function( db, pep695_ctx, definition, function_stmt_node, has_implicitly_positional_first_parameter, ); let generic_context = raw_signature.generic_context; raw_signature.add_implicit_self_annotation(db, || { if self.is_staticmethod(db) { return None; } // We have not yet added an implicit annotation to the `self` parameter, so any // typevars that currently appear in the method's generic context come from explicit // annotations. let method_has_explicit_self = generic_context .is_some_and(|context| context.variables(db).any(|v| v.typevar(db).is_self(db))); let class_scope_id = definition.scope(db); let class_scope = index.scope(class_scope_id.file_scope_id(db)); let class_node = class_scope.node().as_class()?; let class_def = index.expect_single_definition(class_node); let Type::ClassLiteral(class_literal) = infer_definition_types(db, class_def) .declaration_type(class_def) .inner_type() else { return None; }; let class_is_generic = class_literal.generic_context(db).is_some(); let class_is_fallback = class_literal .known(db) .is_some_and(KnownClass::is_fallback_class); // Normally we implicitly annotate `self` or `cls` with `Self` or `type[Self]`, and // create a `Self` typevar that we then have to solve for whenever this method is // called. As an optimization, we can skip creating that typevar in certain situations: // // - The method cannot use explicit `Self` in any other parameter annotations, // or in its return type. If it does, then we really do need specialization // inference at each call site to see which specific instance type should be // used in those other parameters / return type. // // - The class cannot be generic. If it is, then we might need an actual `Self` // typevar to help carry through constraints that relate the instance type to // other typevars in the method signature. // // - The class cannot be a "fallback class". A fallback class is used like a mixin, // and so we need specialization inference to determine the "real" class that the // fallback is augmenting. (See KnownClass::is_fallback_class for more details.) if method_has_explicit_self || class_is_generic || class_is_fallback { let scope_id = definition.scope(db); let typevar_binding_context = Some(definition); let index = semantic_index(db, scope_id.file(db)); let class = nearest_enclosing_class(db, index, scope_id).unwrap(); let typing_self = typing_self(db, scope_id, typevar_binding_context, class).expect( "We should always find the surrounding class \ for an implicit self: Self annotation", ); if self.is_classmethod(db) { Some(SubclassOfType::from( db, SubclassOfInner::TypeVar(typing_self), )) } else { Some(Type::TypeVar(typing_self)) } } else { // If skip creating the typevar, we use "instance of class" or "subclass of // class" as the implicit annotation instead. if self.is_classmethod(db) { Some(SubclassOfType::from( db, SubclassOfInner::Class(ClassType::NonGeneric(class_literal)), )) } else { Some(class_literal.to_non_generic_instance(db)) } } }); raw_signature } pub(crate) fn parameter_span( self, db: &'db dyn Db, parameter_index: Option<usize>, ) -> Option<(Span, Span)> { let function_scope = self.body_scope(db); let span = Span::from(function_scope.file(db)); let node = function_scope.node(db); let module = parsed_module(db, self.file(db)).load(db); let func_def = node.as_function()?.node(&module); let range = parameter_index .and_then(|parameter_index| { func_def .parameters .iter() .nth(parameter_index) .map(|param| param.range()) }) .unwrap_or(func_def.parameters.range); let name_span = span.clone().with_range(func_def.name.range); let parameter_span = span.with_range(range); Some((name_span, parameter_span)) } pub(crate) fn spans(self, db: &'db dyn Db) -> Option<FunctionSpans> { let function_scope = self.body_scope(db); let span = Span::from(function_scope.file(db)); let node = function_scope.node(db); let module = parsed_module(db, self.file(db)).load(db); let func_def = node.as_function()?.node(&module); let return_type_range = func_def.returns.as_ref().map(|returns| returns.range()); let mut signature = func_def.name.range.cover(func_def.parameters.range); if let Some(return_type_range) = return_type_range { signature = signature.cover(return_type_range); } Some(FunctionSpans { signature: span.clone().with_range(signature), name: span.clone().with_range(func_def.name.range), parameters: span.clone().with_range(func_def.parameters.range), return_type: return_type_range.map(|range| span.clone().with_range(range)), }) } } /// Representation of a function definition in the AST, along with any previous overloads of the /// function. Each overload can be separately generic or not, and each generic overload uses /// distinct typevars. /// /// # Ordering /// Ordering is based on the function's id assigned by salsa and not on the function literal's /// values. The id may change between runs, or when the function literal was garbage collected and /// recreated. #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub struct FunctionLiteral<'db> { pub(crate) last_definition: OverloadLiteral<'db>, } // The Salsa heap is tracked separately. impl get_size2::GetSize for FunctionLiteral<'_> {} fn overloads_and_implementation_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: FunctionLiteral<'db>, ) -> (Box<[OverloadLiteral<'db>]>, Option<OverloadLiteral<'db>>) { (Box::new([]), None) } #[salsa::tracked] impl<'db> FunctionLiteral<'db> { fn name(self, db: &'db dyn Db) -> &'db ast::name::Name { // All of the overloads of a function literal should have the same name. self.last_definition(db).name(db) } fn known(self, db: &'db dyn Db) -> Option<KnownFunction> { // Whether a function is known is based on its name (and its containing module's name), so // all overloads should be known (or not) equivalently. self.last_definition(db).known(db) } fn has_known_decorator(self, db: &dyn Db, decorator: FunctionDecorators) -> bool { self.iter_overloads_and_implementation(db) .any(|overload| overload.decorators(db).contains(decorator)) } /// If the implementation of this function is deprecated, returns the `@warnings.deprecated`. /// /// Checking if an overload is deprecated requires deeper call analysis. fn implementation_deprecated(self, db: &'db dyn Db) -> Option<DeprecatedInstance<'db>> { let (_overloads, implementation) = self.overloads_and_implementation(db); implementation.and_then(|overload| overload.deprecated(db)) } fn definition(self, db: &'db dyn Db) -> Definition<'db> { self.last_definition(db).definition(db) } fn parameter_span( self, db: &'db dyn Db, parameter_index: Option<usize>, ) -> Option<(Span, Span)> { self.last_definition(db).parameter_span(db, parameter_index) } fn spans(self, db: &'db dyn Db) -> Option<FunctionSpans> { self.last_definition(db).spans(db) } fn overloads_and_implementation( self, db: &'db dyn Db, ) -> (&'db [OverloadLiteral<'db>], Option<OverloadLiteral<'db>>) { #[salsa::tracked( returns(ref), heap_size=ruff_memory_usage::heap_size, cycle_initial=overloads_and_implementation_cycle_initial )] fn overloads_and_implementation_inner<'db>( db: &'db dyn Db, function: FunctionLiteral<'db>, ) -> (Box<[OverloadLiteral<'db>]>, Option<OverloadLiteral<'db>>) { let self_overload = function.last_definition(db); let mut current = self_overload; let mut overloads = vec![]; while let Some(previous) = current.previous_overload(db) { let overload = previous.last_definition(db); overloads.push(overload); current = overload; } // Overloads are inserted in reverse order, from bottom to top. overloads.reverse(); let implementation = if self_overload.is_overload(db) { overloads.push(self_overload); None } else { Some(self_overload) }; (overloads.into_boxed_slice(), implementation) } let (overloads, implementation) = overloads_and_implementation_inner(db, self); (overloads.as_ref(), *implementation) } fn iter_overloads_and_implementation( self, db: &'db dyn Db, ) -> impl Iterator<Item = OverloadLiteral<'db>> + 'db { let (implementation, overloads) = self.overloads_and_implementation(db); overloads.into_iter().chain(implementation.iter().copied()) } /// Typed externally-visible signature for this function. /// /// This is the signature as seen by external callers, possibly modified by decorators and/or /// overloaded. /// /// ## Warning /// /// This uses the semantic index to find the definition of the function. This means that if the /// calling query is not in the same file as this function is defined in, then this will create /// a cross-module dependency directly on the full AST which will lead to cache /// over-invalidation. fn signature(self, db: &'db dyn Db) -> CallableSignature<'db> { // We only include an implementation (i.e. a definition not decorated with `@overload`) if // it's the only definition. let (overloads, implementation) = self.overloads_and_implementation(db); if let Some(implementation) = implementation && overloads.is_empty() { return CallableSignature::single(implementation.signature(db)); } CallableSignature::from_overloads(overloads.iter().map(|overload| overload.signature(db))) } /// Typed externally-visible signature of the last overload or implementation of this function. /// /// ## Warning /// /// This uses the semantic index to find the definition of the function. This means that if the /// calling query is not in the same file as this function is defined in, then this will create /// a cross-module dependency directly on the full AST which will lead to cache /// over-invalidation. fn last_definition_signature(self, db: &'db dyn Db) -> Signature<'db> { self.last_definition(db).signature(db) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/narrow.rs
crates/ty_python_semantic/src/types/narrow.rs
use crate::Db; use crate::semantic_index::expression::Expression; use crate::semantic_index::place::{PlaceExpr, PlaceTable, ScopedPlaceId}; use crate::semantic_index::place_table; use crate::semantic_index::predicate::{ CallableAndCallExpr, ClassPatternKind, PatternPredicate, PatternPredicateKind, Predicate, PredicateNode, }; use crate::semantic_index::scope::ScopeId; use crate::subscript::PyIndex; use crate::types::enums::{enum_member_literals, enum_metadata}; use crate::types::function::KnownFunction; use crate::types::infer::{ExpressionInference, infer_same_file_expression_type}; use crate::types::typed_dict::{ SynthesizedTypedDictType, TypedDictField, TypedDictFieldBuilder, TypedDictSchema, TypedDictType, }; use crate::types::{ CallableType, ClassLiteral, ClassType, IntersectionBuilder, IntersectionType, KnownClass, KnownInstanceType, SpecialFormType, SubclassOfInner, SubclassOfType, Truthiness, Type, TypeContext, TypeVarBoundOrConstraints, UnionBuilder, infer_expression_types, }; use ruff_db::parsed::{ParsedModuleRef, parsed_module}; use ruff_python_ast::name::Name; use ruff_python_stdlib::identifiers::is_identifier; use super::UnionType; use itertools::Itertools; use ruff_python_ast as ast; use ruff_python_ast::{BoolOp, ExprBoolOp}; use rustc_hash::FxHashMap; use smallvec::{SmallVec, smallvec}; use std::collections::hash_map::Entry; /// Return the type constraint that `test` (if true) would place on `symbol`, if any. /// /// For example, if we have this code: /// /// ```python /// y = 1 if flag else None /// x = 1 if flag else None /// if x is not None: /// ... /// ``` /// /// The `test` expression `x is not None` places the constraint "not None" on the definition of /// `x`, so in that case we'd return `Some(Type::Intersection(negative=[Type::None]))`. /// /// But if we called this with the same `test` expression, but the `symbol` of `y`, no /// constraint is applied to that symbol, so we'd just return `None`. pub(crate) fn infer_narrowing_constraint<'db>( db: &'db dyn Db, predicate: Predicate<'db>, place: ScopedPlaceId, ) -> Option<NarrowingConstraint<'db>> { let constraints = match predicate.node { PredicateNode::Expression(expression) => { if predicate.is_positive { all_narrowing_constraints_for_expression(db, expression) } else { all_negative_narrowing_constraints_for_expression(db, expression) } } PredicateNode::Pattern(pattern) => { if predicate.is_positive { all_narrowing_constraints_for_pattern(db, pattern) } else { all_negative_narrowing_constraints_for_pattern(db, pattern) } } PredicateNode::ReturnsNever(_) => return None, PredicateNode::StarImportPlaceholder(_) => return None, }; constraints.and_then(|constraints| constraints.get(&place).cloned()) } #[salsa::tracked(returns(as_ref), heap_size=ruff_memory_usage::heap_size)] fn all_narrowing_constraints_for_pattern<'db>( db: &'db dyn Db, pattern: PatternPredicate<'db>, ) -> Option<NarrowingConstraints<'db>> { let module = parsed_module(db, pattern.file(db)).load(db); NarrowingConstraintsBuilder::new(db, &module, PredicateNode::Pattern(pattern), true).finish() } #[salsa::tracked( returns(as_ref), cycle_initial=constraints_for_expression_cycle_initial, heap_size=ruff_memory_usage::heap_size, )] fn all_narrowing_constraints_for_expression<'db>( db: &'db dyn Db, expression: Expression<'db>, ) -> Option<NarrowingConstraints<'db>> { let module = parsed_module(db, expression.file(db)).load(db); NarrowingConstraintsBuilder::new(db, &module, PredicateNode::Expression(expression), true) .finish() } #[salsa::tracked( returns(as_ref), cycle_initial=negative_constraints_for_expression_cycle_initial, heap_size=ruff_memory_usage::heap_size, )] fn all_negative_narrowing_constraints_for_expression<'db>( db: &'db dyn Db, expression: Expression<'db>, ) -> Option<NarrowingConstraints<'db>> { let module = parsed_module(db, expression.file(db)).load(db); NarrowingConstraintsBuilder::new(db, &module, PredicateNode::Expression(expression), false) .finish() } #[salsa::tracked(returns(as_ref), heap_size=ruff_memory_usage::heap_size)] fn all_negative_narrowing_constraints_for_pattern<'db>( db: &'db dyn Db, pattern: PatternPredicate<'db>, ) -> Option<NarrowingConstraints<'db>> { let module = parsed_module(db, pattern.file(db)).load(db); NarrowingConstraintsBuilder::new(db, &module, PredicateNode::Pattern(pattern), false).finish() } fn constraints_for_expression_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _expression: Expression<'db>, ) -> Option<NarrowingConstraints<'db>> { None } fn negative_constraints_for_expression_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _expression: Expression<'db>, ) -> Option<NarrowingConstraints<'db>> { None } /// Functions that can be used to narrow the type of a first argument using a "classinfo" second argument. /// /// A "classinfo" argument is either a class or a tuple of classes, or a tuple of tuples of classes /// (etc. for arbitrary levels of recursion) #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ClassInfoConstraintFunction { /// `builtins.isinstance` IsInstance, /// `builtins.issubclass` IsSubclass, } impl ClassInfoConstraintFunction { /// Generate a constraint from the type of a `classinfo` argument to `isinstance` or `issubclass`. /// /// The `classinfo` argument can be a class literal, a tuple of (tuples of) class literals. PEP 604 /// union types are not yet supported. Returns `None` if the `classinfo` argument has a wrong type. fn generate_constraint<'db>(self, db: &'db dyn Db, classinfo: Type<'db>) -> Option<Type<'db>> { let constraint_fn = |class: ClassLiteral<'db>| match self { ClassInfoConstraintFunction::IsInstance => { Type::instance(db, class.top_materialization(db)) } ClassInfoConstraintFunction::IsSubclass => { SubclassOfType::from(db, class.top_materialization(db)) } }; match classinfo { Type::TypeAlias(alias) => self.generate_constraint(db, alias.value_type(db)), Type::ClassLiteral(class_literal) => Some(constraint_fn(class_literal)), Type::SubclassOf(subclass_of_ty) => match subclass_of_ty.subclass_of() { SubclassOfInner::Class(ClassType::NonGeneric(class)) => Some(constraint_fn(class)), // It's not valid to use a generic alias as the second argument to `isinstance()` or `issubclass()`, // e.g. `isinstance(x, list[int])` fails at runtime. SubclassOfInner::Class(ClassType::Generic(_)) => None, SubclassOfInner::Dynamic(dynamic) => Some(Type::Dynamic(dynamic)), SubclassOfInner::TypeVar(bound_typevar) => match self { ClassInfoConstraintFunction::IsSubclass => Some(classinfo), ClassInfoConstraintFunction::IsInstance => Some(Type::TypeVar(bound_typevar)), }, }, Type::Dynamic(_) => Some(classinfo), Type::Intersection(intersection) => { if intersection.negative(db).is_empty() { let mut builder = IntersectionBuilder::new(db); for element in intersection.positive(db) { builder = builder.add_positive(self.generate_constraint(db, *element)?); } Some(builder.build()) } else { // TODO: can we do better here? None } } Type::Union(union) => { union.try_map(db, |element| self.generate_constraint(db, *element)) } Type::TypeVar(bound_typevar) => { match bound_typevar.typevar(db).bound_or_constraints(db)? { TypeVarBoundOrConstraints::UpperBound(bound) => { self.generate_constraint(db, bound) } TypeVarBoundOrConstraints::Constraints(constraints) => { self.generate_constraint(db, constraints.as_type(db)) } } } // It's not valid to use a generic alias as the second argument to `isinstance()` or `issubclass()`, // e.g. `isinstance(x, list[int])` fails at runtime. Type::GenericAlias(_) => None, Type::NominalInstance(nominal) => nominal.tuple_spec(db).and_then(|tuple| { UnionType::try_from_elements( db, tuple .iter_all_elements() .map(|element| self.generate_constraint(db, element)), ) }), Type::KnownInstance(KnownInstanceType::UnionType(instance)) => { UnionType::try_from_elements( db, instance.value_expression_types(db).ok()?.map(|element| { // A special case is made for `None` at runtime // (it's implicitly converted to `NoneType` in `int | None`) // which means that `isinstance(x, int | None)` works even though // `None` is not a class literal. if element.is_none(db) { self.generate_constraint(db, KnownClass::NoneType.to_class_literal(db)) } else { self.generate_constraint(db, element) } }), ) } // We don't have a good meta-type for `Callable`s right now, // so only apply `isinstance()` narrowing, not `issubclass()` Type::SpecialForm(SpecialFormType::Callable) if self == ClassInfoConstraintFunction::IsInstance => { Some(Type::Callable(CallableType::unknown(db)).top_materialization(db)) } Type::SpecialForm(special_form) => special_form .aliased_stdlib_class() .and_then(|class| self.generate_constraint(db, class.to_class_literal(db))), Type::AlwaysFalsy | Type::AlwaysTruthy | Type::BooleanLiteral(_) | Type::BoundMethod(_) | Type::BoundSuper(_) | Type::BytesLiteral(_) | Type::EnumLiteral(_) | Type::Callable(_) | Type::DataclassDecorator(_) | Type::Never | Type::KnownBoundMethod(_) | Type::ModuleLiteral(_) | Type::FunctionLiteral(_) | Type::ProtocolInstance(_) | Type::PropertyInstance(_) | Type::LiteralString | Type::StringLiteral(_) | Type::IntLiteral(_) | Type::KnownInstance(_) | Type::TypeIs(_) | Type::TypeGuard(_) | Type::WrapperDescriptor(_) | Type::DataclassTransformer(_) | Type::TypedDict(_) | Type::NewTypeInstance(_) => None, } } } /// Represents narrowing constraints in Disjunctive Normal Form (DNF). /// /// This is a disjunction (OR) of conjunctions (AND) of constraints. /// The DNF representation allows us to properly track `TypeGuard` constraints /// through boolean operations. /// /// For example: /// - `f(x) and g(x)` where f returns `TypeIs[A]` and g returns `TypeGuard[B]` /// => and /// ===> `NarrowingConstraint { regular_disjunct: Some(A), typeguard_disjuncts: [] }` /// ===> `NarrowingConstraint { regular_disjunct: None, typeguard_disjuncts: [B] }` /// => `NarrowingConstraint { regular_disjunct: None, typeguard_disjuncts: [B] }` /// => evaluates to `B` (`TypeGuard` clobbers any previous type information) /// /// - `f(x) or g(x)` where f returns `TypeIs[A]` and g returns `TypeGuard[B]` /// => or /// ===> `NarrowingConstraint { regular_disjunct: Some(A), typeguard_disjuncts: [] }` /// ===> `NarrowingConstraint { regular_disjunct: None, typeguard_disjuncts: [B] }` /// => `NarrowingConstraint { regular_disjunct: Some(A), typeguard_disjuncts: [B] }` /// => evaluates to `(P & A) | B`, where `P` is our previously-known type #[derive(Hash, PartialEq, Debug, Eq, Clone, salsa::Update, get_size2::GetSize)] pub(crate) struct NarrowingConstraint<'db> { /// Regular constraint (from narrowing comparisons or `TypeIs`). We can use a single type here /// because we can eagerly union disjunctions and eagerly intersect conjunctions. regular_disjunct: Option<Type<'db>>, /// `TypeGuard` constraints. We can't eagerly union disjunctions because `TypeGuard` clobbers /// the previously-known type; within each `TypeGuard` disjunct, we may eagerly intersect /// conjunctions with a later regular narrowing. typeguard_disjuncts: SmallVec<[Type<'db>; 1]>, } impl<'db> NarrowingConstraint<'db> { /// Create a constraint from a regular (non-`TypeGuard`) type pub(crate) fn regular(constraint: Type<'db>) -> Self { Self { regular_disjunct: Some(constraint), typeguard_disjuncts: smallvec![], } } /// Create a constraint from a `TypeGuard` type fn typeguard(constraint: Type<'db>) -> Self { Self { regular_disjunct: None, typeguard_disjuncts: smallvec![constraint], } } /// Merge two constraints, taking their intersection but respecting `TypeGuard` semantics (with /// `other` winning) pub(crate) fn merge_constraint_and(&self, other: Self, db: &'db dyn Db) -> Self { // Distribute AND over OR: (A1 | A2 | ...) AND (B1 | B2 | ...) // becomes (A1 & B1) | (A1 & B2) | ... | (A2 & B1) | ... // // In our representation, the RHS `typeguard_disjuncts` will all clobber the LHS disjuncts // when they are anded, so they'll just stay as is. // // The thing we actually need to deal with is the RHS `regular_disjunct`. It gets // intersected with the LHS `regular_disjunct` to form the new `regular_disjunct`, and // intersected with each LHS `typeguard_disjunct` to form new additional // `typeguard_disjuncts`. let Some(other_regular_disjunct) = other.regular_disjunct else { return other; }; let new_regular_disjunct = self.regular_disjunct.map(|regular_disjunct| { IntersectionType::from_elements(db, [regular_disjunct, other_regular_disjunct]) }); let additional_typeguard_disjuncts = self.typeguard_disjuncts.iter().map(|typeguard_disjunct| { IntersectionType::from_elements(db, [*typeguard_disjunct, other_regular_disjunct]) }); let mut new_typeguard_disjuncts = other.typeguard_disjuncts; new_typeguard_disjuncts.extend(additional_typeguard_disjuncts); NarrowingConstraint { regular_disjunct: new_regular_disjunct, typeguard_disjuncts: new_typeguard_disjuncts, } } /// Evaluate the type this effectively constrains to /// /// Forgets whether each constraint originated from a `TypeGuard` or not pub(crate) fn evaluate_constraint_type(self, db: &'db dyn Db) -> Type<'db> { UnionType::from_elements( db, self.typeguard_disjuncts .into_iter() .chain(self.regular_disjunct), ) } } impl<'db> From<Type<'db>> for NarrowingConstraint<'db> { fn from(constraint: Type<'db>) -> Self { Self::regular(constraint) } } type NarrowingConstraints<'db> = FxHashMap<ScopedPlaceId, NarrowingConstraint<'db>>; /// Merge constraints with AND semantics (intersection/conjunction). /// /// When we have `constraint1 & constraint2`, we need to distribute AND over the OR /// in the DNF representations: /// `(A | B) & (C | D)` becomes `(A & C) | (A & D) | (B & C) | (B & D)` /// /// For each conjunction pair, we: /// - Take the right conjunct if it has a `TypeGuard` /// - Intersect the constraints normally otherwise fn merge_constraints_and<'db>( into: &mut NarrowingConstraints<'db>, from: NarrowingConstraints<'db>, db: &'db dyn Db, ) { for (key, from_constraint) in from { match into.entry(key) { Entry::Occupied(mut entry) => { let into_constraint = entry.get(); entry.insert(into_constraint.merge_constraint_and(from_constraint, db)); } Entry::Vacant(entry) => { entry.insert(from_constraint); } } } } /// Merge constraints with OR semantics (union/disjunction). /// /// When we have `constraint1 OR constraint2`, we simply concatenate the disjuncts /// from both constraints: `(A | B) OR (C | D)` becomes `A | B | C | D` /// /// However, if a place appears in only one branch of the OR, we need to widen it /// to `object` in the overall result (because the other branch doesn't constrain it). fn merge_constraints_or<'db>( into: &mut NarrowingConstraints<'db>, from: NarrowingConstraints<'db>, db: &'db dyn Db, ) { // For places that appear in `into` but not in `from`, widen to object into.retain(|key, _| from.contains_key(key)); for (key, from_constraint) in from { match into.entry(key) { Entry::Occupied(mut entry) => { let into_constraint = entry.get_mut(); // Union the regular constraints into_constraint.regular_disjunct = match ( into_constraint.regular_disjunct, from_constraint.regular_disjunct, ) { (Some(a), Some(b)) => Some(UnionType::from_elements(db, [a, b])), (Some(a), None) => Some(a), (None, Some(b)) => Some(b), (None, None) => None, }; // Concatenate typeguard disjuncts into_constraint .typeguard_disjuncts .extend(from_constraint.typeguard_disjuncts); } Entry::Vacant(_) => { // Place only appears in `from`, not in `into`. No constraint needed. } } } } fn place_expr(expr: &ast::Expr) -> Option<PlaceExpr> { match expr { ast::Expr::Named(named) => PlaceExpr::try_from_expr(named.target.as_ref()), _ => PlaceExpr::try_from_expr(expr), } } /// Return `true` if it is possible for any two inhabitants of the given types to /// compare equal to each other; otherwise return `false`. fn could_compare_equal<'db>(db: &'db dyn Db, left_ty: Type<'db>, right_ty: Type<'db>) -> bool { if !left_ty.is_disjoint_from(db, right_ty) { // If types overlap, they have inhabitants in common; it's definitely possible // for an object to compare equal to itself. return true; } match (left_ty, right_ty) { // In order to be sure a union type cannot compare equal to another type, it // must be true that no element of the union can compare equal to that type. (Type::Union(union), _) => union .elements(db) .iter() .any(|ty| could_compare_equal(db, *ty, right_ty)), (_, Type::Union(union)) => union .elements(db) .iter() .any(|ty| could_compare_equal(db, left_ty, *ty)), // Boolean literals and int literals are disjoint, and single valued, and yet // `True == 1` and `False == 0`. (Type::BooleanLiteral(b), Type::IntLiteral(i)) | (Type::IntLiteral(i), Type::BooleanLiteral(b)) => i64::from(b) == i, // We assume that tuples use `tuple.__eq__` which only returns True // for other tuples, so they cannot compare equal to non-tuple types. (Type::NominalInstance(instance), _) if instance.tuple_spec(db).is_some() => false, (_, Type::NominalInstance(instance)) if instance.tuple_spec(db).is_some() => false, // Other than the above cases, two single-valued disjoint types cannot compare // equal. _ => !(left_ty.is_single_valued(db) && right_ty.is_single_valued(db)), } } struct NarrowingConstraintsBuilder<'db, 'ast> { db: &'db dyn Db, module: &'ast ParsedModuleRef, predicate: PredicateNode<'db>, is_positive: bool, } impl<'db, 'ast> NarrowingConstraintsBuilder<'db, 'ast> { fn new( db: &'db dyn Db, module: &'ast ParsedModuleRef, predicate: PredicateNode<'db>, is_positive: bool, ) -> Self { Self { db, module, predicate, is_positive, } } fn finish(mut self) -> Option<NarrowingConstraints<'db>> { let mut constraints: Option<NarrowingConstraints<'db>> = match self.predicate { PredicateNode::Expression(expression) => { self.evaluate_expression_predicate(expression, self.is_positive) } PredicateNode::Pattern(pattern) => { self.evaluate_pattern_predicate(pattern, self.is_positive) } PredicateNode::ReturnsNever(_) => return None, PredicateNode::StarImportPlaceholder(_) => return None, }; if let Some(ref mut constraints) = constraints { constraints.shrink_to_fit(); } constraints } fn evaluate_expression_predicate( &mut self, expression: Expression<'db>, is_positive: bool, ) -> Option<NarrowingConstraints<'db>> { let expression_node = expression.node_ref(self.db, self.module); self.evaluate_expression_node_predicate(expression_node, expression, is_positive) } fn evaluate_expression_node_predicate( &mut self, expression_node: &ruff_python_ast::Expr, expression: Expression<'db>, is_positive: bool, ) -> Option<NarrowingConstraints<'db>> { match expression_node { ast::Expr::Name(_) | ast::Expr::Attribute(_) | ast::Expr::Subscript(_) => { self.evaluate_simple_expr(expression_node, is_positive) } ast::Expr::Compare(expr_compare) => { self.evaluate_expr_compare(expr_compare, expression, is_positive) } ast::Expr::Call(expr_call) => { self.evaluate_expr_call(expr_call, expression, is_positive) } ast::Expr::UnaryOp(unary_op) if unary_op.op == ast::UnaryOp::Not => { self.evaluate_expression_node_predicate(&unary_op.operand, expression, !is_positive) } ast::Expr::BoolOp(bool_op) => self.evaluate_bool_op(bool_op, expression, is_positive), ast::Expr::Named(expr_named) => self.evaluate_expr_named(expr_named, is_positive), _ => None, } } fn evaluate_pattern_predicate_kind( &mut self, pattern_predicate_kind: &PatternPredicateKind<'db>, subject: Expression<'db>, is_positive: bool, ) -> Option<NarrowingConstraints<'db>> { match pattern_predicate_kind { PatternPredicateKind::Singleton(singleton) => { self.evaluate_match_pattern_singleton(subject, *singleton, is_positive) } PatternPredicateKind::Class(cls, kind) => { self.evaluate_match_pattern_class(subject, *cls, *kind, is_positive) } PatternPredicateKind::Value(expr) => { self.evaluate_match_pattern_value(subject, *expr, is_positive) } PatternPredicateKind::Or(predicates) => { self.evaluate_match_pattern_or(subject, predicates, is_positive) } PatternPredicateKind::As(pattern, _) => pattern .as_deref() .and_then(|p| self.evaluate_pattern_predicate_kind(p, subject, is_positive)), PatternPredicateKind::Unsupported => None, } } fn evaluate_pattern_predicate( &mut self, pattern: PatternPredicate<'db>, is_positive: bool, ) -> Option<NarrowingConstraints<'db>> { self.evaluate_pattern_predicate_kind( pattern.kind(self.db), pattern.subject(self.db), is_positive, ) } fn places(&self) -> &'db PlaceTable { place_table(self.db, self.scope()) } fn scope(&self) -> ScopeId<'db> { match self.predicate { PredicateNode::Expression(expression) => expression.scope(self.db), PredicateNode::Pattern(pattern) => pattern.scope(self.db), PredicateNode::ReturnsNever(CallableAndCallExpr { callable, .. }) => { callable.scope(self.db) } PredicateNode::StarImportPlaceholder(definition) => definition.scope(self.db), } } #[track_caller] fn expect_place(&self, place_expr: &PlaceExpr) -> ScopedPlaceId { self.places() .place_id(place_expr) .expect("We should always have a place for every `PlaceExpr`") } /// Check if a type is directly narrowable by `len()` (without considering unions or intersections). /// /// These are types where we know `__bool__` and `__len__` are consistent and the type /// cannot be subclassed with a `__bool__` that disagrees. fn is_base_type_narrowable_by_len(db: &'db dyn Db, ty: Type<'db>) -> bool { match ty { Type::StringLiteral(_) | Type::LiteralString | Type::BytesLiteral(_) => true, Type::NominalInstance(instance) => instance.tuple_spec(db).is_some(), _ => false, } } /// Narrow a type based on `len()`, only narrowing the parts that are safe to narrow. /// /// For narrowable types (literals, tuples), we apply `~AlwaysFalsy` (positive) or /// `~AlwaysTruthy` (negative). For non-narrowable types, we return them unchanged. /// /// Returns `None` if no part of the type is narrowable. fn narrow_type_by_len(db: &'db dyn Db, ty: Type<'db>, is_positive: bool) -> Option<Type<'db>> { match ty { Type::Union(union) => { let mut has_narrowable = false; let narrowed_elements: Vec<_> = union .elements(db) .iter() .map(|element| { if let Some(narrowed) = Self::narrow_type_by_len(db, *element, is_positive) { has_narrowable = true; narrowed } else { // Non-narrowable elements are kept unchanged. *element } }) .collect(); if has_narrowable { Some(UnionType::from_elements(db, narrowed_elements)) } else { None } } Type::Intersection(intersection) => { // For intersections, check if any positive element is narrowable. let positive = intersection.positive(db); let has_narrowable = positive .iter() .any(|element| Self::is_base_type_narrowable_by_len(db, *element)); if has_narrowable { // Apply the narrowing constraint to the whole intersection. let mut builder = IntersectionBuilder::new(db).add_positive(ty); if is_positive { builder = builder.add_negative(Type::AlwaysFalsy); } else { builder = builder.add_negative(Type::AlwaysTruthy); } Some(builder.build()) } else { None } } _ if Self::is_base_type_narrowable_by_len(db, ty) => { let mut builder = IntersectionBuilder::new(db).add_positive(ty); if is_positive { builder = builder.add_negative(Type::AlwaysFalsy); } else { builder = builder.add_negative(Type::AlwaysTruthy); } Some(builder.build()) } _ => None, } } fn evaluate_simple_expr( &mut self, expr: &ast::Expr, is_positive: bool, ) -> Option<NarrowingConstraints<'db>> { let target = place_expr(expr)?; let place = self.expect_place(&target); let ty = if is_positive { Type::AlwaysFalsy.negate(self.db) } else { Type::AlwaysTruthy.negate(self.db) }; Some(NarrowingConstraints::from_iter([( place, NarrowingConstraint::regular(ty), )])) } fn evaluate_expr_named( &mut self, expr_named: &ast::ExprNamed, is_positive: bool, ) -> Option<NarrowingConstraints<'db>> { self.evaluate_simple_expr(&expr_named.target, is_positive) } fn evaluate_expr_eq(&mut self, lhs_ty: Type<'db>, rhs_ty: Type<'db>) -> Option<Type<'db>> { // We can only narrow on equality checks against single-valued types. if rhs_ty.is_single_valued(self.db) || rhs_ty.is_union_of_single_valued(self.db) { // The fully-general (and more efficient) approach here would be to introduce a // `NeverEqualTo` type that can wrap a single-valued type, and then simply return // `~NeverEqualTo(rhs_ty)` here and let union/intersection builder sort it out. This is // how we handle `AlwaysTruthy` and `AlwaysFalsy`. But this means we have to deal with // this type everywhere, and possibly have it show up unsimplified in some cases, and // so we instead prefer to just do the simplification here. (Another hybrid option that // would be similar to this, but more efficient, would be to allow narrowing to return // something that is not a type, and handle this not-a-type in `symbol_from_bindings`, // instead of intersecting with a type.) // Return `true` if `lhs_ty` consists only of `LiteralString` and types that cannot // compare equal to `rhs_ty`. fn can_narrow_to_rhs<'db>( db: &'db dyn Db, lhs_ty: Type<'db>, rhs_ty: Type<'db>, ) -> bool { match lhs_ty { Type::Union(union) => union .elements(db) .iter() .all(|ty| can_narrow_to_rhs(db, *ty, rhs_ty)), // Either `rhs_ty` is a string literal, in which case we can narrow to it (no // other string literal could compare equal to it), or it is not a string // literal, in which case (given that it is single-valued), LiteralString // cannot compare equal to it. Type::LiteralString => true, _ => !could_compare_equal(db, lhs_ty, rhs_ty), } } // Filter `ty` to just the types that cannot be equal to `rhs_ty`. fn filter_to_cannot_be_equal<'db>( db: &'db dyn Db, ty: Type<'db>, rhs_ty: Type<'db>, ) -> Type<'db> { match ty { Type::Union(union) => { union.map(db, |ty| filter_to_cannot_be_equal(db, *ty, rhs_ty)) } // Treat `bool` as `Literal[True, False]`. Type::NominalInstance(instance) if instance.has_known_class(db, KnownClass::Bool) => { UnionType::from_elements( db, [Type::BooleanLiteral(true), Type::BooleanLiteral(false)] .into_iter() .map(|ty| filter_to_cannot_be_equal(db, ty, rhs_ty)), ) } // Treat enums as a union of their members.
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/subclass_of.rs
crates/ty_python_semantic/src/types/subclass_of.rs
use crate::place::PlaceAndQualifiers; use crate::semantic_index::definition::Definition; use crate::types::constraints::ConstraintSet; use crate::types::generics::InferableTypeVars; use crate::types::protocol_class::ProtocolClass; use crate::types::variance::VarianceInferable; use crate::types::{ ApplyTypeMappingVisitor, BoundTypeVarInstance, ClassType, DynamicType, FindLegacyTypeVarsVisitor, HasRelationToVisitor, IsDisjointVisitor, KnownClass, MaterializationKind, MemberLookupPolicy, NormalizedVisitor, SpecialFormType, Type, TypeContext, TypeMapping, TypeRelation, TypeVarBoundOrConstraints, TypedDictType, UnionType, todo_type, }; use crate::{Db, FxOrderSet}; use super::TypeVarVariance; /// A type that represents `type[C]`, i.e. the class object `C` and class objects that are subclasses of `C`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Update, get_size2::GetSize)] pub struct SubclassOfType<'db> { // Keep this field private, so that the only way of constructing the struct is through the `from` method. subclass_of: SubclassOfInner<'db>, } pub(super) fn walk_subclass_of_type<'db, V: super::visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, subclass_of: SubclassOfType<'db>, visitor: &V, ) { visitor.visit_type(db, Type::from(subclass_of)); } impl<'db> SubclassOfType<'db> { /// Construct a new [`Type`] instance representing a given class object (or a given dynamic type) /// and all possible subclasses of that class object/dynamic type. /// /// This method does not always return a [`Type::SubclassOf`] variant. /// If the class object is known to be a final class, /// this method will return a [`Type::ClassLiteral`] variant; this is a more precise type. /// If the class object is `builtins.object`, `Type::NominalInstance(<builtins.type>)` /// will be returned; this is no more precise, but it is exactly equivalent to `type[object]`. /// /// The eager normalization here means that we do not need to worry elsewhere about distinguishing /// between `@final` classes and other classes when dealing with [`Type::SubclassOf`] variants. pub(crate) fn from(db: &'db dyn Db, subclass_of: impl Into<SubclassOfInner<'db>>) -> Type<'db> { let subclass_of = subclass_of.into(); match subclass_of { SubclassOfInner::Class(class) => { if class.is_final(db) { Type::from(class) } else if class.is_object(db) { Self::subclass_of_object(db) } else { Type::SubclassOf(Self { subclass_of }) } } SubclassOfInner::Dynamic(_) | SubclassOfInner::TypeVar(_) => { Type::SubclassOf(Self { subclass_of }) } } } /// Given the class object `T`, returns a [`Type`] instance representing `type[T]`. pub(crate) fn try_from_type(db: &'db dyn Db, ty: Type<'db>) -> Option<Type<'db>> { let subclass_of = match ty { Type::Dynamic(dynamic) => SubclassOfInner::Dynamic(dynamic), Type::ClassLiteral(literal) => { SubclassOfInner::Class(literal.default_specialization(db)) } Type::GenericAlias(generic) => SubclassOfInner::Class(ClassType::Generic(generic)), Type::SpecialForm(SpecialFormType::Any) => SubclassOfInner::Dynamic(DynamicType::Any), Type::SpecialForm(SpecialFormType::Unknown) => { SubclassOfInner::Dynamic(DynamicType::Unknown) } _ => return None, }; Some(Self::from(db, subclass_of)) } /// Given an instance of the class or type variable `T`, returns a [`Type`] instance representing `type[T]`. pub(crate) fn try_from_instance(db: &'db dyn Db, ty: Type<'db>) -> Option<Type<'db>> { // Handle unions by distributing `type[]` over each element: // `type[A | B]` -> `type[A] | type[B]` if let Type::Union(union) = ty { return UnionType::try_from_elements( db, union .elements(db) .iter() .map(|element| Self::try_from_instance(db, *element)), ); } SubclassOfInner::try_from_instance(db, ty).map(|subclass_of| Self::from(db, subclass_of)) } /// Return a [`Type`] instance representing the type `type[Unknown]`. pub(crate) const fn subclass_of_unknown() -> Type<'db> { Type::SubclassOf(SubclassOfType { subclass_of: SubclassOfInner::unknown(), }) } /// Return a [`Type`] instance representing the type `type[Any]`. #[cfg(test)] pub(crate) const fn subclass_of_any() -> Type<'db> { Type::SubclassOf(SubclassOfType { subclass_of: SubclassOfInner::Dynamic(DynamicType::Any), }) } /// Return a [`Type`] instance representing the type `type[object]`. pub(crate) fn subclass_of_object(db: &'db dyn Db) -> Type<'db> { // See the documentation of `SubclassOfType::from` for details. KnownClass::Type.to_instance(db) } /// Return the inner [`SubclassOfInner`] value wrapped by this `SubclassOfType`. pub(crate) const fn subclass_of(self) -> SubclassOfInner<'db> { self.subclass_of } pub(crate) const fn is_dynamic(self) -> bool { // Unpack `self` so that we're forced to update this method if any more fields are added in the future. let Self { subclass_of } = self; subclass_of.is_dynamic() } pub(crate) const fn is_type_var(self) -> bool { let Self { subclass_of } = self; subclass_of.is_type_var() } pub const fn into_type_var(self) -> Option<BoundTypeVarInstance<'db>> { self.subclass_of.into_type_var() } pub(super) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Type<'db> { match self.subclass_of { SubclassOfInner::Class(class) => Type::SubclassOf(Self { subclass_of: SubclassOfInner::Class(class.apply_type_mapping_impl( db, type_mapping, tcx, visitor, )), }), SubclassOfInner::Dynamic(_) => match type_mapping { TypeMapping::Materialize(materialization_kind) => match materialization_kind { MaterializationKind::Top => KnownClass::Type.to_instance(db), MaterializationKind::Bottom => Type::Never, }, _ => Type::SubclassOf(self), }, SubclassOfInner::TypeVar(typevar) => SubclassOfType::try_from_instance( db, typevar.apply_type_mapping_impl(db, type_mapping, visitor), ) .unwrap_or(SubclassOfType::subclass_of_unknown()), } } pub(super) fn find_legacy_typevars_impl( self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { match self.subclass_of { SubclassOfInner::Dynamic(_) => {} SubclassOfInner::Class(class) => { class.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } SubclassOfInner::TypeVar(typevar) => { Type::TypeVar(typevar).find_legacy_typevars_impl( db, binding_context, typevars, visitor, ); } } } pub(crate) fn find_name_in_mro_with_policy( self, db: &'db dyn Db, name: &str, policy: MemberLookupPolicy, ) -> Option<PlaceAndQualifiers<'db>> { let class_like = match self.subclass_of.with_transposed_type_var(db) { SubclassOfInner::Class(class) => Type::from(class), SubclassOfInner::Dynamic(dynamic) => Type::Dynamic(dynamic), SubclassOfInner::TypeVar(bound_typevar) => { match bound_typevar.typevar(db).bound_or_constraints(db) { None => unreachable!(), Some(TypeVarBoundOrConstraints::UpperBound(bound)) => bound, Some(TypeVarBoundOrConstraints::Constraints(constraints)) => { constraints.as_type(db) } } } }; class_like.find_name_in_mro_with_policy(db, name, policy) } /// Return `true` if `self` has a certain relation to `other`. pub(crate) fn has_relation_to_impl( self, db: &'db dyn Db, other: SubclassOfType<'db>, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { match (self.subclass_of, other.subclass_of) { (SubclassOfInner::Dynamic(_), SubclassOfInner::Dynamic(_)) => { ConstraintSet::from(!relation.is_subtyping()) } (SubclassOfInner::Dynamic(_), SubclassOfInner::Class(other_class)) => { ConstraintSet::from(other_class.is_object(db) || relation.is_assignability()) } (SubclassOfInner::Class(_), SubclassOfInner::Dynamic(_)) => { ConstraintSet::from(relation.is_assignability()) } // For example, `type[bool]` describes all possible runtime subclasses of the class `bool`, // and `type[int]` describes all possible runtime subclasses of the class `int`. // The first set is a subset of the second set, because `bool` is itself a subclass of `int`. (SubclassOfInner::Class(self_class), SubclassOfInner::Class(other_class)) => self_class .has_relation_to_impl( db, other_class, inferable, relation, relation_visitor, disjointness_visitor, ), (SubclassOfInner::TypeVar(_), _) | (_, SubclassOfInner::TypeVar(_)) => { unreachable!() } } } /// Return` true` if `self` is a disjoint type from `other`. /// /// See [`Type::is_disjoint_from`] for more details. pub(crate) fn is_disjoint_from_impl( self, db: &'db dyn Db, other: Self, _inferable: InferableTypeVars<'_, 'db>, _visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { match (self.subclass_of, other.subclass_of) { (SubclassOfInner::Dynamic(_), _) | (_, SubclassOfInner::Dynamic(_)) => { ConstraintSet::from(false) } (SubclassOfInner::Class(self_class), SubclassOfInner::Class(other_class)) => { ConstraintSet::from(!self_class.could_coexist_in_mro_with(db, other_class)) } (SubclassOfInner::TypeVar(_), _) | (_, SubclassOfInner::TypeVar(_)) => { unreachable!() } } } pub(crate) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { Self { subclass_of: self.subclass_of.normalized_impl(db, visitor), } } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self { subclass_of: self .subclass_of .recursive_type_normalized_impl(db, div, nested)?, }) } pub(crate) fn to_instance(self, db: &'db dyn Db) -> Type<'db> { match self.subclass_of { SubclassOfInner::Class(class) => Type::instance(db, class), SubclassOfInner::Dynamic(dynamic_type) => Type::Dynamic(dynamic_type), SubclassOfInner::TypeVar(bound_typevar) => Type::TypeVar(bound_typevar), } } /// Compute the metatype of this `type[T]`. /// /// For `type[C]` where `C` is a concrete class, this returns `type[metaclass(C)]`. /// For `type[T]` where `T` is a `TypeVar`, this computes the metatype based on the /// `TypeVar`'s bounds or constraints. pub(crate) fn to_meta_type(self, db: &'db dyn Db) -> Type<'db> { match self.subclass_of.with_transposed_type_var(db) { SubclassOfInner::Dynamic(dynamic) => { SubclassOfType::from(db, SubclassOfInner::Dynamic(dynamic)) } SubclassOfInner::Class(class) => SubclassOfType::try_from_type(db, class.metaclass(db)) .unwrap_or(SubclassOfType::subclass_of_unknown()), // For `type[T]` where `T` is a TypeVar, `with_transposed_type_var` transforms // the bounds from instance types to `type[]` types. For example, `type[T]` where // `T: A | B` becomes a TypeVar with bound `type[A] | type[B]`. The metatype is // then the metatype of that bound. SubclassOfInner::TypeVar(bound_typevar) => { match bound_typevar.typevar(db).bound_or_constraints(db) { // `with_transposed_type_var` always adds a bound for unbounded TypeVars None => unreachable!(), Some(TypeVarBoundOrConstraints::UpperBound(bound)) => bound.to_meta_type(db), Some(TypeVarBoundOrConstraints::Constraints(constraints)) => { constraints.as_type(db).to_meta_type(db) } } } } } pub(crate) fn is_typed_dict(self, db: &'db dyn Db) -> bool { self.subclass_of .into_class(db) .is_some_and(|class| class.class_literal(db).0.is_typed_dict(db)) } } impl<'db> VarianceInferable<'db> for SubclassOfType<'db> { fn variance_of(self, db: &dyn Db, typevar: BoundTypeVarInstance<'_>) -> TypeVarVariance { match self.subclass_of { SubclassOfInner::Class(class) => class.variance_of(db, typevar), SubclassOfInner::Dynamic(_) | SubclassOfInner::TypeVar(_) => TypeVarVariance::Bivariant, } } } /// An enumeration of the different kinds of `type[]` types that a [`SubclassOfType`] can represent: /// /// 1. A "subclass of a class": `type[C]` for any class object `C` /// 2. A "subclass of a dynamic type": `type[Any]`, `type[Unknown]` and `type[@Todo]` /// 3. A "subclass of a type variable": `type[T]` for any type variable `T` /// /// In the long term, we may want to implement <https://github.com/astral-sh/ruff/issues/15381>. /// Doing this would allow us to get rid of this enum, /// since `type[Any]` would be represented as `type & Any` /// rather than using the [`Type::SubclassOf`] variant at all; /// [`SubclassOfType`] would then be a simple wrapper around [`ClassType`]. /// /// Note that this enum is similar to the [`super::ClassBase`] enum, /// but does not include the `ClassBase::Protocol` and `ClassBase::Generic` variants /// (`type[Protocol]` and `type[Generic]` are not valid types). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Update, get_size2::GetSize)] pub(crate) enum SubclassOfInner<'db> { Class(ClassType<'db>), Dynamic(DynamicType<'db>), TypeVar(BoundTypeVarInstance<'db>), } impl<'db> SubclassOfInner<'db> { pub(crate) const fn unknown() -> Self { Self::Dynamic(DynamicType::Unknown) } pub(crate) const fn is_dynamic(self) -> bool { matches!(self, Self::Dynamic(_)) } pub(crate) const fn is_type_var(self) -> bool { matches!(self, Self::TypeVar(_)) } pub(crate) fn into_class(self, db: &'db dyn Db) -> Option<ClassType<'db>> { match self { Self::Dynamic(_) => None, Self::Class(class) => Some(class), Self::TypeVar(bound_typevar) => { match bound_typevar.typevar(db).bound_or_constraints(db) { None => Some(ClassType::object(db)), Some(TypeVarBoundOrConstraints::UpperBound(bound)) => { Self::try_from_instance(db, bound) .and_then(|subclass_of| subclass_of.into_class(db)) } Some(TypeVarBoundOrConstraints::Constraints(constraints)) => { match &**constraints.elements(db) { [bound] => Self::try_from_instance(db, *bound) .and_then(|subclass_of| subclass_of.into_class(db)), _ => Some(ClassType::object(db)), } } } } } } pub(crate) const fn into_dynamic(self) -> Option<DynamicType<'db>> { match self { Self::Class(_) | Self::TypeVar(_) => None, Self::Dynamic(dynamic) => Some(dynamic), } } pub(crate) const fn into_type_var(self) -> Option<BoundTypeVarInstance<'db>> { match self { Self::Class(_) | Self::Dynamic(_) => None, Self::TypeVar(bound_typevar) => Some(bound_typevar), } } pub(crate) fn try_from_instance(db: &'db dyn Db, ty: Type<'db>) -> Option<Self> { Some(match ty { Type::NominalInstance(instance) => SubclassOfInner::Class(instance.class(db)), Type::TypedDict(typed_dict) => match typed_dict { TypedDictType::Class(class) => SubclassOfInner::Class(class), TypedDictType::Synthesized(_) => SubclassOfInner::Dynamic( todo_type!("type[T] for synthesized TypedDicts").expect_dynamic(), ), }, Type::TypeVar(bound_typevar) => SubclassOfInner::TypeVar(bound_typevar), Type::Dynamic(DynamicType::Any) => SubclassOfInner::Dynamic(DynamicType::Any), Type::Dynamic(DynamicType::Unknown) => SubclassOfInner::Dynamic(DynamicType::Unknown), Type::ProtocolInstance(_) => { SubclassOfInner::Dynamic(todo_type!("type[T] for protocols").expect_dynamic()) } _ => return None, }) } /// Transposes `type[T]` with a type variable `T` into `T: type[...]`. /// /// In particular: /// - If `T` has an upper bound of `T: Bound`, this returns `T: type[Bound]`. /// - If `T` has constraints `T: (A, B)`, this returns `T: (type[A], type[B])`. /// - Otherwise, for an unbounded type variable, this returns `type[object]`. /// /// If this is type of a concrete type `C`, returns the type unchanged. pub(crate) fn with_transposed_type_var(self, db: &'db dyn Db) -> Self { let Some(bound_typevar) = self.into_type_var() else { return self; }; let bound_typevar = bound_typevar.map_bound_or_constraints(db, |bound_or_constraints| { Some(match bound_or_constraints { None => TypeVarBoundOrConstraints::UpperBound( SubclassOfType::try_from_instance(db, Type::object()) .unwrap_or(SubclassOfType::subclass_of_unknown()), ), Some(TypeVarBoundOrConstraints::UpperBound(bound)) => { TypeVarBoundOrConstraints::UpperBound( SubclassOfType::try_from_instance(db, bound) .unwrap_or(SubclassOfType::subclass_of_unknown()), ) } Some(TypeVarBoundOrConstraints::Constraints(constraints)) => { TypeVarBoundOrConstraints::Constraints(constraints.map(db, |constraint| { SubclassOfType::try_from_instance(db, *constraint) .unwrap_or(SubclassOfType::subclass_of_unknown()) })) } }) }); Self::TypeVar(bound_typevar) } pub(crate) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { match self { Self::Class(class) => Self::Class(class.normalized_impl(db, visitor)), Self::Dynamic(dynamic) => Self::Dynamic(dynamic.normalized()), Self::TypeVar(bound_typevar) => { Self::TypeVar(bound_typevar.normalized_impl(db, visitor)) } } } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { match self { Self::Class(class) => Some(Self::Class( class.recursive_type_normalized_impl(db, div, nested)?, )), Self::Dynamic(dynamic) => Some(Self::Dynamic(dynamic.recursive_type_normalized())), Self::TypeVar(_) => Some(self), } } } impl<'db> From<ClassType<'db>> for SubclassOfInner<'db> { fn from(value: ClassType<'db>) -> Self { SubclassOfInner::Class(value) } } impl<'db> From<DynamicType<'db>> for SubclassOfInner<'db> { fn from(value: DynamicType<'db>) -> Self { SubclassOfInner::Dynamic(value) } } impl<'db> From<ProtocolClass<'db>> for SubclassOfInner<'db> { fn from(value: ProtocolClass<'db>) -> Self { SubclassOfInner::Class(*value) } } impl<'db> From<BoundTypeVarInstance<'db>> for SubclassOfInner<'db> { fn from(value: BoundTypeVarInstance<'db>) -> Self { SubclassOfInner::TypeVar(value) } } impl<'db> From<SubclassOfType<'db>> for Type<'db> { fn from(value: SubclassOfType<'db>) -> Self { match value.subclass_of { SubclassOfInner::Class(class) => class.into(), SubclassOfInner::Dynamic(dynamic) => Type::Dynamic(dynamic), SubclassOfInner::TypeVar(bound_typevar) => Type::TypeVar(bound_typevar), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/generics.rs
crates/ty_python_semantic/src/types/generics.rs
use std::cell::RefCell; use std::collections::hash_map::Entry; use std::fmt::Display; use itertools::{Either, Itertools}; use ruff_python_ast as ast; use ruff_python_ast::name::Name; use rustc_hash::{FxHashMap, FxHashSet}; use crate::semantic_index::definition::Definition; use crate::semantic_index::scope::{FileScopeId, NodeWithScopeKind, ScopeId}; use crate::semantic_index::{SemanticIndex, semantic_index}; use crate::types::class::ClassType; use crate::types::class_base::ClassBase; use crate::types::constraints::{ConstraintSet, IteratorConstraintsExtension}; use crate::types::instance::{Protocol, ProtocolInstanceType}; use crate::types::signatures::Parameters; use crate::types::tuple::{TupleSpec, TupleType, walk_tuple_type}; use crate::types::variance::VarianceInferable; use crate::types::visitor::{TypeCollector, TypeVisitor, walk_type_with_recursion_guard}; use crate::types::{ ApplyTypeMappingVisitor, BindingContext, BoundTypeVarIdentity, BoundTypeVarInstance, ClassLiteral, FindLegacyTypeVarsVisitor, HasRelationToVisitor, IntersectionType, IsDisjointVisitor, IsEquivalentVisitor, KnownClass, KnownInstanceType, MaterializationKind, NormalizedVisitor, Type, TypeContext, TypeMapping, TypeRelation, TypeVarBoundOrConstraints, TypeVarIdentity, TypeVarInstance, TypeVarKind, TypeVarVariance, UnionType, declaration_type, walk_type_var_bounds, }; use crate::{Db, FxOrderMap, FxOrderSet}; /// Returns an iterator of any generic context introduced by the given scope or any enclosing /// scope. pub(crate) fn enclosing_generic_contexts<'db>( db: &'db dyn Db, index: &SemanticIndex<'db>, scope: FileScopeId, ) -> impl Iterator<Item = GenericContext<'db>> { index .ancestor_scopes(scope) .filter_map(|(_, ancestor_scope)| ancestor_scope.node().generic_context(db, index)) } /// Binds an unbound typevar. /// /// When a typevar is first created, we will have a [`TypeVarInstance`] which does not have an /// associated binding context. When the typevar is used in a generic class or function, we "bind" /// it, adding the [`Definition`] of the generic class or function as its "binding context". /// /// When an expression resolves to a typevar, our inferred type will refer to the unbound /// [`TypeVarInstance`] from when the typevar was first created. This function walks the scopes /// that enclosing the expression, looking for the innermost binding context that binds the /// typevar. /// /// If no enclosing scope has already bound the typevar, we might be in a syntactic position that /// is about to bind it (indicated by a non-`None` `typevar_binding_context`), in which case we /// bind the typevar with that new binding context. pub(crate) fn bind_typevar<'db>( db: &'db dyn Db, index: &SemanticIndex<'db>, containing_scope: FileScopeId, typevar_binding_context: Option<Definition<'db>>, typevar: TypeVarInstance<'db>, ) -> Option<BoundTypeVarInstance<'db>> { // typing.Self is treated like a legacy typevar, but doesn't follow the same scoping rules. It is always bound to the outermost method in the containing class. if matches!(typevar.kind(db), TypeVarKind::TypingSelf) { for ((_, inner), (_, outer)) in index.ancestor_scopes(containing_scope).tuple_windows() { if outer.kind().is_class() { if let NodeWithScopeKind::Function(function) = inner.node() { let definition = index.expect_single_definition(function); return Some(typevar.with_binding_context(db, definition)); } } } } enclosing_generic_contexts(db, index, containing_scope) .find_map(|enclosing_context| enclosing_context.binds_typevar(db, typevar)) .or_else(|| { typevar_binding_context.map(|typevar_binding_context| { typevar.with_binding_context(db, typevar_binding_context) }) }) } /// Create a `typing.Self` type variable for a given class. pub(crate) fn typing_self<'db>( db: &'db dyn Db, function_scope_id: ScopeId, typevar_binding_context: Option<Definition<'db>>, class: ClassLiteral<'db>, ) -> Option<BoundTypeVarInstance<'db>> { let index = semantic_index(db, function_scope_id.file(db)); let identity = TypeVarIdentity::new( db, ast::name::Name::new_static("Self"), Some(class.definition(db)), TypeVarKind::TypingSelf, ); let bounds = TypeVarBoundOrConstraints::UpperBound(Type::instance( db, class.identity_specialization(db), )); let typevar = TypeVarInstance::new( db, identity, Some(bounds.into()), // According to the [spec], we can consider `Self` // equivalent to an invariant type variable // [spec]: https://typing.python.org/en/latest/spec/generics.html#self Some(TypeVarVariance::Invariant), None, ); bind_typevar( db, index, function_scope_id.file_scope_id(db), typevar_binding_context, typevar, ) } #[derive(Clone, Copy, Debug)] pub(crate) enum InferableTypeVars<'a, 'db> { None, One(&'a FxHashSet<BoundTypeVarIdentity<'db>>), Two( &'a InferableTypeVars<'a, 'db>, &'a InferableTypeVars<'a, 'db>, ), } impl<'db> BoundTypeVarInstance<'db> { pub(crate) fn is_inferable( self, db: &'db dyn Db, inferable: InferableTypeVars<'_, 'db>, ) -> bool { match inferable { InferableTypeVars::None => false, InferableTypeVars::One(typevars) => typevars.contains(&self.identity(db)), InferableTypeVars::Two(left, right) => { self.is_inferable(db, *left) || self.is_inferable(db, *right) } } } } impl<'a, 'db> InferableTypeVars<'a, 'db> { pub(crate) fn merge(&'a self, other: &'a InferableTypeVars<'a, 'db>) -> Self { match (self, other) { (InferableTypeVars::None, other) | (other, InferableTypeVars::None) => *other, _ => InferableTypeVars::Two(self, other), } } // This is not an IntoIterator implementation because I have no desire to try to name the // iterator type. pub(crate) fn iter(self) -> impl Iterator<Item = BoundTypeVarIdentity<'db>> { match self { InferableTypeVars::None => Either::Left(Either::Left(std::iter::empty())), InferableTypeVars::One(typevars) => Either::Right(typevars.iter().copied()), InferableTypeVars::Two(left, right) => { let chained: Box<dyn Iterator<Item = BoundTypeVarIdentity<'db>>> = Box::new(left.iter().chain(right.iter())); Either::Left(Either::Right(chained)) } } } // Keep this around for debugging purposes #[expect(dead_code)] pub(crate) fn display(&self, db: &'db dyn Db) -> impl Display { fn find_typevars<'db>( result: &mut FxHashSet<BoundTypeVarIdentity<'db>>, inferable: &InferableTypeVars<'_, 'db>, ) { match inferable { InferableTypeVars::None => {} InferableTypeVars::One(typevars) => result.extend(typevars.iter().copied()), InferableTypeVars::Two(left, right) => { find_typevars(result, left); find_typevars(result, right); } } } let mut typevars = FxHashSet::default(); find_typevars(&mut typevars, self); format!( "[{}]", typevars .into_iter() .map(|identity| identity.display(db)) .format(", ") ) } } /// A list of formal type variables for a generic function, class, or type alias. /// /// # Ordering /// Ordering is based on the context's salsa-assigned id and not on its values. /// The id may change between runs, or when the context was garbage collected and recreated. #[salsa::interned(debug, constructor=new_internal, heap_size=GenericContext::heap_size)] #[derive(PartialOrd, Ord)] pub struct GenericContext<'db> { #[returns(ref)] variables_inner: FxOrderMap<BoundTypeVarIdentity<'db>, BoundTypeVarInstance<'db>>, } pub(super) fn walk_generic_context<'db, V: TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, context: GenericContext<'db>, visitor: &V, ) { for bound_typevar in context.variables(db) { visitor.visit_bound_type_var_type(db, bound_typevar); } } // The Salsa heap is tracked separately. impl get_size2::GetSize for GenericContext<'_> {} impl<'db> GenericContext<'db> { /// Creates a generic context from a list of PEP-695 type parameters. pub(crate) fn from_type_params( db: &'db dyn Db, index: &'db SemanticIndex<'db>, binding_context: Definition<'db>, type_params_node: &ast::TypeParams, ) -> Self { let variables = type_params_node.iter().filter_map(|type_param| { Self::variable_from_type_param(db, index, binding_context, type_param) }); Self::from_typevar_instances(db, variables) } /// Creates a generic context from a list of `BoundTypeVarInstance`s. pub(crate) fn from_typevar_instances( db: &'db dyn Db, type_params: impl IntoIterator<Item = BoundTypeVarInstance<'db>>, ) -> Self { Self::new_internal( db, type_params .into_iter() .map(|variable| (variable.identity(db), variable)) .collect::<FxOrderMap<_, _>>(), ) } /// Merge this generic context with another, returning a new generic context that /// contains type variables from both contexts. pub(crate) fn merge(self, db: &'db dyn Db, other: Self) -> Self { Self::from_typevar_instances( db, self.variables_inner(db) .values() .chain(other.variables_inner(db).values()) .copied(), ) } pub(crate) fn merge_optional( db: &'db dyn Db, left: Option<Self>, right: Option<Self>, ) -> Option<Self> { match (left, right) { (None, None) => None, (Some(one), None) | (None, Some(one)) => Some(one), (Some(left), Some(right)) => Some(left.merge(db, right)), } } pub(crate) fn remove_self( self, db: &'db dyn Db, binding_context: Option<BindingContext<'db>>, ) -> Self { Self::from_typevar_instances( db, self.variables(db).filter(|bound_typevar| { !(bound_typevar.typevar(db).is_self(db) && binding_context.is_none_or(|binding_context| { bound_typevar.binding_context(db) == binding_context })) }), ) } /// Returns the typevars that are inferable in this generic context. This set might include /// more typevars than the ones directly bound by the generic context. For instance, consider a /// method of a generic class: /// /// ```py /// class C[A]: /// def method[T](self, t: T): /// ``` /// /// In this example, `method`'s generic context binds `Self` and `T`, but its inferable set /// also includes `A@C`. This is needed because at each call site, we need to infer the /// specialized class instance type whose method is being invoked. pub(crate) fn inferable_typevars(self, db: &'db dyn Db) -> InferableTypeVars<'db, 'db> { #[derive(Default)] struct CollectTypeVars<'db> { typevars: RefCell<FxHashSet<BoundTypeVarIdentity<'db>>>, recursion_guard: TypeCollector<'db>, } impl<'db> TypeVisitor<'db> for CollectTypeVars<'db> { fn should_visit_lazy_type_attributes(&self) -> bool { false } fn visit_bound_type_var_type( &self, db: &'db dyn Db, bound_typevar: BoundTypeVarInstance<'db>, ) { self.typevars .borrow_mut() .insert(bound_typevar.identity(db)); let typevar = bound_typevar.typevar(db); if let Some(bound_or_constraints) = typevar.bound_or_constraints(db) { walk_type_var_bounds(db, bound_or_constraints, self); } } fn visit_type(&self, db: &'db dyn Db, ty: Type<'db>) { walk_type_with_recursion_guard(db, ty, self, &self.recursion_guard); } } #[salsa::tracked( returns(ref), cycle_initial=inferable_typevars_cycle_initial, heap_size=ruff_memory_usage::heap_size, )] fn inferable_typevars_inner<'db>( db: &'db dyn Db, generic_context: GenericContext<'db>, ) -> FxHashSet<BoundTypeVarIdentity<'db>> { let visitor = CollectTypeVars::default(); for bound_typevar in generic_context.variables(db) { visitor.visit_bound_type_var_type(db, bound_typevar); } visitor.typevars.into_inner() } // This ensures that salsa caches the FxHashSet, not the InferableTypeVars that wraps it. // (That way InferableTypeVars can contain references, and doesn't need to impl // salsa::Update.) InferableTypeVars::One(inferable_typevars_inner(db, self)) } pub(crate) fn variables( self, db: &'db dyn Db, ) -> impl ExactSizeIterator<Item = BoundTypeVarInstance<'db>> + Clone { self.variables_inner(db).values().copied() } /// Returns `true` if this generic context contains exactly one `ParamSpec` and no other type /// variables. /// /// For example: /// ```py /// class Foo[**P]: ... # true /// class Bar[T, **P]: ... # false /// class Baz[T]: ... # false /// ``` pub(crate) fn exactly_one_paramspec(self, db: &'db dyn Db) -> bool { self.variables(db) .exactly_one() .is_ok_and(|bound_typevar| bound_typevar.is_paramspec(db)) } fn variable_from_type_param( db: &'db dyn Db, index: &'db SemanticIndex<'db>, binding_context: Definition<'db>, type_param_node: &ast::TypeParam, ) -> Option<BoundTypeVarInstance<'db>> { match type_param_node { ast::TypeParam::TypeVar(node) => { let definition = index.expect_single_definition(node); let Type::KnownInstance(KnownInstanceType::TypeVar(typevar)) = declaration_type(db, definition).inner_type() else { return None; }; Some(typevar.with_binding_context(db, binding_context)) } ast::TypeParam::ParamSpec(node) => { let definition = index.expect_single_definition(node); let Type::KnownInstance(KnownInstanceType::TypeVar(typevar)) = declaration_type(db, definition).inner_type() else { return None; }; Some(typevar.with_binding_context(db, binding_context)) } // TODO: Support this! ast::TypeParam::TypeVarTuple(_) => None, } } /// Creates a generic context from the legacy `TypeVar`s that appear in a function parameter /// list. pub(crate) fn from_function_params( db: &'db dyn Db, definition: Definition<'db>, parameters: &Parameters<'db>, return_type: Option<Type<'db>>, ) -> Option<Self> { // Find all of the legacy typevars mentioned in the function signature. let mut variables = FxOrderSet::default(); for param in parameters { if let Some(ty) = param.annotated_type() { ty.find_legacy_typevars(db, Some(definition), &mut variables); } if let Some(ty) = param.default_type() { ty.find_legacy_typevars(db, Some(definition), &mut variables); } } if let Some(ty) = return_type { ty.find_legacy_typevars(db, Some(definition), &mut variables); } if variables.is_empty() { return None; } Some(Self::from_typevar_instances(db, variables)) } pub(crate) fn merge_pep695_and_legacy( db: &'db dyn Db, pep695_generic_context: Option<Self>, legacy_generic_context: Option<Self>, ) -> Option<Self> { match (legacy_generic_context, pep695_generic_context) { (Some(legacy_ctx), Some(ctx)) => { if legacy_ctx .variables(db) .exactly_one() .is_ok_and(|bound_typevar| bound_typevar.typevar(db).is_self(db)) { Some(legacy_ctx.merge(db, ctx)) } else { // TODO: Raise a diagnostic — mixing PEP 695 and legacy typevars is not allowed Some(ctx) } } (left, right) => left.or(right), } } /// Creates a generic context from the legacy `TypeVar`s that appear in class's base class /// list. pub(crate) fn from_base_classes( db: &'db dyn Db, definition: Definition<'db>, bases: impl Iterator<Item = Type<'db>>, ) -> Option<Self> { let mut variables = FxOrderSet::default(); for base in bases { base.find_legacy_typevars(db, Some(definition), &mut variables); } if variables.is_empty() { return None; } Some(Self::from_typevar_instances(db, variables)) } pub(crate) fn len(self, db: &'db dyn Db) -> usize { self.variables_inner(db).len() } pub(crate) fn default_specialization( self, db: &'db dyn Db, known_class: Option<KnownClass>, ) -> Specialization<'db> { let partial = self.specialize_partial(db, std::iter::repeat_n(None, self.len(db))); if known_class == Some(KnownClass::Tuple) { Specialization::new( db, self, partial.types(db), None, Some(TupleType::homogeneous(db, Type::unknown())), ) } else { partial } } /// Returns a specialization of this generic context where each typevar is mapped to itself. pub(crate) fn identity_specialization(self, db: &'db dyn Db) -> Specialization<'db> { let types = self.variables(db).map(Type::TypeVar).collect(); self.specialize(db, types) } pub(crate) fn unknown_specialization(self, db: &'db dyn Db) -> Specialization<'db> { let types = vec![Type::unknown(); self.len(db)]; self.specialize(db, types.into()) } pub(crate) fn is_subset_of(self, db: &'db dyn Db, other: GenericContext<'db>) -> bool { let other_variables = other.variables_inner(db); self.variables(db) .all(|bound_typevar| other_variables.contains_key(&bound_typevar.identity(db))) } pub(crate) fn binds_named_typevar( self, db: &'db dyn Db, name: &'db ast::name::Name, ) -> Option<BoundTypeVarInstance<'db>> { self.variables(db) .find(|self_bound_typevar| self_bound_typevar.typevar(db).name(db) == name) } pub(crate) fn binds_typevar( self, db: &'db dyn Db, typevar: TypeVarInstance<'db>, ) -> Option<BoundTypeVarInstance<'db>> { self.variables(db).find(|self_bound_typevar| { self_bound_typevar.typevar(db).identity(db) == typevar.identity(db) }) } /// Creates a specialization of this generic context. Panics if the length of `types` does not /// match the number of typevars in the generic context. /// /// You must provide a specific type for each typevar; no defaults are used. (Use /// [`specialize_partial`](Self::specialize_partial) if you might not have types for every /// typevar.) /// /// The types you provide should not mention any of the typevars in this generic context; /// otherwise, you will be left with a partial specialization. (Use /// [`specialize_recursive`](Self::specialize_recursive) if your types might mention typevars /// in this generic context.) pub(crate) fn specialize( self, db: &'db dyn Db, types: Box<[Type<'db>]>, ) -> Specialization<'db> { assert_eq!(self.len(db), types.len()); Specialization::new(db, self, types, None, None) } /// Creates a specialization of this generic context. Panics if the length of `types` does not /// match the number of typevars in the generic context. /// /// If any provided type is `None`, we will use the corresponding typevar's default type. You /// are allowed to provide types that mention the typevars in this generic context. pub(crate) fn specialize_recursive<I>(self, db: &'db dyn Db, types: I) -> Specialization<'db> where I: IntoIterator<Item = Option<Type<'db>>>, I::IntoIter: ExactSizeIterator, { fn specialize_recursive_impl<'db>( db: &'db dyn Db, context: GenericContext<'db>, mut types: Box<[Type<'db>]>, ) -> Specialization<'db> { let len = types.len(); loop { let mut any_changed = false; for i in 0..len { let partial = PartialSpecialization { generic_context: context, types: &types, // Don't recursively substitute type[i] in itself. Ideally, we could instead // check if the result is self-referential after we're done applying the // partial specialization. But when we apply a paramspec, we don't use the // callable that it maps to directly; we create a new callable that reuses // parts of it. That means we can't look for the previous type directly. // Instead we use this to skip specializing the type in itself in the first // place. skip: Some(i), }; let updated = types[i].apply_type_mapping( db, &TypeMapping::PartialSpecialization(partial), TypeContext::default(), ); if updated != types[i] { types[i] = updated; any_changed = true; } } if !any_changed { return Specialization::new(db, context, types, None, None); } } } let types = self.fill_in_defaults(db, types); specialize_recursive_impl(db, self, types) } /// Creates a specialization of this generic context for the `tuple` class. pub(crate) fn specialize_tuple( self, db: &'db dyn Db, element_type: Type<'db>, tuple: TupleType<'db>, ) -> Specialization<'db> { Specialization::new(db, self, Box::from([element_type]), None, Some(tuple)) } fn fill_in_defaults<I>(self, db: &'db dyn Db, types: I) -> Box<[Type<'db>]> where I: IntoIterator<Item = Option<Type<'db>>>, I::IntoIter: ExactSizeIterator, { let types = types.into_iter(); let variables = self.variables(db); assert_eq!(self.len(db), types.len()); // Typevars can have other typevars as their default values, e.g. // // ```py // class C[T, U = T]: ... // ``` // // If there is a mapping for `T`, we want to map `U` to that type, not to `T`. To handle // this, we repeatedly apply the specialization to itself, until we reach a fixed point. let mut expanded = Vec::with_capacity(types.len()); for typevar in variables.clone() { if typevar.is_paramspec(db) { expanded.push(Type::paramspec_value_callable(db, Parameters::unknown())); } else { expanded.push(Type::unknown()); } } for (idx, (ty, typevar)) in types.zip(variables).enumerate() { if let Some(ty) = ty { expanded[idx] = ty; continue; } let Some(default) = typevar.default_type(db) else { continue; }; // Typevars are only allowed to refer to _earlier_ typevars in their defaults. (This is // statically enforced for PEP-695 contexts, and is explicitly called out as a // requirement for legacy contexts.) let partial = PartialSpecialization { generic_context: self, types: &expanded[0..idx], skip: None, }; let default = default.apply_type_mapping( db, &TypeMapping::PartialSpecialization(partial), TypeContext::default(), ); expanded[idx] = default; } expanded.into_boxed_slice() } /// Creates a specialization of this generic context. Panics if the length of `types` does not /// match the number of typevars in the generic context. If any provided type is `None`, we /// will use the corresponding typevar's default type. pub(crate) fn specialize_partial<I>(self, db: &'db dyn Db, types: I) -> Specialization<'db> where I: IntoIterator<Item = Option<Type<'db>>>, I::IntoIter: ExactSizeIterator, { Specialization::new(db, self, self.fill_in_defaults(db, types), None, None) } pub(crate) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { let variables = self .variables(db) .map(|bound_typevar| bound_typevar.normalized_impl(db, visitor)); Self::from_typevar_instances(db, variables) } fn heap_size( (variables,): &(FxOrderMap<BoundTypeVarIdentity<'db>, BoundTypeVarInstance<'db>>,), ) -> usize { ruff_memory_usage::order_map_heap_size(variables) } } fn inferable_typevars_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _self: GenericContext<'db>, ) -> FxHashSet<BoundTypeVarIdentity<'db>> { FxHashSet::default() } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(super) enum LegacyGenericBase { Generic, Protocol, } impl LegacyGenericBase { const fn as_str(self) -> &'static str { match self { Self::Generic => "Generic", Self::Protocol => "Protocol", } } } impl Display for LegacyGenericBase { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } } /// An assignment of a specific type to each type variable in a generic scope. /// /// TODO: Handle nested specializations better, with actual parent links to the specialization of /// the lexically containing context. /// /// # Ordering /// Ordering is based on the context's salsa-assigned id and not on its values. /// The id may change between runs, or when the context was garbage collected and recreated. #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub struct Specialization<'db> { pub(crate) generic_context: GenericContext<'db>, #[returns(deref)] pub(crate) types: Box<[Type<'db>]>, /// The materialization kind of the specialization. For example, given an invariant /// generic type `A`, `Top[A[Any]]` is a supertype of all materializations of `A[Any]`, /// and is represented here with `Some(MaterializationKind::Top)`. Similarly, /// `Bottom[A[Any]]` is a subtype of all materializations of `A[Any]`, and is represented /// with `Some(MaterializationKind::Bottom)`. /// The `materialization_kind` field may be non-`None` only if the specialization contains /// dynamic types in invariant positions. pub(crate) materialization_kind: Option<MaterializationKind>, /// For specializations of `tuple`, we also store more detailed information about the tuple's /// elements, above what the class's (single) typevar can represent. tuple_inner: Option<TupleType<'db>>, } // The Salsa heap is tracked separately. impl get_size2::GetSize for Specialization<'_> {} pub(super) fn walk_specialization<'db, V: TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, specialization: Specialization<'db>, visitor: &V, ) { walk_generic_context(db, specialization.generic_context(db), visitor); for ty in specialization.types(db) { visitor.visit_type(db, *ty); } if let Some(tuple) = specialization.tuple_inner(db) { walk_tuple_type(db, tuple, visitor); } } #[expect(clippy::too_many_arguments)] fn is_subtype_in_invariant_position<'db>( db: &'db dyn Db, derived_type: &Type<'db>, derived_materialization: MaterializationKind, base_type: &Type<'db>, base_materialization: MaterializationKind, inferable: InferableTypeVars<'_, 'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { let derived_top = derived_type.top_materialization(db); let derived_bottom = derived_type.bottom_materialization(db); let base_top = base_type.top_materialization(db); let base_bottom = base_type.bottom_materialization(db); let is_subtype_of = |derived: Type<'db>, base: Type<'db>| { // TODO: // This should be removed and properly handled in the respective // `(Type::TypeVar(_), _) | (_, Type::TypeVar(_))` branch of // `Type::has_relation_to_impl`. Right now, we cannot generally // return `ConstraintSet::from(true)` from that branch, as that // leads to union simplification, which means that we lose track // of type variables without recording the constraints under which // the relation holds. if matches!(base, Type::TypeVar(_)) || matches!(derived, Type::TypeVar(_)) { return ConstraintSet::from(true); } derived.has_relation_to_impl( db, base, inferable, TypeRelation::Subtyping, relation_visitor, disjointness_visitor, ) }; match (derived_materialization, base_materialization) { // `Derived` is a subtype of `Base` if the range of materializations covered by `Derived` // is a subset of the range covered by `Base`. (MaterializationKind::Top, MaterializationKind::Top) => { is_subtype_of(base_bottom, derived_bottom) .and(db, || is_subtype_of(derived_top, base_top)) } // One bottom is a subtype of another if it covers a strictly larger set of materializations. (MaterializationKind::Bottom, MaterializationKind::Bottom) => { is_subtype_of(derived_bottom, base_bottom) .and(db, || is_subtype_of(base_top, derived_top)) } // The bottom materialization of `Derived` is a subtype of the top materialization // of `Base` if there is some type that is both within the // range of types covered by derived and within the range covered by base, because if such a type // exists, it's a subtype of `Top[base]` and a supertype of `Bottom[derived]`. (MaterializationKind::Bottom, MaterializationKind::Top) => { is_subtype_of(base_bottom, derived_bottom) .and(db, || is_subtype_of(derived_bottom, base_top)) .or(db, || { is_subtype_of(base_bottom, derived_top) .and(db, || is_subtype_of(derived_top, base_top)) }) .or(db, || { is_subtype_of(base_top, derived_top) .and(db, || is_subtype_of(derived_bottom, base_top)) }) } // A top materialization is a subtype of a bottom materialization only if both original // un-materialized types are the same fully static type. (MaterializationKind::Top, MaterializationKind::Bottom) => { is_subtype_of(derived_top, base_bottom)
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/display.rs
crates/ty_python_semantic/src/types/display.rs
//! Display implementations for types. use std::borrow::Cow; use std::cell::RefCell; use std::collections::hash_map::Entry; use std::fmt::{self, Display, Formatter, Write}; use std::rc::Rc; use ruff_db::files::FilePath; use ruff_db::source::line_index; use ruff_python_ast::str::{Quote, TripleQuotes}; use ruff_python_literal::escape::AsciiEscape; use ruff_text_size::{TextLen, TextRange, TextSize}; use rustc_hash::{FxHashMap, FxHashSet}; use crate::Db; use crate::place::Place; use crate::semantic_index::definition::Definition; use crate::types::class::{ClassLiteral, ClassType, GenericAlias}; use crate::types::function::{FunctionType, OverloadLiteral}; use crate::types::generics::{GenericContext, Specialization}; use crate::types::signatures::{ CallableSignature, Parameter, Parameters, ParametersKind, Signature, }; use crate::types::tuple::TupleSpec; use crate::types::visitor::TypeVisitor; use crate::types::{ BoundTypeVarIdentity, CallableType, CallableTypeKind, IntersectionType, KnownBoundMethodType, KnownClass, KnownInstanceType, MaterializationKind, Protocol, ProtocolInstanceType, SpecialFormType, StringLiteralType, SubclassOfInner, Type, TypeGuardLike, TypedDictType, UnionType, WrapperDescriptorKind, visitor, }; /// Settings for displaying types and signatures #[derive(Debug, Clone, Default)] pub struct DisplaySettings<'db> { /// Whether rendering can be multiline pub multiline: bool, /// Class names that should be displayed fully qualified /// (e.g., `module.ClassName` instead of just `ClassName`) pub qualified: Rc<FxHashMap<&'db str, QualificationLevel>>, /// Whether long unions and literals are displayed in full pub preserve_full_unions: bool, /// Disallow Signature printing to introduce a name /// (presumably because we rendered one already) pub disallow_signature_name: bool, } impl<'db> DisplaySettings<'db> { #[must_use] pub fn multiline(&self) -> Self { Self { multiline: true, ..self.clone() } } #[must_use] pub fn singleline(&self) -> Self { Self { multiline: false, ..self.clone() } } #[must_use] pub fn truncate_long_unions(self) -> Self { Self { preserve_full_unions: false, ..self } } #[must_use] pub fn preserve_long_unions(self) -> Self { Self { preserve_full_unions: true, ..self } } #[must_use] pub fn disallow_signature_name(&self) -> Self { Self { disallow_signature_name: true, ..self.clone() } } #[must_use] pub fn from_possibly_ambiguous_types<I, T>(db: &'db dyn Db, types: I) -> Self where I: IntoIterator<Item = T>, T: Into<Type<'db>>, { fn build_display_settings<'db>( collector: &AmbiguousClassCollector<'db>, ) -> DisplaySettings<'db> { DisplaySettings { qualified: Rc::new( collector .class_names .borrow() .iter() .filter_map(|(name, ambiguity)| { Some((*name, QualificationLevel::from_ambiguity_state(ambiguity)?)) }) .collect(), ), ..DisplaySettings::default() } } let collector = AmbiguousClassCollector::default(); for ty in types { collector.visit_type(db, ty.into()); } build_display_settings(&collector) } } /// Details about a type's formatting /// /// The `targets` and `details` are 1:1 (you can `zip` them) pub struct TypeDisplayDetails<'db> { /// The fully formatted type pub label: String, /// Ranges in the label pub targets: Vec<TextRange>, /// Metadata for each range pub details: Vec<TypeDetail<'db>>, /// Whether the label is valid Python syntax pub is_valid_syntax: bool, } /// Abstraction over "are we doing normal formatting, or tracking ranges with metadata?" enum TypeWriter<'a, 'b, 'db> { Formatter(&'a mut Formatter<'b>), Details(TypeDetailsWriter<'db>), } /// Writer that builds a string with range tracking struct TypeDetailsWriter<'db> { label: String, targets: Vec<TextRange>, details: Vec<TypeDetail<'db>>, is_valid_syntax: bool, } impl<'db> TypeDetailsWriter<'db> { fn new() -> Self { Self { label: String::new(), targets: Vec::new(), details: Vec::new(), is_valid_syntax: true, } } /// Produce type info fn finish_type_details(self) -> TypeDisplayDetails<'db> { TypeDisplayDetails { label: self.label, targets: self.targets, details: self.details, is_valid_syntax: self.is_valid_syntax, } } /// Produce function signature info fn finish_signature_details(self) -> SignatureDisplayDetails { // We use SignatureStart and SignatureEnd to delimit nested function signatures inside // this function signature. We only care about the parameters of the outermost function // which should introduce it's own SignatureStart and SignatureEnd let mut parameter_ranges = Vec::new(); let mut parameter_names = Vec::new(); let mut parameter_nesting = 0; for (target, detail) in self.targets.into_iter().zip(self.details) { match detail { TypeDetail::SignatureStart => parameter_nesting += 1, TypeDetail::SignatureEnd => parameter_nesting -= 1, TypeDetail::Parameter(parameter) => { if parameter_nesting <= 1 { // We found parameters at the top-level, record them parameter_names.push(parameter); parameter_ranges.push(target); } } TypeDetail::Type(_) => { /* don't care */ } } } SignatureDisplayDetails { label: self.label, parameter_names, parameter_ranges, } } } impl<'a, 'b, 'db> TypeWriter<'a, 'b, 'db> { /// Indicate the given detail is about to start being written to this Writer /// /// This creates a scoped guard that when Dropped will record the given detail /// as spanning from when it was introduced to when it was dropped. fn with_detail<'c>(&'c mut self, detail: TypeDetail<'db>) -> TypeDetailGuard<'a, 'b, 'c, 'db> { let start = match self { TypeWriter::Formatter(_) => None, TypeWriter::Details(details) => Some(details.label.text_len()), }; TypeDetailGuard { start, inner: self, payload: Some(detail), } } /// Convenience for `with_detail(TypeDetail::Type(ty))` fn with_type<'c>(&'c mut self, ty: Type<'db>) -> TypeDetailGuard<'a, 'b, 'c, 'db> { self.with_detail(TypeDetail::Type(ty)) } fn set_invalid_type_annotation(&mut self) { match self { TypeWriter::Formatter(_) => {} TypeWriter::Details(details) => details.is_valid_syntax = false, } } fn join<'c>(&'c mut self, separator: &'static str) -> Join<'a, 'b, 'c, 'db> { Join { fmt: self, separator, result: Ok(()), seen_first: false, } } } impl Write for TypeWriter<'_, '_, '_> { fn write_str(&mut self, val: &str) -> fmt::Result { match self { TypeWriter::Formatter(formatter) => formatter.write_str(val), TypeWriter::Details(formatter) => formatter.write_str(val), } } } impl Write for TypeDetailsWriter<'_> { fn write_str(&mut self, val: &str) -> fmt::Result { self.label.write_str(val) } } trait FmtDetailed<'db> { fn fmt_detailed(&self, f: &mut TypeWriter<'_, '_, 'db>) -> fmt::Result; } struct Join<'a, 'b, 'c, 'db> { fmt: &'c mut TypeWriter<'a, 'b, 'db>, separator: &'static str, result: fmt::Result, seen_first: bool, } impl<'db> Join<'_, '_, '_, 'db> { fn entry(&mut self, item: &dyn FmtDetailed<'db>) -> &mut Self { if self.seen_first { self.result = self .result .and_then(|()| self.fmt.write_str(self.separator)); } else { self.seen_first = true; } self.result = self.result.and_then(|()| item.fmt_detailed(self.fmt)); self } fn entries<I, F>(&mut self, items: I) -> &mut Self where I: IntoIterator<Item = F>, F: FmtDetailed<'db>, { for item in items { self.entry(&item); } self } fn finish(&mut self) -> fmt::Result { self.result } } pub enum TypeDetail<'db> { /// Dummy item to indicate a function signature's parameters have started SignatureStart, /// Dummy item to indicate a function signature's parameters have ended SignatureEnd, /// A function signature's parameter Parameter(String), /// A type Type(Type<'db>), } /// Look on my Works, ye Mighty, and despair! /// /// It's quite important that we avoid conflating any of these lifetimes, or else the /// borrowchecker will throw a ton of confusing errors about things not living long /// enough. If you get those kinds of errors, it's probably because you introduced /// something like `&'db self`, which, while convenient, and sometimes works, is imprecise. struct TypeDetailGuard<'a, 'b, 'c, 'db> { inner: &'c mut TypeWriter<'a, 'b, 'db>, start: Option<TextSize>, payload: Option<TypeDetail<'db>>, } impl Drop for TypeDetailGuard<'_, '_, '_, '_> { fn drop(&mut self) { // The fallibility here is primarily retrieving `TypeWriter::Details` // everything else is ideally-never-fails pedantry (yay for pedantry!) if let TypeWriter::Details(details) = &mut self.inner && let Some(start) = self.start && let Some(payload) = self.payload.take() { let target = TextRange::new(start, details.label.text_len()); details.targets.push(target); details.details.push(payload); } } } impl<'a, 'b, 'db> std::ops::Deref for TypeDetailGuard<'a, 'b, '_, 'db> { type Target = TypeWriter<'a, 'b, 'db>; fn deref(&self) -> &Self::Target { self.inner } } impl std::ops::DerefMut for TypeDetailGuard<'_, '_, '_, '_> { fn deref_mut(&mut self) -> &mut Self::Target { self.inner } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum QualificationLevel { ModuleName, FileAndLineNumber, } impl QualificationLevel { const fn from_ambiguity_state(state: &AmbiguityState) -> Option<Self> { match state { AmbiguityState::Unambiguous(_) => None, AmbiguityState::RequiresFullyQualifiedName { .. } => Some(Self::ModuleName), AmbiguityState::RequiresFileAndLineNumber => Some(Self::FileAndLineNumber), } } } #[derive(Debug, Default)] struct AmbiguousClassCollector<'db> { visited_types: RefCell<FxHashSet<Type<'db>>>, class_names: RefCell<FxHashMap<&'db str, AmbiguityState<'db>>>, } impl<'db> AmbiguousClassCollector<'db> { fn record_class(&self, db: &'db dyn Db, class: ClassLiteral<'db>) { match self.class_names.borrow_mut().entry(class.name(db)) { Entry::Vacant(entry) => { entry.insert(AmbiguityState::Unambiguous(class)); } Entry::Occupied(mut entry) => { let value = entry.get_mut(); match value { AmbiguityState::Unambiguous(existing) => { if *existing != class { let qualified_name_components = class.qualified_name(db).components_excluding_self(); if existing.qualified_name(db).components_excluding_self() == qualified_name_components { *value = AmbiguityState::RequiresFileAndLineNumber; } else { *value = AmbiguityState::RequiresFullyQualifiedName { class, qualified_name_components, }; } } } AmbiguityState::RequiresFullyQualifiedName { class: existing, qualified_name_components, } => { if *existing != class { let new_components = class.qualified_name(db).components_excluding_self(); if *qualified_name_components == new_components { *value = AmbiguityState::RequiresFileAndLineNumber; } } } AmbiguityState::RequiresFileAndLineNumber => {} } } } } } /// Whether or not a class can be unambiguously identified by its *unqualified* name /// given the other types that are present in the same context. #[derive(Debug, Clone, PartialEq, Eq)] enum AmbiguityState<'db> { /// The class can be displayed unambiguously using its unqualified name Unambiguous(ClassLiteral<'db>), /// The class must be displayed using its fully qualified name to avoid ambiguity. RequiresFullyQualifiedName { class: ClassLiteral<'db>, qualified_name_components: Vec<String>, }, /// Even the class's fully qualified name is not sufficient; /// we must also include the file and line number. RequiresFileAndLineNumber, } impl<'db> TypeVisitor<'db> for AmbiguousClassCollector<'db> { fn should_visit_lazy_type_attributes(&self) -> bool { false } fn visit_type(&self, db: &'db dyn Db, ty: Type<'db>) { match ty { Type::ClassLiteral(class) => self.record_class(db, class), Type::EnumLiteral(literal) => self.record_class(db, literal.enum_class(db)), Type::GenericAlias(alias) => self.record_class(db, alias.origin(db)), // Visit the class (as if it were a nominal-instance type) // rather than the protocol members, if it is a class-based protocol. // (For the purposes of displaying the type, we'll use the class name.) Type::ProtocolInstance(ProtocolInstanceType { inner: Protocol::FromClass(class), .. }) => return self.visit_type(db, Type::from(class)), // no need to recurse into TypeVar bounds/constraints Type::TypeVar(_) => return, _ => {} } if let visitor::TypeKind::NonAtomic(t) = visitor::TypeKind::from(ty) { if !self.visited_types.borrow_mut().insert(ty) { // If we have already seen this type, we can skip it. return; } visitor::walk_non_atomic_type(db, t, self); } } } impl<'db> Type<'db> { pub fn display(self, db: &'db dyn Db) -> DisplayType<'db> { DisplayType { ty: self, settings: DisplaySettings::from_possibly_ambiguous_types(db, [self]), db, } } pub fn display_with(self, db: &'db dyn Db, settings: DisplaySettings<'db>) -> DisplayType<'db> { DisplayType { ty: self, db, settings, } } fn representation( self, db: &'db dyn Db, settings: DisplaySettings<'db>, ) -> DisplayRepresentation<'db> { DisplayRepresentation { db, ty: self, settings, } } } pub struct DisplayType<'db> { ty: Type<'db>, db: &'db dyn Db, settings: DisplaySettings<'db>, } impl<'db> DisplayType<'db> { pub fn to_string_parts(&self) -> TypeDisplayDetails<'db> { let mut f = TypeWriter::Details(TypeDetailsWriter::new()); self.fmt_detailed(&mut f).unwrap(); match f { TypeWriter::Details(details) => details.finish_type_details(), TypeWriter::Formatter(_) => unreachable!("Expected Details variant"), } } } impl<'db> FmtDetailed<'db> for DisplayType<'db> { fn fmt_detailed(&self, f: &mut TypeWriter<'_, '_, 'db>) -> fmt::Result { let representation = self.ty.representation(self.db, self.settings.clone()); match self.ty { Type::IntLiteral(_) | Type::BooleanLiteral(_) | Type::StringLiteral(_) | Type::BytesLiteral(_) | Type::EnumLiteral(_) => { f.with_type(Type::SpecialForm(SpecialFormType::Literal)) .write_str("Literal")?; f.write_char('[')?; representation.fmt_detailed(f)?; f.write_str("]") } _ => representation.fmt_detailed(f), } } } impl Display for DisplayType<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_detailed(&mut TypeWriter::Formatter(f)) } } impl fmt::Debug for DisplayType<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(self, f) } } impl<'db> ClassLiteral<'db> { fn display_with(self, db: &'db dyn Db, settings: DisplaySettings<'db>) -> ClassDisplay<'db> { ClassDisplay { db, class: self, settings, } } } struct ClassDisplay<'db> { db: &'db dyn Db, class: ClassLiteral<'db>, settings: DisplaySettings<'db>, } impl<'db> FmtDetailed<'db> for ClassDisplay<'db> { fn fmt_detailed(&self, f: &mut TypeWriter<'_, '_, 'db>) -> fmt::Result { let qualification_level = self.settings.qualified.get(&**self.class.name(self.db)); let ty = Type::ClassLiteral(self.class); if qualification_level.is_some() { write!(f.with_type(ty), "{}", self.class.qualified_name(self.db))?; } else { write!(f.with_type(ty), "{}", self.class.name(self.db))?; } if qualification_level == Some(&QualificationLevel::FileAndLineNumber) { let file = self.class.file(self.db); let path = file.path(self.db); let path = match path { FilePath::System(path) => Cow::Owned(FilePath::System( path.strip_prefix(self.db.system().current_directory()) .unwrap_or(path) .to_path_buf(), )), FilePath::Vendored(_) | FilePath::SystemVirtual(_) => Cow::Borrowed(path), }; let line_index = line_index(self.db, file); let class_offset = self.class.header_range(self.db).start(); let line_number = line_index.line_index(class_offset); f.set_invalid_type_annotation(); write!(f, " @ {path}:{line_number}")?; } Ok(()) } } impl Display for ClassDisplay<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_detailed(&mut TypeWriter::Formatter(f)) } } /// Helper for displaying `TypeGuardLike` types `TypeIs` and `TypeGuard`. fn fmt_type_guard_like<'db, T: TypeGuardLike<'db>>( db: &'db dyn Db, guard: T, settings: &DisplaySettings<'db>, f: &mut TypeWriter<'_, '_, 'db>, ) -> fmt::Result { f.with_type(Type::SpecialForm(T::special_form())) .write_str(T::FORM_NAME)?; f.write_char('[')?; guard .return_type(db) .display_with(db, settings.singleline()) .fmt_detailed(f)?; if let Some(name) = guard.place_name(db) { f.set_invalid_type_annotation(); f.write_str(" @ ")?; f.write_str(&name)?; } f.write_str("]") } /// Writes the string representation of a type, which is the value displayed either as /// `Literal[<repr>]` or `Literal[<repr1>, <repr2>]` for literal types or as `<repr>` for /// non literals struct DisplayRepresentation<'db> { ty: Type<'db>, db: &'db dyn Db, settings: DisplaySettings<'db>, } impl Display for DisplayRepresentation<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_detailed(&mut TypeWriter::Formatter(f)) } } impl<'db> FmtDetailed<'db> for DisplayRepresentation<'db> { fn fmt_detailed(&self, f: &mut TypeWriter<'_, '_, 'db>) -> fmt::Result { match self.ty { Type::Dynamic(dynamic) => { if dynamic.is_todo() { f.set_invalid_type_annotation(); } write!(f.with_type(self.ty), "{dynamic}") } Type::Never => f.with_type(self.ty).write_str("Never"), Type::NominalInstance(instance) => { let class = instance.class(self.db); match (class, class.known(self.db)) { (_, Some(KnownClass::NoneType)) => f.with_type(self.ty).write_str("None"), (_, Some(KnownClass::NoDefaultType)) => f.with_type(self.ty).write_str("NoDefault"), (ClassType::Generic(alias), Some(KnownClass::Tuple)) => alias .specialization(self.db) .tuple(self.db) .expect("Specialization::tuple() should always return `Some()` for `KnownClass::Tuple`") .display_with(self.db, self.settings.clone()) .fmt_detailed(f), (ClassType::NonGeneric(class), _) => { class.display_with(self.db, self.settings.clone()).fmt_detailed(f) }, (ClassType::Generic(alias), _) => alias.display_with(self.db, self.settings.clone()).fmt_detailed(f), } } Type::ProtocolInstance(protocol) => match protocol.inner { Protocol::FromClass(class) => match *class { ClassType::NonGeneric(class) => class .display_with(self.db, self.settings.clone()) .fmt_detailed(f), ClassType::Generic(alias) => alias .display_with(self.db, self.settings.clone()) .fmt_detailed(f), }, Protocol::Synthesized(synthetic) => { f.set_invalid_type_annotation(); f.write_char('<')?; f.with_type(Type::SpecialForm(SpecialFormType::Protocol)) .write_str("Protocol")?; f.write_str(" with members ")?; let interface = synthetic.interface(); let member_list = interface.members(self.db); let num_members = member_list.len(); for (i, member) in member_list.enumerate() { let is_last = i == num_members - 1; write!(f, "'{}'", member.name())?; if !is_last { f.write_str(", ")?; } } f.write_char('>') } }, Type::PropertyInstance(_) => f.with_type(self.ty).write_str("property"), Type::ModuleLiteral(module) => { f.set_invalid_type_annotation(); f.write_char('<')?; f.with_type(KnownClass::ModuleType.to_class_literal(self.db)) .write_str("module")?; f.write_str(" '")?; f.with_type(self.ty) .write_str(module.module(self.db).name(self.db))?; f.write_str("'>") } Type::ClassLiteral(class) => { f.set_invalid_type_annotation(); let mut f = f.with_type(self.ty); f.write_str("<class '")?; class .display_with(self.db, self.settings.clone()) .fmt_detailed(&mut f)?; f.write_str("'>") } Type::GenericAlias(generic) => { f.set_invalid_type_annotation(); let mut f = f.with_type(self.ty); f.write_str("<class '")?; generic .display_with(self.db, self.settings.clone()) .fmt_detailed(&mut f)?; f.write_str("'>") } Type::SubclassOf(subclass_of_ty) => match subclass_of_ty.subclass_of() { SubclassOfInner::Class(ClassType::NonGeneric(class)) => { f.with_type(KnownClass::Type.to_class_literal(self.db)) .write_str("type")?; f.write_char('[')?; class .display_with(self.db, self.settings.clone()) .fmt_detailed(f)?; f.write_char(']') } SubclassOfInner::Class(ClassType::Generic(alias)) => { f.with_type(KnownClass::Type.to_class_literal(self.db)) .write_str("type")?; f.write_char('[')?; alias .display_with(self.db, self.settings.clone()) .fmt_detailed(f)?; f.write_char(']') } SubclassOfInner::Dynamic(dynamic) => { f.with_type(KnownClass::Type.to_class_literal(self.db)) .write_str("type")?; f.write_char('[')?; write!(f.with_type(Type::Dynamic(dynamic)), "{dynamic}")?; f.write_char(']') } SubclassOfInner::TypeVar(bound_typevar) => { f.set_invalid_type_annotation(); f.with_type(KnownClass::Type.to_class_literal(self.db)) .write_str("type")?; f.write_char('[')?; write!( f.with_type(Type::TypeVar(bound_typevar)), "{}", bound_typevar.identity(self.db).display(self.db) )?; f.write_char(']') } }, Type::SpecialForm(special_form) => { f.set_invalid_type_annotation(); write!(f.with_type(self.ty), "<special-form '{special_form}'>") } Type::KnownInstance(known_instance) => known_instance .display_with(self.db, self.settings.clone()) .fmt_detailed(f), Type::FunctionLiteral(function) => function .display_with(self.db, self.settings.clone()) .fmt_detailed(f), Type::Callable(callable) => callable .display_with(self.db, self.settings.clone()) .fmt_detailed(f), Type::BoundMethod(bound_method) => { let function = bound_method.function(self.db); let self_ty = bound_method.self_instance(self.db); let typing_self_ty = bound_method.typing_self_type(self.db); match function.signature(self.db).overloads.as_slice() { [signature] => { let type_parameters = DisplayOptionalGenericContext { generic_context: signature.generic_context.as_ref(), db: self.db, settings: self.settings.clone(), }; f.set_invalid_type_annotation(); f.write_str("bound method ")?; self_ty .display_with(self.db, self.settings.singleline()) .fmt_detailed(f)?; f.write_char('.')?; f.with_type(self.ty).write_str(function.name(self.db))?; type_parameters.fmt_detailed(f)?; signature .bind_self(self.db, Some(typing_self_ty)) .display_with(self.db, self.settings.disallow_signature_name()) .fmt_detailed(f) } signatures => { // TODO: How to display overloads? if !self.settings.multiline { // TODO: This should ideally have a TypeDetail but we actually // don't have a type for @overload (we just detect the decorator) f.write_str("Overload")?; f.write_char('[')?; } let separator = if self.settings.multiline { "\n" } else { ", " }; let mut join = f.join(separator); for signature in signatures { join.entry( &signature .bind_self(self.db, Some(typing_self_ty)) .display_with(self.db, self.settings.clone()), ); } join.finish()?; if !self.settings.multiline { f.write_str("]")?; } Ok(()) } } } Type::KnownBoundMethod(method_type) => { f.set_invalid_type_annotation(); let (cls, member_name, cls_name, ty, ty_name) = match method_type { KnownBoundMethodType::FunctionTypeDunderGet(function) => ( KnownClass::FunctionType, "__get__", "function", Type::FunctionLiteral(function), Some(&**function.name(self.db)), ), KnownBoundMethodType::FunctionTypeDunderCall(function) => ( KnownClass::FunctionType, "__call__", "function", Type::FunctionLiteral(function), Some(&**function.name(self.db)), ), KnownBoundMethodType::PropertyDunderGet(property) => ( KnownClass::Property, "__get__", "property", Type::PropertyInstance(property), property .getter(self.db) .and_then(Type::as_function_literal) .map(|getter| &**getter.name(self.db)), ), KnownBoundMethodType::PropertyDunderSet(property) => ( KnownClass::Property, "__set__", "property", Type::PropertyInstance(property), property .getter(self.db) .and_then(Type::as_function_literal) .map(|getter| &**getter.name(self.db)), ), KnownBoundMethodType::StrStartswith(literal) => ( KnownClass::Property, "startswith", "string", Type::StringLiteral(literal), Some(literal.value(self.db)), ), KnownBoundMethodType::ConstraintSetRange => { return f.write_str("bound method `ConstraintSet.range`"); } KnownBoundMethodType::ConstraintSetAlways => { return f.write_str("bound method `ConstraintSet.always`"); } KnownBoundMethodType::ConstraintSetNever => { return f.write_str("bound method `ConstraintSet.never`"); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/tuple.rs
crates/ty_python_semantic/src/types/tuple.rs
//! Types describing fixed- and variable-length tuples. //! //! At runtime, a Python tuple is a fixed-length immutable list of values. There is no restriction //! on the types of the elements of a tuple value. In the type system, we want to model both //! "heterogeneous" tuples that have elements of a fixed sequence of specific types, and //! "homogeneous" tuples that have an unknown number of elements of the same single type. And in //! fact, we want to model tuples that are a combination of the two ("mixed" tuples), with a //! heterogeneous prefix and/or suffix, and a homogeneous portion of unknown length in between //! those. //! //! The description of which elements can appear in a `tuple` is called a [`TupleSpec`]. Other //! things besides `tuple` instances can be described by a tuple spec — for instance, the targets //! of an unpacking assignment. A `tuple` specialization that includes `Never` as one of its //! fixed-length elements cannot be instantiated. We reduce the entire `tuple` type down to //! `Never`. The same is not true of tuple specs in general. (That means that it is [`TupleType`] //! that adds that "collapse `Never`" behavior, whereas [`TupleSpec`] allows you to add any element //! types, including `Never`.) use std::cmp::Ordering; use std::hash::Hash; use itertools::{Either, EitherOrBoth, Itertools}; use smallvec::{SmallVec, smallvec_inline}; use crate::semantic_index::definition::Definition; use crate::subscript::{Nth, OutOfBoundsError, PyIndex, PySlice, StepSizeZeroError}; use crate::types::builder::RecursivelyDefined; use crate::types::class::{ClassType, KnownClass}; use crate::types::constraints::{ConstraintSet, IteratorConstraintsExtension}; use crate::types::generics::InferableTypeVars; use crate::types::{ ApplyTypeMappingVisitor, BoundTypeVarInstance, FindLegacyTypeVarsVisitor, HasRelationToVisitor, IntersectionType, IsDisjointVisitor, IsEquivalentVisitor, NormalizedVisitor, Type, TypeMapping, TypeRelation, UnionBuilder, UnionType, }; use crate::types::{Truthiness, TypeContext}; use crate::{Db, FxOrderSet, Program}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum TupleLength { Fixed(usize), Variable(usize, usize), } impl TupleLength { pub(crate) const fn unknown() -> TupleLength { TupleLength::Variable(0, 0) } pub(crate) const fn is_variable(self) -> bool { matches!(self, TupleLength::Variable(_, _)) } /// Returns the minimum and maximum length of this tuple. (The maximum length will be `None` /// for a tuple with a variable-length portion.) pub(crate) fn size_hint(self) -> (usize, Option<usize>) { match self { TupleLength::Fixed(len) => (len, Some(len)), TupleLength::Variable(prefix, suffix) => (prefix + suffix, None), } } /// Returns the minimum length of this tuple. pub(crate) fn minimum(self) -> usize { match self { TupleLength::Fixed(len) => len, TupleLength::Variable(prefix, suffix) => prefix + suffix, } } /// Returns the maximum length of this tuple, if any. pub(crate) fn maximum(self) -> Option<usize> { match self { TupleLength::Fixed(len) => Some(len), TupleLength::Variable(_, _) => None, } } /// Given two [`TupleLength`]s, return the more precise instance, /// if it makes sense to consider one more precise than the other. pub(crate) fn most_precise(self, other: Self) -> Option<Self> { match (self, other) { // A fixed-length tuple is equally as precise as another fixed-length tuple if they // have the same length. For two differently sized fixed-length tuples, however, // neither tuple length is more precise than the other: the two tuple lengths are // entirely disjoint. (TupleLength::Fixed(left), TupleLength::Fixed(right)) => { (left == right).then_some(self) } // A fixed-length tuple is more precise than a variable-length one. (fixed @ TupleLength::Fixed(_), TupleLength::Variable(..)) | (TupleLength::Variable(..), fixed @ TupleLength::Fixed(_)) => Some(fixed), // For two variable-length tuples, the tuple with the larger number // of required items is more precise. (TupleLength::Variable(..), TupleLength::Variable(..)) => { Some(match self.minimum().cmp(&other.minimum()) { Ordering::Less => other, Ordering::Equal | Ordering::Greater => self, }) } } } pub(crate) fn display_minimum(self) -> String { let minimum_length = self.minimum(); match self { TupleLength::Fixed(_) => minimum_length.to_string(), TupleLength::Variable(_, _) => format!("at least {minimum_length}"), } } pub(crate) fn display_maximum(self) -> String { match self.maximum() { Some(maximum) => maximum.to_string(), None => "unlimited".to_string(), } } pub(crate) fn into_fixed_length(self) -> Option<usize> { match self { TupleLength::Fixed(len) => Some(len), TupleLength::Variable(_, _) => None, } } } /// # Ordering /// Ordering is based on the tuple's salsa-assigned id and not on its elements. /// The id may change between runs, or when the tuple was garbage collected and recreated. #[salsa::interned(debug, constructor=new_internal, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub struct TupleType<'db> { #[returns(ref)] pub(crate) tuple: TupleSpec<'db>, } pub(super) fn walk_tuple_type<'db, V: super::visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, tuple: TupleType<'db>, visitor: &V, ) { for element in tuple.tuple(db).iter_all_elements() { visitor.visit_type(db, element); } } // The Salsa heap is tracked separately. impl get_size2::GetSize for TupleType<'_> {} #[salsa::tracked] impl<'db> TupleType<'db> { pub(crate) fn new(db: &'db dyn Db, spec: &TupleSpec<'db>) -> Option<Self> { // If a fixed-length (i.e., mandatory) element of the tuple is `Never`, then it's not // possible to instantiate the tuple as a whole. if spec.fixed_elements().any(Type::is_never) { return None; } // If the variable-length portion is Never, it can only be instantiated with zero elements. // That means this isn't a variable-length tuple after all! if let TupleSpec::Variable(tuple) = spec { if tuple.variable().is_never() { let tuple = TupleSpec::Fixed(FixedLengthTuple::from_elements( tuple .iter_prefix_elements() .chain(tuple.iter_suffix_elements()), )); return Some(TupleType::new_internal::<_, TupleSpec<'db>>(db, tuple)); } } Some(TupleType::new_internal(db, spec)) } pub(crate) fn empty(db: &'db dyn Db) -> Self { TupleType::new_internal(db, TupleSpec::from(FixedLengthTuple::empty())) } pub(crate) fn heterogeneous( db: &'db dyn Db, types: impl IntoIterator<Item = Type<'db>>, ) -> Option<Self> { TupleType::new(db, &TupleSpec::heterogeneous(types)) } #[cfg(test)] pub(crate) fn mixed( db: &'db dyn Db, prefix: impl IntoIterator<Item = Type<'db>>, variable: Type<'db>, suffix: impl IntoIterator<Item = Type<'db>>, ) -> Option<Self> { TupleType::new(db, &VariableLengthTuple::mixed(prefix, variable, suffix)) } pub(crate) fn homogeneous(db: &'db dyn Db, element: Type<'db>) -> Self { match element { Type::Never => TupleType::empty(db), _ => TupleType::new_internal(db, TupleSpec::homogeneous(element)), } } // N.B. If this method is not Salsa-tracked, we take 10 minutes to check // `static-frame` as part of a mypy_primer run! This is because it's called // from `NominalInstanceType::class()`, which is a very hot method. #[salsa::tracked(cycle_initial=to_class_type_cycle_initial, heap_size=ruff_memory_usage::heap_size)] pub(crate) fn to_class_type(self, db: &'db dyn Db) -> ClassType<'db> { let tuple_class = KnownClass::Tuple .try_to_class_literal(db) .expect("Typeshed should always have a `tuple` class in `builtins.pyi`"); tuple_class.apply_specialization(db, |generic_context| { if generic_context.variables(db).len() == 1 { let element_type = self.tuple(db).homogeneous_element_type(db); generic_context.specialize_tuple(db, element_type, self) } else { generic_context.default_specialization(db, Some(KnownClass::Tuple)) } }) } /// Return a normalized version of `self`. /// /// See [`Type::normalized`] for more details. #[must_use] pub(crate) fn normalized_impl( self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>, ) -> Option<Self> { TupleType::new(db, &self.tuple(db).normalized_impl(db, visitor)) } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self::new_internal( db, self.tuple(db) .recursive_type_normalized_impl(db, div, nested)?, )) } pub(crate) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Option<Self> { TupleType::new( db, &self .tuple(db) .apply_type_mapping_impl(db, type_mapping, tcx, visitor), ) } pub(crate) fn find_legacy_typevars_impl( self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { self.tuple(db) .find_legacy_typevars_impl(db, binding_context, typevars, visitor); } pub(crate) fn has_relation_to_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { self.tuple(db).has_relation_to_impl( db, other.tuple(db), inferable, relation, relation_visitor, disjointness_visitor, ) } pub(crate) fn is_disjoint_from_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, disjointness_visitor: &IsDisjointVisitor<'db>, relation_visitor: &HasRelationToVisitor<'db>, ) -> ConstraintSet<'db> { self.tuple(db).is_disjoint_from_impl( db, other.tuple(db), inferable, disjointness_visitor, relation_visitor, ) } pub(crate) fn is_equivalent_to_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, visitor: &IsEquivalentVisitor<'db>, ) -> ConstraintSet<'db> { self.tuple(db) .is_equivalent_to_impl(db, other.tuple(db), inferable, visitor) } pub(crate) fn is_single_valued(self, db: &'db dyn Db) -> bool { self.tuple(db).is_single_valued(db) } } fn to_class_type_cycle_initial<'db>( db: &'db dyn Db, id: salsa::Id, self_: TupleType<'db>, ) -> ClassType<'db> { let tuple_class = KnownClass::Tuple .try_to_class_literal(db) .expect("Typeshed should always have a `tuple` class in `builtins.pyi`"); tuple_class.apply_specialization(db, |generic_context| { if generic_context.variables(db).len() == 1 { generic_context.specialize_tuple(db, Type::divergent(id), self_) } else { generic_context.default_specialization(db, Some(KnownClass::Tuple)) } }) } /// A tuple spec describes the contents of a tuple type, which might be fixed- or variable-length. /// /// Tuple specs are used for more than just `tuple` instances, so they allow `Never` to appear as a /// fixed-length element type. [`TupleType`] adds that additional invariant (since a tuple that /// must contain an element that can't be instantiated, can't be instantiated itself). pub(crate) type TupleSpec<'db> = Tuple<Type<'db>>; /// A fixed-length tuple. /// /// Our tuple representation can hold instances of any Rust type. For tuples containing Python /// types, use [`TupleSpec`], which defines some additional type-specific methods. #[derive(Clone, Debug, Eq, Hash, PartialEq, get_size2::GetSize, salsa::Update)] pub struct FixedLengthTuple<T>(Box<[T]>); impl<T> FixedLengthTuple<T> { fn empty() -> Self { Self(Box::default()) } fn from_elements(elements: impl IntoIterator<Item = T>) -> Self { Self(elements.into_iter().collect()) } pub(crate) fn elements_slice(&self) -> &[T] { &self.0 } pub(crate) fn owned_elements(self) -> Box<[T]> { self.0 } pub(crate) fn all_elements(&self) -> &[T] { &self.0 } pub(crate) fn iter_all_elements(&self) -> impl DoubleEndedIterator<Item = T> where T: Copy, { self.0.iter().copied() } pub(crate) fn into_all_elements_with_kind(self) -> impl Iterator<Item = TupleElement<T>> { self.0.into_iter().map(TupleElement::Fixed) } /// Returns the length of this tuple. pub(crate) fn len(&self) -> usize { self.0.len() } } impl<'db> FixedLengthTuple<Type<'db>> { fn resize( &self, db: &'db dyn Db, new_length: TupleLength, ) -> Result<Tuple<Type<'db>>, ResizeTupleError> { match new_length { TupleLength::Fixed(new_length) => match self.len().cmp(&new_length) { Ordering::Less => Err(ResizeTupleError::TooFewValues), Ordering::Greater => Err(ResizeTupleError::TooManyValues), Ordering::Equal => Ok(Tuple::Fixed(self.clone())), }, TupleLength::Variable(prefix, suffix) => { // The number of rhs values that will be consumed by the starred target. let Some(variable) = self.len().checked_sub(prefix + suffix) else { return Err(ResizeTupleError::TooFewValues); }; // Extract rhs values into the prefix, then into the starred target, then into the // suffix. let mut elements = self.iter_all_elements(); let prefix: Vec<_> = elements.by_ref().take(prefix).collect(); let variable = UnionType::from_elements_leave_aliases(db, elements.by_ref().take(variable)); let suffix = elements.by_ref().take(suffix); Ok(VariableLengthTuple::mixed(prefix, variable, suffix)) } } } #[must_use] fn normalized_impl(&self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { Self::from_elements(self.0.iter().map(|ty| ty.normalized_impl(db, visitor))) } fn recursive_type_normalized_impl( &self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { if nested { Some(Self::from_elements( self.0 .iter() .map(|ty| ty.recursive_type_normalized_impl(db, div, true)) .collect::<Option<Box<[_]>>>()?, )) } else { Some(Self::from_elements( self.0 .iter() .map(|ty| { ty.recursive_type_normalized_impl(db, div, true) .unwrap_or(div) }) .collect::<Box<[_]>>(), )) } } fn apply_type_mapping_impl<'a>( &self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { let tcx_tuple = tcx .annotation .and_then(|annotation| annotation.known_specialization(db, KnownClass::Tuple)) .and_then(|specialization| { specialization .tuple(db) .expect("the specialization of `KnownClass::Tuple` must have a tuple spec") .resize(db, TupleLength::Fixed(self.0.len())) .ok() }); let tcx_elements = match tcx_tuple.as_ref() { None => Either::Right(std::iter::repeat(TypeContext::default())), Some(tuple) => Either::Left( tuple .iter_all_elements() .map(|tcx| TypeContext::new(Some(tcx))), ), }; Self::from_elements( self.0 .iter() .zip(tcx_elements) .map(|(ty, tcx)| ty.apply_type_mapping_impl(db, type_mapping, tcx, visitor)), ) } fn find_legacy_typevars_impl( &self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { for ty in &self.0 { ty.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } } fn has_relation_to_impl( &self, db: &'db dyn Db, other: &Tuple<Type<'db>>, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { match other { Tuple::Fixed(other) => { ConstraintSet::from(self.0.len() == other.0.len()).and(db, || { (self.0.iter().zip(&other.0)).when_all(db, |(self_ty, other_ty)| { self_ty.has_relation_to_impl( db, *other_ty, inferable, relation, relation_visitor, disjointness_visitor, ) }) }) } Tuple::Variable(other) => { // This tuple must have enough elements to match up with the other tuple's prefix // and suffix, and each of those elements must pairwise satisfy the relation. let mut result = ConstraintSet::from(true); let mut self_iter = self.0.iter(); for other_ty in other.prefix_elements() { let Some(self_ty) = self_iter.next() else { return ConstraintSet::from(false); }; let element_constraints = self_ty.has_relation_to_impl( db, *other_ty, inferable, relation, relation_visitor, disjointness_visitor, ); if result .intersect(db, element_constraints) .is_never_satisfied(db) { return result; } } for other_ty in other.iter_suffix_elements().rev() { let Some(self_ty) = self_iter.next_back() else { return ConstraintSet::from(false); }; let element_constraints = self_ty.has_relation_to_impl( db, other_ty, inferable, relation, relation_visitor, disjointness_visitor, ); if result .intersect(db, element_constraints) .is_never_satisfied(db) { return result; } } // In addition, any remaining elements in this tuple must satisfy the // variable-length portion of the other tuple. result.and(db, || { self_iter.when_all(db, |self_ty| { self_ty.has_relation_to_impl( db, other.variable(), inferable, relation, relation_visitor, disjointness_visitor, ) }) }) } } } fn is_equivalent_to_impl( &self, db: &'db dyn Db, other: &Self, inferable: InferableTypeVars<'_, 'db>, visitor: &IsEquivalentVisitor<'db>, ) -> ConstraintSet<'db> { ConstraintSet::from(self.0.len() == other.0.len()).and(db, || { (self.0.iter()) .zip(&other.0) .when_all(db, |(self_ty, other_ty)| { self_ty.is_equivalent_to_impl(db, *other_ty, inferable, visitor) }) }) } fn is_single_valued(&self, db: &'db dyn Db) -> bool { self.0.iter().all(|ty| ty.is_single_valued(db)) } } impl<'db> PyIndex<'db> for &FixedLengthTuple<Type<'db>> { type Item = Type<'db>; fn py_index(self, db: &'db dyn Db, index: i32) -> Result<Self::Item, OutOfBoundsError> { self.0.py_index(db, index).copied() } } impl<'db> PySlice<'db> for FixedLengthTuple<Type<'db>> { type Item = Type<'db>; fn py_slice( &self, db: &'db dyn Db, start: Option<i32>, stop: Option<i32>, step: Option<i32>, ) -> Result<impl Iterator<Item = Self::Item>, StepSizeZeroError> { self.0.py_slice(db, start, stop, step) } } /// A variable-length tuple. /// /// The tuple can contain a fixed-length heterogeneous prefix and/or suffix. All of the elements of /// the variable-length portion must be the same. /// /// Our tuple representation can hold instances of any Rust type. For tuples containing Python /// types, use [`TupleSpec`], which defines some additional type-specific methods. #[derive(Clone, Debug, Eq, Hash, PartialEq, get_size2::GetSize, salsa::Update)] pub struct VariableLengthTuple<T> { pub(crate) elements: smallvec::SmallVec<[T; 1]>, variable_index: usize, } impl<T> VariableLengthTuple<T> { /// Creates a new tuple spec containing zero or more elements of a given type, with no prefix /// or suffix. const fn homogeneous(ty: T) -> Self { let elements = smallvec_inline![ty]; Self { elements, variable_index: 0, } } fn mixed( prefix: impl IntoIterator<Item = T>, variable: T, suffix: impl IntoIterator<Item = T>, ) -> Tuple<T> { Tuple::Variable(Self::new(prefix, variable, suffix)) } fn try_new<P, S>(prefix: P, variable: T, suffix: S) -> Option<Self> where P: IntoIterator<Item = Option<T>>, P::IntoIter: ExactSizeIterator, S: IntoIterator<Item = Option<T>>, S::IntoIter: ExactSizeIterator, { let prefix = prefix.into_iter(); let suffix = suffix.into_iter(); let mut elements = SmallVec::with_capacity(prefix.len().saturating_add(suffix.len()).saturating_add(1)); for element in prefix { elements.push(element?); } let variable_index = elements.len(); elements.push(variable); for element in suffix { elements.push(element?); } elements.shrink_to_fit(); Some(Self { elements, variable_index, }) } fn new( prefix: impl IntoIterator<Item = T>, variable: T, suffix: impl IntoIterator<Item = T>, ) -> Self { let mut elements = SmallVec::new_const(); elements.extend(prefix); let variable_index = elements.len(); elements.push(variable); elements.extend(suffix); elements.shrink_to_fit(); Self { elements, variable_index, } } fn new_from_vec(prefix: Vec<T>, variable: T, suffix: Vec<T>) -> Self { let mut elements = SmallVec::from_vec(prefix); let variable_index = elements.len(); elements.push(variable); elements.extend(suffix); elements.shrink_to_fit(); Self { elements, variable_index, } } pub(crate) fn variable(&self) -> T where T: Copy, { self.elements[self.variable_index] } pub(crate) fn variable_element(&self) -> &T { &self.elements[self.variable_index] } pub(crate) fn variable_element_mut(&mut self) -> &mut T { &mut self.elements[self.variable_index] } pub(crate) fn prefix_elements(&self) -> &[T] { &self.elements[..self.variable_index] } pub(crate) fn iter_prefix_elements(&self) -> impl DoubleEndedIterator<Item = T> where T: Copy, { self.prefix_elements().iter().copied() } pub(crate) fn prefix_elements_mut(&mut self) -> &mut [T] { &mut self.elements[..self.variable_index] } pub(crate) fn suffix_elements(&self) -> &[T] { &self.elements[self.suffix_offset()..] } pub(crate) fn iter_suffix_elements(&self) -> impl DoubleEndedIterator<Item = T> where T: Copy, { self.suffix_elements().iter().copied() } pub(crate) fn suffix_elements_mut(&mut self) -> &mut [T] { let suffix_offset = self.suffix_offset(); &mut self.elements[suffix_offset..] } fn suffix_offset(&self) -> usize { self.variable_index + 1 } fn fixed_elements(&self) -> impl Iterator<Item = &T> + '_ { self.prefix_elements().iter().chain(self.suffix_elements()) } fn all_elements(&self) -> &[T] { &self.elements } fn into_all_elements_with_kind(self) -> impl Iterator<Item = TupleElement<T>> { self.elements .into_iter() .enumerate() .map(move |(i, element)| match i.cmp(&self.variable_index) { Ordering::Less => TupleElement::Prefix(element), Ordering::Equal => TupleElement::Variable(element), Ordering::Greater => TupleElement::Suffix(element), }) } fn prefix_len(&self) -> usize { self.variable_index } fn suffix_len(&self) -> usize { self.elements.len() - self.suffix_offset() } fn len(&self) -> TupleLength { TupleLength::Variable(self.prefix_len(), self.suffix_len()) } } impl<'db> VariableLengthTuple<Type<'db>> { /// Returns the prefix of the prenormalization of this tuple. /// /// This is used in our subtyping and equivalence checks below to handle different tuple types /// that represent the same set of runtime tuple values. For instance, the following two tuple /// types both represent "a tuple of one or more `int`s": /// /// ```py /// tuple[int, *tuple[int, ...]] /// tuple[*tuple[int, ...], int] /// ``` /// /// Prenormalization rewrites both types into the former form. We arbitrarily prefer the /// elements to appear in the prefix if they can, so we move elements from the beginning of the /// suffix, which are equivalent to the variable-length portion, to the end of the prefix. /// /// Complicating matters is that we don't always want to compare with _this_ tuple's /// variable-length portion. (When this tuple's variable-length portion is gradual — /// `tuple[Any, ...]` — we compare with the assumption that the `Any` materializes to the other /// tuple's variable-length portion.) fn prenormalized_prefix_elements<'a>( &'a self, db: &'db dyn Db, variable: Option<Type<'db>>, ) -> impl Iterator<Item = Type<'db>> + 'a { let variable = variable.unwrap_or(self.variable()); self.iter_prefix_elements().chain( self.iter_suffix_elements() .take_while(move |element| element.is_equivalent_to(db, variable)), ) } /// Returns the suffix of the prenormalization of this tuple. /// /// This is used in our subtyping and equivalence checks below to handle different tuple types /// that represent the same set of runtime tuple values. For instance, the following two tuple /// types both represent "a tuple of one or more `int`s": /// /// ```py /// tuple[int, *tuple[int, ...]] /// tuple[*tuple[int, ...], int] /// ``` /// /// Prenormalization rewrites both types into the former form. We arbitrarily prefer the /// elements to appear in the prefix if they can, so we move elements from the beginning of the /// suffix, which are equivalent to the variable-length portion, to the end of the prefix. /// /// Complicating matters is that we don't always want to compare with _this_ tuple's /// variable-length portion. (When this tuple's variable-length portion is gradual — /// `tuple[Any, ...]` — we compare with the assumption that the `Any` materializes to the other /// tuple's variable-length portion.) fn prenormalized_suffix_elements<'a>( &'a self, db: &'db dyn Db, variable: Option<Type<'db>>, ) -> impl Iterator<Item = Type<'db>> + 'a { let variable = variable.unwrap_or(self.variable()); self.iter_suffix_elements() .skip_while(move |element| element.is_equivalent_to(db, variable)) } fn resize( &self, db: &'db dyn Db, new_length: TupleLength, ) -> Result<Tuple<Type<'db>>, ResizeTupleError> { match new_length { TupleLength::Fixed(new_length) => { // The number of elements that will get their value from our variable-length // portion. let Some(variable_count) = new_length.checked_sub(self.len().minimum()) else { return Err(ResizeTupleError::TooManyValues); }; Ok(Tuple::Fixed(FixedLengthTuple::from_elements( (self.iter_prefix_elements()) .chain(std::iter::repeat_n(self.variable(), variable_count)) .chain(self.iter_suffix_elements()), ))) } TupleLength::Variable(prefix_length, suffix_length) => { // "Overflow" are elements of our prefix/suffix that will be folded into the // result's variable-length portion. "Underflow" are elements of the result // prefix/suffix that will come from our variable-length portion. let self_prefix_length = self.prefix_elements().len(); let prefix_underflow = prefix_length.saturating_sub(self_prefix_length); let self_suffix_length = self.suffix_elements().len(); let suffix_overflow = self_suffix_length.saturating_sub(suffix_length); let suffix_underflow = suffix_length.saturating_sub(self_suffix_length); let prefix = (self.iter_prefix_elements().take(prefix_length)) .chain(std::iter::repeat_n(self.variable(), prefix_underflow)); let variable = UnionType::from_elements_leave_aliases( db, self.iter_prefix_elements() .skip(prefix_length) .chain(std::iter::once(self.variable())) .chain(self.iter_suffix_elements().take(suffix_overflow)), );
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/special_form.rs
crates/ty_python_semantic/src/types/special_form.rs
//! An enumeration of special forms in the Python type system. //! Each of these is considered to inhabit a unique type in our model of the type system. use super::{ClassType, Type, class::KnownClass}; use crate::db::Db; use crate::semantic_index::place::ScopedPlaceId; use crate::semantic_index::{FileScopeId, place_table, use_def_map}; use crate::types::TypeDefinition; use ruff_db::files::File; use std::str::FromStr; use ty_module_resolver::{KnownModule, file_to_module, resolve_module_confident}; /// Enumeration of specific runtime symbols that are special enough /// that they can each be considered to inhabit a unique type. /// /// # Ordering /// /// Ordering is stable and should be the same between runs. #[derive( Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Update, PartialOrd, Ord, strum_macros::EnumString, get_size2::GetSize, )] pub enum SpecialFormType { Any, /// The symbol `typing.Annotated` (which can also be found as `typing_extensions.Annotated`) Annotated, /// The symbol `typing.Literal` (which can also be found as `typing_extensions.Literal`) Literal, /// The symbol `typing.LiteralString` (which can also be found as `typing_extensions.LiteralString`) LiteralString, /// The symbol `typing.Optional` (which can also be found as `typing_extensions.Optional`) Optional, /// The symbol `typing.Union` (which can also be found as `typing_extensions.Union`) Union, /// The symbol `typing.NoReturn` (which can also be found as `typing_extensions.NoReturn`) NoReturn, /// The symbol `typing.Never` available since 3.11 (which can also be found as `typing_extensions.Never`) Never, /// The symbol `typing.Tuple` (which can also be found as `typing_extensions.Tuple`) Tuple, /// The symbol `typing.List` (which can also be found as `typing_extensions.List`) List, /// The symbol `typing.Dict` (which can also be found as `typing_extensions.Dict`) Dict, /// The symbol `typing.Set` (which can also be found as `typing_extensions.Set`) Set, /// The symbol `typing.FrozenSet` (which can also be found as `typing_extensions.FrozenSet`) FrozenSet, /// The symbol `typing.ChainMap` (which can also be found as `typing_extensions.ChainMap`) ChainMap, /// The symbol `typing.Counter` (which can also be found as `typing_extensions.Counter`) Counter, /// The symbol `typing.DefaultDict` (which can also be found as `typing_extensions.DefaultDict`) DefaultDict, /// The symbol `typing.Deque` (which can also be found as `typing_extensions.Deque`) Deque, /// The symbol `typing.OrderedDict` (which can also be found as `typing_extensions.OrderedDict`) OrderedDict, /// The symbol `typing.Type` (which can also be found as `typing_extensions.Type`) Type, /// The symbol `ty_extensions.Unknown` Unknown, /// The symbol `ty_extensions.AlwaysTruthy` AlwaysTruthy, /// The symbol `ty_extensions.AlwaysFalsy` AlwaysFalsy, /// The symbol `ty_extensions.Not` Not, /// The symbol `ty_extensions.Intersection` Intersection, /// The symbol `ty_extensions.TypeOf` TypeOf, /// The symbol `ty_extensions.CallableTypeOf` CallableTypeOf, /// The symbol `ty_extensions.Top` Top, /// The symbol `ty_extensions.Bottom` Bottom, /// The symbol `typing.Callable` /// (which can also be found as `typing_extensions.Callable` or as `collections.abc.Callable`) Callable, /// The symbol `typing.Self` (which can also be found as `typing_extensions.Self`) #[strum(serialize = "Self")] TypingSelf, /// The symbol `typing.Final` (which can also be found as `typing_extensions.Final`) Final, /// The symbol `typing.ClassVar` (which can also be found as `typing_extensions.ClassVar`) ClassVar, /// The symbol `typing.Concatenate` (which can also be found as `typing_extensions.Concatenate`) Concatenate, /// The symbol `typing.Unpack` (which can also be found as `typing_extensions.Unpack`) Unpack, /// The symbol `typing.Required` (which can also be found as `typing_extensions.Required`) Required, /// The symbol `typing.NotRequired` (which can also be found as `typing_extensions.NotRequired`) NotRequired, /// The symbol `typing.TypeAlias` (which can also be found as `typing_extensions.TypeAlias`) TypeAlias, /// The symbol `typing.TypeGuard` (which can also be found as `typing_extensions.TypeGuard`) TypeGuard, /// The symbol `typing.TypedDict` (which can also be found as `typing_extensions.TypedDict`) TypedDict, /// The symbol `typing.TypeIs` (which can also be found as `typing_extensions.TypeIs`) TypeIs, /// The symbol `typing.ReadOnly` (which can also be found as `typing_extensions.ReadOnly`) ReadOnly, /// The symbol `typing.Protocol` (which can also be found as `typing_extensions.Protocol`) /// /// Note that instances of subscripted `typing.Protocol` are not represented by this type; /// see also [`super::KnownInstanceType::SubscriptedProtocol`]. Protocol, /// The symbol `typing.Generic` (which can also be found as `typing_extensions.Generic`). /// /// Note that instances of subscripted `typing.Generic` are not represented by this type; /// see also [`super::KnownInstanceType::SubscriptedGeneric`]. Generic, /// The symbol `typing.NamedTuple` (which can also be found as `typing_extensions.NamedTuple`). /// Typeshed defines this symbol as a class, but this isn't accurate: it's actually a factory function /// at runtime. We therefore represent it as a special form internally. NamedTuple, } impl SpecialFormType { /// Return the [`KnownClass`] which this symbol is an instance of pub(crate) const fn class(self) -> KnownClass { match self { Self::Annotated | Self::Literal | Self::LiteralString | Self::Optional | Self::Union | Self::NoReturn | Self::Never | Self::Tuple | Self::Type | Self::TypingSelf | Self::Final | Self::ClassVar | Self::Callable | Self::Concatenate | Self::Unpack | Self::Required | Self::NotRequired | Self::TypeAlias | Self::TypeGuard | Self::TypedDict | Self::TypeIs | Self::TypeOf | Self::Not | Self::Top | Self::Bottom | Self::Intersection | Self::CallableTypeOf | Self::ReadOnly => KnownClass::SpecialForm, // Typeshed says it's an instance of `_SpecialForm`, // but then we wouldn't recognise things like `issubclass(`X, Protocol)` // as being valid. Self::Protocol => KnownClass::ProtocolMeta, Self::Generic | Self::Any => KnownClass::Type, Self::List | Self::Dict | Self::DefaultDict | Self::Set | Self::FrozenSet | Self::Counter | Self::Deque | Self::ChainMap | Self::OrderedDict => KnownClass::StdlibAlias, Self::Unknown | Self::AlwaysTruthy | Self::AlwaysFalsy => KnownClass::Object, Self::NamedTuple => KnownClass::FunctionType, } } /// Return the instance type which this type is a subtype of. /// /// For example, the symbol `typing.Literal` is an instance of `typing._SpecialForm`, /// so `SpecialFormType::Literal.instance_fallback(db)` /// returns `Type::NominalInstance(NominalInstanceType { class: <typing._SpecialForm> })`. pub(super) fn instance_fallback(self, db: &dyn Db) -> Type<'_> { self.class().to_instance(db) } /// Return `true` if this symbol is an instance of `class`. pub(super) fn is_instance_of(self, db: &dyn Db, class: ClassType) -> bool { self.class().is_subclass_of(db, class) } pub(super) fn try_from_file_and_name( db: &dyn Db, file: File, symbol_name: &str, ) -> Option<Self> { let candidate = Self::from_str(symbol_name).ok()?; candidate .check_module(file_to_module(db, file)?.known(db)?) .then_some(candidate) } /// Return `true` if `module` is a module from which this `SpecialFormType` variant can validly originate. /// /// Most variants can only exist in one module, which is the same as `self.class().canonical_module(db)`. /// Some variants could validly be defined in either `typing` or `typing_extensions`, however. pub(super) fn check_module(self, module: KnownModule) -> bool { match self { Self::ClassVar | Self::Deque | Self::List | Self::Dict | Self::DefaultDict | Self::Set | Self::FrozenSet | Self::Counter | Self::ChainMap | Self::OrderedDict | Self::Optional | Self::Union | Self::NoReturn | Self::Tuple | Self::Type | Self::Generic | Self::Callable => module.is_typing(), Self::Annotated | Self::Literal | Self::LiteralString | Self::Never | Self::Final | Self::Concatenate | Self::Unpack | Self::Required | Self::NotRequired | Self::TypeAlias | Self::TypeGuard | Self::TypedDict | Self::TypeIs | Self::TypingSelf | Self::Protocol | Self::NamedTuple | Self::Any | Self::ReadOnly => { matches!(module, KnownModule::Typing | KnownModule::TypingExtensions) } Self::Unknown | Self::AlwaysTruthy | Self::AlwaysFalsy | Self::Not | Self::Top | Self::Bottom | Self::Intersection | Self::TypeOf | Self::CallableTypeOf => module.is_ty_extensions(), } } pub(super) fn to_meta_type(self, db: &dyn Db) -> Type<'_> { self.class().to_class_literal(db) } /// Return true if this special form is callable at runtime. /// Most special forms are not callable (they are type constructors that are subscripted), /// but some like `TypedDict` and collection constructors can be called. pub(super) const fn is_callable(self) -> bool { match self { // TypedDict can be called as a constructor to create TypedDict types Self::TypedDict // Collection constructors are callable // TODO actually implement support for calling them | Self::ChainMap | Self::Counter | Self::DefaultDict | Self::Deque | Self::NamedTuple | Self::OrderedDict => true, // All other special forms are not callable Self::Annotated | Self::Literal | Self::LiteralString | Self::Optional | Self::Union | Self::NoReturn | Self::Never | Self::Tuple | Self::List | Self::Dict | Self::Set | Self::FrozenSet | Self::Type | Self::Unknown | Self::AlwaysTruthy | Self::AlwaysFalsy | Self::Not | Self::Top | Self::Bottom | Self::Intersection | Self::TypeOf | Self::CallableTypeOf | Self::Callable | Self::TypingSelf | Self::Final | Self::ClassVar | Self::Concatenate | Self::Unpack | Self::Required | Self::NotRequired | Self::TypeAlias | Self::TypeGuard | Self::TypeIs | Self::ReadOnly | Self::Protocol | Self::Any | Self::Generic => false, } } /// Return `Some(KnownClass)` if this special form is an alias /// to a standard library class. pub(super) const fn aliased_stdlib_class(self) -> Option<KnownClass> { match self { Self::List => Some(KnownClass::List), Self::Dict => Some(KnownClass::Dict), Self::Set => Some(KnownClass::Set), Self::FrozenSet => Some(KnownClass::FrozenSet), Self::ChainMap => Some(KnownClass::ChainMap), Self::Counter => Some(KnownClass::Counter), Self::DefaultDict => Some(KnownClass::DefaultDict), Self::Deque => Some(KnownClass::Deque), Self::OrderedDict => Some(KnownClass::OrderedDict), Self::Tuple => Some(KnownClass::Tuple), Self::Type => Some(KnownClass::Type), Self::AlwaysFalsy | Self::AlwaysTruthy | Self::Annotated | Self::Bottom | Self::CallableTypeOf | Self::ClassVar | Self::Concatenate | Self::Final | Self::Intersection | Self::Literal | Self::LiteralString | Self::Never | Self::NoReturn | Self::Not | Self::ReadOnly | Self::Required | Self::TypeAlias | Self::TypeGuard | Self::NamedTuple | Self::NotRequired | Self::Optional | Self::Top | Self::TypeIs | Self::TypedDict | Self::TypingSelf | Self::Union | Self::Unknown | Self::TypeOf | Self::Any // `typing.Callable` is an alias to `collections.abc.Callable`, // but they're both the same `SpecialFormType` in our model, // and neither is a class in typeshed (even though the `collections.abc` one is at runtime) | Self::Callable | Self::Protocol | Self::Generic | Self::Unpack => None, } } /// Return `true` if this special form is valid as the second argument /// to `issubclass()` and `isinstance()` calls. pub(super) const fn is_valid_isinstance_target(self) -> bool { match self { Self::Callable | Self::ChainMap | Self::Counter | Self::DefaultDict | Self::Deque | Self::FrozenSet | Self::Dict | Self::List | Self::OrderedDict | Self::Set | Self::Tuple | Self::Type | Self::Protocol | Self::Generic => true, Self::AlwaysFalsy | Self::AlwaysTruthy | Self::Annotated | Self::Bottom | Self::CallableTypeOf | Self::ClassVar | Self::Concatenate | Self::Final | Self::Intersection | Self::Literal | Self::LiteralString | Self::Never | Self::NoReturn | Self::Not | Self::ReadOnly | Self::Required | Self::TypeAlias | Self::TypeGuard | Self::NamedTuple | Self::NotRequired | Self::Optional | Self::Top | Self::TypeIs | Self::TypedDict | Self::TypingSelf | Self::Union | Self::Unknown | Self::TypeOf | Self::Any // can be used in `issubclass()` but not `isinstance()`. | Self::Unpack => false, } } /// Return the name of the symbol at runtime pub(super) const fn name(self) -> &'static str { match self { SpecialFormType::Any => "Any", SpecialFormType::Annotated => "Annotated", SpecialFormType::Literal => "Literal", SpecialFormType::LiteralString => "LiteralString", SpecialFormType::Optional => "Optional", SpecialFormType::Union => "Union", SpecialFormType::NoReturn => "NoReturn", SpecialFormType::Never => "Never", SpecialFormType::Tuple => "Tuple", SpecialFormType::Type => "Type", SpecialFormType::TypingSelf => "Self", SpecialFormType::Final => "Final", SpecialFormType::ClassVar => "ClassVar", SpecialFormType::Callable => "Callable", SpecialFormType::Concatenate => "Concatenate", SpecialFormType::Unpack => "Unpack", SpecialFormType::Required => "Required", SpecialFormType::NotRequired => "NotRequired", SpecialFormType::TypeAlias => "TypeAlias", SpecialFormType::TypeGuard => "TypeGuard", SpecialFormType::TypedDict => "TypedDict", SpecialFormType::TypeIs => "TypeIs", SpecialFormType::List => "List", SpecialFormType::Dict => "Dict", SpecialFormType::DefaultDict => "DefaultDict", SpecialFormType::Set => "Set", SpecialFormType::FrozenSet => "FrozenSet", SpecialFormType::Counter => "Counter", SpecialFormType::Deque => "Deque", SpecialFormType::ChainMap => "ChainMap", SpecialFormType::OrderedDict => "OrderedDict", SpecialFormType::ReadOnly => "ReadOnly", SpecialFormType::Unknown => "Unknown", SpecialFormType::AlwaysTruthy => "AlwaysTruthy", SpecialFormType::AlwaysFalsy => "AlwaysFalsy", SpecialFormType::Not => "Not", SpecialFormType::Intersection => "Intersection", SpecialFormType::TypeOf => "TypeOf", SpecialFormType::CallableTypeOf => "CallableTypeOf", SpecialFormType::Top => "Top", SpecialFormType::Bottom => "Bottom", SpecialFormType::Protocol => "Protocol", SpecialFormType::Generic => "Generic", SpecialFormType::NamedTuple => "NamedTuple", } } /// Return the module(s) in which this special form could be defined fn definition_modules(self) -> &'static [KnownModule] { match self { SpecialFormType::Any | SpecialFormType::Annotated | SpecialFormType::Literal | SpecialFormType::LiteralString | SpecialFormType::Optional | SpecialFormType::Union | SpecialFormType::NoReturn | SpecialFormType::Never | SpecialFormType::Tuple | SpecialFormType::Type | SpecialFormType::TypingSelf | SpecialFormType::Final | SpecialFormType::ClassVar | SpecialFormType::Callable | SpecialFormType::Concatenate | SpecialFormType::Unpack | SpecialFormType::Required | SpecialFormType::NotRequired | SpecialFormType::TypeAlias | SpecialFormType::TypeGuard | SpecialFormType::TypedDict | SpecialFormType::TypeIs | SpecialFormType::ReadOnly | SpecialFormType::Protocol | SpecialFormType::Generic | SpecialFormType::NamedTuple | SpecialFormType::List | SpecialFormType::Dict | SpecialFormType::DefaultDict | SpecialFormType::Set | SpecialFormType::FrozenSet | SpecialFormType::Counter | SpecialFormType::Deque | SpecialFormType::ChainMap | SpecialFormType::OrderedDict => &[KnownModule::Typing, KnownModule::TypingExtensions], SpecialFormType::Unknown | SpecialFormType::AlwaysTruthy | SpecialFormType::AlwaysFalsy | SpecialFormType::Not | SpecialFormType::Intersection | SpecialFormType::TypeOf | SpecialFormType::CallableTypeOf | SpecialFormType::Top | SpecialFormType::Bottom => &[KnownModule::TyExtensions], } } pub(super) fn definition(self, db: &dyn Db) -> Option<TypeDefinition<'_>> { self.definition_modules() .iter() .find_map(|module| { let file = resolve_module_confident(db, &module.name())?.file(db)?; let scope = FileScopeId::global().to_scope_id(db, file); let symbol_id = place_table(db, scope).symbol_id(self.name())?; use_def_map(db, scope) .end_of_scope_bindings(ScopedPlaceId::Symbol(symbol_id)) .next()? .binding .definition() }) .map(TypeDefinition::SpecialForm) } } impl std::fmt::Display for SpecialFormType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}.{}", self.definition_modules()[0].as_str(), self.name() ) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/variance.rs
crates/ty_python_semantic/src/types/variance.rs
use crate::{Db, types::BoundTypeVarInstance}; #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub enum TypeVarVariance { Invariant, Covariant, Contravariant, Bivariant, } impl TypeVarVariance { pub const fn bottom() -> Self { TypeVarVariance::Bivariant } pub const fn top() -> Self { TypeVarVariance::Invariant } // supremum #[must_use] pub(crate) const fn join(self, other: Self) -> Self { use TypeVarVariance::{Bivariant, Contravariant, Covariant, Invariant}; match (self, other) { (Invariant, _) | (_, Invariant) => Invariant, (Covariant, Covariant) => Covariant, (Contravariant, Contravariant) => Contravariant, (Covariant, Contravariant) | (Contravariant, Covariant) => Invariant, (Bivariant, other) | (other, Bivariant) => other, } } /// Compose two variances: useful for combining use-site and definition-site variances, e.g. /// `C[D[T]]` or function argument/return position variances. /// /// `other` is a thunk to avoid unnecessary computation when `self` is `Bivariant`. /// /// Based on the variance composition/transformation operator in /// <https://people.cs.umass.edu/~yannis/variance-extended2011.pdf>, page 5 /// /// While their operation would have `compose(Invariant, Bivariant) == /// Invariant`, we instead have it evaluate to `Bivariant`. This is a valid /// choice, as discussed on that same page, where type equality is semantic /// rather than syntactic. To see that this holds for our setting consider /// the type /// ```python /// type ConstantInt[T] = int /// ``` /// We would say `ConstantInt[str]` = `ConstantInt[float]`, so we qualify as /// using semantic equivalence. #[must_use] pub(crate) fn compose(self, other: Self) -> Self { self.compose_thunk(|| other) } /// Like `compose`, but takes `other` as a thunk to avoid unnecessary /// computation when `self` is `Bivariant`. #[must_use] pub(crate) fn compose_thunk<F>(self, other: F) -> Self where F: FnOnce() -> Self, { match self { TypeVarVariance::Covariant => other(), TypeVarVariance::Contravariant => other().flip(), TypeVarVariance::Bivariant => TypeVarVariance::Bivariant, TypeVarVariance::Invariant => { if TypeVarVariance::Bivariant == other() { TypeVarVariance::Bivariant } else { TypeVarVariance::Invariant } } } } /// Flips the polarity of the variance. /// /// Covariant becomes contravariant, contravariant becomes covariant, others remain unchanged. pub(crate) const fn flip(self) -> Self { match self { TypeVarVariance::Invariant => TypeVarVariance::Invariant, TypeVarVariance::Covariant => TypeVarVariance::Contravariant, TypeVarVariance::Contravariant => TypeVarVariance::Covariant, TypeVarVariance::Bivariant => TypeVarVariance::Bivariant, } } pub(crate) const fn is_covariant(self) -> bool { matches!( self, TypeVarVariance::Covariant | TypeVarVariance::Bivariant ) } } impl std::iter::FromIterator<Self> for TypeVarVariance { fn from_iter<T: IntoIterator<Item = Self>>(iter: T) -> Self { use std::ops::ControlFlow; // TODO: use `into_value` when control_flow_into_value is stable let (ControlFlow::Break(variance) | ControlFlow::Continue(variance)) = iter .into_iter() .try_fold(TypeVarVariance::Bivariant, |acc, variance| { let supremum = acc.join(variance); match supremum { // short circuit at top TypeVarVariance::Invariant => ControlFlow::Break(supremum), TypeVarVariance::Bivariant | TypeVarVariance::Covariant | TypeVarVariance::Contravariant => ControlFlow::Continue(supremum), } }); variance } } pub(crate) trait VarianceInferable<'db>: Sized { /// The variance of `typevar` in `self` /// /// Generally, one will implement this by traversing any types within `self` /// in which `typevar` could occur, and calling `variance_of` recursively on /// them. /// /// Sometimes the recursive calls will be in positions where you need to /// specify a non-covariant polarity. See `with_polarity` for more details. fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance; /// Creates a `VarianceInferable` that applies `polarity` (see /// `TypeVarVariance::compose`) to the result of variance inference on the /// underlying value. /// /// In some cases, we need to apply a polarity to the recursive call. /// You can do this with `ty.with_polarity(polarity).variance_of(typevar)`. /// Generally, this will be whenever the type occurs in argument-position, /// in which case you will want `TypeVarVariance::Contravariant`, or /// `TypeVarVariance::Invariant` if the value(s) being annotated is known to /// be mutable, such as `T` in `list[T]`. See the [typing spec][typing-spec] /// for more details. /// /// [typing-spec]: https://typing.python.org/en/latest/spec/generics.html#variance fn with_polarity(self, polarity: TypeVarVariance) -> impl VarianceInferable<'db> { WithPolarity { variance_inferable: self, polarity, } } } pub(crate) struct WithPolarity<T> { variance_inferable: T, polarity: TypeVarVariance, } impl<'db, T> VarianceInferable<'db> for WithPolarity<T> where T: VarianceInferable<'db>, { fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance { let WithPolarity { variance_inferable, polarity, } = self; polarity.compose_thunk(|| variance_inferable.variance_of(db, typevar)) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/property_tests.rs
crates/ty_python_semantic/src/types/property_tests.rs
//! This module contains quickcheck-based property tests for `Type`s. //! //! These tests are disabled by default, as they are non-deterministic and slow. You can //! run them explicitly using: //! //! ```sh //! cargo test -p ty_python_semantic -- --ignored types::property_tests::stable //! ``` //! //! The number of tests (default: 100) can be controlled by setting the `QUICKCHECK_TESTS` //! environment variable. For example: //! //! ```sh //! QUICKCHECK_TESTS=10000 cargo test … //! ``` //! //! If you want to run these tests for a longer period of time, it's advisable to run them //! in release mode. As some tests are slower than others, it's advisable to run them in a //! loop until they fail: //! //! ```sh //! export QUICKCHECK_TESTS=100000 //! while cargo test --release -p ty_python_semantic -- \ //! --ignored types::property_tests::stable; do :; done //! ``` mod setup; mod type_generation; use type_generation::{intersection, union}; /// A macro to define a property test for types. /// /// The `$test_name` identifier specifies the name of the test function. The `$db` identifier /// is used to refer to the salsa database in the property to be tested. The actual property is /// specified using the syntax: /// /// forall types t1, t2, ..., tn . <property>` /// /// where `t1`, `t2`, ..., `tn` are identifiers that represent arbitrary types, and `<property>` /// is an expression using these identifiers. macro_rules! type_property_test { ($test_name:ident, $db:ident, forall types $($types:ident),+ . $property:expr) => { #[quickcheck_macros::quickcheck] #[ignore] fn $test_name($($types: crate::types::property_tests::type_generation::Ty),+) -> bool { let $db = &crate::types::property_tests::setup::get_cached_db(); $(let $types = $types.into_type($db);)+ let result = $property; if !result { println!("\nFailing types were:"); $(println!("{}", $types.display($db));)+ } result } }; ($test_name:ident, $db:ident, forall fully_static_types $($types:ident),+ . $property:expr) => { #[quickcheck_macros::quickcheck] #[ignore] fn $test_name($($types: crate::types::property_tests::type_generation::FullyStaticTy),+) -> bool { let $db = &crate::types::property_tests::setup::get_cached_db(); $(let $types = $types.into_type($db);)+ let result = $property; if !result { println!("\nFailing types were:"); $(println!("{}", $types.display($db));)+ } result } }; // A property test with a logical implication. ($name:ident, $db:ident, forall $typekind:ident $($types:ident),+ . $premise:expr => $conclusion:expr) => { type_property_test!($name, $db, forall $typekind $($types),+ . !($premise) || ($conclusion)); }; } mod stable { use super::union; use crate::types::{CallableType, KnownClass, Type}; // Reflexivity: `T` is equivalent to itself. type_property_test!( equivalent_to_is_reflexive, db, forall types t. t.is_equivalent_to(db, t) ); // Symmetry: If `S` is equivalent to `T`, then `T` must be equivalent to `S`. type_property_test!( equivalent_to_is_symmetric, db, forall types s, t. s.is_equivalent_to(db, t) => t.is_equivalent_to(db, s) ); // Transitivity: If `S` is equivalent to `T` and `T` is equivalent to `U`, then `S` must be equivalent to `U`. type_property_test!( equivalent_to_is_transitive, db, forall types s, t, u. s.is_equivalent_to(db, t) && t.is_equivalent_to(db, u) => s.is_equivalent_to(db, u) ); // `S <: T` and `T <: U` implies that `S <: U`. type_property_test!( subtype_of_is_transitive, db, forall types s, t, u. s.is_subtype_of(db, t) && t.is_subtype_of(db, u) => s.is_subtype_of(db, u) ); // `S <: T` and `T <: S` implies that `S` is equivalent to `T`. type_property_test!( subtype_of_is_antisymmetric, db, forall types s, t. s.is_subtype_of(db, t) && t.is_subtype_of(db, s) => s.is_equivalent_to(db, t) ); // `T` is not disjoint from itself, unless `T` is `Never`. type_property_test!( disjoint_from_is_irreflexive, db, forall types t. t.is_disjoint_from(db, t) => t.is_never() ); // `S` is disjoint from `T` implies that `T` is disjoint from `S`. type_property_test!( disjoint_from_is_symmetric, db, forall types s, t. s.is_disjoint_from(db, t) == t.is_disjoint_from(db, s) ); // `S <: T` implies that `S` is not disjoint from `T`, unless `S` is `Never`. type_property_test!( subtype_of_implies_not_disjoint_from, db, forall types s, t. s.is_subtype_of(db, t) => !s.is_disjoint_from(db, t) || s.is_never() ); // `S <: T` implies that `S` can be assigned to `T`. type_property_test!( subtype_of_implies_assignable_to, db, forall types s, t. s.is_subtype_of(db, t) => s.is_assignable_to(db, t) ); // If `T` is a singleton, it is also single-valued. type_property_test!( singleton_implies_single_valued, db, forall types t. t.is_singleton(db) => t.is_single_valued(db) ); // All types should be assignable to `object` type_property_test!( all_types_assignable_to_object, db, forall types t. t.is_assignable_to(db, Type::object()) ); // And all types should be subtypes of `object` type_property_test!( all_types_subtype_of_object, db, forall types t. t.is_subtype_of(db, Type::object()) ); // Never should be assignable to every type type_property_test!( never_assignable_to_every_type, db, forall types t. Type::Never.is_assignable_to(db, t) ); // And it should be a subtype of all types type_property_test!( never_subtype_of_every_type, db, forall types t. Type::Never.is_subtype_of(db, t) ); // Similar to `Never`, a "bottom" callable type should be a subtype of all callable types type_property_test!( bottom_callable_is_subtype_of_all_callable, db, forall types t. t.is_callable_type() => Type::Callable(CallableType::bottom(db)).is_subtype_of(db, t) ); // `T` can be assigned to itself. type_property_test!( assignable_to_is_reflexive, db, forall types t. t.is_assignable_to(db, t) ); // For *any* pair of types, each of the pair should be assignable to the union of the two. type_property_test!( all_type_pairs_are_assignable_to_their_union, db, forall types s, t. s.is_assignable_to(db, union(db, [s, t])) && t.is_assignable_to(db, union(db, [s, t])) ); // Only `Never` is a subtype of `Any`. type_property_test!( only_never_is_subtype_of_any, db, forall types s. !s.is_equivalent_to(db, Type::Never) => !s.is_subtype_of(db, Type::any()) ); // Only `object` is a supertype of `Any`. type_property_test!( only_object_is_supertype_of_any, db, forall types t. !t.is_equivalent_to(db, Type::object()) => !Type::any().is_subtype_of(db, t) ); // Equivalence is commutative. type_property_test!( equivalent_to_is_commutative, db, forall types s, t. s.is_equivalent_to(db, t) == t.is_equivalent_to(db, s) ); // A fully static type `T` is a subtype of itself. (This is not true for non-fully-static // types; `Any` is not a subtype of `Any`, only `Never` is.) type_property_test!( subtype_of_is_reflexive_for_fully_static_types, db, forall fully_static_types t. t.is_subtype_of(db, t) ); // For any two fully static types, each type in the pair must be a subtype of their union. // (This is clearly not true for non-fully-static types, since their subtyping is not // reflexive.) type_property_test!( all_fully_static_type_pairs_are_subtype_of_their_union, db, forall fully_static_types s, t. s.is_subtype_of(db, union(db, [s, t])) && t.is_subtype_of(db, union(db, [s, t])) ); // Any type assignable to `Iterable[object]` should be considered iterable. // // Note that the inverse is not true, due to the fact that we recognize the old-style // iteration protocol as well as the new-style iteration protocol: not all objects that // we consider iterable are assignable to `Iterable[object]`. // // Note also that (like other property tests in this module), // this invariant will only hold true for Liskov-compliant types assignable to `Iterable`. // Since protocols can participate in nominal assignability/subtyping as well as // structural assignability/subtyping, it is possible to construct types that a type // checker must consider to be subtypes of `Iterable` even though they are not in fact // iterable (as long as the user `type: ignore`s any type-checker errors stemming from // the Liskov violation). All you need to do is to create a class that subclasses // `Iterable` but assigns `__iter__ = None` in the class body (or similar). type_property_test!( all_type_assignable_to_iterable_are_iterable, db, forall types t. t.is_assignable_to(db, KnownClass::Iterable.to_specialized_instance(db, [Type::object()])) => t.try_iterate(db).is_ok() ); } /// This module contains property tests that currently lead to many false positives. /// /// The reason for this is our insufficient understanding of equivalence of types. For /// example, we currently consider `int | str` and `str | int` to be different types. /// Similar issues exist for intersection types. Once this is resolved, we can move these /// tests to the `stable` section. In the meantime, it can still be useful to run these /// tests (using [`types::property_tests::flaky`]), to see if there are any new obvious bugs. mod flaky { use itertools::Itertools; use super::{intersection, union}; // Negating `T` twice is equivalent to `T`. type_property_test!( double_negation_is_identity, db, forall types t. t.negate(db).negate(db).is_equivalent_to(db, t) ); // For any fully static type `T`, `T` should be disjoint from `~T`. // https://github.com/astral-sh/ty/issues/216 type_property_test!( negation_of_fully_static_types_is_disjoint, db, forall fully_static_types t. t.negate(db).is_disjoint_from(db, t) ); // For two types, their intersection must be a subtype of each type in the pair. type_property_test!( all_type_pairs_are_supertypes_of_their_intersection, db, forall types s, t. intersection(db, [s, t]).is_subtype_of(db, s) && intersection(db, [s, t]).is_subtype_of(db, t) ); // And the intersection of a pair of types // should be assignable to both types of the pair. // Currently fails due to https://github.com/astral-sh/ruff/issues/14899 type_property_test!( all_type_pairs_can_be_assigned_from_their_intersection, db, forall types s, t. intersection(db, [s, t]).is_assignable_to(db, s) && intersection(db, [s, t]).is_assignable_to(db, t) ); // Equal element sets of intersections implies equivalence // flaky at least in part because of https://github.com/astral-sh/ruff/issues/15513 type_property_test!( intersection_equivalence_not_order_dependent, db, forall types s, t, u. [s, t, u] .into_iter() .permutations(3) .map(|trio_of_types| intersection(db, trio_of_types)) .permutations(2) .all(|vec_of_intersections| vec_of_intersections[0].is_equivalent_to(db, vec_of_intersections[1])) ); // Equal element sets of unions implies equivalence // flaky at least in part because of https://github.com/astral-sh/ruff/issues/15513 type_property_test!( union_equivalence_not_order_dependent, db, forall types s, t, u. [s, t, u] .into_iter() .permutations(3) .map(|trio_of_types| union(db, trio_of_types)) .permutations(2) .all(|vec_of_unions| vec_of_unions[0].is_equivalent_to(db, vec_of_unions[1])) ); // `S | T` is always a supertype of `S`. // Thus, `S` is never disjoint from `S | T`. type_property_test!( constituent_members_of_union_is_not_disjoint_from_that_union, db, forall types s, t. !s.is_disjoint_from(db, union(db, [s, t])) && !t.is_disjoint_from(db, union(db, [s, t])) ); // If `S <: T`, then `~T <: ~S`. // // DO NOT STABILISE this test until the mdtests here pass: // https://github.com/astral-sh/ruff/blob/2711e08eb8eb38d1ce323aae0517fede371cba15/crates/ty_python_semantic/resources/mdtest/type_properties/is_subtype_of.md?plain=1#L276-L315 // // This test has flakes relating to those subtyping and simplification tests // (see https://github.com/astral-sh/ruff/issues/16913), but it is hard to // reliably trigger the flakes when running this test manually as the flakes // occur very rarely (even running the test with several million seeds does // not always reliably reproduce the flake). type_property_test!( negation_reverses_subtype_order, db, forall types s, t. s.is_subtype_of(db, t) => t.negate(db).is_subtype_of(db, s.negate(db)) ); // Both the top and bottom materialization tests are flaky in part due to various failures that // it discovers in the current implementation of assignability of the types. // TODO: Create a issue with some example failures to keep track of it // `T'`, the top materialization of `T`, should be assignable to `T`. type_property_test!( top_materialization_of_type_is_assignable_to_type, db, forall types t. t.top_materialization(db).is_assignable_to(db, t) ); // Similarly, `T'`, the bottom materialization of `T`, should also be assignable to `T`. type_property_test!( bottom_materialization_of_type_is_assignable_to_type, db, forall types t. t.bottom_materialization(db).is_assignable_to(db, t) ); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/definition.rs
crates/ty_python_semantic/src/types/definition.rs
use crate::Db; use crate::semantic_index::definition::Definition; use ruff_db::files::FileRange; use ruff_db::parsed::parsed_module; use ruff_db::source::source_text; use ruff_text_size::{TextLen, TextRange}; use ty_module_resolver::Module; #[derive(Debug, PartialEq, Eq, Hash)] pub enum TypeDefinition<'db> { Module(Module<'db>), Class(Definition<'db>), Function(Definition<'db>), TypeVar(Definition<'db>), TypeAlias(Definition<'db>), NewType(Definition<'db>), SpecialForm(Definition<'db>), } impl TypeDefinition<'_> { pub fn focus_range(&self, db: &dyn Db) -> Option<FileRange> { match self { Self::Module(_) => None, Self::Class(definition) | Self::Function(definition) | Self::TypeVar(definition) | Self::TypeAlias(definition) | Self::SpecialForm(definition) | Self::NewType(definition) => { let module = parsed_module(db, definition.file(db)).load(db); Some(definition.focus_range(db, &module)) } } } pub fn full_range(&self, db: &dyn Db) -> Option<FileRange> { match self { Self::Module(module) => { let file = module.file(db)?; let source = source_text(db, file); Some(FileRange::new(file, TextRange::up_to(source.text_len()))) } Self::Class(definition) | Self::Function(definition) | Self::TypeVar(definition) | Self::TypeAlias(definition) | Self::SpecialForm(definition) | Self::NewType(definition) => { let module = parsed_module(db, definition.file(db)).load(db); Some(definition.full_range(db, &module)) } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/type_ordering.rs
crates/ty_python_semantic/src/types/type_ordering.rs
use std::cmp::Ordering; use salsa::plumbing::AsId; use crate::{db::Db, types::bound_super::SuperOwnerKind}; use super::{ DynamicType, TodoType, Type, TypeGuardLike, TypeGuardType, TypeIsType, class_base::ClassBase, subclass_of::SubclassOfInner, }; /// Return an [`Ordering`] that describes the canonical order in which two types should appear /// in an [`crate::types::IntersectionType`] or a [`crate::types::UnionType`] in order for them /// to be compared for equivalence. /// /// Two intersections are compared lexicographically. Element types in the intersection must /// already be sorted. Two unions are never compared in this function because DNF does not permit /// nested unions. /// /// ## Why not just implement [`Ord`] on [`Type`]? /// /// It would be fairly easy to slap `#[derive(PartialOrd, Ord)]` on [`Type`], and the ordering we /// create here is not user-facing. However, it doesn't really "make sense" for `Type` to implement /// [`Ord`] in terms of the semantics. There are many different ways in which you could plausibly /// sort a list of types; this is only one (somewhat arbitrary, at times) possible ordering. pub(super) fn union_or_intersection_elements_ordering<'db>( db: &'db dyn Db, left: &Type<'db>, right: &Type<'db>, ) -> Ordering { debug_assert_eq!( *left, left.normalized(db), "`left` must be normalized before a meaningful ordering can be established" ); debug_assert_eq!( *right, right.normalized(db), "`right` must be normalized before a meaningful ordering can be established" ); if left == right { return Ordering::Equal; } match (left, right) { (Type::Never, _) => Ordering::Less, (_, Type::Never) => Ordering::Greater, (Type::LiteralString, _) => Ordering::Less, (_, Type::LiteralString) => Ordering::Greater, (Type::BooleanLiteral(left), Type::BooleanLiteral(right)) => left.cmp(right), (Type::BooleanLiteral(_), _) => Ordering::Less, (_, Type::BooleanLiteral(_)) => Ordering::Greater, (Type::IntLiteral(left), Type::IntLiteral(right)) => left.cmp(right), (Type::IntLiteral(_), _) => Ordering::Less, (_, Type::IntLiteral(_)) => Ordering::Greater, (Type::StringLiteral(left), Type::StringLiteral(right)) => left.cmp(right), (Type::StringLiteral(_), _) => Ordering::Less, (_, Type::StringLiteral(_)) => Ordering::Greater, (Type::BytesLiteral(left), Type::BytesLiteral(right)) => left.cmp(right), (Type::BytesLiteral(_), _) => Ordering::Less, (_, Type::BytesLiteral(_)) => Ordering::Greater, (Type::EnumLiteral(left), Type::EnumLiteral(right)) => left.cmp(right), (Type::EnumLiteral(_), _) => Ordering::Less, (_, Type::EnumLiteral(_)) => Ordering::Greater, (Type::FunctionLiteral(left), Type::FunctionLiteral(right)) => left.cmp(right), (Type::FunctionLiteral(_), _) => Ordering::Less, (_, Type::FunctionLiteral(_)) => Ordering::Greater, (Type::BoundMethod(left), Type::BoundMethod(right)) => left.cmp(right), (Type::BoundMethod(_), _) => Ordering::Less, (_, Type::BoundMethod(_)) => Ordering::Greater, (Type::KnownBoundMethod(left), Type::KnownBoundMethod(right)) => left.cmp(right), (Type::KnownBoundMethod(_), _) => Ordering::Less, (_, Type::KnownBoundMethod(_)) => Ordering::Greater, (Type::WrapperDescriptor(left), Type::WrapperDescriptor(right)) => left.cmp(right), (Type::WrapperDescriptor(_), _) => Ordering::Less, (_, Type::WrapperDescriptor(_)) => Ordering::Greater, (Type::DataclassDecorator(left), Type::DataclassDecorator(right)) => left.cmp(right), (Type::DataclassDecorator(_), _) => Ordering::Less, (_, Type::DataclassDecorator(_)) => Ordering::Greater, (Type::DataclassTransformer(left), Type::DataclassTransformer(right)) => left.cmp(right), (Type::DataclassTransformer(_), _) => Ordering::Less, (_, Type::DataclassTransformer(_)) => Ordering::Greater, (Type::Callable(left), Type::Callable(right)) => left.cmp(right), (Type::Callable(_), _) => Ordering::Less, (_, Type::Callable(_)) => Ordering::Greater, (Type::ModuleLiteral(left), Type::ModuleLiteral(right)) => left.cmp(right), (Type::ModuleLiteral(_), _) => Ordering::Less, (_, Type::ModuleLiteral(_)) => Ordering::Greater, (Type::ClassLiteral(left), Type::ClassLiteral(right)) => left.cmp(right), (Type::ClassLiteral(_), _) => Ordering::Less, (_, Type::ClassLiteral(_)) => Ordering::Greater, (Type::GenericAlias(left), Type::GenericAlias(right)) => left.cmp(right), (Type::GenericAlias(_), _) => Ordering::Less, (_, Type::GenericAlias(_)) => Ordering::Greater, (Type::SubclassOf(left), Type::SubclassOf(right)) => { match (left.subclass_of(), right.subclass_of()) { (SubclassOfInner::Class(left), SubclassOfInner::Class(right)) => left.cmp(&right), (SubclassOfInner::Class(_), _) => Ordering::Less, (_, SubclassOfInner::Class(_)) => Ordering::Greater, (SubclassOfInner::Dynamic(left), SubclassOfInner::Dynamic(right)) => { dynamic_elements_ordering(left, right) } (SubclassOfInner::TypeVar(left), SubclassOfInner::TypeVar(right)) => { left.as_id().cmp(&right.as_id()) } (SubclassOfInner::TypeVar(_), _) => Ordering::Less, (_, SubclassOfInner::TypeVar(_)) => Ordering::Greater, } } (Type::SubclassOf(_), _) => Ordering::Less, (_, Type::SubclassOf(_)) => Ordering::Greater, (Type::TypeIs(left), Type::TypeIs(right)) => typeis_ordering(db, *left, *right), (Type::TypeIs(_), _) => Ordering::Less, (_, Type::TypeIs(_)) => Ordering::Greater, (Type::TypeGuard(left), Type::TypeGuard(right)) => typeguard_ordering(db, *left, *right), (Type::TypeGuard(_), _) => Ordering::Less, (_, Type::TypeGuard(_)) => Ordering::Greater, (Type::NominalInstance(left), Type::NominalInstance(right)) => { left.class(db).cmp(&right.class(db)) } (Type::NominalInstance(_), _) => Ordering::Less, (_, Type::NominalInstance(_)) => Ordering::Greater, (Type::ProtocolInstance(left_proto), Type::ProtocolInstance(right_proto)) => { left_proto.cmp(right_proto) } (Type::ProtocolInstance(_), _) => Ordering::Less, (_, Type::ProtocolInstance(_)) => Ordering::Greater, // This is one place where we want to compare the typevar identities directly, instead of // falling back on `is_same_typevar_as` or `can_be_bound_for`. (Type::TypeVar(left), Type::TypeVar(right)) => left.as_id().cmp(&right.as_id()), (Type::TypeVar(_), _) => Ordering::Less, (_, Type::TypeVar(_)) => Ordering::Greater, (Type::AlwaysTruthy, _) => Ordering::Less, (_, Type::AlwaysTruthy) => Ordering::Greater, (Type::AlwaysFalsy, _) => Ordering::Less, (_, Type::AlwaysFalsy) => Ordering::Greater, (Type::BoundSuper(left), Type::BoundSuper(right)) => { (match (left.pivot_class(db), right.pivot_class(db)) { (ClassBase::Class(left), ClassBase::Class(right)) => left.cmp(&right), (ClassBase::Class(_), _) => Ordering::Less, (_, ClassBase::Class(_)) => Ordering::Greater, (ClassBase::Protocol, _) => Ordering::Less, (_, ClassBase::Protocol) => Ordering::Greater, (ClassBase::Generic, _) => Ordering::Less, (_, ClassBase::Generic) => Ordering::Greater, (ClassBase::TypedDict, _) => Ordering::Less, (_, ClassBase::TypedDict) => Ordering::Greater, (ClassBase::Dynamic(left), ClassBase::Dynamic(right)) => { dynamic_elements_ordering(left, right) } }) .then_with(|| match (left.owner(db), right.owner(db)) { (SuperOwnerKind::Class(left), SuperOwnerKind::Class(right)) => left.cmp(&right), (SuperOwnerKind::Class(_), _) => Ordering::Less, (_, SuperOwnerKind::Class(_)) => Ordering::Greater, (SuperOwnerKind::Instance(left), SuperOwnerKind::Instance(right)) => { left.class(db).cmp(&right.class(db)) } (SuperOwnerKind::Instance(_), _) => Ordering::Less, (_, SuperOwnerKind::Instance(_)) => Ordering::Greater, (SuperOwnerKind::Dynamic(left), SuperOwnerKind::Dynamic(right)) => { dynamic_elements_ordering(left, right) } }) } (Type::BoundSuper(_), _) => Ordering::Less, (_, Type::BoundSuper(_)) => Ordering::Greater, (Type::SpecialForm(left), Type::SpecialForm(right)) => left.cmp(right), (Type::SpecialForm(_), _) => Ordering::Less, (_, Type::SpecialForm(_)) => Ordering::Greater, (Type::KnownInstance(left), Type::KnownInstance(right)) => left.cmp(right), (Type::KnownInstance(_), _) => Ordering::Less, (_, Type::KnownInstance(_)) => Ordering::Greater, (Type::PropertyInstance(left), Type::PropertyInstance(right)) => left.cmp(right), (Type::PropertyInstance(_), _) => Ordering::Less, (_, Type::PropertyInstance(_)) => Ordering::Greater, (Type::Dynamic(left), Type::Dynamic(right)) => dynamic_elements_ordering(*left, *right), (Type::Dynamic(_), _) => Ordering::Less, (_, Type::Dynamic(_)) => Ordering::Greater, (Type::TypeAlias(left), Type::TypeAlias(right)) => left.cmp(right), (Type::TypeAlias(_), _) => Ordering::Less, (_, Type::TypeAlias(_)) => Ordering::Greater, (Type::TypedDict(left), Type::TypedDict(right)) => { left.defining_class().cmp(&right.defining_class()) } (Type::TypedDict(_), _) => Ordering::Less, (_, Type::TypedDict(_)) => Ordering::Greater, (Type::NewTypeInstance(left), Type::NewTypeInstance(right)) => left.cmp(right), (Type::NewTypeInstance(_), _) => Ordering::Less, (_, Type::NewTypeInstance(_)) => Ordering::Greater, (Type::Union(_), _) | (_, Type::Union(_)) => { unreachable!("our type representation does not permit nested unions"); } (Type::Intersection(left), Type::Intersection(right)) => { // Lexicographically compare the elements of the two unequal intersections. let left_positive = left.positive(db); let right_positive = right.positive(db); if left_positive.len() != right_positive.len() { return left_positive.len().cmp(&right_positive.len()); } let left_negative = left.negative(db); let right_negative = right.negative(db); if left_negative.len() != right_negative.len() { return left_negative.len().cmp(&right_negative.len()); } for (left, right) in left_positive.iter().zip(right_positive) { let ordering = union_or_intersection_elements_ordering(db, left, right); if ordering != Ordering::Equal { return ordering; } } for (left, right) in left_negative.iter().zip(right_negative) { let ordering = union_or_intersection_elements_ordering(db, left, right); if ordering != Ordering::Equal { return ordering; } } unreachable!("Two equal, normalized intersections should share the same Salsa ID") } } } /// Determine a canonical order for two instances of [`DynamicType`]. fn dynamic_elements_ordering(left: DynamicType, right: DynamicType) -> Ordering { match (left, right) { (DynamicType::Any, _) => Ordering::Less, (_, DynamicType::Any) => Ordering::Greater, (DynamicType::Unknown, _) => Ordering::Less, (_, DynamicType::Unknown) => Ordering::Greater, (DynamicType::UnknownGeneric(_), _) => Ordering::Less, (_, DynamicType::UnknownGeneric(_)) => Ordering::Greater, #[cfg(debug_assertions)] (DynamicType::Todo(TodoType(left)), DynamicType::Todo(TodoType(right))) => left.cmp(right), #[cfg(not(debug_assertions))] (DynamicType::Todo(TodoType), DynamicType::Todo(TodoType)) => Ordering::Equal, (DynamicType::TodoUnpack, _) => Ordering::Less, (_, DynamicType::TodoUnpack) => Ordering::Greater, (DynamicType::TodoStarredExpression, _) => Ordering::Less, (_, DynamicType::TodoStarredExpression) => Ordering::Greater, (DynamicType::Divergent(left), DynamicType::Divergent(right)) => left.cmp(&right), (DynamicType::Divergent(_), _) => Ordering::Less, (_, DynamicType::Divergent(_)) => Ordering::Greater, } } /// Generic helper for ordering type guard-like types. /// /// The following criteria are considered, in order: /// * Boundness: Unbound precedes bound /// * Symbol name: String comparison /// * Guarded type: [`union_or_intersection_elements_ordering`] fn guard_like_ordering<'db, T: TypeGuardLike<'db>>(db: &'db dyn Db, left: T, right: T) -> Ordering { let (left_ty, right_ty) = (left.return_type(db), right.return_type(db)); match (left.place_info(db), right.place_info(db)) { (None, Some(_)) => Ordering::Less, (Some(_), None) => Ordering::Greater, (None, None) => union_or_intersection_elements_ordering(db, &left_ty, &right_ty), (Some(_), Some(_)) => match left.place_name(db).cmp(&right.place_name(db)) { Ordering::Equal => union_or_intersection_elements_ordering(db, &left_ty, &right_ty), ordering => ordering, }, } } /// Determine a canonical order for two instances of [`TypeIsType`]. fn typeis_ordering(db: &dyn Db, left: TypeIsType, right: TypeIsType) -> Ordering { guard_like_ordering(db, left, right) } /// Determine a canonical order for two instances of [`TypeGuardType`]. fn typeguard_ordering(db: &dyn Db, left: TypeGuardType, right: TypeGuardType) -> Ordering { guard_like_ordering(db, left, right) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/constraints.rs
crates/ty_python_semantic/src/types/constraints.rs
//! Constraints under which type properties hold //! //! For "concrete" types (which contain no type variables), type properties like assignability have //! simple answers: one type is either assignable to another type, or it isn't. (The _rules_ for //! comparing two particular concrete types can be rather complex, but the _answer_ is a simple //! "yes" or "no".) //! //! These properties are more complex when type variables are involved, because there are (usually) //! many different concrete types that a typevar can be specialized to, and the type property might //! hold for some specializations, but not for others. That means that for types that include //! typevars, "Is this type assignable to another?" no longer makes sense as a question. The better //! question is: "Under what constraints is this type assignable to another?". //! //! This module provides the machinery for representing the "under what constraints" part of that //! question. //! //! An individual constraint restricts the specialization of a single typevar to be within a //! particular lower and upper bound. (A type is within a lower and upper bound if it is a //! supertype of the lower bound and a subtype of the upper bound.) You can then build up more //! complex constraint sets using union, intersection, and negation operations. We use a [binary //! decision diagram][bdd] (BDD) to represent a constraint set. //! //! Note that all lower and upper bounds in a constraint must be fully static. We take the bottom //! and top materializations of the types to remove any gradual forms if needed. //! //! NOTE: This module is currently in a transitional state. We've added the BDD [`ConstraintSet`] //! representation, and updated all of our property checks to build up a constraint set and then //! check whether it is ever or always satisfiable, as appropriate. We are not yet inferring //! specializations from those constraints. //! //! ### Examples //! //! For instance, in the following Python code: //! //! ```py //! class A: ... //! class B(A): ... //! //! def _[T: B](t: T) -> None: ... //! def _[U: (int, str)](u: U) -> None: ... //! ``` //! //! The typevar `T` has an upper bound of `B`, which would translate into the constraint `Never ≤ T //! ≤ B`. (Every type is a supertype of `Never`, so having `Never` as a lower bound means that //! there is effectively no lower bound. Similarly, an upper bound of `object` means that there is //! effectively no upper bound.) The `T ≤ B` part expresses that the type can specialize to any //! type that is a subtype of B. //! //! The typevar `U` is constrained to be either `int` or `str`, which would translate into the //! constraint `(int ≤ T ≤ int) ∪ (str ≤ T ≤ str)`. When the lower and upper bounds are the same, //! the constraint says that the typevar must specialize to that _exact_ type, not to a subtype or //! supertype of it. //! //! ### Tracing //! //! This module is instrumented with debug- and trace-level `tracing` messages. You can set the //! `TY_LOG` environment variable to see this output when testing locally. `tracing` log messages //! typically have a `target` field, which is the name of the module the message appears in — in //! this case, `ty_python_semantic::types::constraints`. We add additional detail to these targets, //! in case you only want to debug parts of the implementation. For instance, if you want to debug //! how we construct sequent maps, you could use //! //! ```sh //! env TY_LOG=ty_python_semantic::types::constraints::SequentMap=trace ty check ... //! ``` //! //! [bdd]: https://en.wikipedia.org/wiki/Binary_decision_diagram use std::cell::RefCell; use std::cmp::Ordering; use std::fmt::Display; use std::ops::Range; use itertools::Itertools; use rustc_hash::{FxHashMap, FxHashSet}; use salsa::plumbing::AsId; use crate::types::generics::{GenericContext, InferableTypeVars, Specialization}; use crate::types::visitor::{ TypeCollector, TypeVisitor, any_over_type, walk_type_with_recursion_guard, }; use crate::types::{ BoundTypeVarIdentity, BoundTypeVarInstance, IntersectionType, Type, TypeVarBoundOrConstraints, UnionType, walk_bound_type_var_type, }; use crate::{Db, FxOrderMap, FxOrderSet}; /// An extension trait for building constraint sets from [`Option`] values. pub(crate) trait OptionConstraintsExtension<T> { /// Returns a constraint set that is always satisfiable if the option is `None`; otherwise /// applies a function to determine under what constraints the value inside of it holds. fn when_none_or<'db>(self, f: impl FnOnce(T) -> ConstraintSet<'db>) -> ConstraintSet<'db>; /// Returns a constraint set that is never satisfiable if the option is `None`; otherwise /// applies a function to determine under what constraints the value inside of it holds. fn when_some_and<'db>(self, f: impl FnOnce(T) -> ConstraintSet<'db>) -> ConstraintSet<'db>; } impl<T> OptionConstraintsExtension<T> for Option<T> { fn when_none_or<'db>(self, f: impl FnOnce(T) -> ConstraintSet<'db>) -> ConstraintSet<'db> { match self { Some(value) => f(value), None => ConstraintSet::always(), } } fn when_some_and<'db>(self, f: impl FnOnce(T) -> ConstraintSet<'db>) -> ConstraintSet<'db> { match self { Some(value) => f(value), None => ConstraintSet::never(), } } } /// An extension trait for building constraint sets from an [`Iterator`]. pub(crate) trait IteratorConstraintsExtension<T> { /// Returns the constraints under which any element of the iterator holds. /// /// This method short-circuits; if we encounter any element that /// [`is_always_satisfied`][ConstraintSet::is_always_satisfied], then the overall result /// must be as well, and we stop consuming elements from the iterator. fn when_any<'db>( self, db: &'db dyn Db, f: impl FnMut(T) -> ConstraintSet<'db>, ) -> ConstraintSet<'db>; /// Returns the constraints under which every element of the iterator holds. /// /// This method short-circuits; if we encounter any element that /// [`is_never_satisfied`][ConstraintSet::is_never_satisfied], then the overall result /// must be as well, and we stop consuming elements from the iterator. fn when_all<'db>( self, db: &'db dyn Db, f: impl FnMut(T) -> ConstraintSet<'db>, ) -> ConstraintSet<'db>; } impl<I, T> IteratorConstraintsExtension<T> for I where I: Iterator<Item = T>, { fn when_any<'db>( self, db: &'db dyn Db, mut f: impl FnMut(T) -> ConstraintSet<'db>, ) -> ConstraintSet<'db> { let mut result = ConstraintSet::never(); for child in self { if result.union(db, f(child)).is_always_satisfied(db) { return result; } } result } fn when_all<'db>( self, db: &'db dyn Db, mut f: impl FnMut(T) -> ConstraintSet<'db>, ) -> ConstraintSet<'db> { let mut result = ConstraintSet::always(); for child in self { if result.intersect(db, f(child)).is_never_satisfied(db) { return result; } } result } } /// A set of constraints under which a type property holds. /// /// This is called a "set of constraint sets", and denoted _𝒮_, in [[POPL2015][]]. /// /// The underlying representation tracks the order that individual constraints are added to the /// constraint set, which typically tracks when they appear in the underlying Python source. For /// this to work, you should ensure that you call "combining" operators like [`and`][Self::and] and /// [`or`][Self::or] in a consistent order. /// /// [POPL2015]: https://doi.org/10.1145/2676726.2676991 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, get_size2::GetSize, salsa::Update)] pub struct ConstraintSet<'db> { /// The BDD representing this constraint set node: Node<'db>, } impl<'db> ConstraintSet<'db> { fn never() -> Self { Self { node: Node::AlwaysFalse, } } fn always() -> Self { Self { node: Node::AlwaysTrue, } } /// Returns a constraint set that constraints a typevar to a particular range of types. pub(crate) fn constrain_typevar( db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>, lower: Type<'db>, upper: Type<'db>, ) -> Self { Self { node: ConstrainedTypeVar::new_node(db, typevar, lower, upper), } } /// Returns whether this constraint set never holds pub(crate) fn is_never_satisfied(self, db: &'db dyn Db) -> bool { self.node.is_never_satisfied(db) } /// Returns whether this constraint set always holds pub(crate) fn is_always_satisfied(self, db: &'db dyn Db) -> bool { self.node.is_always_satisfied(db) } /// Returns whether this constraint set contains any cycles between typevars. If it does, then /// we cannot create a specialization from this constraint set. /// /// We have restrictions in place that ensure that there are no cycles in the _lower and upper /// bounds_ of each constraint, but it's still possible for a constraint to _mention_ another /// typevar without _constraining_ it. For instance, `(T ≤ int) ∧ (U ≤ list[T])` is a valid /// constraint set, which we can create a specialization from (`T = int, U = list[int]`). But /// `(T ≤ list[U]) ∧ (U ≤ list[T])` does not violate our lower/upper bounds restrictions, since /// neither bound _is_ a typevar. And it's not something we can create a specialization from, /// since we would endlessly substitute until we stack overflow. pub(crate) fn is_cyclic(self, db: &'db dyn Db) -> bool { #[derive(Default)] struct CollectReachability<'db> { reachable_typevars: RefCell<FxHashSet<BoundTypeVarIdentity<'db>>>, recursion_guard: TypeCollector<'db>, } impl<'db> TypeVisitor<'db> for CollectReachability<'db> { fn should_visit_lazy_type_attributes(&self) -> bool { true } fn visit_bound_type_var_type( &self, db: &'db dyn Db, bound_typevar: BoundTypeVarInstance<'db>, ) { self.reachable_typevars .borrow_mut() .insert(bound_typevar.identity(db)); walk_bound_type_var_type(db, bound_typevar, self); } fn visit_type(&self, db: &'db dyn Db, ty: Type<'db>) { walk_type_with_recursion_guard(db, ty, self, &self.recursion_guard); } } fn visit_dfs<'db>( reachable_typevars: &mut FxHashMap< BoundTypeVarIdentity<'db>, FxHashSet<BoundTypeVarIdentity<'db>>, >, discovered: &mut FxHashSet<BoundTypeVarIdentity<'db>>, bound_typevar: BoundTypeVarIdentity<'db>, ) -> bool { discovered.insert(bound_typevar); let outgoing = reachable_typevars .remove(&bound_typevar) .expect("should not visit typevar twice in DFS"); for outgoing in outgoing { if discovered.contains(&outgoing) { return true; } if reachable_typevars.contains_key(&outgoing) { if visit_dfs(reachable_typevars, discovered, outgoing) { return true; } } } discovered.remove(&bound_typevar); false } // First find all of the typevars that each constraint directly mentions. let mut reachable_typevars: FxHashMap< BoundTypeVarIdentity<'db>, FxHashSet<BoundTypeVarIdentity<'db>>, > = FxHashMap::default(); self.node.for_each_constraint(db, &mut |constraint, _| { let visitor = CollectReachability::default(); visitor.visit_type(db, constraint.lower(db)); visitor.visit_type(db, constraint.upper(db)); reachable_typevars .entry(constraint.typevar(db).identity(db)) .or_default() .extend(visitor.reachable_typevars.into_inner()); }); // Then perform a depth-first search to see if there are any cycles. let mut discovered: FxHashSet<BoundTypeVarIdentity<'db>> = FxHashSet::default(); while let Some(bound_typevar) = reachable_typevars.keys().copied().next() { if !discovered.contains(&bound_typevar) { let cycle_found = visit_dfs(&mut reachable_typevars, &mut discovered, bound_typevar); if cycle_found { return true; } } } false } /// Returns the constraints under which `lhs` is a subtype of `rhs`, assuming that the /// constraints in this constraint set hold. Panics if neither of the types being compared are /// a typevar. (That case is handled by `Type::has_relation_to`.) pub(crate) fn implies_subtype_of( self, db: &'db dyn Db, lhs: Type<'db>, rhs: Type<'db>, ) -> Self { Self { node: self.node.implies_subtype_of(db, lhs, rhs), } } /// Returns whether this constraint set is satisfied by all of the typevars that it mentions. /// /// Each typevar has a set of _valid specializations_, which is defined by any upper bound or /// constraints that the typevar has. /// /// Each typevar is also either _inferable_ or _non-inferable_. (You provide a list of the /// `inferable` typevars; all others are considered non-inferable.) For an inferable typevar, /// then there must be _some_ valid specialization that satisfies the constraint set. For a /// non-inferable typevar, then _all_ valid specializations must satisfy it. /// /// Note that we don't have to consider typevars that aren't mentioned in the constraint set, /// since the constraint set cannot be affected by any typevars that it does not mention. That /// means that those additional typevars trivially satisfy the constraint set, regardless of /// whether they are inferable or not. pub(crate) fn satisfied_by_all_typevars( self, db: &'db dyn Db, inferable: InferableTypeVars<'_, 'db>, ) -> bool { self.node.satisfied_by_all_typevars(db, inferable) } pub(crate) fn limit_to_valid_specializations(self, db: &'db dyn Db) -> Self { let mut result = self.node; let mut seen = FxHashSet::default(); self.node.for_each_constraint(db, &mut |constraint, _| { let bound_typevar = constraint.typevar(db); if seen.insert(bound_typevar) { result = result.and_with_offset(db, bound_typevar.valid_specializations(db)); } }); Self { node: result } } /// Updates this constraint set to hold the union of itself and another constraint set. /// /// In the result, `self` will appear before `other` according to the `source_order` of the BDD /// nodes. pub(crate) fn union(&mut self, db: &'db dyn Db, other: Self) -> Self { self.node = self.node.or_with_offset(db, other.node); *self } /// Updates this constraint set to hold the intersection of itself and another constraint set. /// /// In the result, `self` will appear before `other` according to the `source_order` of the BDD /// nodes. pub(crate) fn intersect(&mut self, db: &'db dyn Db, other: Self) -> Self { self.node = self.node.and_with_offset(db, other.node); *self } /// Returns the negation of this constraint set. pub(crate) fn negate(self, db: &'db dyn Db) -> Self { Self { node: self.node.negate(db), } } /// Returns the intersection of this constraint set and another. The other constraint set is /// provided as a thunk, to implement short-circuiting: the thunk is not forced if the /// constraint set is already saturated. /// /// In the result, `self` will appear before `other` according to the `source_order` of the BDD /// nodes. pub(crate) fn and(mut self, db: &'db dyn Db, other: impl FnOnce() -> Self) -> Self { if !self.is_never_satisfied(db) { self.intersect(db, other()); } self } /// Returns the union of this constraint set and another. The other constraint set is provided /// as a thunk, to implement short-circuiting: the thunk is not forced if the constraint set is /// already saturated. /// /// In the result, `self` will appear before `other` according to the `source_order` of the BDD /// nodes. pub(crate) fn or(mut self, db: &'db dyn Db, other: impl FnOnce() -> Self) -> Self { if !self.is_always_satisfied(db) { self.union(db, other()); } self } /// Returns a constraint set encoding that this constraint set implies another. /// /// In the result, `self` will appear before `other` according to the `source_order` of the BDD /// nodes. pub(crate) fn implies(self, db: &'db dyn Db, other: impl FnOnce() -> Self) -> Self { self.negate(db).or(db, other) } /// Returns a constraint set encoding that this constraint set is equivalent to another. /// /// In the result, `self` will appear before `other` according to the `source_order` of the BDD /// nodes. pub(crate) fn iff(self, db: &'db dyn Db, other: Self) -> Self { ConstraintSet { node: self.node.iff_with_offset(db, other.node), } } /// Reduces the set of inferable typevars for this constraint set. You provide an iterator of /// the typevars that were inferable when this constraint set was created, and which should be /// abstracted away. Those typevars will be removed from the constraint set, and the constraint /// set will return true whenever there was _any_ specialization of those typevars that /// returned true before. pub(crate) fn reduce_inferable( self, db: &'db dyn Db, to_remove: impl IntoIterator<Item = BoundTypeVarIdentity<'db>>, ) -> Self { let node = self.node.exists(db, to_remove); Self { node } } pub(crate) fn for_each_path(self, db: &'db dyn Db, f: impl FnMut(&PathAssignments<'db>)) { self.node.for_each_path(db, f); } pub(crate) fn range( db: &'db dyn Db, lower: Type<'db>, typevar: BoundTypeVarInstance<'db>, upper: Type<'db>, ) -> Self { Self::constrain_typevar(db, typevar, lower, upper) } #[expect(dead_code)] // Keep this around for debugging purposes pub(crate) fn display(self, db: &'db dyn Db) -> impl Display { self.node.simplify_for_display(db).display(db) } #[expect(dead_code)] // Keep this around for debugging purposes pub(crate) fn display_graph(self, db: &'db dyn Db, prefix: &dyn Display) -> impl Display { self.node.display_graph(db, prefix) } } impl From<bool> for ConstraintSet<'_> { fn from(b: bool) -> Self { if b { Self::always() } else { Self::never() } } } impl<'db> BoundTypeVarInstance<'db> { /// Returns whether this typevar can be the lower or upper bound of another typevar in a /// constraint set. /// /// We enforce an (arbitrary) ordering on typevars, and ensure that the bounds of a constraint /// are "later" according to that order than the typevar being constrained. Having an order /// ensures that we can build up transitive relationships between constraints without incurring /// any cycles. This particular ordering plays nicely with how we are ordering constraints /// within a BDD — it means that if a typevar has another typevar as a bound, all of the /// constraints that apply to the bound will appear lower in the BDD. fn can_be_bound_for(self, db: &'db dyn Db, typevar: Self) -> bool { self.identity(db) > typevar.identity(db) } } #[derive(Clone, Copy, Debug)] enum IntersectionResult<'db> { Simplified(ConstrainedTypeVar<'db>), CannotSimplify, Disjoint, } impl IntersectionResult<'_> { fn is_disjoint(self) -> bool { matches!(self, IntersectionResult::Disjoint) } } /// An individual constraint in a constraint set. This restricts a single typevar to be within a /// lower and upper bound. #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] pub(crate) struct ConstrainedTypeVar<'db> { pub(crate) typevar: BoundTypeVarInstance<'db>, pub(crate) lower: Type<'db>, pub(crate) upper: Type<'db>, } // The Salsa heap is tracked separately. impl get_size2::GetSize for ConstrainedTypeVar<'_> {} #[salsa::tracked] impl<'db> ConstrainedTypeVar<'db> { /// Returns a new range constraint. /// /// Panics if `lower` and `upper` are not both fully static. fn new_node( db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>, mut lower: Type<'db>, mut upper: Type<'db>, ) -> Node<'db> { // It's not useful for an upper bound to be an intersection type, or for a lower bound to // be a union type. Because the following equivalences hold, we can break these bounds // apart and create an equivalent BDD with more nodes but simpler constraints. (Fewer, // simpler constraints mean that our sequent maps won't grow pathologically large.) // // T ≤ (α & β) ⇔ (T ≤ α) ∧ (T ≤ β) // T ≤ (¬α & ¬β) ⇔ (T ≤ ¬α) ∧ (T ≤ ¬β) // (α | β) ≤ T ⇔ (α ≤ T) ∧ (β ≤ T) if let Type::Union(lower_union) = lower { let mut result = Node::AlwaysTrue; for lower_element in lower_union.elements(db) { result = result.and_with_offset( db, ConstrainedTypeVar::new_node(db, typevar, *lower_element, upper), ); } return result; } // A negated type ¬α is represented as an intersection with no positive elements, and a // single negative element. We _don't_ want to treat that an "intersection" for the // purposes of simplifying upper bounds. if let Type::Intersection(upper_intersection) = upper && !upper_intersection.is_simple_negation(db) { let mut result = Node::AlwaysTrue; for upper_element in upper_intersection.iter_positive(db) { result = result.and_with_offset( db, ConstrainedTypeVar::new_node(db, typevar, lower, upper_element), ); } for upper_element in upper_intersection.iter_negative(db) { result = result.and_with_offset( db, ConstrainedTypeVar::new_node(db, typevar, lower, upper_element.negate(db)), ); } return result; } // Two identical typevars must always solve to the same type, so it is not useful to have // an upper or lower bound that is the typevar being constrained. match lower { Type::TypeVar(lower_bound_typevar) if typevar.is_same_typevar_as(db, lower_bound_typevar) => { lower = Type::Never; } Type::Intersection(intersection) if intersection.positive(db).iter().any(|element| { element.as_typevar().is_some_and(|element_bound_typevar| { typevar.is_same_typevar_as(db, element_bound_typevar) }) }) => { lower = Type::Never; } Type::Intersection(intersection) if intersection.negative(db).iter().any(|element| { element.as_typevar().is_some_and(|element_bound_typevar| { typevar.is_same_typevar_as(db, element_bound_typevar) }) }) => { return Node::new_constraint( db, ConstrainedTypeVar::new(db, typevar, Type::Never, Type::object()), 1, ) .negate(db); } _ => {} } match upper { Type::TypeVar(upper_bound_typevar) if typevar.is_same_typevar_as(db, upper_bound_typevar) => { upper = Type::object(); } Type::Union(union) if union.elements(db).iter().any(|element| { element.as_typevar().is_some_and(|element_bound_typevar| { typevar.is_same_typevar_as(db, element_bound_typevar) }) }) => { upper = Type::object(); } _ => {} } // If `lower ≰ upper`, then the constraint cannot be satisfied, since there is no type that // is both greater than `lower`, and less than `upper`. if !lower.is_constraint_set_assignable_to(db, upper) { return Node::AlwaysFalse; } // We have an (arbitrary) ordering for typevars. If the upper and/or lower bounds are // typevars, we have to ensure that the bounds are "later" according to that order than the // typevar being constrained. // // In the comments below, we use brackets to indicate which typevar is "earlier", and // therefore the typevar that the constraint applies to. match (lower, upper) { // L ≤ T ≤ L == (T ≤ [L] ≤ T) (Type::TypeVar(lower), Type::TypeVar(upper)) if lower.is_same_typevar_as(db, upper) => { let (bound, typevar) = if lower.can_be_bound_for(db, typevar) { (lower, typevar) } else { (typevar, lower) }; Node::new_constraint( db, ConstrainedTypeVar::new( db, typevar, Type::TypeVar(bound), Type::TypeVar(bound), ), 1, ) } // L ≤ T ≤ U == ([L] ≤ T) && (T ≤ [U]) (Type::TypeVar(lower), Type::TypeVar(upper)) if typevar.can_be_bound_for(db, lower) && typevar.can_be_bound_for(db, upper) => { let lower = Node::new_constraint( db, ConstrainedTypeVar::new(db, lower, Type::Never, Type::TypeVar(typevar)), 1, ); let upper = Node::new_constraint( db, ConstrainedTypeVar::new(db, upper, Type::TypeVar(typevar), Type::object()), 1, ); lower.and(db, upper) } // L ≤ T ≤ U == ([L] ≤ T) && ([T] ≤ U) (Type::TypeVar(lower), _) if typevar.can_be_bound_for(db, lower) => { let lower = Node::new_constraint( db, ConstrainedTypeVar::new(db, lower, Type::Never, Type::TypeVar(typevar)), 1, ); let upper = if upper.is_object() { Node::AlwaysTrue } else { Self::new_node(db, typevar, Type::Never, upper) }; lower.and(db, upper) } // L ≤ T ≤ U == (L ≤ [T]) && (T ≤ [U]) (_, Type::TypeVar(upper)) if typevar.can_be_bound_for(db, upper) => { let lower = if lower.is_never() { Node::AlwaysTrue } else { Self::new_node(db, typevar, lower, Type::object()) }; let upper = Node::new_constraint( db, ConstrainedTypeVar::new(db, upper, Type::TypeVar(typevar), Type::object()), 1, ); lower.and(db, upper) } _ => Node::new_constraint(db, ConstrainedTypeVar::new(db, typevar, lower, upper), 1), } } fn when_true(self) -> ConstraintAssignment<'db> { ConstraintAssignment::Positive(self) } fn when_false(self) -> ConstraintAssignment<'db> { ConstraintAssignment::Negative(self) } fn normalized(self, db: &'db dyn Db) -> Self { Self::new( db, self.typevar(db), self.lower(db).normalized(db), self.upper(db).normalized(db), ) } /// Defines the ordering of the variables in a constraint set BDD. /// /// If we only care about _correctness_, we can choose any ordering that we want, as long as /// it's consistent. However, different orderings can have very different _performance_ /// characteristics. Many BDD libraries attempt to reorder variables on the fly while building /// and working with BDDs. We don't do that, but we have tried to make some simple choices that /// have clear wins. /// /// In particular, we compare the _typevars_ of each constraint first, so that all constraints /// for a single typevar are guaranteed to be adjacent in the BDD structure. There are several /// simplifications that we perform that operate on constraints with the same typevar, and this /// ensures that we can find all candidate simplifications more easily. fn ordering(self, db: &'db dyn Db) -> impl Ord { ( self.typevar(db).binding_context(db), self.typevar(db).identity(db), self.as_id(), ) } /// Returns whether this constraint implies another — i.e., whether every type that /// satisfies this constraint also satisfies `other`. /// /// This is used to simplify how we display constraint sets, by removing redundant constraints /// from a clause. fn implies(self, db: &'db dyn Db, other: Self) -> bool { if !self.typevar(db).is_same_typevar_as(db, other.typevar(db)) { return false; } other .lower(db) .is_constraint_set_assignable_to(db, self.lower(db)) && self .upper(db) .is_constraint_set_assignable_to(db, other.upper(db)) } /// Returns the intersection of two range constraints, or `None` if the intersection is empty. fn intersect(self, db: &'db dyn Db, other: Self) -> IntersectionResult<'db> { // (s₁ ≤ α ≤ t₁) ∧ (s₂ ≤ α ≤ t₂) = (s₁ ∪ s₂) ≤ α ≤ (t₁ ∩ t₂)) let lower = UnionType::from_elements(db, [self.lower(db), other.lower(db)]); let upper = IntersectionType::from_elements(db, [self.upper(db), other.upper(db)]); // If `lower ≰ upper`, then the intersection is empty, since there is no type that is both // greater than `lower`, and less than `upper`. if !lower.is_constraint_set_assignable_to(db, upper) { return IntersectionResult::Disjoint; } if lower.is_union() || upper.is_nontrivial_intersection(db) { return IntersectionResult::CannotSimplify; } IntersectionResult::Simplified(Self::new(db, self.typevar(db), lower, upper)) } pub(crate) fn display(self, db: &'db dyn Db) -> impl Display { self.display_inner(db, false) } fn display_negated(self, db: &'db dyn Db) -> impl Display { self.display_inner(db, true) } fn display_inner(self, db: &'db dyn Db, negated: bool) -> impl Display { struct DisplayConstrainedTypeVar<'db> { constraint: ConstrainedTypeVar<'db>, negated: bool, db: &'db dyn Db, } impl Display for DisplayConstrainedTypeVar<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let lower = self.constraint.lower(self.db); let upper = self.constraint.upper(self.db); let typevar = self.constraint.typevar(self.db);
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/typed_dict.rs
crates/ty_python_semantic/src/types/typed_dict.rs
use std::cmp::Ordering; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use bitflags::bitflags; use ruff_db::diagnostic::{Annotation, Diagnostic, Span, SubDiagnostic, SubDiagnosticSeverity}; use ruff_db::parsed::parsed_module; use ruff_python_ast::Arguments; use ruff_python_ast::{self as ast, AnyNodeRef, StmtClassDef, name::Name}; use ruff_text_size::Ranged; use super::class::{ClassType, CodeGeneratorKind, Field}; use super::context::InferContext; use super::diagnostic::{ self, INVALID_ARGUMENT_TYPE, INVALID_ASSIGNMENT, report_invalid_key_on_typed_dict, report_missing_typed_dict_key, }; use super::{ApplyTypeMappingVisitor, Type, TypeMapping, visitor}; use crate::Db; use crate::semantic_index::definition::Definition; use crate::types::class::FieldKind; use crate::types::constraints::{ConstraintSet, IteratorConstraintsExtension}; use crate::types::generics::InferableTypeVars; use crate::types::{ HasRelationToVisitor, IsDisjointVisitor, IsEquivalentVisitor, NormalizedVisitor, TypeContext, TypeRelation, }; use ordermap::OrderSet; bitflags! { /// Used for `TypedDict` class parameters. /// Keeps track of the keyword arguments that were passed-in during class definition. /// (see https://typing.python.org/en/latest/spec/typeddict.html) #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TypedDictParams: u8 { /// Whether keys are required by default (`total=True`) const TOTAL = 1 << 0; } } impl get_size2::GetSize for TypedDictParams {} impl Default for TypedDictParams { fn default() -> Self { Self::TOTAL } } /// Type that represents the set of all inhabitants (`dict` instances) that conform to /// a given `TypedDict` schema. #[derive(Debug, Copy, Clone, PartialEq, Eq, salsa::Update, Hash, get_size2::GetSize)] pub enum TypedDictType<'db> { /// A reference to the class (inheriting from `typing.TypedDict`) that specifies the /// schema of this `TypedDict`. Class(ClassType<'db>), /// A `TypedDict` that doesn't correspond to a class definition, either because it's been /// `normalized`, or because it's been synthesized to represent constraints. Synthesized(SynthesizedTypedDictType<'db>), } impl<'db> TypedDictType<'db> { pub(crate) fn new(defining_class: ClassType<'db>) -> Self { Self::Class(defining_class) } pub(crate) fn defining_class(self) -> Option<ClassType<'db>> { match self { Self::Class(defining_class) => Some(defining_class), Self::Synthesized(_) => None, } } pub(crate) fn items(self, db: &'db dyn Db) -> &'db TypedDictSchema<'db> { #[salsa::tracked(returns(ref), heap_size=ruff_memory_usage::heap_size)] fn class_based_items<'db>(db: &'db dyn Db, class: ClassType<'db>) -> TypedDictSchema<'db> { let (class_literal, specialization) = class.class_literal(db); class_literal .fields(db, specialization, CodeGeneratorKind::TypedDict) .into_iter() .map(|(name, field)| { let field = match field { Field { first_declaration, declared_ty, kind: FieldKind::TypedDict { is_required, is_read_only, }, } => TypedDictFieldBuilder::new(*declared_ty) .required(*is_required) .read_only(*is_read_only) .first_declaration(*first_declaration) .build(), _ => unreachable!("TypedDict field expected"), }; (name.clone(), field) }) .collect() } match self { Self::Class(defining_class) => class_based_items(db, defining_class), Self::Synthesized(synthesized) => synthesized.items(db), } } pub(crate) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { // TODO: Materialization of gradual TypedDicts needs more logic match self { Self::Class(defining_class) => { Self::Class(defining_class.apply_type_mapping_impl(db, type_mapping, tcx, visitor)) } Self::Synthesized(synthesized) => Self::Synthesized( synthesized.apply_type_mapping_impl(db, type_mapping, tcx, visitor), ), } } // Subtyping between `TypedDict`s follows the algorithm described at: // https://typing.python.org/en/latest/spec/typeddict.html#subtyping-between-typeddict-types pub(super) fn has_relation_to_impl( self, db: &'db dyn Db, target: TypedDictType<'db>, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { // First do a quick nominal check that (if it succeeds) means that we can avoid // materializing the full `TypedDict` schema for either `self` or `target`. // This should be cheaper in many cases, and also helps us avoid some cycles. if let Some(defining_class) = self.defining_class() && let Some(target_defining_class) = target.defining_class() && defining_class.is_subclass_of(db, target_defining_class) { return ConstraintSet::from(true); } let self_items = self.items(db); let target_items = target.items(db); // Many rules violations short-circuit with "never", but asking whether one field is // [relation] to/of another can produce more complicated constraints, and we collect those. let mut constraints = ConstraintSet::from(true); for (target_item_name, target_item_field) in target_items { let field_constraints = if target_item_field.is_required() { // required target fields let Some(self_item_field) = self_items.get(target_item_name) else { // Self is missing a required field. return ConstraintSet::from(false); }; if !self_item_field.is_required() { // A required field is not required in self. return ConstraintSet::from(false); } if target_item_field.is_read_only() { // For `ReadOnly[]` fields in the target, the corresponding fields in // self need to have the same assignability/subtyping/etc relation // individually that we're looking for overall between the // `TypedDict`s. self_item_field.declared_ty.has_relation_to_impl( db, target_item_field.declared_ty, inferable, relation, relation_visitor, disjointness_visitor, ) } else { if self_item_field.is_read_only() { // A read-only field can't be assigned to a mutable target. return ConstraintSet::from(false); } // For mutable fields in the target, the relation needs to apply both // ways, or else mutating the target could violate the structural // invariants of self. For fully-static types, this is "equivalence". // For gradual types, it depends on the relation, but mutual // assignability is "consistency". self_item_field .declared_ty .has_relation_to_impl( db, target_item_field.declared_ty, inferable, relation, relation_visitor, disjointness_visitor, ) .and(db, || { target_item_field.declared_ty.has_relation_to_impl( db, self_item_field.declared_ty, inferable, relation, relation_visitor, disjointness_visitor, ) }) } } else { // `NotRequired[]` target fields if target_item_field.is_read_only() { // As above, for `NotRequired[]` + `ReadOnly[]` fields in the target. It's // tempting to refactor things and unify some of these calls to // `has_relation_to_impl`, but this branch will get more complicated when we // add support for `closed` and `extra_items` (which is why the rules in the // spec are structured like they are), and following the structure of the spec // makes it easier to check the logic here. if let Some(self_item_field) = self_items.get(target_item_name) { self_item_field.declared_ty.has_relation_to_impl( db, target_item_field.declared_ty, inferable, relation, relation_visitor, disjointness_visitor, ) } else { // Self is missing this not-required, read-only item. However, since all // `TypedDict`s by default are allowed to have "extra items" of any type // (until we support `closed` and explicit `extra_items`), this key could // actually turn out to have a value. To make sure this is type-safe, the // not-required field in the target needs to be assignable from `object`. // TODO: `closed` and `extra_items` support will go here. Type::object().when_assignable_to( db, target_item_field.declared_ty, inferable, ) } } else { // As above, for `NotRequired[]` mutable fields in the target. Again the logic // is largely the same for now, but it will get more complicated with `closed` // and `extra_items`. if let Some(self_item_field) = self_items.get(target_item_name) { if self_item_field.is_read_only() { // A read-only field can't be assigned to a mutable target. return ConstraintSet::from(false); } if self_item_field.is_required() { // A required field can't be assigned to a not-required, mutable field // in the target, because `del` is allowed on the target field. return ConstraintSet::from(false); } // As above, for mutable fields in the target, the relation needs // to apply both ways. self_item_field .declared_ty .has_relation_to_impl( db, target_item_field.declared_ty, inferable, relation, relation_visitor, disjointness_visitor, ) .and(db, || { target_item_field.declared_ty.has_relation_to_impl( db, self_item_field.declared_ty, inferable, relation, relation_visitor, disjointness_visitor, ) }) } else { // Self is missing this not-required, mutable field. This isn't ok if self // has read-only extra items, which all `TypedDict`s effectively do until // we support `closed` and explicit `extra_items`. See "A subtle // interaction between two structural assignability rules prevents // unsoundness" in `typed_dict.md`. // TODO: `closed` and `extra_items` support will go here. ConstraintSet::from(false) } } }; constraints.intersect(db, field_constraints); if constraints.is_never_satisfied(db) { return constraints; } } constraints } pub fn definition(self, db: &'db dyn Db) -> Option<Definition<'db>> { match self { TypedDictType::Class(defining_class) => Some(defining_class.definition(db)), TypedDictType::Synthesized(_) => None, } } pub(crate) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { match self { TypedDictType::Class(_) => { let synthesized = SynthesizedTypedDictType::new(db, self.items(db)); TypedDictType::Synthesized(synthesized.normalized_impl(db, visitor)) } TypedDictType::Synthesized(synthesized) => { TypedDictType::Synthesized(synthesized.normalized_impl(db, visitor)) } } } pub(crate) fn is_equivalent_to_impl( self, db: &'db dyn Db, other: TypedDictType<'db>, inferable: InferableTypeVars<'_, 'db>, visitor: &IsEquivalentVisitor<'db>, ) -> ConstraintSet<'db> { // TODO: `closed` and `extra_items` support will go here. Until then we don't look at the // params at all, because `total` is already incorporated into `FieldKind`. // Since both sides' fields are pre-sorted into `BTreeMap`s, we can iterate over them in // sorted order instead of paying for a lookup for each field, as long as their lengths are // the same. if self.items(db).len() != other.items(db).len() { return ConstraintSet::from(false); } self.items(db).iter().zip(other.items(db)).when_all( db, |((name, field), (other_name, other_field))| { if name != other_name || field.flags != other_field.flags { return ConstraintSet::from(false); } field.declared_ty.is_equivalent_to_impl( db, other_field.declared_ty, inferable, visitor, ) }, ) } /// Two `TypedDict`s `A` and `B` are disjoint if it's impossible to come up with a third /// `TypedDict` `C` that's fully-static and assignable to both of them. /// /// `TypedDict` assignability is determined field-by-field, so we determine disjointness /// similarly. For any field that's only in `A`, it's always possible for our hypothetical `C` /// to copy/paste that field without losing assignability to `B` (and vice versa), so we only /// need to consider fields that are present in both `A` and `B`. /// /// There are three properties of each field to consider: the declared type, whether it's /// mutable ("mut" vs "imm" below), and whether it's required ("req" vs "opt" below). Here's a /// table summary of the restrictions on the declared type of a source field (for us that means /// in `C`, which we want to be assignable to both `A` and `B`) given a destination field (for /// us that means in either `A` or `B`). For completeness we'll also include the possibility /// that the source field is missing entirely, though we'll soon see that we can ignore that /// case. This table is essentially what `has_relation_to_impl` implements above. Here /// "equivalent" means the source and destination types must be equivalent/compatible, /// "assignable" means the source must be assignable to the destination, and "-" means the /// assignment is never allowed: /// /// | dest ↓ source → | mut + req | mut + opt | imm + req | imm + opt | \[missing] | /// |------------------|------------|------------|------------|------------|---------------| /// | mut + req | equivalent | - | - | - | - | /// | mut + opt | - | equivalent | - | - | - | /// | imm + req | assignable | - | assignable | - | - | /// | imm + opt | assignable | assignable | assignable | assignable | \[dest is obj]| /// /// We can cut that table down substantially by noticing two things: /// /// - We don't need to consider the cases where the source field (in `C`) is `ReadOnly`/"imm", /// because the mutable version of the same field is always "strictly more assignable". In /// other words, nothing in the `TypedDict` assignability rules ever requires a source field /// to be immutable. /// - We don't need to consider the special case where the source field is missing, because /// that's only allowed when the destination is `ReadOnly[NotRequired[object]]`, which is /// compatible with *any* choice of source field. /// /// The cases we actually need to reason about are this smaller table: /// /// | dest ↓ source → | mut + req | mut + opt | /// |------------------|------------|------------| /// | mut + req | equivalent | - | /// | mut + opt | - | equivalent | /// | imm + req | assignable | - | /// | imm + opt | assignable | assignable | /// /// So, given a field name that's in both `A` and `B`, here are the conditions where it's /// *impossible* to choose a source field for `C` that's compatible with both destinations, /// which tells us that `A` and `B` are disjoint: /// /// 1. If one side is "mut+opt" (which forces the field in `C` to be "opt") and the other side /// is "req" (which forces the field in `C` to be "req"). /// 2. If both sides are mutable, and their types are not equivalent/compatible. (Because the /// type in `C` must be compatible with both of them.) /// 3. If one sides is mutable, and its type is not assignable to the immutable side's type. /// (Because the type in `C` must be compatible with the mutable side.) /// 4. If both sides are immutable, and their types are disjoint. (Because the type in `C` must /// be assignable to both.) /// /// TODO: Adding support for `closed` and `extra_items` will complicate this. pub(crate) fn is_disjoint_from_impl( self, db: &'db dyn Db, other: TypedDictType<'db>, inferable: InferableTypeVars<'_, 'db>, disjointness_visitor: &IsDisjointVisitor<'db>, relation_visitor: &HasRelationToVisitor<'db>, ) -> ConstraintSet<'db> { let fields_in_common = btreemap_values_with_same_key(self.items(db), other.items(db)); fields_in_common.when_any(db, |(self_field, other_field)| { // Condition 1 above. if self_field.is_required() || other_field.is_required() { if (!self_field.is_required() && !self_field.is_read_only()) || (!other_field.is_required() && !other_field.is_read_only()) { // One side demands a `Required` source field, while the other side demands a // `NotRequired` one. They must be disjoint. return ConstraintSet::from(true); } } if !self_field.is_read_only() && !other_field.is_read_only() { // Condition 2 above. This field is mutable on both sides, so the so the types must // be compatible, i.e. mutually assignable. self_field .declared_ty .has_relation_to_impl( db, other_field.declared_ty, inferable, TypeRelation::Assignability, relation_visitor, disjointness_visitor, ) .and(db, || { other_field.declared_ty.has_relation_to_impl( db, self_field.declared_ty, inferable, TypeRelation::Assignability, relation_visitor, disjointness_visitor, ) }) .negate(db) } else if !self_field.is_read_only() { // Half of condition 3 above. self_field .declared_ty .has_relation_to_impl( db, other_field.declared_ty, inferable, TypeRelation::Assignability, relation_visitor, disjointness_visitor, ) .negate(db) } else if !other_field.is_read_only() { // The other half of condition 3 above. other_field .declared_ty .has_relation_to_impl( db, self_field.declared_ty, inferable, TypeRelation::Assignability, relation_visitor, disjointness_visitor, ) .negate(db) } else { // Condition 4 above. self_field.declared_ty.is_disjoint_from_impl( db, other_field.declared_ty, inferable, disjointness_visitor, relation_visitor, ) } }) } } pub(crate) fn walk_typed_dict_type<'db, V: visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, typed_dict: TypedDictType<'db>, visitor: &V, ) { match typed_dict { TypedDictType::Class(defining_class) => { visitor.visit_type(db, defining_class.into()); } TypedDictType::Synthesized(synthesized) => { for field in synthesized.items(db).values() { visitor.visit_type(db, field.declared_ty); } } } } pub(super) fn typed_dict_params_from_class_def(class_stmt: &StmtClassDef) -> TypedDictParams { let mut typed_dict_params = TypedDictParams::default(); // Check for `total` keyword argument in the class definition // Note that it is fine to only check for Boolean literals here // (https://typing.python.org/en/latest/spec/typeddict.html#totality) if let Some(arguments) = &class_stmt.arguments { for keyword in &arguments.keywords { if keyword.arg.as_deref() == Some("total") && matches!( &keyword.value, ast::Expr::BooleanLiteral(ast::ExprBooleanLiteral { value: false, .. }) ) { typed_dict_params.remove(TypedDictParams::TOTAL); } } } typed_dict_params } #[derive(Debug, Clone, Copy)] pub(super) enum TypedDictAssignmentKind { /// For subscript assignments like `d["key"] = value` Subscript, /// For constructor arguments like `MyTypedDict(key=value)` Constructor, } impl TypedDictAssignmentKind { fn diagnostic_name(self) -> &'static str { match self { Self::Subscript => "assignment", Self::Constructor => "argument", } } fn diagnostic_type(self) -> &'static crate::lint::LintMetadata { match self { Self::Subscript => &INVALID_ASSIGNMENT, Self::Constructor => &INVALID_ARGUMENT_TYPE, } } const fn is_subscript(self) -> bool { matches!(self, Self::Subscript) } } /// Validates assignment of a value to a specific key on a `TypedDict`. /// /// Returns true if the assignment is valid, or false otherwise. #[expect(clippy::too_many_arguments)] pub(super) fn validate_typed_dict_key_assignment<'db, 'ast>( context: &InferContext<'db, 'ast>, typed_dict: TypedDictType<'db>, full_object_ty: Option<Type<'db>>, key: &str, value_ty: Type<'db>, typed_dict_node: impl Into<AnyNodeRef<'ast>> + Copy, key_node: impl Into<AnyNodeRef<'ast>>, value_node: impl Into<AnyNodeRef<'ast>>, assignment_kind: TypedDictAssignmentKind, emit_diagnostic: bool, ) -> bool { let db = context.db(); let items = typed_dict.items(db); // Check if key exists in `TypedDict` let Some((_, item)) = items.iter().find(|(name, _)| *name == key) else { if emit_diagnostic { report_invalid_key_on_typed_dict( context, typed_dict_node.into(), key_node.into(), Type::TypedDict(typed_dict), full_object_ty, Type::string_literal(db, key), items, ); } return false; }; let add_object_type_annotation = |diagnostic: &mut Diagnostic| { if let Some(full_object_ty) = full_object_ty { diagnostic.annotate(context.secondary(typed_dict_node.into()).message( format_args!( "TypedDict `{}` in {kind} type `{}`", Type::TypedDict(typed_dict).display(db), full_object_ty.display(db), kind = if full_object_ty.is_union() { "union" } else { "intersection" }, ), )); } else { diagnostic.annotate(context.secondary(typed_dict_node.into()).message( format_args!("TypedDict `{}`", Type::TypedDict(typed_dict).display(db)), )); } }; let add_item_definition_subdiagnostic = |diagnostic: &mut Diagnostic, message| { if let Some(declaration) = item.first_declaration() { let file = declaration.file(db); let module = parsed_module(db, file).load(db); let mut sub = SubDiagnostic::new(SubDiagnosticSeverity::Info, "Item declaration"); sub.annotate( Annotation::secondary( Span::from(file).with_range(declaration.full_range(db, &module).range()), ) .message(message), ); diagnostic.sub(sub); } }; if assignment_kind.is_subscript() && item.is_read_only() { if emit_diagnostic && let Some(builder) = context.report_lint(assignment_kind.diagnostic_type(), key_node.into()) { let typed_dict_ty = Type::TypedDict(typed_dict); let typed_dict_d = typed_dict_ty.display(db); let mut diagnostic = builder.into_diagnostic(format_args!( "Cannot assign to key \"{key}\" on TypedDict `{typed_dict_d}`", )); diagnostic.set_primary_message(format_args!("key is marked read-only")); add_object_type_annotation(&mut diagnostic); add_item_definition_subdiagnostic(&mut diagnostic, "Read-only item declared here"); } return false; } // Key exists, check if value type is assignable to declared type if value_ty.is_assignable_to(db, item.declared_ty) { return true; } let value_node = value_node.into(); if diagnostic::is_invalid_typed_dict_literal(context.db(), item.declared_ty, value_node) { return false; } // Invalid assignment - emit diagnostic if emit_diagnostic && let Some(builder) = context.report_lint(assignment_kind.diagnostic_type(), value_node) { let typed_dict_ty = Type::TypedDict(typed_dict); let typed_dict_d = typed_dict_ty.display(db); let value_d = value_ty.display(db); let item_type_d = item.declared_ty.display(db); let mut diagnostic = builder.into_diagnostic(format_args!( "Invalid {} to key \"{key}\" with declared type `{item_type_d}` on TypedDict `{typed_dict_d}`", assignment_kind.diagnostic_name(), )); diagnostic.set_primary_message(format_args!("value of type `{value_d}`")); diagnostic.annotate( context .secondary(key_node.into()) .message(format_args!("key has declared type `{item_type_d}`")), ); add_item_definition_subdiagnostic(&mut diagnostic, "Item declared here"); add_object_type_annotation(&mut diagnostic); } false } /// Validates that all required keys are provided in a `TypedDict` construction. /// /// Reports errors for any keys that are required but not provided. /// /// Returns true if the assignment is valid, or false otherwise. pub(super) fn validate_typed_dict_required_keys<'db, 'ast>( context: &InferContext<'db, 'ast>, typed_dict: TypedDictType<'db>, provided_keys: &OrderSet<&str>, error_node: AnyNodeRef<'ast>, ) -> bool { let db = context.db(); let items = typed_dict.items(db); let required_keys: OrderSet<&str> = items .iter() .filter_map(|(key_name, field)| field.is_required().then_some(key_name.as_str())) .collect(); let missing_keys = required_keys.difference(provided_keys); let mut has_missing_key = false; for missing_key in missing_keys { has_missing_key = true; report_missing_typed_dict_key( context, error_node, Type::TypedDict(typed_dict), missing_key, ); } !has_missing_key } pub(super) fn validate_typed_dict_constructor<'db, 'ast>( context: &InferContext<'db, 'ast>, typed_dict: TypedDictType<'db>, arguments: &'ast Arguments, error_node: AnyNodeRef<'ast>, expression_type_fn: impl Fn(&ast::Expr) -> Type<'db>, ) { let has_positional_dict = arguments.args.len() == 1 && arguments.args[0].is_dict_expr(); let provided_keys = if has_positional_dict { validate_from_dict_literal( context, typed_dict, arguments, error_node, &expression_type_fn, ) } else { validate_from_keywords( context, typed_dict, arguments, error_node, &expression_type_fn, ) }; validate_typed_dict_required_keys(context, typed_dict, &provided_keys, error_node); } /// Validates a `TypedDict` constructor call with a single positional dictionary argument /// e.g. `Person({"name": "Alice", "age": 30})` fn validate_from_dict_literal<'db, 'ast>( context: &InferContext<'db, 'ast>, typed_dict: TypedDictType<'db>, arguments: &'ast Arguments, error_node: AnyNodeRef<'ast>, expression_type_fn: &impl Fn(&ast::Expr) -> Type<'db>, ) -> OrderSet<&'ast str> { let mut provided_keys = OrderSet::new();
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/unpacker.rs
crates/ty_python_semantic/src/types/unpacker.rs
use std::borrow::Cow; use ruff_db::parsed::ParsedModuleRef; use rustc_hash::FxHashMap; use ruff_python_ast::{self as ast, AnyNodeRef}; use crate::Db; use crate::semantic_index::ast_ids::node_key::ExpressionNodeKey; use crate::semantic_index::scope::ScopeId; use crate::types::tuple::{ResizeTupleError, Tuple, TupleLength, TupleSpec, TupleUnpacker}; use crate::types::{Type, TypeCheckDiagnostics, TypeContext, infer_expression_types}; use crate::unpack::{UnpackKind, UnpackValue}; use super::context::InferContext; use super::diagnostic::INVALID_ASSIGNMENT; /// Unpacks the value expression type to their respective targets. pub(crate) struct Unpacker<'db, 'ast> { context: InferContext<'db, 'ast>, targets: FxHashMap<ExpressionNodeKey, Type<'db>>, } impl<'db, 'ast> Unpacker<'db, 'ast> { pub(crate) fn new( db: &'db dyn Db, target_scope: ScopeId<'db>, module: &'ast ParsedModuleRef, ) -> Self { Self { context: InferContext::new(db, target_scope, module), targets: FxHashMap::default(), } } fn db(&self) -> &'db dyn Db { self.context.db() } fn module(&self) -> &'ast ParsedModuleRef { self.context.module() } /// Unpack the value to the target expression. pub(crate) fn unpack(&mut self, target: &ast::Expr, value: UnpackValue<'db>) { debug_assert!( matches!(target, ast::Expr::List(_) | ast::Expr::Tuple(_)), "Unpacking target must be a list or tuple expression" ); let value_type = infer_expression_types(self.db(), value.expression(), TypeContext::default()) .expression_type(value.expression().node_ref(self.db(), self.module())); let value_type = match value.kind() { UnpackKind::Assign => { if self.context.in_stub() && value .expression() .node_ref(self.db(), self.module()) .is_ellipsis_literal_expr() { Type::unknown() } else { value_type } } UnpackKind::Iterable { mode } => value_type .try_iterate_with_mode(self.db(), mode) .map(|tuple| tuple.homogeneous_element_type(self.db())) .unwrap_or_else(|err| { err.report_diagnostic( &self.context, value_type, value.as_any_node_ref(self.db(), self.module()), ); err.fallback_element_type(self.db()) }), UnpackKind::ContextManager { mode } => value_type .try_enter_with_mode(self.db(), mode) .unwrap_or_else(|err| { err.report_diagnostic( &self.context, value_type, value.as_any_node_ref(self.db(), self.module()), ); err.fallback_enter_type(self.db()) }), }; self.unpack_inner( target, value.as_any_node_ref(self.db(), self.module()), value_type, ); } fn unpack_inner( &mut self, target: &ast::Expr, value_expr: AnyNodeRef<'_>, value_ty: Type<'db>, ) { match target { ast::Expr::Name(_) | ast::Expr::Attribute(_) | ast::Expr::Subscript(_) => { self.targets.insert(target.into(), value_ty); } ast::Expr::Starred(ast::ExprStarred { value, .. }) => { self.unpack_inner(value, value_expr, value_ty); } ast::Expr::List(ast::ExprList { elts, .. }) | ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => { let target_len = match elts.iter().position(ast::Expr::is_starred_expr) { Some(starred_index) => { TupleLength::Variable(starred_index, elts.len() - (starred_index + 1)) } None => TupleLength::Fixed(elts.len()), }; let mut unpacker = TupleUnpacker::new(self.db(), target_len); // N.B. `Type::try_iterate` internally handles unions, but in a lossy way. // For our purposes here, we get better error messages and more precise inference // if we manually map over the union and call `try_iterate` on each union element. // See <https://github.com/astral-sh/ruff/pull/20377#issuecomment-3401380305> // for more discussion. let unpack_types = match value_ty { Type::Union(union_ty) => union_ty.elements(self.db()), _ => std::slice::from_ref(&value_ty), }; for ty in unpack_types.iter().copied() { let tuple = ty.try_iterate(self.db()).unwrap_or_else(|err| { err.report_diagnostic(&self.context, ty, value_expr); Cow::Owned(TupleSpec::homogeneous(err.fallback_element_type(self.db()))) }); if let Err(err) = unpacker.unpack_tuple(tuple.as_ref()) { unpacker .unpack_tuple(&Tuple::homogeneous(Type::unknown())) .expect("adding a homogeneous tuple should always succeed"); if let Some(builder) = self.context.report_lint(&INVALID_ASSIGNMENT, target) { match err { ResizeTupleError::TooManyValues => { let mut diag = builder.into_diagnostic("Too many values to unpack"); diag.set_primary_message(format_args!( "Expected {}", target_len.display_minimum(), )); diag.annotate(self.context.secondary(value_expr).message( format_args!("Got {}", tuple.len().display_minimum()), )); } ResizeTupleError::TooFewValues => { let mut diag = builder.into_diagnostic("Not enough values to unpack"); diag.set_primary_message(format_args!( "Expected {}", target_len.display_minimum(), )); diag.annotate(self.context.secondary(value_expr).message( format_args!("Got {}", tuple.len().display_maximum()), )); } } } } } // We constructed unpacker above using the length of elts, so the zip should // consume the same number of elements from each. for (target, value_ty) in elts.iter().zip(unpacker.into_types()) { self.unpack_inner(target, value_expr, value_ty); } } _ => {} } } pub(crate) fn finish(mut self) -> UnpackResult<'db> { self.targets.shrink_to_fit(); UnpackResult { diagnostics: self.context.finish(), targets: self.targets, cycle_recovery: None, } } } #[derive(Debug, Default, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) struct UnpackResult<'db> { targets: FxHashMap<ExpressionNodeKey, Type<'db>>, diagnostics: TypeCheckDiagnostics, /// The fallback type for missing expressions. /// /// This is used only when constructing a cycle-recovery `UnpackResult`. cycle_recovery: Option<Type<'db>>, } impl<'db> UnpackResult<'db> { /// Returns the inferred type for a given sub-expression of the left-hand side target /// of an unpacking assignment. /// /// # Panics /// /// May panic if a scoped expression ID is passed in that does not correspond to a sub- /// expression of the target. #[track_caller] pub(crate) fn expression_type(&self, expr_id: impl Into<ExpressionNodeKey>) -> Type<'db> { self.try_expression_type(expr_id).expect( "expression should belong to this `UnpackResult` and \ `Unpacker` should have inferred a type for it", ) } pub(crate) fn try_expression_type( &self, expr: impl Into<ExpressionNodeKey>, ) -> Option<Type<'db>> { self.targets .get(&expr.into()) .copied() .or(self.cycle_recovery) } /// Returns the diagnostics in this unpacking assignment. pub(crate) fn diagnostics(&self) -> &TypeCheckDiagnostics { &self.diagnostics } pub(crate) fn cycle_initial(cycle_recovery: Type<'db>) -> Self { Self { targets: FxHashMap::default(), diagnostics: TypeCheckDiagnostics::default(), cycle_recovery: Some(cycle_recovery), } } pub(crate) fn cycle_normalized( mut self, db: &'db dyn Db, previous_cycle_result: &UnpackResult<'db>, cycle: &salsa::Cycle, ) -> Self { for (expr, ty) in &mut self.targets { let previous_ty = previous_cycle_result.expression_type(*expr); *ty = ty.cycle_normalized(db, previous_ty, cycle); } self } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/member.rs
crates/ty_python_semantic/src/types/member.rs
use crate::Db; use crate::place::{ ConsideredDefinitions, Place, PlaceAndQualifiers, RequiresExplicitReExport, place_by_id, place_from_bindings, }; use crate::semantic_index::{place_table, scope::ScopeId, use_def_map}; use crate::types::Type; /// The return type of certain member-lookup operations. Contains information /// about the type, type qualifiers, boundness/declaredness. #[derive(Debug, Clone, Copy, PartialEq, Eq, salsa::Update, get_size2::GetSize, Default)] pub(super) struct Member<'db> { /// Type, qualifiers, and boundness information of this member pub(super) inner: PlaceAndQualifiers<'db>, } impl<'db> Member<'db> { pub(super) fn unbound() -> Self { Self { inner: PlaceAndQualifiers::unbound(), } } pub(super) fn definitely_declared(ty: Type<'db>) -> Self { Self { inner: Place::declared(ty).into(), } } /// Returns `true` if the inner place is undefined (i.e. there is no such member). pub(super) fn is_undefined(&self) -> bool { self.inner.place.is_undefined() } /// Returns the inner type, unless it is definitely undefined. pub(super) fn ignore_possibly_undefined(&self) -> Option<Type<'db>> { self.inner.place.ignore_possibly_undefined() } /// Map a type transformation function over the type of this member. #[must_use] pub(super) fn map_type(self, f: impl FnOnce(Type<'db>) -> Type<'db>) -> Self { Self { inner: self.inner.map_type(f), } } } /// Infer the public type of a class member/symbol (its type as seen from outside its scope) in the given /// `scope`. pub(super) fn class_member<'db>(db: &'db dyn Db, scope: ScopeId<'db>, name: &str) -> Member<'db> { place_table(db, scope) .symbol_id(name) .map(|symbol_id| { let place_and_quals = place_by_id( db, scope, symbol_id.into(), RequiresExplicitReExport::No, ConsideredDefinitions::EndOfScope, ); if !place_and_quals.is_undefined() && !place_and_quals.is_init_var() { // Trust the declared type if we see a class-level declaration return Member { inner: place_and_quals, }; } if let PlaceAndQualifiers { place: Place::Defined(ty, _, _, _), qualifiers, } = place_and_quals { // Otherwise, we need to check if the symbol has bindings let use_def = use_def_map(db, scope); let bindings = use_def.end_of_scope_symbol_bindings(symbol_id); let inferred = place_from_bindings(db, bindings).place; // TODO: we should not need to calculate inferred type second time. This is a temporary // solution until the notion of Boundness and Declaredness is split. See #16036, #16264 Member { inner: match inferred { Place::Undefined => Place::Undefined.with_qualifiers(qualifiers), Place::Defined(_, origin, boundness, widening) => { Place::Defined(ty, origin, boundness, widening) .with_qualifiers(qualifiers) } }, } } else { Member::unbound() } }) .unwrap_or_default() }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/context.rs
crates/ty_python_semantic/src/types/context.rs
use std::fmt; use drop_bomb::DebugDropBomb; use ruff_db::diagnostic::{DiagnosticTag, SubDiagnostic, SubDiagnosticSeverity}; use ruff_db::parsed::ParsedModuleRef; use ruff_db::{ diagnostic::{Annotation, Diagnostic, DiagnosticId, IntoDiagnosticMessage, Severity, Span}, files::File, }; use ruff_text_size::{Ranged, TextRange}; use super::{Type, TypeCheckDiagnostics, binding_type}; use crate::diagnostic::DiagnosticGuard; use crate::lint::LintSource; use crate::semantic_index::scope::ScopeId; use crate::semantic_index::semantic_index; use crate::types::function::FunctionDecorators; use crate::{ Db, lint::{LintId, LintMetadata}, suppression::suppressions, }; /// Context for inferring the types of a single file. /// /// One context exists for at least for every inferred region but it's /// possible that inferring a sub-region, like an unpack assignment, creates /// a sub-context. /// /// Tracks the reported diagnostics of the inferred region. /// /// ## Consuming /// It's important that the context is explicitly consumed before dropping by calling /// [`InferContext::finish`] and the returned diagnostics must be stored /// on the current inference result. pub(crate) struct InferContext<'db, 'ast> { db: &'db dyn Db, scope: ScopeId<'db>, file: File, module: &'ast ParsedModuleRef, diagnostics: std::cell::RefCell<TypeCheckDiagnostics>, no_type_check: InNoTypeCheck, multi_inference: bool, bomb: DebugDropBomb, } impl<'db, 'ast> InferContext<'db, 'ast> { pub(crate) fn new(db: &'db dyn Db, scope: ScopeId<'db>, module: &'ast ParsedModuleRef) -> Self { Self { db, scope, module, file: scope.file(db), multi_inference: false, diagnostics: std::cell::RefCell::new(TypeCheckDiagnostics::default()), no_type_check: InNoTypeCheck::default(), bomb: DebugDropBomb::new( "`InferContext` needs to be explicitly consumed by calling `::finish` to prevent accidental loss of diagnostics.", ), } } /// The file for which the types are inferred. pub(crate) fn file(&self) -> File { self.file } /// The module for which the types are inferred. pub(crate) fn module(&self) -> &'ast ParsedModuleRef { self.module } pub(crate) fn scope(&self) -> ScopeId<'db> { self.scope } /// Create a span with the range of the given expression /// in the file being currently type checked. /// /// If you're creating a diagnostic with snippets in files /// other than this one, you should create the span directly /// and not use this convenience API. pub(crate) fn span<T: Ranged>(&self, ranged: T) -> Span { Span::from(self.file()).with_range(ranged.range()) } /// Create a secondary annotation attached to the range of the given value in /// the file currently being type checked. /// /// The annotation returned has no message attached to it. pub(crate) fn secondary<T: Ranged>(&self, ranged: T) -> Annotation { Annotation::secondary(self.span(ranged)) } pub(crate) fn db(&self) -> &'db dyn Db { self.db } pub(crate) fn extend(&mut self, other: &TypeCheckDiagnostics) { if !self.is_in_multi_inference() { self.diagnostics.get_mut().extend(other); } } pub(super) fn is_lint_enabled(&self, lint: &'static LintMetadata) -> bool { LintDiagnosticGuardBuilder::severity_and_source(self, LintId::of(lint)).is_some() } /// Optionally return a builder for a lint diagnostic guard. /// /// If the current context believes a diagnostic should be reported for /// the given lint, then a builder is returned that enables building a /// lint diagnostic guard. The guard can then be used, via its `DerefMut` /// implementation, to directly mutate a `Diagnostic`. /// /// The severity of the diagnostic returned is automatically determined /// by the given lint and configuration. The message given to /// `LintDiagnosticGuardBuilder::to_diagnostic` is used to construct the /// initial diagnostic and should be considered the "top-level message" of /// the diagnostic. (i.e., If nothing else about the diagnostic is seen, /// aside from its identifier, the message is probably the thing you'd pick /// to show.) /// /// The diagnostic constructed also includes a primary annotation with a /// `Span` derived from the range given attached to the `File` in this /// typing context. (That means the range given _must_ be valid for the /// `File` currently being type checked.) This primary annotation does /// not have a message attached to it, but callers can attach one via /// `LintDiagnosticGuard::set_primary_message`. /// /// After using the builder to make a guard, once the guard is dropped, the /// diagnostic is added to the context, unless there is something in the /// diagnostic that excludes it. (Currently, no such conditions exist.) /// /// If callers need to create a non-lint diagnostic, you'll want to use the /// lower level `InferContext::report_diagnostic` routine. pub(super) fn report_lint<'ctx, T: Ranged>( &'ctx self, lint: &'static LintMetadata, ranged: T, ) -> Option<LintDiagnosticGuardBuilder<'ctx, 'db>> { LintDiagnosticGuardBuilder::new(self, lint, ranged.range()) } /// Optionally return a builder for a diagnostic guard. /// /// This only returns a builder if the current context allows a diagnostic /// with the given information to be added. In general, the requirements /// here are quite a bit less than for `InferContext::report_lint`, since /// this routine doesn't take rule selection into account (among other /// things). /// /// After using the builder to make a guard, once the guard is dropped, the /// diagnostic is added to the context, unless there is something in the /// diagnostic that excludes it. (Currently, no such conditions exist.) /// /// Callers should generally prefer adding a lint diagnostic via /// `InferContext::report_lint` whenever possible. pub(super) fn report_diagnostic<'ctx>( &'ctx self, id: DiagnosticId, severity: Severity, ) -> Option<DiagnosticGuardBuilder<'ctx, 'db>> { DiagnosticGuardBuilder::new(self, id, severity) } /// Returns `true` if the current expression is being inferred for a second /// (or subsequent) time, with a potentially different bidirectional type /// context. pub(super) fn is_in_multi_inference(&self) -> bool { self.multi_inference } /// Set the multi-inference state, returning the previous value. pub(super) fn set_multi_inference(&mut self, multi_inference: bool) -> bool { std::mem::replace(&mut self.multi_inference, multi_inference) } pub(super) fn set_in_no_type_check(&mut self, no_type_check: InNoTypeCheck) -> InNoTypeCheck { std::mem::replace(&mut self.no_type_check, no_type_check) } fn is_in_no_type_check(&self) -> bool { match self.no_type_check { InNoTypeCheck::Possibly => { // Accessing the semantic index here is fine because // the index belongs to the same file as for which we emit the diagnostic. let index = semantic_index(self.db, self.file); let scope_id = self.scope.file_scope_id(self.db); // Inspect all ancestor function scopes by walking bottom up and infer the function's type. let mut function_scope_tys = index .ancestor_scopes(scope_id) .filter_map(|(_, scope)| scope.node().as_function()) .map(|node| binding_type(self.db, index.expect_single_definition(node))) .filter_map(Type::as_function_literal); // Iterate over all functions and test if any is decorated with `@no_type_check`. function_scope_tys.any(|function_ty| { function_ty.has_known_decorator(self.db, FunctionDecorators::NO_TYPE_CHECK) }) } InNoTypeCheck::Yes => true, } } /// Are we currently inferring types in a stub file? pub(crate) fn in_stub(&self) -> bool { self.file.is_stub(self.db()) } #[must_use] pub(crate) fn finish(mut self) -> TypeCheckDiagnostics { self.bomb.defuse(); let mut diagnostics = self.diagnostics.into_inner(); diagnostics.shrink_to_fit(); diagnostics } } impl fmt::Debug for InferContext<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("TyContext") .field("file", &self.file) .field("diagnostics", &self.diagnostics) .field("defused", &self.bomb) .finish() } } #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] pub(crate) enum InNoTypeCheck { /// The inference might be in a `no_type_check` block but only if any /// ancestor function is decorated with `@no_type_check`. #[default] Possibly, /// The inference is known to be in an `@no_type_check` decorated function. Yes, } /// An abstraction for mutating a diagnostic through the lense of a lint. /// /// Callers can build this guard by starting with `InferContext::report_lint`. /// /// There are two primary functions of this guard, which mutably derefs to /// a `Diagnostic`: /// /// * On `Drop`, the underlying diagnostic is added to the typing context. /// * Some convenience methods for mutating the underlying `Diagnostic` /// in lint context. For example, `LintDiagnosticGuard::set_primary_message` /// will attach a message to the primary span on the diagnostic. pub(super) struct LintDiagnosticGuard<'db, 'ctx> { /// The typing context. ctx: &'ctx InferContext<'db, 'ctx>, /// The diagnostic that we want to report. /// /// This is always `Some` until the `Drop` impl. diag: Option<Diagnostic>, source: LintSource, } impl LintDiagnosticGuard<'_, '_> { /// Set the message on the primary annotation for this diagnostic. /// /// If a message already exists on the primary annotation, then this /// overwrites the existing message. /// /// This message is associated with the primary annotation created /// for every `Diagnostic` that uses the `LintDiagnosticGuard` API. /// Specifically, the annotation is derived from the `TextRange` given to /// the `InferContext::report_lint` API. /// /// Callers can add additional primary or secondary annotations via the /// `DerefMut` trait implementation to a `Diagnostic`. pub(super) fn set_primary_message(&mut self, message: impl IntoDiagnosticMessage) { // N.B. It is normally bad juju to define `self` methods // on types that implement `Deref`. Instead, it's idiomatic // to do `fn foo(this: &mut LintDiagnosticGuard)`, which in // turn forces callers to use // `LintDiagnosticGuard(&mut guard, message)`. But this is // supremely annoying for what is expected to be a common // case. // // Moreover, most of the downside that comes from these sorts // of methods is a semver hazard. Because the deref target type // could also define a method by the same name, and that leads // to confusion. But we own all the code involved here and // there is no semver boundary. So... ¯\_(ツ)_/¯ ---AG // OK because we know the diagnostic was constructed with a single // primary annotation that will always come before any other annotation // in the diagnostic. (This relies on the `Diagnostic` API not exposing // any methods for removing annotations or re-ordering them, which is // true as of 2025-04-11.) let ann = self.primary_annotation_mut().unwrap(); ann.set_message(message); } /// Adds a tag on the primary annotation for this diagnostic. /// /// This tag is associated with the primary annotation created /// for every `Diagnostic` that uses the `LintDiagnosticGuard` API. /// Specifically, the annotation is derived from the `TextRange` given to /// the `InferContext::report_lint` API. /// /// Callers can add additional primary or secondary annotations via the /// `DerefMut` trait implementation to a `Diagnostic`. pub(super) fn add_primary_tag(&mut self, tag: DiagnosticTag) { let ann = self.primary_annotation_mut().unwrap(); ann.push_tag(tag); } } impl std::ops::Deref for LintDiagnosticGuard<'_, '_> { type Target = Diagnostic; fn deref(&self) -> &Diagnostic { // OK because `self.diag` is only `None` within `Drop`. self.diag.as_ref().unwrap() } } /// Return a mutable borrow of the diagnostic in this guard. /// /// Callers may mutate the diagnostic to add new sub-diagnostics /// or annotations. /// /// The diagnostic is added to the typing context, if appropriate, /// when this guard is dropped. impl std::ops::DerefMut for LintDiagnosticGuard<'_, '_> { fn deref_mut(&mut self) -> &mut Diagnostic { // OK because `self.diag` is only `None` within `Drop`. self.diag.as_mut().unwrap() } } /// Finishes use of this guard. /// /// This will add the lint as a diagnostic to the typing context if /// appropriate. The diagnostic may be skipped, for example, if there is a /// relevant suppression. impl Drop for LintDiagnosticGuard<'_, '_> { fn drop(&mut self) { // OK because the only way `self.diag` is `None` // is via this impl, which can only run at most // once. let mut diag = self.diag.take().unwrap(); diag.sub(SubDiagnostic::new( SubDiagnosticSeverity::Info, match self.source { LintSource::Default => format!("rule `{}` is enabled by default", diag.id()), LintSource::Cli => format!("rule `{}` was selected on the command line", diag.id()), LintSource::File => { format!( "rule `{}` was selected in the configuration file", diag.id() ) } LintSource::Editor => { format!("rule `{}` was selected in the editor settings", diag.id()) } }, )); self.ctx.diagnostics.borrow_mut().push(diag); } } /// A builder for constructing a lint diagnostic guard. /// /// This type exists to separate the phases of "check if a diagnostic should /// be reported" and "build the actual diagnostic." It's why, for example, /// `InferContext::report_lint` only requires a `LintMetadata` (and a range), /// but this builder further requires a message before one can mutate the /// diagnostic. This is because the `LintMetadata` can be used to derive /// the diagnostic ID and its severity (based on configuration). Combined /// with a message you get the minimum amount of data required to build a /// `Diagnostic`. /// /// Additionally, the range is used to construct a primary annotation (without /// a message) using the file current being type checked. The range given to /// `InferContext::report_lint` must be from the file currently being type /// checked. /// /// If callers need to report a diagnostic with an identifier type other /// than `DiagnosticId::Lint`, then they should use the more general /// `InferContext::report_diagnostic` API. But note that this API will not take /// rule selection or suppressions into account. /// /// # When is the diagnostic added? /// /// When a builder is not returned by `InferContext::report_lint`, then /// it is known that the diagnostic should not be reported. This can happen /// when the diagnostic is disabled or suppressed (among other reasons). pub(super) struct LintDiagnosticGuardBuilder<'db, 'ctx> { ctx: &'ctx InferContext<'db, 'ctx>, id: LintId, severity: Severity, source: LintSource, primary_range: TextRange, } impl<'db, 'ctx> LintDiagnosticGuardBuilder<'db, 'ctx> { fn severity_and_source( ctx: &'ctx InferContext<'db, 'ctx>, lint: LintId, ) -> Option<(Severity, LintSource)> { // The comment below was copied from the original // implementation of diagnostic reporting. The code // has been refactored, but this still kind of looked // relevant, so I've preserved the note. ---AG // // TODO: Don't emit the diagnostic if: // * The enclosing node contains any syntax errors // * The rule is disabled for this file. We probably want to introduce a new query that // returns a rule selector for a given file that respects the package's settings, // any global pragma comments in the file, and any per-file-ignores. if !ctx.db.should_check_file(ctx.file) { return None; } // Skip over diagnostics if the rule // is disabled. let (severity, source) = ctx.db.rule_selection(ctx.file).get(lint)?; // If we're not in type checking mode, // we can bail now. if ctx.is_in_no_type_check() { return None; } // If this lint is being reported as part of multi-inference of a given expression, // silence it to avoid duplicated diagnostics. if ctx.is_in_multi_inference() { return None; } Some((severity, source)) } fn new( ctx: &'ctx InferContext<'db, 'ctx>, lint: &'static LintMetadata, range: TextRange, ) -> Option<LintDiagnosticGuardBuilder<'db, 'ctx>> { let lint_id = LintId::of(lint); let (severity, source) = Self::severity_and_source(ctx, lint_id)?; let suppressions = suppressions(ctx.db(), ctx.file()); if let Some(suppression) = suppressions.find_suppression(range, lint_id) { ctx.diagnostics.borrow_mut().mark_used(suppression.id()); return None; } Some(LintDiagnosticGuardBuilder { ctx, id: lint_id, severity, source, primary_range: range, }) } /// Create a new lint diagnostic guard. /// /// This initializes a new diagnostic using the given message along with /// the ID and severity derived from the `LintMetadata` used to create /// this builder. The diagnostic also includes a primary annotation /// without a message. To add a message to this primary annotation, use /// `LintDiagnosticGuard::set_primary_message`. /// /// The diagnostic can be further mutated on the guard via its `DerefMut` /// impl to `Diagnostic`. pub(super) fn into_diagnostic( self, message: impl std::fmt::Display, ) -> LintDiagnosticGuard<'db, 'ctx> { let mut diag = Diagnostic::new(DiagnosticId::Lint(self.id.name()), self.severity, message); diag.set_documentation_url(Some(self.id.documentation_url())); // This is why `LintDiagnosticGuard::set_primary_message` exists. // We add the primary annotation here (because it's required), but // the optional message can be added later. We could accept it here // in this `build` method, but we already accept the main diagnostic // message. So the messages are likely to be quite confusable. let primary_span = Span::from(self.ctx.file()).with_range(self.primary_range); diag.annotate(Annotation::primary(primary_span)); LintDiagnosticGuard { ctx: self.ctx, source: self.source, diag: Some(diag), } } } /// A builder for constructing a diagnostic guard. /// /// This type exists to separate the phases of "check if a diagnostic should /// be reported" and "build the actual diagnostic." It's why, for example, /// `InferContext::report_diagnostic` only requires an ID and a severity, but /// this builder further requires a message (with those three things being the /// minimal amount of information with which to construct a diagnostic) before /// one can mutate the diagnostic. pub(super) struct DiagnosticGuardBuilder<'db, 'ctx> { ctx: &'ctx InferContext<'db, 'ctx>, id: DiagnosticId, severity: Severity, } impl<'db, 'ctx> DiagnosticGuardBuilder<'db, 'ctx> { fn new( ctx: &'ctx InferContext<'db, 'ctx>, id: DiagnosticId, severity: Severity, ) -> Option<DiagnosticGuardBuilder<'db, 'ctx>> { if !ctx.db.should_check_file(ctx.file) { return None; } // If this lint is being reported as part of multi-inference of a given expression, // silence it to avoid duplicated diagnostics. if ctx.is_in_multi_inference() { return None; } Some(DiagnosticGuardBuilder { ctx, id, severity }) } /// Create a new guard. /// /// This initializes a new diagnostic using the given message along with /// the ID and severity used to create this builder. /// /// The diagnostic can be further mutated on the guard via its `DerefMut` /// impl to `Diagnostic`. pub(super) fn into_diagnostic(self, message: impl std::fmt::Display) -> DiagnosticGuard<'ctx> { let diag = Diagnostic::new(self.id, self.severity, message); DiagnosticGuard::new(self.ctx.file, &self.ctx.diagnostics, diag) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/instance.rs
crates/ty_python_semantic/src/types/instance.rs
//! Instance types: both nominal and structural. use std::borrow::Cow; use std::marker::PhantomData; use super::protocol_class::ProtocolInterface; use super::{BoundTypeVarInstance, ClassType, KnownClass, SubclassOfType, Type, TypeVarVariance}; use crate::place::PlaceAndQualifiers; use crate::semantic_index::definition::Definition; use crate::types::constraints::{ConstraintSet, IteratorConstraintsExtension}; use crate::types::enums::is_single_member_enum; use crate::types::generics::{InferableTypeVars, walk_specialization}; use crate::types::protocol_class::{ProtocolClass, walk_protocol_interface}; use crate::types::tuple::{TupleSpec, TupleType, walk_tuple_type}; use crate::types::{ ApplyTypeMappingVisitor, ClassBase, ClassLiteral, FindLegacyTypeVarsVisitor, HasRelationToVisitor, IsDisjointVisitor, IsEquivalentVisitor, NormalizedVisitor, TypeContext, TypeMapping, TypeRelation, VarianceInferable, }; use crate::{Db, FxOrderSet}; pub(super) use synthesized_protocol::SynthesizedProtocolType; impl<'db> Type<'db> { pub(crate) const fn object() -> Self { Type::NominalInstance(NominalInstanceType(NominalInstanceInner::Object)) } pub(crate) const fn is_object(&self) -> bool { matches!( self, Type::NominalInstance(NominalInstanceType(NominalInstanceInner::Object)) ) } pub(crate) fn instance(db: &'db dyn Db, class: ClassType<'db>) -> Self { let (class_literal, specialization) = class.class_literal(db); match class_literal.known(db) { Some(KnownClass::Tuple) => Type::tuple(TupleType::new( db, specialization .and_then(|spec| Some(Cow::Borrowed(spec.tuple(db)?))) .unwrap_or_else(|| Cow::Owned(TupleSpec::homogeneous(Type::unknown()))) .as_ref(), )), Some(KnownClass::Object) => Type::object(), _ => class_literal .is_typed_dict(db) .then(|| Type::typed_dict(class)) .or_else(|| { class.into_protocol_class(db).map(|protocol_class| { Self::ProtocolInstance(ProtocolInstanceType::from_class(protocol_class)) }) }) .unwrap_or(Type::NominalInstance(NominalInstanceType( NominalInstanceInner::NonTuple(class), ))), } } pub(crate) fn tuple(tuple: Option<TupleType<'db>>) -> Self { let Some(tuple) = tuple else { return Type::Never; }; Type::tuple_instance(tuple) } pub(crate) fn homogeneous_tuple(db: &'db dyn Db, element: Type<'db>) -> Self { Type::tuple_instance(TupleType::homogeneous(db, element)) } pub(crate) fn heterogeneous_tuple<I, T>(db: &'db dyn Db, elements: I) -> Self where I: IntoIterator<Item = T>, T: Into<Type<'db>>, { Type::tuple(TupleType::heterogeneous( db, elements.into_iter().map(Into::into), )) } pub(crate) fn empty_tuple(db: &'db dyn Db) -> Self { Type::tuple_instance(TupleType::empty(db)) } /// **Private** helper function to create a `Type::NominalInstance` from a tuple. fn tuple_instance(tuple: TupleType<'db>) -> Self { Type::NominalInstance(NominalInstanceType(NominalInstanceInner::ExactTuple(tuple))) } pub(crate) const fn is_nominal_instance(self) -> bool { matches!(self, Type::NominalInstance(_)) } pub(crate) const fn as_nominal_instance(self) -> Option<NominalInstanceType<'db>> { match self { Type::NominalInstance(instance_type) => Some(instance_type), _ => None, } } /// Return `true` if `self` is a nominal instance of the given known class. pub(crate) fn is_instance_of(self, db: &'db dyn Db, known_class: KnownClass) -> bool { match self { Type::NominalInstance(instance) => instance.class(db).is_known(db, known_class), _ => false, } } /// Synthesize a protocol instance type with a given set of read-only property members. pub(super) fn protocol_with_readonly_members<'a, M>(db: &'db dyn Db, members: M) -> Self where M: IntoIterator<Item = (&'a str, Type<'db>)>, { Self::ProtocolInstance(ProtocolInstanceType::synthesized( SynthesizedProtocolType::new( db, ProtocolInterface::with_property_members(db, members), &NormalizedVisitor::default(), ), )) } /// Return `true` if `self` conforms to the interface described by `protocol`. pub(super) fn satisfies_protocol( self, db: &'db dyn Db, protocol: ProtocolInstanceType<'db>, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { let structurally_satisfied = if let Type::ProtocolInstance(self_protocol) = self { self_protocol.interface(db).has_relation_to_impl( db, protocol.interface(db), inferable, relation, relation_visitor, disjointness_visitor, ) } else { protocol .inner .interface(db) .members(db) .when_all(db, |member| { member.is_satisfied_by( db, self, inferable, relation, relation_visitor, disjointness_visitor, ) }) }; // Even if `self` does not satisfy the protocol from a structural perspective, // we may still need to consider it as satisfying the protocol if `protocol` is // a class-based protocol and `self` has the protocol class in its MRO. // // This matches the behaviour of other type checkers, and is required for us to // recognise `str` as a subtype of `Container[str]`. structurally_satisfied.or(db, || { let Some(nominal_instance) = protocol.to_nominal_instance() else { return ConstraintSet::from(false); }; // if `self` and `other` are *both* protocols, we also need to treat `self` as if it // were a nominal type, or we won't consider a protocol `P` that explicitly inherits // from a protocol `Q` to be a subtype of `Q` to be a subtype of `Q` if it overrides // `Q`'s members in a Liskov-incompatible way. let type_to_test = self .as_protocol_instance() .and_then(ProtocolInstanceType::to_nominal_instance) .map(Type::NominalInstance) .unwrap_or(self); type_to_test.has_relation_to_impl( db, Type::NominalInstance(nominal_instance), inferable, relation, relation_visitor, disjointness_visitor, ) }) } } /// A type representing the set of runtime objects which are instances of a certain nominal class. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, salsa::Update, get_size2::GetSize)] pub struct NominalInstanceType<'db>( // Keep this field private, so that the only way of constructing `NominalInstanceType` instances // is through the `Type::instance` constructor function. NominalInstanceInner<'db>, ); pub(super) fn walk_nominal_instance_type<'db, V: super::visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, nominal: NominalInstanceType<'db>, visitor: &V, ) { match nominal.0 { NominalInstanceInner::ExactTuple(tuple) => { walk_tuple_type(db, tuple, visitor); } NominalInstanceInner::Object => {} NominalInstanceInner::NonTuple(class) => { visitor.visit_type(db, class.into()); } } } impl<'db> NominalInstanceType<'db> { pub(super) fn class(&self, db: &'db dyn Db) -> ClassType<'db> { match self.0 { NominalInstanceInner::ExactTuple(tuple) => tuple.to_class_type(db), NominalInstanceInner::NonTuple(class) => class, NominalInstanceInner::Object => KnownClass::Object .try_to_class_literal(db) .expect("Typeshed should always have a `object` class in `builtins.pyi`") .default_specialization(db), } } pub(super) fn class_literal(&self, db: &'db dyn Db) -> ClassLiteral<'db> { let class = match self.0 { NominalInstanceInner::ExactTuple(tuple) => tuple.to_class_type(db), NominalInstanceInner::NonTuple(class) => class, NominalInstanceInner::Object => { return KnownClass::Object .try_to_class_literal(db) .expect("Typeshed should always have a `object` class in `builtins.pyi`"); } }; let (class_literal, _) = class.class_literal(db); class_literal } /// Returns the [`KnownClass`] that this is a nominal instance of, or `None` if it is not an /// instance of a known class. pub(super) fn known_class(&self, db: &'db dyn Db) -> Option<KnownClass> { match self.0 { NominalInstanceInner::ExactTuple(_) => Some(KnownClass::Tuple), NominalInstanceInner::NonTuple(class) => class.known(db), NominalInstanceInner::Object => Some(KnownClass::Object), } } /// Returns whether this is a nominal instance of a particular [`KnownClass`]. pub(super) fn has_known_class(&self, db: &'db dyn Db, known_class: KnownClass) -> bool { self.known_class(db) == Some(known_class) } /// If this is an instance type where the class has a tuple spec, returns the tuple spec. /// /// I.e., for the type `tuple[int, str]`, this will return the tuple spec `[int, str]`. /// For a subclass of `tuple[int, str]`, it will return the same tuple spec. pub(super) fn tuple_spec(&self, db: &'db dyn Db) -> Option<Cow<'db, TupleSpec<'db>>> { match self.0 { NominalInstanceInner::ExactTuple(tuple) => Some(Cow::Borrowed(tuple.tuple(db))), NominalInstanceInner::NonTuple(class) => { // Avoid an expensive MRO traversal for common stdlib classes. if class .known(db) .is_some_and(|known_class| !known_class.is_tuple_subclass()) { return None; } class .iter_mro(db) .filter_map(ClassBase::into_class) .find_map(|class| match class.known(db)? { // N.B. this is a pure optimisation: iterating through the MRO would give us // the correct tuple spec for `sys._version_info`, since we special-case the class // in `ClassLiteral::explicit_bases()` so that it is inferred as inheriting from // a tuple type with the correct spec for the user's configured Python version and platform. KnownClass::VersionInfo => { Some(Cow::Owned(TupleSpec::version_info_spec(db))) } KnownClass::Tuple => Some( class .into_generic_alias() .and_then(|alias| { Some(Cow::Borrowed(alias.specialization(db).tuple(db)?)) }) .unwrap_or_else(|| { Cow::Owned(TupleSpec::homogeneous(Type::unknown())) }), ), _ => None, }) } NominalInstanceInner::Object => None, } } /// Return `true` if this type represents instances of the class `builtins.object`. pub(super) const fn is_object(self) -> bool { matches!(self.0, NominalInstanceInner::Object) } pub(super) fn is_definition_generic(self) -> bool { match self.0 { NominalInstanceInner::NonTuple(class) => class.is_generic(), NominalInstanceInner::ExactTuple(_) => true, NominalInstanceInner::Object => false, } } /// If this type is an *exact* tuple type (*not* a subclass of `tuple`), returns the /// tuple spec. /// /// You usually don't want to use this method, as you usually want to consider a subclass /// of a tuple type in the same way as the `tuple` type itself. Only use this method if you /// are certain that a *literal tuple* is required, and that a subclass of tuple will not /// do. /// /// I.e., for the type `tuple[int, str]`, this will return the tuple spec `[int, str]`. /// But for a subclass of `tuple[int, str]`, it will return `None`. pub(super) fn own_tuple_spec(&self, db: &'db dyn Db) -> Option<Cow<'db, TupleSpec<'db>>> { match self.0 { NominalInstanceInner::ExactTuple(tuple) => Some(Cow::Borrowed(tuple.tuple(db))), NominalInstanceInner::NonTuple(_) | NominalInstanceInner::Object => None, } } /// If this is a specialized instance of `slice`, returns a [`SliceLiteral`] describing it. /// Otherwise returns `None`. /// /// The specialization must be one in which the typevars are solved as being statically known /// integers or `None`. pub(crate) fn slice_literal(self, db: &'db dyn Db) -> Option<SliceLiteral> { let class = match self.0 { NominalInstanceInner::ExactTuple(_) | NominalInstanceInner::Object => return None, NominalInstanceInner::NonTuple(class) => class, }; let (class, Some(specialization)) = class.class_literal(db) else { return None; }; if !class.is_known(db, KnownClass::Slice) { return None; } let [start, stop, step] = specialization.types(db) else { return None; }; let to_u32 = |ty: &Type<'db>| match ty { Type::IntLiteral(n) => i32::try_from(*n).map(Some).ok(), Type::BooleanLiteral(b) => Some(Some(i32::from(*b))), Type::NominalInstance(instance) if instance.has_known_class(db, KnownClass::NoneType) => { Some(None) } _ => None, }; Some(SliceLiteral { start: to_u32(start)?, stop: to_u32(stop)?, step: to_u32(step)?, }) } pub(super) fn normalized_impl( self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>, ) -> Type<'db> { match self.0 { NominalInstanceInner::ExactTuple(tuple) => { Type::tuple(tuple.normalized_impl(db, visitor)) } NominalInstanceInner::NonTuple(class) => Type::NominalInstance(NominalInstanceType( NominalInstanceInner::NonTuple(class.normalized_impl(db, visitor)), )), NominalInstanceInner::Object => Type::object(), } } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { match self.0 { NominalInstanceInner::ExactTuple(tuple) => { Some(Self(NominalInstanceInner::ExactTuple( tuple.recursive_type_normalized_impl(db, div, nested)?, ))) } NominalInstanceInner::NonTuple(class) => Some(Self(NominalInstanceInner::NonTuple( class.recursive_type_normalized_impl(db, div, nested)?, ))), NominalInstanceInner::Object => Some(Self(NominalInstanceInner::Object)), } } pub(super) fn has_relation_to_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { match (self.0, other.0) { (_, NominalInstanceInner::Object) => ConstraintSet::from(true), ( NominalInstanceInner::ExactTuple(tuple1), NominalInstanceInner::ExactTuple(tuple2), ) => tuple1.has_relation_to_impl( db, tuple2, inferable, relation, relation_visitor, disjointness_visitor, ), _ => self.class(db).has_relation_to_impl( db, other.class(db), inferable, relation, relation_visitor, disjointness_visitor, ), } } pub(super) fn is_equivalent_to_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, visitor: &IsEquivalentVisitor<'db>, ) -> ConstraintSet<'db> { match (self.0, other.0) { ( NominalInstanceInner::ExactTuple(tuple1), NominalInstanceInner::ExactTuple(tuple2), ) => tuple1.is_equivalent_to_impl(db, tuple2, inferable, visitor), (NominalInstanceInner::Object, NominalInstanceInner::Object) => { ConstraintSet::from(true) } (NominalInstanceInner::NonTuple(class1), NominalInstanceInner::NonTuple(class2)) => { class1.is_equivalent_to_impl(db, class2, inferable, visitor) } _ => ConstraintSet::from(false), } } pub(super) fn is_disjoint_from_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, disjointness_visitor: &IsDisjointVisitor<'db>, relation_visitor: &HasRelationToVisitor<'db>, ) -> ConstraintSet<'db> { if self.is_object() || other.is_object() { return ConstraintSet::from(false); } let mut result = ConstraintSet::from(false); if let Some(self_spec) = self.tuple_spec(db) { if let Some(other_spec) = other.tuple_spec(db) { let compatible = self_spec.is_disjoint_from_impl( db, &other_spec, inferable, disjointness_visitor, relation_visitor, ); if result.union(db, compatible).is_always_satisfied(db) { return result; } } } result.or(db, || { ConstraintSet::from(!(self.class(db)).could_coexist_in_mro_with(db, other.class(db))) }) } pub(super) fn is_singleton(self, db: &'db dyn Db) -> bool { match self.0 { // The empty tuple is a singleton on CPython and PyPy, but not on other Python // implementations such as GraalPy. Its *use* as a singleton is discouraged and // should not be relied on for type narrowing, so we do not treat it as one. // See: // https://docs.python.org/3/reference/expressions.html#parenthesized-forms NominalInstanceInner::ExactTuple(_) | NominalInstanceInner::Object => false, NominalInstanceInner::NonTuple(class) => class .known(db) .map(KnownClass::is_singleton) .unwrap_or_else(|| is_single_member_enum(db, class.class_literal(db).0)), } } pub(super) fn is_single_valued(self, db: &'db dyn Db) -> bool { match self.0 { NominalInstanceInner::ExactTuple(tuple) => tuple.is_single_valued(db), NominalInstanceInner::Object => false, NominalInstanceInner::NonTuple(class) => class .known(db) .and_then(KnownClass::is_single_valued) .or_else(|| Some(self.tuple_spec(db)?.is_single_valued(db))) .unwrap_or_else(|| is_single_member_enum(db, class.class_literal(db).0)), } } pub(super) fn to_meta_type(self, db: &'db dyn Db) -> Type<'db> { SubclassOfType::from(db, self.class(db)) } pub(super) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Type<'db> { match self.0 { NominalInstanceInner::ExactTuple(tuple) => { Type::tuple(tuple.apply_type_mapping_impl(db, type_mapping, tcx, visitor)) } NominalInstanceInner::NonTuple(class) => { Type::NominalInstance(NominalInstanceType(NominalInstanceInner::NonTuple( class.apply_type_mapping_impl(db, type_mapping, tcx, visitor), ))) } NominalInstanceInner::Object => Type::object(), } } pub(super) fn find_legacy_typevars_impl( self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { match self.0 { NominalInstanceInner::ExactTuple(tuple) => { tuple.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } NominalInstanceInner::NonTuple(class) => { class.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } NominalInstanceInner::Object => {} } } } impl<'db> From<NominalInstanceType<'db>> for Type<'db> { fn from(value: NominalInstanceType<'db>) -> Self { Self::NominalInstance(value) } } /// [`NominalInstanceType`] is split into two variants internally as a pure /// optimization to avoid having to materialize the [`ClassType`] for tuple /// instances where it would be unnecessary (this is somewhat expensive!). #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, salsa::Update, get_size2::GetSize)] enum NominalInstanceInner<'db> { /// An instance of `object`. /// /// We model it with a dedicated enum variant since its use as "the type of all values" is so /// prevalent and foundational, and it's useful to be able to instantiate this without having /// to load the definition of `object` from the typeshed. Object, /// A tuple type, e.g. `tuple[int, str]`. /// /// Note that the type `tuple[int, str]` includes subtypes of `tuple[int, str]`, /// but those subtypes would be represented using the `NonTuple` variant. ExactTuple(TupleType<'db>), /// Any instance type that does not represent some kind of instance of the /// builtin `tuple` class. /// /// This variant includes types that are subtypes of "exact tuple" types, /// because they represent "all instances of a class that is a tuple subclass". NonTuple(ClassType<'db>), } pub(crate) struct SliceLiteral { pub(crate) start: Option<i32>, pub(crate) stop: Option<i32>, pub(crate) step: Option<i32>, } impl<'db> VarianceInferable<'db> for NominalInstanceType<'db> { fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance { self.class(db).variance_of(db, typevar) } } /// A `ProtocolInstanceType` represents the set of all possible runtime objects /// that conform to the interface described by a certain protocol. #[derive( Copy, Clone, Debug, Eq, PartialEq, Hash, salsa::Update, PartialOrd, Ord, get_size2::GetSize, )] pub struct ProtocolInstanceType<'db> { pub(super) inner: Protocol<'db>, // Keep the inner field here private, // so that the only way of constructing `ProtocolInstanceType` instances // is through the `Type::instance` constructor function. _phantom: PhantomData<()>, } pub(super) fn walk_protocol_instance_type<'db, V: super::visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, protocol: ProtocolInstanceType<'db>, visitor: &V, ) { if visitor.should_visit_lazy_type_attributes() { walk_protocol_interface(db, protocol.inner.interface(db), visitor); } else { match protocol.inner { Protocol::FromClass(class) => { if let Some(specialization) = class.class_literal(db).1 { walk_specialization(db, specialization, visitor); } } Protocol::Synthesized(synthesized) => { walk_protocol_interface(db, synthesized.interface(), visitor); } } } } impl<'db> ProtocolInstanceType<'db> { // Keep this method private, so that the only way of constructing `ProtocolInstanceType` // instances is through the `Type::instance` constructor function. fn from_class(class: ProtocolClass<'db>) -> Self { Self { inner: Protocol::FromClass(class), _phantom: PhantomData, } } // Keep this method private, so that the only way of constructing `ProtocolInstanceType` // instances is through the `Type::instance` constructor function. fn synthesized(synthesized: SynthesizedProtocolType<'db>) -> Self { Self { inner: Protocol::Synthesized(synthesized), _phantom: PhantomData, } } /// If this is a class-based protocol, convert the protocol-instance into a nominal instance. /// /// If this is a synthesized protocol that does not correspond to a class definition /// in source code, return `None`. These are "pure" abstract types, that cannot be /// treated in a nominal way. pub(super) fn to_nominal_instance(self) -> Option<NominalInstanceType<'db>> { match self.inner { Protocol::FromClass(class) => { Some(NominalInstanceType(NominalInstanceInner::NonTuple(*class))) } Protocol::Synthesized(_) => None, } } /// Return the meta-type of this protocol-instance type. pub(super) fn to_meta_type(self, db: &'db dyn Db) -> Type<'db> { match self.inner { Protocol::FromClass(class) => SubclassOfType::from(db, class), // TODO: we can and should do better here. // // This is supported by mypy, and should be supported by us as well. // We'll need to come up with a better solution for the meta-type of // synthesized protocols to solve this: // // ```py // from typing import Callable // // def foo(x: Callable[[], int]) -> None: // reveal_type(type(x)) # mypy: "type[def (builtins.int) -> builtins.str]" // reveal_type(type(x).__call__) # mypy: "def (*args: Any, **kwds: Any) -> Any" // ``` Protocol::Synthesized(_) => KnownClass::Type.to_instance(db), } } /// Return `true` if this protocol is a supertype of `object`. /// /// This indicates that the protocol represents the same set of possible runtime objects /// as `object` (since `object` is the universal set of *all* possible runtime objects!). /// Such a protocol is therefore an equivalent type to `object`, which would in fact be /// normalised to `object`. pub(super) fn is_equivalent_to_object(self, db: &'db dyn Db) -> bool { #[salsa::tracked(cycle_initial=initial, heap_size=ruff_memory_usage::heap_size)] fn is_equivalent_to_object_inner<'db>( db: &'db dyn Db, protocol: ProtocolInstanceType<'db>, _: (), ) -> bool { Type::object() .satisfies_protocol( db, protocol, InferableTypeVars::None, TypeRelation::Subtyping, &HasRelationToVisitor::default(), &IsDisjointVisitor::default(), ) .is_always_satisfied(db) } fn initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _value: ProtocolInstanceType<'db>, _: (), ) -> bool { true } is_equivalent_to_object_inner(db, self, ()) } /// Return a "normalized" version of this `Protocol` type. /// /// See [`Type::normalized`] for more details. pub(super) fn normalized(self, db: &'db dyn Db) -> Type<'db> { self.normalized_impl(db, &NormalizedVisitor::default()) } /// Return a "normalized" version of this `Protocol` type. /// /// See [`Type::normalized`] for more details. pub(super) fn normalized_impl( self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>, ) -> Type<'db> { if self.is_equivalent_to_object(db) { return Type::object(); } match self.inner { Protocol::FromClass(_) => Type::ProtocolInstance(Self::synthesized( SynthesizedProtocolType::new(db, self.inner.interface(db), visitor), )), Protocol::Synthesized(_) => Type::ProtocolInstance(self), } } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self { inner: self.inner.recursive_type_normalized_impl(db, div, nested)?, _phantom: PhantomData, }) } /// Return `true` if this protocol type is equivalent to the protocol `other`. /// /// TODO: consider the types of the members as well as their existence pub(super) fn is_equivalent_to_impl( self, db: &'db dyn Db, other: Self, _inferable: InferableTypeVars<'_, 'db>, _visitor: &IsEquivalentVisitor<'db>, ) -> ConstraintSet<'db> { if self == other { return ConstraintSet::from(true); } let self_normalized = self.normalized(db); if self_normalized == Type::ProtocolInstance(other) { return ConstraintSet::from(true); } ConstraintSet::from(self_normalized == other.normalized(db)) } /// Return `true` if this protocol type is disjoint from the protocol `other`. /// /// TODO: a protocol `X` is disjoint from a protocol `Y` if `X` and `Y` /// have a member with the same name but disjoint types #[expect(clippy::unused_self)] pub(super) fn is_disjoint_from_impl( self, _db: &'db dyn Db, _other: Self, _inferable: InferableTypeVars<'_, 'db>, _visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { ConstraintSet::from(false) } pub(crate) fn instance_member(self, db: &'db dyn Db, name: &str) -> PlaceAndQualifiers<'db> { match self.inner { Protocol::FromClass(class) => class.instance_member(db, name), Protocol::Synthesized(synthesized) => synthesized.interface().instance_member(db, name), } } pub(super) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { match self.inner { Protocol::FromClass(class) => { Self::from_class(class.apply_type_mapping_impl(db, type_mapping, tcx, visitor)) } Protocol::Synthesized(synthesized) => Self::synthesized( synthesized.apply_type_mapping_impl(db, type_mapping, tcx, visitor), ), } } pub(super) fn find_legacy_typevars_impl( self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { match self.inner { Protocol::FromClass(class) => { class.find_legacy_typevars_impl(db, binding_context, typevars, visitor); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/protocol_class.rs
crates/ty_python_semantic/src/types/protocol_class.rs
use std::fmt::Write; use std::{collections::BTreeMap, ops::Deref}; use itertools::Itertools; use ruff_python_ast::name::Name; use rustc_hash::FxHashMap; use crate::types::{CallableTypeKind, TypeContext}; use crate::{ Db, FxOrderSet, place::{Definedness, Place, PlaceAndQualifiers, place_from_bindings, place_from_declarations}, semantic_index::{definition::Definition, place::ScopedPlaceId, place_table, use_def_map}, types::{ ApplyTypeMappingVisitor, BoundTypeVarInstance, CallableType, ClassBase, ClassLiteral, ClassType, FindLegacyTypeVarsVisitor, HasRelationToVisitor, InstanceFallbackShadowsNonDataDescriptor, IsDisjointVisitor, KnownFunction, MemberLookupPolicy, NormalizedVisitor, PropertyInstanceType, Signature, Type, TypeMapping, TypeQualifiers, TypeRelation, TypeVarVariance, VarianceInferable, constraints::{ConstraintSet, IteratorConstraintsExtension, OptionConstraintsExtension}, context::InferContext, diagnostic::report_undeclared_protocol_member, generics::InferableTypeVars, signatures::{Parameter, Parameters}, todo_type, }, }; impl<'db> ClassLiteral<'db> { /// Returns `Some` if this is a protocol class, `None` otherwise. pub(super) fn into_protocol_class(self, db: &'db dyn Db) -> Option<ProtocolClass<'db>> { self.is_protocol(db) .then_some(ProtocolClass(ClassType::NonGeneric(self))) } } impl<'db> ClassType<'db> { /// Returns `Some` if this is a protocol class, `None` otherwise. pub(super) fn into_protocol_class(self, db: &'db dyn Db) -> Option<ProtocolClass<'db>> { self.is_protocol(db).then_some(ProtocolClass(self)) } } /// Representation of a single `Protocol` class definition. /// /// # Ordering /// /// Ordering is based on the wrapped data's salsa-assigned id and not on its values. /// The id may change between runs, or when e.g. a `ProtocolClass` was garbage-collected and recreated. #[derive( Debug, Copy, Clone, PartialEq, Eq, Hash, salsa::Update, get_size2::GetSize, PartialOrd, Ord, )] pub(super) struct ProtocolClass<'db>(ClassType<'db>); impl<'db> ProtocolClass<'db> { /// Returns the protocol members of this class. /// /// A protocol's members define the interface declared by the protocol. /// They therefore determine how the protocol should behave with regards to /// assignability and subtyping. /// /// The list of members consists of all bindings and declarations that take place /// in the protocol's class body, except for a list of excluded attributes which should /// not be taken into account. (This list includes `__init__` and `__new__`, which can /// legally be defined on protocol classes but do not constitute protocol members.) /// /// It is illegal for a protocol class to have any instance attributes that are not declared /// in the protocol's class body. If any are assigned to, they are not taken into account in /// the protocol's list of members. pub(super) fn interface(self, db: &'db dyn Db) -> ProtocolInterface<'db> { let _span = tracing::trace_span!("protocol_members", "class='{}'", self.name(db)).entered(); cached_protocol_interface(db, *self) } pub(super) fn is_runtime_checkable(self, db: &'db dyn Db) -> bool { self.class_literal(db) .0 .known_function_decorators(db) .contains(&KnownFunction::RuntimeCheckable) } /// Iterate through the body of the protocol class. Check that all definitions /// in the protocol class body are either explicitly declared directly in the /// class body, or are declared in a superclass of the protocol class. pub(super) fn validate_members(self, context: &InferContext) { let db = context.db(); let interface = self.interface(db); let body_scope = self.class_literal(db).0.body_scope(db); let class_place_table = place_table(db, body_scope); for (symbol_id, mut bindings_iterator) in use_def_map(db, body_scope).all_end_of_scope_symbol_bindings() { let symbol_name = class_place_table.symbol(symbol_id).name(); if !interface.includes_member(db, symbol_name) { continue; } let has_declaration = self.iter_mro(db) .filter_map(ClassBase::into_class) .any(|superclass| { let superclass_scope = superclass.class_literal(db).0.body_scope(db); let Some(scoped_symbol_id) = place_table(db, superclass_scope).symbol_id(symbol_name) else { return false; }; !place_from_declarations( db, use_def_map(db, superclass_scope) .end_of_scope_declarations(ScopedPlaceId::Symbol(scoped_symbol_id)), ) .into_place_and_conflicting_declarations() .0 .place .is_undefined() }); if has_declaration { continue; } let Some(first_definition) = bindings_iterator.find_map(|binding| binding.binding.definition()) else { continue; }; report_undeclared_protocol_member(context, first_definition, self, class_place_table); } } pub(super) fn apply_type_mapping_impl<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { Self( self.0 .apply_type_mapping_impl(db, type_mapping, tcx, visitor), ) } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self( self.0.recursive_type_normalized_impl(db, div, nested)?, )) } } impl<'db> Deref for ProtocolClass<'db> { type Target = ClassType<'db>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'db> From<ProtocolClass<'db>> for Type<'db> { fn from(value: ProtocolClass<'db>) -> Self { Self::from(value.0) } } /// The interface of a protocol: the members of that protocol, and the types of those members. /// /// # Ordering /// Ordering is based on the protocol interface member's salsa-assigned id and not on its members. /// The id may change between runs, or when the protocol instance members was garbage collected and recreated. #[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub(super) struct ProtocolInterface<'db> { #[returns(ref)] inner: BTreeMap<Name, ProtocolMemberData<'db>>, } impl get_size2::GetSize for ProtocolInterface<'_> {} pub(super) fn walk_protocol_interface<'db, V: super::visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, interface: ProtocolInterface<'db>, visitor: &V, ) { for member in interface.members(db) { walk_protocol_member(db, &member, visitor); } } impl<'db> ProtocolInterface<'db> { /// Synthesize a new protocol interface with the given members. /// /// All created members will be covariant, read-only property members /// rather than method members or mutable attribute members. pub(super) fn with_property_members<'a, M>(db: &'db dyn Db, members: M) -> Self where M: IntoIterator<Item = (&'a str, Type<'db>)>, { let members: BTreeMap<_, _> = members .into_iter() .map(|(name, ty)| { // Synthesize a read-only property (one that has a getter but no setter) // which returns the specified type from its getter. let property_getter_signature = Signature::new( Parameters::new( db, [Parameter::positional_only(Some(Name::new_static("self")))], ), Some(ty.normalized(db)), ); let property_getter = Type::single_callable(db, property_getter_signature); let property = PropertyInstanceType::new(db, Some(property_getter), None); ( Name::new(name), ProtocolMemberData { qualifiers: TypeQualifiers::default(), kind: ProtocolMemberKind::Property(property), }, ) }) .collect(); Self::new(db, members) } fn empty(db: &'db dyn Db) -> Self { Self::new(db, BTreeMap::default()) } pub(super) fn members<'a>( self, db: &'db dyn Db, ) -> impl ExactSizeIterator<Item = ProtocolMember<'a, 'db>> where 'db: 'a, { self.inner(db).iter().map(|(name, data)| ProtocolMember { name, kind: data.kind, qualifiers: data.qualifiers, }) } fn member_by_name<'a>(self, db: &'db dyn Db, name: &'a str) -> Option<ProtocolMember<'a, 'db>> { self.inner(db).get(name).map(|data| ProtocolMember { name, kind: data.kind, qualifiers: data.qualifiers, }) } pub(super) fn includes_member(self, db: &'db dyn Db, name: &str) -> bool { self.inner(db).contains_key(name) } pub(super) fn instance_member(self, db: &'db dyn Db, name: &str) -> PlaceAndQualifiers<'db> { self.member_by_name(db, name) .map(|member| PlaceAndQualifiers { place: Place::bound(member.ty()), qualifiers: member.qualifiers(), }) .unwrap_or_else(|| Type::object().member(db, name)) } pub(super) fn has_relation_to_impl( self, db: &'db dyn Db, other: Self, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { other.members(db).when_all(db, |other_member| { self.member_by_name(db, other_member.name) .when_some_and(|our_member| match (our_member.kind, other_member.kind) { // Method members are always immutable; // they can never be subtypes of/assignable to mutable attribute members. (ProtocolMemberKind::Method(_), ProtocolMemberKind::Other(_)) => { ConstraintSet::from(false) } // A property member can only be a subtype of an attribute member // if the property is readable *and* writable. // // TODO: this should also consider the types of the members on both sides. (ProtocolMemberKind::Property(property), ProtocolMemberKind::Other(_)) => { ConstraintSet::from( property.getter(db).is_some() && property.setter(db).is_some(), ) } // A `@property` member can never be a subtype of a method member, as it is not necessarily // accessible on the meta-type, whereas a method member must be. (ProtocolMemberKind::Property(_), ProtocolMemberKind::Method(_)) => { ConstraintSet::from(false) } // But an attribute member *can* be a subtype of a method member, // providing it is marked `ClassVar` ( ProtocolMemberKind::Other(our_type), ProtocolMemberKind::Method(other_type), ) => ConstraintSet::from( our_member.qualifiers.contains(TypeQualifiers::CLASS_VAR), ) .and(db, || { our_type.has_relation_to_impl( db, Type::Callable(protocol_bind_self(db, other_type, None)), inferable, relation, relation_visitor, disjointness_visitor, ) }), ( ProtocolMemberKind::Method(our_method), ProtocolMemberKind::Method(other_method), ) => our_method.bind_self(db, None).has_relation_to_impl( db, protocol_bind_self(db, other_method, None), inferable, relation, relation_visitor, disjointness_visitor, ), ( ProtocolMemberKind::Other(our_type), ProtocolMemberKind::Other(other_type), ) => our_type .has_relation_to_impl( db, other_type, inferable, relation, relation_visitor, disjointness_visitor, ) .and(db, || { other_type.has_relation_to_impl( db, our_type, inferable, relation, relation_visitor, disjointness_visitor, ) }), // TODO: finish assignability/subtyping between two `@property` members, // and between a `@property` member and a member of a different kind. ( ProtocolMemberKind::Property(_) | ProtocolMemberKind::Method(_) | ProtocolMemberKind::Other(_), ProtocolMemberKind::Property(_), ) => ConstraintSet::from(true), }) }) } pub(super) fn normalized_impl(self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { Self::new( db, self.inner(db) .iter() .map(|(name, data)| (name.clone(), data.normalized_impl(db, visitor))) .collect::<BTreeMap<_, _>>(), ) } pub(super) fn recursive_type_normalized_impl( self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self::new( db, self.inner(db) .iter() .map(|(name, data)| { Some(( name.clone(), data.recursive_type_normalized_impl(db, div, nested)?, )) }) .collect::<Option<BTreeMap<_, _>>>()?, )) } pub(super) fn specialized_and_normalized<'a>( self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, ) -> Self { Self::new( db, self.inner(db) .iter() .map(|(name, data)| { ( name.clone(), data.apply_type_mapping_impl( db, type_mapping, tcx, &ApplyTypeMappingVisitor::default(), ) .normalized(db), ) }) .collect::<BTreeMap<_, _>>(), ) } pub(super) fn find_legacy_typevars_impl( self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { for data in self.inner(db).values() { data.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } } pub(super) fn display(self, db: &'db dyn Db) -> impl std::fmt::Display { struct ProtocolInterfaceDisplay<'db> { db: &'db dyn Db, interface: ProtocolInterface<'db>, } impl std::fmt::Display for ProtocolInterfaceDisplay<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_char('{')?; for (i, (name, data)) in self.interface.inner(self.db).iter().enumerate() { write!(f, "\"{name}\": {data}", data = data.display(self.db))?; if i < self.interface.inner(self.db).len() - 1 { f.write_str(", ")?; } } f.write_char('}') } } ProtocolInterfaceDisplay { db, interface: self, } } } impl<'db> VarianceInferable<'db> for ProtocolInterface<'db> { fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance { self.members(db) // TODO do we need to switch on member kind? .map(|member| member.ty().variance_of(db, typevar)) .collect() } } #[derive(Debug, PartialEq, Eq, Clone, Hash, salsa::Update, get_size2::GetSize)] pub(super) struct ProtocolMemberData<'db> { kind: ProtocolMemberKind<'db>, qualifiers: TypeQualifiers, } impl<'db> ProtocolMemberData<'db> { fn normalized(&self, db: &'db dyn Db) -> Self { self.normalized_impl(db, &NormalizedVisitor::default()) } fn normalized_impl(&self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { Self { kind: self.kind.normalized_impl(db, visitor), qualifiers: self.qualifiers, } } fn recursive_type_normalized_impl( &self, db: &'db dyn Db, div: Type<'db>, nested: bool, ) -> Option<Self> { Some(Self { kind: match &self.kind { ProtocolMemberKind::Method(callable) => ProtocolMemberKind::Method( callable.recursive_type_normalized_impl(db, div, nested)?, ), ProtocolMemberKind::Property(property) => ProtocolMemberKind::Property( property.recursive_type_normalized_impl(db, div, nested)?, ), ProtocolMemberKind::Other(ty) if nested => { ProtocolMemberKind::Other(ty.recursive_type_normalized_impl(db, div, true)?) } ProtocolMemberKind::Other(ty) => ProtocolMemberKind::Other( ty.recursive_type_normalized_impl(db, div, true) .unwrap_or(div), ), }, qualifiers: self.qualifiers, }) } fn apply_type_mapping_impl<'a>( &self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { Self { kind: self .kind .apply_type_mapping_impl(db, type_mapping, tcx, visitor), qualifiers: self.qualifiers, } } fn find_legacy_typevars_impl( &self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { self.kind .find_legacy_typevars_impl(db, binding_context, typevars, visitor); } fn display(&self, db: &'db dyn Db) -> impl std::fmt::Display { struct ProtocolMemberDataDisplay<'db> { db: &'db dyn Db, data: ProtocolMemberKind<'db>, qualifiers: TypeQualifiers, } impl std::fmt::Display for ProtocolMemberDataDisplay<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.data { ProtocolMemberKind::Method(callable) => { write!(f, "MethodMember(`{}`)", callable.display(self.db)) } ProtocolMemberKind::Property(property) => { let mut d = f.debug_struct("PropertyMember"); if let Some(getter) = property.getter(self.db) { d.field("getter", &format_args!("`{}`", &getter.display(self.db))); } if let Some(setter) = property.setter(self.db) { d.field("setter", &format_args!("`{}`", &setter.display(self.db))); } d.finish() } ProtocolMemberKind::Other(ty) => { f.write_str("AttributeMember(")?; write!(f, "`{}`", ty.display(self.db))?; if self.qualifiers.contains(TypeQualifiers::CLASS_VAR) { f.write_str("; ClassVar")?; } f.write_char(')') } } } } ProtocolMemberDataDisplay { db, data: self.kind, qualifiers: self.qualifiers, } } } #[derive(Debug, Copy, Clone, PartialEq, Eq, salsa::Update, Hash, get_size2::GetSize)] enum ProtocolMemberKind<'db> { Method(CallableType<'db>), Property(PropertyInstanceType<'db>), Other(Type<'db>), } impl<'db> ProtocolMemberKind<'db> { fn normalized_impl(&self, db: &'db dyn Db, visitor: &NormalizedVisitor<'db>) -> Self { match self { ProtocolMemberKind::Method(callable) => { ProtocolMemberKind::Method(callable.normalized_impl(db, visitor)) } ProtocolMemberKind::Property(property) => { ProtocolMemberKind::Property(property.normalized_impl(db, visitor)) } ProtocolMemberKind::Other(ty) => { ProtocolMemberKind::Other(ty.normalized_impl(db, visitor)) } } } fn apply_type_mapping_impl<'a>( &self, db: &'db dyn Db, type_mapping: &TypeMapping<'a, 'db>, tcx: TypeContext<'db>, visitor: &ApplyTypeMappingVisitor<'db>, ) -> Self { match self { ProtocolMemberKind::Method(callable) => ProtocolMemberKind::Method( callable.apply_type_mapping_impl(db, type_mapping, tcx, visitor), ), ProtocolMemberKind::Property(property) => ProtocolMemberKind::Property( property.apply_type_mapping_impl(db, type_mapping, tcx, visitor), ), ProtocolMemberKind::Other(ty) => ProtocolMemberKind::Other(ty.apply_type_mapping_impl( db, type_mapping, tcx, visitor, )), } } fn find_legacy_typevars_impl( &self, db: &'db dyn Db, binding_context: Option<Definition<'db>>, typevars: &mut FxOrderSet<BoundTypeVarInstance<'db>>, visitor: &FindLegacyTypeVarsVisitor<'db>, ) { match self { ProtocolMemberKind::Method(callable) => { callable.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } ProtocolMemberKind::Property(property) => { property.find_legacy_typevars_impl(db, binding_context, typevars, visitor); } ProtocolMemberKind::Other(ty) => { ty.find_legacy_typevars(db, binding_context, typevars); } } } } /// A single member of a protocol interface. #[derive(Debug, PartialEq, Eq)] pub(super) struct ProtocolMember<'a, 'db> { name: &'a str, kind: ProtocolMemberKind<'db>, qualifiers: TypeQualifiers, } fn walk_protocol_member<'db, V: super::visitor::TypeVisitor<'db> + ?Sized>( db: &'db dyn Db, member: &ProtocolMember<'_, 'db>, visitor: &V, ) { match member.kind { ProtocolMemberKind::Method(method) => visitor.visit_callable_type(db, method), ProtocolMemberKind::Property(property) => { visitor.visit_property_instance_type(db, property); } ProtocolMemberKind::Other(ty) => visitor.visit_type(db, ty), } } impl<'a, 'db> ProtocolMember<'a, 'db> { pub(super) fn name(&self) -> &'a str { self.name } pub(super) fn qualifiers(&self) -> TypeQualifiers { self.qualifiers } fn ty(&self) -> Type<'db> { match &self.kind { ProtocolMemberKind::Method(callable) => Type::Callable(*callable), ProtocolMemberKind::Property(property) => Type::PropertyInstance(*property), ProtocolMemberKind::Other(ty) => *ty, } } pub(super) fn has_disjoint_type_from( &self, db: &'db dyn Db, other: Type<'db>, inferable: InferableTypeVars<'_, 'db>, disjointness_visitor: &IsDisjointVisitor<'db>, relation_visitor: &HasRelationToVisitor<'db>, ) -> ConstraintSet<'db> { match &self.kind { // TODO: implement disjointness for property/method members as well as attribute members ProtocolMemberKind::Property(_) | ProtocolMemberKind::Method(_) => { ConstraintSet::from(false) } ProtocolMemberKind::Other(ty) => ty.is_disjoint_from_impl( db, other, inferable, disjointness_visitor, relation_visitor, ), } } /// Return `true` if `other` contains an attribute/method/property that satisfies /// the part of the interface defined by this protocol member. pub(super) fn is_satisfied_by( &self, db: &'db dyn Db, other: Type<'db>, inferable: InferableTypeVars<'_, 'db>, relation: TypeRelation<'db>, relation_visitor: &HasRelationToVisitor<'db>, disjointness_visitor: &IsDisjointVisitor<'db>, ) -> ConstraintSet<'db> { match &self.kind { ProtocolMemberKind::Method(method) => { // `__call__` members must be special cased for several reasons: // // 1. Looking up `__call__` on the meta-type of a `Callable` type returns `Place::Undefined` currently // 2. Looking up `__call__` on the meta-type of a function-literal type currently returns a type that // has an extremely vague signature (`(*args, **kwargs) -> Any`), which is not useful for protocol // checking. // 3. Looking up `__call__` on the meta-type of a class-literal, generic-alias or subclass-of type is // unfortunately not sufficient to obtain the `Callable` supertypes of these types, due to the // complex interaction between `__new__`, `__init__` and metaclass `__call__`. let attribute_type = if self.name == "__call__" { other } else { let Place::Defined(attribute_type, _, Definedness::AlwaysDefined, _) = other .invoke_descriptor_protocol( db, self.name, Place::Undefined.into(), InstanceFallbackShadowsNonDataDescriptor::No, MemberLookupPolicy::default(), ) .place else { return ConstraintSet::from(false); }; attribute_type }; // TODO: Instances of `typing.Self` in the protocol member should specialize to the // type that we are checking. Without this, we will treat `Self` as an inferable // typevar, and allow it to match against _any_ type. // // It's not very principled, but we also use the literal fallback type, instead of // `other` directly. This lets us check whether things like `Literal[0]` satisfy a // protocol that includes methods that have `typing.Self` annotations, without // overly constraining `Self` to that specific literal. // // With the new solver, we should be to replace all of this with an additional // constraint that enforces what `Self` can specialize to. let fallback_other = other.literal_fallback_instance(db).unwrap_or(other); attribute_type .try_upcast_to_callable(db) .when_some_and(|callables| { callables .map(|callable| callable.apply_self(db, fallback_other)) .has_relation_to_impl( db, protocol_bind_self(db, *method, Some(fallback_other)), inferable, relation, relation_visitor, disjointness_visitor, ) }) } // TODO: consider the types of the attribute on `other` for property members ProtocolMemberKind::Property(_) => ConstraintSet::from(matches!( other.member(db, self.name).place, Place::Defined(_, _, Definedness::AlwaysDefined, _) )), ProtocolMemberKind::Other(member_type) => { let Place::Defined(attribute_type, _, Definedness::AlwaysDefined, _) = other.member(db, self.name).place else { return ConstraintSet::from(false); }; member_type .has_relation_to_impl( db, attribute_type, inferable, relation, relation_visitor, disjointness_visitor, ) .and(db, || { attribute_type.has_relation_to_impl( db, *member_type, inferable, relation, relation_visitor, disjointness_visitor, ) }) } } } } /// Returns `true` if a declaration or binding to a given name in a protocol class body /// should be excluded from the list of protocol members of that class. /// /// The list of excluded members is subject to change between Python versions, /// especially for dunders, but it probably doesn't matter *too* much if this /// list goes out of date. It's up to date as of Python commit 87b1ea016b1454b1e83b9113fa9435849b7743aa /// (<https://github.com/python/cpython/blob/87b1ea016b1454b1e83b9113fa9435849b7743aa/Lib/typing.py#L1776-L1814>) fn excluded_from_proto_members(member: &str) -> bool { matches!( member, "_is_protocol" | "__non_callable_proto_members__" | "__static_attributes__" | "__orig_class__" | "__match_args__" | "__weakref__" | "__doc__" | "__parameters__" | "__module__" | "_MutableMapping__marker" | "__slots__" | "__dict__" | "__new__" | "__protocol_attrs__" | "__init__" | "__class_getitem__" | "__firstlineno__" | "__abstractmethods__" | "__orig_bases__" | "_is_runtime_protocol" | "__subclasshook__"
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/diagnostic.rs
crates/ty_python_semantic/src/types/diagnostic.rs
use super::call::CallErrorKind; use super::context::InferContext; use super::mro::DuplicateBaseError; use super::{ CallArguments, CallDunderError, ClassBase, ClassLiteral, KnownClass, add_inferred_python_version_hint_to_diagnostic, }; use crate::diagnostic::did_you_mean; use crate::diagnostic::format_enumeration; use crate::lint::{Level, LintRegistryBuilder, LintStatus}; use crate::place::Place; use crate::semantic_index::definition::{Definition, DefinitionKind}; use crate::semantic_index::place::{PlaceTable, ScopedPlaceId}; use crate::semantic_index::{global_scope, place_table, use_def_map}; use crate::suppression::FileSuppressionId; use crate::types::call::CallError; use crate::types::class::{CodeGeneratorKind, DisjointBase, DisjointBaseKind, MethodDecorator}; use crate::types::function::{FunctionDecorators, FunctionType, KnownFunction, OverloadLiteral}; use crate::types::infer::UnsupportedComparisonError; use crate::types::overrides::MethodKind; use crate::types::string_annotation::{ BYTE_STRING_TYPE_ANNOTATION, ESCAPE_CHARACTER_IN_FORWARD_ANNOTATION, FSTRING_TYPE_ANNOTATION, IMPLICIT_CONCATENATED_STRING_TYPE_ANNOTATION, INVALID_SYNTAX_IN_FORWARD_ANNOTATION, RAW_STRING_TYPE_ANNOTATION, }; use crate::types::tuple::TupleSpec; use crate::types::typed_dict::TypedDictSchema; use crate::types::{ BoundTypeVarInstance, ClassType, DynamicType, LintDiagnosticGuard, Protocol, ProtocolInstanceType, SpecialFormType, SubclassOfInner, Type, TypeContext, binding_type, protocol_class::ProtocolClass, }; use crate::types::{DataclassFlags, KnownInstanceType, MemberLookupPolicy, TypeVarInstance}; use crate::{Db, DisplaySettings, FxIndexMap, Program, declare_lint}; use itertools::Itertools; use ruff_db::{ diagnostic::{Annotation, Diagnostic, Span, SubDiagnostic, SubDiagnosticSeverity}, parsed::parsed_module, }; use ruff_diagnostics::{Edit, Fix}; use ruff_python_ast::name::Name; use ruff_python_ast::token::parentheses_iterator; use ruff_python_ast::{self as ast, AnyNodeRef, PythonVersion, StringFlags}; use ruff_text_size::{Ranged, TextRange}; use rustc_hash::FxHashSet; use std::fmt::{self, Formatter}; use ty_module_resolver::{Module, ModuleName}; /// Registers all known type check lints. pub(crate) fn register_lints(registry: &mut LintRegistryBuilder) { registry.register_lint(&AMBIGUOUS_PROTOCOL_MEMBER); registry.register_lint(&CALL_NON_CALLABLE); registry.register_lint(&CALL_TOP_CALLABLE); registry.register_lint(&POSSIBLY_MISSING_IMPLICIT_CALL); registry.register_lint(&CONFLICTING_ARGUMENT_FORMS); registry.register_lint(&CONFLICTING_DECLARATIONS); registry.register_lint(&CONFLICTING_METACLASS); registry.register_lint(&CYCLIC_CLASS_DEFINITION); registry.register_lint(&CYCLIC_TYPE_ALIAS_DEFINITION); registry.register_lint(&DEPRECATED); registry.register_lint(&DIVISION_BY_ZERO); registry.register_lint(&DUPLICATE_BASE); registry.register_lint(&DUPLICATE_KW_ONLY); registry.register_lint(&INSTANCE_LAYOUT_CONFLICT); registry.register_lint(&INCONSISTENT_MRO); registry.register_lint(&INDEX_OUT_OF_BOUNDS); registry.register_lint(&INVALID_KEY); registry.register_lint(&INVALID_ARGUMENT_TYPE); registry.register_lint(&INVALID_RETURN_TYPE); registry.register_lint(&INVALID_ASSIGNMENT); registry.register_lint(&INVALID_AWAIT); registry.register_lint(&INVALID_BASE); registry.register_lint(&INVALID_CONTEXT_MANAGER); registry.register_lint(&INVALID_DECLARATION); registry.register_lint(&INVALID_EXCEPTION_CAUGHT); registry.register_lint(&INVALID_GENERIC_CLASS); registry.register_lint(&INVALID_LEGACY_TYPE_VARIABLE); registry.register_lint(&INVALID_PARAMSPEC); registry.register_lint(&INVALID_TYPE_ALIAS_TYPE); registry.register_lint(&INVALID_NEWTYPE); registry.register_lint(&INVALID_METACLASS); registry.register_lint(&INVALID_OVERLOAD); registry.register_lint(&USELESS_OVERLOAD_BODY); registry.register_lint(&INVALID_PARAMETER_DEFAULT); registry.register_lint(&INVALID_PROTOCOL); registry.register_lint(&INVALID_NAMED_TUPLE); registry.register_lint(&INVALID_RAISE); registry.register_lint(&INVALID_SUPER_ARGUMENT); registry.register_lint(&INVALID_TYPE_ARGUMENTS); registry.register_lint(&INVALID_TYPE_CHECKING_CONSTANT); registry.register_lint(&INVALID_TYPE_FORM); registry.register_lint(&INVALID_TYPE_GUARD_DEFINITION); registry.register_lint(&INVALID_TYPE_GUARD_CALL); registry.register_lint(&INVALID_TYPE_VARIABLE_CONSTRAINTS); registry.register_lint(&MISSING_ARGUMENT); registry.register_lint(&NO_MATCHING_OVERLOAD); registry.register_lint(&NOT_SUBSCRIPTABLE); registry.register_lint(&NOT_ITERABLE); registry.register_lint(&UNSUPPORTED_BOOL_CONVERSION); registry.register_lint(&PARAMETER_ALREADY_ASSIGNED); registry.register_lint(&POSSIBLY_MISSING_ATTRIBUTE); registry.register_lint(&POSSIBLY_MISSING_IMPORT); registry.register_lint(&POSSIBLY_UNRESOLVED_REFERENCE); registry.register_lint(&SUBCLASS_OF_FINAL_CLASS); registry.register_lint(&OVERRIDE_OF_FINAL_METHOD); registry.register_lint(&TYPE_ASSERTION_FAILURE); registry.register_lint(&TOO_MANY_POSITIONAL_ARGUMENTS); registry.register_lint(&UNAVAILABLE_IMPLICIT_SUPER_ARGUMENTS); registry.register_lint(&UNDEFINED_REVEAL); registry.register_lint(&UNKNOWN_ARGUMENT); registry.register_lint(&POSITIONAL_ONLY_PARAMETER_AS_KWARG); registry.register_lint(&UNRESOLVED_ATTRIBUTE); registry.register_lint(&UNRESOLVED_IMPORT); registry.register_lint(&UNRESOLVED_REFERENCE); registry.register_lint(&UNSUPPORTED_BASE); registry.register_lint(&UNSUPPORTED_OPERATOR); registry.register_lint(&ZERO_STEPSIZE_IN_SLICE); registry.register_lint(&STATIC_ASSERT_ERROR); registry.register_lint(&INVALID_ATTRIBUTE_ACCESS); registry.register_lint(&REDUNDANT_CAST); registry.register_lint(&UNRESOLVED_GLOBAL); registry.register_lint(&MISSING_TYPED_DICT_KEY); registry.register_lint(&INVALID_METHOD_OVERRIDE); registry.register_lint(&INVALID_EXPLICIT_OVERRIDE); registry.register_lint(&SUPER_CALL_IN_NAMED_TUPLE_METHOD); registry.register_lint(&INVALID_FROZEN_DATACLASS_SUBCLASS); // String annotations registry.register_lint(&BYTE_STRING_TYPE_ANNOTATION); registry.register_lint(&ESCAPE_CHARACTER_IN_FORWARD_ANNOTATION); registry.register_lint(&FSTRING_TYPE_ANNOTATION); registry.register_lint(&IMPLICIT_CONCATENATED_STRING_TYPE_ANNOTATION); registry.register_lint(&INVALID_SYNTAX_IN_FORWARD_ANNOTATION); registry.register_lint(&RAW_STRING_TYPE_ANNOTATION); } declare_lint! { /// ## What it does /// Checks for calls to non-callable objects. /// /// ## Why is this bad? /// Calling a non-callable object will raise a `TypeError` at runtime. /// /// ## Examples /// ```python /// 4() # TypeError: 'int' object is not callable /// ``` pub(crate) static CALL_NON_CALLABLE = { summary: "detects calls to non-callable objects", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for calls to objects typed as `Top[Callable[..., T]]` (the infinite union of all /// callable types with return type `T`). /// /// ## Why is this bad? /// When an object is narrowed to `Top[Callable[..., object]]` (e.g., via `callable(x)` or /// `isinstance(x, Callable)`), we know the object is callable, but we don't know its /// precise signature. This type represents the set of all possible callable types /// (including, e.g., functions that take no arguments and functions that require arguments), /// so no specific set of arguments can be guaranteed to be valid. /// /// ## Examples /// ```python /// def f(x: object): /// if callable(x): /// x() # error: We know `x` is callable, but not what arguments it accepts /// ``` pub(crate) static CALL_TOP_CALLABLE = { summary: "detects calls to the top callable type", status: LintStatus::stable("0.0.7"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for implicit calls to possibly missing methods. /// /// ## Why is this bad? /// Expressions such as `x[y]` and `x * y` call methods /// under the hood (`__getitem__` and `__mul__` respectively). /// Calling a missing method will raise an `AttributeError` at runtime. /// /// ## Examples /// ```python /// import datetime /// /// class A: /// if datetime.date.today().weekday() != 6: /// def __getitem__(self, v): ... /// /// A()[0] # TypeError: 'A' object is not subscriptable /// ``` pub(crate) static POSSIBLY_MISSING_IMPLICIT_CALL = { summary: "detects implicit calls to possibly missing methods", status: LintStatus::stable("0.0.1-alpha.22"), default_level: Level::Warn, } } declare_lint! { /// ## What it does /// Checks whether an argument is used as both a value and a type form in a call. /// /// ## Why is this bad? /// Such calls have confusing semantics and often indicate a logic error. /// /// ## Examples /// ```python /// from typing import reveal_type /// from ty_extensions import is_singleton /// /// if flag: /// f = repr # Expects a value /// else: /// f = is_singleton # Expects a type form /// /// f(int) # error /// ``` pub(crate) static CONFLICTING_ARGUMENT_FORMS = { summary: "detects when an argument is used as both a value and a type form in a call", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks whether a variable has been declared as two conflicting types. /// /// ## Why is this bad /// A variable with two conflicting declarations likely indicates a mistake. /// Moreover, it could lead to incorrect or ill-defined type inference for /// other code that relies on these variables. /// /// ## Examples /// ```python /// if b: /// a: int /// else: /// a: str /// /// a = 1 /// ``` pub(crate) static CONFLICTING_DECLARATIONS = { summary: "detects conflicting declarations", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for class definitions where the metaclass of the class /// being created would not be a subclass of the metaclasses of /// all the class's bases. /// /// ## Why is it bad? /// Such a class definition raises a `TypeError` at runtime. /// /// ## Examples /// ```python /// class M1(type): ... /// class M2(type): ... /// class A(metaclass=M1): ... /// class B(metaclass=M2): ... /// /// # TypeError: metaclass conflict /// class C(A, B): ... /// ``` pub(crate) static CONFLICTING_METACLASS = { summary: "detects conflicting metaclasses", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for class definitions in stub files that inherit /// (directly or indirectly) from themselves. /// /// ## Why is it bad? /// Although forward references are natively supported in stub files, /// inheritance cycles are still disallowed, as it is impossible to /// resolve a consistent [method resolution order] for a class that /// inherits from itself. /// /// ## Examples /// ```python /// # foo.pyi /// class A(B): ... /// class B(A): ... /// ``` /// /// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order pub(crate) static CYCLIC_CLASS_DEFINITION = { summary: "detects cyclic class definitions", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for type alias definitions that (directly or mutually) refer to themselves. /// /// ## Why is it bad? /// Although it is permitted to define a recursive type alias, it is not meaningful /// to have a type alias whose expansion can only result in itself, and is therefore not allowed. /// /// ## Examples /// ```python /// type Itself = Itself /// /// type A = B /// type B = A /// ``` pub(crate) static CYCLIC_TYPE_ALIAS_DEFINITION = { summary: "detects cyclic type alias definitions", status: LintStatus::preview("1.0.0"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// It detects division by zero. /// /// ## Why is this bad? /// Dividing by zero raises a `ZeroDivisionError` at runtime. /// /// ## Rule status /// This rule is currently disabled by default because of the number of /// false positives it can produce. /// /// ## Examples /// ```python /// 5 / 0 /// ``` pub(crate) static DIVISION_BY_ZERO = { summary: "detects division by zero", status: LintStatus::preview("0.0.1-alpha.1"), default_level: Level::Ignore, } } declare_lint! { /// ## What it does /// Checks for uses of deprecated items /// /// ## Why is this bad? /// Deprecated items should no longer be used. /// /// ## Examples /// ```python /// @warnings.deprecated("use new_func instead") /// def old_func(): ... /// /// old_func() # emits [deprecated] diagnostic /// ``` pub(crate) static DEPRECATED = { summary: "detects uses of deprecated items", status: LintStatus::stable("0.0.1-alpha.16"), default_level: Level::Warn, } } declare_lint! { /// ## What it does /// Checks for class definitions with duplicate bases. /// /// ## Why is this bad? /// Class definitions with duplicate bases raise `TypeError` at runtime. /// /// ## Examples /// ```python /// class A: ... /// /// # TypeError: duplicate base class /// class B(A, A): ... /// ``` pub(crate) static DUPLICATE_BASE = { summary: "detects class definitions with duplicate bases", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for dataclass definitions with more than one field /// annotated with `KW_ONLY`. /// /// ## Why is this bad? /// `dataclasses.KW_ONLY` is a special marker used to /// emulate the `*` syntax in normal signatures. /// It can only be used once per dataclass. /// /// Attempting to annotate two different fields with /// it will lead to a runtime error. /// /// ## Examples /// ```python /// from dataclasses import dataclass, KW_ONLY /// /// @dataclass /// class A: # Crash at runtime /// b: int /// _1: KW_ONLY /// c: str /// _2: KW_ONLY /// d: bytes /// ``` pub(crate) static DUPLICATE_KW_ONLY = { summary: "detects dataclass definitions with more than one usage of `KW_ONLY`", status: LintStatus::stable("0.0.1-alpha.12"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for classes definitions which will fail at runtime due to /// "instance memory layout conflicts". /// /// This error is usually caused by attempting to combine multiple classes /// that define non-empty `__slots__` in a class's [Method Resolution Order] /// (MRO), or by attempting to combine multiple builtin classes in a class's /// MRO. /// /// ## Why is this bad? /// Inheriting from bases with conflicting instance memory layouts /// will lead to a `TypeError` at runtime. /// /// An instance memory layout conflict occurs when CPython cannot determine /// the memory layout instances of a class should have, because the instance /// memory layout of one of its bases conflicts with the instance memory layout /// of one or more of its other bases. /// /// For example, if a Python class defines non-empty `__slots__`, this will /// impact the memory layout of instances of that class. Multiple inheritance /// from more than one different class defining non-empty `__slots__` is not /// allowed: /// /// ```python /// class A: /// __slots__ = ("a", "b") /// /// class B: /// __slots__ = ("a", "b") # Even if the values are the same /// /// # TypeError: multiple bases have instance lay-out conflict /// class C(A, B): ... /// ``` /// /// An instance layout conflict can also be caused by attempting to use /// multiple inheritance with two builtin classes, due to the way that these /// classes are implemented in a CPython C extension: /// /// ```python /// class A(int, float): ... # TypeError: multiple bases have instance lay-out conflict /// ``` /// /// Note that pure-Python classes with no `__slots__`, or pure-Python classes /// with empty `__slots__`, are always compatible: /// /// ```python /// class A: ... /// class B: /// __slots__ = () /// class C: /// __slots__ = ("a", "b") /// /// # fine /// class D(A, B, C): ... /// ``` /// /// ## Known problems /// Classes that have "dynamic" definitions of `__slots__` (definitions do not consist /// of string literals, or tuples of string literals) are not currently considered disjoint /// bases by ty. /// /// Additionally, this check is not exhaustive: many C extensions (including several in /// the standard library) define classes that use extended memory layouts and thus cannot /// coexist in a single MRO. Since it is currently not possible to represent this fact in /// stub files, having a full knowledge of these classes is also impossible. When it comes /// to classes that do not define `__slots__` at the Python level, therefore, ty, currently /// only hard-codes a number of cases where it knows that a class will produce instances with /// an atypical memory layout. /// /// ## Further reading /// - [CPython documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) /// - [CPython documentation: Method Resolution Order](https://docs.python.org/3/glossary.html#term-method-resolution-order) /// /// [Method Resolution Order]: https://docs.python.org/3/glossary.html#term-method-resolution-order pub(crate) static INSTANCE_LAYOUT_CONFLICT = { summary: "detects class definitions that raise `TypeError` due to instance layout conflict", status: LintStatus::stable("0.0.1-alpha.12"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for protocol classes that will raise `TypeError` at runtime. /// /// ## Why is this bad? /// An invalidly defined protocol class may lead to the type checker inferring /// unexpected things. It may also lead to `TypeError`s at runtime. /// /// ## Examples /// A `Protocol` class cannot inherit from a non-`Protocol` class; /// this raises a `TypeError` at runtime: /// /// ```pycon /// >>> from typing import Protocol /// >>> class Foo(int, Protocol): ... /// ... /// Traceback (most recent call last): /// File "<python-input-1>", line 1, in <module> /// class Foo(int, Protocol): ... /// TypeError: Protocols can only inherit from other protocols, got <class 'int'> /// ``` pub(crate) static INVALID_PROTOCOL = { summary: "detects invalid protocol class definitions", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } // Added in #17750. declare_lint! { /// ## What it does /// Checks for protocol classes with members that will lead to ambiguous interfaces. /// /// ## Why is this bad? /// Assigning to an undeclared variable in a protocol class leads to an ambiguous /// interface which may lead to the type checker inferring unexpected things. It's /// recommended to ensure that all members of a protocol class are explicitly declared. /// /// ## Examples /// /// ```py /// from typing import Protocol /// /// class BaseProto(Protocol): /// a: int # fine (explicitly declared as `int`) /// def method_member(self) -> int: ... # fine: a method definition using `def` is considered a declaration /// c = "some variable" # error: no explicit declaration, leading to ambiguity /// b = method_member # error: no explicit declaration, leading to ambiguity /// /// # error: this creates implicit assignments of `d` and `e` in the protocol class body. /// # Were they really meant to be considered protocol members? /// for d, e in enumerate(range(42)): /// pass /// /// class SubProto(BaseProto, Protocol): /// a = 42 # fine (declared in superclass) /// ``` pub(crate) static AMBIGUOUS_PROTOCOL_MEMBER = { summary: "detects protocol classes with ambiguous interfaces", status: LintStatus::stable("0.0.1-alpha.20"), default_level: Level::Warn, } } declare_lint! { /// ## What it does /// Checks for invalidly defined `NamedTuple` classes. /// /// ## Why is this bad? /// An invalidly defined `NamedTuple` class may lead to the type checker /// drawing incorrect conclusions. It may also lead to `TypeError`s or /// `AttributeError`s at runtime. /// /// ## Examples /// A class definition cannot combine `NamedTuple` with other base classes /// in multiple inheritance; doing so raises a `TypeError` at runtime. The sole /// exception to this rule is `Generic[]`, which can be used alongside `NamedTuple` /// in a class's bases list. /// /// ```pycon /// >>> from typing import NamedTuple /// >>> class Foo(NamedTuple, object): ... /// TypeError: can only inherit from a NamedTuple type and Generic /// ``` /// /// Further, `NamedTuple` field names cannot start with an underscore: /// /// ```pycon /// >>> from typing import NamedTuple /// >>> class Foo(NamedTuple): /// ... _bar: int /// ValueError: Field names cannot start with an underscore: '_bar' /// ``` /// /// `NamedTuple` classes also have certain synthesized attributes (like `_asdict`, `_make`, /// `_replace`, etc.) that cannot be overwritten. Attempting to assign to these attributes /// without a type annotation will raise an `AttributeError` at runtime. /// /// ```pycon /// >>> from typing import NamedTuple /// >>> class Foo(NamedTuple): /// ... x: int /// ... _asdict = 42 /// AttributeError: Cannot overwrite NamedTuple attribute _asdict /// ``` pub(crate) static INVALID_NAMED_TUPLE = { summary: "detects invalid `NamedTuple` class definitions", status: LintStatus::stable("0.0.1-alpha.19"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for classes with an inconsistent [method resolution order] (MRO). /// /// ## Why is this bad? /// Classes with an inconsistent MRO will raise a `TypeError` at runtime. /// /// ## Examples /// ```python /// class A: ... /// class B(A): ... /// /// # TypeError: Cannot create a consistent method resolution order /// class C(A, B): ... /// ``` /// /// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order pub(crate) static INCONSISTENT_MRO = { summary: "detects class definitions with an inconsistent MRO", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for attempts to use an out of bounds index to get an item from /// a container. /// /// ## Why is this bad? /// Using an out of bounds index will raise an `IndexError` at runtime. /// /// ## Examples /// ```python /// t = (0, 1, 2) /// t[3] # IndexError: tuple index out of range /// ``` pub(crate) static INDEX_OUT_OF_BOUNDS = { summary: "detects index out of bounds errors", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } // Added in #19763. declare_lint! { /// ## What it does /// Checks for subscript accesses with invalid keys and `TypedDict` construction with an /// unknown key. /// /// ## Why is this bad? /// Subscripting with an invalid key will raise a `KeyError` at runtime. /// /// Creating a `TypedDict` with an unknown key is likely a mistake; if the `TypedDict` is /// `closed=true` it also violates the expectations of the type. /// /// ## Examples /// ```python /// from typing import TypedDict /// /// class Person(TypedDict): /// name: str /// age: int /// /// alice = Person(name="Alice", age=30) /// alice["height"] # KeyError: 'height' /// /// bob: Person = { "name": "Bob", "age": 30 } # typo! /// /// carol = Person(name="Carol", age=25) # typo! /// ``` pub(crate) static INVALID_KEY = { summary: "detects invalid subscript accesses or TypedDict literal keys", status: LintStatus::stable("0.0.1-alpha.17"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Detects call arguments whose type is not assignable to the corresponding typed parameter. /// /// ## Why is this bad? /// Passing an argument of a type the function (or callable object) does not accept violates /// the expectations of the function author and may cause unexpected runtime errors within the /// body of the function. /// /// ## Examples /// ```python /// def func(x: int): ... /// func("foo") # error: [invalid-argument-type] /// ``` pub(crate) static INVALID_ARGUMENT_TYPE = { summary: "detects call arguments whose type is not assignable to the corresponding typed parameter", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Detects returned values that can't be assigned to the function's annotated return type. /// /// ## Why is this bad? /// Returning an object of a type incompatible with the annotated return type may cause confusion to the user calling the function. /// /// ## Examples /// ```python /// def func() -> int: /// return "a" # error: [invalid-return-type] /// ``` pub(crate) static INVALID_RETURN_TYPE = { summary: "detects returned values that can't be assigned to the function's annotated return type", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for assignments where the type of the value /// is not [assignable to] the type of the assignee. /// /// ## Why is this bad? /// Such assignments break the rules of the type system and /// weaken a type checker's ability to accurately reason about your code. /// /// ## Examples /// ```python /// a: int = '' /// ``` /// /// [assignable to]: https://typing.python.org/en/latest/spec/glossary.html#term-assignable pub(crate) static INVALID_ASSIGNMENT = { summary: "detects invalid assignments", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for `await` being used with types that are not [Awaitable]. /// /// ## Why is this bad? /// Such expressions will lead to `TypeError` being raised at runtime. /// /// ## Examples /// ```python /// import asyncio /// /// class InvalidAwait: /// def __await__(self) -> int: /// return 5 /// /// async def main() -> None: /// await InvalidAwait() # error: [invalid-await] /// await 42 # error: [invalid-await] /// /// asyncio.run(main()) /// ``` /// /// [Awaitable]: https://docs.python.org/3/library/collections.abc.html#collections.abc.Awaitable pub(crate) static INVALID_AWAIT = { summary: "detects awaiting on types that don't support it", status: LintStatus::stable("0.0.1-alpha.19"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for class definitions that have bases which are not instances of `type`. /// /// ## Why is this bad? /// Class definitions with bases like this will lead to `TypeError` being raised at runtime. /// /// ## Examples /// ```python /// class A(42): ... # error: [invalid-base] /// ``` pub(crate) static INVALID_BASE = { summary: "detects class bases that will cause the class definition to raise an exception at runtime", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for class definitions that have bases which are unsupported by ty. /// /// ## Why is this bad? /// If a class has a base that is an instance of a complex type such as a union type, /// ty will not be able to resolve the [method resolution order] (MRO) for the class. /// This will lead to an inferior understanding of your codebase and unpredictable /// type-checking behavior. /// /// ## Examples /// ```python /// import datetime /// /// class A: ... /// class B: ... /// /// if datetime.date.today().weekday() != 6: /// C = A /// else: /// C = B /// /// class D(C): ... # error: [unsupported-base] /// ``` /// /// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order pub(crate) static UNSUPPORTED_BASE = { summary: "detects class bases that are unsupported as ty could not feasibly calculate the class's MRO", status: LintStatus::stable("0.0.1-alpha.7"), default_level: Level::Warn, } } declare_lint! { /// ## What it does /// Checks for expressions used in `with` statements /// that do not implement the context manager protocol. /// /// ## Why is this bad? /// Such a statement will raise `TypeError` at runtime. /// /// ## Examples /// ```python /// # TypeError: 'int' object does not support the context manager protocol /// with 1: /// print(2) /// ``` pub(crate) static INVALID_CONTEXT_MANAGER = { summary: "detects expressions used in with statements that don't implement the context manager protocol", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for declarations where the inferred type of an existing symbol /// is not [assignable to] its post-hoc declared type. /// /// ## Why is this bad? /// Such declarations break the rules of the type system and /// weaken a type checker's ability to accurately reason about your code. /// /// ## Examples /// ```python /// a = 1 /// a: str /// ``` /// /// [assignable to]: https://typing.python.org/en/latest/spec/glossary.html#term-assignable pub(crate) static INVALID_DECLARATION = { summary: "detects invalid declarations", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for exception handlers that catch non-exception classes. /// /// ## Why is this bad? /// Catching classes that do not inherit from `BaseException` will raise a `TypeError` at runtime. /// /// ## Example /// ```python /// try: /// 1 / 0 /// except 1:
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/string_annotation.rs
crates/ty_python_semantic/src/types/string_annotation.rs
use ruff_db::source::source_text; use ruff_python_ast::{self as ast, ModExpression}; use ruff_python_parser::Parsed; use ruff_text_size::Ranged; use crate::declare_lint; use crate::lint::{Level, LintStatus}; use super::context::InferContext; declare_lint! { /// ## What it does /// Checks for f-strings in type annotation positions. /// /// ## Why is this bad? /// Static analysis tools like ty can't analyze type annotations that use f-string notation. /// /// ## Examples /// ```python /// def test(): -> f"int": /// ... /// ``` /// /// Use instead: /// ```python /// def test(): -> "int": /// ... /// ``` pub(crate) static FSTRING_TYPE_ANNOTATION = { summary: "detects F-strings in type annotation positions", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for byte-strings in type annotation positions. /// /// ## Why is this bad? /// Static analysis tools like ty can't analyze type annotations that use byte-string notation. /// /// ## Examples /// ```python /// def test(): -> b"int": /// ... /// ``` /// /// Use instead: /// ```python /// def test(): -> "int": /// ... /// ``` pub(crate) static BYTE_STRING_TYPE_ANNOTATION = { summary: "detects byte strings in type annotation positions", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for raw-strings in type annotation positions. /// /// ## Why is this bad? /// Static analysis tools like ty can't analyze type annotations that use raw-string notation. /// /// ## Examples /// ```python /// def test(): -> r"int": /// ... /// ``` /// /// Use instead: /// ```python /// def test(): -> "int": /// ... /// ``` pub(crate) static RAW_STRING_TYPE_ANNOTATION = { summary: "detects raw strings in type annotation positions", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for implicit concatenated strings in type annotation positions. /// /// ## Why is this bad? /// Static analysis tools like ty can't analyze type annotations that use implicit concatenated strings. /// /// ## Examples /// ```python /// def test(): -> "Literal[" "5" "]": /// ... /// ``` /// /// Use instead: /// ```python /// def test(): -> "Literal[5]": /// ... /// ``` pub(crate) static IMPLICIT_CONCATENATED_STRING_TYPE_ANNOTATION = { summary: "detects implicit concatenated strings in type annotations", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for string-literal annotations where the string cannot be /// parsed as a Python expression. /// /// ## Why is this bad? /// Type annotations are expected to be Python expressions that /// describe the expected type of a variable, parameter, attribute or /// `return` statement. /// /// Type annotations are permitted to be string-literal expressions, in /// order to enable forward references to names not yet defined. /// However, it must be possible to parse the contents of that string /// literal as a normal Python expression. /// /// ## Example /// /// ```python /// def foo() -> "intstance of C": /// return 42 /// /// class C: ... /// ``` /// /// Use instead: /// /// ```python /// def foo() -> "C": /// return 42 /// /// class C: ... /// ``` /// /// ## References /// - [Typing spec: The meaning of annotations](https://typing.python.org/en/latest/spec/annotations.html#the-meaning-of-annotations) /// - [Typing spec: String annotations](https://typing.python.org/en/latest/spec/annotations.html#string-annotations) pub(crate) static INVALID_SYNTAX_IN_FORWARD_ANNOTATION = { summary: "detects invalid syntax in forward annotations", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } declare_lint! { /// ## What it does /// Checks for forward annotations that contain escape characters. /// /// ## Why is this bad? /// Static analysis tools like ty can't analyze type annotations that contain escape characters. /// /// ## Example /// /// ```python /// def foo() -> "intt\b": ... /// ``` pub(crate) static ESCAPE_CHARACTER_IN_FORWARD_ANNOTATION = { summary: "detects forward type annotations with escape characters", status: LintStatus::stable("0.0.1-alpha.1"), default_level: Level::Error, } } /// Parses the given expression as a string annotation. pub(crate) fn parse_string_annotation( context: &InferContext, string_expr: &ast::ExprStringLiteral, ) -> Option<Parsed<ModExpression>> { let file = context.file(); let db = context.db(); let _span = tracing::trace_span!("parse_string_annotation", string=?string_expr.range(), ?file) .entered(); let source = source_text(db, file); if let Some(string_literal) = string_expr.as_single_part_string() { let prefix = string_literal.flags.prefix(); if prefix.is_raw() { if let Some(builder) = context.report_lint(&RAW_STRING_TYPE_ANNOTATION, string_literal) { builder.into_diagnostic("Type expressions cannot use raw string literal"); } // Compare the raw contents (without quotes) of the expression with the parsed contents // contained in the string literal. } else if &source[string_literal.content_range()] == string_literal.as_str() { match ruff_python_parser::parse_string_annotation(source.as_str(), string_literal) { Ok(parsed) => return Some(parsed), Err(parse_error) => { if let Some(builder) = context.report_lint(&INVALID_SYNTAX_IN_FORWARD_ANNOTATION, string_literal) { builder.into_diagnostic(format_args!( "Syntax error in forward annotation: {}", parse_error.error )); } } } } else if let Some(builder) = context.report_lint(&ESCAPE_CHARACTER_IN_FORWARD_ANNOTATION, string_expr) { // The raw contents of the string doesn't match the parsed content. This could be the // case for annotations that contain escape sequences. builder.into_diagnostic("Type expressions cannot contain escape characters"); } } else if let Some(builder) = context.report_lint(&IMPLICIT_CONCATENATED_STRING_TYPE_ANNOTATION, string_expr) { // String is implicitly concatenated. builder.into_diagnostic("Type expressions cannot span multiple string literals"); } None }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/call/bind.rs
crates/ty_python_semantic/src/types/call/bind.rs
//! When analyzing a call site, we create _bindings_, which match and type-check the actual //! arguments against the parameters of the callable. Like with //! [signatures][crate::types::signatures], we have to handle the fact that the callable might be a //! union of types, each of which might contain multiple overloads. //! //! ### Tracing //! //! This module is instrumented with debug-level `tracing` messages. You can set the `TY_LOG` //! environment variable to see this output when testing locally. `tracing` log messages typically //! have a `target` field, which is the name of the module the message appears in — in this case, //! `ty_python_semantic::types::call::bind`. use std::borrow::Cow; use std::collections::HashSet; use std::fmt; use itertools::Itertools; use ruff_db::parsed::parsed_module; use ruff_python_ast::name::Name; use rustc_hash::{FxHashMap, FxHashSet}; use smallvec::{SmallVec, smallvec, smallvec_inline}; use super::{Argument, CallArguments, CallError, CallErrorKind, InferContext, Signature, Type}; use crate::db::Db; use crate::dunder_all::dunder_all_names; use crate::place::{Definedness, Place, known_module_symbol}; use crate::types::call::arguments::{Expansion, is_expandable_type}; use crate::types::constraints::ConstraintSet; use crate::types::diagnostic::{ CALL_NON_CALLABLE, CALL_TOP_CALLABLE, CONFLICTING_ARGUMENT_FORMS, INVALID_ARGUMENT_TYPE, MISSING_ARGUMENT, NO_MATCHING_OVERLOAD, PARAMETER_ALREADY_ASSIGNED, POSITIONAL_ONLY_PARAMETER_AS_KWARG, TOO_MANY_POSITIONAL_ARGUMENTS, UNKNOWN_ARGUMENT, }; use crate::types::enums::is_enum_class; use crate::types::function::{ DataclassTransformerFlags, DataclassTransformerParams, FunctionType, KnownFunction, OverloadLiteral, }; use crate::types::generics::{ InferableTypeVars, Specialization, SpecializationBuilder, SpecializationError, }; use crate::types::signatures::{Parameter, ParameterForm, ParameterKind, Parameters}; use crate::types::tuple::{TupleLength, TupleSpec, TupleType}; use crate::types::{ BoundMethodType, BoundTypeVarIdentity, BoundTypeVarInstance, CallableSignature, CallableType, CallableTypeKind, ClassLiteral, DATACLASS_FLAGS, DataclassFlags, DataclassParams, FieldInstance, KnownBoundMethodType, KnownClass, KnownInstanceType, MemberLookupPolicy, NominalInstanceType, PropertyInstanceType, SpecialFormType, TrackedConstraintSet, TypeAliasType, TypeContext, TypeVarVariance, UnionBuilder, UnionType, WrapperDescriptorKind, enums, list_members, todo_type, }; use crate::unpack::EvaluationMode; use crate::{DisplaySettings, Program}; use ruff_db::diagnostic::{Annotation, Diagnostic, SubDiagnostic, SubDiagnosticSeverity}; use ruff_python_ast::{self as ast, ArgOrKeyword, PythonVersion}; use ty_module_resolver::KnownModule; /// Binding information for a possible union of callables. At a call site, the arguments must be /// compatible with _all_ of the types in the union for the call to be valid. /// /// It's guaranteed that the wrapped bindings have no errors. #[derive(Debug, Clone)] pub(crate) struct Bindings<'db> { /// The type that is (hopefully) callable. callable_type: Type<'db>, /// The type of the instance being constructed, if this signature is for a constructor. constructor_instance_type: Option<Type<'db>>, /// By using `SmallVec`, we avoid an extra heap allocation for the common case of a non-union /// type. elements: SmallVec<[CallableBinding<'db>; 1]>, /// Whether each argument will be used as a value and/or a type form in this call. argument_forms: ArgumentForms, } impl<'db> Bindings<'db> { /// Creates a new `Bindings` from an iterator of [`Bindings`]s. Panics if the iterator is /// empty. pub(crate) fn from_union<I>(callable_type: Type<'db>, elements: I) -> Self where I: IntoIterator<Item = Bindings<'db>>, { let elements: SmallVec<_> = elements .into_iter() .flat_map(|s| s.elements.into_iter()) .collect(); assert!(!elements.is_empty()); Self { callable_type, elements, argument_forms: ArgumentForms::new(0), constructor_instance_type: None, } } pub(crate) fn replace_callable_type(&mut self, before: Type<'db>, after: Type<'db>) { if self.callable_type == before { self.callable_type = after; } for binding in &mut self.elements { binding.replace_callable_type(before, after); } } pub(crate) fn with_constructor_instance_type( mut self, constructor_instance_type: Type<'db>, ) -> Self { self.constructor_instance_type = Some(constructor_instance_type); for binding in &mut self.elements { binding.constructor_instance_type = Some(constructor_instance_type); for binding in &mut binding.overloads { binding.constructor_instance_type = Some(constructor_instance_type); } } self } pub(crate) fn set_dunder_call_is_possibly_unbound(&mut self) { for binding in &mut self.elements { binding.dunder_call_is_possibly_unbound = true; } } pub(crate) fn argument_forms(&self) -> &[Option<ParameterForm>] { &self.argument_forms.values } pub(crate) fn iter(&self) -> std::slice::Iter<'_, CallableBinding<'db>> { self.elements.iter() } pub(crate) fn map(self, f: impl Fn(CallableBinding<'db>) -> CallableBinding<'db>) -> Self { Self { callable_type: self.callable_type, argument_forms: self.argument_forms, constructor_instance_type: self.constructor_instance_type, elements: self.elements.into_iter().map(f).collect(), } } /// Match the arguments of a call site against the parameters of a collection of possibly /// unioned, possibly overloaded signatures. /// /// The returned bindings tell you which parameter (in each signature) each argument was /// matched against. You can then perform type inference on each argument with extra context /// about the expected parameter types. /// /// Once you have argument types available, you can call [`check_types`][Self::check_types] to /// verify that each argument type is assignable to the corresponding parameter type. pub(crate) fn match_parameters( mut self, db: &'db dyn Db, arguments: &CallArguments<'_, 'db>, ) -> Self { let mut argument_forms = ArgumentForms::new(arguments.len()); for binding in &mut self.elements { binding.match_parameters(db, arguments, &mut argument_forms); } argument_forms.shrink_to_fit(); self.argument_forms = argument_forms; self } /// Verify that the type of each argument is assignable to type of the parameter that it was /// matched to. /// /// You must provide an `argument_types` that was created from the same `arguments` that you /// provided to [`match_parameters`][Self::match_parameters]. /// /// The type context of the call expression is also used to infer the specialization of generic /// calls. /// /// We update the bindings to include the return type of the call, the bound types for all /// parameters, and any errors resulting from binding the call, all for each union element and /// overload (if any). pub(crate) fn check_types( mut self, db: &'db dyn Db, argument_types: &CallArguments<'_, 'db>, call_expression_tcx: TypeContext<'db>, dataclass_field_specifiers: &[Type<'db>], ) -> Result<Self, CallError<'db>> { match self.check_types_impl( db, argument_types, call_expression_tcx, dataclass_field_specifiers, ) { Ok(()) => Ok(self), Err(err) => Err(CallError(err, Box::new(self))), } } pub(crate) fn check_types_impl( &mut self, db: &'db dyn Db, argument_types: &CallArguments<'_, 'db>, call_expression_tcx: TypeContext<'db>, dataclass_field_specifiers: &[Type<'db>], ) -> Result<(), CallErrorKind> { for element in &mut self.elements { if let Some(mut updated_argument_forms) = element.check_types(db, argument_types, call_expression_tcx) { // If this element returned a new set of argument forms (indicating successful // argument type expansion), update the `Bindings` with these forms. updated_argument_forms.shrink_to_fit(); self.argument_forms = updated_argument_forms; } } self.evaluate_known_cases(db, argument_types, dataclass_field_specifiers); // In order of precedence: // // - If every union element is Ok, then the union is too. // - If any element has a BindingError, the union has a BindingError. // - If every element is NotCallable, then the union is also NotCallable. // - Otherwise, the elements are some mixture of Ok, NotCallable, and PossiblyNotCallable. // The union as a whole is PossiblyNotCallable. // // For example, the union type `Callable[[int], int] | None` may not be callable at all, // because the `None` element in this union has no `__call__` method. // // On the other hand, the union type `Callable[[int], int] | Callable[[str], str]` is // always *callable*, but it would produce a `BindingError` if an inhabitant of this type // was called with a single `int` argument passed in. That's because the second element in // the union doesn't accept an `int` when it's called: it only accepts a `str`. let mut all_ok = true; let mut any_binding_error = false; let mut all_not_callable = true; if self.argument_forms.conflicting.contains(&true) { all_ok = false; any_binding_error = true; all_not_callable = false; } for binding in &self.elements { let result = binding.as_result(); all_ok &= result.is_ok(); any_binding_error |= matches!(result, Err(CallErrorKind::BindingError)); all_not_callable &= matches!(result, Err(CallErrorKind::NotCallable)); } if all_ok { Ok(()) } else if any_binding_error { Err(CallErrorKind::BindingError) } else if all_not_callable { Err(CallErrorKind::NotCallable) } else { Err(CallErrorKind::PossiblyNotCallable) } } pub(crate) fn is_single(&self) -> bool { self.elements.len() == 1 } pub(crate) fn single_element(&self) -> Option<&CallableBinding<'db>> { match self.elements.as_slice() { [element] => Some(element), _ => None, } } pub(crate) fn callable_type(&self) -> Type<'db> { self.callable_type } pub(crate) fn constructor_instance_type(&self) -> Option<Type<'db>> { self.constructor_instance_type } /// Returns the return type of the call. For successful calls, this is the actual return type. /// For calls with binding errors, this is a type that best approximates the return type. For /// types that are not callable, returns `Type::Unknown`. pub(crate) fn return_type(&self, db: &'db dyn Db) -> Type<'db> { if let [binding] = self.elements.as_slice() { return binding.return_type(); } UnionType::from_elements(db, self.into_iter().map(CallableBinding::return_type)) } /// Report diagnostics for all of the errors that occurred when trying to match actual /// arguments to formal parameters. If the callable is a union, or has multiple overloads, we /// report a single diagnostic if we couldn't match any union element or overload. /// TODO: Update this to add subdiagnostics about how we failed to match each union element and /// overload. pub(crate) fn report_diagnostics( &self, context: &InferContext<'db, '_>, node: ast::AnyNodeRef, ) { // If all union elements are not callable, report that the union as a whole is not // callable. if self.into_iter().all(|b| !b.is_callable()) { if let Some(builder) = context.report_lint(&CALL_NON_CALLABLE, node) { builder.into_diagnostic(format_args!( "Object of type `{}` is not callable", self.callable_type().display(context.db()) )); } return; } for (index, conflicting_form) in self.argument_forms.conflicting.iter().enumerate() { if *conflicting_form { let node = BindingError::get_node(node, Some(index)); if let Some(builder) = context.report_lint(&CONFLICTING_ARGUMENT_FORMS, node) { builder.into_diagnostic( "Argument is used as both a value and a type form in call", ); } } } // If this is not a union, then report a diagnostic for any // errors as normal. if let Some(binding) = self.single_element() { binding.report_diagnostics(context, node, None); return; } for binding in self { let union_diag = UnionDiagnostic { callable_type: self.callable_type(), binding, }; binding.report_diagnostics(context, node, Some(&union_diag)); } } /// Evaluates the return type of certain known callables, where we have special-case logic to /// determine the return type in a way that isn't directly expressible in the type system. fn evaluate_known_cases( &mut self, db: &'db dyn Db, argument_types: &CallArguments<'_, 'db>, dataclass_field_specifiers: &[Type<'db>], ) { let to_bool = |ty: &Option<Type<'_>>, default: bool| -> bool { if let Some(Type::BooleanLiteral(value)) = ty { *value } else { // TODO: emit a diagnostic if we receive `bool` default } }; // Each special case listed here should have a corresponding clause in `Type::bindings`. for binding in &mut self.elements { let binding_type = binding.callable_type; for (overload_index, overload) in binding.matching_overloads_mut() { match binding_type { Type::KnownBoundMethod(KnownBoundMethodType::FunctionTypeDunderGet( function, )) => { if function.is_classmethod(db) { match overload.parameter_types() { [_, Some(owner)] => { overload.set_return_type(Type::BoundMethod( BoundMethodType::new(db, function, *owner), )); } [Some(instance), None] => { overload.set_return_type(Type::BoundMethod( BoundMethodType::new( db, function, instance.to_meta_type(db), ), )); } _ => {} } } else if function.is_staticmethod(db) { overload.set_return_type(Type::FunctionLiteral(function)); } else if let [Some(first), _] = overload.parameter_types() { if first.is_none(db) { overload.set_return_type(Type::FunctionLiteral(function)); } else { overload.set_return_type(Type::BoundMethod(BoundMethodType::new( db, function, *first, ))); } } } Type::WrapperDescriptor(WrapperDescriptorKind::FunctionTypeDunderGet) => { if let [Some(function_ty @ Type::FunctionLiteral(function)), ..] = overload.parameter_types() { if function.is_classmethod(db) { match overload.parameter_types() { [_, _, Some(owner)] => { overload.set_return_type(Type::BoundMethod( BoundMethodType::new(db, *function, *owner), )); } [_, Some(instance), None] => { overload.set_return_type(Type::BoundMethod( BoundMethodType::new( db, *function, instance.to_meta_type(db), ), )); } _ => {} } } else if function.is_staticmethod(db) { overload.set_return_type(*function_ty); } else { match overload.parameter_types() { [_, Some(instance), _] if instance.is_none(db) => { overload.set_return_type(*function_ty); } [_, Some(instance), _] => { overload.set_return_type(Type::BoundMethod( BoundMethodType::new(db, *function, *instance), )); } _ => {} } } } } Type::WrapperDescriptor(WrapperDescriptorKind::PropertyDunderGet) => { match overload.parameter_types() { [ Some(property @ Type::PropertyInstance(_)), Some(instance), .., ] if instance.is_none(db) => { overload.set_return_type(*property); } [ Some(Type::PropertyInstance(property)), Some(Type::KnownInstance(KnownInstanceType::TypeAliasType( type_alias, ))), .., ] if property.getter(db).is_some_and(|getter| { getter .as_function_literal() .is_some_and(|f| f.name(db) == "__name__") }) => { overload .set_return_type(Type::string_literal(db, type_alias.name(db))); } [ Some(Type::PropertyInstance(property)), Some(Type::KnownInstance(KnownInstanceType::TypeVar(typevar))), .., ] => { match property .getter(db) .and_then(Type::as_function_literal) .map(|f| f.name(db).as_str()) { Some("__name__") => { overload.set_return_type(Type::string_literal( db, typevar.name(db), )); } Some("__bound__") => { overload.set_return_type( typevar .upper_bound(db) .unwrap_or_else(|| Type::none(db)), ); } Some("__constraints__") => { overload.set_return_type(Type::heterogeneous_tuple( db, typevar.constraints(db).into_iter().flatten(), )); } Some("__default__") => { overload.set_return_type( typevar.default_type(db).unwrap_or_else(|| { KnownClass::NoDefaultType.to_instance(db) }), ); } _ => {} } } [Some(Type::PropertyInstance(property)), Some(instance), ..] => { if let Some(getter) = property.getter(db) { if let Ok(return_ty) = getter .try_call(db, &CallArguments::positional([*instance])) .map(|binding| binding.return_type(db)) { overload.set_return_type(return_ty); } else { overload.errors.push(BindingError::InternalCallError( "calling the getter failed", )); overload.set_return_type(Type::unknown()); } } else { overload .errors .push(BindingError::PropertyHasNoSetter(*property)); overload.set_return_type(Type::Never); } } _ => {} } } Type::KnownBoundMethod(KnownBoundMethodType::PropertyDunderGet(property)) => { match overload.parameter_types() { [Some(instance), ..] if instance.is_none(db) => { overload.set_return_type(Type::PropertyInstance(property)); } [Some(instance), ..] => { if let Some(getter) = property.getter(db) { if let Ok(return_ty) = getter .try_call(db, &CallArguments::positional([*instance])) .map(|binding| binding.return_type(db)) { overload.set_return_type(return_ty); } else { overload.errors.push(BindingError::InternalCallError( "calling the getter failed", )); overload.set_return_type(Type::unknown()); } } else { overload.set_return_type(Type::Never); overload.errors.push(BindingError::InternalCallError( "property has no getter", )); } } _ => {} } } Type::WrapperDescriptor(WrapperDescriptorKind::PropertyDunderSet) => { if let [ Some(Type::PropertyInstance(property)), Some(instance), Some(value), .., ] = overload.parameter_types() { if let Some(setter) = property.setter(db) { if let Err(_call_error) = setter .try_call(db, &CallArguments::positional([*instance, *value])) { overload.errors.push(BindingError::InternalCallError( "calling the setter failed", )); } } else { overload .errors .push(BindingError::PropertyHasNoSetter(*property)); } } } Type::KnownBoundMethod(KnownBoundMethodType::PropertyDunderSet(property)) => { if let [Some(instance), Some(value), ..] = overload.parameter_types() { if let Some(setter) = property.setter(db) { if let Err(_call_error) = setter .try_call(db, &CallArguments::positional([*instance, *value])) { overload.errors.push(BindingError::InternalCallError( "calling the setter failed", )); } } else { overload .errors .push(BindingError::PropertyHasNoSetter(property)); } } } Type::KnownBoundMethod(KnownBoundMethodType::StrStartswith(literal)) => { if let [Some(Type::StringLiteral(prefix)), None, None] = overload.parameter_types() { overload.set_return_type(Type::BooleanLiteral( literal.value(db).starts_with(prefix.value(db)), )); } } Type::DataclassTransformer(params) => { if let [Some(Type::FunctionLiteral(function))] = overload.parameter_types() { overload.set_return_type(Type::FunctionLiteral( function.with_dataclass_transformer_params(db, params), )); } } Type::BoundMethod(bound_method) if bound_method.self_instance(db).is_property_instance() => { match bound_method.function(db).name(db).as_str() { "setter" => { if let [Some(_), Some(setter)] = overload.parameter_types() { let mut ty_property = bound_method.self_instance(db); if let Type::PropertyInstance(property) = ty_property { ty_property = Type::PropertyInstance(PropertyInstanceType::new( db, property.getter(db), Some(*setter), )); } overload.set_return_type(ty_property); } } "getter" => { if let [Some(_), Some(getter)] = overload.parameter_types() { let mut ty_property = bound_method.self_instance(db); if let Type::PropertyInstance(property) = ty_property { ty_property = Type::PropertyInstance(PropertyInstanceType::new( db, Some(*getter), property.setter(db), )); } overload.set_return_type(ty_property); } } "deleter" => { // TODO: we do not store deleters yet let ty_property = bound_method.self_instance(db); overload.set_return_type(ty_property); } _ => { // Fall back to typeshed stubs for all other methods } } } // TODO: This branch can be removed once https://github.com/astral-sh/ty/issues/501 is resolved Type::BoundMethod(bound_method) if bound_method.function(db).name(db) == "__iter__" && is_enum_class(db, bound_method.self_instance(db)) => { if let Some(enum_instance) = bound_method.self_instance(db).to_instance(db) { overload.set_return_type( KnownClass::Iterator.to_specialized_instance(db, [enum_instance]), ); } } function @ Type::FunctionLiteral(function_type) if dataclass_field_specifiers.contains(&function) || function_type.is_known(db, KnownFunction::Field) => { // Helper to get the type of a keyword argument by name. We first try to get it from // the parameter binding (for explicit parameters), and then fall back to checking the // call site arguments (for field-specifier functions that use a `**kwargs` parameter, // instead of specifying `init`, `default` etc. explicitly). let get_argument_type = |name, fallback_to_default| -> Option<Type<'db>> { if let Ok(ty) = overload.parameter_type_by_name(name, fallback_to_default) { return ty; } argument_types.iter().find_map(|(arg, ty)| {
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/call/arguments.rs
crates/ty_python_semantic/src/types/call/arguments.rs
use std::borrow::Cow; use std::fmt::Display; use itertools::{Either, Itertools}; use ruff_python_ast as ast; use crate::Db; use crate::types::KnownClass; use crate::types::enums::{enum_member_literals, enum_metadata}; use crate::types::tuple::{Tuple, TupleType}; use super::Type; #[derive(Clone, Copy, Debug)] pub(crate) enum Argument<'a> { /// The synthetic `self` or `cls` argument, which doesn't appear explicitly at the call site. Synthetic, /// A positional argument. Positional, /// A starred positional argument (e.g. `*args`) containing the specified number of elements. Variadic, /// A keyword argument (e.g. `a=1`). Keyword(&'a str), /// The double-starred keywords argument (e.g. `**kwargs`). Keywords, } /// Arguments for a single call, in source order, along with inferred types for each argument. #[derive(Clone, Debug, Default)] pub(crate) struct CallArguments<'a, 'db> { arguments: Vec<Argument<'a>>, types: Vec<Option<Type<'db>>>, } impl<'a, 'db> CallArguments<'a, 'db> { fn new(arguments: Vec<Argument<'a>>, types: Vec<Option<Type<'db>>>) -> Self { debug_assert!(arguments.len() == types.len()); Self { arguments, types } } /// Create `CallArguments` from AST arguments. We will use the provided callback to obtain the /// type of each splatted argument, so that we can determine its length. All other arguments /// will remain uninitialized as `Unknown`. pub(crate) fn from_arguments( arguments: &'a ast::Arguments, mut infer_argument_type: impl FnMut(Option<&ast::Expr>, &ast::Expr) -> Type<'db>, ) -> Self { arguments .arguments_source_order() .map(|arg_or_keyword| match arg_or_keyword { ast::ArgOrKeyword::Arg(arg) => match arg { ast::Expr::Starred(ast::ExprStarred { value, .. }) => { let ty = infer_argument_type(Some(arg), value); (Argument::Variadic, Some(ty)) } _ => (Argument::Positional, None), }, ast::ArgOrKeyword::Keyword(ast::Keyword { arg, value, .. }) => { if let Some(arg) = arg { (Argument::Keyword(&arg.id), None) } else { let ty = infer_argument_type(None, value); (Argument::Keywords, Some(ty)) } } }) .collect() } /// Like [`Self::from_arguments`] but fills as much typing info in as possible. /// /// This currently only exists for the LSP usecase, and shouldn't be used in normal /// typechecking. pub(crate) fn from_arguments_typed( arguments: &'a ast::Arguments, mut infer_argument_type: impl FnMut(Option<&ast::Expr>, &ast::Expr) -> Type<'db>, ) -> Self { arguments .arguments_source_order() .map(|arg_or_keyword| match arg_or_keyword { ast::ArgOrKeyword::Arg(arg) => match arg { ast::Expr::Starred(ast::ExprStarred { value, .. }) => { let ty = infer_argument_type(Some(arg), value); (Argument::Variadic, Some(ty)) } _ => { let ty = infer_argument_type(None, arg); (Argument::Positional, Some(ty)) } }, ast::ArgOrKeyword::Keyword(ast::Keyword { arg, value, .. }) => { let ty = infer_argument_type(None, value); if let Some(arg) = arg { (Argument::Keyword(&arg.id), Some(ty)) } else { (Argument::Keywords, Some(ty)) } } }) .collect() } /// Create a [`CallArguments`] with no arguments. pub(crate) fn none() -> Self { Self::default() } /// Create a [`CallArguments`] from an iterator over non-variadic positional argument types. pub(crate) fn positional(positional_tys: impl IntoIterator<Item = Type<'db>>) -> Self { let types: Vec<_> = positional_tys.into_iter().map(Some).collect(); let arguments = vec![Argument::Positional; types.len()]; Self { arguments, types } } pub(crate) fn len(&self) -> usize { self.arguments.len() } pub(crate) fn types(&self) -> &[Option<Type<'db>>] { &self.types } pub(crate) fn iter_types(&self) -> impl Iterator<Item = Type<'db>> { self.types.iter().map(|ty| ty.unwrap_or_else(Type::unknown)) } /// Prepend an optional extra synthetic argument (for a `self` or `cls` parameter) to the front /// of this argument list. (If `bound_self` is none, we return the argument list /// unmodified.) pub(crate) fn with_self(&self, bound_self: Option<Type<'db>>) -> Cow<'_, Self> { if bound_self.is_some() { let arguments = std::iter::once(Argument::Synthetic) .chain(self.arguments.iter().copied()) .collect(); let types = std::iter::once(bound_self) .chain(self.types.iter().copied()) .collect(); Cow::Owned(CallArguments { arguments, types }) } else { Cow::Borrowed(self) } } pub(crate) fn iter(&self) -> impl Iterator<Item = (Argument<'a>, Option<Type<'db>>)> + '_ { (self.arguments.iter().copied()).zip(self.types.iter().copied()) } pub(crate) fn iter_mut( &mut self, ) -> impl Iterator<Item = (Argument<'a>, &mut Option<Type<'db>>)> + '_ { (self.arguments.iter().copied()).zip(self.types.iter_mut()) } /// Create a new [`CallArguments`] starting from the specified index. pub(super) fn start_from(&self, index: usize) -> Self { Self { arguments: self.arguments[index..].to_vec(), types: self.types[index..].to_vec(), } } /// Returns an iterator on performing [argument type expansion]. /// /// Each element of the iterator represents a set of argument lists, where each argument list /// contains the same arguments, but with one or more of the argument types expanded. /// /// [argument type expansion]: https://typing.python.org/en/latest/spec/overload.html#argument-type-expansion pub(super) fn expand(&self, db: &'db dyn Db) -> impl Iterator<Item = Expansion<'a, 'db>> + '_ { /// Maximum number of argument lists that can be generated in a single expansion step. static MAX_EXPANSIONS: usize = 512; /// Represents the state of the expansion process. enum State<'a, 'b, 'db> { LimitReached(usize), Expanding(ExpandingState<'a, 'b, 'db>), } /// Represents the expanding state with either the initial types or the expanded types. /// /// This is useful to avoid cloning the initial types vector if none of the types can be /// expanded. enum ExpandingState<'a, 'b, 'db> { Initial(&'b Vec<Option<Type<'db>>>), Expanded(Vec<CallArguments<'a, 'db>>), } impl<'db> ExpandingState<'_, '_, 'db> { fn len(&self) -> usize { match self { ExpandingState::Initial(_) => 1, ExpandingState::Expanded(expanded) => expanded.len(), } } fn iter(&self) -> impl Iterator<Item = &[Option<Type<'db>>]> + '_ { match self { ExpandingState::Initial(types) => { Either::Left(std::iter::once(types.as_slice())) } ExpandingState::Expanded(expanded) => { Either::Right(expanded.iter().map(CallArguments::types)) } } } } let mut index = 0; std::iter::successors( Some(State::Expanding(ExpandingState::Initial(&self.types))), move |previous| { let state = match previous { State::LimitReached(index) => return Some(State::LimitReached(*index)), State::Expanding(expanding_state) => expanding_state, }; // Find the next type that can be expanded. let expanded_types = loop { let arg_type = self.types.get(index)?; if let Some(arg_type) = arg_type { if let Some(expanded_types) = expand_type(db, *arg_type) { break expanded_types; } } index += 1; }; let expansion_size = expanded_types.len() * state.len(); if expansion_size > MAX_EXPANSIONS { tracing::debug!( "Skipping argument type expansion as it would exceed the \ maximum number of expansions ({MAX_EXPANSIONS})" ); return Some(State::LimitReached(index)); } let mut expanded_arguments = Vec::with_capacity(expansion_size); for pre_expanded_types in state.iter() { for subtype in &expanded_types { let mut new_expanded_types = pre_expanded_types.to_vec(); new_expanded_types[index] = Some(*subtype); expanded_arguments.push(CallArguments::new( self.arguments.clone(), new_expanded_types, )); } } // Increment the index to move to the next argument type for the next iteration. index += 1; Some(State::Expanding(ExpandingState::Expanded( expanded_arguments, ))) }, ) .skip(1) // Skip the initial state, which has no expanded types. .map(|state| match state { State::LimitReached(index) => Expansion::LimitReached(index), State::Expanding(ExpandingState::Initial(_)) => { unreachable!("initial state should be skipped") } State::Expanding(ExpandingState::Expanded(expanded)) => Expansion::Expanded(expanded), }) } pub(super) fn display(&self, db: &'db dyn Db) -> impl Display { struct DisplayCallArguments<'a, 'db> { call_arguments: &'a CallArguments<'a, 'db>, db: &'db dyn Db, } impl std::fmt::Display for DisplayCallArguments<'_, '_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("(")?; for (index, (argument, ty)) in self.call_arguments.iter().enumerate() { if index > 0 { write!(f, ", ")?; } match argument { Argument::Synthetic => write!( f, "self: {}", ty.unwrap_or_else(Type::unknown).display(self.db) )?, Argument::Positional => { write!(f, "{}", ty.unwrap_or_else(Type::unknown).display(self.db))?; } Argument::Variadic => { write!(f, "*{}", ty.unwrap_or_else(Type::unknown).display(self.db))?; } Argument::Keyword(name) => write!( f, "{}={}", name, ty.unwrap_or_else(Type::unknown).display(self.db) )?, Argument::Keywords => { write!(f, "**{}", ty.unwrap_or_else(Type::unknown).display(self.db))?; } } } f.write_str(")") } } DisplayCallArguments { call_arguments: self, db, } } } /// Represents a single element of the expansion process for argument types for [`expand`]. /// /// [`expand`]: CallArguments::expand pub(super) enum Expansion<'a, 'db> { /// Indicates that the expansion process has reached the maximum number of argument lists /// that can be generated in a single step. /// /// The contained `usize` is the index of the argument type which would have been expanded /// next, if not for the limit. LimitReached(usize), /// Contains the expanded argument lists, where each list contains the same arguments, but with /// one or more of the argument types expanded. Expanded(Vec<CallArguments<'a, 'db>>), } impl<'a, 'db> FromIterator<(Argument<'a>, Option<Type<'db>>)> for CallArguments<'a, 'db> { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = (Argument<'a>, Option<Type<'db>>)>, { let (arguments, types) = iter.into_iter().unzip(); Self { arguments, types } } } /// Returns `true` if the type can be expanded into its subtypes. /// /// In other words, it returns `true` if [`expand_type`] returns [`Some`] for the given type. pub(crate) fn is_expandable_type<'db>(db: &'db dyn Db, ty: Type<'db>) -> bool { match ty { Type::NominalInstance(instance) => { let class = instance.class(db); class.is_known(db, KnownClass::Bool) || instance.tuple_spec(db).is_some_and(|spec| match &*spec { Tuple::Fixed(fixed_length_tuple) => fixed_length_tuple .iter_all_elements() .any(|element| is_expandable_type(db, element)), Tuple::Variable(_) => false, }) || enum_metadata(db, class.class_literal(db).0).is_some() } Type::Union(_) => true, _ => false, } } /// Expands a type into its possible subtypes, if applicable. /// /// Returns [`None`] if the type cannot be expanded. fn expand_type<'db>(db: &'db dyn Db, ty: Type<'db>) -> Option<Vec<Type<'db>>> { // NOTE: Update `is_expandable_type` if this logic changes accordingly. match ty { Type::NominalInstance(instance) => { let class = instance.class(db); if class.is_known(db, KnownClass::Bool) { return Some(vec![ Type::BooleanLiteral(true), Type::BooleanLiteral(false), ]); } // If the class is a fixed-length tuple subtype, we expand it to its elements. if let Some(spec) = instance.tuple_spec(db) { return match &*spec { Tuple::Fixed(fixed_length_tuple) => { let expanded = fixed_length_tuple .iter_all_elements() .map(|element| { if let Some(expanded) = expand_type(db, element) { Either::Left(expanded.into_iter()) } else { Either::Right(std::iter::once(element)) } }) .multi_cartesian_product() .map(|types| Type::tuple(TupleType::heterogeneous(db, types))) .collect::<Vec<_>>(); if expanded.len() == 1 { // There are no elements in the tuple type that can be expanded. None } else { Some(expanded) } } Tuple::Variable(_) => None, }; } if let Some(enum_members) = enum_member_literals(db, class.class_literal(db).0, None) { return Some(enum_members.collect()); } None } Type::Union(union) => Some(union.elements(db).to_vec()), // We don't handle `type[A | B]` here because it's already stored in the expanded form // i.e., `type[A] | type[B]` which is handled by the `Type::Union` case. _ => None, } } #[cfg(test)] mod tests { use crate::db::tests::setup_db; use crate::types::tuple::TupleType; use crate::types::{KnownClass, Type, UnionType}; use super::expand_type; #[test] fn expand_union_type() { let db = setup_db(); let types = [ KnownClass::Int.to_instance(&db), KnownClass::Str.to_instance(&db), KnownClass::Bytes.to_instance(&db), ]; let union_type = UnionType::from_elements(&db, types); let expanded = expand_type(&db, union_type).unwrap(); assert_eq!(expanded.len(), types.len()); assert_eq!(expanded, types); } #[test] fn expand_bool_type() { let db = setup_db(); let bool_instance = KnownClass::Bool.to_instance(&db); let expanded = expand_type(&db, bool_instance).unwrap(); let expected_types = [Type::BooleanLiteral(true), Type::BooleanLiteral(false)]; assert_eq!(expanded.len(), expected_types.len()); assert_eq!(expanded, expected_types); } #[test] fn expand_tuple_type() { let db = setup_db(); let int_ty = KnownClass::Int.to_instance(&db); let str_ty = KnownClass::Str.to_instance(&db); let bytes_ty = KnownClass::Bytes.to_instance(&db); let bool_ty = KnownClass::Bool.to_instance(&db); let true_ty = Type::BooleanLiteral(true); let false_ty = Type::BooleanLiteral(false); // Empty tuple let empty_tuple = Type::empty_tuple(&db); let expanded = expand_type(&db, empty_tuple); assert!(expanded.is_none()); // None of the elements can be expanded. let tuple_type1 = Type::heterogeneous_tuple(&db, [int_ty, str_ty]); let expanded = expand_type(&db, tuple_type1); assert!(expanded.is_none()); // All elements can be expanded. let tuple_type2 = Type::heterogeneous_tuple( &db, [ bool_ty, UnionType::from_elements(&db, [int_ty, str_ty, bytes_ty]), ], ); let expected_types = [ Type::heterogeneous_tuple(&db, [true_ty, int_ty]), Type::heterogeneous_tuple(&db, [true_ty, str_ty]), Type::heterogeneous_tuple(&db, [true_ty, bytes_ty]), Type::heterogeneous_tuple(&db, [false_ty, int_ty]), Type::heterogeneous_tuple(&db, [false_ty, str_ty]), Type::heterogeneous_tuple(&db, [false_ty, bytes_ty]), ]; let expanded = expand_type(&db, tuple_type2).unwrap(); assert_eq!(expanded, expected_types); // Mixed set of elements where some can be expanded while others cannot be. let tuple_type3 = Type::heterogeneous_tuple( &db, [ bool_ty, int_ty, UnionType::from_elements(&db, [str_ty, bytes_ty]), str_ty, ], ); let expected_types = [ Type::heterogeneous_tuple(&db, [true_ty, int_ty, str_ty, str_ty]), Type::heterogeneous_tuple(&db, [true_ty, int_ty, bytes_ty, str_ty]), Type::heterogeneous_tuple(&db, [false_ty, int_ty, str_ty, str_ty]), Type::heterogeneous_tuple(&db, [false_ty, int_ty, bytes_ty, str_ty]), ]; let expanded = expand_type(&db, tuple_type3).unwrap(); assert_eq!(expanded, expected_types); // Variable-length tuples are not expanded. let variable_length_tuple = Type::tuple(TupleType::mixed( &db, [bool_ty], int_ty, [UnionType::from_elements(&db, [str_ty, bytes_ty]), str_ty], )); let expanded = expand_type(&db, variable_length_tuple); assert!(expanded.is_none()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/infer/builder.rs
crates/ty_python_semantic/src/types/infer/builder.rs
use std::iter; use itertools::{Either, EitherOrBoth, Itertools}; use ruff_db::diagnostic::{Annotation, Diagnostic, DiagnosticId, Severity, Span}; use ruff_db::files::File; use ruff_db::parsed::{ParsedModuleRef, parsed_module}; use ruff_db::source::source_text; use ruff_python_ast::visitor::{Visitor, walk_expr}; use ruff_python_ast::{ self as ast, AnyNodeRef, ExprContext, HasNodeIndex, NodeIndex, PythonVersion, }; use ruff_python_stdlib::builtins::version_builtin_was_added; use ruff_text_size::{Ranged, TextRange}; use rustc_hash::{FxHashMap, FxHashSet}; use smallvec::SmallVec; use ty_module_resolver::{ KnownModule, ModuleName, ModuleNameResolutionError, ModuleResolveMode, file_to_module, resolve_module, search_paths, }; use super::{ DefinitionInference, DefinitionInferenceExtra, ExpressionInference, ExpressionInferenceExtra, InferenceRegion, ScopeInference, ScopeInferenceExtra, infer_deferred_types, infer_definition_types, infer_expression_types, infer_same_file_expression_type, infer_unpack_types, }; use crate::diagnostic::format_enumeration; use crate::node_key::NodeKey; use crate::place::{ ConsideredDefinitions, Definedness, LookupError, Place, PlaceAndQualifiers, TypeOrigin, builtins_module_scope, builtins_symbol, class_body_implicit_symbol, explicit_global_symbol, global_symbol, module_type_implicit_global_declaration, module_type_implicit_global_symbol, place, place_from_bindings, place_from_declarations, typing_extensions_symbol, }; use crate::semantic_index::ast_ids::node_key::ExpressionNodeKey; use crate::semantic_index::ast_ids::{HasScopedUseId, ScopedUseId}; use crate::semantic_index::definition::{ AnnotatedAssignmentDefinitionKind, AssignmentDefinitionKind, ComprehensionDefinitionKind, Definition, DefinitionKind, DefinitionNodeKey, DefinitionState, ExceptHandlerDefinitionKind, ForStmtDefinitionKind, TargetKind, WithItemDefinitionKind, }; use crate::semantic_index::expression::{Expression, ExpressionKind}; use crate::semantic_index::narrowing_constraints::ConstraintKey; use crate::semantic_index::place::{PlaceExpr, PlaceExprRef}; use crate::semantic_index::scope::{ FileScopeId, NodeWithScopeKind, NodeWithScopeRef, ScopeId, ScopeKind, }; use crate::semantic_index::symbol::{ScopedSymbolId, Symbol}; use crate::semantic_index::{ ApplicableConstraints, EnclosingSnapshotResult, SemanticIndex, place_table, }; use crate::subscript::{PyIndex, PySlice}; use crate::types::call::bind::{CallableDescription, MatchingOverloadIndex}; use crate::types::call::{Binding, Bindings, CallArguments, CallError, CallErrorKind}; use crate::types::class::{CodeGeneratorKind, FieldKind, MetaclassErrorKind, MethodDecorator}; use crate::types::context::{InNoTypeCheck, InferContext}; use crate::types::cyclic::CycleDetector; use crate::types::diagnostic::{ self, CALL_NON_CALLABLE, CONFLICTING_DECLARATIONS, CONFLICTING_METACLASS, CYCLIC_CLASS_DEFINITION, CYCLIC_TYPE_ALIAS_DEFINITION, DIVISION_BY_ZERO, DUPLICATE_KW_ONLY, INCONSISTENT_MRO, INVALID_ARGUMENT_TYPE, INVALID_ASSIGNMENT, INVALID_ATTRIBUTE_ACCESS, INVALID_BASE, INVALID_DECLARATION, INVALID_GENERIC_CLASS, INVALID_KEY, INVALID_LEGACY_TYPE_VARIABLE, INVALID_METACLASS, INVALID_NAMED_TUPLE, INVALID_NEWTYPE, INVALID_OVERLOAD, INVALID_PARAMETER_DEFAULT, INVALID_PARAMSPEC, INVALID_PROTOCOL, INVALID_TYPE_ARGUMENTS, INVALID_TYPE_FORM, INVALID_TYPE_GUARD_CALL, INVALID_TYPE_VARIABLE_CONSTRAINTS, IncompatibleBases, NOT_SUBSCRIPTABLE, POSSIBLY_MISSING_ATTRIBUTE, POSSIBLY_MISSING_IMPLICIT_CALL, POSSIBLY_MISSING_IMPORT, SUBCLASS_OF_FINAL_CLASS, TypedDictDeleteErrorKind, UNDEFINED_REVEAL, UNRESOLVED_ATTRIBUTE, UNRESOLVED_GLOBAL, UNRESOLVED_IMPORT, UNRESOLVED_REFERENCE, UNSUPPORTED_OPERATOR, USELESS_OVERLOAD_BODY, hint_if_stdlib_attribute_exists_on_other_versions, hint_if_stdlib_submodule_exists_on_other_versions, report_attempted_protocol_instantiation, report_bad_dunder_set_call, report_bad_frozen_dataclass_inheritance, report_cannot_delete_typed_dict_key, report_cannot_pop_required_field_on_typed_dict, report_duplicate_bases, report_implicit_return_type, report_index_out_of_bounds, report_instance_layout_conflict, report_invalid_arguments_to_annotated, report_invalid_assignment, report_invalid_attribute_assignment, report_invalid_exception_caught, report_invalid_exception_cause, report_invalid_exception_raised, report_invalid_exception_tuple_caught, report_invalid_generator_function_return_type, report_invalid_key_on_typed_dict, report_invalid_or_unsupported_base, report_invalid_return_type, report_invalid_type_checking_constant, report_invalid_type_param_order, report_named_tuple_field_with_leading_underscore, report_namedtuple_field_without_default_after_field_with_default, report_not_subscriptable, report_possibly_missing_attribute, report_possibly_unresolved_reference, report_rebound_typevar, report_slice_step_size_zero, report_unsupported_augmented_assignment, report_unsupported_binary_operation, report_unsupported_comparison, }; use crate::types::function::{ FunctionDecorators, FunctionLiteral, FunctionType, KnownFunction, OverloadLiteral, is_implicit_classmethod, is_implicit_staticmethod, }; use crate::types::generics::{ GenericContext, InferableTypeVars, LegacyGenericBase, SpecializationBuilder, bind_typevar, enclosing_generic_contexts, typing_self, }; use crate::types::infer::nearest_enclosing_function; use crate::types::instance::SliceLiteral; use crate::types::mro::MroErrorKind; use crate::types::newtype::NewType; use crate::types::subclass_of::SubclassOfInner; use crate::types::tuple::{Tuple, TupleLength, TupleSpec, TupleType}; use crate::types::typed_dict::{ TypedDictAssignmentKind, validate_typed_dict_constructor, validate_typed_dict_dict_literal, validate_typed_dict_key_assignment, }; use crate::types::visitor::any_over_type; use crate::types::{ BoundTypeVarIdentity, BoundTypeVarInstance, CallDunderError, CallableBinding, CallableType, CallableTypeKind, ClassLiteral, ClassType, DataclassParams, DynamicType, InternedType, IntersectionBuilder, IntersectionType, KnownClass, KnownInstanceType, KnownUnion, LintDiagnosticGuard, MemberLookupPolicy, MetaclassCandidate, PEP695TypeAliasType, ParamSpecAttrKind, Parameter, ParameterForm, Parameters, Signature, SpecialFormType, SubclassOfType, TrackedConstraintSet, Truthiness, Type, TypeAliasType, TypeAndQualifiers, TypeContext, TypeQualifiers, TypeVarBoundOrConstraints, TypeVarBoundOrConstraintsEvaluation, TypeVarDefaultEvaluation, TypeVarIdentity, TypeVarInstance, TypeVarKind, TypeVarVariance, TypedDictType, UnionBuilder, UnionType, UnionTypeInstance, binding_type, infer_scope_types, todo_type, }; use crate::types::{CallableTypes, overrides}; use crate::types::{ClassBase, add_inferred_python_version_hint_to_diagnostic}; use crate::unpack::{EvaluationMode, UnpackPosition}; use crate::{Db, FxIndexSet, FxOrderSet, Program}; mod annotation_expression; mod type_expression; /// Whether the intersection type is on the left or right side of the comparison. #[derive(Debug, Clone, Copy)] enum IntersectionOn { Left, Right, } #[derive(Debug, Clone, Copy, Eq, PartialEq)] struct TypeAndRange<'db> { ty: Type<'db>, range: TextRange, } /// A helper to track if we already know that declared and inferred types are the same. #[derive(Debug, Clone, PartialEq, Eq)] enum DeclaredAndInferredType<'db> { /// We know that both the declared and inferred types are the same. AreTheSame(TypeAndQualifiers<'db>), /// Declared and inferred types might be different, we need to check assignability. MightBeDifferent { declared_ty: TypeAndQualifiers<'db>, inferred_ty: Type<'db>, }, } impl<'db> DeclaredAndInferredType<'db> { fn are_the_same_type(ty: Type<'db>) -> Self { Self::AreTheSame(TypeAndQualifiers::new( ty, TypeOrigin::Inferred, TypeQualifiers::empty(), )) } } /// A [`CycleDetector`] that is used in `infer_binary_type_comparison`. type BinaryComparisonVisitor<'db> = CycleDetector< ast::CmpOp, (Type<'db>, ast::CmpOp, Type<'db>), Result<Type<'db>, UnsupportedComparisonError<'db>>, >; /// We currently store one dataclass field-specifiers inline, because that covers standard /// dataclasses. attrs uses 2 specifiers, pydantic and strawberry use 3 specifiers. SQLAlchemy /// uses 7 field specifiers. We could probably store more inline if this turns out to be a /// performance problem. For now, we optimize for memory usage. const NUM_FIELD_SPECIFIERS_INLINE: usize = 1; /// Builder to infer all types in a region. /// /// A builder is used by creating it with [`new()`](TypeInferenceBuilder::new), and then calling /// [`finish_expression()`](TypeInferenceBuilder::finish_expression), [`finish_definition()`](TypeInferenceBuilder::finish_definition), or [`finish_scope()`](TypeInferenceBuilder::finish_scope) on it, which returns /// type inference result.. /// /// There are a few different kinds of methods in the type inference builder, and the naming /// distinctions are a bit subtle. /// /// The `finish` methods call [`infer_region`](TypeInferenceBuilder::infer_region), which delegates /// to one of [`infer_region_scope`](TypeInferenceBuilder::infer_region_scope), /// [`infer_region_definition`](TypeInferenceBuilder::infer_region_definition), or /// [`infer_region_expression`](TypeInferenceBuilder::infer_region_expression), depending which /// kind of [`InferenceRegion`] we are inferring types for. /// /// Scope inference starts with the scope body, walking all statements and expressions and /// recording the types of each expression in the inference result. Most of the methods /// here (with names like `infer_*_statement` or `infer_*_expression` or some other node kind) take /// a single AST node and are called as part of this AST visit. /// /// When the visit encounters a node which creates a [`Definition`], we look up the definition in /// the semantic index and call the [`infer_definition_types()`] query on it, which creates another /// [`TypeInferenceBuilder`] just for that definition, and we merge the returned inference result /// into the one we are currently building for the entire scope. Using the query in this way /// ensures that if we first infer types for some scattered definitions in a scope, and later for /// the entire scope, we don't re-infer any types, we reuse the cached inference for those /// definitions and their sub-expressions. /// /// Functions with a name like `infer_*_definition` take both a node and a [`Definition`], and are /// called by [`infer_region_definition`](TypeInferenceBuilder::infer_region_definition). /// /// So for example we have both /// [`infer_function_definition_statement`](TypeInferenceBuilder::infer_function_definition_statement), /// which takes just the function AST node, and /// [`infer_function_definition`](TypeInferenceBuilder::infer_function_definition), which takes /// both the node and the [`Definition`] id. The former is called as part of walking the AST, and /// it just looks up the [`Definition`] for that function in the semantic index and calls /// [`infer_definition_types()`] on it, which will create a new [`TypeInferenceBuilder`] with /// [`InferenceRegion::Definition`], and in that builder /// [`infer_region_definition`](TypeInferenceBuilder::infer_region_definition) will call /// [`infer_function_definition`](TypeInferenceBuilder::infer_function_definition) to actually /// infer a type for the definition. /// /// Similarly, when we encounter a standalone-inferable expression (right-hand side of an /// assignment, type narrowing guard), we use the [`infer_expression_types()`] query to ensure we /// don't infer its types more than once. pub(super) struct TypeInferenceBuilder<'db, 'ast> { context: InferContext<'db, 'ast>, index: &'db SemanticIndex<'db>, region: InferenceRegion<'db>, /// The types of every expression in this region. expressions: FxHashMap<ExpressionNodeKey, Type<'db>>, /// Expressions that are string annotations string_annotations: FxHashSet<ExpressionNodeKey>, /// The scope this region is part of. scope: ScopeId<'db>, // bindings, declarations, and deferred can only exist in definition, or scope contexts. /// The types of every binding in this region. /// /// The list should only contain one entry per binding at most. bindings: VecMap<Definition<'db>, Type<'db>>, /// The types and type qualifiers of every declaration in this region. /// /// The list should only contain one entry per declaration at most. declarations: VecMap<Definition<'db>, TypeAndQualifiers<'db>>, /// The definitions with deferred sub-parts. /// /// The list should only contain one entry per definition. deferred: VecSet<Definition<'db>>, /// The returned types and their corresponding ranges of the region, if it is a function body. return_types_and_ranges: Vec<TypeAndRange<'db>>, /// A set of functions that have been defined **and** called in this region. /// /// This is a set because the same function could be called multiple times in the same region. /// This is mainly used in [`check_overloaded_functions`] to check an overloaded function that /// is shadowed by a function with the same name in this scope but has been called before. For /// example: /// /// ```py /// from typing import overload /// /// @overload /// def foo() -> None: ... /// @overload /// def foo(x: int) -> int: ... /// def foo(x: int | None) -> int | None: return x /// /// foo() # An overloaded function that was defined in this scope have been called /// /// def foo(x: int) -> int: /// return x /// ``` /// /// To keep the calculation deterministic, we use an `FxIndexSet` whose order is determined by the sequence of insertion calls. /// /// [`check_overloaded_functions`]: TypeInferenceBuilder::check_overloaded_functions called_functions: FxIndexSet<FunctionType<'db>>, /// Whether we are in a context that binds unbound typevars. typevar_binding_context: Option<Definition<'db>>, /// The deferred state of inferring types of certain expressions within the region. /// /// This is different from [`InferenceRegion::Deferred`] which works on the entire definition /// while this is relevant for specific expressions within the region itself and is updated /// during the inference process. /// /// For example, when inferring the types of an annotated assignment, the type of an annotation /// expression could be deferred if the file has `from __future__ import annotations` import or /// is a stub file but we're still in a non-deferred region. deferred_state: DeferredExpressionState, multi_inference_state: MultiInferenceState, /// If you cannot avoid the possibility of calling `infer(_type)_expression` multiple times for a given expression, /// set this to `Get` after the expression has been inferred for the first time. /// While this is `Get`, any expressions will be considered to have already been inferred. inner_expression_inference_state: InnerExpressionInferenceState, /// For function definitions, the undecorated type of the function. undecorated_type: Option<Type<'db>>, /// The fallback type for missing expressions/bindings/declarations or recursive type inference. cycle_recovery: Option<Type<'db>>, /// `true` if all places in this expression are definitely bound all_definitely_bound: bool, /// A list of `dataclass_transform` field specifiers that are "active" (when inferring /// the right hand side of an annotated assignment in a class that is a dataclass). dataclass_field_specifiers: SmallVec<[Type<'db>; NUM_FIELD_SPECIFIERS_INLINE]>, } impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> { /// How big a string do we build before bailing? /// /// This is a fairly arbitrary number. It should be *far* more than enough /// for most use cases, but we can reevaluate it later if useful. pub(super) const MAX_STRING_LITERAL_SIZE: usize = 4096; /// Creates a new builder for inferring types in a region. pub(super) fn new( db: &'db dyn Db, region: InferenceRegion<'db>, index: &'db SemanticIndex<'db>, module: &'ast ParsedModuleRef, ) -> Self { let scope = region.scope(db); Self { context: InferContext::new(db, scope, module), index, region, scope, return_types_and_ranges: vec![], called_functions: FxIndexSet::default(), deferred_state: DeferredExpressionState::None, multi_inference_state: MultiInferenceState::Panic, inner_expression_inference_state: InnerExpressionInferenceState::Infer, expressions: FxHashMap::default(), string_annotations: FxHashSet::default(), bindings: VecMap::default(), declarations: VecMap::default(), typevar_binding_context: None, deferred: VecSet::default(), undecorated_type: None, cycle_recovery: None, all_definitely_bound: true, dataclass_field_specifiers: SmallVec::new(), } } fn fallback_type(&self) -> Option<Type<'db>> { self.cycle_recovery } fn extend_cycle_recovery(&mut self, other: Option<Type<'db>>) { if let Some(other) = other { match self.cycle_recovery { Some(existing) => { self.cycle_recovery = Some(UnionType::from_elements(self.db(), [existing, other])); } None => { self.cycle_recovery = Some(other); } } } } fn extend_definition(&mut self, inference: &DefinitionInference<'db>) { #[cfg(debug_assertions)] assert_eq!(self.scope, inference.scope); self.expressions.extend(inference.expressions.iter()); self.declarations .extend(inference.declarations(), self.multi_inference_state); if !matches!(self.region, InferenceRegion::Scope(..)) { self.bindings .extend(inference.bindings(), self.multi_inference_state); } if let Some(extra) = &inference.extra { self.extend_cycle_recovery(extra.cycle_recovery); self.context.extend(&extra.diagnostics); self.deferred .extend(extra.deferred.iter().copied(), self.multi_inference_state); self.string_annotations .extend(extra.string_annotations.iter().copied()); } } fn extend_expression(&mut self, inference: &ExpressionInference<'db>) { #[cfg(debug_assertions)] assert_eq!(self.scope, inference.scope); self.extend_expression_unchecked(inference); } fn extend_expression_unchecked(&mut self, inference: &ExpressionInference<'db>) { self.expressions.extend(inference.expressions.iter()); if let Some(extra) = &inference.extra { self.context.extend(&extra.diagnostics); self.extend_cycle_recovery(extra.cycle_recovery); self.string_annotations .extend(extra.string_annotations.iter().copied()); if !matches!(self.region, InferenceRegion::Scope(..)) { self.bindings .extend(extra.bindings.iter().copied(), self.multi_inference_state); } } } fn file(&self) -> File { self.context.file() } fn module(&self) -> &'ast ParsedModuleRef { self.context.module() } fn db(&self) -> &'db dyn Db { self.context.db() } fn scope(&self) -> ScopeId<'db> { self.scope } /// Set the multi-inference state, returning the previous value. fn set_multi_inference_state(&mut self, state: MultiInferenceState) -> MultiInferenceState { std::mem::replace(&mut self.multi_inference_state, state) } /// Are we currently inferring types in file with deferred types? /// This is true for stub files, for files with `__future__.annotations`, and /// by default for all source files in Python 3.14 and later. fn defer_annotations(&self) -> bool { self.index.has_future_annotations() || self.in_stub() || Program::get(self.db()).python_version(self.db()) >= PythonVersion::PY314 } /// Are we currently in a context where name resolution should be deferred /// (`__future__.annotations`, stub file, or stringified annotation)? fn is_deferred(&self) -> bool { self.deferred_state.is_deferred() } /// Return the node key of the given AST node, or the key of the outermost enclosing string /// literal, if the node originates from inside a stringified annotation. fn enclosing_node_key(&self, node: AnyNodeRef<'_>) -> NodeKey { match self.deferred_state { DeferredExpressionState::InStringAnnotation(enclosing_node_key) => enclosing_node_key, _ => NodeKey::from_node(node), } } /// Check if a given AST node is reachable. /// /// Note that this only works if reachability is explicitly tracked for this specific /// type of node (see `node_reachability` in the use-def map). fn is_reachable<'a, N>(&self, node: N) -> bool where N: Into<AnyNodeRef<'a>>, { let file_scope_id = self.scope().file_scope_id(self.db()); self.index.is_node_reachable( self.db(), file_scope_id, self.enclosing_node_key(node.into()), ) } fn in_stub(&self) -> bool { self.context.in_stub() } /// Get the already-inferred type of an expression node, or Unknown. fn expression_type(&self, expr: &ast::Expr) -> Type<'db> { self.try_expression_type(expr).unwrap_or_else(Type::unknown) } fn try_expression_type(&self, expr: &ast::Expr) -> Option<Type<'db>> { self.expressions .get(&expr.into()) .copied() .or(self.fallback_type()) } /// Get the type of an expression from any scope in the same file. /// /// If the expression is in the current scope, and we are inferring the entire scope, just look /// up the expression in our own results, otherwise call [`infer_scope_types()`] for the scope /// of the expression. /// /// ## Panics /// /// If the expression is in the current scope but we haven't yet inferred a type for it. /// /// Can cause query cycles if the expression is from a different scope and type inference is /// already in progress for that scope (further up the stack). fn file_expression_type(&self, expression: &ast::Expr) -> Type<'db> { let file_scope = self.index.expression_scope_id(expression); let expr_scope = file_scope.to_scope_id(self.db(), self.file()); match self.region { InferenceRegion::Scope(scope) if scope == expr_scope => { self.expression_type(expression) } _ => infer_scope_types(self.db(), expr_scope).expression_type(expression), } } /// Infers types in the given [`InferenceRegion`]. fn infer_region(&mut self) { match self.region { InferenceRegion::Scope(scope) => self.infer_region_scope(scope), InferenceRegion::Definition(definition) => self.infer_region_definition(definition), InferenceRegion::Deferred(definition) => self.infer_region_deferred(definition), InferenceRegion::Expression(expression, tcx) => { self.infer_region_expression(expression, tcx); } } } fn infer_region_scope(&mut self, scope: ScopeId<'db>) { let node = scope.node(self.db()); match node { NodeWithScopeKind::Module => { self.infer_module(self.module().syntax()); } NodeWithScopeKind::Function(function) => { self.infer_function_body(function.node(self.module())); } NodeWithScopeKind::Lambda(lambda) => self.infer_lambda_body(lambda.node(self.module())), NodeWithScopeKind::Class(class) => self.infer_class_body(class.node(self.module())), NodeWithScopeKind::ClassTypeParameters(class) => { self.infer_class_type_params(class.node(self.module())); } NodeWithScopeKind::FunctionTypeParameters(function) => { self.infer_function_type_params(function.node(self.module())); } NodeWithScopeKind::TypeAliasTypeParameters(type_alias) => { self.infer_type_alias_type_params(type_alias.node(self.module())); } NodeWithScopeKind::TypeAlias(type_alias) => { self.infer_type_alias(type_alias.node(self.module())); } NodeWithScopeKind::ListComprehension(comprehension) => { self.infer_list_comprehension_expression_scope(comprehension.node(self.module())); } NodeWithScopeKind::SetComprehension(comprehension) => { self.infer_set_comprehension_expression_scope(comprehension.node(self.module())); } NodeWithScopeKind::DictComprehension(comprehension) => { self.infer_dict_comprehension_expression_scope(comprehension.node(self.module())); } NodeWithScopeKind::GeneratorExpression(generator) => { self.infer_generator_expression_scope(generator.node(self.module())); } } // Infer deferred types for all definitions. for definition in std::mem::take(&mut self.deferred) { self.extend_definition(infer_deferred_types(self.db(), definition)); } assert!( self.deferred.is_empty(), "Inferring deferred types should not add more deferred definitions" ); if self.db().should_check_file(self.file()) { self.check_class_definitions(); self.check_overloaded_functions(node); } } /// Iterate over all class definitions to check that the definition will not cause an exception /// to be raised at runtime. This needs to be done after most other types in the scope have been /// inferred, due to the fact that base classes can be deferred. If it looks like a class /// definition is invalid in some way, issue a diagnostic. /// /// Among the things we check for in this method are whether Python will be able to determine a /// consistent "[method resolution order]" and [metaclass] for each class. /// /// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order /// [metaclass]: https://docs.python.org/3/reference/datamodel.html#metaclasses fn check_class_definitions(&mut self) { let class_definitions = self.declarations.iter().filter_map(|(definition, ty)| { // Filter out class literals that result from imports if let DefinitionKind::Class(class) = definition.kind(self.db()) { ty.inner_type() .as_class_literal() .map(|class_literal| (class_literal, class.node(self.module()))) } else { None } }); // Iterate through all class definitions in this scope. for (class, class_node) in class_definitions { // (1) Check that the class does not have a cyclic definition if let Some(inheritance_cycle) = class.inheritance_cycle(self.db()) { if inheritance_cycle.is_participant() { if let Some(builder) = self .context .report_lint(&CYCLIC_CLASS_DEFINITION, class_node) { builder.into_diagnostic(format_args!( "Cyclic definition of `{}` (class cannot inherit from itself)", class.name(self.db()) )); } } // If a class is cyclically defined, that's a sufficient error to report; the // following checks (which are all inheritance-based) aren't even relevant. continue; } let is_named_tuple = CodeGeneratorKind::NamedTuple.matches(self.db(), class, None); // (2) If it's a `NamedTuple` class, check that no field without a default value // appears after a field with a default value. if is_named_tuple { let mut field_with_default_encountered = None; for (field_name, field) in class.own_fields(self.db(), None, CodeGeneratorKind::NamedTuple) { if field_name.starts_with('_') { report_named_tuple_field_with_leading_underscore( &self.context, class, &field_name, field.first_declaration, ); } if matches!( field.kind, FieldKind::NamedTuple { default_ty: Some(_) } ) { field_with_default_encountered = Some((field_name, field.first_declaration)); } else if let Some(field_with_default) = field_with_default_encountered.as_ref() { report_namedtuple_field_without_default_after_field_with_default( &self.context, class, (&field_name, field.first_declaration), field_with_default, ); } } } let is_protocol = class.is_protocol(self.db()); let mut disjoint_bases = IncompatibleBases::default(); // (3) Iterate through the class's explicit bases to check for various possible errors: // - Check for inheritance from plain `Generic`, // - Check for inheritance from a `@final` classes // - If the class is a protocol class: check for inheritance from a non-protocol class // - If the class is a NamedTuple class: check for multiple inheritance that isn't `Generic[]` for (i, base_class) in class.explicit_bases(self.db()).iter().enumerate() { if is_named_tuple && !matches!( base_class, Type::SpecialForm(SpecialFormType::NamedTuple) | Type::KnownInstance(KnownInstanceType::SubscriptedGeneric(_)) ) { if let Some(builder) = self .context .report_lint(&INVALID_NAMED_TUPLE, &class_node.bases()[i]) { builder.into_diagnostic(format_args!( "NamedTuple class `{}` cannot use multiple inheritance except with `Generic[]`", class.name(self.db()), )); } } let base_class = match base_class { Type::SpecialForm(SpecialFormType::Generic) => { if let Some(builder) = self .context .report_lint(&INVALID_BASE, &class_node.bases()[i]) { // Unsubscripted `Generic` can appear in the MRO of many classes, // but it is never valid as an explicit base class in user code. builder.into_diagnostic("Cannot inherit from plain `Generic`"); } continue; } // Note that unlike several of the other errors caught in this function,
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/infer/tests.rs
crates/ty_python_semantic/src/types/infer/tests.rs
use super::builder::TypeInferenceBuilder; use crate::db::tests::{TestDb, setup_db}; use crate::place::symbol; use crate::place::{ConsideredDefinitions, Place, global_symbol}; use crate::semantic_index::definition::Definition; use crate::semantic_index::scope::FileScopeId; use crate::semantic_index::{global_scope, place_table, semantic_index, use_def_map}; use crate::types::{KnownClass, KnownInstanceType, check_types}; use ruff_db::diagnostic::Diagnostic; use ruff_db::files::{File, system_path_to_file}; use ruff_db::system::DbWithWritableSystem as _; use ruff_db::testing::{assert_function_query_was_not_run, assert_function_query_was_run}; use super::*; #[track_caller] fn get_symbol<'db>( db: &'db TestDb, file_name: &str, scopes: &[&str], symbol_name: &str, ) -> Place<'db> { let file = system_path_to_file(db, file_name).expect("file to exist"); let module = parsed_module(db, file).load(db); let index = semantic_index(db, file); let mut file_scope_id = FileScopeId::global(); let mut scope = file_scope_id.to_scope_id(db, file); for expected_scope_name in scopes { file_scope_id = index .child_scopes(file_scope_id) .next() .unwrap_or_else(|| panic!("scope of {expected_scope_name}")) .0; scope = file_scope_id.to_scope_id(db, file); assert_eq!(scope.name(db, &module), *expected_scope_name); } symbol(db, scope, symbol_name, ConsideredDefinitions::EndOfScope).place } #[track_caller] fn assert_diagnostic_messages(diagnostics: &[Diagnostic], expected: &[&str]) { let messages: Vec<&str> = diagnostics .iter() .map(Diagnostic::primary_message) .collect(); assert_eq!(&messages, expected); } #[track_caller] fn assert_file_diagnostics(db: &TestDb, filename: &str, expected: &[&str]) { let file = system_path_to_file(db, filename).unwrap(); let diagnostics = check_types(db, file); assert_diagnostic_messages(&diagnostics, expected); } #[test] fn not_literal_string() -> anyhow::Result<()> { let mut db = setup_db(); let content = format!( r#" from typing_extensions import Literal, assert_type assert_type(not "{y}", bool) assert_type(not 10*"{y}", bool) assert_type(not "{y}"*10, bool) assert_type(not 0*"{y}", Literal[True]) assert_type(not (-100)*"{y}", Literal[True]) "#, y = "a".repeat(TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE + 1), ); db.write_dedented("src/a.py", &content)?; assert_file_diagnostics(&db, "src/a.py", &[]); Ok(()) } #[test] fn multiplied_string() -> anyhow::Result<()> { let mut db = setup_db(); let content = format!( r#" from typing_extensions import Literal, LiteralString, assert_type assert_type(2 * "hello", Literal["hellohello"]) assert_type("goodbye" * 3, Literal["goodbyegoodbyegoodbye"]) assert_type("a" * {y}, Literal["{a_repeated}"]) assert_type({z} * "b", LiteralString) assert_type(0 * "hello", Literal[""]) assert_type(-3 * "hello", Literal[""]) "#, y = TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE, z = TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE + 1, a_repeated = "a".repeat(TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE), ); db.write_dedented("src/a.py", &content)?; assert_file_diagnostics(&db, "src/a.py", &[]); Ok(()) } #[test] fn multiplied_literal_string() -> anyhow::Result<()> { let mut db = setup_db(); let content = format!( r#" from typing_extensions import Literal, LiteralString, assert_type assert_type("{y}", LiteralString) assert_type(10*"{y}", LiteralString) assert_type("{y}"*10, LiteralString) assert_type(0*"{y}", Literal[""]) assert_type((-100)*"{y}", Literal[""]) "#, y = "a".repeat(TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE + 1), ); db.write_dedented("src/a.py", &content)?; assert_file_diagnostics(&db, "src/a.py", &[]); Ok(()) } #[test] fn truncated_string_literals_become_literal_string() -> anyhow::Result<()> { let mut db = setup_db(); let content = format!( r#" from typing_extensions import LiteralString, assert_type assert_type("{y}", LiteralString) assert_type("a" + "{z}", LiteralString) "#, y = "a".repeat(TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE + 1), z = "a".repeat(TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE), ); db.write_dedented("src/a.py", &content)?; assert_file_diagnostics(&db, "src/a.py", &[]); Ok(()) } #[test] fn adding_string_literals_and_literal_string() -> anyhow::Result<()> { let mut db = setup_db(); let content = format!( r#" from typing_extensions import LiteralString, assert_type assert_type("{y}", LiteralString) assert_type("{y}" + "a", LiteralString) assert_type("a" + "{y}", LiteralString) assert_type("{y}" + "{y}", LiteralString) "#, y = "a".repeat(TypeInferenceBuilder::MAX_STRING_LITERAL_SIZE + 1), ); db.write_dedented("src/a.py", &content)?; assert_file_diagnostics(&db, "src/a.py", &[]); Ok(()) } #[test] fn pep695_type_params() { let mut db = setup_db(); db.write_dedented( "src/a.py", " def f[T, U: A, V: (A, B), W = A, X: A = A1, Y: (int,)](): pass class A: ... class B: ... class A1(A): ... ", ) .unwrap(); let check_typevar = |var: &'static str, display: &'static str, upper_bound: Option<&'static str>, constraints: Option<&[&'static str]>, default: Option<&'static str>| { let var_ty = get_symbol(&db, "src/a.py", &["f"], var).expect_type(); assert_eq!(var_ty.display(&db).to_string(), display); let expected_name_ty = format!(r#"Literal["{var}"]"#); let name_ty = var_ty.member(&db, "__name__").place.expect_type(); assert_eq!(name_ty.display(&db).to_string(), expected_name_ty); let Type::KnownInstance(KnownInstanceType::TypeVar(typevar)) = var_ty else { panic!("expected TypeVar"); }; assert_eq!( typevar .upper_bound(&db) .map(|ty| ty.display(&db).to_string()), upper_bound.map(std::borrow::ToOwned::to_owned) ); assert_eq!( typevar.constraints(&db).map(|tys| tys .iter() .map(|ty| ty.display(&db).to_string()) .collect::<Vec<_>>()), constraints.map(|strings| strings .iter() .map(std::string::ToString::to_string) .collect::<Vec<_>>()) ); assert_eq!( typevar .default_type(&db) .map(|ty| ty.display(&db).to_string()), default.map(std::borrow::ToOwned::to_owned) ); }; check_typevar("T", "TypeVar", None, None, None); check_typevar("U", "TypeVar", Some("A"), None, None); check_typevar("V", "TypeVar", None, Some(&["A", "B"]), None); check_typevar("W", "TypeVar", None, None, Some("A")); check_typevar("X", "TypeVar", Some("A"), None, Some("A1")); // a typevar with less than two constraints is treated as unconstrained check_typevar("Y", "TypeVar", None, None, None); } /// Test that a symbol known to be unbound in a scope does not still trigger cycle-causing /// reachability-constraint checks in that scope. #[test] fn unbound_symbol_no_reachability_constraint_check() { let mut db = setup_db(); // First, type-check a random other file so that we cache a result for the `module_type_symbols` // query (which often encounters cycles due to `types.pyi` importing `typing_extensions` and // `typing_extensions.pyi` importing `types`). Clear the events afterwards so that unrelated // cycles from that query don't interfere with our test. db.write_dedented("src/wherever.py", "print(x)").unwrap(); assert_file_diagnostics(&db, "src/wherever.py", &["Name `x` used when not defined"]); db.clear_salsa_events(); // If the bug we are testing for is not fixed, what happens is that when inferring the // `flag: bool = True` definitions, we look up `bool` as a deferred name (thus from end of // scope), and because of the early return its "unbound" binding has a reachability // constraint of `~flag`, which we evaluate, meaning we have to evaluate the definition of // `flag` -- and we are in a cycle. With the fix, we short-circuit evaluating reachability // constraints on "unbound" if a symbol is otherwise not bound. db.write_dedented( "src/a.py", " from __future__ import annotations def f(): flag: bool = True if flag: return True ", ) .unwrap(); db.clear_salsa_events(); assert_file_diagnostics(&db, "src/a.py", &[]); let events = db.take_salsa_events(); let cycles = salsa::attach(&db, || { events .iter() .filter_map(|event| { if let salsa::EventKind::WillIterateCycle { database_key, .. } = event.kind { Some(format!("{database_key:?}")) } else { None } }) .collect::<Vec<_>>() }); let expected: Vec<String> = vec![]; assert_eq!(cycles, expected); } // Incremental inference tests #[track_caller] fn first_public_binding<'db>(db: &'db TestDb, file: File, name: &str) -> Definition<'db> { let scope = global_scope(db, file); use_def_map(db, scope) .end_of_scope_symbol_bindings(place_table(db, scope).symbol_id(name).unwrap()) .find_map(|b| b.binding.definition()) .expect("no binding found") } #[test] fn dependency_public_symbol_type_change() -> anyhow::Result<()> { let mut db = setup_db(); db.write_files([ ("/src/a.py", "from foo import x"), ("/src/foo.py", "x: int = 10\ndef foo(): ..."), ])?; let a = system_path_to_file(&db, "/src/a.py").unwrap(); let x_ty = global_symbol(&db, a, "x").place.expect_type(); assert_eq!(x_ty.display(&db).to_string(), "int"); // Change `x` to a different value db.write_file("/src/foo.py", "x: bool = True\ndef foo(): ...")?; let a = system_path_to_file(&db, "/src/a.py").unwrap(); let x_ty_2 = global_symbol(&db, a, "x").place.expect_type(); assert_eq!(x_ty_2.display(&db).to_string(), "bool"); Ok(()) } #[test] fn dependency_internal_symbol_change() -> anyhow::Result<()> { let mut db = setup_db(); db.write_files([ ("/src/a.py", "from foo import x"), ("/src/foo.py", "x: int = 10\ndef foo(): y = 1"), ])?; let a = system_path_to_file(&db, "/src/a.py").unwrap(); let x_ty = global_symbol(&db, a, "x").place.expect_type(); assert_eq!(x_ty.display(&db).to_string(), "int"); db.write_file("/src/foo.py", "x: int = 10\ndef foo(): pass")?; let a = system_path_to_file(&db, "/src/a.py").unwrap(); db.clear_salsa_events(); let x_ty_2 = global_symbol(&db, a, "x").place.expect_type(); assert_eq!(x_ty_2.display(&db).to_string(), "int"); let events = db.take_salsa_events(); assert_function_query_was_not_run( &db, infer_definition_types, first_public_binding(&db, a, "x"), &events, ); Ok(()) } #[test] fn dependency_unrelated_symbol() -> anyhow::Result<()> { let mut db = setup_db(); db.write_files([ ("/src/a.py", "from foo import x"), ("/src/foo.py", "x: int = 10\ny: bool = True"), ])?; let a = system_path_to_file(&db, "/src/a.py").unwrap(); let x_ty = global_symbol(&db, a, "x").place.expect_type(); assert_eq!(x_ty.display(&db).to_string(), "int"); db.write_file("/src/foo.py", "x: int = 10\ny: bool = False")?; let a = system_path_to_file(&db, "/src/a.py").unwrap(); db.clear_salsa_events(); let x_ty_2 = global_symbol(&db, a, "x").place.expect_type(); assert_eq!(x_ty_2.display(&db).to_string(), "int"); let events = db.take_salsa_events(); assert_function_query_was_not_run( &db, infer_definition_types, first_public_binding(&db, a, "x"), &events, ); Ok(()) } #[test] fn dependency_implicit_instance_attribute() -> anyhow::Result<()> { fn x_rhs_expression(db: &TestDb) -> Expression<'_> { let file_main = system_path_to_file(db, "/src/main.py").unwrap(); let ast = parsed_module(db, file_main).load(db); // Get the second statement in `main.py` (x = …) and extract the expression // node on the right-hand side: let x_rhs_node = &ast.syntax().body[1].as_assign_stmt().unwrap().value; let index = semantic_index(db, file_main); index.expression(x_rhs_node.as_ref()) } let mut db = setup_db(); db.write_dedented( "/src/mod.py", r#" class C: def f(self): self.attr: int | None = None "#, )?; db.write_dedented( "/src/main.py", r#" from mod import C # multiple targets ensures RHS is a standalone expression, relied on by this test x = y = C().attr "#, )?; let file_main = system_path_to_file(&db, "/src/main.py").unwrap(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "int | None"); // Change the type of `attr` to `str | None`; this should trigger the type of `x` to be re-inferred db.write_dedented( "/src/mod.py", r#" class C: def f(self): self.attr: str | None = None "#, )?; let events = { db.clear_salsa_events(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "str | None"); db.take_salsa_events() }; assert_function_query_was_run( &db, infer_expression_types_impl, InferExpression::Bare(x_rhs_expression(&db)), &events, ); // Add a comment; this should not trigger the type of `x` to be re-inferred db.write_dedented( "/src/mod.py", r#" class C: def f(self): # a comment! self.attr: str | None = None "#, )?; let events = { db.clear_salsa_events(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "str | None"); db.take_salsa_events() }; assert_function_query_was_not_run( &db, infer_expression_types_impl, InferExpression::Bare(x_rhs_expression(&db)), &events, ); Ok(()) } /// This test verifies that changing a class's declaration in a non-meaningful way (e.g. by adding a comment) /// doesn't trigger type inference for expressions that depend on the class's members. #[test] fn dependency_own_instance_member() -> anyhow::Result<()> { fn x_rhs_expression(db: &TestDb) -> Expression<'_> { let file_main = system_path_to_file(db, "/src/main.py").unwrap(); let ast = parsed_module(db, file_main).load(db); // Get the second statement in `main.py` (x = …) and extract the expression // node on the right-hand side: let x_rhs_node = &ast.syntax().body[1].as_assign_stmt().unwrap().value; let index = semantic_index(db, file_main); index.expression(x_rhs_node.as_ref()) } let mut db = setup_db(); db.write_dedented( "/src/mod.py", r#" class C: if random.choice([True, False]): attr: int = 42 else: attr: None = None "#, )?; db.write_dedented( "/src/main.py", r#" from mod import C # multiple targets ensures RHS is a standalone expression, relied on by this test x = y = C().attr "#, )?; let file_main = system_path_to_file(&db, "/src/main.py").unwrap(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "int | None"); // Change the type of `attr` to `str | None`; this should trigger the type of `x` to be re-inferred db.write_dedented( "/src/mod.py", r#" class C: if random.choice([True, False]): attr: str = "42" else: attr: None = None "#, )?; let events = { db.clear_salsa_events(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "str | None"); db.take_salsa_events() }; assert_function_query_was_run( &db, infer_expression_types_impl, InferExpression::Bare(x_rhs_expression(&db)), &events, ); // Add a comment; this should not trigger the type of `x` to be re-inferred db.write_dedented( "/src/mod.py", r#" class C: # comment if random.choice([True, False]): attr: str = "42" else: attr: None = None "#, )?; let events = { db.clear_salsa_events(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "str | None"); db.take_salsa_events() }; assert_function_query_was_not_run( &db, infer_expression_types_impl, InferExpression::Bare(x_rhs_expression(&db)), &events, ); Ok(()) } #[test] fn dependency_implicit_class_member() -> anyhow::Result<()> { fn x_rhs_expression(db: &TestDb) -> Expression<'_> { let file_main = system_path_to_file(db, "/src/main.py").unwrap(); let ast = parsed_module(db, file_main).load(db); // Get the third statement in `main.py` (x = …) and extract the expression // node on the right-hand side: let x_rhs_node = &ast.syntax().body[2].as_assign_stmt().unwrap().value; let index = semantic_index(db, file_main); index.expression(x_rhs_node.as_ref()) } let mut db = setup_db(); db.write_dedented( "/src/mod.py", r#" class C: def __init__(self): self.instance_attr: str = "24" @classmethod def method(cls): cls.class_attr: int = 42 "#, )?; db.write_dedented( "/src/main.py", r#" from mod import C C.method() # multiple targets ensures RHS is a standalone expression, relied on by this test x = y = C().class_attr "#, )?; let file_main = system_path_to_file(&db, "/src/main.py").unwrap(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "int"); // Change the type of `class_attr` to `str`; this should trigger the type of `x` to be re-inferred db.write_dedented( "/src/mod.py", r#" class C: def __init__(self): self.instance_attr: str = "24" @classmethod def method(cls): cls.class_attr: str = "42" "#, )?; let events = { db.clear_salsa_events(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "str"); db.take_salsa_events() }; assert_function_query_was_run( &db, infer_expression_types_impl, InferExpression::Bare(x_rhs_expression(&db)), &events, ); // Add a comment; this should not trigger the type of `x` to be re-inferred db.write_dedented( "/src/mod.py", r#" class C: def __init__(self): self.instance_attr: str = "24" @classmethod def method(cls): # comment cls.class_attr: str = "42" "#, )?; let events = { db.clear_salsa_events(); let attr_ty = global_symbol(&db, file_main, "x").place.expect_type(); assert_eq!(attr_ty.display(&db).to_string(), "str"); db.take_salsa_events() }; assert_function_query_was_not_run( &db, infer_expression_types_impl, InferExpression::Bare(x_rhs_expression(&db)), &events, ); Ok(()) } /// Inferring the result of a call-expression shouldn't need to re-run after /// a trivial change to the function's file (e.g. by adding a docstring to the function). #[test] fn call_type_doesnt_rerun_when_only_callee_changed() -> anyhow::Result<()> { let mut db = setup_db(); db.write_dedented( "src/foo.py", r#" def foo() -> int: return 5 "#, )?; db.write_dedented( "src/bar.py", r#" from foo import foo # multiple targets ensures RHS is a standalone expression, relied on by this test a = b = foo() "#, )?; let bar = system_path_to_file(&db, "src/bar.py")?; let a = global_symbol(&db, bar, "a").place; assert_eq!(a.expect_type(), KnownClass::Int.to_instance(&db)); let events = db.take_salsa_events(); let module = parsed_module(&db, bar).load(&db); let call = &*module.syntax().body[1].as_assign_stmt().unwrap().value; let foo_call = semantic_index(&db, bar).expression(call); assert_function_query_was_run( &db, infer_expression_types_impl, InferExpression::Bare(foo_call), &events, ); // Add a docstring to foo to trigger a re-run. // The bar-call site of foo should not be re-run because of that db.write_dedented( "src/foo.py", r#" def foo() -> int: "Computes a value" return 5 "#, )?; db.clear_salsa_events(); let a = global_symbol(&db, bar, "a").place; assert_eq!(a.expect_type(), KnownClass::Int.to_instance(&db)); let events = db.take_salsa_events(); let module = parsed_module(&db, bar).load(&db); let call = &*module.syntax().body[1].as_assign_stmt().unwrap().value; let foo_call = semantic_index(&db, bar).expression(call); assert_function_query_was_not_run( &db, infer_expression_types_impl, InferExpression::Bare(foo_call), &events, ); Ok(()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/infer/builder/type_expression.rs
crates/ty_python_semantic/src/types/infer/builder/type_expression.rs
use itertools::Either; use ruff_python_ast as ast; use super::{DeferredExpressionState, TypeInferenceBuilder}; use crate::FxOrderSet; use crate::semantic_index::semantic_index; use crate::types::diagnostic::{ self, INVALID_TYPE_FORM, NOT_SUBSCRIPTABLE, report_invalid_argument_number_to_special_form, report_invalid_arguments_to_callable, }; use crate::types::generics::bind_typevar; use crate::types::infer::builder::InnerExpressionInferenceState; use crate::types::signatures::Signature; use crate::types::string_annotation::parse_string_annotation; use crate::types::tuple::{TupleSpecBuilder, TupleType}; use crate::types::{ BindingContext, CallableType, DynamicType, GenericContext, IntersectionBuilder, KnownClass, KnownInstanceType, LintDiagnosticGuard, Parameter, Parameters, SpecialFormType, SubclassOfType, Type, TypeAliasType, TypeContext, TypeGuardType, TypeIsType, TypeMapping, TypeVarKind, UnionBuilder, UnionType, any_over_type, todo_type, }; /// Type expressions impl<'db> TypeInferenceBuilder<'db, '_> { /// Infer the type of a type expression. pub(super) fn infer_type_expression(&mut self, expression: &ast::Expr) -> Type<'db> { if self.inner_expression_inference_state.is_get() { return self.expression_type(expression); } let previous_deferred_state = self.deferred_state; // `DeferredExpressionState::InStringAnnotation` takes precedence over other states. // However, if it's not a stringified annotation, we must still ensure that annotation expressions // are always deferred in stub files. match previous_deferred_state { DeferredExpressionState::None => { if self.in_stub() { self.deferred_state = DeferredExpressionState::Deferred; } } DeferredExpressionState::InStringAnnotation(_) | DeferredExpressionState::Deferred => {} } let ty = self.infer_type_expression_no_store(expression); self.deferred_state = previous_deferred_state; self.store_expression_type(expression, ty); ty } /// Similar to [`infer_type_expression`], but accepts a [`DeferredExpressionState`]. /// /// [`infer_type_expression`]: TypeInferenceBuilder::infer_type_expression fn infer_type_expression_with_state( &mut self, expression: &ast::Expr, deferred_state: DeferredExpressionState, ) -> Type<'db> { let previous_deferred_state = std::mem::replace(&mut self.deferred_state, deferred_state); let annotation_ty = self.infer_type_expression(expression); self.deferred_state = previous_deferred_state; annotation_ty } /// Similar to [`infer_type_expression`], but accepts an optional expression. /// /// [`infer_type_expression`]: TypeInferenceBuilder::infer_type_expression_with_state pub(super) fn infer_optional_type_expression( &mut self, expression: Option<&ast::Expr>, ) -> Option<Type<'db>> { expression.map(|expr| self.infer_type_expression(expr)) } fn report_invalid_type_expression( &self, expression: &ast::Expr, message: std::fmt::Arguments, ) -> Option<LintDiagnosticGuard<'_, '_>> { self.context .report_lint(&INVALID_TYPE_FORM, expression) .map(|builder| { diagnostic::add_type_expression_reference_link(builder.into_diagnostic(message)) }) } /// Infer the type of a type expression without storing the result. pub(super) fn infer_type_expression_no_store(&mut self, expression: &ast::Expr) -> Type<'db> { if self.inner_expression_inference_state.is_get() { return self.expression_type(expression); } // https://typing.python.org/en/latest/spec/annotations.html#grammar-token-expression-grammar-type_expression match expression { ast::Expr::Name(name) => match name.ctx { ast::ExprContext::Load => self .infer_name_expression(name) .default_specialize(self.db()) .in_type_expression(self.db(), self.scope(), self.typevar_binding_context) .unwrap_or_else(|error| { error.into_fallback_type( &self.context, expression, self.is_reachable(expression), ) }), ast::ExprContext::Invalid => Type::unknown(), ast::ExprContext::Store | ast::ExprContext::Del => { todo_type!("Name expression annotation in Store/Del context") } }, ast::Expr::Attribute(attribute_expression) => match attribute_expression.ctx { ast::ExprContext::Load => self .infer_attribute_expression(attribute_expression) .default_specialize(self.db()) .in_type_expression(self.db(), self.scope(), self.typevar_binding_context) .unwrap_or_else(|error| { error.into_fallback_type( &self.context, expression, self.is_reachable(expression), ) }), ast::ExprContext::Invalid => Type::unknown(), ast::ExprContext::Store | ast::ExprContext::Del => { todo_type!("Attribute expression annotation in Store/Del context") } }, ast::Expr::NoneLiteral(_literal) => Type::none(self.db()), // https://typing.python.org/en/latest/spec/annotations.html#string-annotations ast::Expr::StringLiteral(string) => self.infer_string_type_expression(string), ast::Expr::Subscript(subscript) => { let ast::ExprSubscript { value, slice, ctx: _, range: _, node_index: _, } = subscript; let value_ty = self.infer_expression(value, TypeContext::default()); self.infer_subscript_type_expression_no_store(subscript, slice, value_ty) } ast::Expr::BinOp(binary) => { match binary.op { // PEP-604 unions are okay, e.g., `int | str` ast::Operator::BitOr => { let left_ty = self.infer_type_expression(&binary.left); let right_ty = self.infer_type_expression(&binary.right); UnionType::from_elements_leave_aliases(self.db(), [left_ty, right_ty]) } // anything else is an invalid annotation: op => { // Avoid inferring the types of invalid binary expressions that have been // parsed from a string annotation, as they are not present in the semantic // index. if !self.deferred_state.in_string_annotation() { self.infer_binary_expression(binary, TypeContext::default()); } self.report_invalid_type_expression( expression, format_args!( "Invalid binary operator `{}` in type annotation", op.as_str() ), ); Type::unknown() } } } // Avoid inferring the types of invalid type expressions that have been parsed from a // string annotation, as they are not present in the semantic index. _ if self.deferred_state.in_string_annotation() => Type::unknown(), // ===================================================================================== // Forms which are invalid in the context of annotation expressions: we infer their // nested expressions as normal expressions, but the type of the top-level expression is // always `Type::unknown` in these cases. // ===================================================================================== // TODO: add a subdiagnostic linking to type-expression grammar // and stating that it is only valid in `typing.Literal[]` or `typing.Annotated[]` ast::Expr::BytesLiteral(_) => { self.report_invalid_type_expression( expression, format_args!( "Bytes literals are not allowed in this context in a type expression" ), ); Type::unknown() } ast::Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Int(_), .. }) => { self.report_invalid_type_expression( expression, format_args!( "Int literals are not allowed in this context in a type expression" ), ); Type::unknown() } ast::Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Float(_), .. }) => { self.report_invalid_type_expression( expression, format_args!("Float literals are not allowed in type expressions"), ); Type::unknown() } ast::Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Complex { .. }, .. }) => { self.report_invalid_type_expression( expression, format_args!("Complex literals are not allowed in type expressions"), ); Type::unknown() } ast::Expr::BooleanLiteral(_) => { self.report_invalid_type_expression( expression, format_args!( "Boolean literals are not allowed in this context in a type expression" ), ); Type::unknown() } ast::Expr::List(list) => { let db = self.db(); let inner_types: Vec<Type<'db>> = list .iter() .map(|element| self.infer_type_expression(element)) .collect(); if let Some(mut diagnostic) = self.report_invalid_type_expression( expression, format_args!( "List literals are not allowed in this context in a type expression" ), ) { if !inner_types.iter().any(|ty| { matches!( ty, Type::Dynamic(DynamicType::Todo(_) | DynamicType::Unknown) ) }) { let hinted_type = if list.len() == 1 { KnownClass::List.to_specialized_instance(db, inner_types) } else { Type::heterogeneous_tuple(db, inner_types) }; diagnostic.set_primary_message(format_args!( "Did you mean `{}`?", hinted_type.display(self.db()), )); } } Type::unknown() } ast::Expr::Tuple(tuple) => { let inner_types: Vec<Type<'db>> = tuple .elts .iter() .map(|expr| self.infer_type_expression(expr)) .collect(); if tuple.parenthesized { if let Some(mut diagnostic) = self.report_invalid_type_expression( expression, format_args!( "Tuple literals are not allowed in this context in a type expression" ), ) { if !inner_types.iter().any(|ty| { matches!( ty, Type::Dynamic(DynamicType::Todo(_) | DynamicType::Unknown) ) }) { let hinted_type = Type::heterogeneous_tuple(self.db(), inner_types); diagnostic.set_primary_message(format_args!( "Did you mean `{}`?", hinted_type.display(self.db()), )); } } } Type::unknown() } ast::Expr::BoolOp(bool_op) => { self.infer_boolean_expression(bool_op); self.report_invalid_type_expression( expression, format_args!("Boolean operations are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Named(named) => { self.infer_named_expression(named); self.report_invalid_type_expression( expression, format_args!("Named expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::UnaryOp(unary) => { self.infer_unary_expression(unary); self.report_invalid_type_expression( expression, format_args!("Unary operations are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Lambda(lambda_expression) => { self.infer_lambda_expression(lambda_expression); self.report_invalid_type_expression( expression, format_args!("`lambda` expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::If(if_expression) => { self.infer_if_expression(if_expression, TypeContext::default()); self.report_invalid_type_expression( expression, format_args!("`if` expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Dict(dict) => { self.infer_dict_expression(dict, TypeContext::default()); self.report_invalid_type_expression( expression, format_args!("Dict literals are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Set(set) => { self.infer_set_expression(set, TypeContext::default()); self.report_invalid_type_expression( expression, format_args!("Set literals are not allowed in type expressions"), ); Type::unknown() } ast::Expr::DictComp(dictcomp) => { self.infer_dict_comprehension_expression(dictcomp, TypeContext::default()); self.report_invalid_type_expression( expression, format_args!("Dict comprehensions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::ListComp(listcomp) => { self.infer_list_comprehension_expression(listcomp, TypeContext::default()); self.report_invalid_type_expression( expression, format_args!("List comprehensions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::SetComp(setcomp) => { self.infer_set_comprehension_expression(setcomp, TypeContext::default()); self.report_invalid_type_expression( expression, format_args!("Set comprehensions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Generator(generator) => { self.infer_generator_expression(generator); self.report_invalid_type_expression( expression, format_args!("Generator expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Await(await_expression) => { self.infer_await_expression(await_expression); self.report_invalid_type_expression( expression, format_args!("`await` expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Yield(yield_expression) => { self.infer_yield_expression(yield_expression); self.report_invalid_type_expression( expression, format_args!("`yield` expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::YieldFrom(yield_from) => { self.infer_yield_from_expression(yield_from); self.report_invalid_type_expression( expression, format_args!("`yield from` expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Compare(compare) => { self.infer_compare_expression(compare); self.report_invalid_type_expression( expression, format_args!("Comparison expressions are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Call(call_expr) => { self.infer_call_expression(call_expr, TypeContext::default()); self.report_invalid_type_expression( expression, format_args!("Function calls are not allowed in type expressions"), ); Type::unknown() } ast::Expr::FString(fstring) => { self.infer_fstring_expression(fstring); self.report_invalid_type_expression( expression, format_args!("F-strings are not allowed in type expressions"), ); Type::unknown() } ast::Expr::TString(tstring) => { self.infer_tstring_expression(tstring); self.report_invalid_type_expression( expression, format_args!("T-strings are not allowed in type expressions"), ); Type::unknown() } ast::Expr::Slice(slice) => { self.infer_slice_expression(slice); self.report_invalid_type_expression( expression, format_args!("Slices are not allowed in type expressions"), ); Type::unknown() } // ================================================================================= // Branches where we probably should emit diagnostics in some context, but don't yet // ================================================================================= // TODO: When this case is implemented and the `todo!` usage // is removed, consider adding `todo = "warn"` to the Clippy // lint configuration in `Cargo.toml`. At time of writing, // 2025-08-22, this was the only usage of `todo!` in ruff/ty. // ---AG ast::Expr::IpyEscapeCommand(_) => todo!("Implement Ipy escape command support"), ast::Expr::EllipsisLiteral(_) => { todo_type!("ellipsis literal in type expression") } ast::Expr::Starred(starred) => self.infer_starred_type_expression(starred), } } fn infer_starred_type_expression(&mut self, starred: &ast::ExprStarred) -> Type<'db> { let ast::ExprStarred { range: _, node_index: _, value, ctx: _, } = starred; let starred_type = self.infer_type_expression(value); if starred_type.exact_tuple_instance_spec(self.db()).is_some() { starred_type } else { Type::Dynamic(DynamicType::TodoStarredExpression) } } pub(super) fn infer_subscript_type_expression_no_store( &mut self, subscript: &ast::ExprSubscript, slice: &ast::Expr, value_ty: Type<'db>, ) -> Type<'db> { match value_ty { Type::ClassLiteral(class_literal) => match class_literal.known(self.db()) { Some(KnownClass::Tuple) => Type::tuple(self.infer_tuple_type_expression(slice)), Some(KnownClass::Type) => self.infer_subclass_of_type_expression(slice), _ => self.infer_subscript_type_expression(subscript, value_ty), }, _ => self.infer_subscript_type_expression(subscript, value_ty), } } /// Infer the type of a string type expression. pub(super) fn infer_string_type_expression( &mut self, string: &ast::ExprStringLiteral, ) -> Type<'db> { match parse_string_annotation(&self.context, string) { Some(parsed) => { self.string_annotations .insert(ruff_python_ast::ExprRef::StringLiteral(string).into()); // String annotations are always evaluated in the deferred context. self.infer_type_expression_with_state( parsed.expr(), DeferredExpressionState::InStringAnnotation( self.enclosing_node_key(string.into()), ), ) } None => Type::unknown(), } } /// Given the slice of a `tuple[]` annotation, return the type that the annotation represents pub(super) fn infer_tuple_type_expression( &mut self, tuple_slice: &ast::Expr, ) -> Option<TupleType<'db>> { /// In most cases, if a subelement of the tuple is inferred as `Todo`, /// we should only infer `Todo` for that specific subelement. /// Certain specific AST nodes can however change the meaning of the entire tuple, /// however: for example, `tuple[int, ...]` or `tuple[int, *tuple[str, ...]]` are a /// homogeneous tuple and a partly homogeneous tuple (respectively) due to the `...` /// and the starred expression (respectively), Neither is supported by us right now, /// so we should infer `Todo` for the *entire* tuple if we encounter one of those elements. fn element_could_alter_type_of_whole_tuple( element: &ast::Expr, element_ty: Type, builder: &mut TypeInferenceBuilder, ) -> bool { if !element_ty.is_todo() { return false; } match element { ast::Expr::Starred(_) => { element_ty.exact_tuple_instance_spec(builder.db()).is_none() } ast::Expr::Subscript(ast::ExprSubscript { value, .. }) => { let value_ty = if builder.deferred_state.in_string_annotation() { // Using `.expression_type` does not work in string annotations, because // we do not store types for sub-expressions. Re-infer the type here. builder.infer_expression(value, TypeContext::default()) } else { builder.expression_type(value) }; value_ty == Type::SpecialForm(SpecialFormType::Unpack) } _ => false, } } // TODO: PEP 646 match tuple_slice { ast::Expr::Tuple(elements) => { if let [element, ellipsis @ ast::Expr::EllipsisLiteral(_)] = &*elements.elts { self.infer_expression(ellipsis, TypeContext::default()); let result = TupleType::homogeneous(self.db(), self.infer_type_expression(element)); self.store_expression_type(tuple_slice, Type::tuple(Some(result))); return Some(result); } let mut element_types = TupleSpecBuilder::with_capacity(elements.len()); // Whether to infer `Todo` for the whole tuple // (see docstring for `element_could_alter_type_of_whole_tuple`) let mut return_todo = false; for element in elements { let element_ty = self.infer_type_expression(element); return_todo |= element_could_alter_type_of_whole_tuple(element, element_ty, self); if let ast::Expr::Starred(_) = element { if let Some(inner_tuple) = element_ty.exact_tuple_instance_spec(self.db()) { element_types = element_types.concat(self.db(), &inner_tuple); } else { // TODO: emit a diagnostic } } else { element_types.push(element_ty); } } let ty = if return_todo { Some(TupleType::homogeneous(self.db(), todo_type!("PEP 646"))) } else { TupleType::new(self.db(), &element_types.build()) }; // Here, we store the type for the inner `int, str` tuple-expression, // while the type for the outer `tuple[int, str]` slice-expression is // stored in the surrounding `infer_type_expression` call: self.store_expression_type(tuple_slice, Type::tuple(ty)); ty } single_element => { let single_element_ty = self.infer_type_expression(single_element); if element_could_alter_type_of_whole_tuple(single_element, single_element_ty, self) { Some(TupleType::homogeneous(self.db(), todo_type!("PEP 646"))) } else { TupleType::heterogeneous(self.db(), std::iter::once(single_element_ty)) } } } } /// Given the slice of a `type[]` annotation, return the type that the annotation represents fn infer_subclass_of_type_expression(&mut self, slice: &ast::Expr) -> Type<'db> { match slice { ast::Expr::Name(_) | ast::Expr::Attribute(_) => { SubclassOfType::try_from_instance(self.db(), self.infer_type_expression(slice)) .unwrap_or(todo_type!("unsupported type[X] special form")) } ast::Expr::BinOp(binary) if binary.op == ast::Operator::BitOr => { let union_ty = UnionType::from_elements_leave_aliases( self.db(), [ self.infer_subclass_of_type_expression(&binary.left), self.infer_subclass_of_type_expression(&binary.right), ], ); self.store_expression_type(slice, union_ty); union_ty } ast::Expr::Tuple(_) => { self.infer_type_expression(slice); if let Some(builder) = self.context.report_lint(&INVALID_TYPE_FORM, slice) { builder.into_diagnostic("type[...] must have exactly one type argument"); } Type::unknown() } ast::Expr::Subscript( subscript @ ast::ExprSubscript { value, slice: parameters, .. }, ) => { let parameters_ty = match self.infer_expression(value, TypeContext::default()) { Type::SpecialForm(SpecialFormType::Union) => match &**parameters { ast::Expr::Tuple(tuple) => { let ty = UnionType::from_elements_leave_aliases( self.db(), tuple .iter() .map(|element| self.infer_subclass_of_type_expression(element)), ); self.store_expression_type(parameters, ty); ty } _ => self.infer_subclass_of_type_expression(parameters), }, value_ty @ Type::ClassLiteral(class_literal) => { if class_literal.is_protocol(self.db()) { SubclassOfType::from( self.db(), todo_type!("type[T] for protocols").expect_dynamic(), ) } else if class_literal.is_tuple(self.db()) { let class_type = self .infer_tuple_type_expression(parameters) .map(|tuple_type| tuple_type.to_class_type(self.db())) .unwrap_or_else(|| class_literal.default_specialization(self.db())); SubclassOfType::from(self.db(), class_type) } else { match class_literal.generic_context(self.db()) { Some(generic_context) => { let db = self.db(); let specialize = |types: &[Option<Type<'db>>]| { SubclassOfType::from( db, class_literal.apply_specialization(db, |_| { generic_context .specialize_partial(db, types.iter().copied()) }), ) }; self.infer_explicit_callable_specialization( subscript, value_ty, generic_context, specialize, ) } None => { // TODO: emit a diagnostic if you try to specialize a non-generic class. self.infer_type_expression(parameters); todo_type!("specialized non-generic class") } } } } _ => { self.infer_type_expression(parameters); todo_type!("unsupported nested subscript in type[X]") } }; self.store_expression_type(slice, parameters_ty); parameters_ty } // TODO: subscripts, etc. _ => { self.infer_type_expression(slice); todo_type!("unsupported type[X] special form") } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/infer/builder/annotation_expression.rs
crates/ty_python_semantic/src/types/infer/builder/annotation_expression.rs
use ruff_python_ast as ast; use super::{DeferredExpressionState, TypeInferenceBuilder}; use crate::place::TypeOrigin; use crate::types::diagnostic::{INVALID_TYPE_FORM, report_invalid_arguments_to_annotated}; use crate::types::string_annotation::{ BYTE_STRING_TYPE_ANNOTATION, FSTRING_TYPE_ANNOTATION, parse_string_annotation, }; use crate::types::{ KnownClass, SpecialFormType, Type, TypeAndQualifiers, TypeContext, TypeQualifiers, todo_type, }; #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum PEP613Policy { Allowed, Disallowed, } /// Annotation expressions. impl<'db> TypeInferenceBuilder<'db, '_> { /// Infer the type of an annotation expression with the given [`DeferredExpressionState`]. pub(super) fn infer_annotation_expression( &mut self, annotation: &ast::Expr, deferred_state: DeferredExpressionState, ) -> TypeAndQualifiers<'db> { self.infer_annotation_expression_inner(annotation, deferred_state, PEP613Policy::Disallowed) } /// Infer the type of an annotation expression with the given [`DeferredExpressionState`], /// allowing a PEP 613 `typing.TypeAlias` annotation. pub(super) fn infer_annotation_expression_allow_pep_613( &mut self, annotation: &ast::Expr, deferred_state: DeferredExpressionState, ) -> TypeAndQualifiers<'db> { self.infer_annotation_expression_inner(annotation, deferred_state, PEP613Policy::Allowed) } /// Similar to [`infer_annotation_expression`], but accepts an optional annotation expression /// and returns [`None`] if the annotation is [`None`]. /// /// [`infer_annotation_expression`]: TypeInferenceBuilder::infer_annotation_expression pub(super) fn infer_optional_annotation_expression( &mut self, annotation: Option<&ast::Expr>, deferred_state: DeferredExpressionState, ) -> Option<TypeAndQualifiers<'db>> { annotation.map(|expr| self.infer_annotation_expression(expr, deferred_state)) } fn infer_annotation_expression_inner( &mut self, annotation: &ast::Expr, deferred_state: DeferredExpressionState, pep_613_policy: PEP613Policy, ) -> TypeAndQualifiers<'db> { // `DeferredExpressionState::InStringAnnotation` takes precedence over other deferred states. // However, if it's not a stringified annotation, we must still ensure that annotation expressions // are always deferred in stub files. let state = if deferred_state.in_string_annotation() { deferred_state } else if self.in_stub() { DeferredExpressionState::Deferred } else { deferred_state }; let previous_deferred_state = std::mem::replace(&mut self.deferred_state, state); let annotation_ty = self.infer_annotation_expression_impl(annotation, pep_613_policy); self.deferred_state = previous_deferred_state; annotation_ty } /// Implementation of [`infer_annotation_expression`]. /// /// [`infer_annotation_expression`]: TypeInferenceBuilder::infer_annotation_expression fn infer_annotation_expression_impl( &mut self, annotation: &ast::Expr, pep_613_policy: PEP613Policy, ) -> TypeAndQualifiers<'db> { fn infer_name_or_attribute<'db>( ty: Type<'db>, annotation: &ast::Expr, builder: &TypeInferenceBuilder<'db, '_>, pep_613_policy: PEP613Policy, ) -> TypeAndQualifiers<'db> { match ty { Type::SpecialForm(SpecialFormType::ClassVar) => TypeAndQualifiers::new( Type::unknown(), TypeOrigin::Declared, TypeQualifiers::CLASS_VAR, ), Type::SpecialForm(SpecialFormType::Final) => TypeAndQualifiers::new( Type::unknown(), TypeOrigin::Declared, TypeQualifiers::FINAL, ), Type::SpecialForm(SpecialFormType::Required) => TypeAndQualifiers::new( Type::unknown(), TypeOrigin::Declared, TypeQualifiers::REQUIRED, ), Type::SpecialForm(SpecialFormType::NotRequired) => TypeAndQualifiers::new( Type::unknown(), TypeOrigin::Declared, TypeQualifiers::NOT_REQUIRED, ), Type::SpecialForm(SpecialFormType::ReadOnly) => TypeAndQualifiers::new( Type::unknown(), TypeOrigin::Declared, TypeQualifiers::READ_ONLY, ), Type::SpecialForm(SpecialFormType::TypeAlias) if pep_613_policy == PEP613Policy::Allowed => { TypeAndQualifiers::declared(ty) } // Conditional import of `typing.TypeAlias` or `typing_extensions.TypeAlias` on a // Python version where the former doesn't exist. Type::Union(union) if pep_613_policy == PEP613Policy::Allowed && union.elements(builder.db()).iter().all(|ty| { matches!( ty, Type::SpecialForm(SpecialFormType::TypeAlias) | Type::Dynamic(_) ) }) => { TypeAndQualifiers::declared(Type::SpecialForm(SpecialFormType::TypeAlias)) } Type::ClassLiteral(class) if class.is_known(builder.db(), KnownClass::InitVar) => { if let Some(builder) = builder.context.report_lint(&INVALID_TYPE_FORM, annotation) { builder .into_diagnostic("`InitVar` may not be used without a type argument"); } TypeAndQualifiers::new( Type::unknown(), TypeOrigin::Declared, TypeQualifiers::INIT_VAR, ) } _ => TypeAndQualifiers::declared( ty.default_specialize(builder.db()) .in_type_expression( builder.db(), builder.scope(), builder.typevar_binding_context, ) .unwrap_or_else(|error| { error.into_fallback_type( &builder.context, annotation, builder.is_reachable(annotation), ) }), ), } } // https://typing.python.org/en/latest/spec/annotations.html#grammar-token-expression-grammar-annotation_expression let annotation_ty = match annotation { // String annotations: https://typing.python.org/en/latest/spec/annotations.html#string-annotations ast::Expr::StringLiteral(string) => self.infer_string_annotation_expression(string), // Annotation expressions also get special handling for `*args` and `**kwargs`. ast::Expr::Starred(starred) => { TypeAndQualifiers::declared(self.infer_starred_expression(starred)) } ast::Expr::BytesLiteral(bytes) => { if let Some(builder) = self .context .report_lint(&BYTE_STRING_TYPE_ANNOTATION, bytes) { builder.into_diagnostic("Type expressions cannot use bytes literal"); } TypeAndQualifiers::declared(Type::unknown()) } ast::Expr::FString(fstring) => { if let Some(builder) = self.context.report_lint(&FSTRING_TYPE_ANNOTATION, fstring) { builder.into_diagnostic("Type expressions cannot use f-strings"); } self.infer_fstring_expression(fstring); TypeAndQualifiers::declared(Type::unknown()) } ast::Expr::Attribute(attribute) => match attribute.ctx { ast::ExprContext::Load => { let attribute_type = self.infer_attribute_expression(attribute); if let Type::TypeVar(typevar) = attribute_type && typevar.paramspec_attr(self.db()).is_some() { TypeAndQualifiers::declared(attribute_type) } else { infer_name_or_attribute(attribute_type, annotation, self, pep_613_policy) } } ast::ExprContext::Invalid => TypeAndQualifiers::declared(Type::unknown()), ast::ExprContext::Store | ast::ExprContext::Del => TypeAndQualifiers::declared( todo_type!("Attribute expression annotation in Store/Del context"), ), }, ast::Expr::Name(name) => match name.ctx { ast::ExprContext::Load => infer_name_or_attribute( self.infer_name_expression(name), annotation, self, pep_613_policy, ), ast::ExprContext::Invalid => TypeAndQualifiers::declared(Type::unknown()), ast::ExprContext::Store | ast::ExprContext::Del => TypeAndQualifiers::declared( todo_type!("Name expression annotation in Store/Del context"), ), }, ast::Expr::Subscript(subscript @ ast::ExprSubscript { value, slice, .. }) => { let value_ty = self.infer_expression(value, TypeContext::default()); let slice = &**slice; match value_ty { Type::SpecialForm(SpecialFormType::Annotated) => { // This branch is similar to the corresponding branch in `infer_parameterized_special_form_type_expression`, but // `Annotated[…]` can appear both in annotation expressions and in type expressions, and needs to be handled slightly // differently in each case (calling either `infer_type_expression_*` or `infer_annotation_expression_*`). if let ast::Expr::Tuple(ast::ExprTuple { elts: arguments, .. }) = slice { if arguments.len() < 2 { report_invalid_arguments_to_annotated(&self.context, subscript); } if let [inner_annotation, metadata @ ..] = &arguments[..] { for element in metadata { self.infer_expression(element, TypeContext::default()); } let inner_annotation_ty = self.infer_annotation_expression_impl( inner_annotation, PEP613Policy::Disallowed, ); self.store_expression_type(slice, inner_annotation_ty.inner_type()); inner_annotation_ty } else { for argument in arguments { self.infer_expression(argument, TypeContext::default()); } self.store_expression_type(slice, Type::unknown()); TypeAndQualifiers::declared(Type::unknown()) } } else { report_invalid_arguments_to_annotated(&self.context, subscript); self.infer_annotation_expression_impl(slice, PEP613Policy::Disallowed) } } Type::SpecialForm( type_qualifier @ (SpecialFormType::ClassVar | SpecialFormType::Final | SpecialFormType::Required | SpecialFormType::NotRequired | SpecialFormType::ReadOnly), ) => { let arguments = if let ast::Expr::Tuple(tuple) = slice { &*tuple.elts } else { std::slice::from_ref(slice) }; let type_and_qualifiers = if let [argument] = arguments { let mut type_and_qualifiers = self.infer_annotation_expression_impl( argument, PEP613Policy::Disallowed, ); match type_qualifier { SpecialFormType::ClassVar => { type_and_qualifiers.add_qualifier(TypeQualifiers::CLASS_VAR); } SpecialFormType::Final => { type_and_qualifiers.add_qualifier(TypeQualifiers::FINAL); } SpecialFormType::Required => { type_and_qualifiers.add_qualifier(TypeQualifiers::REQUIRED); } SpecialFormType::NotRequired => { type_and_qualifiers.add_qualifier(TypeQualifiers::NOT_REQUIRED); } SpecialFormType::ReadOnly => { type_and_qualifiers.add_qualifier(TypeQualifiers::READ_ONLY); } _ => unreachable!(), } type_and_qualifiers } else { for element in arguments { self.infer_annotation_expression_impl( element, PEP613Policy::Disallowed, ); } if let Some(builder) = self.context.report_lint(&INVALID_TYPE_FORM, subscript) { let num_arguments = arguments.len(); builder.into_diagnostic(format_args!( "Type qualifier `{type_qualifier}` expected exactly 1 argument, \ got {num_arguments}", )); } TypeAndQualifiers::declared(Type::unknown()) }; if slice.is_tuple_expr() { self.store_expression_type(slice, type_and_qualifiers.inner_type()); } type_and_qualifiers } Type::ClassLiteral(class) if class.is_known(self.db(), KnownClass::InitVar) => { let arguments = if let ast::Expr::Tuple(tuple) = slice { &*tuple.elts } else { std::slice::from_ref(slice) }; let type_and_qualifiers = if let [argument] = arguments { let mut type_and_qualifiers = self.infer_annotation_expression_impl( argument, PEP613Policy::Disallowed, ); type_and_qualifiers.add_qualifier(TypeQualifiers::INIT_VAR); type_and_qualifiers } else { for element in arguments { self.infer_annotation_expression_impl( element, PEP613Policy::Disallowed, ); } if let Some(builder) = self.context.report_lint(&INVALID_TYPE_FORM, subscript) { let num_arguments = arguments.len(); builder.into_diagnostic(format_args!( "Type qualifier `InitVar` expected exactly 1 argument, \ got {num_arguments}", )); } TypeAndQualifiers::declared(Type::unknown()) }; if slice.is_tuple_expr() { self.store_expression_type(slice, type_and_qualifiers.inner_type()); } type_and_qualifiers } _ => TypeAndQualifiers::declared( self.infer_subscript_type_expression_no_store(subscript, slice, value_ty), ), } } // All other annotation expressions are (possibly) valid type expressions, so handle // them there instead. type_expr => { TypeAndQualifiers::declared(self.infer_type_expression_no_store(type_expr)) } }; self.store_expression_type(annotation, annotation_ty.inner_type()); annotation_ty } /// Infer the type of a string annotation expression. fn infer_string_annotation_expression( &mut self, string: &ast::ExprStringLiteral, ) -> TypeAndQualifiers<'db> { match parse_string_annotation(&self.context, string) { Some(parsed) => { self.string_annotations .insert(ruff_python_ast::ExprRef::StringLiteral(string).into()); // String annotations are always evaluated in the deferred context. self.infer_annotation_expression( parsed.expr(), DeferredExpressionState::InStringAnnotation( self.enclosing_node_key(string.into()), ), ) } None => TypeAndQualifiers::declared(Type::unknown()), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/property_tests/setup.rs
crates/ty_python_semantic/src/types/property_tests/setup.rs
use crate::db::tests::{TestDb, setup_db}; use std::sync::{Arc, Mutex, OnceLock}; static CACHED_DB: OnceLock<Arc<Mutex<TestDb>>> = OnceLock::new(); pub(crate) fn get_cached_db() -> TestDb { let db = CACHED_DB.get_or_init(|| Arc::new(Mutex::new(setup_db()))); db.lock().unwrap().clone() }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/types/property_tests/type_generation.rs
crates/ty_python_semantic/src/types/property_tests/type_generation.rs
use crate::Db; use crate::db::tests::TestDb; use crate::place::{builtins_symbol, known_module_symbol}; use crate::types::enums::is_single_member_enum; use crate::types::tuple::TupleType; use crate::types::{ BoundMethodType, EnumLiteralType, IntersectionBuilder, IntersectionType, KnownClass, Parameter, Parameters, Signature, SpecialFormType, SubclassOfType, Type, UnionType, }; use quickcheck::{Arbitrary, Gen}; use ruff_python_ast::name::Name; use rustc_hash::FxHashSet; use ty_module_resolver::KnownModule; /// A test representation of a type that can be transformed unambiguously into a real Type, /// given a db. /// /// TODO: We should add some variants that exercise generic classes and specializations thereof. #[derive(Debug, Clone, PartialEq)] pub(crate) enum Ty { Never, Unknown, None, Any, IntLiteral(i64), BooleanLiteral(bool), StringLiteral(&'static str), LiteralString, BytesLiteral(&'static str), // An enum literal variant, using `uuid.SafeUUID` as base EnumLiteral(&'static str), // A single-member enum literal, using `dataclasses.MISSING` SingleMemberEnumLiteral, // BuiltinInstance("str") corresponds to an instance of the builtin `str` class BuiltinInstance(&'static str), /// Members of the `abc` stdlib module AbcInstance(&'static str), AbcClassLiteral(&'static str), TypingLiteral, // BuiltinClassLiteral("str") corresponds to the builtin `str` class object itself BuiltinClassLiteral(&'static str), KnownClassInstance(KnownClass), Union(Vec<Ty>), Intersection { pos: Vec<Ty>, neg: Vec<Ty>, }, FixedLengthTuple(Vec<Ty>), VariableLengthTuple(Vec<Ty>, Box<Ty>, Vec<Ty>), SubclassOfAny, SubclassOfBuiltinClass(&'static str), SubclassOfAbcClass(&'static str), AlwaysTruthy, AlwaysFalsy, BuiltinsFunction(&'static str), BuiltinsBoundMethod { class: &'static str, method: &'static str, }, Callable { params: CallableParams, returns: Option<Box<Ty>>, }, /// `unittest.mock.Mock` is interesting because it is a nominal instance type /// where the class has `Any` in its MRO UnittestMockInstance, UnittestMockLiteral, } #[derive(Debug, Clone, PartialEq)] pub(crate) enum CallableParams { GradualForm, List(Vec<Param>), } impl CallableParams { pub(crate) fn into_parameters(self, db: &TestDb) -> Parameters<'_> { match self { CallableParams::GradualForm => Parameters::gradual_form(), CallableParams::List(params) => Parameters::new( db, params.into_iter().map(|param| { let mut parameter = match param.kind { ParamKind::PositionalOnly => Parameter::positional_only(param.name), ParamKind::PositionalOrKeyword => { Parameter::positional_or_keyword(param.name.unwrap()) } ParamKind::Variadic => Parameter::variadic(param.name.unwrap()), ParamKind::KeywordOnly => Parameter::keyword_only(param.name.unwrap()), ParamKind::KeywordVariadic => { Parameter::keyword_variadic(param.name.unwrap()) } }; if let Some(annotated_ty) = param.annotated_ty { parameter = parameter.with_annotated_type(annotated_ty.into_type(db)); } if let Some(default_ty) = param.default_ty { parameter = parameter.with_default_type(default_ty.into_type(db)); } parameter }), ), } } } #[derive(Debug, Clone, PartialEq)] pub(crate) struct Param { kind: ParamKind, name: Option<Name>, annotated_ty: Option<Ty>, default_ty: Option<Ty>, } #[derive(Debug, Clone, Copy, PartialEq)] enum ParamKind { PositionalOnly, PositionalOrKeyword, Variadic, KeywordOnly, KeywordVariadic, } #[salsa::tracked(heap_size=ruff_memory_usage::heap_size)] fn create_bound_method<'db>( db: &'db dyn Db, function: Type<'db>, builtins_class: Type<'db>, ) -> Type<'db> { Type::BoundMethod(BoundMethodType::new( db, function.expect_function_literal(), builtins_class.to_instance(db).unwrap(), )) } impl Ty { pub(crate) fn into_type(self, db: &TestDb) -> Type<'_> { match self { Ty::Never => Type::Never, Ty::Unknown => Type::unknown(), Ty::None => Type::none(db), Ty::Any => Type::any(), Ty::IntLiteral(n) => Type::IntLiteral(n), Ty::StringLiteral(s) => Type::string_literal(db, s), Ty::BooleanLiteral(b) => Type::BooleanLiteral(b), Ty::LiteralString => Type::LiteralString, Ty::BytesLiteral(s) => Type::bytes_literal(db, s.as_bytes()), Ty::EnumLiteral(name) => Type::EnumLiteral(EnumLiteralType::new( db, known_module_symbol(db, KnownModule::Uuid, "SafeUUID") .place .expect_type() .expect_class_literal(), Name::new(name), )), Ty::SingleMemberEnumLiteral => { let ty = known_module_symbol(db, KnownModule::Dataclasses, "MISSING") .place .expect_type(); debug_assert!( matches!(ty, Type::NominalInstance(instance) if is_single_member_enum(db, instance.class_literal(db))) ); ty } Ty::BuiltinInstance(s) => builtins_symbol(db, s) .place .expect_type() .to_instance(db) .unwrap(), Ty::AbcInstance(s) => known_module_symbol(db, KnownModule::Abc, s) .place .expect_type() .to_instance(db) .unwrap(), Ty::AbcClassLiteral(s) => known_module_symbol(db, KnownModule::Abc, s) .place .expect_type(), Ty::UnittestMockLiteral => known_module_symbol(db, KnownModule::UnittestMock, "Mock") .place .expect_type(), Ty::UnittestMockInstance => Ty::UnittestMockLiteral .into_type(db) .to_instance(db) .unwrap(), Ty::TypingLiteral => Type::SpecialForm(SpecialFormType::Literal), Ty::BuiltinClassLiteral(s) => builtins_symbol(db, s).place.expect_type(), Ty::KnownClassInstance(known_class) => known_class.to_instance(db), Ty::Union(tys) => { UnionType::from_elements(db, tys.into_iter().map(|ty| ty.into_type(db))) } Ty::Intersection { pos, neg } => { let mut builder = IntersectionBuilder::new(db); for p in pos { builder = builder.add_positive(p.into_type(db)); } for n in neg { builder = builder.add_negative(n.into_type(db)); } builder.build() } Ty::FixedLengthTuple(tys) => { let elements = tys.into_iter().map(|ty| ty.into_type(db)); Type::heterogeneous_tuple(db, elements) } Ty::VariableLengthTuple(prefix, variable, suffix) => { let prefix = prefix.into_iter().map(|ty| ty.into_type(db)); let variable = variable.into_type(db); let suffix = suffix.into_iter().map(|ty| ty.into_type(db)); Type::tuple(TupleType::mixed(db, prefix, variable, suffix)) } Ty::SubclassOfAny => SubclassOfType::subclass_of_any(), Ty::SubclassOfBuiltinClass(s) => SubclassOfType::from( db, builtins_symbol(db, s) .place .expect_type() .expect_class_literal() .default_specialization(db), ), Ty::SubclassOfAbcClass(s) => SubclassOfType::from( db, known_module_symbol(db, KnownModule::Abc, s) .place .expect_type() .expect_class_literal() .default_specialization(db), ), Ty::AlwaysTruthy => Type::AlwaysTruthy, Ty::AlwaysFalsy => Type::AlwaysFalsy, Ty::BuiltinsFunction(name) => builtins_symbol(db, name).place.expect_type(), Ty::BuiltinsBoundMethod { class, method } => { let builtins_class = builtins_symbol(db, class).place.expect_type(); let function = builtins_class.member(db, method).place.expect_type(); create_bound_method(db, function, builtins_class) } Ty::Callable { params, returns } => Type::single_callable( db, Signature::new( params.into_parameters(db), returns.map(|ty| ty.into_type(db)), ), ), } } } #[derive(Debug, Clone, PartialEq)] pub(crate) struct FullyStaticTy(Ty); impl FullyStaticTy { pub(crate) fn into_type(self, db: &TestDb) -> Type<'_> { self.0.into_type(db) } } fn arbitrary_core_type(g: &mut Gen, fully_static: bool) -> Ty { // We could select a random integer here, but this would make it much less // likely to explore interesting edge cases: let int_lit = Ty::IntLiteral(*g.choose(&[-2, -1, 0, 1, 2]).unwrap()); let bool_lit = Ty::BooleanLiteral(bool::arbitrary(g)); // Update this if new non-fully-static types are added below. let fully_static_index = 5; let types = &[ Ty::Any, Ty::Unknown, Ty::SubclassOfAny, Ty::UnittestMockLiteral, Ty::UnittestMockInstance, // Add fully static types below, dynamic types above. // Update `fully_static_index` above if adding new dynamic types! Ty::Never, Ty::None, int_lit, bool_lit, Ty::StringLiteral(""), Ty::StringLiteral("a"), Ty::LiteralString, Ty::BytesLiteral(""), Ty::BytesLiteral("\x00"), Ty::EnumLiteral("safe"), Ty::EnumLiteral("unsafe"), Ty::EnumLiteral("unknown"), Ty::SingleMemberEnumLiteral, Ty::KnownClassInstance(KnownClass::Object), Ty::KnownClassInstance(KnownClass::Str), Ty::KnownClassInstance(KnownClass::Int), Ty::KnownClassInstance(KnownClass::Bool), Ty::KnownClassInstance(KnownClass::FunctionType), Ty::KnownClassInstance(KnownClass::SpecialForm), Ty::KnownClassInstance(KnownClass::TypeVar), Ty::KnownClassInstance(KnownClass::TypeAliasType), Ty::KnownClassInstance(KnownClass::NoDefaultType), Ty::TypingLiteral, Ty::BuiltinClassLiteral("str"), Ty::BuiltinClassLiteral("int"), Ty::BuiltinClassLiteral("bool"), Ty::BuiltinClassLiteral("object"), Ty::BuiltinInstance("type"), Ty::AbcInstance("ABC"), Ty::AbcInstance("ABCMeta"), Ty::SubclassOfBuiltinClass("object"), Ty::SubclassOfBuiltinClass("str"), Ty::SubclassOfBuiltinClass("type"), Ty::AbcClassLiteral("ABC"), Ty::AbcClassLiteral("ABCMeta"), Ty::SubclassOfAbcClass("ABC"), Ty::SubclassOfAbcClass("ABCMeta"), Ty::AlwaysTruthy, Ty::AlwaysFalsy, Ty::BuiltinsFunction("chr"), Ty::BuiltinsFunction("ascii"), Ty::BuiltinsBoundMethod { class: "str", method: "isascii", }, Ty::BuiltinsBoundMethod { class: "int", method: "bit_length", }, ]; let types = if fully_static { &types[fully_static_index..] } else { types }; g.choose(types).unwrap().clone() } /// Constructs an arbitrary type. /// /// The `size` parameter controls the depth of the type tree. For example, /// a simple type like `int` has a size of 0, `Union[int, str]` has a size /// of 1, `tuple[int, Union[str, bytes]]` has a size of 2, etc. /// /// The `fully_static` parameter, if `true`, limits generation to fully static types. fn arbitrary_type(g: &mut Gen, size: u32, fully_static: bool) -> Ty { if size == 0 { arbitrary_core_type(g, fully_static) } else { match u32::arbitrary(g) % 6 { 0 => arbitrary_core_type(g, fully_static), 1 => Ty::Union( (0..*g.choose(&[2, 3]).unwrap()) .map(|_| arbitrary_type(g, size - 1, fully_static)) .collect(), ), 2 => Ty::FixedLengthTuple( (0..*g.choose(&[0, 1, 2]).unwrap()) .map(|_| arbitrary_type(g, size - 1, fully_static)) .collect(), ), 3 => Ty::VariableLengthTuple( (0..*g.choose(&[0, 1, 2]).unwrap()) .map(|_| arbitrary_type(g, size - 1, fully_static)) .collect(), Box::new(arbitrary_type(g, size - 1, fully_static)), (0..*g.choose(&[0, 1, 2]).unwrap()) .map(|_| arbitrary_type(g, size - 1, fully_static)) .collect(), ), 4 => Ty::Intersection { pos: (0..*g.choose(&[0, 1, 2]).unwrap()) .map(|_| arbitrary_type(g, size - 1, fully_static)) .collect(), neg: (0..*g.choose(&[0, 1, 2]).unwrap()) .map(|_| arbitrary_type(g, size - 1, fully_static)) .collect(), }, 5 => Ty::Callable { params: match u32::arbitrary(g) % 2 { 0 if !fully_static => CallableParams::GradualForm, _ => CallableParams::List(arbitrary_parameter_list(g, size, fully_static)), }, returns: arbitrary_annotation(g, size - 1, fully_static).map(Box::new), }, _ => unreachable!(), } } } fn arbitrary_parameter_list(g: &mut Gen, size: u32, fully_static: bool) -> Vec<Param> { let mut params: Vec<Param> = vec![]; let mut used_names = FxHashSet::default(); // First, choose the number of parameters to generate. for _ in 0..*g.choose(&[0, 1, 2, 3, 4, 5]).unwrap() { // Next, choose the kind of parameters that can be generated based on the last parameter. let next_kind = match params.last().map(|p| p.kind) { None | Some(ParamKind::PositionalOnly) => *g .choose(&[ ParamKind::PositionalOnly, ParamKind::PositionalOrKeyword, ParamKind::Variadic, ParamKind::KeywordOnly, ParamKind::KeywordVariadic, ]) .unwrap(), Some(ParamKind::PositionalOrKeyword) => *g .choose(&[ ParamKind::PositionalOrKeyword, ParamKind::Variadic, ParamKind::KeywordOnly, ParamKind::KeywordVariadic, ]) .unwrap(), Some(ParamKind::Variadic | ParamKind::KeywordOnly) => *g .choose(&[ParamKind::KeywordOnly, ParamKind::KeywordVariadic]) .unwrap(), Some(ParamKind::KeywordVariadic) => { // There can't be any other parameter kind after a keyword variadic parameter. break; } }; let name = loop { let name = if matches!(next_kind, ParamKind::PositionalOnly) { arbitrary_optional_name(g) } else { Some(arbitrary_name(g)) }; if let Some(name) = name { if used_names.insert(name.clone()) { break Some(name); } } else { break None; } }; params.push(Param { kind: next_kind, name, annotated_ty: arbitrary_annotation(g, size, fully_static), default_ty: if matches!(next_kind, ParamKind::Variadic | ParamKind::KeywordVariadic) { None } else { arbitrary_optional_type(g, size, fully_static) }, }); } params } /// An arbitrary optional type, always `Some` if fully static. fn arbitrary_annotation(g: &mut Gen, size: u32, fully_static: bool) -> Option<Ty> { if fully_static { Some(arbitrary_type(g, size, true)) } else { arbitrary_optional_type(g, size, false) } } fn arbitrary_optional_type(g: &mut Gen, size: u32, fully_static: bool) -> Option<Ty> { match u32::arbitrary(g) % 2 { 0 => None, 1 => Some(arbitrary_type(g, size, fully_static)), _ => unreachable!(), } } fn arbitrary_name(g: &mut Gen) -> Name { Name::new(format!("n{}", u32::arbitrary(g) % 10)) } fn arbitrary_optional_name(g: &mut Gen) -> Option<Name> { match u32::arbitrary(g) % 2 { 0 => None, 1 => Some(arbitrary_name(g)), _ => unreachable!(), } } impl Arbitrary for Ty { fn arbitrary(g: &mut Gen) -> Ty { const MAX_SIZE: u32 = 2; arbitrary_type(g, MAX_SIZE, false) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { match self.clone() { Ty::Union(types) => Box::new(types.shrink().filter_map(|elts| match elts.len() { 0 => None, 1 => Some(elts.into_iter().next().unwrap()), _ => Some(Ty::Union(elts)), })), Ty::FixedLengthTuple(types) => { Box::new(types.shrink().filter_map(|elts| match elts.len() { 0 => None, 1 => Some(elts.into_iter().next().unwrap()), _ => Some(Ty::FixedLengthTuple(elts)), })) } Ty::VariableLengthTuple(prefix, variable, suffix) => { // We shrink the suffix first, then the prefix, then the variable-length type. let suffix_shrunk = suffix.shrink().map({ let prefix = prefix.clone(); let variable = variable.clone(); move |suffix| Ty::VariableLengthTuple(prefix.clone(), variable.clone(), suffix) }); let prefix_shrunk = prefix.shrink().map({ let variable = variable.clone(); let suffix = suffix.clone(); move |prefix| Ty::VariableLengthTuple(prefix, variable.clone(), suffix.clone()) }); let variable_shrunk = variable.shrink().map({ let prefix = prefix.clone(); let suffix = suffix.clone(); move |variable| { Ty::VariableLengthTuple(prefix.clone(), variable, suffix.clone()) } }); Box::new(suffix_shrunk.chain(prefix_shrunk).chain(variable_shrunk)) } Ty::Intersection { pos, neg } => { // Shrinking on intersections is not exhaustive! // // We try to shrink the positive side or the negative side, // but we aren't shrinking both at the same time. // // This should remove positive or negative constraints but // won't shrink (A & B & ~C & ~D) to (A & ~C) in one shrink // iteration. // // Instead, it hopes that (A & B & ~C) or (A & ~C & ~D) fails // so that shrinking can happen there. let pos_orig = pos.clone(); let neg_orig = neg.clone(); Box::new( // we shrink negative constraints first, as // intersections with only negative constraints are // more confusing neg.shrink() .map(move |shrunk_neg| Ty::Intersection { pos: pos_orig.clone(), neg: shrunk_neg, }) .chain(pos.shrink().map(move |shrunk_pos| Ty::Intersection { pos: shrunk_pos, neg: neg_orig.clone(), })) .filter_map(|ty| { if let Ty::Intersection { pos, neg } = &ty { match (pos.len(), neg.len()) { // an empty intersection does not mean // anything (0, 0) => None, // a single positive element should be // unwrapped (1, 0) => Some(pos[0].clone()), _ => Some(ty), } } else { unreachable!() } }), ) } _ => Box::new(std::iter::empty()), } } } impl Arbitrary for FullyStaticTy { fn arbitrary(g: &mut Gen) -> FullyStaticTy { const MAX_SIZE: u32 = 2; FullyStaticTy(arbitrary_type(g, MAX_SIZE, true)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new(self.0.shrink().map(FullyStaticTy)) } } pub(crate) fn intersection<'db>( db: &'db TestDb, tys: impl IntoIterator<Item = Type<'db>>, ) -> Type<'db> { IntersectionType::from_elements(db, tys) } pub(crate) fn union<'db>(db: &'db TestDb, tys: impl IntoIterator<Item = Type<'db>>) -> Type<'db> { UnionType::from_elements(db, tys) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/builder.rs
crates/ty_python_semantic/src/semantic_index/builder.rs
use std::cell::{OnceCell, RefCell}; use std::sync::Arc; use except_handlers::TryNodeContextStackManager; use rustc_hash::{FxHashMap, FxHashSet}; use ruff_db::files::File; use ruff_db::parsed::ParsedModuleRef; use ruff_db::source::{SourceText, source_text}; use ruff_index::IndexVec; use ruff_python_ast::name::Name; use ruff_python_ast::visitor::{Visitor, walk_expr, walk_pattern, walk_stmt}; use ruff_python_ast::{self as ast, NodeIndex, PySourceType, PythonVersion}; use ruff_python_parser::semantic_errors::{ SemanticSyntaxChecker, SemanticSyntaxContext, SemanticSyntaxError, SemanticSyntaxErrorKind, }; use ruff_text_size::TextRange; use ty_module_resolver::{ModuleName, resolve_module}; use crate::ast_node_ref::AstNodeRef; use crate::node_key::NodeKey; use crate::semantic_index::ast_ids::AstIdsBuilder; use crate::semantic_index::ast_ids::node_key::ExpressionNodeKey; use crate::semantic_index::definition::{ AnnotatedAssignmentDefinitionNodeRef, AssignmentDefinitionNodeRef, ComprehensionDefinitionNodeRef, Definition, DefinitionCategory, DefinitionNodeKey, DefinitionNodeRef, Definitions, ExceptHandlerDefinitionNodeRef, ForStmtDefinitionNodeRef, ImportDefinitionNodeRef, ImportFromDefinitionNodeRef, ImportFromSubmoduleDefinitionNodeRef, MatchPatternDefinitionNodeRef, StarImportDefinitionNodeRef, WithItemDefinitionNodeRef, }; use crate::semantic_index::expression::{Expression, ExpressionKind}; use crate::semantic_index::place::{PlaceExpr, PlaceTableBuilder, ScopedPlaceId}; use crate::semantic_index::predicate::{ CallableAndCallExpr, ClassPatternKind, PatternPredicate, PatternPredicateKind, Predicate, PredicateNode, PredicateOrLiteral, ScopedPredicateId, StarImportPlaceholderPredicate, }; use crate::semantic_index::re_exports::exported_names; use crate::semantic_index::reachability_constraints::{ ReachabilityConstraintsBuilder, ScopedReachabilityConstraintId, }; use crate::semantic_index::scope::{ FileScopeId, NodeWithScopeKey, NodeWithScopeKind, NodeWithScopeRef, }; use crate::semantic_index::scope::{Scope, ScopeId, ScopeKind, ScopeLaziness}; use crate::semantic_index::symbol::{ScopedSymbolId, Symbol}; use crate::semantic_index::use_def::{ EnclosingSnapshotKey, FlowSnapshot, ScopedEnclosingSnapshotId, UseDefMapBuilder, }; use crate::semantic_index::{ExpressionsScopeMap, SemanticIndex, VisibleAncestorsIter}; use crate::semantic_model::HasTrackedScope; use crate::unpack::{EvaluationMode, Unpack, UnpackKind, UnpackPosition, UnpackValue}; use crate::{Db, Program}; mod except_handlers; #[derive(Clone, Debug, Default)] struct Loop { /// Flow states at each `break` in the current loop. break_states: Vec<FlowSnapshot>, } impl Loop { fn push_break(&mut self, state: FlowSnapshot) { self.break_states.push(state); } } struct ScopeInfo { file_scope_id: FileScopeId, /// Current loop state; None if we are not currently visiting a loop current_loop: Option<Loop>, } pub(super) struct SemanticIndexBuilder<'db, 'ast> { // Builder state db: &'db dyn Db, file: File, source_type: PySourceType, module: &'ast ParsedModuleRef, scope_stack: Vec<ScopeInfo>, /// The assignments we're currently visiting, with /// the most recent visit at the end of the Vec current_assignments: Vec<CurrentAssignment<'ast, 'db>>, /// The match case we're currently visiting. current_match_case: Option<CurrentMatchCase<'ast>>, /// The name of the first function parameter of the innermost function that we're currently visiting. current_first_parameter_name: Option<&'ast str>, /// Per-scope contexts regarding nested `try`/`except` statements try_node_context_stack_manager: TryNodeContextStackManager, /// Flags about the file's global scope has_future_annotations: bool, /// Whether we are currently visiting an `if TYPE_CHECKING` block. in_type_checking_block: bool, // Used for checking semantic syntax errors python_version: PythonVersion, source_text: OnceCell<SourceText>, semantic_checker: SemanticSyntaxChecker, // Semantic Index fields scopes: IndexVec<FileScopeId, Scope>, scope_ids_by_scope: IndexVec<FileScopeId, ScopeId<'db>>, place_tables: IndexVec<FileScopeId, PlaceTableBuilder>, ast_ids: IndexVec<FileScopeId, AstIdsBuilder>, use_def_maps: IndexVec<FileScopeId, UseDefMapBuilder<'db>>, scopes_by_node: FxHashMap<NodeWithScopeKey, FileScopeId>, scopes_by_expression: ExpressionsScopeMapBuilder, definitions_by_node: FxHashMap<DefinitionNodeKey, Definitions<'db>>, expressions_by_node: FxHashMap<ExpressionNodeKey, Expression<'db>>, imported_modules: FxHashSet<ModuleName>, seen_submodule_imports: FxHashSet<String>, /// Hashset of all [`FileScopeId`]s that correspond to [generator functions]. /// /// [generator functions]: https://docs.python.org/3/glossary.html#term-generator generator_functions: FxHashSet<FileScopeId>, /// Snapshots of enclosing-scope place states visible from nested scopes. enclosing_snapshots: FxHashMap<EnclosingSnapshotKey, ScopedEnclosingSnapshotId>, /// Errors collected by the `semantic_checker`. semantic_syntax_errors: RefCell<Vec<SemanticSyntaxError>>, } impl<'db, 'ast> SemanticIndexBuilder<'db, 'ast> { pub(super) fn new(db: &'db dyn Db, file: File, module_ref: &'ast ParsedModuleRef) -> Self { let mut builder = Self { db, file, source_type: file.source_type(db), module: module_ref, scope_stack: Vec::new(), current_assignments: vec![], current_match_case: None, current_first_parameter_name: None, try_node_context_stack_manager: TryNodeContextStackManager::default(), has_future_annotations: false, in_type_checking_block: false, scopes: IndexVec::new(), place_tables: IndexVec::new(), ast_ids: IndexVec::new(), scope_ids_by_scope: IndexVec::new(), use_def_maps: IndexVec::new(), scopes_by_expression: ExpressionsScopeMapBuilder::new(), scopes_by_node: FxHashMap::default(), definitions_by_node: FxHashMap::default(), expressions_by_node: FxHashMap::default(), seen_submodule_imports: FxHashSet::default(), imported_modules: FxHashSet::default(), generator_functions: FxHashSet::default(), enclosing_snapshots: FxHashMap::default(), python_version: Program::get(db).python_version(db), source_text: OnceCell::new(), semantic_checker: SemanticSyntaxChecker::default(), semantic_syntax_errors: RefCell::default(), }; builder.push_scope_with_parent( NodeWithScopeRef::Module, None, ScopedReachabilityConstraintId::ALWAYS_TRUE, ); builder } fn current_scope_info(&self) -> &ScopeInfo { self.scope_stack .last() .expect("SemanticIndexBuilder should have created a root scope") } fn current_scope_info_mut(&mut self) -> &mut ScopeInfo { self.scope_stack .last_mut() .expect("SemanticIndexBuilder should have created a root scope") } fn current_scope(&self) -> FileScopeId { self.current_scope_info().file_scope_id } /// Returns the scope ID of the current scope if the current scope /// is a method inside a class body or an eagerly executed scope inside a method. /// Returns `None` otherwise, e.g. if the current scope is a function body outside of a class, or if the current scope is not a /// function body. fn is_method_or_eagerly_executed_in_method(&self) -> Option<FileScopeId> { let mut scopes_rev = self .scope_stack .iter() .rev() .skip_while(|scope| self.scopes[scope.file_scope_id].is_eager()); let current = scopes_rev.next()?; if self.scopes[current.file_scope_id].kind() != ScopeKind::Function { return None; } let maybe_method = current.file_scope_id; let parent = scopes_rev.next()?; match self.scopes[parent.file_scope_id].kind() { ScopeKind::Class => Some(maybe_method), ScopeKind::TypeParams => { // If the function is generic, the parent scope is an annotation scope. // In this case, we need to go up one level higher to find the class scope. let grandparent = scopes_rev.next()?; if self.scopes[grandparent.file_scope_id].kind() == ScopeKind::Class { Some(maybe_method) } else { None } } _ => None, } } /// Checks if a symbol name is bound in any intermediate eager scopes /// between the current scope and the specified method scope. /// fn is_symbol_bound_in_intermediate_eager_scopes( &self, symbol_name: &str, method_scope_id: FileScopeId, ) -> bool { for scope_info in self.scope_stack.iter().rev() { let scope_id = scope_info.file_scope_id; if scope_id == method_scope_id { break; } if let Some(symbol_id) = self.place_tables[scope_id].symbol_id(symbol_name) { let symbol = self.place_tables[scope_id].symbol(symbol_id); if symbol.is_bound() { return true; } } } false } /// Push a new loop, returning the outer loop, if any. fn push_loop(&mut self) -> Option<Loop> { self.current_scope_info_mut() .current_loop .replace(Loop::default()) } /// Pop a loop, replacing with the previous saved outer loop, if any. fn pop_loop(&mut self, outer_loop: Option<Loop>) -> Loop { std::mem::replace(&mut self.current_scope_info_mut().current_loop, outer_loop) .expect("pop_loop() should not be called without a prior push_loop()") } fn current_loop_mut(&mut self) -> Option<&mut Loop> { self.current_scope_info_mut().current_loop.as_mut() } fn push_scope(&mut self, node: NodeWithScopeRef) { let parent = self.current_scope(); let reachability = self.current_use_def_map().reachability; self.push_scope_with_parent(node, Some(parent), reachability); } fn push_scope_with_parent( &mut self, node: NodeWithScopeRef, parent: Option<FileScopeId>, reachability: ScopedReachabilityConstraintId, ) { let children_start = self.scopes.next_index() + 1; // Note `node` is guaranteed to be a child of `self.module` let node_with_kind = node.to_kind(self.module); let scope = Scope::new( parent, node_with_kind, children_start..children_start, reachability, self.in_type_checking_block, ); let is_class_scope = scope.kind().is_class(); self.try_node_context_stack_manager.enter_nested_scope(); let file_scope_id = self.scopes.push(scope); self.place_tables.push(PlaceTableBuilder::default()); self.use_def_maps .push(UseDefMapBuilder::new(is_class_scope)); let ast_id_scope = self.ast_ids.push(AstIdsBuilder::default()); let scope_id = ScopeId::new(self.db, self.file, file_scope_id); self.scope_ids_by_scope.push(scope_id); let previous = self.scopes_by_node.insert(node.node_key(), file_scope_id); debug_assert_eq!(previous, None); debug_assert_eq!(ast_id_scope, file_scope_id); self.scope_stack.push(ScopeInfo { file_scope_id, current_loop: None, }); } // Records snapshots of the place states visible from the current eager scope. fn record_eager_snapshots(&mut self, popped_scope_id: FileScopeId) { let popped_scope = &self.scopes[popped_scope_id]; let popped_scope_is_annotation_scope = popped_scope.kind().is_annotation(); // If the scope that we just popped off is an eager scope, we need to "lock" our view of // which bindings reach each of the uses in the scope. Loop through each enclosing scope, // looking for any that bind each place. // TODO: Bindings in eager nested scopes also need to be recorded. For example: // ```python // class C: // x: int | None = None // c = C() // class _: // c.x = 1 // reveal_type(c.x) # revealed: Literal[1] // ``` for enclosing_scope_info in self.scope_stack.iter().rev() { let enclosing_scope_id = enclosing_scope_info.file_scope_id; let is_immediately_enclosing_scope = popped_scope.parent() == Some(enclosing_scope_id); let enclosing_scope_kind = self.scopes[enclosing_scope_id].kind(); let enclosing_place_table = &self.place_tables[enclosing_scope_id]; for nested_place in self.place_tables[popped_scope_id].iter() { // Skip this place if this enclosing scope doesn't contain any bindings for it. // Note that even if this place is bound in the popped scope, // it may refer to the enclosing scope bindings // so we also need to snapshot the bindings of the enclosing scope. let Some(enclosing_place_id) = enclosing_place_table.place_id(nested_place) else { continue; }; let enclosing_place = enclosing_place_table.place(enclosing_place_id); // Snapshot the state of this place that are visible at this point in this // enclosing scope. let key = EnclosingSnapshotKey { enclosing_scope: enclosing_scope_id, enclosing_place: enclosing_place_id, nested_scope: popped_scope_id, nested_laziness: ScopeLaziness::Eager, }; let eager_snapshot = self.use_def_maps[enclosing_scope_id] .snapshot_enclosing_state( enclosing_place_id, enclosing_scope_kind, enclosing_place, popped_scope_is_annotation_scope && is_immediately_enclosing_scope, ); self.enclosing_snapshots.insert(key, eager_snapshot); } // Lazy scopes are "sticky": once we see a lazy scope we stop doing lookups // eagerly, even if we would encounter another eager enclosing scope later on. if !enclosing_scope_kind.is_eager() { break; } } } fn bound_scope(&self, enclosing_scope: FileScopeId, symbol: &Symbol) -> Option<FileScopeId> { self.scope_stack .iter() .rev() .skip_while(|scope| scope.file_scope_id != enclosing_scope) .find_map(|scope_info| { let scope_id = scope_info.file_scope_id; let place_table = &self.place_tables[scope_id]; let place_id = place_table.symbol_id(symbol.name())?; place_table.place(place_id).is_bound().then_some(scope_id) }) } // Records snapshots of the place states visible from the current lazy scope. fn record_lazy_snapshots(&mut self, popped_scope_id: FileScopeId) { for enclosing_scope_info in self.scope_stack.iter().rev() { let enclosing_scope_id = enclosing_scope_info.file_scope_id; let enclosing_scope_kind = self.scopes[enclosing_scope_id].kind(); let enclosing_place_table = &self.place_tables[enclosing_scope_id]; // We don't record lazy snapshots of attributes or subscripts, because these are difficult to track as they modify. for nested_symbol in self.place_tables[popped_scope_id].symbols() { // For the same reason, symbols declared as nonlocal or global are not recorded. // Also, if the enclosing scope allows its members to be modified from elsewhere, the snapshot will not be recorded. // (In the case of class scopes, class variables can be modified from elsewhere, but this has no effect in nested scopes, // as class variables are not visible to them) if self.scopes[enclosing_scope_id].kind().is_module() { continue; } // Skip this place if this enclosing scope doesn't contain any bindings for it. // Note that even if this place is bound in the popped scope, // it may refer to the enclosing scope bindings // so we also need to snapshot the bindings of the enclosing scope. let Some(enclosed_symbol_id) = enclosing_place_table.symbol_id(nested_symbol.name()) else { continue; }; let enclosing_place = enclosing_place_table.symbol(enclosed_symbol_id); if !enclosing_place.is_bound() { // If the bound scope of a place can be modified from elsewhere, the snapshot will not be recorded. if self .bound_scope(enclosing_scope_id, nested_symbol) .is_none_or(|scope| self.scopes[scope].visibility().is_public()) { continue; } } // Snapshot the state of this place that are visible at this point in this // enclosing scope (this may later be invalidated and swept away). let key = EnclosingSnapshotKey { enclosing_scope: enclosing_scope_id, enclosing_place: enclosed_symbol_id.into(), nested_scope: popped_scope_id, nested_laziness: ScopeLaziness::Lazy, }; let lazy_snapshot = self.use_def_maps[enclosing_scope_id].snapshot_enclosing_state( enclosed_symbol_id.into(), enclosing_scope_kind, enclosing_place.into(), false, ); self.enclosing_snapshots.insert(key, lazy_snapshot); } } } /// Any lazy snapshots of the place that have been reassigned are obsolete, so update them. /// ```py /// def outer() -> None: /// x = None /// /// def inner2() -> None: /// # `inner` can be referenced before its definition, /// # but `inner2` must still be called after the definition of `inner` for this call to be valid. /// inner() /// /// # In this scope, `x` may refer to `x = None` or `x = 1`. /// reveal_type(x) # revealed: None | Literal[1] /// /// # Reassignment of `x` after the definition of `inner2`. /// # Update lazy snapshots of `x` for `inner2`. /// x = 1 /// /// def inner() -> None: /// # In this scope, `x = None` appears as being shadowed by `x = 1`. /// reveal_type(x) # revealed: Literal[1] /// /// # No reassignment of `x` after the definition of `inner`, so we can safely use a lazy snapshot for `inner` as is. /// inner() /// inner2() /// ``` fn update_lazy_snapshots(&mut self, symbol: ScopedSymbolId) { let current_scope = self.current_scope(); let current_place_table = &self.place_tables[current_scope]; let symbol = current_place_table.symbol(symbol); // Optimization: if this is the first binding of the symbol we've seen, there can't be any // lazy snapshots of it to update. if !symbol.is_reassigned() { return; } for (key, snapshot_id) in &self.enclosing_snapshots { if let Some(enclosing_symbol) = key.enclosing_place.as_symbol() { let name = self.place_tables[key.enclosing_scope] .symbol(enclosing_symbol) .name(); let is_reassignment_of_snapshotted_symbol = || { for (ancestor, _) in VisibleAncestorsIter::new(&self.scopes, key.enclosing_scope) { if ancestor == current_scope { return true; } let ancestor_table = &self.place_tables[ancestor]; // If there is a symbol binding in an ancestor scope, // then a reassignment in the current scope is not relevant to the snapshot. if ancestor_table .symbol_id(name) .is_some_and(|id| ancestor_table.symbol(id).is_bound()) { return false; } } false }; if key.nested_laziness.is_lazy() && symbol.name() == name && is_reassignment_of_snapshotted_symbol() { self.use_def_maps[key.enclosing_scope] .update_enclosing_snapshot(*snapshot_id, enclosing_symbol); } } } } fn sweep_nonlocal_lazy_snapshots(&mut self) { self.enclosing_snapshots.retain(|key, _| { let place_table = &self.place_tables[key.enclosing_scope]; let is_bound_and_non_local = || -> bool { let ScopedPlaceId::Symbol(symbol_id) = key.enclosing_place else { return false; }; let symbol = place_table.symbol(symbol_id); self.scopes .iter_enumerated() .skip_while(|(scope_id, _)| *scope_id != key.enclosing_scope) .any(|(scope_id, _)| { let other_scope_place_table = &self.place_tables[scope_id]; let Some(symbol_id) = other_scope_place_table.symbol_id(symbol.name()) else { return false; }; let symbol = other_scope_place_table.symbol(symbol_id); symbol.is_nonlocal() && symbol.is_bound() }) }; key.nested_laziness.is_eager() || !is_bound_and_non_local() }); } fn pop_scope(&mut self) -> FileScopeId { self.try_node_context_stack_manager.exit_scope(); let ScopeInfo { file_scope_id: popped_scope_id, .. } = self .scope_stack .pop() .expect("Root scope should be present"); let children_end = self.scopes.next_index(); let popped_scope = &mut self.scopes[popped_scope_id]; popped_scope.extend_descendants(children_end); if popped_scope.is_eager() { self.record_eager_snapshots(popped_scope_id); } else { self.record_lazy_snapshots(popped_scope_id); } popped_scope_id } fn current_place_table(&self) -> &PlaceTableBuilder { let scope_id = self.current_scope(); &self.place_tables[scope_id] } fn current_place_table_mut(&mut self) -> &mut PlaceTableBuilder { let scope_id = self.current_scope(); &mut self.place_tables[scope_id] } fn current_use_def_map_mut(&mut self) -> &mut UseDefMapBuilder<'db> { let scope_id = self.current_scope(); &mut self.use_def_maps[scope_id] } fn current_use_def_map(&self) -> &UseDefMapBuilder<'db> { let scope_id = self.current_scope(); &self.use_def_maps[scope_id] } fn current_reachability_constraints_mut(&mut self) -> &mut ReachabilityConstraintsBuilder { let scope_id = self.current_scope(); &mut self.use_def_maps[scope_id].reachability_constraints } fn current_ast_ids(&mut self) -> &mut AstIdsBuilder { let scope_id = self.current_scope(); &mut self.ast_ids[scope_id] } fn flow_snapshot(&self) -> FlowSnapshot { self.current_use_def_map().snapshot() } fn flow_restore(&mut self, state: FlowSnapshot) { self.current_use_def_map_mut().restore(state); } fn flow_merge(&mut self, state: FlowSnapshot) { self.current_use_def_map_mut().merge(state); } /// Add a symbol to the place table and the use-def map. /// Return the [`ScopedPlaceId`] that uniquely identifies the symbol in both. fn add_symbol(&mut self, name: Name) -> ScopedSymbolId { let (symbol_id, added) = self.current_place_table_mut().add_symbol(Symbol::new(name)); if added { self.current_use_def_map_mut().add_place(symbol_id.into()); } symbol_id } /// Add a place to the place table and the use-def map. /// Return the [`ScopedPlaceId`] that uniquely identifies the place in both. fn add_place(&mut self, place_expr: PlaceExpr) -> ScopedPlaceId { let (place_id, added) = self.current_place_table_mut().add_place(place_expr); if added { self.current_use_def_map_mut().add_place(place_id); } place_id } #[track_caller] fn mark_place_bound(&mut self, id: ScopedPlaceId) { self.current_place_table_mut().mark_bound(id); } #[track_caller] fn mark_place_declared(&mut self, id: ScopedPlaceId) { self.current_place_table_mut().mark_declared(id); } #[track_caller] fn mark_symbol_used(&mut self, id: ScopedSymbolId) { self.current_place_table_mut().symbol_mut(id).mark_used(); } fn add_entry_for_definition_key(&mut self, key: DefinitionNodeKey) -> &mut Definitions<'db> { self.definitions_by_node.entry(key).or_default() } /// Add a [`Definition`] associated with the `definition_node` AST node. /// /// ## Panics /// /// This method panics if `debug_assertions` are enabled and the `definition_node` AST node /// already has a [`Definition`] associated with it. This is an important invariant to maintain /// for all nodes *except* [`ast::Alias`] nodes representing `*` imports. fn add_definition( &mut self, place: ScopedPlaceId, definition_node: impl Into<DefinitionNodeRef<'ast, 'db>> + std::fmt::Debug + Copy, ) -> Definition<'db> { let (definition, num_definitions) = self.push_additional_definition(place, definition_node); debug_assert_eq!( num_definitions, 1, "Attempted to create multiple `Definition`s associated with AST node {definition_node:?}" ); definition } fn delete_associated_bindings(&mut self, place: ScopedPlaceId) { let scope = self.current_scope(); // Don't delete associated bindings if the scope is a class scope & place is a name (it's never visible to nested scopes) if self.scopes[scope].kind() == ScopeKind::Class && place.is_symbol() { return; } for associated_place in self.place_tables[scope] .associated_place_ids(place) .iter() .copied() { self.use_def_maps[scope].delete_binding(associated_place.into()); } } fn delete_binding(&mut self, place: ScopedPlaceId) { self.current_use_def_map_mut().delete_binding(place); } /// Push a new [`Definition`] onto the list of definitions /// associated with the `definition_node` AST node. /// /// Returns a 2-element tuple, where the first element is the newly created [`Definition`] /// and the second element is the number of definitions that are now associated with /// `definition_node`. /// /// This method should only be used when adding a definition associated with a `*` import. /// All other nodes can only ever be associated with exactly 1 or 0 [`Definition`]s. /// For any node other than an [`ast::Alias`] representing a `*` import, /// prefer to use `self.add_definition()`, which ensures that this invariant is maintained. fn push_additional_definition( &mut self, place: ScopedPlaceId, definition_node: impl Into<DefinitionNodeRef<'ast, 'db>>, ) -> (Definition<'db>, usize) { let definition_node: DefinitionNodeRef<'ast, 'db> = definition_node.into(); // Note `definition_node` is guaranteed to be a child of `self.module` let kind = definition_node.into_owned(self.module); let category = kind.category(self.source_type.is_stub(), self.module); let is_reexported = kind.is_reexported(); let definition: Definition<'db> = Definition::new( self.db, self.file, self.current_scope(), place, kind, is_reexported, ); let num_definitions = { let definitions = self.add_entry_for_definition_key(definition_node.key()); definitions.push(definition); definitions.len() }; if category.is_binding() { self.mark_place_bound(place); } if category.is_declaration() { self.mark_place_declared(place); } let use_def = self.current_use_def_map_mut(); match category { DefinitionCategory::DeclarationAndBinding => { use_def.record_declaration_and_binding(place, definition); self.delete_associated_bindings(place); } DefinitionCategory::Declaration => use_def.record_declaration(place, definition), DefinitionCategory::Binding => { use_def.record_binding(place, definition); self.delete_associated_bindings(place); } } if category.is_binding() { if let Some(id) = place.as_symbol() { self.update_lazy_snapshots(id); } } let mut try_node_stack_manager = std::mem::take(&mut self.try_node_context_stack_manager); try_node_stack_manager.record_definition(self); self.try_node_context_stack_manager = try_node_stack_manager; (definition, num_definitions) } fn record_expression_narrowing_constraint( &mut self, predicate_node: &ast::Expr, ) -> PredicateOrLiteral<'db> { let predicate = self.build_predicate(predicate_node); self.record_narrowing_constraint(predicate); predicate } fn build_predicate(&mut self, predicate_node: &ast::Expr) -> PredicateOrLiteral<'db> { // Some commonly used test expressions are eagerly evaluated as `true` // or `false` here for performance reasons. This list does not need to // be exhaustive. More complex expressions will still evaluate to the // correct value during type-checking. fn resolve_to_literal(node: &ast::Expr) -> Option<bool> { match node { ast::Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) => Some(*value), ast::Expr::Name(ast::ExprName { id, .. }) if id == "TYPE_CHECKING" => Some(true), ast::Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Int(n), .. }) => Some(*n != 0), ast::Expr::EllipsisLiteral(_) => Some(true), ast::Expr::NoneLiteral(_) => Some(false), ast::Expr::UnaryOp(ast::ExprUnaryOp { op: ast::UnaryOp::Not, operand, .. }) => Some(!resolve_to_literal(operand)?), _ => None, } } let expression = self.add_standalone_expression(predicate_node); match resolve_to_literal(predicate_node) { Some(literal) => PredicateOrLiteral::Literal(literal), None => PredicateOrLiteral::Predicate(Predicate { node: PredicateNode::Expression(expression), is_positive: true, }), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/place.rs
crates/ty_python_semantic/src/semantic_index/place.rs
use crate::semantic_index::member::{ Member, MemberExpr, MemberExprRef, MemberTable, MemberTableBuilder, ScopedMemberId, }; use crate::semantic_index::scope::FileScopeId; use crate::semantic_index::symbol::{ScopedSymbolId, Symbol, SymbolTable, SymbolTableBuilder}; use ruff_index::IndexVec; use ruff_python_ast as ast; use smallvec::SmallVec; use std::hash::Hash; use std::iter::FusedIterator; /// An expression that can be the target of a `Definition`. #[derive(Eq, PartialEq, Debug, get_size2::GetSize)] pub(crate) enum PlaceExpr { /// A simple symbol, e.g. `x`. Symbol(Symbol), /// A member expression, e.g. `x.y.z[0]`. Member(Member), } impl PlaceExpr { /// Create a new `PlaceExpr` from a name. /// /// This always returns a `PlaceExpr::Symbol` with empty flags and `name`. pub(crate) fn from_expr_name(name: &ast::ExprName) -> Self { PlaceExpr::Symbol(Symbol::new(name.id.clone())) } /// Tries to create a `PlaceExpr` from an expression. /// /// Returns `None` if the expression is not a valid place expression and `Some` otherwise. /// /// Valid expressions are: /// * name: `x` /// * attribute: `x.y` /// * subscripts with integer or string literals: `x[0]`, `x['key']` pub(crate) fn try_from_expr<'e>(expr: impl Into<ast::ExprRef<'e>>) -> Option<Self> { let expr = expr.into(); if let ast::ExprRef::Name(name) = expr { return Some(PlaceExpr::Symbol(Symbol::new(name.id.clone()))); } let member_expression = MemberExpr::try_from_expr(expr)?; Some(Self::Member(Member::new(member_expression))) } } impl std::fmt::Display for PlaceExpr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Symbol(symbol) => std::fmt::Display::fmt(symbol, f), Self::Member(member) => std::fmt::Display::fmt(member, f), } } } /// Reference to a place expression, which can be a symbol or a member expression. /// /// Needed so that we can iterate over all places without cloning them. #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub(crate) enum PlaceExprRef<'a> { Symbol(&'a Symbol), Member(&'a Member), } impl<'a> PlaceExprRef<'a> { /// Returns `Some` if the reference is a `Symbol`, otherwise `None`. pub(crate) const fn as_symbol(self) -> Option<&'a Symbol> { if let PlaceExprRef::Symbol(symbol) = self { Some(symbol) } else { None } } /// Returns `true` if the reference is a `Symbol`, otherwise `false`. pub(crate) const fn is_symbol(self) -> bool { matches!(self, PlaceExprRef::Symbol(_)) } pub(crate) fn is_declared(self) -> bool { match self { Self::Symbol(symbol) => symbol.is_declared(), Self::Member(member) => member.is_declared(), } } pub(crate) const fn is_bound(self) -> bool { match self { PlaceExprRef::Symbol(symbol) => symbol.is_bound(), PlaceExprRef::Member(member) => member.is_bound(), } } pub(crate) fn num_member_segments(self) -> usize { match self { PlaceExprRef::Symbol(_) => 0, PlaceExprRef::Member(member) => member.expression().num_segments(), } } } impl<'a> From<&'a Symbol> for PlaceExprRef<'a> { fn from(value: &'a Symbol) -> Self { Self::Symbol(value) } } impl<'a> From<&'a Member> for PlaceExprRef<'a> { fn from(value: &'a Member) -> Self { Self::Member(value) } } impl<'a> From<&'a PlaceExpr> for PlaceExprRef<'a> { fn from(value: &'a PlaceExpr) -> Self { match value { PlaceExpr::Symbol(symbol) => PlaceExprRef::Symbol(symbol), PlaceExpr::Member(member) => PlaceExprRef::Member(member), } } } impl std::fmt::Display for PlaceExprRef<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Symbol(symbol) => std::fmt::Display::fmt(symbol, f), Self::Member(member) => std::fmt::Display::fmt(member, f), } } } /// ID that uniquely identifies a place inside a [`Scope`](super::FileScopeId). #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, get_size2::GetSize, salsa::Update)] pub enum ScopedPlaceId { Symbol(ScopedSymbolId), Member(ScopedMemberId), } #[derive(Debug, Eq, PartialEq, salsa::Update, get_size2::GetSize)] pub(crate) struct PlaceTable { symbols: SymbolTable, members: MemberTable, } impl PlaceTable { /// Iterate over the "root" expressions of the place (e.g. `x.y.z`, `x.y`, `x` for `x.y.z[0]`). /// /// Note, this iterator may skip some parents if they are not defined in the current scope. pub(crate) fn parents<'a>( &'a self, place_expr: impl Into<PlaceExprRef<'a>>, ) -> ParentPlaceIter<'a> { match place_expr.into() { PlaceExprRef::Symbol(_) => ParentPlaceIter::for_symbol(), PlaceExprRef::Member(member) => { ParentPlaceIter::for_member(member.expression(), &self.symbols, &self.members) } } } /// Iterator over all symbols in this scope. pub(crate) fn symbols(&self) -> std::slice::Iter<'_, Symbol> { self.symbols.iter() } /// Iterator over all members in this scope. pub(crate) fn members(&self) -> std::slice::Iter<'_, Member> { self.members.iter() } /// Looks up a symbol by its ID and returns a reference to it. /// /// ## Panics /// If the symbol ID is not found in the table. #[track_caller] pub(crate) fn symbol(&self, id: ScopedSymbolId) -> &Symbol { self.symbols.symbol(id) } /// Looks up a symbol by its name and returns a reference to it, if it exists. /// /// This should only be used in diagnostics and tests. pub(crate) fn symbol_by_name(&self, name: &str) -> Option<&Symbol> { self.symbols.symbol_id(name).map(|id| self.symbol(id)) } /// Looks up a member by its ID and returns a reference to it. /// /// ## Panics /// If the member ID is not found in the table. #[track_caller] pub(crate) fn member(&self, id: ScopedMemberId) -> &Member { self.members.member(id) } /// Returns the [`ScopedSymbolId`] of the place named `name`. pub(crate) fn symbol_id(&self, name: &str) -> Option<ScopedSymbolId> { self.symbols.symbol_id(name) } /// Returns the [`ScopedPlaceId`] of the place expression. pub(crate) fn place_id<'e>( &self, place_expr: impl Into<PlaceExprRef<'e>>, ) -> Option<ScopedPlaceId> { let place_expr = place_expr.into(); match place_expr { PlaceExprRef::Symbol(symbol) => self.symbols.symbol_id(symbol.name()).map(Into::into), PlaceExprRef::Member(member) => { self.members.member_id(member.expression()).map(Into::into) } } } /// Returns the place expression for the given place ID. /// /// ## Panics /// If the place ID is not found in the table. #[track_caller] pub(crate) fn place(&self, place_id: impl Into<ScopedPlaceId>) -> PlaceExprRef<'_> { match place_id.into() { ScopedPlaceId::Symbol(symbol) => self.symbol(symbol).into(), ScopedPlaceId::Member(member) => self.member(member).into(), } } pub(crate) fn member_id_by_instance_attribute_name( &self, name: &str, ) -> Option<ScopedMemberId> { self.members.place_id_by_instance_attribute_name(name) } } #[derive(Default)] pub(crate) struct PlaceTableBuilder { symbols: SymbolTableBuilder, member: MemberTableBuilder, associated_symbol_members: IndexVec<ScopedSymbolId, SmallVec<[ScopedMemberId; 4]>>, associated_sub_members: IndexVec<ScopedMemberId, SmallVec<[ScopedMemberId; 4]>>, } impl PlaceTableBuilder { /// Looks up a place ID by its expression. pub(super) fn place_id(&self, expression: PlaceExprRef) -> Option<ScopedPlaceId> { match expression { PlaceExprRef::Symbol(symbol) => self.symbols.symbol_id(symbol.name()).map(Into::into), PlaceExprRef::Member(member) => { self.member.member_id(member.expression()).map(Into::into) } } } #[track_caller] pub(super) fn symbol(&self, id: ScopedSymbolId) -> &Symbol { self.symbols.symbol(id) } pub(super) fn symbol_id(&self, name: &str) -> Option<ScopedSymbolId> { self.symbols.symbol_id(name) } #[track_caller] pub(super) fn symbol_mut(&mut self, id: ScopedSymbolId) -> &mut Symbol { self.symbols.symbol_mut(id) } #[track_caller] pub(super) fn member_mut(&mut self, id: ScopedMemberId) -> &mut Member { self.member.member_mut(id) } #[track_caller] pub(crate) fn place(&self, place_id: impl Into<ScopedPlaceId>) -> PlaceExprRef<'_> { match place_id.into() { ScopedPlaceId::Symbol(id) => PlaceExprRef::Symbol(self.symbols.symbol(id)), ScopedPlaceId::Member(id) => PlaceExprRef::Member(self.member.member(id)), } } pub(crate) fn associated_place_ids(&self, place: ScopedPlaceId) -> &[ScopedMemberId] { match place { ScopedPlaceId::Symbol(symbol) => &self.associated_symbol_members[symbol], ScopedPlaceId::Member(member) => &self.associated_sub_members[member], } } pub(crate) fn iter(&self) -> impl Iterator<Item = PlaceExprRef<'_>> { self.symbols .iter() .map(Into::into) .chain(self.member.iter().map(PlaceExprRef::Member)) } pub(crate) fn symbols(&self) -> impl Iterator<Item = &Symbol> { self.symbols.iter() } pub(crate) fn add_symbol(&mut self, symbol: Symbol) -> (ScopedSymbolId, bool) { let (id, is_new) = self.symbols.add(symbol); if is_new { let new_id = self.associated_symbol_members.push(SmallVec::new_const()); debug_assert_eq!(new_id, id); } (id, is_new) } pub(crate) fn add_member(&mut self, member: Member) -> (ScopedMemberId, bool) { let (id, is_new) = self.member.add(member); if is_new { let new_id = self.associated_sub_members.push(SmallVec::new_const()); debug_assert_eq!(new_id, id); let member = self.member.member(id); // iterate over parents for parent_id in ParentPlaceIter::for_member(member.expression(), &self.symbols, &self.member) { match parent_id { ScopedPlaceId::Symbol(scoped_symbol_id) => { self.associated_symbol_members[scoped_symbol_id].push(id); } ScopedPlaceId::Member(scoped_member_id) => { self.associated_sub_members[scoped_member_id].push(id); } } } } (id, is_new) } pub(crate) fn add_place(&mut self, place: PlaceExpr) -> (ScopedPlaceId, bool) { match place { PlaceExpr::Symbol(symbol) => { let (id, is_new) = self.add_symbol(symbol); (ScopedPlaceId::Symbol(id), is_new) } PlaceExpr::Member(member) => { let (id, is_new) = self.add_member(member); (ScopedPlaceId::Member(id), is_new) } } } #[track_caller] pub(super) fn mark_bound(&mut self, id: ScopedPlaceId) { match id { ScopedPlaceId::Symbol(symbol_id) => { self.symbol_mut(symbol_id).mark_bound(); } ScopedPlaceId::Member(member_id) => { self.member_mut(member_id).mark_bound(); } } } #[track_caller] pub(super) fn mark_declared(&mut self, id: ScopedPlaceId) { match id { ScopedPlaceId::Symbol(symbol_id) => { self.symbol_mut(symbol_id).mark_declared(); } ScopedPlaceId::Member(member_id) => { self.member_mut(member_id).mark_declared(); } } } pub(crate) fn finish(self) -> PlaceTable { PlaceTable { symbols: self.symbols.build(), members: self.member.build(), } } } impl ScopedPlaceId { pub const fn is_symbol(self) -> bool { matches!(self, ScopedPlaceId::Symbol(_)) } pub const fn is_member(self) -> bool { matches!(self, ScopedPlaceId::Member(_)) } pub const fn as_symbol(self) -> Option<ScopedSymbolId> { if let ScopedPlaceId::Symbol(id) = self { Some(id) } else { None } } pub const fn expect_symbol(self) -> ScopedSymbolId { match self { ScopedPlaceId::Symbol(symbol) => symbol, ScopedPlaceId::Member(_) => { panic!("Expected ScopedPlaceId::Symbol, found ScopedPlaceId::Member") } } } pub const fn as_member(self) -> Option<ScopedMemberId> { if let ScopedPlaceId::Member(id) = self { Some(id) } else { None } } } impl<T> std::ops::Index<ScopedPlaceId> for Vec<T> { type Output = T; fn index(&self, index: ScopedPlaceId) -> &Self::Output { match index { ScopedPlaceId::Symbol(id) => &self[id.index()], ScopedPlaceId::Member(id) => &self[id.index()], } } } impl From<ScopedMemberId> for ScopedPlaceId { fn from(value: ScopedMemberId) -> Self { Self::Member(value) } } impl From<ScopedSymbolId> for ScopedPlaceId { fn from(value: ScopedSymbolId) -> Self { Self::Symbol(value) } } /// ID that uniquely identifies a place in a file. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct FilePlaceId { scope: FileScopeId, scoped_place_id: ScopedPlaceId, } impl FilePlaceId { pub fn scope(self) -> FileScopeId { self.scope } pub(crate) fn scoped_place_id(self) -> ScopedPlaceId { self.scoped_place_id } } impl From<FilePlaceId> for ScopedPlaceId { fn from(val: FilePlaceId) -> Self { val.scoped_place_id() } } pub(crate) struct ParentPlaceIter<'a> { state: Option<ParentPlaceIterState<'a>>, } enum ParentPlaceIterState<'a> { Symbol { symbol_name: &'a str, symbols: &'a SymbolTable, }, Member { symbols: &'a SymbolTable, members: &'a MemberTable, next_member: MemberExprRef<'a>, }, } impl<'a> ParentPlaceIterState<'a> { fn parent_state( expression: &MemberExprRef<'a>, symbols: &'a SymbolTable, members: &'a MemberTable, ) -> Self { match expression.parent() { Some(parent) => Self::Member { next_member: parent, symbols, members, }, None => Self::Symbol { symbol_name: expression.symbol_name(), symbols, }, } } } impl<'a> ParentPlaceIter<'a> { pub(super) fn for_symbol() -> Self { ParentPlaceIter { state: None } } pub(super) fn for_member( expression: &'a MemberExpr, symbol_table: &'a SymbolTable, member_table: &'a MemberTable, ) -> Self { let expr_ref = expression.as_ref(); ParentPlaceIter { state: Some(ParentPlaceIterState::parent_state( &expr_ref, symbol_table, member_table, )), } } } impl Iterator for ParentPlaceIter<'_> { type Item = ScopedPlaceId; fn next(&mut self) -> Option<Self::Item> { loop { match self.state.take()? { ParentPlaceIterState::Symbol { symbol_name, symbols, } => { let id = symbols.symbol_id(symbol_name)?; break Some(id.into()); } ParentPlaceIterState::Member { symbols, members, next_member, } => { self.state = Some(ParentPlaceIterState::parent_state( &next_member, symbols, members, )); if let Some(id) = members.member_id(next_member) { break Some(id.into()); } } } } } } impl FusedIterator for ParentPlaceIter<'_> {}
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/use_def.rs
crates/ty_python_semantic/src/semantic_index/use_def.rs
//! First, some terminology: //! //! * A "place" is semantically a location where a value can be read or written, and syntactically, //! an expression that can be the target of an assignment, e.g. `x`, `x[0]`, `x.y`. (The term is //! borrowed from Rust). In Python syntax, an expression like `f().x` is also allowed as the //! target so it can be called a place, but we do not record declarations / bindings like `f().x: //! int`, `f().x = ...`. Type checking itself can be done by recording only assignments to names, //! but in order to perform type narrowing by attribute/subscript assignments, they must also be //! recorded. //! //! * A "binding" gives a new value to a place. This includes many different Python statements //! (assignment statements of course, but also imports, `def` and `class` statements, `as` //! clauses in `with` and `except` statements, match patterns, and others) and even one //! expression kind (named expressions). It notably does not include annotated assignment //! statements without a right-hand side value; these do not assign any new value to the place. //! We consider function parameters to be bindings as well, since (from the perspective of the //! function's internal scope), a function parameter begins the scope bound to a value. //! //! * A "declaration" establishes an upper bound type for the values that a variable may be //! permitted to take on. Annotated assignment statements (with or without an RHS value) are //! declarations; annotated function parameters are also declarations. We consider `def` and //! `class` statements to also be declarations, so as to prohibit accidentally shadowing them. //! //! Annotated assignments with a right-hand side, and annotated function parameters, are both //! bindings and declarations. //! //! We use [`Definition`] as the universal term (and Salsa tracked struct) encompassing both //! bindings and declarations. (This sacrifices a bit of type safety in exchange for improved //! performance via fewer Salsa tracked structs and queries, since most declarations -- typed //! parameters and annotated assignments with RHS -- are both bindings and declarations.) //! //! At any given use of a variable, we can ask about both its "declared type" and its "inferred //! type". These may be different, but the inferred type must always be assignable to the declared //! type; that is, the declared type is always wider, and the inferred type may be more precise. If //! we see an invalid assignment, we emit a diagnostic and abandon our inferred type, deferring to //! the declared type (this allows an explicit annotation to override bad inference, without a //! cast), maintaining the invariant. //! //! The **inferred type** represents the most precise type we believe encompasses all possible //! values for the variable at a given use. It is based on a union of the bindings which can reach //! that use through some control flow path, and the narrowing constraints that control flow must //! have passed through between the binding and the use. For example, in this code: //! //! ```python //! x = 1 if flag else None //! if x is not None: //! use(x) //! ``` //! //! For the use of `x` on the third line, the inferred type should be `Literal[1]`. This is based //! on the binding on the first line, which assigns the type `Literal[1] | None`, and the narrowing //! constraint on the second line, which rules out the type `None`, since control flow must pass //! through this constraint to reach the use in question. //! //! The **declared type** represents the code author's declaration (usually through a type //! annotation) that a given variable should not be assigned any type outside the declared type. In //! our model, declared types are also control-flow-sensitive; we allow the code author to //! explicitly redeclare the same variable with a different type. So for a given binding of a //! variable, we will want to ask which declarations of that variable can reach that binding, in //! order to determine whether the binding is permitted, or should be a type error. For example: //! //! ```python //! from pathlib import Path //! def f(path: str): //! path: Path = Path(path) //! ``` //! //! In this function, the initial declared type of `path` is `str`, meaning that the assignment //! `path = Path(path)` would be a type error, since it assigns to `path` a value whose type is not //! assignable to `str`. This is the purpose of declared types: they prevent accidental assignment //! of the wrong type to a variable. //! //! But in some cases it is useful to "shadow" or "redeclare" a variable with a new type, and we //! permit this, as long as it is done with an explicit re-annotation. So `path: Path = //! Path(path)`, with the explicit `: Path` annotation, is permitted. //! //! The general rule is that whatever declaration(s) can reach a given binding determine the //! validity of that binding. If there is a path in which the place is not declared, that is a //! declaration of `Unknown`. If multiple declarations can reach a binding, we union them, but by //! default we also issue a type error, since this implicit union of declared types may hide an //! error. //! //! To support type inference, we build a map from each use of a place to the bindings live at //! that use, and the type narrowing constraints that apply to each binding. //! //! Let's take this code sample: //! //! ```python //! x = 1 //! x = 2 //! y = x //! if flag: //! x = 3 //! else: //! x = 4 //! z = x //! ``` //! //! In this snippet, we have four bindings of `x` (the statements assigning `1`, `2`, `3`, and `4` //! to it), and two uses of `x` (the `y = x` and `z = x` assignments). The first binding of `x` //! does not reach any use, because it's immediately replaced by the second binding, before any use //! happens. (A linter could thus flag the statement `x = 1` as likely superfluous.) //! //! The first use of `x` has one live binding: the assignment `x = 2`. //! //! Things get a bit more complex when we have branches. We will definitely take either the `if` or //! the `else` branch. Thus, the second use of `x` has two live bindings: `x = 3` and `x = 4`. The //! `x = 2` assignment is no longer visible, because it must be replaced by either `x = 3` or `x = //! 4`, no matter which branch was taken. We don't know which branch was taken, so we must consider //! both bindings as live, which means eventually we would (in type inference) look at these two //! bindings and infer a type of `Literal[3, 4]` -- the union of `Literal[3]` and `Literal[4]` -- //! for the second use of `x`. //! //! So that's one question our use-def map needs to answer: given a specific use of a place, which //! binding(s) can reach that use. In [`AstIds`](crate::semantic_index::ast_ids::AstIds) we number //! all uses (that means a `Name`/`ExprAttribute`/`ExprSubscript` node with `Load` context) //! so we have a `ScopedUseId` to efficiently represent each use. //! //! We also need to know, for a given definition of a place, what type narrowing constraints apply //! to it. For instance, in this code sample: //! //! ```python //! x = 1 if flag else None //! if x is not None: //! use(x) //! ``` //! //! At the use of `x`, the live binding of `x` is `1 if flag else None`, which would infer as the //! type `Literal[1] | None`. But the constraint `x is not None` dominates this use, which means we //! can rule out the possibility that `x` is `None` here, which should give us the type //! `Literal[1]` for this use. //! //! For declared types, we need to be able to answer the question "given a binding to a place, //! which declarations of that place can reach the binding?" This allows us to emit a diagnostic //! if the binding is attempting to bind a value of a type that is not assignable to the declared //! type for that place, at that point in control flow. //! //! We also need to know, given a declaration of a place, what the inferred type of that place is //! at that point. This allows us to emit a diagnostic in a case like `x = "foo"; x: int`. The //! binding `x = "foo"` occurs before the declaration `x: int`, so according to our //! control-flow-sensitive interpretation of declarations, the assignment is not an error. But the //! declaration is an error, since it would violate the "inferred type must be assignable to //! declared type" rule. //! //! Another case we need to handle is when a place is referenced from a different scope (for //! example, an import or a nonlocal reference). We call this "public" use of a place. For public //! use of a place, we prefer the declared type, if there are any declarations of that place; if //! not, we fall back to the inferred type. So we also need to know which declarations and bindings //! can reach the end of the scope. //! //! Technically, public use of a place could occur from any point in control flow of the scope //! where the place is defined (via inline imports and import cycles, in the case of an import, or //! via a function call partway through the local scope that ends up using a place from the scope //! via a global or nonlocal reference.) But modeling this fully accurately requires whole-program //! analysis that isn't tractable for an efficient analysis, since it means a given place could //! have a different type every place it's referenced throughout the program, depending on the //! shape of arbitrarily-sized call/import graphs. So we follow other Python type checkers in //! making the simplifying assumption that usually the scope will finish execution before its //! places are made visible to other scopes; for instance, most imports will import from a //! complete module, not a partially-executed module. (We may want to get a little smarter than //! this in the future for some closures, but for now this is where we start.) //! //! The data structure we build to answer these questions is the `UseDefMap`. It has a //! `bindings_by_use` vector of [`Bindings`] indexed by [`ScopedUseId`], a //! `declarations_by_binding` vector of [`Declarations`] indexed by [`ScopedDefinitionId`], a //! `bindings_by_declaration` vector of [`Bindings`] indexed by [`ScopedDefinitionId`], and //! `public_bindings` and `public_definitions` vectors indexed by [`ScopedPlaceId`]. The values in //! each of these vectors are (in principle) a list of live bindings at that use/definition, or at //! the end of the scope for that place, with a list of the dominating constraints for each //! binding. //! //! In order to avoid vectors-of-vectors-of-vectors and all the allocations that would entail, we //! don't actually store these "list of visible definitions" as a vector of [`Definition`]. //! Instead, [`Bindings`] and [`Declarations`] are structs which use bit-sets to track //! definitions (and constraints, in the case of bindings) in terms of [`ScopedDefinitionId`] and //! [`ScopedPredicateId`], which are indices into the `all_definitions` and `predicates` //! indexvecs in the [`UseDefMap`]. //! //! There is another special kind of possible "definition" for a place: there might be a path from //! the scope entry to a given use in which the place is never bound. We model this with a special //! "unbound/undeclared" definition (a [`DefinitionState::Undefined`] entry at the start of the //! `all_definitions` vector). If that sentinel definition is present in the live bindings at a //! given use, it means that there is a possible path through control flow in which that place is //! unbound. Similarly, if that sentinel is present in the live declarations, it means that the //! place is (possibly) undeclared. //! //! To build a [`UseDefMap`], the [`UseDefMapBuilder`] is notified of each new use, definition, and //! constraint as they are encountered by the //! [`SemanticIndexBuilder`](crate::semantic_index::builder::SemanticIndexBuilder) AST visit. For //! each place, the builder tracks the `PlaceState` (`Bindings` and `Declarations`) for that place. //! When we hit a use or definition of a place, we record the necessary parts of the current state //! for that place that we need for that use or definition. When we reach the end of the scope, it //! records the state for each place as the public definitions of that place. //! //! ```python //! x = 1 //! x = 2 //! y = x //! if flag: //! x = 3 //! else: //! x = 4 //! z = x //! ``` //! //! Let's walk through the above example. Initially we do not have any record of `x`. When we add //! the new place (before we process the first binding), we create a new undefined `PlaceState` //! which has a single live binding (the "unbound" definition) and a single live declaration (the //! "undeclared" definition). When we see `x = 1`, we record that as the sole live binding of `x`. //! The "unbound" binding is no longer visible. Then we see `x = 2`, and we replace `x = 1` as the //! sole live binding of `x`. When we get to `y = x`, we record that the live bindings for that use //! of `x` are just the `x = 2` definition. //! //! Then we hit the `if` branch. We visit the `test` node (`flag` in this case), since that will //! happen regardless. Then we take a pre-branch snapshot of the current state for all places, //! which we'll need later. Then we record `flag` as a possible constraint on the current binding //! (`x = 2`), and go ahead and visit the `if` body. When we see `x = 3`, it replaces `x = 2` //! (constrained by `flag`) as the sole live binding of `x`. At the end of the `if` body, we take //! another snapshot of the current place state; we'll call this the post-if-body snapshot. //! //! Now we need to visit the `else` clause. The conditions when entering the `else` clause should //! be the pre-if conditions; if we are entering the `else` clause, we know that the `if` test //! failed and we didn't execute the `if` body. So we first reset the builder to the pre-if state, //! using the snapshot we took previously (meaning we now have `x = 2` as the sole binding for `x` //! again), and record a *negative* `flag` constraint for all live bindings (`x = 2`). We then //! visit the `else` clause, where `x = 4` replaces `x = 2` as the sole live binding of `x`. //! //! Now we reach the end of the if/else, and want to visit the following code. The state here needs //! to reflect that we might have gone through the `if` branch, or we might have gone through the //! `else` branch, and we don't know which. So we need to "merge" our current builder state //! (reflecting the end-of-else state, with `x = 4` as the only live binding) with our post-if-body //! snapshot (which has `x = 3` as the only live binding). The result of this merge is that we now //! have two live bindings of `x`: `x = 3` and `x = 4`. //! //! Another piece of information that the `UseDefMap` needs to provide are reachability constraints. //! See `reachability_constraints.rs` for more details, in particular how they apply to bindings. //! //! The [`UseDefMapBuilder`] itself just exposes methods for taking a snapshot, resetting to a //! snapshot, and merging a snapshot into the current state. The logic using these methods lives in //! [`SemanticIndexBuilder`](crate::semantic_index::builder::SemanticIndexBuilder), e.g. where it //! visits a `StmtIf` node. use ruff_index::{IndexVec, newtype_index}; use rustc_hash::FxHashMap; use crate::node_key::NodeKey; use crate::place::BoundnessAnalysis; use crate::semantic_index::ast_ids::ScopedUseId; use crate::semantic_index::definition::{Definition, DefinitionState}; use crate::semantic_index::member::ScopedMemberId; use crate::semantic_index::narrowing_constraints::{ ConstraintKey, NarrowingConstraints, NarrowingConstraintsBuilder, NarrowingConstraintsIterator, ScopedNarrowingConstraint, }; use crate::semantic_index::place::{PlaceExprRef, ScopedPlaceId}; use crate::semantic_index::predicate::{ Predicate, PredicateOrLiteral, Predicates, PredicatesBuilder, ScopedPredicateId, }; use crate::semantic_index::reachability_constraints::{ ReachabilityConstraints, ReachabilityConstraintsBuilder, ScopedReachabilityConstraintId, }; use crate::semantic_index::scope::{FileScopeId, ScopeKind, ScopeLaziness}; use crate::semantic_index::symbol::ScopedSymbolId; use crate::semantic_index::use_def::place_state::{ Bindings, Declarations, EnclosingSnapshot, LiveBindingsIterator, LiveDeclaration, LiveDeclarationsIterator, PlaceState, PreviousDefinitions, ScopedDefinitionId, }; use crate::semantic_index::{EnclosingSnapshotResult, SemanticIndex}; use crate::types::{NarrowingConstraint, Truthiness, Type, infer_narrowing_constraint}; mod place_state; /// Applicable definitions and constraints for every use of a name. #[derive(Debug, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) struct UseDefMap<'db> { /// Array of [`Definition`] in this scope. Only the first entry should be [`DefinitionState::Undefined`]; /// this represents the implicit "unbound"/"undeclared" definition of every place. all_definitions: IndexVec<ScopedDefinitionId, DefinitionState<'db>>, /// Array of predicates in this scope. predicates: Predicates<'db>, /// Array of narrowing constraints in this scope. narrowing_constraints: NarrowingConstraints, /// Array of reachability constraints in this scope. reachability_constraints: ReachabilityConstraints, /// [`Bindings`] reaching a [`ScopedUseId`]. bindings_by_use: IndexVec<ScopedUseId, Bindings>, /// Tracks whether or not a given AST node is reachable from the start of the scope. node_reachability: FxHashMap<NodeKey, ScopedReachabilityConstraintId>, /// If the definition is a binding (only) -- `x = 1` for example -- then we need /// [`Declarations`] to know whether this binding is permitted by the live declarations. /// /// If the definition is both a declaration and a binding -- `x: int = 1` for example -- then /// we don't actually need anything here, all we'll need to validate is that our own RHS is a /// valid assignment to our own annotation. declarations_by_binding: FxHashMap<Definition<'db>, Declarations>, /// If the definition is a declaration (only) -- `x: int` for example -- then we need /// [`Bindings`] to know whether this declaration is consistent with the previously /// inferred type. /// /// If the definition is both a declaration and a binding -- `x: int = 1` for example -- then /// we don't actually need anything here, all we'll need to validate is that our own RHS is a /// valid assignment to our own annotation. /// /// If we see a binding to a `Final`-qualified symbol, we also need this map to find previous /// bindings to that symbol. If there are any, the assignment is invalid. bindings_by_definition: FxHashMap<Definition<'db>, Bindings>, /// [`PlaceState`] visible at end of scope for each symbol. end_of_scope_symbols: IndexVec<ScopedSymbolId, PlaceState>, /// [`PlaceState`] visible at end of scope for each member. end_of_scope_members: IndexVec<ScopedMemberId, PlaceState>, /// All potentially reachable bindings and declarations, for each symbol. reachable_definitions_by_symbol: IndexVec<ScopedSymbolId, ReachableDefinitions>, /// All potentially reachable bindings and declarations, for each member. reachable_definitions_by_member: IndexVec<ScopedMemberId, ReachableDefinitions>, /// Snapshot of bindings in this scope that can be used to resolve a reference in a nested /// scope. enclosing_snapshots: EnclosingSnapshots, /// Whether or not the end of the scope is reachable. /// /// This is used to check if the function can implicitly return `None`. /// For example: /// ```py /// def f(cond: bool) -> int | None: /// if cond: /// return 1 /// /// def g() -> int: /// if True: /// return 1 /// ``` /// /// Function `f` may implicitly return `None`, but `g` cannot. /// /// This is used by [`UseDefMap::can_implicitly_return_none`]. end_of_scope_reachability: ScopedReachabilityConstraintId, } pub(crate) enum ApplicableConstraints<'map, 'db> { UnboundBinding(ConstraintsIterator<'map, 'db>), ConstrainedBindings(BindingWithConstraintsIterator<'map, 'db>), } impl<'db> UseDefMap<'db> { pub(crate) fn bindings_at_use( &self, use_id: ScopedUseId, ) -> BindingWithConstraintsIterator<'_, 'db> { self.bindings_iterator( &self.bindings_by_use[use_id], BoundnessAnalysis::BasedOnUnboundVisibility, ) } pub(crate) fn applicable_constraints( &self, constraint_key: ConstraintKey, enclosing_scope: FileScopeId, expr: PlaceExprRef, index: &'db SemanticIndex, ) -> ApplicableConstraints<'_, 'db> { match constraint_key { ConstraintKey::NarrowingConstraint(constraint) => { ApplicableConstraints::UnboundBinding(ConstraintsIterator { predicates: &self.predicates, constraint_ids: self.narrowing_constraints.iter_predicates(constraint), }) } ConstraintKey::NestedScope(nested_scope) => { let EnclosingSnapshotResult::FoundBindings(bindings) = index.enclosing_snapshot(enclosing_scope, expr, nested_scope) else { unreachable!( "The result of `SemanticIndex::eager_snapshot` must be `FoundBindings`" ) }; ApplicableConstraints::ConstrainedBindings(bindings) } ConstraintKey::UseId(use_id) => { ApplicableConstraints::ConstrainedBindings(self.bindings_at_use(use_id)) } } } pub(super) fn is_reachable( &self, db: &dyn crate::Db, reachability: ScopedReachabilityConstraintId, ) -> bool { self.reachability_constraints .evaluate(db, &self.predicates, reachability) .may_be_true() } /// Check whether or not a given expression is reachable from the start of the scope. This /// is a local analysis which does not capture the possibility that the entire scope might /// be unreachable. Use [`super::SemanticIndex::is_node_reachable`] for the global /// analysis. #[track_caller] pub(super) fn is_node_reachable(&self, db: &dyn crate::Db, node_key: NodeKey) -> bool { self .reachability_constraints .evaluate( db, &self.predicates, *self .node_reachability .get(&node_key) .expect("`is_node_reachable` should only be called on AST nodes with recorded reachability"), ) .may_be_true() } pub(crate) fn end_of_scope_bindings( &self, place: ScopedPlaceId, ) -> BindingWithConstraintsIterator<'_, 'db> { match place { ScopedPlaceId::Symbol(symbol) => self.end_of_scope_symbol_bindings(symbol), ScopedPlaceId::Member(member) => self.end_of_scope_member_bindings(member), } } pub(crate) fn end_of_scope_symbol_bindings( &self, symbol: ScopedSymbolId, ) -> BindingWithConstraintsIterator<'_, 'db> { self.bindings_iterator( self.end_of_scope_symbols[symbol].bindings(), BoundnessAnalysis::BasedOnUnboundVisibility, ) } pub(crate) fn end_of_scope_member_bindings( &self, member: ScopedMemberId, ) -> BindingWithConstraintsIterator<'_, 'db> { self.bindings_iterator( self.end_of_scope_members[member].bindings(), BoundnessAnalysis::BasedOnUnboundVisibility, ) } pub(crate) fn reachable_bindings( &self, place: ScopedPlaceId, ) -> BindingWithConstraintsIterator<'_, 'db> { match place { ScopedPlaceId::Symbol(symbol) => self.reachable_symbol_bindings(symbol), ScopedPlaceId::Member(member) => self.reachable_member_bindings(member), } } pub(crate) fn reachable_symbol_bindings( &self, symbol: ScopedSymbolId, ) -> BindingWithConstraintsIterator<'_, 'db> { let bindings = &self.reachable_definitions_by_symbol[symbol].bindings; self.bindings_iterator(bindings, BoundnessAnalysis::AssumeBound) } pub(crate) fn reachable_member_bindings( &self, symbol: ScopedMemberId, ) -> BindingWithConstraintsIterator<'_, 'db> { let bindings = &self.reachable_definitions_by_member[symbol].bindings; self.bindings_iterator(bindings, BoundnessAnalysis::AssumeBound) } pub(crate) fn enclosing_snapshot( &self, snapshot_id: ScopedEnclosingSnapshotId, nested_laziness: ScopeLaziness, ) -> EnclosingSnapshotResult<'_, 'db> { let boundness_analysis = if nested_laziness.is_eager() { BoundnessAnalysis::BasedOnUnboundVisibility } else { // TODO: We haven't implemented proper boundness analysis for nonlocal symbols, so we assume the boundness is bound for now. BoundnessAnalysis::AssumeBound }; match self.enclosing_snapshots.get(snapshot_id) { Some(EnclosingSnapshot::Constraint(constraint)) => { EnclosingSnapshotResult::FoundConstraint(*constraint) } Some(EnclosingSnapshot::Bindings(bindings)) => EnclosingSnapshotResult::FoundBindings( self.bindings_iterator(bindings, boundness_analysis), ), None => EnclosingSnapshotResult::NotFound, } } pub(crate) fn bindings_at_definition( &self, definition: Definition<'db>, ) -> BindingWithConstraintsIterator<'_, 'db> { self.bindings_iterator( &self.bindings_by_definition[&definition], BoundnessAnalysis::BasedOnUnboundVisibility, ) } pub(crate) fn declarations_at_binding( &self, binding: Definition<'db>, ) -> DeclarationsIterator<'_, 'db> { self.declarations_iterator( &self.declarations_by_binding[&binding], BoundnessAnalysis::BasedOnUnboundVisibility, ) } pub(crate) fn end_of_scope_declarations<'map>( &'map self, place: ScopedPlaceId, ) -> DeclarationsIterator<'map, 'db> { match place { ScopedPlaceId::Symbol(symbol) => self.end_of_scope_symbol_declarations(symbol), ScopedPlaceId::Member(member) => self.end_of_scope_member_declarations(member), } } pub(crate) fn end_of_scope_symbol_declarations<'map>( &'map self, symbol: ScopedSymbolId, ) -> DeclarationsIterator<'map, 'db> { let declarations = self.end_of_scope_symbols[symbol].declarations(); self.declarations_iterator(declarations, BoundnessAnalysis::BasedOnUnboundVisibility) } pub(crate) fn end_of_scope_member_declarations<'map>( &'map self, member: ScopedMemberId, ) -> DeclarationsIterator<'map, 'db> { let declarations = self.end_of_scope_members[member].declarations(); self.declarations_iterator(declarations, BoundnessAnalysis::BasedOnUnboundVisibility) } pub(crate) fn reachable_symbol_declarations( &self, symbol: ScopedSymbolId, ) -> DeclarationsIterator<'_, 'db> { let declarations = &self.reachable_definitions_by_symbol[symbol].declarations; self.declarations_iterator(declarations, BoundnessAnalysis::AssumeBound) } pub(crate) fn reachable_member_declarations( &self, member: ScopedMemberId, ) -> DeclarationsIterator<'_, 'db> { let declarations = &self.reachable_definitions_by_member[member].declarations; self.declarations_iterator(declarations, BoundnessAnalysis::AssumeBound) } pub(crate) fn reachable_declarations( &self, place: ScopedPlaceId, ) -> DeclarationsIterator<'_, 'db> { match place { ScopedPlaceId::Symbol(symbol) => self.reachable_symbol_declarations(symbol), ScopedPlaceId::Member(member) => self.reachable_member_declarations(member), } } pub(crate) fn all_end_of_scope_symbol_declarations<'map>( &'map self, ) -> impl Iterator<Item = (ScopedSymbolId, DeclarationsIterator<'map, 'db>)> + 'map { self.end_of_scope_symbols .indices() .map(|symbol_id| (symbol_id, self.end_of_scope_symbol_declarations(symbol_id))) } pub(crate) fn all_end_of_scope_symbol_bindings<'map>( &'map self, ) -> impl Iterator<Item = (ScopedSymbolId, BindingWithConstraintsIterator<'map, 'db>)> + 'map { self.end_of_scope_symbols .indices() .map(|symbol_id| (symbol_id, self.end_of_scope_symbol_bindings(symbol_id))) } pub(crate) fn all_reachable_symbols<'map>( &'map self, ) -> impl Iterator< Item = ( ScopedSymbolId, DeclarationsIterator<'map, 'db>, BindingWithConstraintsIterator<'map, 'db>, ), > + 'map { self.reachable_definitions_by_symbol.iter_enumerated().map( |(symbol_id, reachable_definitions)| { let declarations = self.declarations_iterator( &reachable_definitions.declarations, BoundnessAnalysis::AssumeBound, ); let bindings = self.bindings_iterator( &reachable_definitions.bindings, BoundnessAnalysis::AssumeBound, ); (symbol_id, declarations, bindings) }, ) } /// This function is intended to be called only once inside `TypeInferenceBuilder::infer_function_body`. pub(crate) fn can_implicitly_return_none(&self, db: &dyn crate::Db) -> bool { !self .reachability_constraints .evaluate(db, &self.predicates, self.end_of_scope_reachability) .is_always_false() } pub(crate) fn binding_reachability( &self, db: &dyn crate::Db, binding: &BindingWithConstraints<'_, 'db>, ) -> Truthiness { self.reachability_constraints.evaluate( db, &self.predicates, binding.reachability_constraint, ) } fn bindings_iterator<'map>( &'map self, bindings: &'map Bindings, boundness_analysis: BoundnessAnalysis, ) -> BindingWithConstraintsIterator<'map, 'db> { BindingWithConstraintsIterator { all_definitions: &self.all_definitions, predicates: &self.predicates, narrowing_constraints: &self.narrowing_constraints, reachability_constraints: &self.reachability_constraints, boundness_analysis, inner: bindings.iter(), } } fn declarations_iterator<'map>( &'map self, declarations: &'map Declarations, boundness_analysis: BoundnessAnalysis, ) -> DeclarationsIterator<'map, 'db> { DeclarationsIterator { all_definitions: &self.all_definitions, predicates: &self.predicates, reachability_constraints: &self.reachability_constraints, boundness_analysis, inner: declarations.iter(), } } } /// Uniquely identifies a snapshot of an enclosing scope place state that can be used to resolve a /// reference in a nested scope. /// /// An eager scope has its entire body executed immediately at the location where it is defined. /// For any free references in the nested scope, we use the bindings that are visible at the point /// where the nested scope is defined, instead of using the public type of the place. /// /// There is a unique ID for each distinct [`EnclosingSnapshotKey`] in the file. #[newtype_index] #[derive(get_size2::GetSize)] pub(crate) struct ScopedEnclosingSnapshotId; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, get_size2::GetSize)] pub(crate) struct EnclosingSnapshotKey { /// The enclosing scope containing the bindings pub(crate) enclosing_scope: FileScopeId, /// The referenced place (in the enclosing scope) pub(crate) enclosing_place: ScopedPlaceId, /// The nested scope containing the reference pub(crate) nested_scope: FileScopeId, /// Laziness of the nested scope (technically redundant, but convenient to have here) pub(crate) nested_laziness: ScopeLaziness, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/reachability_constraints.rs
crates/ty_python_semantic/src/semantic_index/reachability_constraints.rs
//! # Reachability constraints //! //! During semantic index building, we record so-called reachability constraints that keep track //! of a set of conditions that need to apply in order for a certain statement or expression to //! be reachable from the start of the scope. As an example, consider the following situation where //! we have just processed an `if`-statement: //! ```py //! if test: //! <is this reachable?> //! ``` //! In this case, we would record a reachability constraint of `test`, which would later allow us //! to re-analyze the control flow during type-checking, once we actually know the static truthiness //! of `test`. When evaluating a constraint, there are three possible outcomes: always true, always //! false, or ambiguous. For a simple constraint like this, always-true and always-false correspond //! to the case in which we can infer that the type of `test` is `Literal[True]` or `Literal[False]`. //! In any other case, like if the type of `test` is `bool` or `Unknown`, we cannot statically //! determine whether `test` is truthy or falsy, so the outcome would be "ambiguous". //! //! //! ## Sequential constraints (ternary AND) //! //! Whenever control flow branches, we record reachability constraints. If we already have a //! constraint, we create a new one using a ternary AND operation. Consider the following example: //! ```py //! if test1: //! if test2: //! <is this reachable?> //! ``` //! Here, we would accumulate a reachability constraint of `test1 AND test2`. We can statically //! determine that this position is *always* reachable only if both `test1` and `test2` are //! always true. On the other hand, we can statically determine that this position is *never* //! reachable if *either* `test1` or `test2` is always false. In any other case, we cannot //! determine whether this position is reachable or not, so the outcome is "ambiguous". This //! corresponds to a ternary *AND* operation in [Kleene] logic: //! //! ```text //! | AND | always-false | ambiguous | always-true | //! |--------------|--------------|--------------|--------------| //! | always false | always-false | always-false | always-false | //! | ambiguous | always-false | ambiguous | ambiguous | //! | always true | always-false | ambiguous | always-true | //! ``` //! //! //! ## Merged constraints (ternary OR) //! //! We also need to consider the case where control flow merges again. Consider a case like this: //! ```py //! def _(): //! if test1: //! pass //! elif test2: //! pass //! else: //! return //! //! <is this reachable?> //! ``` //! Here, the first branch has a `test1` constraint, and the second branch has a `test2` constraint. //! The third branch ends in a terminal statement [^1]. When we merge control flow, we need to consider //! the reachability through either the first or the second branch. The current position is only //! *definitely* unreachable if both `test1` and `test2` are always false. It is definitely //! reachable if *either* `test1` or `test2` is always true. In any other case, we cannot statically //! determine whether it is reachable or not. This operation corresponds to a ternary *OR* operation: //! //! ```text //! | OR | always-false | ambiguous | always-true | //! |--------------|--------------|--------------|--------------| //! | always false | always-false | ambiguous | always-true | //! | ambiguous | ambiguous | ambiguous | always-true | //! | always true | always-true | always-true | always-true | //! ``` //! //! [^1]: What's actually happening here is that we merge all three branches using a ternary OR. The //! third branch has a reachability constraint of `always-false`, and `t OR always-false` is equal //! to `t` (see first column in that table), so it was okay to omit the third branch in the discussion //! above. //! //! //! ## Negation //! //! Control flow elements like `if-elif-else` or `match` statements can also lead to negated //! constraints. For example, we record a constraint of `~test` for the `else` branch here: //! ```py //! if test: //! pass //! else: //! <is this reachable?> //! ``` //! //! ## Explicit ambiguity //! //! In some cases, we explicitly record an “ambiguous” constraint. We do this when branching on //! something that we cannot (or intentionally do not want to) analyze statically. `for` loops are //! one example: //! ```py //! def _(): //! for _ in range(2): //! return //! //! <is this reachable?> //! ``` //! If we would not record any constraints at the branching point, we would have an `always-true` //! reachability for the no-loop branch, and a `always-true` reachability for the branch which enters //! the loop. Merging those would lead to a reachability of `always-true OR always-true = always-true`, //! i.e. we would consider the end of the scope to be unconditionally reachable, which is not correct. //! //! Recording an ambiguous constraint at the branching point modifies the constraints in both branches to //! `always-true AND ambiguous = ambiguous`. Merging these two using OR correctly leads to `ambiguous` for //! the end-of-scope reachability. //! //! //! ## Reachability constraints and bindings //! //! To understand how reachability constraints apply to bindings in particular, consider the following //! example: //! ```py //! x = <unbound> # not a live binding for the use of x below, shadowed by `x = 1` //! y = <unbound> # reachability constraint: ~test //! //! x = 1 # reachability constraint: ~test //! if test: //! x = 2 # reachability constraint: test //! //! y = 2 # reachability constraint: test //! //! use(x) //! use(y) //! ``` //! Both the type and the boundness of `x` and `y` are affected by reachability constraints: //! //! ```text //! | `test` truthiness | type of `x` | boundness of `y` | //! |-------------------|-----------------|------------------| //! | always false | `Literal[1]` | unbound | //! | ambiguous | `Literal[1, 2]` | possibly unbound | //! | always true | `Literal[2]` | bound | //! ``` //! //! To achieve this, we apply reachability constraints retroactively to bindings that came before //! the branching point. In the example above, the `x = 1` binding has a `test` constraint in the //! `if` branch, and a `~test` constraint in the implicit `else` branch. Since it is shadowed by //! `x = 2` in the `if` branch, we are only left with the `~test` constraint after control flow //! has merged again. //! //! For live bindings, the reachability constraint therefore refers to the following question: //! Is the binding reachable from the start of the scope, and is there a control flow path from //! that binding to a use of that symbol at the current position? //! //! In the example above, `x = 1` is always reachable, but that binding can only reach the use of //! `x` at the current position if `test` is falsy. //! //! To handle boundness correctly, we also add implicit `y = <unbound>` bindings at the start of //! the scope. This allows us to determine whether a symbol is definitely bound (if that implicit //! `y = <unbound>` binding is not visible), possibly unbound (if the reachability constraint //! evaluates to `Ambiguous`), or definitely unbound (in case the `y = <unbound>` binding is //! always visible). //! //! //! ### Representing formulas //! //! Given everything above, we can represent a reachability constraint as a _ternary formula_. This //! is like a boolean formula (which maps several true/false variables to a single true/false //! result), but which allows the third "ambiguous" value in addition to "true" and "false". //! //! [_Binary decision diagrams_][bdd] (BDDs) are a common way to represent boolean formulas when //! doing program analysis. We extend this to a _ternary decision diagram_ (TDD) to support //! ambiguous values. //! //! A TDD is a graph, and a ternary formula is represented by a node in this graph. There are three //! possible leaf nodes representing the "true", "false", and "ambiguous" constant functions. //! Interior nodes consist of a ternary variable to evaluate, and outgoing edges for whether the //! variable evaluates to true, false, or ambiguous. //! //! Our TDDs are _reduced_ and _ordered_ (as is typical for BDDs). //! //! An ordered TDD means that variables appear in the same order in all paths within the graph. //! //! A reduced TDD means two things: First, we intern the graph nodes, so that we only keep a single //! copy of interior nodes with the same contents. Second, we eliminate any nodes that are "noops", //! where the "true" and "false" outgoing edges lead to the same node. (This implies that it //! doesn't matter what value that variable has when evaluating the formula, and we can leave it //! out of the evaluation chain completely.) //! //! Reduced and ordered decision diagrams are _normal forms_, which means that two equivalent //! formulas (which have the same outputs for every combination of inputs) are represented by //! exactly the same graph node. (Because of interning, this is not _equal_ nodes, but _identical_ //! ones.) That means that we can compare formulas for equivalence in constant time, and in //! particular, can check whether a reachability constraint is statically always true or false, //! regardless of any Python program state, by seeing if the constraint's formula is the "true" or //! "false" leaf node. //! //! [Kleene]: <https://en.wikipedia.org/wiki/Three-valued_logic#Kleene_and_Priest_logics> //! [bdd]: https://en.wikipedia.org/wiki/Binary_decision_diagram use std::cmp::Ordering; use ruff_index::{Idx, IndexVec}; use rustc_hash::FxHashMap; use crate::Db; use crate::dunder_all::dunder_all_names; use crate::place::{RequiresExplicitReExport, imported_symbol}; use crate::rank::RankBitBox; use crate::semantic_index::place_table; use crate::semantic_index::predicate::{ CallableAndCallExpr, PatternPredicate, PatternPredicateKind, Predicate, PredicateNode, Predicates, ScopedPredicateId, }; use crate::types::{ CallableTypes, IntersectionBuilder, Truthiness, Type, TypeContext, UnionBuilder, UnionType, infer_expression_type, static_expression_truthiness, }; /// A ternary formula that defines under what conditions a binding is visible. (A ternary formula /// is just like a boolean formula, but with `Ambiguous` as a third potential result. See the /// module documentation for more details.) /// /// The primitive atoms of the formula are [`Predicate`]s, which express some property of the /// runtime state of the code that we are analyzing. /// /// We assume that each atom has a stable value each time that the formula is evaluated. An atom /// that resolves to `Ambiguous` might be true or false, and we can't tell which — but within that /// evaluation, we assume that the atom has the _same_ unknown value each time it appears. That /// allows us to perform simplifications like `A ∨ !A → true` and `A ∧ !A → false`. /// /// That means that when you are constructing a formula, you might need to create distinct atoms /// for a particular [`Predicate`], if your formula needs to consider how a particular runtime /// property might be different at different points in the execution of the program. /// /// reachability constraints are normalized, so equivalent constraints are guaranteed to have equal /// IDs. #[derive(Clone, Copy, Eq, Hash, PartialEq, get_size2::GetSize)] pub(crate) struct ScopedReachabilityConstraintId(u32); impl std::fmt::Debug for ScopedReachabilityConstraintId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut f = f.debug_tuple("ScopedReachabilityConstraintId"); match *self { // We use format_args instead of rendering the strings directly so that we don't get // any quotes in the output: ScopedReachabilityConstraintId(AlwaysTrue) instead of // ScopedReachabilityConstraintId("AlwaysTrue"). ALWAYS_TRUE => f.field(&format_args!("AlwaysTrue")), AMBIGUOUS => f.field(&format_args!("Ambiguous")), ALWAYS_FALSE => f.field(&format_args!("AlwaysFalse")), _ => f.field(&self.0), }; f.finish() } } // Internal details: // // There are 3 terminals, with hard-coded constraint IDs: true, ambiguous, and false. // // _Atoms_ are the underlying Predicates, which are the variables that are evaluated by the // ternary function. // // _Interior nodes_ provide the TDD structure for the formula. Interior nodes are stored in an // arena Vec, with the constraint ID providing an index into the arena. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, get_size2::GetSize)] struct InteriorNode { /// A "variable" that is evaluated as part of a TDD ternary function. For reachability /// constraints, this is a `Predicate` that represents some runtime property of the Python /// code that we are evaluating. atom: ScopedPredicateId, if_true: ScopedReachabilityConstraintId, if_ambiguous: ScopedReachabilityConstraintId, if_false: ScopedReachabilityConstraintId, } impl ScopedReachabilityConstraintId { /// A special ID that is used for an "always true" / "always visible" constraint. pub(crate) const ALWAYS_TRUE: ScopedReachabilityConstraintId = ScopedReachabilityConstraintId(0xffff_ffff); /// A special ID that is used for an ambiguous constraint. pub(crate) const AMBIGUOUS: ScopedReachabilityConstraintId = ScopedReachabilityConstraintId(0xffff_fffe); /// A special ID that is used for an "always false" / "never visible" constraint. pub(crate) const ALWAYS_FALSE: ScopedReachabilityConstraintId = ScopedReachabilityConstraintId(0xffff_fffd); fn is_terminal(self) -> bool { self.0 >= SMALLEST_TERMINAL.0 } fn as_u32(self) -> u32 { self.0 } } impl Idx for ScopedReachabilityConstraintId { #[inline] fn new(value: usize) -> Self { assert!(value <= (SMALLEST_TERMINAL.0 as usize)); #[expect(clippy::cast_possible_truncation)] Self(value as u32) } #[inline] fn index(self) -> usize { debug_assert!(!self.is_terminal()); self.0 as usize } } // Rebind some constants locally so that we don't need as many qualifiers below. const ALWAYS_TRUE: ScopedReachabilityConstraintId = ScopedReachabilityConstraintId::ALWAYS_TRUE; const AMBIGUOUS: ScopedReachabilityConstraintId = ScopedReachabilityConstraintId::AMBIGUOUS; const ALWAYS_FALSE: ScopedReachabilityConstraintId = ScopedReachabilityConstraintId::ALWAYS_FALSE; const SMALLEST_TERMINAL: ScopedReachabilityConstraintId = ALWAYS_FALSE; fn singleton_to_type(db: &dyn Db, singleton: ruff_python_ast::Singleton) -> Type<'_> { let ty = match singleton { ruff_python_ast::Singleton::None => Type::none(db), ruff_python_ast::Singleton::True => Type::BooleanLiteral(true), ruff_python_ast::Singleton::False => Type::BooleanLiteral(false), }; debug_assert!(ty.is_singleton(db)); ty } /// Turn a `match` pattern kind into a type that represents the set of all values that would definitely /// match that pattern. fn pattern_kind_to_type<'db>(db: &'db dyn Db, kind: &PatternPredicateKind<'db>) -> Type<'db> { match kind { PatternPredicateKind::Singleton(singleton) => singleton_to_type(db, *singleton), PatternPredicateKind::Value(value) => { infer_expression_type(db, *value, TypeContext::default()) } PatternPredicateKind::Class(class_expr, kind) => { if kind.is_irrefutable() { infer_expression_type(db, *class_expr, TypeContext::default()) .to_instance(db) .unwrap_or(Type::Never) .top_materialization(db) } else { Type::Never } } PatternPredicateKind::Or(predicates) => { UnionType::from_elements(db, predicates.iter().map(|p| pattern_kind_to_type(db, p))) } PatternPredicateKind::As(pattern, _) => pattern .as_deref() .map(|p| pattern_kind_to_type(db, p)) .unwrap_or_else(Type::object), PatternPredicateKind::Unsupported => Type::Never, } } /// Go through the list of previous match cases, and accumulate a union of all types that were already /// matched by these patterns. fn type_excluded_by_previous_patterns<'db>( db: &'db dyn Db, mut predicate: PatternPredicate<'db>, ) -> Type<'db> { let mut builder = UnionBuilder::new(db); while let Some(previous) = predicate.previous_predicate(db) { predicate = *previous; if predicate.guard(db).is_none() { builder = builder.add(pattern_kind_to_type(db, predicate.kind(db))); } } builder.build() } /// Analyze a pattern predicate to determine its static truthiness. /// /// This is a Salsa tracked function to enable memoization. Without memoization, for a match /// statement with N cases where each case references the subject (e.g., `self`), we would /// re-analyze each pattern O(N) times (once per reference), leading to O(N²) total work. /// With memoization, each pattern is analyzed exactly once. #[salsa::tracked(cycle_initial = analyze_pattern_predicate_cycle_initial, heap_size = get_size2::GetSize::get_heap_size)] fn analyze_pattern_predicate<'db>(db: &'db dyn Db, predicate: PatternPredicate<'db>) -> Truthiness { let subject_ty = infer_expression_type(db, predicate.subject(db), TypeContext::default()); let narrowed_subject = IntersectionBuilder::new(db) .add_positive(subject_ty) .add_negative(type_excluded_by_previous_patterns(db, predicate)); let narrowed_subject_ty = narrowed_subject.clone().build(); // Consider a case where we match on a subject type of `Self` with an upper bound of `Answer`, // where `Answer` is a {YES, NO} enum. After a previous pattern matching on `NO`, the narrowed // subject type is `Self & ~Literal[NO]`. This type is *not* equivalent to `Literal[YES]`, // because `Self` could also specialize to `Literal[NO]` or `Never`, making the intersection // empty. However, if the current pattern matches on `YES`, the *next* narrowed subject type // will be `Self & ~Literal[NO] & ~Literal[YES]`, which *is* always equivalent to `Never`. This // means that subsequent patterns can never match. And we know that if we reach this point, // the current pattern will have to match. We return `AlwaysTrue` here, since the call to // `analyze_single_pattern_predicate_kind` below would return `Ambiguous` in this case. let next_narrowed_subject_ty = narrowed_subject .add_negative(pattern_kind_to_type(db, predicate.kind(db))) .build(); if !narrowed_subject_ty.is_never() && next_narrowed_subject_ty.is_never() { return Truthiness::AlwaysTrue; } let truthiness = ReachabilityConstraints::analyze_single_pattern_predicate_kind( db, predicate.kind(db), narrowed_subject_ty, ); if truthiness == Truthiness::AlwaysTrue && predicate.guard(db).is_some() { // Fall back to ambiguous, the guard might change the result. // TODO: actually analyze guard truthiness Truthiness::Ambiguous } else { truthiness } } fn analyze_pattern_predicate_cycle_initial<'db>( _db: &'db dyn Db, _id: salsa::Id, _predicate: PatternPredicate<'db>, ) -> Truthiness { Truthiness::Ambiguous } /// A collection of reachability constraints for a given scope. #[derive(Debug, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) struct ReachabilityConstraints { /// The interior TDD nodes that were marked as used when being built. used_interiors: Box<[InteriorNode]>, /// A bit vector indicating which interior TDD nodes were marked as used. This is indexed by /// the node's [`ScopedReachabilityConstraintId`]. The rank of the corresponding bit gives the /// index of that node in the `used_interiors` vector. used_indices: RankBitBox, } #[derive(Debug, Default, PartialEq, Eq)] pub(crate) struct ReachabilityConstraintsBuilder { interiors: IndexVec<ScopedReachabilityConstraintId, InteriorNode>, interior_used: IndexVec<ScopedReachabilityConstraintId, bool>, interior_cache: FxHashMap<InteriorNode, ScopedReachabilityConstraintId>, not_cache: FxHashMap<ScopedReachabilityConstraintId, ScopedReachabilityConstraintId>, and_cache: FxHashMap< ( ScopedReachabilityConstraintId, ScopedReachabilityConstraintId, ), ScopedReachabilityConstraintId, >, or_cache: FxHashMap< ( ScopedReachabilityConstraintId, ScopedReachabilityConstraintId, ), ScopedReachabilityConstraintId, >, } impl ReachabilityConstraintsBuilder { pub(crate) fn build(self) -> ReachabilityConstraints { let used_indices = RankBitBox::from_bits(self.interior_used.iter().copied()); let used_interiors = (self.interiors.into_iter()) .zip(self.interior_used) .filter_map(|(interior, used)| used.then_some(interior)) .collect(); ReachabilityConstraints { used_interiors, used_indices, } } /// Marks that a particular TDD node is used. This lets us throw away interior nodes that were /// only calculated for intermediate values, and which don't need to be included in the final /// built result. pub(crate) fn mark_used(&mut self, node: ScopedReachabilityConstraintId) { if !node.is_terminal() && !self.interior_used[node] { self.interior_used[node] = true; let node = self.interiors[node]; self.mark_used(node.if_true); self.mark_used(node.if_ambiguous); self.mark_used(node.if_false); } } /// Implements the ordering that determines which level a TDD node appears at. /// /// Each interior node checks the value of a single variable (for us, a `Predicate`). /// TDDs are ordered such that every path from the root of the graph to the leaves must /// check each variable at most once, and must check each variable in the same order. /// /// We can choose any ordering that we want, as long as it's consistent — with the /// caveat that terminal nodes must always be last in the ordering, since they are the /// leaf nodes of the graph. /// /// We currently compare interior nodes by looking at the Salsa IDs of each variable's /// `Predicate`, since this is already available and easy to compare. We also _reverse_ /// the comparison of those Salsa IDs. The Salsa IDs are assigned roughly sequentially /// while traversing the source code. Reversing the comparison means `Predicate`s that /// appear later in the source will tend to be placed "higher" (closer to the root) in /// the TDD graph. We have found empirically that this leads to smaller TDD graphs [1], /// since there are often repeated combinations of `Predicate`s from earlier in the /// file. /// /// [1]: https://github.com/astral-sh/ruff/pull/20098 fn cmp_atoms( &self, a: ScopedReachabilityConstraintId, b: ScopedReachabilityConstraintId, ) -> Ordering { if a == b || (a.is_terminal() && b.is_terminal()) { Ordering::Equal } else if a.is_terminal() { Ordering::Greater } else if b.is_terminal() { Ordering::Less } else { // See https://github.com/astral-sh/ruff/pull/20098 for an explanation of why this // ordering is reversed. self.interiors[a] .atom .cmp(&self.interiors[b].atom) .reverse() } } /// Adds an interior node, ensuring that we always use the same reachability constraint ID for /// equal nodes. fn add_interior(&mut self, node: InteriorNode) -> ScopedReachabilityConstraintId { // If the true and false branches lead to the same node, we can override the ambiguous // branch to go there too. And this node is then redundant and can be reduced. if node.if_true == node.if_false { return node.if_true; } *self.interior_cache.entry(node).or_insert_with(|| { self.interior_used.push(false); self.interiors.push(node) }) } /// Adds a new reachability constraint that checks a single [`Predicate`]. /// /// [`ScopedPredicateId`]s are the “variables” that are evaluated by a TDD. A TDD variable has /// the same value no matter how many times it appears in the ternary formula that the TDD /// represents. /// /// However, we sometimes have to model how a `Predicate` can have a different runtime /// value at different points in the execution of the program. To handle this, you can take /// advantage of the fact that the [`Predicates`] arena does not deduplicate `Predicate`s. /// You can add a `Predicate` multiple times, yielding different `ScopedPredicateId`s, which /// you can then create separate TDD atoms for. pub(crate) fn add_atom( &mut self, predicate: ScopedPredicateId, ) -> ScopedReachabilityConstraintId { if predicate == ScopedPredicateId::ALWAYS_FALSE { ScopedReachabilityConstraintId::ALWAYS_FALSE } else if predicate == ScopedPredicateId::ALWAYS_TRUE { ScopedReachabilityConstraintId::ALWAYS_TRUE } else { self.add_interior(InteriorNode { atom: predicate, if_true: ALWAYS_TRUE, if_ambiguous: AMBIGUOUS, if_false: ALWAYS_FALSE, }) } } /// Adds a new reachability constraint that is the ternary NOT of an existing one. pub(crate) fn add_not_constraint( &mut self, a: ScopedReachabilityConstraintId, ) -> ScopedReachabilityConstraintId { if a == ALWAYS_TRUE { return ALWAYS_FALSE; } else if a == AMBIGUOUS { return AMBIGUOUS; } else if a == ALWAYS_FALSE { return ALWAYS_TRUE; } if let Some(cached) = self.not_cache.get(&a) { return *cached; } let a_node = self.interiors[a]; let if_true = self.add_not_constraint(a_node.if_true); let if_ambiguous = self.add_not_constraint(a_node.if_ambiguous); let if_false = self.add_not_constraint(a_node.if_false); let result = self.add_interior(InteriorNode { atom: a_node.atom, if_true, if_ambiguous, if_false, }); self.not_cache.insert(a, result); result } /// Adds a new reachability constraint that is the ternary OR of two existing ones. pub(crate) fn add_or_constraint( &mut self, a: ScopedReachabilityConstraintId, b: ScopedReachabilityConstraintId, ) -> ScopedReachabilityConstraintId { match (a, b) { (ALWAYS_TRUE, _) | (_, ALWAYS_TRUE) => return ALWAYS_TRUE, (ALWAYS_FALSE, other) | (other, ALWAYS_FALSE) => return other, (AMBIGUOUS, AMBIGUOUS) => return AMBIGUOUS, _ => {} } // OR is commutative, which lets us halve the cache requirements let (a, b) = if b.0 < a.0 { (b, a) } else { (a, b) }; if let Some(cached) = self.or_cache.get(&(a, b)) { return *cached; } let (atom, if_true, if_ambiguous, if_false) = match self.cmp_atoms(a, b) { Ordering::Equal => { let a_node = self.interiors[a]; let b_node = self.interiors[b]; let if_true = self.add_or_constraint(a_node.if_true, b_node.if_true); let if_false = self.add_or_constraint(a_node.if_false, b_node.if_false); let if_ambiguous = if if_true == if_false { if_true } else { self.add_or_constraint(a_node.if_ambiguous, b_node.if_ambiguous) }; (a_node.atom, if_true, if_ambiguous, if_false) } Ordering::Less => { let a_node = self.interiors[a]; let if_true = self.add_or_constraint(a_node.if_true, b); let if_false = self.add_or_constraint(a_node.if_false, b); let if_ambiguous = if if_true == if_false { if_true } else { self.add_or_constraint(a_node.if_ambiguous, b) }; (a_node.atom, if_true, if_ambiguous, if_false) } Ordering::Greater => { let b_node = self.interiors[b]; let if_true = self.add_or_constraint(a, b_node.if_true); let if_false = self.add_or_constraint(a, b_node.if_false); let if_ambiguous = if if_true == if_false { if_true } else { self.add_or_constraint(a, b_node.if_ambiguous) }; (b_node.atom, if_true, if_ambiguous, if_false) } }; let result = self.add_interior(InteriorNode { atom, if_true, if_ambiguous, if_false, }); self.or_cache.insert((a, b), result); result } /// Adds a new reachability constraint that is the ternary AND of two existing ones. pub(crate) fn add_and_constraint( &mut self, a: ScopedReachabilityConstraintId, b: ScopedReachabilityConstraintId, ) -> ScopedReachabilityConstraintId { match (a, b) { (ALWAYS_FALSE, _) | (_, ALWAYS_FALSE) => return ALWAYS_FALSE, (ALWAYS_TRUE, other) | (other, ALWAYS_TRUE) => return other, (AMBIGUOUS, AMBIGUOUS) => return AMBIGUOUS, _ => {} } // AND is commutative, which lets us halve the cache requirements let (a, b) = if b.0 < a.0 { (b, a) } else { (a, b) }; if let Some(cached) = self.and_cache.get(&(a, b)) { return *cached; } let (atom, if_true, if_ambiguous, if_false) = match self.cmp_atoms(a, b) { Ordering::Equal => { let a_node = self.interiors[a]; let b_node = self.interiors[b]; let if_true = self.add_and_constraint(a_node.if_true, b_node.if_true); let if_false = self.add_and_constraint(a_node.if_false, b_node.if_false); let if_ambiguous = if if_true == if_false { if_true } else { self.add_and_constraint(a_node.if_ambiguous, b_node.if_ambiguous) }; (a_node.atom, if_true, if_ambiguous, if_false) } Ordering::Less => { let a_node = self.interiors[a]; let if_true = self.add_and_constraint(a_node.if_true, b); let if_false = self.add_and_constraint(a_node.if_false, b); let if_ambiguous = if if_true == if_false { if_true } else { self.add_and_constraint(a_node.if_ambiguous, b) }; (a_node.atom, if_true, if_ambiguous, if_false) } Ordering::Greater => { let b_node = self.interiors[b]; let if_true = self.add_and_constraint(a, b_node.if_true); let if_false = self.add_and_constraint(a, b_node.if_false); let if_ambiguous = if if_true == if_false { if_true } else { self.add_and_constraint(a, b_node.if_ambiguous) }; (b_node.atom, if_true, if_ambiguous, if_false) } }; let result = self.add_interior(InteriorNode { atom, if_true, if_ambiguous, if_false, }); self.and_cache.insert((a, b), result); result } } impl ReachabilityConstraints { /// Analyze the statically known reachability for a given constraint. pub(crate) fn evaluate<'db>( &self, db: &'db dyn Db, predicates: &Predicates<'db>, mut id: ScopedReachabilityConstraintId,
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/predicate.rs
crates/ty_python_semantic/src/semantic_index/predicate.rs
//! _Predicates_ are Python expressions whose runtime values can affect type inference. //! //! We currently use predicates in two places: //! //! - [_Narrowing constraints_][crate::semantic_index::narrowing_constraints] constrain the type of //! a binding that is visible at a particular use. //! - [_Reachability constraints_][crate::semantic_index::reachability_constraints] determine the //! static reachability of a binding, and the reachability of a statement or expression. use ruff_db::files::File; use ruff_index::{Idx, IndexVec}; use ruff_python_ast::{Singleton, name::Name}; use crate::db::Db; use crate::semantic_index::expression::Expression; use crate::semantic_index::global_scope; use crate::semantic_index::scope::{FileScopeId, ScopeId}; use crate::semantic_index::symbol::ScopedSymbolId; // A scoped identifier for each `Predicate` in a scope. #[derive(Clone, Debug, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, get_size2::GetSize)] pub(crate) struct ScopedPredicateId(u32); impl ScopedPredicateId { /// A special ID that is used for an "always true" predicate. pub(crate) const ALWAYS_TRUE: ScopedPredicateId = ScopedPredicateId(0xffff_ffff); /// A special ID that is used for an "always false" predicate. pub(crate) const ALWAYS_FALSE: ScopedPredicateId = ScopedPredicateId(0xffff_fffe); const SMALLEST_TERMINAL: ScopedPredicateId = Self::ALWAYS_FALSE; fn is_terminal(self) -> bool { self >= Self::SMALLEST_TERMINAL } #[cfg(test)] pub(crate) fn as_u32(self) -> u32 { self.0 } } impl Idx for ScopedPredicateId { #[inline] fn new(value: usize) -> Self { assert!(value <= (Self::SMALLEST_TERMINAL.0 as usize)); #[expect(clippy::cast_possible_truncation)] Self(value as u32) } #[inline] fn index(self) -> usize { debug_assert!(!self.is_terminal()); self.0 as usize } } // A collection of predicates for a given scope. pub(crate) type Predicates<'db> = IndexVec<ScopedPredicateId, Predicate<'db>>; #[derive(Debug, Default)] pub(crate) struct PredicatesBuilder<'db> { predicates: IndexVec<ScopedPredicateId, Predicate<'db>>, } impl<'db> PredicatesBuilder<'db> { /// Adds a predicate. Note that we do not deduplicate predicates. If you add a `Predicate` /// more than once, you will get distinct `ScopedPredicateId`s for each one. (This lets you /// model predicates that might evaluate to different values at different points of execution.) pub(crate) fn add_predicate(&mut self, predicate: Predicate<'db>) -> ScopedPredicateId { self.predicates.push(predicate) } pub(crate) fn build(mut self) -> Predicates<'db> { self.predicates.shrink_to_fit(); self.predicates } } #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) struct Predicate<'db> { pub(crate) node: PredicateNode<'db>, pub(crate) is_positive: bool, } #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) enum PredicateOrLiteral<'db> { Literal(bool), Predicate(Predicate<'db>), } impl PredicateOrLiteral<'_> { pub(crate) fn negated(self) -> Self { match self { PredicateOrLiteral::Literal(value) => PredicateOrLiteral::Literal(!value), PredicateOrLiteral::Predicate(Predicate { node, is_positive }) => { PredicateOrLiteral::Predicate(Predicate { node, is_positive: !is_positive, }) } } } } #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) struct CallableAndCallExpr<'db> { pub(crate) callable: Expression<'db>, pub(crate) call_expr: Expression<'db>, } #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) enum PredicateNode<'db> { Expression(Expression<'db>), ReturnsNever(CallableAndCallExpr<'db>), Pattern(PatternPredicate<'db>), StarImportPlaceholder(StarImportPlaceholderPredicate<'db>), } #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) enum ClassPatternKind { Irrefutable, Refutable, } impl ClassPatternKind { pub(crate) fn is_irrefutable(self) -> bool { matches!(self, ClassPatternKind::Irrefutable) } } /// Pattern kinds for which we support type narrowing and/or static reachability analysis. #[derive(Debug, Clone, Hash, PartialEq, salsa::Update, get_size2::GetSize)] pub(crate) enum PatternPredicateKind<'db> { Singleton(Singleton), Value(Expression<'db>), Or(Vec<PatternPredicateKind<'db>>), Class(Expression<'db>, ClassPatternKind), As(Option<Box<PatternPredicateKind<'db>>>, Option<Name>), Unsupported, } #[salsa::tracked(debug, heap_size=ruff_memory_usage::heap_size)] pub(crate) struct PatternPredicate<'db> { pub(crate) file: File, pub(crate) file_scope: FileScopeId, pub(crate) subject: Expression<'db>, #[returns(ref)] pub(crate) kind: PatternPredicateKind<'db>, pub(crate) guard: Option<Expression<'db>>, /// A reference to the pattern of the previous match case pub(crate) previous_predicate: Option<Box<PatternPredicate<'db>>>, } // The Salsa heap is tracked separately. impl get_size2::GetSize for PatternPredicate<'_> {} impl<'db> PatternPredicate<'db> { pub(crate) fn scope(self, db: &'db dyn Db) -> ScopeId<'db> { self.file_scope(db).to_scope_id(db, self.file(db)) } } /// A "placeholder predicate" that is used to model the fact that the boundness of a (possible) /// definition or declaration caused by a `*` import cannot be fully determined until type- /// inference time. This is essentially the same as a standard reachability constraint, so we reuse /// the [`Predicate`] infrastructure to model it. /// /// To illustrate, say we have a module `exporter.py` like so: /// /// ```py /// if <condition>: /// class A: ... /// ``` /// /// and we have a module `importer.py` like so: /// /// ```py /// A = 1 /// /// from exporter import * /// ``` /// /// Since we cannot know whether or not <condition> is true at semantic-index time, we record /// a definition for `A` in `importer.py` as a result of the `from exporter import *` statement, /// but place a predicate on it to record the fact that we don't yet know whether this definition /// will be visible from all control-flow paths or not. Essentially, we model `importer.py` as /// something similar to this: /// /// ```py /// A = 1 /// /// if <star_import_placeholder_predicate>: /// from a import A /// ``` /// /// At type-check time, the placeholder predicate for the `A` definition is evaluated by attempting /// to resolve the `A` symbol in `exporter.py`'s global namespace: /// - If it resolves to a definitely bound symbol, then the predicate resolves to [`Truthiness::AlwaysTrue`] /// - If it resolves to an unbound symbol, then the predicate resolves to [`Truthiness::AlwaysFalse`] /// - If it resolves to a possibly bound symbol, then the predicate resolves to [`Truthiness::Ambiguous`] /// /// [Truthiness]: [crate::types::Truthiness] #[salsa::tracked(debug, heap_size=ruff_memory_usage::heap_size)] pub(crate) struct StarImportPlaceholderPredicate<'db> { pub(crate) importing_file: File, /// Each symbol imported by a `*` import has a separate predicate associated with it: /// this field identifies which symbol that is. /// /// Note that a [`ScopedPlaceId`] is only meaningful if you also know the scope /// it is relative to. For this specific struct, however, there's no need to store a /// separate field to hold the ID of the scope. `StarImportPredicate`s are only created /// for valid `*`-import definitions, and valid `*`-import definitions can only ever /// exist in the global scope; thus, we know that the `symbol_id` here will be relative /// to the global scope of the importing file. pub(crate) symbol_id: ScopedSymbolId, pub(crate) referenced_file: File, } // The Salsa heap is tracked separately. impl get_size2::GetSize for StarImportPlaceholderPredicate<'_> {} impl<'db> StarImportPlaceholderPredicate<'db> { pub(crate) fn scope(self, db: &'db dyn Db) -> ScopeId<'db> { // See doc-comment above [`StarImportPlaceholderPredicate::symbol_id`]: // valid `*`-import definitions can only take place in the global scope. global_scope(db, self.importing_file(db)) } } impl<'db> From<StarImportPlaceholderPredicate<'db>> for PredicateOrLiteral<'db> { fn from(predicate: StarImportPlaceholderPredicate<'db>) -> Self { PredicateOrLiteral::Predicate(Predicate { node: PredicateNode::StarImportPlaceholder(predicate), is_positive: true, }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/narrowing_constraints.rs
crates/ty_python_semantic/src/semantic_index/narrowing_constraints.rs
//! # Narrowing constraints //! //! When building a semantic index for a file, we associate each binding with a _narrowing //! constraint_, which constrains the type of the binding's place. Note that a binding can be //! associated with a different narrowing constraint at different points in a file. See the //! [`use_def`][crate::semantic_index::use_def] module for more details. //! //! This module defines how narrowing constraints are stored internally. //! //! A _narrowing constraint_ consists of a list of _predicates_, each of which corresponds with an //! expression in the source file (represented by a [`Predicate`]). We need to support the //! following operations on narrowing constraints: //! //! - Adding a new predicate to an existing constraint //! - Merging two constraints together, which produces the _intersection_ of their predicates //! - Iterating through the predicates in a constraint //! //! In particular, note that we do not need random access to the predicates in a constraint. That //! means that we can use a simple [_sorted association list_][crate::list] as our data structure. //! That lets us use a single 32-bit integer to store each narrowing constraint, no matter how many //! predicates it contains. It also makes merging two narrowing constraints fast, since alists //! support fast intersection. //! //! Because we visit the contents of each scope in source-file order, and assign scoped IDs in //! source-file order, that means that we will tend to visit narrowing constraints in order by //! their predicate IDs. This is exactly how to get the best performance from our alist //! implementation. //! //! [`Predicate`]: crate::semantic_index::predicate::Predicate use crate::list::{List, ListBuilder, ListSetReverseIterator, ListStorage}; use crate::semantic_index::ast_ids::ScopedUseId; use crate::semantic_index::predicate::ScopedPredicateId; use crate::semantic_index::scope::FileScopeId; /// A narrowing constraint associated with a live binding. /// /// A constraint is a list of [`Predicate`]s that each constrain the type of the binding's place. /// /// [`Predicate`]: crate::semantic_index::predicate::Predicate pub(crate) type ScopedNarrowingConstraint = List<ScopedNarrowingConstraintPredicate>; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum ConstraintKey { NarrowingConstraint(ScopedNarrowingConstraint), NestedScope(FileScopeId), UseId(ScopedUseId), } /// One of the [`Predicate`]s in a narrowing constraint, which constraints the type of the /// binding's place. /// /// Note that those [`Predicate`]s are stored in [their own per-scope /// arena][crate::semantic_index::predicate::Predicates], so internally we use a /// [`ScopedPredicateId`] to refer to the underlying predicate. /// /// [`Predicate`]: crate::semantic_index::predicate::Predicate #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, get_size2::GetSize)] pub(crate) struct ScopedNarrowingConstraintPredicate(ScopedPredicateId); impl ScopedNarrowingConstraintPredicate { /// Returns (the ID of) the `Predicate` pub(crate) fn predicate(self) -> ScopedPredicateId { self.0 } } impl From<ScopedPredicateId> for ScopedNarrowingConstraintPredicate { fn from(predicate: ScopedPredicateId) -> ScopedNarrowingConstraintPredicate { ScopedNarrowingConstraintPredicate(predicate) } } /// A collection of narrowing constraints for a given scope. #[derive(Debug, Eq, PartialEq, get_size2::GetSize)] pub(crate) struct NarrowingConstraints { lists: ListStorage<ScopedNarrowingConstraintPredicate>, } // Building constraints // -------------------- /// A builder for creating narrowing constraints. #[derive(Debug, Default, Eq, PartialEq)] pub(crate) struct NarrowingConstraintsBuilder { lists: ListBuilder<ScopedNarrowingConstraintPredicate>, } impl NarrowingConstraintsBuilder { pub(crate) fn build(self) -> NarrowingConstraints { NarrowingConstraints { lists: self.lists.build(), } } /// Adds a predicate to an existing narrowing constraint. pub(crate) fn add_predicate_to_constraint( &mut self, constraint: ScopedNarrowingConstraint, predicate: ScopedNarrowingConstraintPredicate, ) -> ScopedNarrowingConstraint { self.lists.insert(constraint, predicate) } /// Returns the intersection of two narrowing constraints. The result contains the predicates /// that appear in both inputs. pub(crate) fn intersect_constraints( &mut self, a: ScopedNarrowingConstraint, b: ScopedNarrowingConstraint, ) -> ScopedNarrowingConstraint { self.lists.intersect(a, b) } } // Iteration // --------- pub(crate) type NarrowingConstraintsIterator<'a> = std::iter::Copied<ListSetReverseIterator<'a, ScopedNarrowingConstraintPredicate>>; impl NarrowingConstraints { /// Iterates over the predicates in a narrowing constraint. pub(crate) fn iter_predicates( &self, set: ScopedNarrowingConstraint, ) -> NarrowingConstraintsIterator<'_> { self.lists.iter_set_reverse(set).copied() } } // Test support // ------------ #[cfg(test)] mod tests { use super::*; impl ScopedNarrowingConstraintPredicate { pub(crate) fn as_u32(self) -> u32 { self.0.as_u32() } } impl NarrowingConstraintsBuilder { pub(crate) fn iter_predicates( &self, set: ScopedNarrowingConstraint, ) -> NarrowingConstraintsIterator<'_> { self.lists.iter_set_reverse(set).copied() } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/expression.rs
crates/ty_python_semantic/src/semantic_index/expression.rs
use crate::ast_node_ref::AstNodeRef; use crate::db::Db; use crate::semantic_index::scope::{FileScopeId, ScopeId}; use ruff_db::files::File; use ruff_db::parsed::ParsedModuleRef; use ruff_python_ast as ast; use salsa; /// Whether or not this expression should be inferred as a normal expression or /// a type expression. For example, in `self.x: <annotation> = <value>`, the /// `<annotation>` is inferred as a type expression, while `<value>` is inferred /// as a normal expression. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, get_size2::GetSize)] pub(crate) enum ExpressionKind { Normal, TypeExpression, } /// An independently type-inferable expression. /// /// Includes constraint expressions (e.g. if tests) and the RHS of an unpacking assignment. /// /// ## Module-local type /// This type should not be used as part of any cross-module API because /// it holds a reference to the AST node. Range-offset changes /// then propagate through all usages, and deserialization requires /// reparsing the entire module. /// /// E.g. don't use this type in: /// /// * a return type of a cross-module query /// * a field of a type that is a return type of a cross-module query /// * an argument of a cross-module query #[salsa::tracked(debug, heap_size=ruff_memory_usage::heap_size)] pub(crate) struct Expression<'db> { /// The file in which the expression occurs. pub(crate) file: File, /// The scope in which the expression occurs. pub(crate) file_scope: FileScopeId, /// The expression node. #[no_eq] #[tracked] #[returns(ref)] pub(crate) _node_ref: AstNodeRef<ast::Expr>, /// An assignment statement, if this expression is immediately used as the rhs of that /// assignment. /// /// (Note that this is the _immediately_ containing assignment — if a complex expression is /// assigned to some target, only the outermost expression node has this set. The inner /// expressions are used to build up the assignment result, and are not "immediately assigned" /// to the target, and so have `None` for this field.) #[no_eq] #[tracked] pub(crate) assigned_to: Option<AstNodeRef<ast::StmtAssign>>, /// Should this expression be inferred as a normal expression or a type expression? pub(crate) kind: ExpressionKind, } // The Salsa heap is tracked separately. impl get_size2::GetSize for Expression<'_> {} impl<'db> Expression<'db> { pub(crate) fn node_ref<'ast>( self, db: &'db dyn Db, parsed: &'ast ParsedModuleRef, ) -> &'ast ast::Expr { self._node_ref(db).node(parsed) } pub(crate) fn scope(self, db: &'db dyn Db) -> ScopeId<'db> { self.file_scope(db).to_scope_id(db, self.file(db)) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/scope.rs
crates/ty_python_semantic/src/semantic_index/scope.rs
use std::ops::Range; use ruff_db::{files::File, parsed::ParsedModuleRef}; use ruff_index::newtype_index; use ruff_python_ast as ast; use crate::{ Db, ast_node_ref::AstNodeRef, node_key::NodeKey, semantic_index::{ SemanticIndex, reachability_constraints::ScopedReachabilityConstraintId, semantic_index, }, types::{GenericContext, binding_type, infer_definition_types}, }; /// A cross-module identifier of a scope that can be used as a salsa query parameter. #[salsa::tracked(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(PartialOrd, Ord)] pub struct ScopeId<'db> { pub file: File, pub file_scope_id: FileScopeId, } // The Salsa heap is tracked separately. impl get_size2::GetSize for ScopeId<'_> {} impl<'db> ScopeId<'db> { pub(crate) fn is_annotation(self, db: &'db dyn Db) -> bool { self.node(db).scope_kind().is_annotation() } pub(crate) fn node(self, db: &dyn Db) -> &NodeWithScopeKind { self.scope(db).node() } pub(crate) fn scope(self, db: &dyn Db) -> &Scope { semantic_index(db, self.file(db)).scope(self.file_scope_id(db)) } #[cfg(test)] pub(crate) fn name<'ast>(self, db: &'db dyn Db, module: &'ast ParsedModuleRef) -> &'ast str { match self.node(db) { NodeWithScopeKind::Module => "<module>", NodeWithScopeKind::Class(class) | NodeWithScopeKind::ClassTypeParameters(class) => { class.node(module).name.as_str() } NodeWithScopeKind::Function(function) | NodeWithScopeKind::FunctionTypeParameters(function) => { function.node(module).name.as_str() } NodeWithScopeKind::TypeAlias(type_alias) | NodeWithScopeKind::TypeAliasTypeParameters(type_alias) => type_alias .node(module) .name .as_name_expr() .map(|name| name.id.as_str()) .unwrap_or("<type alias>"), NodeWithScopeKind::Lambda(_) => "<lambda>", NodeWithScopeKind::ListComprehension(_) => "<listcomp>", NodeWithScopeKind::SetComprehension(_) => "<setcomp>", NodeWithScopeKind::DictComprehension(_) => "<dictcomp>", NodeWithScopeKind::GeneratorExpression(_) => "<generator>", } } } /// ID that uniquely identifies a scope inside of a module. #[newtype_index] #[derive(salsa::Update, get_size2::GetSize)] pub struct FileScopeId; impl FileScopeId { /// Returns the scope id of the module-global scope. pub fn global() -> Self { FileScopeId::from_u32(0) } pub fn is_global(self) -> bool { self == FileScopeId::global() } pub fn to_scope_id(self, db: &dyn Db, file: File) -> ScopeId<'_> { let index = semantic_index(db, file); index.scope_ids_by_scope[self] } pub(crate) fn is_generator_function(self, index: &SemanticIndex) -> bool { index.generator_functions.contains(&self) } } #[derive(Debug, salsa::Update, get_size2::GetSize)] pub(crate) struct Scope { /// The parent scope, if any. parent: Option<FileScopeId>, /// The node that introduces this scope. node: NodeWithScopeKind, /// The range of [`FileScopeId`]s that are descendants of this scope. descendants: Range<FileScopeId>, /// The constraint that determines the reachability of this scope. reachability: ScopedReachabilityConstraintId, /// Whether this scope is defined inside an `if TYPE_CHECKING:` block. in_type_checking_block: bool, } impl Scope { pub(super) fn new( parent: Option<FileScopeId>, node: NodeWithScopeKind, descendants: Range<FileScopeId>, reachability: ScopedReachabilityConstraintId, in_type_checking_block: bool, ) -> Self { Scope { parent, node, descendants, reachability, in_type_checking_block, } } pub(crate) fn parent(&self) -> Option<FileScopeId> { self.parent } pub(crate) fn node(&self) -> &NodeWithScopeKind { &self.node } pub(crate) fn kind(&self) -> ScopeKind { self.node().scope_kind() } pub(crate) fn visibility(&self) -> ScopeVisibility { self.kind().visibility() } pub(crate) fn descendants(&self) -> Range<FileScopeId> { self.descendants.clone() } pub(super) fn extend_descendants(&mut self, children_end: FileScopeId) { self.descendants = self.descendants.start..children_end; } pub(crate) fn is_eager(&self) -> bool { self.kind().is_eager() } pub(crate) fn reachability(&self) -> ScopedReachabilityConstraintId { self.reachability } pub(crate) fn in_type_checking_block(&self) -> bool { self.in_type_checking_block } } #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, get_size2::GetSize)] pub(crate) enum ScopeVisibility { /// The scope is private (e.g. function, type alias, comprehension scope). Private, /// The scope is public (e.g. module, class scope). Public, } impl ScopeVisibility { pub(crate) const fn is_public(self) -> bool { matches!(self, ScopeVisibility::Public) } pub(crate) const fn is_private(self) -> bool { matches!(self, ScopeVisibility::Private) } } #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, get_size2::GetSize)] pub(crate) enum ScopeLaziness { /// The scope is evaluated lazily (e.g. function, type alias scope). Lazy, /// The scope is evaluated eagerly (e.g. module, class, comprehension scope). Eager, } impl ScopeLaziness { pub(crate) const fn is_eager(self) -> bool { matches!(self, ScopeLaziness::Eager) } pub(crate) const fn is_lazy(self) -> bool { matches!(self, ScopeLaziness::Lazy) } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum ScopeKind { Module, TypeParams, Class, Function, Lambda, Comprehension, TypeAlias, } impl ScopeKind { pub(crate) const fn is_eager(self) -> bool { self.laziness().is_eager() } pub(crate) const fn laziness(self) -> ScopeLaziness { match self { ScopeKind::Module | ScopeKind::Class | ScopeKind::Comprehension | ScopeKind::TypeParams => ScopeLaziness::Eager, ScopeKind::Function | ScopeKind::Lambda | ScopeKind::TypeAlias => ScopeLaziness::Lazy, } } pub(crate) const fn visibility(self) -> ScopeVisibility { match self { ScopeKind::Module | ScopeKind::Class => ScopeVisibility::Public, ScopeKind::TypeParams | ScopeKind::TypeAlias | ScopeKind::Function | ScopeKind::Lambda | ScopeKind::Comprehension => ScopeVisibility::Private, } } pub(crate) const fn is_function_like(self) -> bool { // Type parameter scopes behave like function scopes in terms of name resolution; CPython // symbol table also uses the term "function-like" for these scopes. matches!( self, ScopeKind::TypeParams | ScopeKind::Function | ScopeKind::Lambda | ScopeKind::TypeAlias | ScopeKind::Comprehension ) } pub(crate) const fn is_class(self) -> bool { matches!(self, ScopeKind::Class) } pub(crate) const fn is_module(self) -> bool { matches!(self, ScopeKind::Module) } pub(crate) const fn is_annotation(self) -> bool { matches!(self, ScopeKind::TypeParams | ScopeKind::TypeAlias) } pub(crate) const fn is_non_lambda_function(self) -> bool { matches!(self, ScopeKind::Function) } } /// Reference to a node that introduces a new scope. #[derive(Copy, Clone, Debug)] pub(crate) enum NodeWithScopeRef<'a> { Module, Class(&'a ast::StmtClassDef), Function(&'a ast::StmtFunctionDef), Lambda(&'a ast::ExprLambda), FunctionTypeParameters(&'a ast::StmtFunctionDef), ClassTypeParameters(&'a ast::StmtClassDef), TypeAlias(&'a ast::StmtTypeAlias), TypeAliasTypeParameters(&'a ast::StmtTypeAlias), ListComprehension(&'a ast::ExprListComp), SetComprehension(&'a ast::ExprSetComp), DictComprehension(&'a ast::ExprDictComp), GeneratorExpression(&'a ast::ExprGenerator), } impl NodeWithScopeRef<'_> { /// Converts the unowned reference to an owned [`NodeWithScopeKind`]. /// /// Note that node wrapped by `self` must be a child of `module`. pub(super) fn to_kind(self, module: &ParsedModuleRef) -> NodeWithScopeKind { match self { NodeWithScopeRef::Module => NodeWithScopeKind::Module, NodeWithScopeRef::Class(class) => { NodeWithScopeKind::Class(AstNodeRef::new(module, class)) } NodeWithScopeRef::Function(function) => { NodeWithScopeKind::Function(AstNodeRef::new(module, function)) } NodeWithScopeRef::TypeAlias(type_alias) => { NodeWithScopeKind::TypeAlias(AstNodeRef::new(module, type_alias)) } NodeWithScopeRef::TypeAliasTypeParameters(type_alias) => { NodeWithScopeKind::TypeAliasTypeParameters(AstNodeRef::new(module, type_alias)) } NodeWithScopeRef::Lambda(lambda) => { NodeWithScopeKind::Lambda(AstNodeRef::new(module, lambda)) } NodeWithScopeRef::FunctionTypeParameters(function) => { NodeWithScopeKind::FunctionTypeParameters(AstNodeRef::new(module, function)) } NodeWithScopeRef::ClassTypeParameters(class) => { NodeWithScopeKind::ClassTypeParameters(AstNodeRef::new(module, class)) } NodeWithScopeRef::ListComprehension(comprehension) => { NodeWithScopeKind::ListComprehension(AstNodeRef::new(module, comprehension)) } NodeWithScopeRef::SetComprehension(comprehension) => { NodeWithScopeKind::SetComprehension(AstNodeRef::new(module, comprehension)) } NodeWithScopeRef::DictComprehension(comprehension) => { NodeWithScopeKind::DictComprehension(AstNodeRef::new(module, comprehension)) } NodeWithScopeRef::GeneratorExpression(generator) => { NodeWithScopeKind::GeneratorExpression(AstNodeRef::new(module, generator)) } } } pub(crate) fn node_key(self) -> NodeWithScopeKey { match self { NodeWithScopeRef::Module => NodeWithScopeKey::Module, NodeWithScopeRef::Class(class) => NodeWithScopeKey::Class(NodeKey::from_node(class)), NodeWithScopeRef::Function(function) => { NodeWithScopeKey::Function(NodeKey::from_node(function)) } NodeWithScopeRef::Lambda(lambda) => { NodeWithScopeKey::Lambda(NodeKey::from_node(lambda)) } NodeWithScopeRef::FunctionTypeParameters(function) => { NodeWithScopeKey::FunctionTypeParameters(NodeKey::from_node(function)) } NodeWithScopeRef::ClassTypeParameters(class) => { NodeWithScopeKey::ClassTypeParameters(NodeKey::from_node(class)) } NodeWithScopeRef::TypeAlias(type_alias) => { NodeWithScopeKey::TypeAlias(NodeKey::from_node(type_alias)) } NodeWithScopeRef::TypeAliasTypeParameters(type_alias) => { NodeWithScopeKey::TypeAliasTypeParameters(NodeKey::from_node(type_alias)) } NodeWithScopeRef::ListComprehension(comprehension) => { NodeWithScopeKey::ListComprehension(NodeKey::from_node(comprehension)) } NodeWithScopeRef::SetComprehension(comprehension) => { NodeWithScopeKey::SetComprehension(NodeKey::from_node(comprehension)) } NodeWithScopeRef::DictComprehension(comprehension) => { NodeWithScopeKey::DictComprehension(NodeKey::from_node(comprehension)) } NodeWithScopeRef::GeneratorExpression(generator) => { NodeWithScopeKey::GeneratorExpression(NodeKey::from_node(generator)) } } } } /// Node that introduces a new scope. #[derive(Clone, Debug, salsa::Update, get_size2::GetSize)] pub(crate) enum NodeWithScopeKind { Module, Class(AstNodeRef<ast::StmtClassDef>), ClassTypeParameters(AstNodeRef<ast::StmtClassDef>), Function(AstNodeRef<ast::StmtFunctionDef>), FunctionTypeParameters(AstNodeRef<ast::StmtFunctionDef>), TypeAliasTypeParameters(AstNodeRef<ast::StmtTypeAlias>), TypeAlias(AstNodeRef<ast::StmtTypeAlias>), Lambda(AstNodeRef<ast::ExprLambda>), ListComprehension(AstNodeRef<ast::ExprListComp>), SetComprehension(AstNodeRef<ast::ExprSetComp>), DictComprehension(AstNodeRef<ast::ExprDictComp>), GeneratorExpression(AstNodeRef<ast::ExprGenerator>), } impl NodeWithScopeKind { pub(crate) const fn scope_kind(&self) -> ScopeKind { match self { Self::Module => ScopeKind::Module, Self::Class(_) => ScopeKind::Class, Self::Function(_) => ScopeKind::Function, Self::Lambda(_) => ScopeKind::Lambda, Self::FunctionTypeParameters(_) | Self::ClassTypeParameters(_) | Self::TypeAliasTypeParameters(_) => ScopeKind::TypeParams, Self::TypeAlias(_) => ScopeKind::TypeAlias, Self::ListComprehension(_) | Self::SetComprehension(_) | Self::DictComprehension(_) | Self::GeneratorExpression(_) => ScopeKind::Comprehension, } } pub(crate) fn as_class(&self) -> Option<&AstNodeRef<ast::StmtClassDef>> { match self { Self::Class(class) => Some(class), _ => None, } } pub(crate) fn expect_class(&self) -> &AstNodeRef<ast::StmtClassDef> { self.as_class().expect("expected class") } pub(crate) fn as_function(&self) -> Option<&AstNodeRef<ast::StmtFunctionDef>> { match self { Self::Function(function) => Some(function), _ => None, } } pub(crate) fn expect_function(&self) -> &AstNodeRef<ast::StmtFunctionDef> { self.as_function().expect("expected function") } pub(crate) fn as_type_alias(&self) -> Option<&AstNodeRef<ast::StmtTypeAlias>> { match self { Self::TypeAlias(type_alias) => Some(type_alias), _ => None, } } pub(crate) fn expect_type_alias(&self) -> &AstNodeRef<ast::StmtTypeAlias> { self.as_type_alias().expect("expected type alias") } pub(crate) fn generic_context<'db>( &self, db: &'db dyn Db, index: &SemanticIndex<'db>, ) -> Option<GenericContext<'db>> { match self { NodeWithScopeKind::Class(class) => { let definition = index.expect_single_definition(class); binding_type(db, definition) .as_class_literal()? .generic_context(db) } NodeWithScopeKind::Function(function) => { let definition = index.expect_single_definition(function); infer_definition_types(db, definition) .undecorated_type() .expect("function should have undecorated type") .as_function_literal()? .last_definition_signature(db) .generic_context } NodeWithScopeKind::TypeAlias(type_alias) => { let definition = index.expect_single_definition(type_alias); binding_type(db, definition) .as_type_alias()? .as_pep_695_type_alias()? .generic_context(db) } _ => None, } } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, get_size2::GetSize)] pub(crate) enum NodeWithScopeKey { Module, Class(NodeKey), ClassTypeParameters(NodeKey), Function(NodeKey), FunctionTypeParameters(NodeKey), TypeAlias(NodeKey), TypeAliasTypeParameters(NodeKey), Lambda(NodeKey), ListComprehension(NodeKey), SetComprehension(NodeKey), DictComprehension(NodeKey), GeneratorExpression(NodeKey), }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/definition.rs
crates/ty_python_semantic/src/semantic_index/definition.rs
use std::ops::Deref; use ruff_db::files::{File, FileRange}; use ruff_db::parsed::{ParsedModuleRef, parsed_module}; use ruff_python_ast::find_node::covering_node; use ruff_python_ast::traversal::suite; use ruff_python_ast::{self as ast, AnyNodeRef, Expr}; use ruff_text_size::{Ranged, TextRange}; use crate::Db; use crate::ast_node_ref::AstNodeRef; use crate::node_key::NodeKey; use crate::semantic_index::place::ScopedPlaceId; use crate::semantic_index::scope::{FileScopeId, ScopeId}; use crate::semantic_index::symbol::ScopedSymbolId; use crate::unpack::{Unpack, UnpackPosition}; /// A definition of a place. /// /// ## ID stability /// The `Definition`'s ID is stable when the only field that change is its `kind` (AST node). /// /// The `Definition` changes when the `file`, `scope`, or `place` change. This can be /// because a new scope gets inserted before the `Definition` or a new place is inserted /// before this `Definition`. However, the ID can be considered stable and it is okay to use /// `Definition` in cross-module` salsa queries or as a field on other salsa tracked structs. /// /// # Ordering /// Ordering is based on the definition's salsa-assigned id and not on its values. /// The id may change between runs, or when the definition was garbage collected and recreated. #[salsa::tracked(debug, heap_size=ruff_memory_usage::heap_size)] #[derive(Ord, PartialOrd)] pub struct Definition<'db> { /// The file in which the definition occurs. pub file: File, /// The scope in which the definition occurs. pub(crate) file_scope: FileScopeId, /// The place ID of the definition. pub(crate) place: ScopedPlaceId, /// WARNING: Only access this field when doing type inference for the same /// file as where `Definition` is defined to avoid cross-file query dependencies. #[no_eq] #[returns(ref)] #[tracked] pub kind: DefinitionKind<'db>, /// This is a dedicated field to avoid accessing `kind` to compute this value. pub(crate) is_reexported: bool, } // The Salsa heap is tracked separately. impl get_size2::GetSize for Definition<'_> {} impl<'db> Definition<'db> { pub(crate) fn scope(self, db: &'db dyn Db) -> ScopeId<'db> { self.file_scope(db).to_scope_id(db, self.file(db)) } pub fn full_range(self, db: &'db dyn Db, module: &ParsedModuleRef) -> FileRange { FileRange::new(self.file(db), self.kind(db).full_range(module)) } pub fn focus_range(self, db: &'db dyn Db, module: &ParsedModuleRef) -> FileRange { FileRange::new(self.file(db), self.kind(db).target_range(module)) } /// Returns the name of the item being defined, if applicable. pub fn name(self, db: &'db dyn Db) -> Option<String> { let file = self.file(db); let module = parsed_module(db, file).load(db); let kind = self.kind(db); match kind { DefinitionKind::Function(def) => { let node = def.node(&module); Some(node.name.as_str().to_string()) } DefinitionKind::Class(def) => { let node = def.node(&module); Some(node.name.as_str().to_string()) } DefinitionKind::TypeAlias(def) => { let node = def.node(&module); Some( node.name .as_name_expr() .expect("type alias name should be a NameExpr") .id .as_str() .to_string(), ) } DefinitionKind::Assignment(assignment) => { let target_node = assignment.target.node(&module); target_node .as_name_expr() .map(|name_expr| name_expr.id.as_str().to_string()) } _ => None, } } /// Extract a docstring from this definition, if applicable. /// This method returns a docstring for function, class, and attribute definitions. /// The docstring is extracted from the first statement in the body if it's a string literal. pub fn docstring(self, db: &'db dyn Db) -> Option<String> { let file = self.file(db); let module = parsed_module(db, file).load(db); let kind = self.kind(db); match kind { DefinitionKind::Assignment(assign_def) => { let assign_node = assign_def.target(&module); attribute_docstring(&module, assign_node) .map(|docstring_expr| docstring_expr.value.to_str().to_owned()) } DefinitionKind::AnnotatedAssignment(assign_def) => { let assign_node = assign_def.target(&module); attribute_docstring(&module, assign_node) .map(|docstring_expr| docstring_expr.value.to_str().to_owned()) } DefinitionKind::Function(function_def) => { let function_node = function_def.node(&module); docstring_from_body(&function_node.body) .map(|docstring_expr| docstring_expr.value.to_str().to_owned()) } DefinitionKind::Class(class_def) => { let class_node = class_def.node(&module); docstring_from_body(&class_node.body) .map(|docstring_expr| docstring_expr.value.to_str().to_owned()) } _ => None, } } } /// Get the module-level docstring for the given file. pub(crate) fn module_docstring(db: &dyn Db, file: File) -> Option<String> { let module = parsed_module(db, file).load(db); docstring_from_body(module.suite()) .map(|docstring_expr| docstring_expr.value.to_str().to_owned()) } /// Extract a docstring from a function, module, or class body. fn docstring_from_body(body: &[ast::Stmt]) -> Option<&ast::ExprStringLiteral> { let stmt = body.first()?; // Require the docstring to be a standalone expression. let ast::Stmt::Expr(ast::StmtExpr { value, range: _, node_index: _, }) = stmt else { return None; }; // Only match string literals. value.as_string_literal_expr() } /// Extract a docstring from an attribute. /// /// This is a non-standardized but popular-and-supported-by-sphinx kind of docstring /// where you just place the docstring underneath an assignment to an attribute and /// that counts as docs. /// /// This is annoying to extract because we have a reference to (part of) an assignment statement /// and we need to find the statement *after it*, which is easy to say but not something the /// AST wants to encourage. fn attribute_docstring<'a>( module: &'a ParsedModuleRef, assign_lvalue: &Expr, ) -> Option<&'a ast::ExprStringLiteral> { // Find all the ancestors of the assign lvalue let covering_node = covering_node(module.syntax().into(), assign_lvalue.range()); // The assignment is the closest parent statement let assign = covering_node.find_first(AnyNodeRef::is_statement).ok()?; let parent = assign.parent()?; let assign_node = assign.node(); // The docs must be the next statement let parent_body = suite(assign_node, parent)?; let next_stmt = parent_body.next_sibling()?; // Require the docstring to be a standalone expression. let ast::Stmt::Expr(ast::StmtExpr { value, range: _, node_index: _, }) = next_stmt else { return None; }; // Only match string literals. value.as_string_literal_expr() } /// One or more [`Definition`]s. #[derive(Debug, Default, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub struct Definitions<'db> { definitions: smallvec::SmallVec<[Definition<'db>; 1]>, } impl<'db> Definitions<'db> { pub(crate) fn single(definition: Definition<'db>) -> Self { Self { definitions: smallvec::smallvec_inline![definition], } } pub(crate) fn push(&mut self, definition: Definition<'db>) { self.definitions.push(definition); } } impl<'db> Deref for Definitions<'db> { type Target = [Definition<'db>]; fn deref(&self) -> &Self::Target { &self.definitions } } impl<'a, 'db> IntoIterator for &'a Definitions<'db> { type Item = &'a Definition<'db>; type IntoIter = std::slice::Iter<'a, Definition<'db>>; fn into_iter(self) -> Self::IntoIter { self.definitions.iter() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(crate) enum DefinitionState<'db> { Defined(Definition<'db>), /// Represents the implicit "unbound"/"undeclared" definition of every place. Undefined, /// Represents a definition that has been deleted. /// This used when an attribute/subscript definition (such as `x.y = ...`, `x[0] = ...`) becomes obsolete due to a reassignment of the root place. Deleted, } impl<'db> DefinitionState<'db> { pub(crate) fn is_defined_and(self, f: impl Fn(Definition<'db>) -> bool) -> bool { matches!(self, DefinitionState::Defined(def) if f(def)) } pub(crate) fn is_undefined_or(self, f: impl Fn(Definition<'db>) -> bool) -> bool { matches!(self, DefinitionState::Undefined) || matches!(self, DefinitionState::Defined(def) if f(def)) } #[allow(unused)] pub(crate) fn definition(self) -> Option<Definition<'db>> { match self { DefinitionState::Defined(def) => Some(def), DefinitionState::Deleted | DefinitionState::Undefined => None, } } } #[derive(Copy, Clone, Debug)] pub(crate) enum DefinitionNodeRef<'ast, 'db> { Import(ImportDefinitionNodeRef<'ast>), ImportFrom(ImportFromDefinitionNodeRef<'ast>), ImportFromSubmodule(ImportFromSubmoduleDefinitionNodeRef<'ast>), ImportStar(StarImportDefinitionNodeRef<'ast>), For(ForStmtDefinitionNodeRef<'ast, 'db>), Function(&'ast ast::StmtFunctionDef), Class(&'ast ast::StmtClassDef), TypeAlias(&'ast ast::StmtTypeAlias), NamedExpression(&'ast ast::ExprNamed), Assignment(AssignmentDefinitionNodeRef<'ast, 'db>), AnnotatedAssignment(AnnotatedAssignmentDefinitionNodeRef<'ast>), AugmentedAssignment(&'ast ast::StmtAugAssign), Comprehension(ComprehensionDefinitionNodeRef<'ast, 'db>), VariadicPositionalParameter(&'ast ast::Parameter), VariadicKeywordParameter(&'ast ast::Parameter), Parameter(&'ast ast::ParameterWithDefault), WithItem(WithItemDefinitionNodeRef<'ast, 'db>), MatchPattern(MatchPatternDefinitionNodeRef<'ast>), ExceptHandler(ExceptHandlerDefinitionNodeRef<'ast>), TypeVar(&'ast ast::TypeParamTypeVar), ParamSpec(&'ast ast::TypeParamParamSpec), TypeVarTuple(&'ast ast::TypeParamTypeVarTuple), } impl<'ast> From<&'ast ast::StmtFunctionDef> for DefinitionNodeRef<'ast, '_> { fn from(node: &'ast ast::StmtFunctionDef) -> Self { Self::Function(node) } } impl<'ast> From<&'ast ast::StmtClassDef> for DefinitionNodeRef<'ast, '_> { fn from(node: &'ast ast::StmtClassDef) -> Self { Self::Class(node) } } impl<'ast> From<&'ast ast::StmtTypeAlias> for DefinitionNodeRef<'ast, '_> { fn from(node: &'ast ast::StmtTypeAlias) -> Self { Self::TypeAlias(node) } } impl<'ast> From<&'ast ast::ExprNamed> for DefinitionNodeRef<'ast, '_> { fn from(node: &'ast ast::ExprNamed) -> Self { Self::NamedExpression(node) } } impl<'ast> From<&'ast ast::StmtAugAssign> for DefinitionNodeRef<'ast, '_> { fn from(node: &'ast ast::StmtAugAssign) -> Self { Self::AugmentedAssignment(node) } } impl<'ast> From<&'ast ast::TypeParamTypeVar> for DefinitionNodeRef<'ast, '_> { fn from(value: &'ast ast::TypeParamTypeVar) -> Self { Self::TypeVar(value) } } impl<'ast> From<&'ast ast::TypeParamParamSpec> for DefinitionNodeRef<'ast, '_> { fn from(value: &'ast ast::TypeParamParamSpec) -> Self { Self::ParamSpec(value) } } impl<'ast> From<&'ast ast::TypeParamTypeVarTuple> for DefinitionNodeRef<'ast, '_> { fn from(value: &'ast ast::TypeParamTypeVarTuple) -> Self { Self::TypeVarTuple(value) } } impl<'ast> From<ImportDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> { fn from(node_ref: ImportDefinitionNodeRef<'ast>) -> Self { Self::Import(node_ref) } } impl<'ast> From<ImportFromDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> { fn from(node_ref: ImportFromDefinitionNodeRef<'ast>) -> Self { Self::ImportFrom(node_ref) } } impl<'ast> From<ImportFromSubmoduleDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> { fn from(node_ref: ImportFromSubmoduleDefinitionNodeRef<'ast>) -> Self { Self::ImportFromSubmodule(node_ref) } } impl<'ast, 'db> From<ForStmtDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> { fn from(value: ForStmtDefinitionNodeRef<'ast, 'db>) -> Self { Self::For(value) } } impl<'ast, 'db> From<AssignmentDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> { fn from(node_ref: AssignmentDefinitionNodeRef<'ast, 'db>) -> Self { Self::Assignment(node_ref) } } impl<'ast> From<AnnotatedAssignmentDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> { fn from(node_ref: AnnotatedAssignmentDefinitionNodeRef<'ast>) -> Self { Self::AnnotatedAssignment(node_ref) } } impl<'ast, 'db> From<WithItemDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> { fn from(node_ref: WithItemDefinitionNodeRef<'ast, 'db>) -> Self { Self::WithItem(node_ref) } } impl<'ast, 'db> From<ComprehensionDefinitionNodeRef<'ast, 'db>> for DefinitionNodeRef<'ast, 'db> { fn from(node: ComprehensionDefinitionNodeRef<'ast, 'db>) -> Self { Self::Comprehension(node) } } impl<'ast> From<&'ast ast::ParameterWithDefault> for DefinitionNodeRef<'ast, '_> { fn from(node: &'ast ast::ParameterWithDefault) -> Self { Self::Parameter(node) } } impl<'ast> From<MatchPatternDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> { fn from(node: MatchPatternDefinitionNodeRef<'ast>) -> Self { Self::MatchPattern(node) } } impl<'ast> From<StarImportDefinitionNodeRef<'ast>> for DefinitionNodeRef<'ast, '_> { fn from(node: StarImportDefinitionNodeRef<'ast>) -> Self { Self::ImportStar(node) } } #[derive(Copy, Clone, Debug)] pub(crate) struct ImportDefinitionNodeRef<'ast> { pub(crate) node: &'ast ast::StmtImport, pub(crate) alias_index: usize, pub(crate) is_reexported: bool, } #[derive(Copy, Clone, Debug)] pub(crate) struct StarImportDefinitionNodeRef<'ast> { pub(crate) node: &'ast ast::StmtImportFrom, pub(crate) symbol_id: ScopedSymbolId, } #[derive(Copy, Clone, Debug)] pub(crate) struct ImportFromDefinitionNodeRef<'ast> { pub(crate) node: &'ast ast::StmtImportFrom, pub(crate) alias_index: usize, pub(crate) is_reexported: bool, } #[derive(Copy, Clone, Debug)] pub(crate) struct ImportFromSubmoduleDefinitionNodeRef<'ast> { pub(crate) node: &'ast ast::StmtImportFrom, } #[derive(Copy, Clone, Debug)] pub(crate) struct AssignmentDefinitionNodeRef<'ast, 'db> { pub(crate) unpack: Option<(UnpackPosition, Unpack<'db>)>, pub(crate) value: &'ast ast::Expr, pub(crate) target: &'ast ast::Expr, } #[derive(Copy, Clone, Debug)] pub(crate) struct AnnotatedAssignmentDefinitionNodeRef<'ast> { pub(crate) node: &'ast ast::StmtAnnAssign, pub(crate) annotation: &'ast ast::Expr, pub(crate) value: Option<&'ast ast::Expr>, pub(crate) target: &'ast ast::Expr, } #[derive(Copy, Clone, Debug)] pub(crate) struct WithItemDefinitionNodeRef<'ast, 'db> { pub(crate) unpack: Option<(UnpackPosition, Unpack<'db>)>, pub(crate) context_expr: &'ast ast::Expr, pub(crate) target: &'ast ast::Expr, pub(crate) is_async: bool, } #[derive(Copy, Clone, Debug)] pub(crate) struct ForStmtDefinitionNodeRef<'ast, 'db> { pub(crate) unpack: Option<(UnpackPosition, Unpack<'db>)>, pub(crate) iterable: &'ast ast::Expr, pub(crate) target: &'ast ast::Expr, pub(crate) is_async: bool, } #[derive(Copy, Clone, Debug)] pub(crate) struct ExceptHandlerDefinitionNodeRef<'ast> { pub(crate) handler: &'ast ast::ExceptHandlerExceptHandler, pub(crate) is_star: bool, } #[derive(Copy, Clone, Debug)] pub(crate) struct ComprehensionDefinitionNodeRef<'ast, 'db> { pub(crate) unpack: Option<(UnpackPosition, Unpack<'db>)>, pub(crate) iterable: &'ast ast::Expr, pub(crate) target: &'ast ast::Expr, pub(crate) first: bool, pub(crate) is_async: bool, } #[derive(Copy, Clone, Debug)] pub(crate) struct MatchPatternDefinitionNodeRef<'ast> { /// The outermost pattern node in which the identifier being defined occurs. pub(crate) pattern: &'ast ast::Pattern, /// The identifier being defined. pub(crate) identifier: &'ast ast::Identifier, /// The index of the identifier in the pattern when visiting the `pattern` node in evaluation /// order. pub(crate) index: u32, } impl<'db> DefinitionNodeRef<'_, 'db> { pub(super) fn into_owned(self, parsed: &ParsedModuleRef) -> DefinitionKind<'db> { match self { DefinitionNodeRef::Import(ImportDefinitionNodeRef { node, alias_index, is_reexported, }) => DefinitionKind::Import(ImportDefinitionKind { node: AstNodeRef::new(parsed, node), alias_index, is_reexported, }), DefinitionNodeRef::ImportFrom(ImportFromDefinitionNodeRef { node, alias_index, is_reexported, }) => DefinitionKind::ImportFrom(ImportFromDefinitionKind { node: AstNodeRef::new(parsed, node), alias_index, is_reexported, }), DefinitionNodeRef::ImportFromSubmodule(ImportFromSubmoduleDefinitionNodeRef { node, }) => DefinitionKind::ImportFromSubmodule(ImportFromSubmoduleDefinitionKind { node: AstNodeRef::new(parsed, node), }), DefinitionNodeRef::ImportStar(star_import) => { let StarImportDefinitionNodeRef { node, symbol_id } = star_import; DefinitionKind::StarImport(StarImportDefinitionKind { node: AstNodeRef::new(parsed, node), symbol_id, }) } DefinitionNodeRef::Function(function) => { DefinitionKind::Function(AstNodeRef::new(parsed, function)) } DefinitionNodeRef::Class(class) => { DefinitionKind::Class(AstNodeRef::new(parsed, class)) } DefinitionNodeRef::TypeAlias(type_alias) => { DefinitionKind::TypeAlias(AstNodeRef::new(parsed, type_alias)) } DefinitionNodeRef::NamedExpression(named) => { DefinitionKind::NamedExpression(AstNodeRef::new(parsed, named)) } DefinitionNodeRef::Assignment(AssignmentDefinitionNodeRef { unpack, value, target, }) => DefinitionKind::Assignment(AssignmentDefinitionKind { target_kind: TargetKind::from(unpack), value: AstNodeRef::new(parsed, value), target: AstNodeRef::new(parsed, target), }), DefinitionNodeRef::AnnotatedAssignment(AnnotatedAssignmentDefinitionNodeRef { node: _, annotation, value, target, }) => DefinitionKind::AnnotatedAssignment(AnnotatedAssignmentDefinitionKind { target: AstNodeRef::new(parsed, target), annotation: AstNodeRef::new(parsed, annotation), value: value.map(|v| AstNodeRef::new(parsed, v)), }), DefinitionNodeRef::AugmentedAssignment(augmented_assignment) => { DefinitionKind::AugmentedAssignment(AstNodeRef::new(parsed, augmented_assignment)) } DefinitionNodeRef::For(ForStmtDefinitionNodeRef { unpack, iterable, target, is_async, }) => DefinitionKind::For(ForStmtDefinitionKind { target_kind: TargetKind::from(unpack), iterable: AstNodeRef::new(parsed, iterable), target: AstNodeRef::new(parsed, target), is_async, }), DefinitionNodeRef::Comprehension(ComprehensionDefinitionNodeRef { unpack, iterable, target, first, is_async, }) => DefinitionKind::Comprehension(ComprehensionDefinitionKind { target_kind: TargetKind::from(unpack), iterable: AstNodeRef::new(parsed, iterable), target: AstNodeRef::new(parsed, target), first, is_async, }), DefinitionNodeRef::VariadicPositionalParameter(parameter) => { DefinitionKind::VariadicPositionalParameter(AstNodeRef::new(parsed, parameter)) } DefinitionNodeRef::VariadicKeywordParameter(parameter) => { DefinitionKind::VariadicKeywordParameter(AstNodeRef::new(parsed, parameter)) } DefinitionNodeRef::Parameter(parameter) => { DefinitionKind::Parameter(AstNodeRef::new(parsed, parameter)) } DefinitionNodeRef::WithItem(WithItemDefinitionNodeRef { unpack, context_expr, target, is_async, }) => DefinitionKind::WithItem(WithItemDefinitionKind { target_kind: TargetKind::from(unpack), context_expr: AstNodeRef::new(parsed, context_expr), target: AstNodeRef::new(parsed, target), is_async, }), DefinitionNodeRef::MatchPattern(MatchPatternDefinitionNodeRef { pattern, identifier, index, }) => DefinitionKind::MatchPattern(MatchPatternDefinitionKind { pattern: AstNodeRef::new(parsed, pattern), identifier: AstNodeRef::new(parsed, identifier), index, }), DefinitionNodeRef::ExceptHandler(ExceptHandlerDefinitionNodeRef { handler, is_star, }) => DefinitionKind::ExceptHandler(ExceptHandlerDefinitionKind { handler: AstNodeRef::new(parsed, handler), is_star, }), DefinitionNodeRef::TypeVar(node) => { DefinitionKind::TypeVar(AstNodeRef::new(parsed, node)) } DefinitionNodeRef::ParamSpec(node) => { DefinitionKind::ParamSpec(AstNodeRef::new(parsed, node)) } DefinitionNodeRef::TypeVarTuple(node) => { DefinitionKind::TypeVarTuple(AstNodeRef::new(parsed, node)) } } } pub(super) fn key(self) -> DefinitionNodeKey { match self { Self::Import(ImportDefinitionNodeRef { node, alias_index, is_reexported: _, }) => (&node.names[alias_index]).into(), Self::ImportFrom(ImportFromDefinitionNodeRef { node, alias_index, is_reexported: _, }) => (&node.names[alias_index]).into(), Self::ImportFromSubmodule(ImportFromSubmoduleDefinitionNodeRef { node }) => node.into(), // INVARIANT: for an invalid-syntax statement such as `from foo import *, bar, *`, // we only create a `StarImportDefinitionKind` for the *first* `*` alias in the names list. Self::ImportStar(StarImportDefinitionNodeRef { node, symbol_id: _ }) => node .names .iter() .find(|alias| &alias.name == "*") .expect( "The `StmtImportFrom` node of a `StarImportDefinitionKind` instance \ should always have at least one `alias` with the name `*`.", ) .into(), Self::Function(node) => node.into(), Self::Class(node) => node.into(), Self::TypeAlias(node) => node.into(), Self::NamedExpression(node) => node.into(), Self::Assignment(AssignmentDefinitionNodeRef { value: _, unpack: _, target, }) => DefinitionNodeKey(NodeKey::from_node(target)), Self::AnnotatedAssignment(ann_assign) => ann_assign.node.into(), Self::AugmentedAssignment(node) => node.into(), Self::For(ForStmtDefinitionNodeRef { target, iterable: _, unpack: _, is_async: _, }) => DefinitionNodeKey(NodeKey::from_node(target)), Self::Comprehension(ComprehensionDefinitionNodeRef { target, .. }) => { DefinitionNodeKey(NodeKey::from_node(target)) } Self::VariadicPositionalParameter(node) => node.into(), Self::VariadicKeywordParameter(node) => node.into(), Self::Parameter(node) => node.into(), Self::WithItem(WithItemDefinitionNodeRef { context_expr: _, unpack: _, is_async: _, target, }) => DefinitionNodeKey(NodeKey::from_node(target)), Self::MatchPattern(MatchPatternDefinitionNodeRef { identifier, .. }) => { identifier.into() } Self::ExceptHandler(ExceptHandlerDefinitionNodeRef { handler, .. }) => handler.into(), Self::TypeVar(node) => node.into(), Self::ParamSpec(node) => node.into(), Self::TypeVarTuple(node) => node.into(), } } } #[derive(Clone, Copy, Debug)] pub(crate) enum DefinitionCategory { /// A Definition which binds a value to a name (e.g. `x = 1`). Binding, /// A Definition which declares the upper-bound of acceptable types for this name (`x: int`). Declaration, /// A Definition which both declares a type and binds a value (e.g. `x: int = 1`). DeclarationAndBinding, } impl DefinitionCategory { /// True if this definition establishes a "declared type" for the place. /// /// If so, any assignments reached by this definition are in error if they assign a value of a /// type not assignable to the declared type. /// /// Annotations establish a declared type. So do function and class definitions, and imports. pub(crate) fn is_declaration(self) -> bool { matches!( self, DefinitionCategory::Declaration | DefinitionCategory::DeclarationAndBinding ) } /// True if this definition assigns a value to the place. /// /// False only for annotated assignments without a RHS. pub(crate) fn is_binding(self) -> bool { matches!( self, DefinitionCategory::Binding | DefinitionCategory::DeclarationAndBinding ) } } /// The kind of a definition. /// /// ## Usage in salsa tracked structs /// /// [`DefinitionKind`] fields in salsa tracked structs should be tracked (attributed with `#[tracked]`) /// because the kind is a thin wrapper around [`AstNodeRef`]. See the [`AstNodeRef`] documentation /// for an in-depth explanation of why this is necessary. #[derive(Clone, Debug, get_size2::GetSize)] pub enum DefinitionKind<'db> { Import(ImportDefinitionKind), ImportFrom(ImportFromDefinitionKind), ImportFromSubmodule(ImportFromSubmoduleDefinitionKind), StarImport(StarImportDefinitionKind), Function(AstNodeRef<ast::StmtFunctionDef>), Class(AstNodeRef<ast::StmtClassDef>), TypeAlias(AstNodeRef<ast::StmtTypeAlias>), NamedExpression(AstNodeRef<ast::ExprNamed>), Assignment(AssignmentDefinitionKind<'db>), AnnotatedAssignment(AnnotatedAssignmentDefinitionKind), AugmentedAssignment(AstNodeRef<ast::StmtAugAssign>), For(ForStmtDefinitionKind<'db>), Comprehension(ComprehensionDefinitionKind<'db>), VariadicPositionalParameter(AstNodeRef<ast::Parameter>), VariadicKeywordParameter(AstNodeRef<ast::Parameter>), Parameter(AstNodeRef<ast::ParameterWithDefault>), WithItem(WithItemDefinitionKind<'db>), MatchPattern(MatchPatternDefinitionKind), ExceptHandler(ExceptHandlerDefinitionKind), TypeVar(AstNodeRef<ast::TypeParamTypeVar>), ParamSpec(AstNodeRef<ast::TypeParamParamSpec>), TypeVarTuple(AstNodeRef<ast::TypeParamTypeVarTuple>), } impl DefinitionKind<'_> { pub(crate) fn is_reexported(&self) -> bool { match self { DefinitionKind::Import(import) => import.is_reexported(), DefinitionKind::ImportFrom(import) => import.is_reexported(), DefinitionKind::ImportFromSubmodule(_) => true, _ => true, } } pub(crate) const fn as_star_import(&self) -> Option<&StarImportDefinitionKind> { match self { DefinitionKind::StarImport(import) => Some(import), _ => None, } } pub(crate) const fn as_class(&self) -> Option<&AstNodeRef<ast::StmtClassDef>> { match self { DefinitionKind::Class(class) => Some(class), _ => None, } } pub(crate) fn is_import(&self) -> bool { matches!( self, DefinitionKind::Import(_) | DefinitionKind::ImportFrom(_) | DefinitionKind::StarImport(_) | DefinitionKind::ImportFromSubmodule(_) ) } pub(crate) const fn is_unannotated_assignment(&self) -> bool { matches!(self, DefinitionKind::Assignment(_)) } pub(crate) const fn is_function_def(&self) -> bool { matches!(self, DefinitionKind::Function(_)) } /// Returns the [`TextRange`] of the definition target. /// /// A definition target would mainly be the node representing the place being defined i.e., /// [`ast::ExprName`], [`ast::Identifier`], [`ast::ExprAttribute`] or [`ast::ExprSubscript`] but could also be other nodes. pub(crate) fn target_range(&self, module: &ParsedModuleRef) -> TextRange { match self { DefinitionKind::Import(import) => import.alias(module).range(), DefinitionKind::ImportFrom(import) => import.alias(module).range(), DefinitionKind::ImportFromSubmodule(import) => import.import(module).range(), DefinitionKind::StarImport(import) => import.alias(module).range(), DefinitionKind::Function(function) => function.node(module).name.range(), DefinitionKind::Class(class) => class.node(module).name.range(), DefinitionKind::TypeAlias(type_alias) => type_alias.node(module).name.range(), DefinitionKind::NamedExpression(named) => named.node(module).target.range(), DefinitionKind::Assignment(assignment) => assignment.target.node(module).range(), DefinitionKind::AnnotatedAssignment(assign) => assign.target.node(module).range(), DefinitionKind::AugmentedAssignment(aug_assign) => { aug_assign.node(module).target.range() } DefinitionKind::For(for_stmt) => for_stmt.target.node(module).range(), DefinitionKind::Comprehension(comp) => comp.target(module).range(), DefinitionKind::VariadicPositionalParameter(parameter) => { parameter.node(module).name.range() } DefinitionKind::VariadicKeywordParameter(parameter) => { parameter.node(module).name.range() } DefinitionKind::Parameter(parameter) => parameter.node(module).parameter.name.range(), DefinitionKind::WithItem(with_item) => with_item.target.node(module).range(), DefinitionKind::MatchPattern(match_pattern) => { match_pattern.identifier.node(module).range() } DefinitionKind::ExceptHandler(handler) => handler.node(module).range(), DefinitionKind::TypeVar(type_var) => type_var.node(module).name.range(), DefinitionKind::ParamSpec(param_spec) => param_spec.node(module).name.range(), DefinitionKind::TypeVarTuple(type_var_tuple) => {
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/re_exports.rs
crates/ty_python_semantic/src/semantic_index/re_exports.rs
//! A visitor and query to find all global-scope symbols that are exported from a module //! when a wildcard import is used. //! //! For example, if a module `foo` contains `from bar import *`, which symbols from the global //! scope of `bar` are imported into the global namespace of `foo`? //! //! ## Why is this a separate query rather than a part of semantic indexing? //! //! This query is called by the [`super::SemanticIndexBuilder`] in order to add the correct //! [`super::Definition`]s to the semantic index of a module `foo` if `foo` has a //! `from bar import *` statement in its global namespace. Adding the correct `Definition`s to //! `foo`'s [`super::SemanticIndex`] requires knowing which symbols are exported from `bar`. //! //! If we determined the set of exported names during semantic indexing rather than as a //! separate query, we would need to complete semantic indexing on `bar` in order to //! complete analysis of the global namespace of `foo`. Since semantic indexing is somewhat //! expensive, this would be undesirable. A separate query allows us to avoid this issue. //! //! An additional concern is that the recursive nature of this query means that it must be able //! to handle cycles. We do this using fixpoint iteration; adding fixpoint iteration to the //! whole [`super::semantic_index()`] query would probably be prohibitively expensive. use ruff_db::{files::File, parsed::parsed_module}; use ruff_python_ast::{ self as ast, name::Name, visitor::{Visitor, walk_expr, walk_pattern, walk_stmt}, }; use rustc_hash::FxHashMap; use ty_module_resolver::{ModuleName, resolve_module}; use crate::Db; fn exports_cycle_initial(_db: &dyn Db, _id: salsa::Id, _file: File) -> Box<[Name]> { Box::default() } #[salsa::tracked(returns(deref), cycle_initial=exports_cycle_initial, heap_size=ruff_memory_usage::heap_size)] pub(super) fn exported_names(db: &dyn Db, file: File) -> Box<[Name]> { let module = parsed_module(db, file).load(db); let mut finder = ExportFinder::new(db, file); finder.visit_body(module.suite()); let mut exports = finder.resolve_exports(); // Sort the exports to ensure convergence regardless of hash map // or insertion order. See <https://github.com/astral-sh/ty/issues/444> exports.sort_unstable(); exports.into() } struct ExportFinder<'db> { db: &'db dyn Db, file: File, visiting_stub_file: bool, exports: FxHashMap<&'db Name, PossibleExportKind>, dunder_all: DunderAll, } impl<'db> ExportFinder<'db> { fn new(db: &'db dyn Db, file: File) -> Self { Self { db, file, visiting_stub_file: file.is_stub(db), exports: FxHashMap::default(), dunder_all: DunderAll::NotPresent, } } fn possibly_add_export(&mut self, export: &'db Name, kind: PossibleExportKind) { self.exports.insert(export, kind); if export == "__all__" { self.dunder_all = DunderAll::Present; } } fn resolve_exports(self) -> Vec<Name> { match self.dunder_all { DunderAll::NotPresent => self .exports .into_iter() .filter_map(|(name, kind)| { if kind == PossibleExportKind::StubImportWithoutRedundantAlias { return None; } if name.starts_with('_') { return None; } Some(name.clone()) }) .collect(), DunderAll::Present => self.exports.into_keys().cloned().collect(), } } } impl<'db> Visitor<'db> for ExportFinder<'db> { fn visit_alias(&mut self, alias: &'db ast::Alias) { let ast::Alias { name, asname, range: _, node_index: _, } = alias; let name = &name.id; let asname = asname.as_ref().map(|asname| &asname.id); // If the source is a stub, names defined by imports are only exported // if they use the explicit `foo as foo` syntax: let kind = if self.visiting_stub_file && asname.is_none_or(|asname| asname != name) { PossibleExportKind::StubImportWithoutRedundantAlias } else { PossibleExportKind::Normal }; self.possibly_add_export(asname.unwrap_or(name), kind); } fn visit_pattern(&mut self, pattern: &'db ast::Pattern) { match pattern { ast::Pattern::MatchAs(ast::PatternMatchAs { pattern, name, range: _, node_index: _, }) => { if let Some(pattern) = pattern { self.visit_pattern(pattern); } if let Some(name) = name { // Wildcard patterns (`case _:`) do not bind names. // Currently `self.possibly_add_export()` just ignores // all names with leading underscores, but this will not always be the case // (in the future we will want to support modules with `__all__ = ['_']`). if name != "_" { self.possibly_add_export(&name.id, PossibleExportKind::Normal); } } } ast::Pattern::MatchMapping(ast::PatternMatchMapping { patterns, rest, keys: _, range: _, node_index: _, }) => { for pattern in patterns { self.visit_pattern(pattern); } if let Some(rest) = rest { self.possibly_add_export(&rest.id, PossibleExportKind::Normal); } } ast::Pattern::MatchStar(ast::PatternMatchStar { name, range: _, node_index: _, }) => { if let Some(name) = name { self.possibly_add_export(&name.id, PossibleExportKind::Normal); } } ast::Pattern::MatchSequence(_) | ast::Pattern::MatchOr(_) | ast::Pattern::MatchClass(_) => { walk_pattern(self, pattern); } ast::Pattern::MatchSingleton(_) | ast::Pattern::MatchValue(_) => {} } } fn visit_stmt(&mut self, stmt: &'db ast::Stmt) { match stmt { ast::Stmt::ClassDef(ast::StmtClassDef { name, decorator_list, arguments, type_params: _, // We don't want to visit the type params of the class body: _, // We don't want to visit the body of the class range: _, node_index: _, }) => { self.possibly_add_export(&name.id, PossibleExportKind::Normal); for decorator in decorator_list { self.visit_decorator(decorator); } if let Some(arguments) = arguments { self.visit_arguments(arguments); } } ast::Stmt::FunctionDef(ast::StmtFunctionDef { name, decorator_list, parameters, returns, type_params: _, // We don't want to visit the type params of the function body: _, // We don't want to visit the body of the function range: _, node_index: _, is_async: _, }) => { self.possibly_add_export(&name.id, PossibleExportKind::Normal); for decorator in decorator_list { self.visit_decorator(decorator); } self.visit_parameters(parameters); if let Some(returns) = returns { self.visit_expr(returns); } } ast::Stmt::AnnAssign(ast::StmtAnnAssign { target, value, annotation, simple: _, range: _, node_index: _, }) => { if value.is_some() || self.visiting_stub_file { self.visit_expr(target); } self.visit_expr(annotation); if let Some(value) = value { self.visit_expr(value); } } ast::Stmt::TypeAlias(ast::StmtTypeAlias { name, type_params: _, value: _, range: _, node_index: _, }) => { self.visit_expr(name); // Neither walrus expressions nor statements cannot appear in type aliases; // no need to recursively visit the `value` or `type_params` } ast::Stmt::ImportFrom(node) => { let mut found_star = false; for name in &node.names { if &name.name.id == "*" { if !found_star { found_star = true; for export in ModuleName::from_import_statement(self.db, self.file, node) .ok() .and_then(|module_name| { resolve_module(self.db, self.file, &module_name) }) .iter() .flat_map(|module| { module .file(self.db) .map(|file| exported_names(self.db, file)) .unwrap_or_default() }) { self.possibly_add_export(export, PossibleExportKind::Normal); } } } else { self.visit_alias(name); } } } ast::Stmt::Import(_) | ast::Stmt::AugAssign(_) | ast::Stmt::While(_) | ast::Stmt::If(_) | ast::Stmt::With(_) | ast::Stmt::Assert(_) | ast::Stmt::Try(_) | ast::Stmt::Expr(_) | ast::Stmt::For(_) | ast::Stmt::Assign(_) | ast::Stmt::Match(_) => walk_stmt(self, stmt), ast::Stmt::Global(_) | ast::Stmt::Raise(_) | ast::Stmt::Return(_) | ast::Stmt::Break(_) | ast::Stmt::Continue(_) | ast::Stmt::IpyEscapeCommand(_) | ast::Stmt::Delete(_) | ast::Stmt::Nonlocal(_) | ast::Stmt::Pass(_) => {} } } fn visit_expr(&mut self, expr: &'db ast::Expr) { match expr { ast::Expr::Name(ast::ExprName { id, ctx, range: _, node_index: _, }) => { if ctx.is_store() { self.possibly_add_export(id, PossibleExportKind::Normal); } } ast::Expr::Lambda(_) | ast::Expr::BooleanLiteral(_) | ast::Expr::NoneLiteral(_) | ast::Expr::NumberLiteral(_) | ast::Expr::BytesLiteral(_) | ast::Expr::EllipsisLiteral(_) | ast::Expr::StringLiteral(_) => {} // Walrus definitions "leak" from comprehension scopes into the comprehension's // enclosing scope; they thus need special handling ast::Expr::SetComp(_) | ast::Expr::ListComp(_) | ast::Expr::Generator(_) | ast::Expr::DictComp(_) => { let mut walrus_finder = WalrusFinder { export_finder: self, }; walk_expr(&mut walrus_finder, expr); } ast::Expr::BoolOp(_) | ast::Expr::Named(_) | ast::Expr::BinOp(_) | ast::Expr::UnaryOp(_) | ast::Expr::If(_) | ast::Expr::Attribute(_) | ast::Expr::Subscript(_) | ast::Expr::Starred(_) | ast::Expr::Call(_) | ast::Expr::Compare(_) | ast::Expr::Yield(_) | ast::Expr::YieldFrom(_) | ast::Expr::FString(_) | ast::Expr::TString(_) | ast::Expr::Tuple(_) | ast::Expr::List(_) | ast::Expr::Slice(_) | ast::Expr::IpyEscapeCommand(_) | ast::Expr::Dict(_) | ast::Expr::Set(_) | ast::Expr::Await(_) => walk_expr(self, expr), } } } struct WalrusFinder<'a, 'db> { export_finder: &'a mut ExportFinder<'db>, } impl<'db> Visitor<'db> for WalrusFinder<'_, 'db> { fn visit_expr(&mut self, expr: &'db ast::Expr) { match expr { // It's important for us to short-circuit here for lambdas specifically, // as walruses cannot leak out of the body of a lambda function. ast::Expr::Lambda(_) | ast::Expr::BooleanLiteral(_) | ast::Expr::NoneLiteral(_) | ast::Expr::NumberLiteral(_) | ast::Expr::BytesLiteral(_) | ast::Expr::EllipsisLiteral(_) | ast::Expr::StringLiteral(_) | ast::Expr::Name(_) => {} ast::Expr::Named(ast::ExprNamed { target, value: _, range: _, node_index: _, }) => { if let ast::Expr::Name(ast::ExprName { id, ctx: ast::ExprContext::Store, range: _, node_index: _, }) = &**target { self.export_finder .possibly_add_export(id, PossibleExportKind::Normal); } } // We must recurse inside nested comprehensions, // as even a walrus inside a comprehension inside a comprehension in the global scope // will leak out into the global scope ast::Expr::DictComp(_) | ast::Expr::SetComp(_) | ast::Expr::ListComp(_) | ast::Expr::Generator(_) | ast::Expr::BoolOp(_) | ast::Expr::BinOp(_) | ast::Expr::UnaryOp(_) | ast::Expr::If(_) | ast::Expr::Attribute(_) | ast::Expr::Subscript(_) | ast::Expr::Starred(_) | ast::Expr::Call(_) | ast::Expr::Compare(_) | ast::Expr::Yield(_) | ast::Expr::YieldFrom(_) | ast::Expr::FString(_) | ast::Expr::TString(_) | ast::Expr::Tuple(_) | ast::Expr::List(_) | ast::Expr::Slice(_) | ast::Expr::IpyEscapeCommand(_) | ast::Expr::Dict(_) | ast::Expr::Set(_) | ast::Expr::Await(_) => walk_expr(self, expr), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum PossibleExportKind { Normal, StubImportWithoutRedundantAlias, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum DunderAll { NotPresent, Present, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/member.rs
crates/ty_python_semantic/src/semantic_index/member.rs
use bitflags::bitflags; use hashbrown::hash_table::Entry; use ruff_index::{IndexVec, newtype_index}; use ruff_python_ast::{self as ast, name::Name}; use ruff_text_size::{TextLen as _, TextRange, TextSize}; use rustc_hash::FxHasher; use smallvec::SmallVec; use std::hash::{Hash, Hasher as _}; use std::ops::{Deref, DerefMut}; /// A member access, e.g. `x.y` or `x[1]` or `x["foo"]`. #[derive(Clone, Debug, PartialEq, Eq, get_size2::GetSize)] pub(crate) struct Member { expression: MemberExpr, flags: MemberFlags, } impl Member { pub(crate) fn new(expression: MemberExpr) -> Self { Self { expression, flags: MemberFlags::empty(), } } /// Returns the left most part of the member expression, e.g. `x` in `x.y.z`. /// /// This is the symbol on which the member access is performed. pub(crate) fn symbol_name(&self) -> &str { self.expression.symbol_name() } pub(crate) fn expression(&self) -> &MemberExpr { &self.expression } /// Is the place given a value in its containing scope? pub(crate) const fn is_bound(&self) -> bool { self.flags.contains(MemberFlags::IS_BOUND) } /// Is the place declared in its containing scope? pub(crate) fn is_declared(&self) -> bool { self.flags.contains(MemberFlags::IS_DECLARED) } pub(super) fn mark_bound(&mut self) { self.insert_flags(MemberFlags::IS_BOUND); } pub(super) fn mark_declared(&mut self) { self.insert_flags(MemberFlags::IS_DECLARED); } pub(super) fn mark_instance_attribute(&mut self) { self.flags.insert(MemberFlags::IS_INSTANCE_ATTRIBUTE); } /// Is the place an instance attribute? pub(crate) fn is_instance_attribute(&self) -> bool { let is_instance_attribute = self.flags.contains(MemberFlags::IS_INSTANCE_ATTRIBUTE); if is_instance_attribute { debug_assert!(self.is_instance_attribute_candidate()); } is_instance_attribute } fn insert_flags(&mut self, flags: MemberFlags) { self.flags.insert(flags); } /// If the place expression has the form `<NAME>.<MEMBER>` /// (meaning it *may* be an instance attribute), /// return `Some(<MEMBER>)`. Else, return `None`. /// /// This method is internal to the semantic-index submodule. /// It *only* checks that the AST structure of the `Place` is /// correct. It does not check whether the `Place` actually occurred in /// a method context, or whether the `<NAME>` actually refers to the first /// parameter of the method (i.e. `self`). To answer those questions, /// use [`Self::as_instance_attribute`]. pub(super) fn as_instance_attribute_candidate(&self) -> Option<&str> { let mut segments = self.expression().segments(); let first_segment = segments.next()?; if first_segment.kind == SegmentKind::Attribute && segments.next().is_none() { Some(first_segment.text) } else { None } } /// Return `true` if the place expression has the form `<NAME>.<MEMBER>`, /// indicating that it *may* be an instance attribute if we are in a method context. /// /// This method is internal to the semantic-index submodule. /// It *only* checks that the AST structure of the `Place` is /// correct. It does not check whether the `Place` actually occurred in /// a method context, or whether the `<NAME>` actually refers to the first /// parameter of the method (i.e. `self`). To answer those questions, /// use [`Self::is_instance_attribute`]. pub(super) fn is_instance_attribute_candidate(&self) -> bool { self.as_instance_attribute_candidate().is_some() } /// Does the place expression have the form `self.{name}` (`self` is the first parameter of the method)? pub(super) fn is_instance_attribute_named(&self, name: &str) -> bool { self.as_instance_attribute() == Some(name) } /// Return `Some(<ATTRIBUTE>)` if the place expression is an instance attribute. pub(crate) fn as_instance_attribute(&self) -> Option<&str> { if self.is_instance_attribute() { debug_assert!(self.as_instance_attribute_candidate().is_some()); self.as_instance_attribute_candidate() } else { None } } } impl std::fmt::Display for Member { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.expression, f) } } bitflags! { /// Flags that can be queried to obtain information about a member in a given scope. /// /// See the doc-comment at the top of [`super::use_def`] for explanations of what it /// means for a member to be *bound* as opposed to *declared*. #[derive(Copy, Clone, Debug, Eq, PartialEq)] struct MemberFlags: u8 { const IS_BOUND = 1 << 0; const IS_DECLARED = 1 << 1; const IS_INSTANCE_ATTRIBUTE = 1 << 2; } } impl get_size2::GetSize for MemberFlags {} /// An expression accessing a member on a symbol named `symbol_name`, e.g. `x.y.z`. /// /// The parts after the symbol name are called segments, and they can be either: /// * An attribute access, e.g. `.y` in `x.y` /// * An integer-based subscript, e.g. `[1]` in `x[1]` /// * A string-based subscript, e.g. `["foo"]` in `x["foo"]` /// /// Uses a compact representation where the entire expression is stored as a single path. /// For example, `foo.bar[0]["baz"]` is stored as: /// - path: `foobar0baz` /// - segments: stores where each segment starts and its kind (attribute, int subscript, string subscript) /// /// The symbol name can be extracted from the path by taking the text up to the first segment's start offset. #[derive(Clone, Debug, PartialEq, Eq, get_size2::GetSize)] pub(crate) struct MemberExpr { /// The entire path as a single Name path: Name, /// Metadata for each segment (in forward order) segments: Segments, } impl MemberExpr { pub(super) fn try_from_expr(expression: ast::ExprRef<'_>) -> Option<Self> { fn visit(expr: ast::ExprRef) -> Option<(Name, SmallVec<[SegmentInfo; 8]>)> { use std::fmt::Write as _; match expr { ast::ExprRef::Name(name) => { Some((name.id.clone(), smallvec::SmallVec::new_const())) } ast::ExprRef::Attribute(attribute) => { let (mut path, mut segments) = visit(ast::ExprRef::from(&attribute.value))?; let start_offset = path.text_len(); let _ = write!(path, "{}", attribute.attr.id); segments.push(SegmentInfo::new(SegmentKind::Attribute, start_offset)); Some((path, segments)) } ast::ExprRef::Subscript(subscript) => { let (mut path, mut segments) = visit((&subscript.value).into())?; let start_offset = path.text_len(); match &*subscript.slice { ast::Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Int(index), .. }) => { let _ = write!(path, "{index}"); segments .push(SegmentInfo::new(SegmentKind::IntSubscript, start_offset)); } ast::Expr::StringLiteral(string) => { let _ = write!(path, "{}", string.value); segments .push(SegmentInfo::new(SegmentKind::StringSubscript, start_offset)); } _ => { return None; } } Some((path, segments)) } _ => None, } } let (path, segments) = visit(expression)?; if segments.is_empty() { None } else { Some(Self { path, segments: Segments::from_vec(segments), }) } } fn segment_infos(&self) -> impl Iterator<Item = SegmentInfo> + '_ { self.segments.iter() } fn segments(&self) -> impl Iterator<Item = Segment<'_>> + '_ { SegmentsIterator::new(self.path.as_str(), self.segment_infos()) } fn shrink_to_fit(&mut self) { self.path.shrink_to_fit(); } /// Returns the left most part of the member expression, e.g. `x` in `x.y.z`. /// /// This is the symbol on which the member access is performed. pub(crate) fn symbol_name(&self) -> &str { self.as_ref().symbol_name() } pub(super) fn num_segments(&self) -> usize { self.segments.len() } pub(crate) fn as_ref(&self) -> MemberExprRef<'_> { MemberExprRef { path: self.path.as_str(), segments: SegmentsRef::from(&self.segments), } } } impl std::fmt::Display for MemberExpr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.symbol_name())?; for segment in self.segments() { match segment.kind { SegmentKind::Attribute => write!(f, ".{}", segment.text)?, SegmentKind::IntSubscript => write!(f, "[{}]", segment.text)?, SegmentKind::StringSubscript => write!(f, "[\"{}\"]", segment.text)?, } } Ok(()) } } impl PartialEq<MemberExprRef<'_>> for MemberExpr { fn eq(&self, other: &MemberExprRef) -> bool { self.as_ref() == *other } } impl PartialEq<MemberExprRef<'_>> for &MemberExpr { fn eq(&self, other: &MemberExprRef) -> bool { self.as_ref() == *other } } impl PartialEq<MemberExpr> for MemberExprRef<'_> { fn eq(&self, other: &MemberExpr) -> bool { other == self } } impl PartialEq<&MemberExpr> for MemberExprRef<'_> { fn eq(&self, other: &&MemberExpr) -> bool { *other == self } } /// Reference to a member expression. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct MemberExprRef<'a> { path: &'a str, segments: SegmentsRef<'a>, } impl<'a> MemberExprRef<'a> { pub(super) fn symbol_name(&self) -> &'a str { let end = self .segments .iter() .next() .map(SegmentInfo::offset) .unwrap_or(self.path.text_len()); let range = TextRange::new(TextSize::default(), end); &self.path[range] } #[cfg(test)] fn segments(&self) -> impl Iterator<Item = Segment<'_>> + '_ { SegmentsIterator::new(self.path, self.segments.iter()) } pub(super) fn parent(&self) -> Option<MemberExprRef<'a>> { let parent_segments = self.segments.parent()?; // The removed segment is always the last one. Find its start offset. let last_segment = self.segments.iter().last()?; let path_end = last_segment.offset(); Some(MemberExprRef { path: &self.path[TextRange::new(TextSize::default(), path_end)], segments: parent_segments, }) } } impl<'a> From<&'a MemberExpr> for MemberExprRef<'a> { fn from(value: &'a MemberExpr) -> Self { value.as_ref() } } impl Hash for MemberExprRef<'_> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { // Path on its own isn't 100% unique, but it should avoid // most collisions and avoids iterating all segments. self.path.hash(state); } } /// Uniquely identifies a member in a scope. #[newtype_index] #[derive(get_size2::GetSize, salsa::Update)] pub struct ScopedMemberId; /// The members of a scope. Allows lookup by member path and [`ScopedMemberId`]. #[derive(Default, get_size2::GetSize)] pub(super) struct MemberTable { members: IndexVec<ScopedMemberId, Member>, /// Map from member path to its ID. /// /// Uses a hash table to avoid storing the path twice. map: hashbrown::HashTable<ScopedMemberId>, } impl MemberTable { /// Returns the member with the given ID. /// /// ## Panics /// If the ID is not valid for this table. #[track_caller] pub(crate) fn member(&self, id: ScopedMemberId) -> &Member { &self.members[id] } /// Returns a mutable reference to the member with the given ID. /// /// ## Panics /// If the ID is not valid for this table. #[track_caller] pub(super) fn member_mut(&mut self, id: ScopedMemberId) -> &mut Member { &mut self.members[id] } /// Returns an iterator over all members in the table. pub(crate) fn iter(&self) -> std::slice::Iter<'_, Member> { self.members.iter() } fn hash_member_expression_ref(member: &MemberExprRef) -> u64 { hash_single(member) } /// Returns the ID of the member with the given expression, if it exists. pub(crate) fn member_id<'a>( &self, member: impl Into<MemberExprRef<'a>>, ) -> Option<ScopedMemberId> { let member = member.into(); let hash = Self::hash_member_expression_ref(&member); self.map .find(hash, |id| self.members[*id].expression == member) .copied() } pub(crate) fn place_id_by_instance_attribute_name(&self, name: &str) -> Option<ScopedMemberId> { for (id, member) in self.members.iter_enumerated() { if member.is_instance_attribute_named(name) { return Some(id); } } None } } impl PartialEq for MemberTable { fn eq(&self, other: &Self) -> bool { // It's sufficient to compare the members as the map is only a reverse lookup. self.members == other.members } } impl Eq for MemberTable {} impl std::fmt::Debug for MemberTable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("MemberTable").field(&self.members).finish() } } #[derive(Debug, Default)] pub(super) struct MemberTableBuilder { table: MemberTable, } impl MemberTableBuilder { /// Adds a member to the table or updates the flags of an existing member if it already exists. /// /// Members are identified by their expression, which is hashed to find the entry in the table. pub(super) fn add(&mut self, mut member: Member) -> (ScopedMemberId, bool) { let member_ref = member.expression.as_ref(); let hash = MemberTable::hash_member_expression_ref(&member_ref); let entry = self.table.map.entry( hash, |id| self.table.members[*id].expression.as_ref() == member.expression.as_ref(), |id| { let ref_expr = self.table.members[*id].expression.as_ref(); MemberTable::hash_member_expression_ref(&ref_expr) }, ); match entry { Entry::Occupied(entry) => { let id = *entry.get(); if !member.flags.is_empty() { self.members[id].flags.insert(member.flags); } (id, false) } Entry::Vacant(entry) => { member.expression.shrink_to_fit(); let id = self.table.members.push(member); entry.insert(id); (id, true) } } } pub(super) fn build(self) -> MemberTable { let mut table = self.table; table.members.shrink_to_fit(); table.map.shrink_to_fit(|id| { let ref_expr = table.members[*id].expression.as_ref(); MemberTable::hash_member_expression_ref(&ref_expr) }); table } } impl Deref for MemberTableBuilder { type Target = MemberTable; fn deref(&self) -> &Self::Target { &self.table } } impl DerefMut for MemberTableBuilder { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.table } } /// Representation of segments that can be either inline or heap-allocated. /// /// Design choices: /// - Uses `Box<[SegmentInfo]>` instead of `ThinVec` because even with a `ThinVec`, the size of `Segments` is still 128 bytes. /// - Uses u64 for inline storage. That's the largest size without increasing the overall size of `Segments` and allows to encode up to 7 segments. #[derive(Clone, Debug, PartialEq, Eq, get_size2::GetSize)] enum Segments { /// Inline storage for up to 7 segments with 6-bit relative offsets (max 63 bytes per segment) Small(SmallSegments), /// Heap storage for expressions that don't fit inline Heap(Box<[SegmentInfo]>), } static_assertions::assert_eq_size!(SmallSegments, u64); #[cfg(target_pointer_width = "64")] static_assertions::assert_eq_size!(Segments, [u64; 2]); impl Segments { fn from_vec(segments: SmallVec<[SegmentInfo; 8]>) -> Self { debug_assert!( !segments.is_empty(), "Segments cannot be empty. A member without segments is a symbol" ); if let Some(small) = SmallSegments::try_from_slice(&segments) { Self::Small(small) } else { Self::Heap(segments.into_vec().into_boxed_slice()) } } fn len(&self) -> usize { match self { Self::Small(small) => small.len(), Self::Heap(segments) => segments.len(), } } fn iter(&self) -> impl Iterator<Item = SegmentInfo> + '_ { match self { Self::Small(small) => itertools::Either::Left(small.iter()), Self::Heap(heap) => itertools::Either::Right(heap.iter().copied()), } } } /// Segment metadata - packed into a single u32 /// Layout: [kind: 2 bits][offset: 30 bits] /// - Bits 0-1: `SegmentKind` (0=Attribute, 1=IntSubscript, 2=StringSubscript) /// - Bits 2-31: Absolute offset from start of path (up to 1,073,741,823 bytes) #[derive(Clone, Copy, PartialEq, Eq, Hash, get_size2::GetSize)] struct SegmentInfo(u32); const KIND_MASK: u32 = 0b11; const OFFSET_SHIFT: u32 = 2; const MAX_OFFSET: u32 = (1 << 30) - 1; // 2^30 - 1 impl SegmentInfo { const fn new(kind: SegmentKind, offset: TextSize) -> Self { assert!(offset.to_u32() < MAX_OFFSET); let value = (offset.to_u32() << OFFSET_SHIFT) | (kind as u32); Self(value) } const fn kind(self) -> SegmentKind { match self.0 & KIND_MASK { 0 => SegmentKind::Attribute, 1 => SegmentKind::IntSubscript, 2 => SegmentKind::StringSubscript, _ => panic!("Invalid SegmentKind bits"), } } const fn offset(self) -> TextSize { TextSize::new(self.0 >> OFFSET_SHIFT) } } impl std::fmt::Debug for SegmentInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SegmentInfo") .field("kind", &self.kind()) .field("offset", &self.offset()) .finish() } } struct Segment<'a> { kind: SegmentKind, text: &'a str, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, get_size2::GetSize)] #[repr(u8)] enum SegmentKind { Attribute = 0, IntSubscript = 1, StringSubscript = 2, } /// Iterator over segments that converts `SegmentInfo` to `Segment` with text slices. struct SegmentsIterator<'a, I> { path: &'a str, segment_infos: I, current: Option<SegmentInfo>, next: Option<SegmentInfo>, } impl<'a, I> SegmentsIterator<'a, I> where I: Iterator<Item = SegmentInfo>, { fn new(path: &'a str, mut segment_infos: I) -> Self { let current = segment_infos.next(); let next = segment_infos.next(); Self { path, segment_infos, current, next, } } } impl<'a, I> Iterator for SegmentsIterator<'a, I> where I: Iterator<Item = SegmentInfo>, { type Item = Segment<'a>; fn next(&mut self) -> Option<Self::Item> { let info = self.current.take()?; let end = self .next .map(SegmentInfo::offset) .unwrap_or(self.path.text_len()); self.current = self.next; self.next = self.segment_infos.next(); Some(Segment { kind: info.kind(), text: &self.path[TextRange::new(info.offset(), end)], }) } } const INLINE_COUNT_BITS: u32 = 3; const INLINE_COUNT_MASK: u64 = (1 << INLINE_COUNT_BITS) - 1; const INLINE_SEGMENT_BITS: u32 = 8; const INLINE_SEGMENT_MASK: u64 = (1 << INLINE_SEGMENT_BITS) - 1; const INLINE_KIND_BITS: u32 = 2; const INLINE_KIND_MASK: u64 = (1 << INLINE_KIND_BITS) - 1; const INLINE_PREV_LEN_BITS: u32 = 6; const INLINE_PREV_LEN_MASK: u64 = (1 << INLINE_PREV_LEN_BITS) - 1; const INLINE_MAX_SEGMENTS: usize = 7; const INLINE_MAX_RELATIVE_OFFSET: u32 = (1 << INLINE_PREV_LEN_BITS) - 1; // 63 /// Compact representation that can store up to 7 segments inline in a u64. /// /// Layout: /// - Bits 0-2: Number of segments minus 1 (0-6, representing 1-7 segments) /// - Bits 3-10: Segment 0 (2 bits kind + 6 bits relative offset, max 63 bytes) /// - Bits 11-18: Segment 1 (2 bits kind + 6 bits relative offset, max 63 bytes) /// - Bits 19-26: Segment 2 (2 bits kind + 6 bits relative offset, max 63 bytes) /// - Bits 27-34: Segment 3 (2 bits kind + 6 bits relative offset, max 63 bytes) /// - Bits 35-42: Segment 4 (2 bits kind + 6 bits relative offset, max 63 bytes) /// - Bits 43-50: Segment 5 (2 bits kind + 6 bits relative offset, max 63 bytes) /// - Bits 51-58: Segment 6 (2 bits kind + 6 bits relative offset, max 63 bytes) /// - Bits 59-63: Unused (5 bits) /// /// Constraints: /// - Maximum 7 segments (realistic limit for member access chains) /// - Maximum 63-byte relative offset per segment (sufficient for most identifiers) /// - Never empty (`segments.len()` >= 1) /// #[derive(Clone, Copy, PartialEq, Eq, get_size2::GetSize)] #[repr(transparent)] struct SmallSegments(u64); impl SmallSegments { fn try_from_slice(segments: &[SegmentInfo]) -> Option<Self> { if segments.is_empty() || segments.len() > INLINE_MAX_SEGMENTS { return None; } // Pack into inline representation // Store count minus 1 (since segments are never empty, range 0-6 represents 1-7 segments) let mut packed = (segments.len() - 1) as u64; let mut prev_offset = TextSize::new(0); for (i, segment) in segments.iter().enumerate() { // Compute relative offset on-the-fly let relative_offset = segment.offset() - prev_offset; if relative_offset > TextSize::from(INLINE_MAX_RELATIVE_OFFSET) { return None; } let kind = segment.kind() as u64; let relative_offset_val = u64::from(relative_offset.to_u32()); let segment_data = (relative_offset_val << INLINE_KIND_BITS) | kind; let shift = INLINE_COUNT_BITS + (u32::try_from(i).expect("i is bounded by INLINE_MAX_SEGMENTS") * INLINE_SEGMENT_BITS); packed |= segment_data << shift; prev_offset = segment.offset(); } Some(Self(packed)) } #[expect( clippy::cast_possible_truncation, reason = "INLINE_COUNT_MASK ensures value is at most 7" )] const fn len(self) -> usize { // Add 1 because we store count minus 1 ((self.0 & INLINE_COUNT_MASK) + 1) as usize } fn iter(self) -> SmallSegmentsInfoIterator { SmallSegmentsInfoIterator { segments: self, index: 0, next_offset: TextSize::new(0), } } /// Returns the parent member expression, e.g. `x.b` from `x.b.c`, or `None` if the parent is /// the `symbol` itself (e, g. parent of `x.a` is just `x`). const fn parent(self) -> Option<Self> { let len = self.len(); if len <= 1 { return None; } // Simply copy the packed value but update the count let mut new_packed = self.0; // Clear the count bits and set the new count (len - 2, since we store count - 1) new_packed &= !INLINE_COUNT_MASK; new_packed |= (len - 2) as u64; Some(Self(new_packed)) } } impl std::fmt::Debug for SmallSegments { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_list().entries(self.iter()).finish() } } struct SmallSegmentsInfoIterator { segments: SmallSegments, index: usize, next_offset: TextSize, } impl Iterator for SmallSegmentsInfoIterator { type Item = SegmentInfo; fn next(&mut self) -> Option<Self::Item> { let count = self.segments.len(); if self.index >= count { return None; } // Extract the relative offset and kind for the current segment let shift = INLINE_COUNT_BITS + (u32::try_from(self.index).expect("index is bounded by INLINE_MAX_SEGMENTS") * INLINE_SEGMENT_BITS); let segment_data = (self.segments.0 >> shift) & INLINE_SEGMENT_MASK; let kind = (segment_data & INLINE_KIND_MASK) as u8; let relative_offset = ((segment_data >> INLINE_KIND_BITS) & INLINE_PREV_LEN_MASK) as u32; // Update the running absolute offset self.next_offset += TextSize::new(relative_offset); let kind = match kind { 0 => SegmentKind::Attribute, 1 => SegmentKind::IntSubscript, 2 => SegmentKind::StringSubscript, _ => panic!("Invalid SegmentKind bits"), }; self.index += 1; Some(SegmentInfo::new(kind, self.next_offset)) } } /// Reference view of segments, can be either small (inline) or heap-allocated. #[derive(Clone, Copy, Debug)] enum SegmentsRef<'a> { Small(SmallSegments), Heap(&'a [SegmentInfo]), } impl<'a> SegmentsRef<'a> { fn len(&self) -> usize { match self { Self::Small(small) => small.len(), Self::Heap(segments) => segments.len(), } } fn iter(&self) -> impl Iterator<Item = SegmentInfo> + '_ { match self { Self::Small(small) => itertools::Either::Left(small.iter()), Self::Heap(heap) => itertools::Either::Right(heap.iter().copied()), } } /// Returns a parent view with one fewer segment, or None if <= 1 segment fn parent(&self) -> Option<SegmentsRef<'a>> { match self { Self::Small(small) => small.parent().map(SegmentsRef::Small), Self::Heap(segments) => { let len = segments.len(); if len <= 1 { None } else { Some(SegmentsRef::Heap(&segments[..len - 1])) } } } } } impl<'a> From<&'a Segments> for SegmentsRef<'a> { fn from(segments: &'a Segments) -> Self { match segments { Segments::Small(small) => SegmentsRef::Small(*small), Segments::Heap(heap) => SegmentsRef::Heap(heap), } } } impl PartialEq for SegmentsRef<'_> { fn eq(&self, other: &Self) -> bool { let len = self.len(); if len != other.len() { return false; } self.iter().eq(other.iter()) } } impl Eq for SegmentsRef<'_> {} /// Helper function to hash a single value and return the hash. fn hash_single<T: Hash>(value: &T) -> u64 { let mut hasher = FxHasher::default(); value.hash(&mut hasher); hasher.finish() } #[cfg(test)] mod tests { use super::*; #[test] fn test_member_expr_ref_hash_and_eq_small_heap() { // For expression: foo.bar[0]["baz"] // The path would be: "foobar0baz" (no dots or brackets in the path) let path = "foobar0baz"; let segments = vec![ SegmentInfo::new(SegmentKind::Attribute, TextSize::new(3)), // .bar at offset 3 SegmentInfo::new(SegmentKind::IntSubscript, TextSize::new(6)), // [0] at offset 6 SegmentInfo::new(SegmentKind::StringSubscript, TextSize::new(7)), // ["baz"] at offset 7 ]; // Create Small version. let small_segments = SmallSegments::try_from_slice(&segments).unwrap(); let member_ref_small = MemberExprRef { path, segments: SegmentsRef::Small(small_segments), }; // Create Heap version with the same data. let heap_segments: Box<[SegmentInfo]> = segments.into_boxed_slice(); let member_ref_heap = MemberExprRef { path, segments: SegmentsRef::Heap(&heap_segments), }; // Test hash equality (MemberExprRef only hashes the path). assert_eq!( hash_single(&member_ref_small), hash_single(&member_ref_heap) ); // Test equality in both directions. assert_eq!(member_ref_small, member_ref_heap); assert_eq!(member_ref_heap, member_ref_small); } #[test] fn test_member_expr_ref_different_segments() { // For expressions: foo.bar[0] vs foo.bar["0"] // Both have the same path "foobar0" but different segment types let path = "foobar0"; // First expression: foo.bar[0] let segments1 = vec![ SegmentInfo::new(SegmentKind::Attribute, TextSize::new(3)), // .bar at offset 3 SegmentInfo::new(SegmentKind::IntSubscript, TextSize::new(6)), // [0] at offset 6 ]; // Second expression: foo.bar["0"] let segments2 = vec![ SegmentInfo::new(SegmentKind::Attribute, TextSize::new(3)), // .bar at offset 3 SegmentInfo::new(SegmentKind::StringSubscript, TextSize::new(6)), // ["0"] at offset 6 ]; // Create MemberExprRef instances let small1 = SmallSegments::try_from_slice(&segments1).unwrap(); let member_ref1 = MemberExprRef { path, segments: SegmentsRef::Small(small1), }; let small2 = SmallSegments::try_from_slice(&segments2).unwrap(); let member_ref2 = MemberExprRef { path, segments: SegmentsRef::Small(small2), }; // Test inequality assert_ne!(member_ref1, member_ref2); assert_ne!(member_ref2, member_ref1); // Test hash equality (MemberExprRef only hashes the path, not segments) assert_eq!(hash_single(&member_ref1), hash_single(&member_ref2)); } #[test] fn test_member_expr_ref_parent() { use ruff_python_parser::parse_expression; // Parse a real Python expression let parsed = parse_expression(r#"foo.bar[0]["baz"]"#).unwrap(); let expr = parsed.expr(); // Convert to MemberExpr let member_expr = MemberExpr::try_from_expr(ast::ExprRef::from(expr)).unwrap(); let member_ref = member_expr.as_ref(); // Verify the initial state: foo.bar[0]["baz"] assert_eq!(member_ref.symbol_name(), "foo"); let segments: Vec<_> = member_ref.segments().map(|s| (s.kind, s.text)).collect(); assert_eq!( segments, vec![ (SegmentKind::Attribute, "bar"), (SegmentKind::IntSubscript, "0"), (SegmentKind::StringSubscript, "baz") ] ); // Test parent() removes the last segment ["baz"] -> foo.bar[0] let parent1 = member_ref.parent().unwrap(); assert_eq!(parent1.symbol_name(), "foo"); let parent1_segments: Vec<_> = parent1.segments().map(|s| (s.kind, s.text)).collect(); assert_eq!( parent1_segments, vec![ (SegmentKind::Attribute, "bar"), (SegmentKind::IntSubscript, "0") ] ); // Test parent of parent removes [0] -> foo.bar let parent2 = parent1.parent().unwrap(); assert_eq!(parent2.symbol_name(), "foo"); let parent2_segments: Vec<_> = parent2.segments().map(|s| (s.kind, s.text)).collect(); assert_eq!(parent2_segments, vec![(SegmentKind::Attribute, "bar")]); // Test parent of single segment is a symbol and not a member. let parent3 = parent2.parent(); assert!(parent3.is_none()); } #[test] fn test_member_expr_small_vs_heap_allocation() { use ruff_python_parser::parse_expression; // Test Small allocation: 7 segments (maximum for inline storage) // Create expression with exactly 7 segments: x.a.b.c.d.e.f.g let small_expr = parse_expression("x.a.b.c.d.e.f.g").unwrap();
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/ast_ids.rs
crates/ty_python_semantic/src/semantic_index/ast_ids.rs
use rustc_hash::FxHashMap; use ruff_index::newtype_index; use ruff_python_ast as ast; use ruff_python_ast::ExprRef; use crate::Db; use crate::semantic_index::ast_ids::node_key::ExpressionNodeKey; use crate::semantic_index::scope::ScopeId; use crate::semantic_index::semantic_index; /// AST ids for a single scope. /// /// The motivation for building the AST ids per scope isn't about reducing invalidation because /// the struct changes whenever the parsed AST changes. Instead, it's mainly that we can /// build the AST ids struct when building the place table and also keep the property that /// IDs of outer scopes are unaffected by changes in inner scopes. /// /// For example, we don't want that adding new statements to `foo` changes the statement id of `x = foo()` in: /// /// ```python /// def foo(): /// return 5 /// /// x = foo() /// ``` #[derive(Debug, salsa::Update, get_size2::GetSize)] pub(crate) struct AstIds { /// Maps expressions which "use" a place (that is, [`ast::ExprName`], [`ast::ExprAttribute`] or [`ast::ExprSubscript`]) to a use id. uses_map: FxHashMap<ExpressionNodeKey, ScopedUseId>, } impl AstIds { fn use_id(&self, key: impl Into<ExpressionNodeKey>) -> ScopedUseId { self.uses_map[&key.into()] } } fn ast_ids<'db>(db: &'db dyn Db, scope: ScopeId) -> &'db AstIds { semantic_index(db, scope.file(db)).ast_ids(scope.file_scope_id(db)) } /// Uniquely identifies a use of a name in a [`crate::semantic_index::FileScopeId`]. #[newtype_index] #[derive(get_size2::GetSize)] pub struct ScopedUseId; pub trait HasScopedUseId { /// Returns the ID that uniquely identifies the use in `scope`. fn scoped_use_id(&self, db: &dyn Db, scope: ScopeId) -> ScopedUseId; } impl HasScopedUseId for ast::Identifier { fn scoped_use_id(&self, db: &dyn Db, scope: ScopeId) -> ScopedUseId { let ast_ids = ast_ids(db, scope); ast_ids.use_id(self) } } impl HasScopedUseId for ast::ExprName { fn scoped_use_id(&self, db: &dyn Db, scope: ScopeId) -> ScopedUseId { let expression_ref = ExprRef::from(self); expression_ref.scoped_use_id(db, scope) } } impl HasScopedUseId for ast::ExprAttribute { fn scoped_use_id(&self, db: &dyn Db, scope: ScopeId) -> ScopedUseId { let expression_ref = ExprRef::from(self); expression_ref.scoped_use_id(db, scope) } } impl HasScopedUseId for ast::ExprSubscript { fn scoped_use_id(&self, db: &dyn Db, scope: ScopeId) -> ScopedUseId { let expression_ref = ExprRef::from(self); expression_ref.scoped_use_id(db, scope) } } impl HasScopedUseId for ast::ExprRef<'_> { fn scoped_use_id(&self, db: &dyn Db, scope: ScopeId) -> ScopedUseId { let ast_ids = ast_ids(db, scope); ast_ids.use_id(*self) } } #[derive(Debug, Default)] pub(super) struct AstIdsBuilder { uses_map: FxHashMap<ExpressionNodeKey, ScopedUseId>, } impl AstIdsBuilder { /// Adds `expr` to the use ids map and returns its id. pub(super) fn record_use(&mut self, expr: impl Into<ExpressionNodeKey>) -> ScopedUseId { let use_id = self.uses_map.len().into(); self.uses_map.insert(expr.into(), use_id); use_id } pub(super) fn finish(mut self) -> AstIds { self.uses_map.shrink_to_fit(); AstIds { uses_map: self.uses_map, } } } /// Node key that can only be constructed for expressions. pub(crate) mod node_key { use ruff_python_ast as ast; use crate::node_key::NodeKey; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, salsa::Update, get_size2::GetSize)] pub(crate) struct ExpressionNodeKey(NodeKey); impl From<ast::ExprRef<'_>> for ExpressionNodeKey { fn from(value: ast::ExprRef<'_>) -> Self { Self(NodeKey::from_node(value)) } } impl From<&ast::Expr> for ExpressionNodeKey { fn from(value: &ast::Expr) -> Self { Self(NodeKey::from_node(value)) } } impl From<&ast::ExprCall> for ExpressionNodeKey { fn from(value: &ast::ExprCall) -> Self { Self(NodeKey::from_node(value)) } } impl From<&ast::Identifier> for ExpressionNodeKey { fn from(value: &ast::Identifier) -> Self { Self(NodeKey::from_node(value)) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/symbol.rs
crates/ty_python_semantic/src/semantic_index/symbol.rs
use bitflags::bitflags; use hashbrown::hash_table::Entry; use ruff_index::{IndexVec, newtype_index}; use ruff_python_ast::name::Name; use rustc_hash::FxHasher; use std::hash::{Hash as _, Hasher as _}; use std::ops::{Deref, DerefMut}; /// Uniquely identifies a symbol in a given scope. #[newtype_index] #[derive(get_size2::GetSize)] pub struct ScopedSymbolId; /// A symbol in a given scope. #[derive(Debug, Clone, PartialEq, Eq, get_size2::GetSize, salsa::Update)] pub(crate) struct Symbol { name: Name, flags: SymbolFlags, } impl std::fmt::Display for Symbol { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.name.fmt(f) } } bitflags! { /// Flags that can be queried to obtain information about a symbol in a given scope. /// /// See the doc-comment at the top of [`super::use_def`] for explanations of what it /// means for a symbol to be *bound* as opposed to *declared*. #[derive(Copy, Clone, Debug, Eq, PartialEq)] struct SymbolFlags: u8 { const IS_USED = 1 << 0; const IS_BOUND = 1 << 1; const IS_DECLARED = 1 << 2; const MARKED_GLOBAL = 1 << 3; const MARKED_NONLOCAL = 1 << 4; /// true if the symbol is assigned more than once, or if it is assigned even though it is already in use const IS_REASSIGNED = 1 << 5; const IS_PARAMETER = 1 << 6; } } impl get_size2::GetSize for SymbolFlags {} impl Symbol { pub(crate) const fn new(name: Name) -> Self { Self { name, flags: SymbolFlags::empty(), } } pub(crate) fn name(&self) -> &Name { &self.name } /// Is the symbol used in its containing scope? pub(crate) fn is_used(&self) -> bool { self.flags.contains(SymbolFlags::IS_USED) } /// Is the symbol given a value in its containing scope? pub(crate) const fn is_bound(&self) -> bool { self.flags.contains(SymbolFlags::IS_BOUND) } /// Is the symbol declared in its containing scope? pub(crate) fn is_declared(&self) -> bool { self.flags.contains(SymbolFlags::IS_DECLARED) } /// Is the symbol `global` its containing scope? pub(crate) fn is_global(&self) -> bool { self.flags.contains(SymbolFlags::MARKED_GLOBAL) } /// Is the symbol `nonlocal` its containing scope? pub(crate) fn is_nonlocal(&self) -> bool { self.flags.contains(SymbolFlags::MARKED_NONLOCAL) } /// Is the symbol defined in this scope, vs referring to some enclosing scope? /// /// There are three common cases where a name refers to an enclosing scope: /// /// 1. explicit `global` variables /// 2. explicit `nonlocal` variables /// 3. "free" variables, which are used in a scope where they're neither bound nor declared /// /// Note that even if `is_local` is false, that doesn't necessarily mean there's an enclosing /// scope that resolves the reference. The symbol could be a built-in like `print`, or a name /// error at runtime, or a global variable added dynamically with e.g. `globals()`. /// /// XXX: There's a fourth case that we don't (can't) handle here. A variable that's bound or /// declared (anywhere) in a class body, but used before it's bound (at runtime), resolves /// (unbelievably) to the global scope. For example: /// ```py /// x = 42 /// def f(): /// x = 43 /// class Foo: /// print(x) # 42 (never 43) /// if secrets.randbelow(2): /// x = 44 /// print(x) # 42 or 44 /// ``` /// In cases like this, the resolution isn't known until runtime, and in fact it varies from /// one use to the next. The semantic index alone can't resolve this, and instead it's a /// special case in type inference (see `infer_place_load`). pub(crate) fn is_local(&self) -> bool { !self.is_global() && !self.is_nonlocal() && (self.is_bound() || self.is_declared()) } pub(crate) const fn is_reassigned(&self) -> bool { self.flags.contains(SymbolFlags::IS_REASSIGNED) } pub(crate) fn is_parameter(&self) -> bool { self.flags.contains(SymbolFlags::IS_PARAMETER) } pub(super) fn mark_global(&mut self) { self.insert_flags(SymbolFlags::MARKED_GLOBAL); } pub(super) fn mark_nonlocal(&mut self) { self.insert_flags(SymbolFlags::MARKED_NONLOCAL); } pub(super) fn mark_bound(&mut self) { if self.is_bound() || self.is_used() { self.insert_flags(SymbolFlags::IS_REASSIGNED); } self.insert_flags(SymbolFlags::IS_BOUND); } pub(super) fn mark_used(&mut self) { self.insert_flags(SymbolFlags::IS_USED); } pub(super) fn mark_declared(&mut self) { self.insert_flags(SymbolFlags::IS_DECLARED); } pub(super) fn mark_parameter(&mut self) { self.insert_flags(SymbolFlags::IS_PARAMETER); } fn insert_flags(&mut self, flags: SymbolFlags) { self.flags.insert(flags); } } /// The symbols of a given scope. /// /// Allows lookup by name and a symbol's ID. #[derive(Default, get_size2::GetSize)] pub(super) struct SymbolTable { symbols: IndexVec<ScopedSymbolId, Symbol>, /// Map from symbol name to its ID. /// /// Uses a hash table to avoid storing the name twice. map: hashbrown::HashTable<ScopedSymbolId>, } impl SymbolTable { /// Look up a symbol by its ID. /// /// ## Panics /// If the ID is not valid for this symbol table. #[track_caller] pub(crate) fn symbol(&self, id: ScopedSymbolId) -> &Symbol { &self.symbols[id] } /// Look up a symbol by its ID, mutably. /// /// ## Panics /// If the ID is not valid for this symbol table. #[track_caller] pub(crate) fn symbol_mut(&mut self, id: ScopedSymbolId) -> &mut Symbol { &mut self.symbols[id] } /// Look up the ID of a symbol by its name. pub(crate) fn symbol_id(&self, name: &str) -> Option<ScopedSymbolId> { self.map .find(Self::hash_name(name), |id| self.symbols[*id].name == name) .copied() } /// Iterate over the symbols in this symbol table. pub(crate) fn iter(&self) -> std::slice::Iter<'_, Symbol> { self.symbols.iter() } fn hash_name(name: &str) -> u64 { let mut h = FxHasher::default(); name.hash(&mut h); h.finish() } } impl PartialEq for SymbolTable { fn eq(&self, other: &Self) -> bool { // It's sufficient to compare the symbols as the map is only a reverse lookup. self.symbols == other.symbols } } impl Eq for SymbolTable {} impl std::fmt::Debug for SymbolTable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("SymbolTable").field(&self.symbols).finish() } } #[derive(Debug, Default)] pub(super) struct SymbolTableBuilder { table: SymbolTable, } impl SymbolTableBuilder { /// Add a new symbol to this scope or update the flags if a symbol with the same name already exists. pub(super) fn add(&mut self, mut symbol: Symbol) -> (ScopedSymbolId, bool) { let hash = SymbolTable::hash_name(symbol.name()); let entry = self.table.map.entry( hash, |id| &self.table.symbols[*id].name == symbol.name(), |id| SymbolTable::hash_name(&self.table.symbols[*id].name), ); match entry { Entry::Occupied(entry) => { let id = *entry.get(); if !symbol.flags.is_empty() { self.symbols[id].flags.insert(symbol.flags); } (id, false) } Entry::Vacant(entry) => { symbol.name.shrink_to_fit(); let id = self.table.symbols.push(symbol); entry.insert(id); (id, true) } } } pub(super) fn build(self) -> SymbolTable { let mut table = self.table; table.symbols.shrink_to_fit(); table .map .shrink_to_fit(|id| SymbolTable::hash_name(&table.symbols[*id].name)); table } } impl Deref for SymbolTableBuilder { type Target = SymbolTable; fn deref(&self) -> &Self::Target { &self.table } } impl DerefMut for SymbolTableBuilder { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.table } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/use_def/place_state.rs
crates/ty_python_semantic/src/semantic_index/use_def/place_state.rs
//! Track live bindings per place, applicable constraints per binding, and live declarations. //! //! These data structures operate entirely on scope-local newtype-indices for definitions and //! constraints, referring to their location in the `all_definitions` and `all_constraints` //! indexvecs in [`super::UseDefMapBuilder`]. //! //! We need to track arbitrary associations between bindings and constraints, not just a single set //! of currently dominating constraints (where "dominating" means "control flow must have passed //! through it to reach this point"), because we can have dominating constraints that apply to some //! bindings but not others, as in this code: //! //! ```python //! x = 1 if flag else None //! if x is not None: //! if flag2: //! x = 2 if flag else None //! x //! ``` //! //! The `x is not None` constraint dominates the final use of `x`, but it applies only to the first //! binding of `x`, not the second, so `None` is a possible value for `x`. //! //! And we can't just track, for each binding, an index into a list of dominating constraints, //! either, because we can have bindings which are still visible, but subject to constraints that //! are no longer dominating, as in this code: //! //! ```python //! x = 0 //! if flag1: //! x = 1 if flag2 else None //! assert x is not None //! x //! ``` //! //! From the point of view of the final use of `x`, the `x is not None` constraint no longer //! dominates, but it does dominate the `x = 1 if flag2 else None` binding, so we have to keep //! track of that. //! //! The data structures use `IndexVec` arenas to store all data compactly and contiguously, while //! supporting very cheap clones. //! //! Tracking live declarations is simpler, since constraints are not involved, but otherwise very //! similar to tracking live bindings. use itertools::{EitherOrBoth, Itertools}; use ruff_index::newtype_index; use smallvec::{SmallVec, smallvec}; use crate::semantic_index::narrowing_constraints::{ NarrowingConstraintsBuilder, ScopedNarrowingConstraint, ScopedNarrowingConstraintPredicate, }; use crate::semantic_index::reachability_constraints::{ ReachabilityConstraintsBuilder, ScopedReachabilityConstraintId, }; /// A newtype-index for a definition in a particular scope. #[newtype_index] #[derive(Ord, PartialOrd, get_size2::GetSize)] pub(super) struct ScopedDefinitionId; impl ScopedDefinitionId { /// A special ID that is used to describe an implicit start-of-scope state. When /// we see that this definition is live, we know that the place is (possibly) /// unbound or undeclared at a given usage site. /// When creating a use-def-map builder, we always add an empty `DefinitionState::Undefined` definition /// at index 0, so this ID is always present. pub(super) const UNBOUND: ScopedDefinitionId = ScopedDefinitionId::from_u32(0); fn is_unbound(self) -> bool { self == Self::UNBOUND } } /// Live declarations for a single place at some point in control flow, with their /// corresponding reachability constraints. #[derive(Clone, Debug, Default, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(super) struct Declarations { /// A list of live declarations for this place, sorted by their `ScopedDefinitionId` live_declarations: SmallVec<[LiveDeclaration; 2]>, } /// One of the live declarations for a single place at some point in control flow. #[derive(Clone, Debug, PartialEq, Eq, get_size2::GetSize)] pub(super) struct LiveDeclaration { pub(super) declaration: ScopedDefinitionId, pub(super) reachability_constraint: ScopedReachabilityConstraintId, } pub(super) type LiveDeclarationsIterator<'a> = std::slice::Iter<'a, LiveDeclaration>; #[derive(Clone, Copy, Debug)] pub(super) enum PreviousDefinitions { AreShadowed, AreKept, } impl PreviousDefinitions { pub(super) fn are_shadowed(self) -> bool { matches!(self, PreviousDefinitions::AreShadowed) } } impl Declarations { pub(super) fn undeclared(reachability_constraint: ScopedReachabilityConstraintId) -> Self { let initial_declaration = LiveDeclaration { declaration: ScopedDefinitionId::UNBOUND, reachability_constraint, }; Self { live_declarations: smallvec![initial_declaration], } } /// Record a newly-encountered declaration for this place. pub(super) fn record_declaration( &mut self, declaration: ScopedDefinitionId, reachability_constraint: ScopedReachabilityConstraintId, previous_definitions: PreviousDefinitions, ) { if previous_definitions.are_shadowed() { // The new declaration replaces all previous live declaration in this path. self.live_declarations.clear(); } self.live_declarations.push(LiveDeclaration { declaration, reachability_constraint, }); } /// Add given reachability constraint to all live declarations. pub(super) fn record_reachability_constraint( &mut self, reachability_constraints: &mut ReachabilityConstraintsBuilder, constraint: ScopedReachabilityConstraintId, ) { for declaration in &mut self.live_declarations { declaration.reachability_constraint = reachability_constraints .add_and_constraint(declaration.reachability_constraint, constraint); } } /// Return an iterator over live declarations for this place. pub(super) fn iter(&self) -> LiveDeclarationsIterator<'_> { self.live_declarations.iter() } fn merge(&mut self, b: Self, reachability_constraints: &mut ReachabilityConstraintsBuilder) { let a = std::mem::take(self); // Invariant: merge_join_by consumes the two iterators in sorted order, which ensures that // the merged `live_declarations` vec remains sorted. If a definition is found in both `a` // and `b`, we compose the constraints from the two paths in an appropriate way // (intersection for narrowing constraints; ternary OR for reachability constraints). If a // definition is found in only one path, it is used as-is. let a = a.live_declarations.into_iter(); let b = b.live_declarations.into_iter(); for zipped in a.merge_join_by(b, |a, b| a.declaration.cmp(&b.declaration)) { match zipped { EitherOrBoth::Both(a, b) => { let reachability_constraint = reachability_constraints .add_or_constraint(a.reachability_constraint, b.reachability_constraint); self.live_declarations.push(LiveDeclaration { declaration: a.declaration, reachability_constraint, }); } EitherOrBoth::Left(declaration) | EitherOrBoth::Right(declaration) => { self.live_declarations.push(declaration); } } } } pub(super) fn finish(&mut self, reachability_constraints: &mut ReachabilityConstraintsBuilder) { self.live_declarations.shrink_to_fit(); for declaration in &self.live_declarations { reachability_constraints.mark_used(declaration.reachability_constraint); } } } /// A snapshot of a place state that can be used to resolve a reference in a nested scope. /// If there are bindings in a (non-class) scope, they are stored in `Bindings`. /// Even if it's a class scope (class variables are not visible to nested scopes) or there are no /// bindings, the current narrowing constraint is necessary for narrowing, so it's stored in /// `Constraint`. #[derive(Clone, Debug, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(super) enum EnclosingSnapshot { Constraint(ScopedNarrowingConstraint), Bindings(Bindings), } impl EnclosingSnapshot { pub(super) fn finish(&mut self, reachability_constraints: &mut ReachabilityConstraintsBuilder) { match self { Self::Constraint(_) => {} Self::Bindings(bindings) => { bindings.finish(reachability_constraints); } } } } /// Live bindings for a single place at some point in control flow. Each live binding comes /// with a set of narrowing constraints and a reachability constraint. #[derive(Clone, Debug, Default, PartialEq, Eq, salsa::Update, get_size2::GetSize)] pub(super) struct Bindings { /// The narrowing constraint applicable to the "unbound" binding, if we need access to it even /// when it's not visible. This happens in class scopes, where local name bindings are not visible /// to nested scopes, but we still need to know what narrowing constraints were applied to the /// "unbound" binding. unbound_narrowing_constraint: Option<ScopedNarrowingConstraint>, /// A list of live bindings for this place, sorted by their `ScopedDefinitionId` live_bindings: SmallVec<[LiveBinding; 2]>, } impl Bindings { pub(super) fn unbound_narrowing_constraint(&self) -> ScopedNarrowingConstraint { self.unbound_narrowing_constraint .unwrap_or(self.live_bindings[0].narrowing_constraint) } pub(super) fn finish(&mut self, reachability_constraints: &mut ReachabilityConstraintsBuilder) { self.live_bindings.shrink_to_fit(); for binding in &self.live_bindings { reachability_constraints.mark_used(binding.reachability_constraint); } } } /// One of the live bindings for a single place at some point in control flow. #[derive(Clone, Debug, PartialEq, Eq, get_size2::GetSize)] pub(super) struct LiveBinding { pub(super) binding: ScopedDefinitionId, pub(super) narrowing_constraint: ScopedNarrowingConstraint, pub(super) reachability_constraint: ScopedReachabilityConstraintId, } pub(super) type LiveBindingsIterator<'a> = std::slice::Iter<'a, LiveBinding>; impl Bindings { pub(super) fn unbound(reachability_constraint: ScopedReachabilityConstraintId) -> Self { let initial_binding = LiveBinding { binding: ScopedDefinitionId::UNBOUND, narrowing_constraint: ScopedNarrowingConstraint::empty(), reachability_constraint, }; Self { unbound_narrowing_constraint: None, live_bindings: smallvec![initial_binding], } } /// Record a newly-encountered binding for this place. pub(super) fn record_binding( &mut self, binding: ScopedDefinitionId, reachability_constraint: ScopedReachabilityConstraintId, is_class_scope: bool, is_place_name: bool, previous_definitions: PreviousDefinitions, ) { // If we are in a class scope, and the unbound name binding was previously visible, but we will // now replace it, record the narrowing constraints on it: if is_class_scope && is_place_name && self.live_bindings[0].binding.is_unbound() { self.unbound_narrowing_constraint = Some(self.live_bindings[0].narrowing_constraint); } // The new binding replaces all previous live bindings in this path, and has no // constraints. if previous_definitions.are_shadowed() { self.live_bindings.clear(); } self.live_bindings.push(LiveBinding { binding, narrowing_constraint: ScopedNarrowingConstraint::empty(), reachability_constraint, }); } /// Add given constraint to all live bindings. pub(super) fn record_narrowing_constraint( &mut self, narrowing_constraints: &mut NarrowingConstraintsBuilder, predicate: ScopedNarrowingConstraintPredicate, ) { for binding in &mut self.live_bindings { binding.narrowing_constraint = narrowing_constraints .add_predicate_to_constraint(binding.narrowing_constraint, predicate); } } /// Add given reachability constraint to all live bindings. pub(super) fn record_reachability_constraint( &mut self, reachability_constraints: &mut ReachabilityConstraintsBuilder, constraint: ScopedReachabilityConstraintId, ) { for binding in &mut self.live_bindings { binding.reachability_constraint = reachability_constraints .add_and_constraint(binding.reachability_constraint, constraint); } } /// Iterate over currently live bindings for this place pub(super) fn iter(&self) -> LiveBindingsIterator<'_> { self.live_bindings.iter() } pub(super) fn merge( &mut self, b: Self, narrowing_constraints: &mut NarrowingConstraintsBuilder, reachability_constraints: &mut ReachabilityConstraintsBuilder, ) { let a = std::mem::take(self); if let Some((a, b)) = a .unbound_narrowing_constraint .zip(b.unbound_narrowing_constraint) { self.unbound_narrowing_constraint = Some(narrowing_constraints.intersect_constraints(a, b)); } // Invariant: merge_join_by consumes the two iterators in sorted order, which ensures that // the merged `live_bindings` vec remains sorted. If a definition is found in both `a` and // `b`, we compose the constraints from the two paths in an appropriate way (intersection // for narrowing constraints; ternary OR for reachability constraints). If a definition is // found in only one path, it is used as-is. let a = a.live_bindings.into_iter(); let b = b.live_bindings.into_iter(); for zipped in a.merge_join_by(b, |a, b| a.binding.cmp(&b.binding)) { match zipped { EitherOrBoth::Both(a, b) => { // If the same definition is visible through both paths, any constraint // that applies on only one path is irrelevant to the resulting type from // unioning the two paths, so we intersect the constraints. let narrowing_constraint = narrowing_constraints .intersect_constraints(a.narrowing_constraint, b.narrowing_constraint); // For reachability constraints, we merge them using a ternary OR operation: let reachability_constraint = reachability_constraints .add_or_constraint(a.reachability_constraint, b.reachability_constraint); self.live_bindings.push(LiveBinding { binding: a.binding, narrowing_constraint, reachability_constraint, }); } EitherOrBoth::Left(binding) | EitherOrBoth::Right(binding) => { self.live_bindings.push(binding); } } } } } #[derive(Clone, Debug, PartialEq, Eq, get_size2::GetSize)] pub(in crate::semantic_index) struct PlaceState { declarations: Declarations, bindings: Bindings, } impl PlaceState { /// Return a new [`PlaceState`] representing an unbound, undeclared place. pub(super) fn undefined(reachability: ScopedReachabilityConstraintId) -> Self { Self { declarations: Declarations::undeclared(reachability), bindings: Bindings::unbound(reachability), } } /// Record a newly-encountered binding for this place. pub(super) fn record_binding( &mut self, binding_id: ScopedDefinitionId, reachability_constraint: ScopedReachabilityConstraintId, is_class_scope: bool, is_place_name: bool, ) { debug_assert_ne!(binding_id, ScopedDefinitionId::UNBOUND); self.bindings.record_binding( binding_id, reachability_constraint, is_class_scope, is_place_name, PreviousDefinitions::AreShadowed, ); } /// Add given constraint to all live bindings. pub(super) fn record_narrowing_constraint( &mut self, narrowing_constraints: &mut NarrowingConstraintsBuilder, constraint: ScopedNarrowingConstraintPredicate, ) { self.bindings .record_narrowing_constraint(narrowing_constraints, constraint); } /// Add given reachability constraint to all live bindings. pub(super) fn record_reachability_constraint( &mut self, reachability_constraints: &mut ReachabilityConstraintsBuilder, constraint: ScopedReachabilityConstraintId, ) { self.bindings .record_reachability_constraint(reachability_constraints, constraint); self.declarations .record_reachability_constraint(reachability_constraints, constraint); } /// Record a newly-encountered declaration of this place. pub(super) fn record_declaration( &mut self, declaration_id: ScopedDefinitionId, reachability_constraint: ScopedReachabilityConstraintId, ) { self.declarations.record_declaration( declaration_id, reachability_constraint, PreviousDefinitions::AreShadowed, ); } /// Merge another [`PlaceState`] into this one. pub(super) fn merge( &mut self, b: PlaceState, narrowing_constraints: &mut NarrowingConstraintsBuilder, reachability_constraints: &mut ReachabilityConstraintsBuilder, ) { self.bindings .merge(b.bindings, narrowing_constraints, reachability_constraints); self.declarations .merge(b.declarations, reachability_constraints); } pub(super) fn bindings(&self) -> &Bindings { &self.bindings } pub(super) fn declarations(&self) -> &Declarations { &self.declarations } pub(super) fn finish(&mut self, reachability_constraints: &mut ReachabilityConstraintsBuilder) { self.declarations.finish(reachability_constraints); self.bindings.finish(reachability_constraints); } } #[cfg(test)] mod tests { use super::*; use ruff_index::Idx; use crate::semantic_index::predicate::ScopedPredicateId; #[track_caller] fn assert_bindings( narrowing_constraints: &NarrowingConstraintsBuilder, place: &PlaceState, expected: &[&str], ) { let actual = place .bindings() .iter() .map(|live_binding| { let def_id = live_binding.binding; let def = if def_id == ScopedDefinitionId::UNBOUND { "unbound".into() } else { def_id.as_u32().to_string() }; let predicates = narrowing_constraints .iter_predicates(live_binding.narrowing_constraint) .map(|idx| idx.as_u32().to_string()) .collect::<Vec<_>>() .join(", "); format!("{def}<{predicates}>") }) .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[track_caller] pub(crate) fn assert_declarations(place: &PlaceState, expected: &[&str]) { let actual = place .declarations() .iter() .map( |LiveDeclaration { declaration, reachability_constraint: _, }| { if *declaration == ScopedDefinitionId::UNBOUND { "undeclared".into() } else { declaration.as_u32().to_string() } }, ) .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[test] fn unbound() { let narrowing_constraints = NarrowingConstraintsBuilder::default(); let sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); assert_bindings(&narrowing_constraints, &sym, &["unbound<>"]); } #[test] fn with() { let narrowing_constraints = NarrowingConstraintsBuilder::default(); let mut sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym.record_binding( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, false, true, ); assert_bindings(&narrowing_constraints, &sym, &["1<>"]); } #[test] fn record_constraint() { let mut narrowing_constraints = NarrowingConstraintsBuilder::default(); let mut sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym.record_binding( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, false, true, ); let predicate = ScopedPredicateId::new(0).into(); sym.record_narrowing_constraint(&mut narrowing_constraints, predicate); assert_bindings(&narrowing_constraints, &sym, &["1<0>"]); } #[test] fn merge() { let mut narrowing_constraints = NarrowingConstraintsBuilder::default(); let mut reachability_constraints = ReachabilityConstraintsBuilder::default(); // merging the same definition with the same constraint keeps the constraint let mut sym1a = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym1a.record_binding( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, false, true, ); let predicate = ScopedPredicateId::new(0).into(); sym1a.record_narrowing_constraint(&mut narrowing_constraints, predicate); let mut sym1b = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym1b.record_binding( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, false, true, ); let predicate = ScopedPredicateId::new(0).into(); sym1b.record_narrowing_constraint(&mut narrowing_constraints, predicate); sym1a.merge( sym1b, &mut narrowing_constraints, &mut reachability_constraints, ); let mut sym1 = sym1a; assert_bindings(&narrowing_constraints, &sym1, &["1<0>"]); // merging the same definition with differing constraints drops all constraints let mut sym2a = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym2a.record_binding( ScopedDefinitionId::from_u32(2), ScopedReachabilityConstraintId::ALWAYS_TRUE, false, true, ); let predicate = ScopedPredicateId::new(1).into(); sym2a.record_narrowing_constraint(&mut narrowing_constraints, predicate); let mut sym1b = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym1b.record_binding( ScopedDefinitionId::from_u32(2), ScopedReachabilityConstraintId::ALWAYS_TRUE, false, true, ); let predicate = ScopedPredicateId::new(2).into(); sym1b.record_narrowing_constraint(&mut narrowing_constraints, predicate); sym2a.merge( sym1b, &mut narrowing_constraints, &mut reachability_constraints, ); let sym2 = sym2a; assert_bindings(&narrowing_constraints, &sym2, &["2<>"]); // merging a constrained definition with unbound keeps both let mut sym3a = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym3a.record_binding( ScopedDefinitionId::from_u32(3), ScopedReachabilityConstraintId::ALWAYS_TRUE, false, true, ); let predicate = ScopedPredicateId::new(3).into(); sym3a.record_narrowing_constraint(&mut narrowing_constraints, predicate); let sym2b = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym3a.merge( sym2b, &mut narrowing_constraints, &mut reachability_constraints, ); let sym3 = sym3a; assert_bindings(&narrowing_constraints, &sym3, &["unbound<>", "3<3>"]); // merging different definitions keeps them each with their existing constraints sym1.merge( sym3, &mut narrowing_constraints, &mut reachability_constraints, ); let sym = sym1; assert_bindings(&narrowing_constraints, &sym, &["unbound<>", "1<0>", "3<3>"]); } #[test] fn no_declaration() { let sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); assert_declarations(&sym, &["undeclared"]); } #[test] fn record_declaration() { let mut sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym.record_declaration( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, ); assert_declarations(&sym, &["1"]); } #[test] fn record_declaration_override() { let mut sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym.record_declaration( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, ); sym.record_declaration( ScopedDefinitionId::from_u32(2), ScopedReachabilityConstraintId::ALWAYS_TRUE, ); assert_declarations(&sym, &["2"]); } #[test] fn record_declaration_merge() { let mut narrowing_constraints = NarrowingConstraintsBuilder::default(); let mut reachability_constraints = ReachabilityConstraintsBuilder::default(); let mut sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym.record_declaration( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, ); let mut sym2 = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym2.record_declaration( ScopedDefinitionId::from_u32(2), ScopedReachabilityConstraintId::ALWAYS_TRUE, ); sym.merge( sym2, &mut narrowing_constraints, &mut reachability_constraints, ); assert_declarations(&sym, &["1", "2"]); } #[test] fn record_declaration_merge_partial_undeclared() { let mut narrowing_constraints = NarrowingConstraintsBuilder::default(); let mut reachability_constraints = ReachabilityConstraintsBuilder::default(); let mut sym = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym.record_declaration( ScopedDefinitionId::from_u32(1), ScopedReachabilityConstraintId::ALWAYS_TRUE, ); let sym2 = PlaceState::undefined(ScopedReachabilityConstraintId::ALWAYS_TRUE); sym.merge( sym2, &mut narrowing_constraints, &mut reachability_constraints, ); assert_declarations(&sym, &["undeclared", "1"]); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/semantic_index/builder/except_handlers.rs
crates/ty_python_semantic/src/semantic_index/builder/except_handlers.rs
use crate::semantic_index::use_def::FlowSnapshot; use super::SemanticIndexBuilder; /// An abstraction over the fact that each scope should have its own [`TryNodeContextStack`] #[derive(Debug, Default)] pub(super) struct TryNodeContextStackManager(Vec<TryNodeContextStack>); impl TryNodeContextStackManager { /// Push a new [`TryNodeContextStack`] onto the stack of stacks. /// /// Each [`TryNodeContextStack`] is only valid for a single scope pub(super) fn enter_nested_scope(&mut self) { self.0.push(TryNodeContextStack::default()); } /// Pop a new [`TryNodeContextStack`] off the stack of stacks. /// /// Each [`TryNodeContextStack`] is only valid for a single scope pub(super) fn exit_scope(&mut self) { let popped_context = self.0.pop(); debug_assert!( popped_context.is_some(), "exit_scope() should never be called on an empty stack \ (this indicates an unbalanced `enter_nested_scope()`/`exit_scope()` pair of calls)" ); } /// Push a [`TryNodeContext`] onto the [`TryNodeContextStack`] /// at the top of our stack of stacks pub(super) fn push_context(&mut self) { self.current_try_context_stack().push_context(); } /// Pop a [`TryNodeContext`] off the [`TryNodeContextStack`] /// at the top of our stack of stacks. Return the Vec of [`FlowSnapshot`]s /// recorded while we were visiting the `try` suite. pub(super) fn pop_context(&mut self) -> Vec<FlowSnapshot> { self.current_try_context_stack().pop_context() } /// Retrieve the stack that is at the top of our stack of stacks. /// For each `try` block on that stack, push the snapshot onto the `try` block pub(super) fn record_definition(&mut self, builder: &SemanticIndexBuilder) { self.current_try_context_stack().record_definition(builder); } /// Retrieve the [`TryNodeContextStack`] that is relevant for the current scope. fn current_try_context_stack(&mut self) -> &mut TryNodeContextStack { self.0 .last_mut() .expect("There should always be at least one `TryBlockContexts` on the stack") } } /// The contexts of nested `try`/`except` blocks for a single scope #[derive(Debug, Default)] struct TryNodeContextStack(Vec<TryNodeContext>); impl TryNodeContextStack { /// Push a new [`TryNodeContext`] for recording intermediate states /// while visiting a [`ruff_python_ast::StmtTry`] node that has a `finally` branch. fn push_context(&mut self) { self.0.push(TryNodeContext::default()); } /// Pop a [`TryNodeContext`] off the stack. Return the Vec of [`FlowSnapshot`]s /// recorded while we were visiting the `try` suite. fn pop_context(&mut self) -> Vec<FlowSnapshot> { let TryNodeContext { try_suite_snapshots, } = self .0 .pop() .expect("Cannot pop a `try` block off an empty `TryBlockContexts` stack"); try_suite_snapshots } /// For each `try` block on the stack, push the snapshot onto the `try` block fn record_definition(&mut self, builder: &SemanticIndexBuilder) { for context in &mut self.0 { context.record_definition(builder.flow_snapshot()); } } } /// Context for tracking definitions over the course of a single /// [`ruff_python_ast::StmtTry`] node /// /// It will likely be necessary to add more fields to this struct in the future /// when we add more advanced handling of `finally` branches. #[derive(Debug, Default)] struct TryNodeContext { try_suite_snapshots: Vec<FlowSnapshot>, } impl TryNodeContext { /// Take a record of what the internal state looked like after a definition fn record_definition(&mut self, snapshot: FlowSnapshot) { self.try_suite_snapshots.push(snapshot); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/suppression/unused.rs
crates/ty_python_semantic/src/suppression/unused.rs
use ruff_db::source::source_text; use ruff_diagnostics::{Edit, Fix}; use ruff_text_size::{TextLen, TextRange, TextSize}; use std::fmt::Write as _; use crate::lint::LintId; use crate::suppression::{ CheckSuppressionsContext, Suppression, SuppressionTarget, UNUSED_IGNORE_COMMENT, }; /// Checks for unused suppression comments in `file` and /// adds diagnostic for each of them to `diagnostics`. /// /// Does nothing if the [`UNUSED_IGNORE_COMMENT`] rule is disabled. pub(super) fn check_unused_suppressions(context: &mut CheckSuppressionsContext) { if context.is_lint_disabled(&UNUSED_IGNORE_COMMENT) { return; } let diagnostics = context.diagnostics.get_mut(); let all = context.suppressions; let mut unused = Vec::with_capacity( all.file .len() .saturating_add(all.line.len()) .saturating_sub(diagnostics.used_len()), ); // Collect all suppressions that are unused after type-checking. for suppression in all { if diagnostics.is_used(suppression.id()) { continue; } // `unused-ignore-comment` diagnostics can only be suppressed by specifying a // code. This is necessary because every `type: ignore` would implicitly also // suppress its own unused-ignore-comment diagnostic. if let Some(unused_suppression) = all .lint_suppressions(suppression.range, LintId::of(&UNUSED_IGNORE_COMMENT)) .find(|unused_ignore_suppression| unused_ignore_suppression.target.is_lint()) { // A `unused-ignore-comment` suppression can't ignore itself. // It can only ignore other suppressions. if unused_suppression.id() != suppression.id() { diagnostics.mark_used(unused_suppression.id()); continue; } } unused.push(suppression); } let mut unused_iter = unused .iter() .filter(|suppression| { // This looks silly but it's necessary to check again if a `unused-ignore-comment` is indeed unused // in case the "unused" directive comes after it: // ```py // a = 10 / 2 # ty: ignore[unused-ignore-comment, division-by-zero] // ``` !context.is_suppression_used(suppression.id()) }) .peekable(); let source = source_text(context.db, context.file); while let Some(suppression) = unused_iter.next() { let mut diag = match suppression.target { SuppressionTarget::All => { let Some(diag) = context.report_unchecked(&UNUSED_IGNORE_COMMENT, suppression.range) else { continue; }; diag.into_diagnostic(format_args!( "Unused blanket `{}` directive", suppression.kind )) } SuppressionTarget::Lint(lint) => { // A single code in a `ty: ignore[<code1>, <code2>, ...]` directive // Is this the first code directly after the `[`? let includes_first_code = source[..suppression.range.start().to_usize()] .trim_end() .ends_with('['); let mut current = suppression; let mut unused_codes = Vec::new(); // Group successive codes together into a single diagnostic, // or report the entire directive if all codes are unused. while let Some(next) = unused_iter.peek() { if let SuppressionTarget::Lint(next_lint) = next.target && next.comment_range == current.comment_range && source[TextRange::new(current.range.end(), next.range.start())] .chars() .all(|c| c.is_whitespace() || c == ',') { unused_codes.push(next_lint); current = *next; unused_iter.next(); } else { break; } } // Is the last suppression code the last code before the closing `]`. let includes_last_code = source[current.range.end().to_usize()..] .trim_start() .starts_with(']'); // If only some codes are unused if !includes_first_code || !includes_last_code { let mut codes = format!("'{}'", lint.name()); for code in &unused_codes { let _ = write!(&mut codes, ", '{code}'", code = code.name()); } if let Some(diag) = context.report_unchecked( &UNUSED_IGNORE_COMMENT, TextRange::new(suppression.range.start(), current.range.end()), ) { let mut diag = diag.into_diagnostic(format_args!( "Unused `{kind}` directive: {codes}", kind = suppression.kind )); diag.primary_annotation_mut() .unwrap() .push_tag(ruff_db::diagnostic::DiagnosticTag::Unnecessary); // Delete everything up to the start of the next code. let trailing_len: TextSize = source[current.range.end().to_usize()..] .chars() .take_while(|c: &char| c.is_whitespace() || *c == ',') .map(TextLen::text_len) .sum(); // If we delete the last codes before `]`, ensure we delete any trailing comma let leading_len: TextSize = if includes_last_code { source[..suppression.range.start().to_usize()] .chars() .rev() .take_while(|c: &char| c.is_whitespace() || *c == ',') .map(TextLen::text_len) .sum() } else { TextSize::default() }; let fix_range = TextRange::new( suppression.range.start() - leading_len, current.range.end() + trailing_len, ); diag.set_fix(Fix::safe_edit(Edit::range_deletion(fix_range))); if unused_codes.is_empty() { diag.help("Remove the unused suppression code"); } else { diag.help("Remove the unused suppression codes"); } } continue; } // All codes are unused let Some(diag) = context.report_unchecked(&UNUSED_IGNORE_COMMENT, suppression.comment_range) else { continue; }; diag.into_diagnostic(format_args!( "Unused `{kind}` directive", kind = suppression.kind )) } SuppressionTarget::Empty => { let Some(diag) = context.report_unchecked(&UNUSED_IGNORE_COMMENT, suppression.range) else { continue; }; diag.into_diagnostic(format_args!( "Unused `{kind}` without a code", kind = suppression.kind )) } }; diag.primary_annotation_mut() .unwrap() .push_tag(ruff_db::diagnostic::DiagnosticTag::Unnecessary); diag.set_fix(remove_comment_fix(suppression, &source)); diag.help("Remove the unused suppression comment"); } } fn remove_comment_fix(suppression: &Suppression, source: &str) -> Fix { let comment_end = suppression.comment_range.end(); let comment_start = suppression.comment_range.start(); let after_comment = &source[comment_end.to_usize()..]; if !after_comment.starts_with(['\n', '\r']) { // For example: `# ty: ignore # fmt: off` // Don't remove the trailing whitespace up to the `ty: ignore` comment return Fix::safe_edit(Edit::range_deletion(suppression.comment_range)); } // Remove any leading whitespace before the comment // to avoid unnecessary trailing whitespace once the comment is removed let before_comment = &source[..comment_start.to_usize()]; let mut leading_len = TextSize::default(); for c in before_comment.chars().rev() { match c { '\n' | '\r' => break, c if c.is_whitespace() => leading_len += c.text_len(), _ => break, } } Fix::safe_edit(Edit::range_deletion(TextRange::new( comment_start - leading_len, comment_end, ))) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/suppression/parser.rs
crates/ty_python_semantic/src/suppression/parser.rs
use std::error::Error; use crate::suppression::SuppressionKind; use ruff_python_trivia::Cursor; use ruff_text_size::{TextLen, TextRange, TextSize}; use smallvec::{SmallVec, smallvec}; use thiserror::Error; pub(super) struct SuppressionParser<'src> { cursor: Cursor<'src>, range: TextRange, } impl<'src> SuppressionParser<'src> { pub(super) fn new(source: &'src str, range: TextRange) -> Self { let cursor = Cursor::new(&source[range]); Self { cursor, range } } fn parse_comment(&mut self) -> Result<SuppressionComment, ParseError> { let comment_start = self.offset(); self.cursor.start_token(); if !self.cursor.eat_char('#') { return self.syntax_error(ParseErrorKind::CommentWithoutHash); } self.eat_whitespace(); // type: ignore[code] // ^^^^^^^^^^^^ let Some(kind) = self.eat_kind() else { return Err(ParseError::new( ParseErrorKind::NotASuppression, TextRange::new(comment_start, self.offset()), )); }; let has_trailing_whitespace = self.eat_whitespace(); // type: ignore[code1, code2] // ^^^^^^ let codes = self.eat_codes(kind)?; if self.cursor.is_eof() || codes.is_some() || has_trailing_whitespace { // Consume the comment until its end or until the next "sub-comment" starts. self.cursor.eat_while(|c| c != '#'); Ok(SuppressionComment { kind, codes, range: TextRange::at(comment_start, self.cursor.token_len()), }) } else { self.syntax_error(ParseErrorKind::NoWhitespaceAfterIgnore(kind)) } } fn eat_kind(&mut self) -> Option<SuppressionKind> { let kind = if self.cursor.as_str().starts_with("type") { SuppressionKind::TypeIgnore } else if self.cursor.as_str().starts_with("ty") { SuppressionKind::Ty } else { return None; }; self.cursor.skip_bytes(kind.len_utf8()); self.eat_whitespace(); if !self.cursor.eat_char(':') { return None; } self.eat_whitespace(); if !self.cursor.as_str().starts_with("ignore") { return None; } self.cursor.skip_bytes("ignore".len()); Some(kind) } fn eat_codes( &mut self, kind: SuppressionKind, ) -> Result<Option<SmallVec<[TextRange; 2]>>, ParseError> { if !self.cursor.eat_char('[') { return Ok(None); } let mut codes: SmallVec<[TextRange; 2]> = smallvec![]; loop { if self.cursor.is_eof() { return self.syntax_error(ParseErrorKind::CodesMissingClosingBracket(kind)); } self.eat_whitespace(); // `ty: ignore[]` or `ty: ignore[a,]` if self.cursor.eat_char(']') { break Ok(Some(codes)); } let code_start = self.offset(); if !self.eat_word() { return self.syntax_error(ParseErrorKind::InvalidCode(kind)); } codes.push(TextRange::new(code_start, self.offset())); self.eat_whitespace(); if !self.cursor.eat_char(',') { if self.cursor.eat_char(']') { break Ok(Some(codes)); } // `ty: ignore[a b] return self.syntax_error(ParseErrorKind::CodesMissingComma(kind)); } } } fn eat_whitespace(&mut self) -> bool { if self.cursor.eat_if(char::is_whitespace) { self.cursor.eat_while(char::is_whitespace); true } else { false } } fn eat_word(&mut self) -> bool { if self.cursor.eat_if(char::is_alphabetic) { // Allow `:` for better error recovery when someone uses `lint:code` instead of just `code`. self.cursor .eat_while(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | ':')); true } else { false } } fn syntax_error<T>(&self, kind: ParseErrorKind) -> Result<T, ParseError> { let len = if self.cursor.is_eof() { TextSize::default() } else { self.cursor.first().text_len() }; Err(ParseError::new(kind, TextRange::at(self.offset(), len))) } fn offset(&self) -> TextSize { self.range.start() + self.range.len() - self.cursor.text_len() } } impl Iterator for SuppressionParser<'_> { type Item = Result<SuppressionComment, ParseError>; fn next(&mut self) -> Option<Self::Item> { if self.cursor.is_eof() { return None; } match self.parse_comment() { Ok(result) => Some(Ok(result)), Err(error) => { self.cursor.eat_while(|c| c != '#'); Some(Err(error)) } } } } /// A single parsed suppression comment. #[derive(Clone, Debug, Eq, PartialEq)] pub(super) struct SuppressionComment { /// The range of the suppression comment. /// /// This can be a sub-range of the comment token if the comment token contains multiple `#` tokens: /// ```py /// # fmt: off # type: ignore /// ^^^^^^^^^^^^^^ /// ``` range: TextRange, kind: SuppressionKind, /// The ranges of the codes in the optional `[...]`. /// `None` for comments that don't specify any code. /// /// ```py /// # type: ignore[unresolved-reference, invalid-exception-caught] /// ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ /// ``` codes: Option<SmallVec<[TextRange; 2]>>, } impl SuppressionComment { pub(super) fn kind(&self) -> SuppressionKind { self.kind } pub(super) fn codes(&self) -> Option<&[TextRange]> { self.codes.as_deref() } pub(super) fn range(&self) -> TextRange { self.range } } #[derive(Debug, Eq, PartialEq, Clone, get_size2::GetSize)] pub(super) struct ParseError { pub(super) kind: ParseErrorKind, /// The position/range at which the parse error occurred. pub(super) range: TextRange, } impl ParseError { fn new(kind: ParseErrorKind, range: TextRange) -> Self { Self { kind, range } } } impl std::fmt::Display for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.kind.fmt(f) } } impl Error for ParseError {} #[derive(Debug, Eq, PartialEq, Clone, Error, get_size2::GetSize)] pub(super) enum ParseErrorKind { /// The comment isn't a suppression comment. #[error("not a suppression comment")] NotASuppression, #[error("the comment doesn't start with a `#`")] CommentWithoutHash, /// A valid suppression `type: ignore` but it misses a whitespaces after the `ignore` keyword. /// /// ```py /// type: ignoree /// ``` #[error("no whitespace after `ignore`")] NoWhitespaceAfterIgnore(SuppressionKind), /// Missing comma between two codes #[error("expected a comma separating the rule codes")] CodesMissingComma(SuppressionKind), /// `ty: ignore[*.*]` #[error("expected a alphanumeric character or `-` or `_` as code")] InvalidCode(SuppressionKind), /// `ty: ignore[a, b` #[error("expected a closing bracket")] CodesMissingClosingBracket(SuppressionKind), } #[cfg(test)] mod tests { use crate::suppression::{SuppressionComment, SuppressionParser}; use insta::assert_debug_snapshot; use ruff_text_size::{TextLen, TextRange}; use std::fmt; use std::fmt::Formatter; #[test] fn type_ignore_no_codes() { assert_debug_snapshot!( SuppressionComments::new( "# type: ignore", ), @r##" [ SuppressionComment { text: "# type: ignore", kind: TypeIgnore, codes: [], }, ] "## ); } #[test] fn type_ignore_explanation() { assert_debug_snapshot!( SuppressionComments::new( "# type: ignore I tried but couldn't figure out the proper type", ), @r##" [ SuppressionComment { text: "# type: ignore I tried but couldn't figure out the proper type", kind: TypeIgnore, codes: [], }, ] "## ); } #[test] fn fmt_comment_before_type_ignore() { assert_debug_snapshot!( SuppressionComments::new( "# fmt: off # type: ignore", ), @r##" [ SuppressionComment { text: "# type: ignore", kind: TypeIgnore, codes: [], }, ] "## ); } #[test] fn type_ignore_before_fmt_off() { assert_debug_snapshot!( SuppressionComments::new( "# type: ignore # fmt: off", ), @r##" [ SuppressionComment { text: "# type: ignore ", kind: TypeIgnore, codes: [], }, ] "## ); } #[test] fn multiple_type_ignore_comments() { assert_debug_snapshot!( SuppressionComments::new( "# type: ignore[a] # type: ignore[b]", ), @r##" [ SuppressionComment { text: "# type: ignore[a] ", kind: TypeIgnore, codes: [ "a", ], }, SuppressionComment { text: "# type: ignore[b]", kind: TypeIgnore, codes: [ "b", ], }, ] "## ); } #[test] fn invalid_type_ignore_valid_type_ignore() { assert_debug_snapshot!( SuppressionComments::new( "# type: ignore[a # type: ignore[b]", ), @r##" [ SuppressionComment { text: "# type: ignore[b]", kind: TypeIgnore, codes: [ "b", ], }, ] "## ); } #[test] fn valid_type_ignore_invalid_type_ignore() { assert_debug_snapshot!( SuppressionComments::new( "# type: ignore[a] # type: ignoreeee", ), @r##" [ SuppressionComment { text: "# type: ignore[a] ", kind: TypeIgnore, codes: [ "a", ], }, ] "## ); } #[test] fn type_ignore_multiple_codes() { assert_debug_snapshot!( SuppressionComments::new( "# type: ignore[invalid-exception-raised, invalid-exception-caught]", ), @r##" [ SuppressionComment { text: "# type: ignore[invalid-exception-raised, invalid-exception-caught]", kind: TypeIgnore, codes: [ "invalid-exception-raised", "invalid-exception-caught", ], }, ] "## ); } #[test] fn type_ignore_single_code() { assert_debug_snapshot!( SuppressionComments::new("# type: ignore[invalid-exception-raised]",), @r##" [ SuppressionComment { text: "# type: ignore[invalid-exception-raised]", kind: TypeIgnore, codes: [ "invalid-exception-raised", ], }, ] "## ); } struct SuppressionComments<'a> { source: &'a str, } impl<'a> SuppressionComments<'a> { fn new(source: &'a str) -> Self { Self { source } } } impl fmt::Debug for SuppressionComments<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut list = f.debug_list(); for comment in SuppressionParser::new( self.source, TextRange::new(0.into(), self.source.text_len()), ) .flatten() { list.entry(&comment.debug(self.source)); } list.finish() } } impl SuppressionComment { fn debug<'a>(&'a self, source: &'a str) -> DebugSuppressionComment<'a> { DebugSuppressionComment { source, comment: self, } } } struct DebugSuppressionComment<'a> { source: &'a str, comment: &'a SuppressionComment, } impl fmt::Debug for DebugSuppressionComment<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { struct DebugCodes<'a> { source: &'a str, codes: &'a [TextRange], } impl fmt::Debug for DebugCodes<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut f = f.debug_list(); for code in self.codes { f.entry(&&self.source[*code]); } f.finish() } } f.debug_struct("SuppressionComment") .field("text", &&self.source[self.comment.range]) .field("kind", &self.comment.kind) .field( "codes", &DebugCodes { source: self.source, codes: self.comment.codes.as_deref().unwrap_or_default(), }, ) .finish() } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/src/suppression/add_ignore.rs
crates/ty_python_semantic/src/suppression/add_ignore.rs
use ruff_db::files::File; use ruff_db::parsed::parsed_module; use ruff_db::source::source_text; use ruff_diagnostics::{Edit, Fix}; use ruff_python_ast::token::TokenKind; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use crate::Db; use crate::lint::LintId; use crate::suppression::{SuppressionTarget, suppressions}; /// Creates a fix for adding a suppression comment to suppress `lint` for `range`. /// /// The fix prefers adding the code to an existing `ty: ignore[]` comment over /// adding a new suppression comment. pub fn create_suppression_fix(db: &dyn Db, file: File, id: LintId, range: TextRange) -> Fix { let suppressions = suppressions(db, file); let source = source_text(db, file); let mut existing_suppressions = suppressions.line_suppressions(range).filter(|suppression| { matches!( suppression.target, SuppressionTarget::Lint(_) | SuppressionTarget::Empty, ) }); // If there's an existing `ty: ignore[]` comment, append the code to it instead of creating a new suppression comment. if let Some(existing) = existing_suppressions.next() { let comment_text = &source[existing.comment_range]; // Only add to the existing ignore comment if it has no reason. if let Some(before_closing_paren) = comment_text.trim_end().strip_suffix(']') { let up_to_last_code = before_closing_paren.trim_end(); let insertion = if up_to_last_code.ends_with(',') { format!(" {id}", id = id.name()) } else { format!(", {id}", id = id.name()) }; let relative_offset_from_end = comment_text.text_len() - up_to_last_code.text_len(); return Fix::safe_edit(Edit::insertion( insertion, existing.comment_range.end() - relative_offset_from_end, )); } } // Always insert a new suppression at the end of the range to avoid having to deal with multiline strings // etc. Also make sure to not pass a sub-token range to `Tokens::after`. let parsed = parsed_module(db, file).load(db); let tokens = parsed.tokens().at_offset(range.end()); let token_range = match tokens { ruff_python_ast::token::TokenAt::None => range, ruff_python_ast::token::TokenAt::Single(token) => token.range(), ruff_python_ast::token::TokenAt::Between(..) => range, }; let tokens_after = parsed.tokens().after(token_range.end()); // Same as for `line_end` when building up the `suppressions`: Ignore newlines // in multiline-strings, inside f-strings, or after a line continuation because we can't // place a comment on those lines. let line_end = tokens_after .iter() .find(|token| { matches!( token.kind(), TokenKind::Newline | TokenKind::NonLogicalNewline ) }) .map(Ranged::start) .unwrap_or(source.text_len()); let up_to_line_end = &source[..line_end.to_usize()]; let up_to_first_content = up_to_line_end.trim_end(); let trailing_whitespace_len = up_to_line_end.text_len() - up_to_first_content.text_len(); let insertion = format!(" # ty:ignore[{id}]", id = id.name()); Fix::safe_edit(if trailing_whitespace_len == TextSize::ZERO { Edit::insertion(insertion, line_end) } else { // `expr # fmt: off<trailing_whitespace>` // Trim the trailing whitespace Edit::replacement(insertion, line_end - trailing_whitespace_len, line_end) }) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/tests/mdtest.rs
crates/ty_python_semantic/tests/mdtest.rs
use anyhow::anyhow; use camino::Utf8Path; use ty_static::EnvVars; use ty_test::OutputFormat; /// See `crates/ty_test/README.md` for documentation on these tests. #[expect(clippy::needless_pass_by_value)] fn mdtest(fixture_path: &Utf8Path, content: String) -> datatest_stable::Result<()> { let short_title = fixture_path .file_name() .ok_or_else(|| anyhow!("Expected fixture path to have a file name"))?; let crate_dir = Utf8Path::new(env!("CARGO_MANIFEST_DIR")); let snapshot_path = crate_dir.join("resources").join("mdtest").join("snapshots"); let absolute_fixture_path = crate_dir.join(fixture_path); let workspace_relative_fixture_path = Utf8Path::new("crates/ty_python_semantic") .join(fixture_path.strip_prefix(".").unwrap_or(fixture_path)); let test_name = fixture_path .strip_prefix("./resources/mdtest") .unwrap_or(fixture_path) .as_str(); let output_format = if std::env::var(EnvVars::MDTEST_GITHUB_ANNOTATIONS_FORMAT).is_ok() { OutputFormat::GitHub } else { OutputFormat::Cli }; ty_test::run( &absolute_fixture_path, &workspace_relative_fixture_path, &content, &snapshot_path, short_title, test_name, output_format, )?; Ok(()) } datatest_stable::harness! { { test = mdtest, root = "./resources/mdtest", pattern = r"\.md$" }, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_python_semantic/tests/corpus.rs
crates/ty_python_semantic/tests/corpus.rs
use std::sync::Arc; use anyhow::{Context, anyhow}; use ruff_db::Db; use ruff_db::files::{File, Files, system_path_to_file}; use ruff_db::system::{DbWithTestSystem, System, SystemPath, SystemPathBuf, TestSystem}; use ruff_db::vendored::VendoredFileSystem; use ruff_python_ast::PythonVersion; use ty_module_resolver::SearchPathSettings; use ty_python_semantic::lint::{LintRegistry, RuleSelection}; use ty_python_semantic::pull_types::pull_types; use ty_python_semantic::{ AnalysisSettings, Program, ProgramSettings, PythonPlatform, PythonVersionSource, PythonVersionWithSource, default_lint_registry, }; use test_case::test_case; fn get_cargo_workspace_root() -> anyhow::Result<SystemPathBuf> { Ok(SystemPathBuf::from(String::from_utf8( std::process::Command::new("cargo") .args(["locate-project", "--workspace", "--message-format", "plain"]) .output()? .stdout, )?) .parent() .unwrap() .to_owned()) } /// Test that all snippets in testcorpus can be checked without panic (except for [`KNOWN_FAILURES`]) #[test] fn corpus_no_panic() -> anyhow::Result<()> { let crate_root = String::from(env!("CARGO_MANIFEST_DIR")); run_corpus_tests(&format!("{crate_root}/resources/corpus/**/*.py")) } #[test] fn parser_no_panic() -> anyhow::Result<()> { let workspace_root = get_cargo_workspace_root()?; run_corpus_tests(&format!( "{workspace_root}/crates/ruff_python_parser/resources/**/*.py" )) } #[test_case("a-e")] #[test_case("f")] #[test_case("g-o")] #[test_case("p")] #[test_case("q-z")] #[test_case("!a-z")] fn linter_no_panic(range: &str) -> anyhow::Result<()> { let workspace_root = get_cargo_workspace_root()?; run_corpus_tests(&format!( "{workspace_root}/crates/ruff_linter/resources/test/fixtures/[{range}]*/**/*.py" )) } #[test] fn linter_stubs_no_panic() -> anyhow::Result<()> { let workspace_root = get_cargo_workspace_root()?; run_corpus_tests(&format!( "{workspace_root}/crates/ruff_linter/resources/test/fixtures/**/*.pyi" )) } #[test_case("a-e")] #[test_case("f-k")] #[test_case("l-p")] #[test_case("q-z")] #[test_case("!a-z")] fn typeshed_no_panic(range: &str) -> anyhow::Result<()> { let workspace_root = get_cargo_workspace_root()?; run_corpus_tests(&format!( "{workspace_root}/crates/ty_vendored/vendor/typeshed/stdlib/[{range}]*.pyi" )) } #[expect(clippy::print_stdout)] fn run_corpus_tests(pattern: &str) -> anyhow::Result<()> { let root = SystemPathBuf::from("/src"); let mut db = CorpusDb::new(); db.memory_file_system().create_directory_all(&root)?; let workspace_root = get_cargo_workspace_root()?; let workspace_root = workspace_root.to_string(); let corpus = glob::glob(pattern).context("Failed to compile pattern")?; for path in corpus { let path = path.context("Failed to glob path")?; let path = SystemPathBuf::from_path_buf(path).map_err(|path| { anyhow!( "Failed to convert path '{path}' to system path", path = path.display() ) })?; let relative_path = path.strip_prefix(&workspace_root)?; let (py_expected_to_fail, pyi_expected_to_fail) = KNOWN_FAILURES .iter() .find_map(|(path, py_fail, pyi_fail)| { if *path == relative_path.as_str().replace('\\', "/") { Some((*py_fail, *pyi_fail)) } else { None } }) .unwrap_or((false, false)); let source = path.as_path(); let source_filename = source.file_name().unwrap(); let code = std::fs::read_to_string(source) .with_context(|| format!("Failed to read test file: {path}"))?; let mut check_with_file_name = |path: &SystemPath| { db.memory_file_system().write_file_all(path, &code).unwrap(); File::sync_path(&mut db, path); // this test is only asserting that we can pull every expression type without a panic // (and some non-expressions that clearly define a single type) let file = system_path_to_file(&db, path).unwrap(); let result = std::panic::catch_unwind(|| pull_types(&db, file)); let expected_to_fail = if path.extension().map(|e| e == "pyi").unwrap_or(false) { pyi_expected_to_fail } else { py_expected_to_fail }; if let Err(err) = result { if !expected_to_fail { println!( "Check failed for {relative_path:?}. Consider fixing it or adding it to KNOWN_FAILURES" ); std::panic::resume_unwind(err); } } else { assert!( !expected_to_fail, "Expected to panic, but did not. Consider removing this path from KNOWN_FAILURES" ); } db.memory_file_system().remove_file(path).unwrap(); file.sync(&mut db); }; if source.extension() == Some("pyi") { println!("checking {relative_path}"); let pyi_dest = root.join(source_filename); check_with_file_name(&pyi_dest); } else { println!("checking {relative_path}"); let py_dest = root.join(source_filename); check_with_file_name(&py_dest); let pyi_dest = root.join(format!("{source_filename}i")); println!("re-checking as stub file: {pyi_dest}"); check_with_file_name(&pyi_dest); } } Ok(()) } /// Whether or not the .py/.pyi version of this file is expected to fail #[rustfmt::skip] const KNOWN_FAILURES: &[(&str, bool, bool)] = &[ ]; #[salsa::db] #[derive(Clone)] pub struct CorpusDb { storage: salsa::Storage<Self>, files: Files, rule_selection: RuleSelection, system: TestSystem, vendored: VendoredFileSystem, analysis_settings: Arc<AnalysisSettings>, } impl CorpusDb { #[expect(clippy::new_without_default)] pub fn new() -> Self { let db = Self { storage: salsa::Storage::new(None), system: TestSystem::default(), vendored: ty_vendored::file_system().clone(), rule_selection: RuleSelection::from_registry(default_lint_registry()), files: Files::default(), analysis_settings: Arc::new(AnalysisSettings::default()), }; Program::from_settings( &db, ProgramSettings { python_version: PythonVersionWithSource { version: PythonVersion::latest_ty(), source: PythonVersionSource::default(), }, python_platform: PythonPlatform::default(), search_paths: SearchPathSettings::new(vec![]) .to_search_paths(db.system(), db.vendored()) .unwrap(), }, ); db } } impl DbWithTestSystem for CorpusDb { fn test_system(&self) -> &TestSystem { &self.system } fn test_system_mut(&mut self) -> &mut TestSystem { &mut self.system } } #[salsa::db] impl ruff_db::Db for CorpusDb { fn vendored(&self) -> &VendoredFileSystem { &self.vendored } fn system(&self) -> &dyn System { &self.system } fn files(&self) -> &Files { &self.files } fn python_version(&self) -> PythonVersion { Program::get(self).python_version(self) } } #[salsa::db] impl ty_module_resolver::Db for CorpusDb { fn search_paths(&self) -> &ty_module_resolver::SearchPaths { Program::get(self).search_paths(self) } } #[salsa::db] impl ty_python_semantic::Db for CorpusDb { fn should_check_file(&self, file: File) -> bool { !file.path(self).is_vendored_path() } fn rule_selection(&self, _file: File) -> &RuleSelection { &self.rule_selection } fn lint_registry(&self) -> &LintRegistry { default_lint_registry() } fn verbose(&self) -> bool { false } fn analysis_settings(&self) -> &AnalysisSettings { &self.analysis_settings } } #[salsa::db] impl salsa::Database for CorpusDb {}
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/round_trip.rs
crates/ruff_dev/src/round_trip.rs
//! Run round-trip source code generation on a given Python or Jupyter notebook file. use std::fs; use std::path::PathBuf; use anyhow::Result; use ruff_python_ast::PySourceType; use ruff_python_codegen::round_trip; #[derive(clap::Args)] pub(crate) struct Args { /// Python or Jupyter notebook file to round-trip. #[arg(required = true)] file: PathBuf, } pub(crate) fn main(args: &Args) -> Result<()> { let path = args.file.as_path(); if PySourceType::from(path).is_ipynb() { println!("{}", ruff_notebook::round_trip(path)?); } else { let contents = fs::read_to_string(&args.file)?; println!("{}", round_trip(&contents)?); } Ok(()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_all.rs
crates/ruff_dev/src/generate_all.rs
//! Run all code and documentation generation steps. use anyhow::Result; use crate::{ generate_cli_help, generate_docs, generate_json_schema, generate_ty_cli_reference, generate_ty_env_vars_reference, generate_ty_options, generate_ty_rules, generate_ty_schema, }; pub(crate) const REGENERATE_ALL_COMMAND: &str = "cargo dev generate-all"; #[derive(clap::Args)] pub(crate) struct Args { #[arg(long, default_value_t, value_enum)] mode: Mode, } #[derive(Copy, Clone, PartialEq, Eq, clap::ValueEnum, Default)] pub(crate) enum Mode { /// Update the content in the `configuration.md`. #[default] Write, /// Don't write to the file, check if the file is up-to-date and error if not. Check, /// Write the generated help to stdout. DryRun, } impl Mode { pub(crate) const fn is_dry_run(self) -> bool { matches!(self, Mode::DryRun) } } pub(crate) fn main(args: &Args) -> Result<()> { generate_json_schema::main(&generate_json_schema::Args { mode: args.mode })?; generate_ty_schema::main(&generate_ty_schema::Args { mode: args.mode })?; generate_cli_help::main(&generate_cli_help::Args { mode: args.mode })?; generate_docs::main(&generate_docs::Args { dry_run: args.mode.is_dry_run(), })?; generate_ty_options::main(&generate_ty_options::Args { mode: args.mode })?; generate_ty_rules::main(&generate_ty_rules::Args { mode: args.mode })?; generate_ty_cli_reference::main(&generate_ty_cli_reference::Args { mode: args.mode })?; generate_ty_env_vars_reference::main(&generate_ty_env_vars_reference::Args { mode: args.mode, })?; Ok(()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/print_ast.rs
crates/ruff_dev/src/print_ast.rs
//! Print the AST for a given Python file. use std::path::PathBuf; use anyhow::Result; use ruff_linter::source_kind::SourceKind; use ruff_python_ast::PySourceType; use ruff_python_parser::{ParseOptions, parse}; #[derive(clap::Args)] pub(crate) struct Args { /// Python file for which to generate the AST. #[arg(required = true)] file: PathBuf, } pub(crate) fn main(args: &Args) -> Result<()> { let source_type = PySourceType::from(&args.file); let source_kind = SourceKind::from_path(&args.file, source_type)?.ok_or_else(|| { anyhow::anyhow!( "Could not determine source kind for file: {}", args.file.display() ) })?; let python_ast = parse(source_kind.source_code(), ParseOptions::from(source_type))?.into_syntax(); println!("{python_ast:#?}"); Ok(()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_ty_schema.rs
crates/ruff_dev/src/generate_ty_schema.rs
use std::fs; use std::path::PathBuf; use anyhow::{Result, bail}; use pretty_assertions::StrComparison; use schemars::generate::SchemaSettings; use crate::ROOT_DIR; use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND}; use ty_project::metadata::options::Options; #[derive(clap::Args)] pub(crate) struct Args { /// Write the generated table to stdout (rather than to `ty.schema.json`). #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } pub(crate) fn main(args: &Args) -> Result<()> { let settings = SchemaSettings::draft07(); let generator = settings.into_generator(); let schema = generator.into_root_schema_for::<Options>(); let schema_string = serde_json::to_string_pretty(&schema).unwrap(); let filename = "ty.schema.json"; let schema_path = PathBuf::from(ROOT_DIR).join(filename); match args.mode { Mode::DryRun => { println!("{schema_string}"); } Mode::Check => { let current = fs::read_to_string(schema_path)?; if current == schema_string { println!("Up-to-date: {filename}"); } else { let comparison = StrComparison::new(&current, &schema_string); bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}"); } } Mode::Write => { let current = fs::read_to_string(&schema_path)?; if current == schema_string { println!("Up-to-date: {filename}"); } else { println!("Updating: {filename}"); fs::write(schema_path, schema_string.as_bytes())?; } } } Ok(()) } #[cfg(test)] mod tests { use anyhow::Result; use std::env; use crate::generate_all::Mode; use super::{Args, main}; #[test] fn test_generate_json_schema() -> Result<()> { let mode = if env::var("TY_UPDATE_SCHEMA").as_deref() == Ok("1") { Mode::Write } else { Mode::Check }; main(&Args { mode }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_ty_options.rs
crates/ruff_dev/src/generate_ty_options.rs
//! Generate a Markdown-compatible listing of configuration options for `pyproject.toml`. use std::borrow::Cow; use std::{fmt::Write, path::PathBuf}; use anyhow::bail; use itertools::Itertools; use pretty_assertions::StrComparison; use ruff_options_metadata::{OptionField, OptionSet, OptionsMetadata, Visit}; use ruff_python_trivia::textwrap; use ty_project::metadata::Options; use crate::{ ROOT_DIR, generate_all::{Mode, REGENERATE_ALL_COMMAND}, }; #[derive(clap::Args)] pub(crate) struct Args { /// Write the generated table to stdout (rather than to `crates/ty/docs/configuration.md`). #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } pub(crate) fn main(args: &Args) -> anyhow::Result<()> { let mut output = String::new(); let file_name = "crates/ty/docs/configuration.md"; let markdown_path = PathBuf::from(ROOT_DIR).join(file_name); output.push_str( "<!-- WARNING: This file is auto-generated (cargo dev generate-all). Update the doc comments on the 'Options' struct in 'crates/ty_project/src/metadata/options.rs' if you want to change anything here. -->\n\n", ); generate_set( &mut output, Set::Toplevel(Options::metadata()), &mut Vec::new(), ); match args.mode { Mode::DryRun => { println!("{output}"); } Mode::Check => { let current = std::fs::read_to_string(&markdown_path)?; if output == current { println!("Up-to-date: {file_name}",); } else { let comparison = StrComparison::new(&current, &output); bail!("{file_name} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}",); } } Mode::Write => { let current = std::fs::read_to_string(&markdown_path)?; if current == output { println!("Up-to-date: {file_name}",); } else { println!("Updating: {file_name}",); std::fs::write(markdown_path, output.as_bytes())?; } } } Ok(()) } fn generate_set(output: &mut String, set: Set, parents: &mut Vec<Set>) { match &set { Set::Toplevel(_) => { output.push_str("# Configuration\n"); } Set::Named { name, .. } => { let title = parents .iter() .filter_map(|set| set.name()) .chain(std::iter::once(name.as_str())) .join("."); writeln!(output, "## `{title}`\n",).unwrap(); } } if let Some(documentation) = set.metadata().documentation() { output.push_str(documentation); output.push('\n'); output.push('\n'); } let mut visitor = CollectOptionsVisitor::default(); set.metadata().record(&mut visitor); let (mut fields, mut sets) = (visitor.fields, visitor.groups); fields.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2)); sets.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2)); parents.push(set); // Generate the fields. for (name, field) in &fields { emit_field(output, name, field, parents.as_slice()); output.push_str("---\n\n"); } // Generate all the sub-sets. for (set_name, sub_set) in &sets { generate_set( output, Set::Named { name: set_name.clone(), set: *sub_set, }, parents, ); } parents.pop(); } #[derive(Debug)] enum Set { Toplevel(OptionSet), Named { name: String, set: OptionSet }, } impl Set { fn name(&self) -> Option<&str> { match self { Set::Toplevel(_) => None, Set::Named { name, .. } => Some(name), } } fn metadata(&self) -> &OptionSet { match self { Set::Toplevel(set) => set, Set::Named { set, .. } => set, } } } fn emit_field(output: &mut String, name: &str, field: &OptionField, parents: &[Set]) { let header_level = "#".repeat(parents.len() + 1); let _ = writeln!(output, "{header_level} `{name}`"); output.push('\n'); if let Some(deprecated) = &field.deprecated { output.push_str("!!! warning \"Deprecated\"\n"); output.push_str(" This option has been deprecated"); if let Some(since) = deprecated.since { write!(output, " in {since}").unwrap(); } output.push('.'); if let Some(message) = deprecated.message { writeln!(output, " {message}").unwrap(); } output.push('\n'); } output.push_str(field.doc); output.push_str("\n\n"); let _ = writeln!(output, "**Default value**: `{}`", field.default); output.push('\n'); let _ = writeln!(output, "**Type**: `{}`", field.value_type); output.push('\n'); output.push_str("**Example usage**:\n\n"); for configuration_file in [ConfigurationFile::PyprojectToml, ConfigurationFile::TyToml] { let (header, example) = format_snippet(field.scope, field.example, parents, configuration_file); output.push_str(&format_tab(configuration_file.name(), &header, &example)); output.push('\n'); } } fn format_tab(tab_name: &str, header: &str, content: &str) -> String { let header = if header.is_empty() { String::new() } else { format!("\n {header}") }; format!( "=== \"{}\"\n\n ```toml{}\n{}\n ```\n", tab_name, header, textwrap::indent(content, " ") ) } /// Format the TOML header for the example usage for a given option. /// /// For example: `[tool.ty.rules]`. fn format_snippet<'a>( scope: Option<&str>, example: &'a str, parents: &[Set], configuration: ConfigurationFile, ) -> (String, Cow<'a, str>) { let mut example = Cow::Borrowed(example); let header = configuration .parent_table() .into_iter() .chain(parents.iter().filter_map(|parent| parent.name())) .chain(scope) .join("."); // Rewrite examples starting with `[tool.ty]` or `[[tool.ty]]` to their `ty.toml` equivalent. if matches!(configuration, ConfigurationFile::TyToml) { example = example.replace("[tool.ty.", "[").into(); } // Ex) `[[tool.ty.xx]]` if example.starts_with(&format!("[[{header}")) { return (String::new(), example); } // Ex) `[tool.ty.rules]` if example.starts_with(&format!("[{header}")) { return (String::new(), example); } if header.is_empty() { (String::new(), example) } else { (format!("[{header}]"), example) } } #[derive(Default)] struct CollectOptionsVisitor { groups: Vec<(String, OptionSet)>, fields: Vec<(String, OptionField)>, } impl Visit for CollectOptionsVisitor { fn record_set(&mut self, name: &str, group: OptionSet) { self.groups.push((name.to_owned(), group)); } fn record_field(&mut self, name: &str, field: OptionField) { self.fields.push((name.to_owned(), field)); } } #[derive(Debug, Copy, Clone)] enum ConfigurationFile { PyprojectToml, TyToml, } impl ConfigurationFile { const fn name(self) -> &'static str { match self { Self::PyprojectToml => "pyproject.toml", Self::TyToml => "ty.toml", } } const fn parent_table(self) -> Option<&'static str> { match self { Self::PyprojectToml => Some("tool.ty"), Self::TyToml => None, } } } #[cfg(test)] mod tests { use anyhow::Result; use crate::generate_all::Mode; use super::{Args, main}; #[test] fn ty_configuration_markdown_up_to_date() -> Result<()> { main(&Args { mode: Mode::Check })?; Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/print_tokens.rs
crates/ruff_dev/src/print_tokens.rs
//! Print the token stream for a given Python file. use std::path::PathBuf; use anyhow::Result; use ruff_linter::source_kind::SourceKind; use ruff_python_ast::PySourceType; use ruff_python_parser::parse_unchecked_source; #[derive(clap::Args)] pub(crate) struct Args { /// Python file for which to generate the AST. #[arg(required = true)] file: PathBuf, } pub(crate) fn main(args: &Args) -> Result<()> { let source_type = PySourceType::from(&args.file); let source_kind = SourceKind::from_path(&args.file, source_type)?.ok_or_else(|| { anyhow::anyhow!( "Could not determine source kind for file: {}", args.file.display() ) })?; let parsed = parse_unchecked_source(source_kind.source_code(), source_type); for token in parsed.tokens() { println!("{token:#?}"); } Ok(()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_json_schema.rs
crates/ruff_dev/src/generate_json_schema.rs
use std::fs; use std::path::PathBuf; use anyhow::{Result, bail}; use pretty_assertions::StrComparison; use schemars::generate::SchemaSettings; use crate::ROOT_DIR; use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND}; use ruff_workspace::options::Options; #[derive(clap::Args)] pub(crate) struct Args { /// Write the generated table to stdout (rather than to `ruff.schema.json`). #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } pub(crate) fn main(args: &Args) -> Result<()> { let settings = SchemaSettings::draft07(); let generator = settings.into_generator(); let schema = generator.into_root_schema_for::<Options>(); let schema_string = serde_json::to_string_pretty(&schema).unwrap(); let filename = "ruff.schema.json"; let schema_path = PathBuf::from(ROOT_DIR).join(filename); match args.mode { Mode::DryRun => { println!("{schema_string}"); } Mode::Check => { let current = fs::read_to_string(schema_path)?; if current == schema_string { println!("Up-to-date: {filename}"); } else { let comparison = StrComparison::new(&current, &schema_string); bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}"); } } Mode::Write => { let current = fs::read_to_string(&schema_path)?; if current == schema_string { println!("Up-to-date: {filename}"); } else { println!("Updating: {filename}"); fs::write(schema_path, schema_string.as_bytes())?; } } } Ok(()) } #[cfg(test)] mod tests { use anyhow::Result; use std::env; use crate::generate_all::Mode; use super::{Args, main}; #[test] fn test_generate_json_schema() -> Result<()> { let mode = if env::var("RUFF_UPDATE_SCHEMA").as_deref() == Ok("1") { Mode::Write } else { Mode::Check }; main(&Args { mode }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/print_cst.rs
crates/ruff_dev/src/print_cst.rs
//! Print the `LibCST` CST for a given Python file. use std::fs; use std::path::PathBuf; use anyhow::{Result, bail}; #[derive(clap::Args)] pub(crate) struct Args { /// Python file for which to generate the CST. #[arg(required = true)] file: PathBuf, } pub(crate) fn main(args: &Args) -> Result<()> { let contents = fs::read_to_string(&args.file)?; match libcst_native::parse_module(&contents, None) { Ok(python_cst) => { println!("{python_cst:#?}"); Ok(()) } Err(_) => bail!("Failed to parse CST"), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/format_dev.rs
crates/ruff_dev/src/format_dev.rs
use std::fmt::{Display, Formatter}; use std::fs::File; use std::io::{BufWriter, Write}; use std::num::NonZeroU16; use std::ops::{Add, AddAssign}; use std::panic::catch_unwind; use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::time::{Duration, Instant}; use std::{fmt, fs, io, iter}; use anyhow::{Context, Error, bail, format_err}; use clap::{CommandFactory, FromArgMatches}; use imara_diff::intern::InternedInput; use imara_diff::sink::Counter; use imara_diff::{Algorithm, diff}; use indicatif::ProgressStyle; #[cfg_attr(feature = "singlethreaded", allow(unused_imports))] use rayon::iter::{IntoParallelIterator, ParallelIterator}; use serde::Deserialize; use similar::{ChangeTag, TextDiff}; use tempfile::NamedTempFile; use tracing::{debug, error, info, info_span}; use tracing_indicatif::IndicatifLayer; use tracing_indicatif::span_ext::IndicatifSpanExt; use tracing_subscriber::EnvFilter; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use ruff::args::{ConfigArguments, FormatArguments, FormatCommand, GlobalConfigArgs, LogLevelArgs}; use ruff::resolve::resolve; use ruff_formatter::{FormatError, LineWidth, PrintError}; use ruff_linter::logging::LogLevel; use ruff_linter::settings::types::{FilePattern, FilePatternSet}; use ruff_python_formatter::{ FormatModuleError, MagicTrailingComma, PreviewMode, PyFormatOptions, format_module_source, }; use ruff_python_parser::ParseError; use ruff_workspace::resolver::{PyprojectConfig, ResolvedFile, Resolver, python_files_in_path}; fn parse_cli(dirs: &[PathBuf]) -> anyhow::Result<(FormatArguments, ConfigArguments)> { let args_matches = FormatCommand::command() .no_binary_name(true) .get_matches_from(dirs); let arguments: FormatCommand = FormatCommand::from_arg_matches(&args_matches)?; let (cli, config_arguments) = arguments.partition(GlobalConfigArgs::default())?; Ok((cli, config_arguments)) } /// Find the [`PyprojectConfig`] to use for formatting. fn find_pyproject_config( cli: &FormatArguments, config_arguments: &ConfigArguments, ) -> anyhow::Result<PyprojectConfig> { let mut pyproject_config = resolve(config_arguments, cli.stdin_filename.as_deref())?; // We don't want to format pyproject.toml pyproject_config.settings.file_resolver.include = FilePatternSet::try_from_iter([ FilePattern::Builtin("*.py"), FilePattern::Builtin("*.pyi"), ]) .unwrap(); Ok(pyproject_config) } /// Find files that ruff would check so we can format them. Adapted from `ruff`. fn ruff_check_paths<'a>( pyproject_config: &'a PyprojectConfig, cli: &FormatArguments, config_arguments: &ConfigArguments, ) -> anyhow::Result<(Vec<Result<ResolvedFile, ignore::Error>>, Resolver<'a>)> { let (paths, resolver) = python_files_in_path(&cli.files, pyproject_config, config_arguments)?; Ok((paths, resolver)) } /// Collects statistics over the formatted files to compute the Jaccard index or the similarity /// index. /// /// If we define `B` as the black formatted input and `R` as the ruff formatted output, then /// * `B∩R`: Unchanged lines, neutral in the diff /// * `B\R`: Black only lines, minus in the diff /// * `R\B`: Ruff only lines, plus in the diff /// /// The [Jaccard index](https://en.wikipedia.org/wiki/Jaccard_index) can be defined as /// ```text /// J(B, R) = |B∩R| / (|B\R| + |R\B| + |B∩R|) /// ``` /// which you can read as number unchanged lines in the diff divided by all lines in the diff. If /// the input is not black formatted, this only becomes a measure for the changes made to the /// codebase during the initial formatting. /// /// Another measure is the similarity index, the percentage of unchanged lines. We compute it as /// ```text /// Sim(B, R) = |B∩R| / (|B\R| + |B∩R|) /// ``` /// which you can alternatively read as all lines in the input #[derive(Default, Debug, Copy, Clone)] pub(crate) struct Statistics { /// The size of `A\B`, the number of lines only in the input, which we assume to be black /// formatted black_input: u32, /// The size of `B\A`, the number of lines only in the formatted output ruff_output: u32, /// The number of matching identical lines intersection: u32, /// Files that have differences files_with_differences: u32, } impl Statistics { pub(crate) fn from_versions(black: &str, ruff: &str) -> Self { if black == ruff { let intersection = u32::try_from(black.lines().count()).unwrap(); Self { black_input: 0, ruff_output: 0, intersection, files_with_differences: 0, } } else { // `similar` was too slow (for some files >90% diffing instead of formatting) let input = InternedInput::new(black, ruff); let changes = diff(Algorithm::Histogram, &input, Counter::default()); assert_eq!( input.before.len() - (changes.removals as usize), input.after.len() - (changes.insertions as usize) ); Self { black_input: changes.removals, ruff_output: changes.insertions, intersection: u32::try_from(input.before.len()).unwrap() - changes.removals, files_with_differences: 1, } } } /// We currently prefer the similarity index, but i'd like to keep this around #[expect(clippy::cast_precision_loss, unused)] pub(crate) fn jaccard_index(&self) -> f32 { self.intersection as f32 / (self.black_input + self.ruff_output + self.intersection) as f32 } #[expect(clippy::cast_precision_loss)] pub(crate) fn similarity_index(&self) -> f32 { self.intersection as f32 / (self.black_input + self.intersection) as f32 } } impl Add<Statistics> for Statistics { type Output = Statistics; fn add(self, rhs: Statistics) -> Self::Output { Statistics { black_input: self.black_input + rhs.black_input, ruff_output: self.ruff_output + rhs.ruff_output, intersection: self.intersection + rhs.intersection, files_with_differences: self.files_with_differences + rhs.files_with_differences, } } } impl AddAssign<Statistics> for Statistics { fn add_assign(&mut self, rhs: Statistics) { *self = *self + rhs; } } /// Control the verbosity of the output #[derive(Copy, Clone, PartialEq, Eq, clap::ValueEnum, Default)] pub(crate) enum Format { /// Filenames only Minimal, /// Filenames and reduced diff #[default] Default, /// Full diff and invalid code Full, } #[expect(clippy::struct_excessive_bools)] #[derive(clap::Args)] pub(crate) struct Args { /// Like `ruff check`'s files. See `--multi-project` if you want to format an ecosystem /// checkout. pub(crate) files: Vec<PathBuf>, /// Check stability /// /// We want to ensure that once formatted content stays the same when formatted again, which is /// known as formatter stability or formatter idempotency, and that the formatter prints /// syntactically valid code. As our test cases cover only a limited amount of code, this allows /// checking entire repositories. #[arg(long)] pub(crate) stability_check: bool, /// Format the files. Without this flag, the python files are not modified #[arg(long)] pub(crate) write: bool, #[arg(long)] pub(crate) preview: bool, /// Control the verbosity of the output #[arg(long, default_value_t, value_enum)] pub(crate) format: Format, /// Print only the first error and exit, `-x` is same as pytest #[arg(long, short = 'x')] pub(crate) exit_first_error: bool, /// Checks each project inside a directory, useful e.g. if you want to check all of the /// ecosystem checkouts. #[arg(long)] pub(crate) multi_project: bool, /// Write all errors to this file in addition to stdout. Only used in multi-project mode. #[arg(long)] pub(crate) error_file: Option<PathBuf>, /// Write all log messages (same as cli) to this file #[arg(long)] pub(crate) log_file: Option<PathBuf>, /// Write a markdown table with the similarity indices to this file #[arg(long)] pub(crate) stats_file: Option<PathBuf>, /// Assert that there are exactly this many input files with errors. This catches regressions /// (or improvements) in the parser. #[arg(long)] pub(crate) files_with_errors: Option<u32>, #[clap(flatten)] #[expect(clippy::struct_field_names)] pub(crate) log_level_args: LogLevelArgs, } pub(crate) fn main(args: &Args) -> anyhow::Result<ExitCode> { setup_logging(&args.log_level_args, args.log_file.as_deref())?; let mut error_file = match &args.error_file { Some(error_file) => Some(BufWriter::new( File::create(error_file).context("Couldn't open error file")?, )), None => None, }; let all_success = if args.multi_project { format_dev_multi_project(args, error_file)? } else { let result = format_dev_project(&args.files, args.stability_check, args.write, args.preview)?; let error_count = result.error_count(); if result.error_count() > 0 { error!(parent: None, "{}", result.display(args.format)); } if let Some(error_file) = &mut error_file { write!(error_file, "{}", result.display(args.format)).unwrap(); } info!( parent: None, "Done: {error_count} stability/syntax errors, {} files, similarity index {:.5}), files with differences: {} took {:.2}s, {} input files contained syntax errors ", result.file_count, result.statistics.similarity_index(), result.statistics.files_with_differences, result.duration.as_secs_f32(), result.syntax_error_in_input, ); if let Some(files_with_errors) = args.files_with_errors { if result.syntax_error_in_input != files_with_errors { error!( "Expected {files_with_errors} input files with errors, found {}", result.syntax_error_in_input ); return Ok(ExitCode::FAILURE); } } error_count == 0 }; if all_success { Ok(ExitCode::SUCCESS) } else { Ok(ExitCode::FAILURE) } } fn setup_logging(log_level_args: &LogLevelArgs, log_file: Option<&Path>) -> io::Result<()> { // Custom translation since we need the tracing type for `EnvFilter` let log_level = match LogLevel::from(log_level_args) { LogLevel::Default => tracing::Level::INFO, LogLevel::Verbose => tracing::Level::DEBUG, LogLevel::Quiet => tracing::Level::WARN, LogLevel::Silent => tracing::Level::ERROR, }; // 1. `RUST_LOG=`, 2. explicit CLI log level, 3. info, the ruff default let filter_layer = EnvFilter::try_from_default_env().unwrap_or_else(|_| { EnvFilter::builder() .with_default_directive(log_level.into()) .parse_lossy("") }); let indicatif_layer = IndicatifLayer::new().with_progress_style( // Default without the spinner ProgressStyle::with_template("{span_child_prefix} {span_name}{{{span_fields}}}").unwrap(), ); let indicitif_compatible_writer_layer = tracing_subscriber::fmt::layer() .with_writer(indicatif_layer.get_stderr_writer()) .with_target(false); let log_layer = log_file.map(File::create).transpose()?.map(|log_file| { tracing_subscriber::fmt::layer() .with_writer(log_file) .with_ansi(false) }); tracing_subscriber::registry() .with(filter_layer) .with(indicitif_compatible_writer_layer) .with(indicatif_layer) .with(log_layer) .init(); Ok(()) } /// Checks a directory of projects fn format_dev_multi_project( args: &Args, mut error_file: Option<BufWriter<File>>, ) -> anyhow::Result<bool> { let mut total_errors = 0; let mut total_files = 0; let mut total_syntax_error_in_input = 0; let start = Instant::now(); let mut project_paths = Vec::new(); for directory in &args.files { for project_directory in directory .read_dir() .with_context(|| "Failed to read projects directory '{directory}'")? { project_paths.push( project_directory .with_context(|| "Failed to read project directory '{project_directory}'")? .path(), ); } } let pb_span = info_span!("format_dev_multi_project progress bar"); pb_span.pb_set_style(&ProgressStyle::default_bar()); pb_span.pb_set_length(project_paths.len() as u64); let pb_span_enter = pb_span.enter(); let mut results = Vec::new(); for project_path in project_paths { debug!(parent: None, "Starting {}", project_path.display()); match format_dev_project( std::slice::from_ref(&project_path), args.stability_check, args.write, args.preview, ) { Ok(result) => { total_errors += result.error_count(); total_files += result.file_count; total_syntax_error_in_input += result.syntax_error_in_input; info!( parent: None, "Finished {}: {} stability errors, {} files, similarity index {:.5}), files with differences {}, took {:.2}s, {} input files contained syntax errors ", project_path.display(), result.error_count(), result.file_count, result.statistics.similarity_index(), result.statistics.files_with_differences, result.duration.as_secs_f32(), result.syntax_error_in_input, ); if result.error_count() > 0 { error!( parent: None, "{}", result.display(args.format).to_string().trim_end() ); } if let Some(error_file) = &mut error_file { write!(error_file, "{}", result.display(args.format)).unwrap(); } results.push(result); pb_span.pb_inc(1); } Err(error) => { error!(parent: None, "Failed {}: {}", project_path.display(), error); pb_span.pb_inc(1); } } } drop(pb_span_enter); drop(pb_span); let duration = start.elapsed(); info!( parent: None, "Finished: {total_errors} stability errors, {total_files} files, tool {}s, {total_syntax_error_in_input} input files contained syntax errors ", duration.as_secs_f32(), ); if let Some(stats_file) = &args.stats_file { results.sort_by(|result1, result2| result1.name.cmp(&result2.name)); let project_col_len = results .iter() .map(|result| result.name.len()) .chain(iter::once("project".len())) .max() .unwrap_or_default(); let mut stats_file = BufWriter::new(File::create(stats_file)?); writeln!( stats_file, "| {:<project_col_len$} | similarity index | total files | changed files |", "project" )?; writeln!( stats_file, "|-{:-<project_col_len$}-|------------------:|------------------:|------------------:|", "" )?; for result in results { writeln!( stats_file, "| {:<project_col_len$} | {:.5} | {:5} | {:5} |", result.name, result.statistics.similarity_index(), result.file_count, result.statistics.files_with_differences )?; } } if let Some(files_with_errors) = args.files_with_errors { if total_syntax_error_in_input != files_with_errors { error!( "Expected {files_with_errors} input files with errors, found {}", total_syntax_error_in_input ); return Ok(false); } } Ok(total_errors == 0) } #[tracing::instrument] fn format_dev_project( files: &[PathBuf], stability_check: bool, write: bool, preview: bool, ) -> anyhow::Result<CheckRepoResult> { let start = Instant::now(); // TODO(konstin): The assumptions between this script (one repo) and ruff (pass in a bunch of // files) mismatch. let black_options = BlackOptions::from_file(&files[0])?; debug!( parent: None, "Options for {}: {black_options:?}", files[0].display() ); // TODO(konstin): Respect black's excludes. // Find files to check (or in this case, format twice). Adapted from ruff // First argument is ignored let (cli, overrides) = parse_cli(files)?; let pyproject_config = find_pyproject_config(&cli, &overrides)?; let (paths, resolver) = ruff_check_paths(&pyproject_config, &cli, &overrides)?; if paths.is_empty() { bail!("No Python files found under the given path(s)"); } let results = { let pb_span = info_span!("format_dev_project progress bar", first_file = %files[0].display()); pb_span.pb_set_style(&ProgressStyle::default_bar()); pb_span.pb_set_length(paths.len() as u64); let _pb_span_enter = pb_span.enter(); #[cfg(not(feature = "singlethreaded"))] let iter = { paths.into_par_iter() }; #[cfg(feature = "singlethreaded")] let iter = { paths.into_iter() }; iter.map(|path| { let result = format_dir_entry( path, stability_check, write, preview, &black_options, &resolver, ); pb_span.pb_inc(1); result }) .collect::<anyhow::Result<Vec<_>>>()? }; let mut statistics = Statistics::default(); let mut formatted_counter = 0; let mut syntax_error_in_input = 0; let mut diagnostics = Vec::new(); for (result, file) in results { formatted_counter += 1; match result { Ok(statistics_file) => statistics += statistics_file, Err(error) => { match error { CheckFileError::SyntaxErrorInInput(error) => { // This is not our error debug!( parent: None, "Syntax error in {}: {}", file.display(), error ); syntax_error_in_input += 1; } _ => diagnostics.push(Diagnostic { file, error }), } } } } let duration = start.elapsed(); let name = files[0] .file_name() .unwrap_or(files[0].as_os_str()) .to_string_lossy() .to_string(); Ok(CheckRepoResult { name, duration, file_count: formatted_counter, diagnostics, statistics, syntax_error_in_input, }) } /// Error handling in between walkdir and `format_dev_file`. fn format_dir_entry( resolved_file: Result<ResolvedFile, ignore::Error>, stability_check: bool, write: bool, preview: bool, options: &BlackOptions, resolver: &Resolver, ) -> anyhow::Result<(Result<Statistics, CheckFileError>, PathBuf), Error> { let resolved_file = resolved_file.context("Iterating the files in the repository failed")?; // For some reason it does not filter in the beginning if resolved_file.file_name() == "pyproject.toml" { return Ok((Ok(Statistics::default()), resolved_file.into_path())); } let path = resolved_file.into_path(); let mut options = options.to_py_format_options(&path); if preview { options = options.with_preview(PreviewMode::Enabled); } let settings = resolver.resolve(&path); // That's a bad way of doing this but it's not worth doing something better for format_dev if settings.formatter.line_width != LineWidth::default() { options = options.with_line_width(settings.formatter.line_width); } // Handle panics (mostly in `debug_assert!`) let result = catch_unwind(|| format_dev_file(&path, stability_check, write, options)) .unwrap_or_else(|panic| { if let Some(message) = panic.downcast_ref::<String>() { Err(CheckFileError::Panic { message: message.clone(), }) } else if let Some(&message) = panic.downcast_ref::<&str>() { Err(CheckFileError::Panic { message: message.to_string(), }) } else { Err(CheckFileError::Panic { // This should not happen, but it can message: "(Panic didn't set a string message)".to_string(), }) } }); Ok((result, path)) } /// A compact diff that only shows a header and changes, but nothing unchanged. This makes viewing /// multiple errors easier. fn diff_show_only_changes( writer: &mut Formatter, formatted: &str, reformatted: &str, ) -> fmt::Result { for changes in TextDiff::from_lines(formatted, reformatted) .unified_diff() .iter_hunks() { for (idx, change) in changes .iter_changes() .filter(|change| change.tag() != ChangeTag::Equal) .enumerate() { if idx == 0 { writeln!(writer, "{}", changes.header())?; } write!(writer, "{}", change.tag())?; writer.write_str(change.value())?; } } Ok(()) } struct CheckRepoResult { name: String, duration: Duration, file_count: usize, diagnostics: Vec<Diagnostic>, statistics: Statistics, syntax_error_in_input: u32, } impl CheckRepoResult { fn display(&self, format: Format) -> DisplayCheckRepoResult<'_> { DisplayCheckRepoResult { result: self, format, } } /// Count the actual errors excluding invalid input files and io errors fn error_count(&self) -> usize { self.diagnostics .iter() .filter(|diagnostics| !diagnostics.error.is_success()) .count() } } struct DisplayCheckRepoResult<'a> { result: &'a CheckRepoResult, format: Format, } impl Display for DisplayCheckRepoResult<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { for diagnostic in &self.result.diagnostics { write!(f, "{}", diagnostic.display(self.format))?; } Ok(()) } } #[derive(Debug)] struct Diagnostic { file: PathBuf, error: CheckFileError, } impl Diagnostic { fn display(&self, format: Format) -> DisplayDiagnostic<'_> { DisplayDiagnostic { diagnostic: self, format, } } } struct DisplayDiagnostic<'a> { format: Format, diagnostic: &'a Diagnostic, } impl Display for DisplayDiagnostic<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let Diagnostic { file, error } = &self.diagnostic; match error { CheckFileError::Unstable { formatted, reformatted, } => { writeln!(f, "Unstable formatting {}", file.display())?; match self.format { Format::Minimal => {} Format::Default => { diff_show_only_changes(f, formatted, reformatted)?; } Format::Full => { let diff = TextDiff::from_lines(formatted.as_str(), reformatted.as_str()) .unified_diff() .header("Formatted once", "Formatted twice") .to_string(); writeln!( f, r#"Reformatting the formatted code a second time resulted in formatting changes. --- {diff}--- Formatted once: --- {formatted}--- Formatted twice: --- {reformatted}---\n"#, )?; } } } CheckFileError::Panic { message } => { writeln!(f, "Panic {}: {}", file.display(), message)?; } CheckFileError::SyntaxErrorInInput(error) => { writeln!(f, "Syntax error in {}: {}", file.display(), error)?; } CheckFileError::SyntaxErrorInOutput { formatted, error } => { writeln!( f, "Formatter generated invalid syntax {}: {}", file.display(), error )?; if self.format == Format::Full { writeln!(f, "---\n{formatted}\n---\n")?; } } CheckFileError::FormatError(error) => { writeln!(f, "Formatter error for {}: {}", file.display(), error)?; } CheckFileError::PrintError(error) => { writeln!(f, "Printer error for {}: {}", file.display(), error)?; } CheckFileError::IoError(error) => { writeln!(f, "Error reading {}: {}", file.display(), error)?; } #[cfg(not(debug_assertions))] CheckFileError::Slow(duration) => { writeln!( f, "Slow formatting {}: Formatting the file took {}ms", file.display(), duration.as_millis() )?; } } Ok(()) } } #[derive(Debug)] enum CheckFileError { /// First and second pass of the formatter are different Unstable { formatted: String, reformatted: String, }, /// The input file was already invalid (not a bug) SyntaxErrorInInput(ParseError), /// The formatter introduced a syntax error SyntaxErrorInOutput { formatted: String, error: ParseError, }, /// The formatter failed (bug) FormatError(FormatError), /// The printer failed (bug) PrintError(PrintError), /// Failed to read the file, this sometimes happens e.g. with strange filenames (not a bug) IoError(io::Error), /// From `catch_unwind` Panic { message: String }, /// Formatting a file took too long #[cfg(not(debug_assertions))] Slow(Duration), } impl CheckFileError { /// Returns `false` if this is a formatter bug or `true` is if it is something outside of ruff fn is_success(&self) -> bool { match self { CheckFileError::SyntaxErrorInInput(_) | CheckFileError::IoError(_) => true, CheckFileError::Unstable { .. } | CheckFileError::SyntaxErrorInOutput { .. } | CheckFileError::FormatError(_) | CheckFileError::PrintError(_) | CheckFileError::Panic { .. } => false, #[cfg(not(debug_assertions))] CheckFileError::Slow(_) => true, } } } impl From<io::Error> for CheckFileError { fn from(value: io::Error) -> Self { Self::IoError(value) } } #[tracing::instrument(skip_all, fields(input_path = % input_path.display()))] fn format_dev_file( input_path: &Path, stability_check: bool, write: bool, options: PyFormatOptions, ) -> Result<Statistics, CheckFileError> { let content = fs::read_to_string(input_path)?; #[cfg(not(debug_assertions))] let start = Instant::now(); let printed = match format_module_source(&content, options.clone()) { Ok(printed) => printed, Err(FormatModuleError::ParseError(err)) => { return Err(CheckFileError::SyntaxErrorInInput(err)); } Err(FormatModuleError::FormatError(err)) => { return Err(CheckFileError::FormatError(err)); } Err(FormatModuleError::PrintError(err)) => { return Err(CheckFileError::PrintError(err)); } }; let formatted = printed.as_code(); #[cfg(not(debug_assertions))] let format_duration = Instant::now() - start; if write && content != formatted { // Simple atomic write. // The file is in a directory so it must have a parent. Surprisingly `DirEntry` doesn't // give us access without unwrap let mut file = NamedTempFile::new_in(input_path.parent().unwrap())?; file.write_all(formatted.as_bytes())?; // "If a file exists at the target path, persist will atomically replace it." file.persist(input_path).map_err(|error| error.error)?; } if stability_check { let reformatted = match format_module_source(formatted, options) { Ok(reformatted) => reformatted, Err(FormatModuleError::ParseError(err)) => { return Err(CheckFileError::SyntaxErrorInOutput { formatted: formatted.to_string(), error: err, }); } Err(FormatModuleError::FormatError(err)) => { return Err(CheckFileError::FormatError(err)); } Err(FormatModuleError::PrintError(err)) => { return Err(CheckFileError::PrintError(err)); } }; if reformatted.as_code() != formatted { return Err(CheckFileError::Unstable { formatted: formatted.to_string(), reformatted: reformatted.into_code(), }); } } #[cfg(not(debug_assertions))] if format_duration > Duration::from_millis(50) { return Err(CheckFileError::Slow(format_duration)); } Ok(Statistics::from_versions(&content, formatted)) } #[derive(Deserialize, Default)] struct PyprojectToml { tool: Option<PyprojectTomlTool>, } #[derive(Deserialize, Default)] struct PyprojectTomlTool { black: Option<BlackOptions>, } #[derive(Deserialize, Debug)] #[serde(default)] struct BlackOptions { // Black actually allows both snake case and kebab case #[serde(alias = "line-length")] line_length: NonZeroU16, #[serde(alias = "skip-magic-trailing-comma")] skip_magic_trailing_comma: bool, preview: bool, } impl Default for BlackOptions { fn default() -> Self { Self { line_length: NonZeroU16::new(88).unwrap(), skip_magic_trailing_comma: false, preview: false, } } } impl BlackOptions { /// TODO(konstin): For the real version, fix printing of error chains and remove the path /// argument fn from_toml(toml: &str, path: &Path) -> anyhow::Result<Self> { let pyproject_toml: PyprojectToml = toml::from_str(toml).map_err(|e| { format_err!( "Not a valid pyproject.toml toml file at {}: {e}", path.display() ) })?; let black_options = pyproject_toml .tool .unwrap_or_default() .black .unwrap_or_default(); debug!( "Found {}, setting black options: {:?}", path.display(), &black_options ); Ok(black_options) } fn from_file(repo: &Path) -> anyhow::Result<Self> { let path = repo.join("pyproject.toml"); if !path.is_file() { debug!( "No pyproject.toml at {}, using black option defaults", path.display() ); return Ok(Self::default()); } Self::from_toml(&fs::read_to_string(&path)?, repo) } fn to_py_format_options(&self, file: &Path) -> PyFormatOptions { PyFormatOptions::from_extension(file) .with_line_width(LineWidth::from(self.line_length)) .with_magic_trailing_comma(if self.skip_magic_trailing_comma { MagicTrailingComma::Ignore } else { MagicTrailingComma::Respect }) .with_preview(if self.preview {
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_docs.rs
crates/ruff_dev/src/generate_docs.rs
//! Generate Markdown documentation for applicable rules. use std::collections::HashSet; use std::fmt::Write as _; use std::fs; use std::path::PathBuf; use anyhow::Result; use itertools::Itertools; use regex::{Captures, Regex}; use ruff_linter::codes::RuleGroup; use strum::IntoEnumIterator; use ruff_linter::FixAvailability; use ruff_linter::registry::{Linter, Rule, RuleNamespace}; use ruff_options_metadata::{OptionEntry, OptionsMetadata}; use ruff_workspace::options::Options; use crate::ROOT_DIR; #[derive(clap::Args)] pub(crate) struct Args { /// Write the generated docs to stdout (rather than to the filesystem). #[arg(long)] pub(crate) dry_run: bool, } pub(crate) fn main(args: &Args) -> Result<()> { for rule in Rule::iter() { if let Some(explanation) = rule.explanation() { let mut output = String::new(); let _ = writeln!(&mut output, "# {} ({})", rule.name(), rule.noqa_code()); let status_text = match rule.group() { RuleGroup::Stable { since } => { format!( r#"Added in <a href="https://github.com/astral-sh/ruff/releases/tag/{since}">{since}</a>"# ) } RuleGroup::Preview { since } => { format!( r#"Preview (since <a href="https://github.com/astral-sh/ruff/releases/tag/{since}">{since}</a>)"# ) } RuleGroup::Deprecated { since } => { format!( r#"Deprecated (since <a href="https://github.com/astral-sh/ruff/releases/tag/{since}">{since}</a>)"# ) } RuleGroup::Removed { since } => { format!( r#"Removed (since <a href="https://github.com/astral-sh/ruff/releases/tag/{since}">{since}</a>)"# ) } }; let _ = writeln!( &mut output, r#"<small> {status_text} · <a href="https://github.com/astral-sh/ruff/issues?q=sort%3Aupdated-desc%20is%3Aissue%20is%3Aopen%20(%27{encoded_name}%27%20OR%20{rule_code})" target="_blank">Related issues</a> · <a href="https://github.com/astral-sh/ruff/blob/main/{file}#L{line}" target="_blank">View source</a> </small> "#, encoded_name = url::form_urlencoded::byte_serialize(rule.name().as_str().as_bytes()) .collect::<String>(), rule_code = rule.noqa_code(), file = url::form_urlencoded::byte_serialize(rule.file().replace('\\', "/").as_bytes()) .collect::<String>(), line = rule.line(), ); let (linter, _) = Linter::parse_code(&rule.noqa_code().to_string()).unwrap(); if linter.url().is_some() { let common_prefix: String = match linter.common_prefix() { "" => linter .upstream_categories() .unwrap() .iter() .map(|c| c.prefix) .join("-"), prefix => prefix.to_string(), }; let anchor = format!( "{}-{}", linter.name().to_lowercase(), common_prefix.to_lowercase() ); let _ = write!( output, "Derived from the **[{}](../rules.md#{})** linter.", linter.name(), anchor, ); output.push('\n'); output.push('\n'); } if rule.is_deprecated() { output.push_str( r"**Warning: This rule is deprecated and will be removed in a future release.**", ); output.push('\n'); output.push('\n'); } if rule.is_removed() { output.push_str( r"**Warning: This rule has been removed and its documentation is only available for historical reasons.**", ); output.push('\n'); output.push('\n'); } let fix_availability = rule.fixable(); if matches!( fix_availability, FixAvailability::Always | FixAvailability::Sometimes ) { output.push_str(&fix_availability.to_string()); output.push('\n'); output.push('\n'); } if rule.is_preview() { output.push_str( r"This rule is unstable and in [preview](../preview.md). The `--preview` flag is required for use.", ); output.push('\n'); output.push('\n'); } process_documentation( explanation.trim(), &mut output, &rule.noqa_code().to_string(), ); let filename = PathBuf::from(ROOT_DIR) .join("docs") .join("rules") .join(&*rule.name()) .with_extension("md"); if args.dry_run { println!("{output}"); } else { fs::create_dir_all("docs/rules")?; fs::write(filename, output)?; } } } Ok(()) } fn process_documentation(documentation: &str, out: &mut String, rule_name: &str) { let mut in_options = false; let mut after = String::new(); let mut referenced_options = HashSet::new(); // HACK: This is an ugly regex hack that's necessary because mkdocs uses // a non-CommonMark-compliant Markdown parser, which doesn't support code // tags in link definitions // (see https://github.com/Python-Markdown/markdown/issues/280). let documentation = Regex::new(r"\[`([^`]*?)`]($|[^\[(])").unwrap().replace_all( documentation, |caps: &Captures| { format!( "[`{option}`][{option}]{sep}", option = &caps[1], sep = &caps[2] ) }, ); for line in documentation.split_inclusive('\n') { if line.starts_with("## ") { in_options = line == "## Options\n"; } else if in_options { if let Some(rest) = line.strip_prefix("- `") { let option = rest.trim_end().trim_end_matches('`'); match Options::metadata().find(option) { Some(OptionEntry::Field(field)) => { if field.deprecated.is_some() { eprintln!("Rule {rule_name} references deprecated option {option}."); } } Some(_) => {} None => { panic!("Unknown option {option} referenced by rule {rule_name}"); } } let anchor = option.replace('.', "_"); let _ = writeln!(out, "- [`{option}`][{option}]"); let _ = writeln!(&mut after, "[{option}]: ../settings.md#{anchor}"); referenced_options.insert(option); continue; } } out.push_str(line); } let re = Regex::new(r"\[`([^`]*?)`]\[(.*?)]").unwrap(); for (_, [option, _]) in re.captures_iter(&documentation).map(|c| c.extract()) { if let Some(OptionEntry::Field(field)) = Options::metadata().find(option) { if referenced_options.insert(option) { let anchor = option.replace('.', "_"); let _ = writeln!(&mut after, "[{option}]: ../settings.md#{anchor}"); } if field.deprecated.is_some() { eprintln!("Rule {rule_name} references deprecated option {option}."); } } } if !after.is_empty() { out.push('\n'); out.push('\n'); out.push_str(&after); } } #[cfg(test)] mod tests { use super::process_documentation; #[test] fn test_process_documentation() { let mut output = String::new(); process_documentation( " See also [`lint.mccabe.max-complexity`] and [`lint.task-tags`]. Something [`else`][other]. Some [link](https://example.com). ## Options - `lint.task-tags` - `lint.mccabe.max-complexity` [other]: http://example.com.", &mut output, "example", ); assert_eq!( output, " See also [`lint.mccabe.max-complexity`][lint.mccabe.max-complexity] and [`lint.task-tags`][lint.task-tags]. Something [`else`][other]. Some [link](https://example.com). ## Options - [`lint.task-tags`][lint.task-tags] - [`lint.mccabe.max-complexity`][lint.mccabe.max-complexity] [other]: http://example.com. [lint.task-tags]: ../settings.md#lint_task-tags [lint.mccabe.max-complexity]: ../settings.md#lint_mccabe_max-complexity " ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_options.rs
crates/ruff_dev/src/generate_options.rs
//! Generate a Markdown-compatible listing of configuration options for `pyproject.toml`. //! //! Used for <https://docs.astral.sh/ruff/settings/>. use itertools::Itertools; use std::fmt::Write; use ruff_options_metadata::{OptionField, OptionSet, OptionsMetadata, Visit}; use ruff_python_trivia::textwrap; use ruff_workspace::options::Options; pub(crate) fn generate() -> String { let mut output = String::new(); generate_set( &mut output, Set::Toplevel(Options::metadata()), &mut Vec::new(), ); output } fn generate_set(output: &mut String, set: Set, parents: &mut Vec<Set>) { match &set { Set::Toplevel(_) => { output.push_str("### Top-level\n"); } Set::Named { name, .. } => { let title = parents .iter() .filter_map(|set| set.name()) .chain(std::iter::once(name.as_str())) .join("."); writeln!(output, "#### `{title}`\n",).unwrap(); } } if let Some(documentation) = set.metadata().documentation() { output.push_str(documentation); output.push('\n'); output.push('\n'); } let mut visitor = CollectOptionsVisitor::default(); set.metadata().record(&mut visitor); let (mut fields, mut sets) = (visitor.fields, visitor.groups); fields.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2)); sets.sort_unstable_by(|(name, _), (name2, _)| name.cmp(name2)); parents.push(set); // Generate the fields. for (name, field) in &fields { emit_field(output, name, field, parents.as_slice()); output.push_str("---\n\n"); } // Generate all the sub-sets. for (set_name, sub_set) in &sets { generate_set( output, Set::Named { name: set_name.clone(), set: *sub_set, }, parents, ); } parents.pop(); } enum Set { Toplevel(OptionSet), Named { name: String, set: OptionSet }, } impl Set { fn name(&self) -> Option<&str> { match self { Set::Toplevel(_) => None, Set::Named { name, .. } => Some(name), } } fn metadata(&self) -> &OptionSet { match self { Set::Toplevel(set) => set, Set::Named { set, .. } => set, } } } fn emit_field(output: &mut String, name: &str, field: &OptionField, parents: &[Set]) { let header_level = if parents.is_empty() { "####" } else { "#####" }; let parents_anchor = parents.iter().filter_map(|parent| parent.name()).join("_"); if parents_anchor.is_empty() { let _ = writeln!(output, "{header_level} [`{name}`](#{name}) {{: #{name} }}"); } else { let _ = writeln!( output, "{header_level} [`{name}`](#{parents_anchor}_{name}) {{: #{parents_anchor}_{name} }}" ); // the anchor used to just be the name, but now it's the group name // for backwards compatibility, we need to keep the old anchor let _ = writeln!(output, "<span id=\"{name}\"></span>"); } output.push('\n'); if let Some(deprecated) = &field.deprecated { output.push_str("!!! warning \"Deprecated\"\n"); output.push_str(" This option has been deprecated"); if let Some(since) = deprecated.since { write!(output, " in {since}").unwrap(); } output.push('.'); if let Some(message) = deprecated.message { writeln!(output, " {message}").unwrap(); } output.push('\n'); } output.push_str(field.doc); output.push_str("\n\n"); let _ = writeln!(output, "**Default value**: `{}`", field.default); output.push('\n'); let _ = writeln!(output, "**Type**: `{}`", field.value_type); output.push('\n'); output.push_str("**Example usage**:\n\n"); output.push_str(&format_tab( "pyproject.toml", &format_header(field.scope, parents, ConfigurationFile::PyprojectToml), field.example, )); output.push_str(&format_tab( "ruff.toml", &format_header(field.scope, parents, ConfigurationFile::RuffToml), field.example, )); output.push('\n'); } fn format_tab(tab_name: &str, header: &str, content: &str) -> String { format!( "=== \"{}\"\n\n ```toml\n {}\n{}\n ```\n", tab_name, header, textwrap::indent(content, " ") ) } /// Format the TOML header for the example usage for a given option. /// /// For example: `[tool.ruff.format]` or `[tool.ruff.lint.isort]`. fn format_header(scope: Option<&str>, parents: &[Set], configuration: ConfigurationFile) -> String { let tool_parent = match configuration { ConfigurationFile::PyprojectToml => Some("tool.ruff"), ConfigurationFile::RuffToml => None, }; let header = tool_parent .into_iter() .chain(parents.iter().filter_map(|parent| parent.name())) .chain(scope) .join("."); if header.is_empty() { String::new() } else { format!("[{header}]") } } #[derive(Debug, Copy, Clone)] enum ConfigurationFile { PyprojectToml, RuffToml, } #[derive(Default)] struct CollectOptionsVisitor { groups: Vec<(String, OptionSet)>, fields: Vec<(String, OptionField)>, } impl Visit for CollectOptionsVisitor { fn record_set(&mut self, name: &str, group: OptionSet) { self.groups.push((name.to_owned(), group)); } fn record_field(&mut self, name: &str, field: OptionField) { self.fields.push((name.to_owned(), field)); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_ty_cli_reference.rs
crates/ruff_dev/src/generate_ty_cli_reference.rs
//! Generate a Markdown-compatible reference for the ty command-line interface. use std::cmp::max; use std::path::PathBuf; use anyhow::{Result, bail}; use clap::{Command, CommandFactory}; use itertools::Itertools; use pretty_assertions::StrComparison; use crate::ROOT_DIR; use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND}; use ty::Cli; const SHOW_HIDDEN_COMMANDS: &[&str] = &["generate-shell-completion"]; #[derive(clap::Args)] pub(crate) struct Args { #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } pub(crate) fn main(args: &Args) -> Result<()> { let reference_string = generate(); let filename = "crates/ty/docs/cli.md"; let reference_path = PathBuf::from(ROOT_DIR).join(filename); match args.mode { Mode::DryRun => { println!("{reference_string}"); } Mode::Check => match std::fs::read_to_string(reference_path) { Ok(current) => { if current == reference_string { println!("Up-to-date: {filename}"); } else { let comparison = StrComparison::new(&current, &reference_string); bail!( "{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}" ); } } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { bail!("{filename} not found, please run `{REGENERATE_ALL_COMMAND}`"); } Err(err) => { bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{err}"); } }, Mode::Write => match std::fs::read_to_string(&reference_path) { Ok(current) => { if current == reference_string { println!("Up-to-date: {filename}"); } else { println!("Updating: {filename}"); std::fs::write(reference_path, reference_string.as_bytes())?; } } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { println!("Updating: {filename}"); std::fs::write(reference_path, reference_string.as_bytes())?; } Err(err) => { bail!("{filename} changed, please run `cargo dev generate-cli-reference`:\n{err}"); } }, } Ok(()) } fn generate() -> String { let mut output = String::new(); let mut ty = Cli::command(); // It is very important to build the command before beginning inspection or subcommands // will be missing all of the propagated options. ty.build(); let mut parents = Vec::new(); output.push_str("<!-- WARNING: This file is auto-generated (cargo dev generate-all). Edit the doc comments in 'crates/ty/src/args.rs' if you want to change anything here. -->\n\n"); output.push_str("# CLI Reference\n\n"); generate_command(&mut output, &ty, &mut parents); output } #[allow(clippy::format_push_string)] fn generate_command<'a>(output: &mut String, command: &'a Command, parents: &mut Vec<&'a Command>) { if command.is_hide_set() && !SHOW_HIDDEN_COMMANDS.contains(&command.get_name()) { return; } // Generate the command header. let name = if parents.is_empty() { command.get_name().to_string() } else { format!( "{} {}", parents.iter().map(|cmd| cmd.get_name()).join(" "), command.get_name() ) }; // Display the top-level `ty` command at the same level as its children let level = max(2, parents.len() + 1); output.push_str(&format!("{} {name}\n\n", "#".repeat(level))); // Display the command description. if let Some(about) = command.get_long_about().or_else(|| command.get_about()) { output.push_str(&about.to_string()); output.push_str("\n\n"); } // Display the usage { // This appears to be the simplest way to get rendered usage from Clap, // it is complicated to render it manually. It's annoying that it // requires a mutable reference but it doesn't really matter. let mut command = command.clone(); output.push_str("<h3 class=\"cli-reference\">Usage</h3>\n\n"); output.push_str(&format!( "```\n{}\n```", command .render_usage() .to_string() .trim_start_matches("Usage: "), )); output.push_str("\n\n"); } if command.get_name() == "help" { return; } // Display a list of child commands let mut subcommands = command.get_subcommands().peekable(); let has_subcommands = subcommands.peek().is_some(); if has_subcommands { output.push_str("<h3 class=\"cli-reference\">Commands</h3>\n\n"); output.push_str("<dl class=\"cli-reference\">"); for subcommand in subcommands { if subcommand.is_hide_set() { continue; } let subcommand_name = format!("{name} {}", subcommand.get_name()); output.push_str(&format!( "<dt><a href=\"#{}\"><code>{subcommand_name}</code></a></dt>", subcommand_name.replace(' ', "-") )); if let Some(about) = subcommand.get_about() { output.push_str(&format!( "<dd>{}</dd>\n", markdown::to_html(&about.to_string()) )); } } output.push_str("</dl>\n\n"); } // Do not display options for commands with children if !has_subcommands { let name_key = name.replace(' ', "-"); // Display positional arguments let mut arguments = command .get_positionals() .filter(|arg| !arg.is_hide_set()) .peekable(); if arguments.peek().is_some() { output.push_str("<h3 class=\"cli-reference\">Arguments</h3>\n\n"); output.push_str("<dl class=\"cli-reference\">"); for arg in arguments { let id = format!("{name_key}--{}", arg.get_id()); output.push_str(&format!("<dt id=\"{id}\">")); output.push_str(&format!( "<a href=\"#{id}\"><code>{}</code></a>", arg.get_id().to_string().to_uppercase(), )); output.push_str("</dt>"); if let Some(help) = arg.get_long_help().or_else(|| arg.get_help()) { output.push_str("<dd>"); output.push_str(&format!("{}\n", markdown::to_html(&help.to_string()))); output.push_str("</dd>"); } } output.push_str("</dl>\n\n"); } // Display options and flags let mut options = command .get_arguments() .filter(|arg| !arg.is_positional()) .filter(|arg| !arg.is_hide_set()) .sorted_by_key(|arg| arg.get_id()) .peekable(); if options.peek().is_some() { output.push_str("<h3 class=\"cli-reference\">Options</h3>\n\n"); output.push_str("<dl class=\"cli-reference\">"); for opt in options { let Some(long) = opt.get_long() else { continue }; let id = format!("{name_key}--{long}"); output.push_str(&format!("<dt id=\"{id}\">")); output.push_str(&format!("<a href=\"#{id}\"><code>--{long}</code></a>")); for long_alias in opt.get_all_aliases().into_iter().flatten() { output.push_str(&format!(", <code>--{long_alias}</code>")); } if let Some(short) = opt.get_short() { output.push_str(&format!(", <code>-{short}</code>")); } for short_alias in opt.get_all_short_aliases().into_iter().flatten() { output.push_str(&format!(", <code>-{short_alias}</code>")); } // Re-implements private `Arg::is_takes_value_set` used in `Command::get_opts` if opt .get_num_args() .unwrap_or_else(|| 1.into()) .takes_values() { if let Some(values) = opt.get_value_names() { for value in values { output.push_str(&format!( " <i>{}</i>", value.to_lowercase().replace('_', "-") )); } } } output.push_str("</dt>"); if let Some(help) = opt.get_long_help().or_else(|| opt.get_help()) { output.push_str("<dd>"); output.push_str(&format!("{}\n", markdown::to_html(&help.to_string()))); emit_env_option(opt, output); emit_default_option(opt, output); emit_possible_options(opt, output); output.push_str("</dd>"); } } output.push_str("</dl>"); } output.push_str("\n\n"); } parents.push(command); // Recurse to all of the subcommands. for subcommand in command.get_subcommands() { generate_command(output, subcommand, parents); } parents.pop(); } fn emit_env_option(opt: &clap::Arg, output: &mut String) { if opt.is_hide_env_set() { return; } if let Some(env) = opt.get_env() { output.push_str(&markdown::to_html(&format!( "May also be set with the `{}` environment variable.", env.to_string_lossy() ))); } } fn emit_default_option(opt: &clap::Arg, output: &mut String) { if opt.is_hide_default_value_set() || !opt.get_num_args().expect("built").takes_values() { return; } let values = opt.get_default_values(); if !values.is_empty() { let value = format!( "\n[default: {}]", opt.get_default_values() .iter() .map(|s| s.to_string_lossy()) .join(",") ); output.push_str(&markdown::to_html(&value)); } } fn emit_possible_options(opt: &clap::Arg, output: &mut String) { if opt.is_hide_possible_values_set() { return; } let values = opt.get_possible_values(); if !values.is_empty() { let value = format!( "\nPossible values:\n{}", values .into_iter() .filter(|value| !value.is_hide_set()) .map(|value| { let name = value.get_name(); value.get_help().map_or_else( || format!(" - `{name}`"), |help| format!(" - `{name}`: {help}"), ) }) .collect_vec() .join("\n"), ); output.push_str(&markdown::to_html(&value)); } } #[cfg(test)] mod tests { use anyhow::Result; use crate::generate_all::Mode; use super::{Args, main}; #[test] fn ty_cli_reference_is_up_to_date() -> Result<()> { main(&Args { mode: Mode::Check }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/main.rs
crates/ruff_dev/src/main.rs
//! This crate implements an internal CLI for developers of Ruff. //! //! Within the ruff repository you can run it with `cargo dev`. #![allow(clippy::print_stdout, clippy::print_stderr)] use anyhow::Result; use clap::{Parser, Subcommand}; use ruff::{args::GlobalConfigArgs, check}; use ruff_linter::logging::set_up_logging; use std::process::ExitCode; mod format_dev; mod generate_all; mod generate_cli_help; mod generate_docs; mod generate_json_schema; mod generate_options; mod generate_rules_table; mod generate_ty_cli_reference; mod generate_ty_env_vars_reference; mod generate_ty_options; mod generate_ty_rules; mod generate_ty_schema; mod print_ast; mod print_cst; mod print_tokens; mod round_trip; const ROOT_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../"); #[derive(Parser)] #[command(author, version, about, long_about = None)] #[command(propagate_version = true)] struct Args { #[command(subcommand)] command: Command, #[clap(flatten)] global_options: GlobalConfigArgs, } #[derive(Subcommand)] #[expect(clippy::large_enum_variant)] enum Command { /// Run all code and documentation generation steps. GenerateAll(generate_all::Args), /// Generate JSON schema for the TOML configuration file. GenerateJSONSchema(generate_json_schema::Args), /// Generate JSON schema for the ty TOML configuration file. GenerateTySchema(generate_ty_schema::Args), /// Generate a Markdown-compatible table of supported lint rules. GenerateRulesTable, GenerateTyRules(generate_ty_rules::Args), /// Generate a Markdown-compatible listing of configuration options. GenerateOptions, GenerateTyOptions(generate_ty_options::Args), /// Generate environment variables reference for ty. GenerateTyEnvVarsReference(generate_ty_env_vars_reference::Args), /// Generate CLI help. GenerateCliHelp(generate_cli_help::Args), /// Generate Markdown docs. GenerateDocs(generate_docs::Args), /// Print the AST for a given Python file. PrintAST(print_ast::Args), /// Print the LibCST CST for a given Python file. PrintCST(print_cst::Args), /// Print the token stream for a given Python file. PrintTokens(print_tokens::Args), /// Run round-trip source code generation on a given Python file. RoundTrip(round_trip::Args), /// Run a ruff command n times for profiling/benchmarking Repeat { #[clap(flatten)] args: ruff::args::CheckCommand, /// Run this many times #[clap(long)] repeat: usize, }, /// Several utils related to the formatter which can be run on one or more repositories. The /// selected set of files in a repository is the same as for `ruff check`. /// /// * Check formatter stability: Format a repository twice and ensure that it looks that the /// first and second formatting look the same. /// * Format: Format the files in a repository to be able to check them with `git diff` /// * Statistics: The subcommand the Jaccard index between the (assumed to be black formatted) /// input and the ruff formatted output FormatDev(format_dev::Args), } fn main() -> Result<ExitCode> { let Args { command, global_options, } = Args::parse(); #[expect(clippy::print_stdout)] match command { Command::GenerateAll(args) => generate_all::main(&args)?, Command::GenerateJSONSchema(args) => generate_json_schema::main(&args)?, Command::GenerateTySchema(args) => generate_ty_schema::main(&args)?, Command::GenerateRulesTable => println!("{}", generate_rules_table::generate()), Command::GenerateTyRules(args) => generate_ty_rules::main(&args)?, Command::GenerateOptions => println!("{}", generate_options::generate()), Command::GenerateTyOptions(args) => generate_ty_options::main(&args)?, Command::GenerateTyEnvVarsReference(args) => generate_ty_env_vars_reference::main(&args)?, Command::GenerateCliHelp(args) => generate_cli_help::main(&args)?, Command::GenerateDocs(args) => generate_docs::main(&args)?, Command::PrintAST(args) => print_ast::main(&args)?, Command::PrintCST(args) => print_cst::main(&args)?, Command::PrintTokens(args) => print_tokens::main(&args)?, Command::RoundTrip(args) => round_trip::main(&args)?, Command::Repeat { args: subcommand_args, repeat, } => { set_up_logging(global_options.log_level())?; for _ in 0..repeat { check(subcommand_args.clone(), global_options.clone())?; } } Command::FormatDev(args) => { let exit_code = format_dev::main(&args)?; return Ok(exit_code); } } Ok(ExitCode::SUCCESS) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_cli_help.rs
crates/ruff_dev/src/generate_cli_help.rs
//! Generate CLI help. use std::path::PathBuf; use std::{fs, str}; use anyhow::{Context, Result, bail}; use clap::CommandFactory; use pretty_assertions::StrComparison; use ruff::args; use crate::ROOT_DIR; use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND}; const COMMAND_HELP_BEGIN_PRAGMA: &str = "<!-- Begin auto-generated command help. -->\n"; const COMMAND_HELP_END_PRAGMA: &str = "<!-- End auto-generated command help. -->"; const CHECK_HELP_BEGIN_PRAGMA: &str = "<!-- Begin auto-generated check help. -->\n"; const CHECK_HELP_END_PRAGMA: &str = "<!-- End auto-generated check help. -->"; const FORMAT_HELP_BEGIN_PRAGMA: &str = "<!-- Begin auto-generated format help. -->\n"; const FORMAT_HELP_END_PRAGMA: &str = "<!-- End auto-generated format help. -->"; #[derive(clap::Args)] pub(crate) struct Args { #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } fn trim_lines(s: &str) -> String { s.lines().map(str::trim_end).collect::<Vec<_>>().join("\n") } /// Takes the existing file contents, inserts the section, returns the transformed content fn replace_docs_section( existing: &str, section: &str, begin_pragma: &str, end_pragma: &str, ) -> Result<String> { // Extract the prefix. let index = existing .find(begin_pragma) .with_context(|| "Unable to find begin pragma")?; let prefix = &existing[..index + begin_pragma.len()]; // Extract the suffix. let index = existing .find(end_pragma) .with_context(|| "Unable to find end pragma")?; let suffix = &existing[index..]; Ok(format!("{prefix}\n{section}{suffix}")) } pub(super) fn main(args: &Args) -> Result<()> { // Generate `ruff help`. let command_help = trim_lines(&help_text()); // Generate `ruff help check`. let check_help = trim_lines(&subcommand_help_text("check")?); // Generate `ruff help format`. let format_help = trim_lines(&subcommand_help_text("format")?); if args.mode.is_dry_run() { print!("{command_help}"); print!("{check_help}"); print!("{format_help}"); return Ok(()); } // Read the existing file. let filename = "docs/configuration.md"; let file = PathBuf::from(ROOT_DIR).join(filename); let existing = fs::read_to_string(&file)?; let new = replace_docs_section( &existing, &format!("```text\n{command_help}\n```\n\n"), COMMAND_HELP_BEGIN_PRAGMA, COMMAND_HELP_END_PRAGMA, )?; let new = replace_docs_section( &new, &format!("```text\n{check_help}\n```\n\n"), CHECK_HELP_BEGIN_PRAGMA, CHECK_HELP_END_PRAGMA, )?; let new = replace_docs_section( &new, &format!("```text\n{format_help}\n```\n\n"), FORMAT_HELP_BEGIN_PRAGMA, FORMAT_HELP_END_PRAGMA, )?; match args.mode { Mode::Check => { if existing == new { println!("up-to-date: {filename}"); } else { let comparison = StrComparison::new(&existing, &new); bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}"); } } _ => { fs::write(file, &new)?; } } Ok(()) } /// Returns the output of `ruff help`. fn help_text() -> String { args::Args::command() .term_width(79) .render_help() .to_string() } /// Returns the output of a given subcommand (e.g., `ruff help check`). fn subcommand_help_text(subcommand: &str) -> Result<String> { let mut cmd = args::Args::command().term_width(79); // The build call is necessary for the help output to contain `Usage: ruff // check` instead of `Usage: check` see https://github.com/clap-rs/clap/issues/4685 cmd.build(); Ok(cmd .find_subcommand_mut(subcommand) .with_context(|| format!("Unable to find subcommand `{subcommand}`"))? .render_help() .to_string()) } #[cfg(test)] mod tests { use anyhow::Result; use crate::generate_all::Mode; use super::{Args, main}; #[test] fn test_generate_json_schema() -> Result<()> { main(&Args { mode: Mode::Check }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_ty_rules.rs
crates/ruff_dev/src/generate_ty_rules.rs
//! Generates the rules table for ty use std::borrow::Cow; use std::fmt::Write as _; use std::fs; use std::path::PathBuf; use anyhow::{Result, bail}; use itertools::Itertools as _; use pretty_assertions::StrComparison; use crate::ROOT_DIR; use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND}; #[derive(clap::Args)] pub(crate) struct Args { /// Write the generated table to stdout (rather than to `ty.schema.json`). #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } pub(crate) fn main(args: &Args) -> Result<()> { let markdown = generate_markdown(); let filename = "crates/ty/docs/rules.md"; let schema_path = PathBuf::from(ROOT_DIR).join(filename); match args.mode { Mode::DryRun => { println!("{markdown}"); } Mode::Check => { let current = fs::read_to_string(schema_path)?; if current == markdown { println!("Up-to-date: {filename}"); } else { let comparison = StrComparison::new(&current, &markdown); bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}"); } } Mode::Write => { let current = fs::read_to_string(&schema_path)?; if current == markdown { println!("Up-to-date: {filename}"); } else { println!("Updating: {filename}"); fs::write(schema_path, markdown.as_bytes())?; } } } Ok(()) } fn generate_markdown() -> String { let registry = ty_python_semantic::default_lint_registry(); let mut output = String::new(); let _ = writeln!( &mut output, "<!-- WARNING: This file is auto-generated (cargo dev generate-all). Edit the lint-declarations in 'crates/ty_python_semantic/src/types/diagnostic.rs' if you want to change anything here. -->\n" ); let _ = writeln!(&mut output, "# Rules\n"); let mut lints: Vec<_> = registry.lints().iter().collect(); lints.sort_by_key(|a| a.name()); for lint in lints { let _ = writeln!(&mut output, "## `{rule_name}`\n", rule_name = lint.name()); // Reformat headers as bold text let mut in_code_fence = false; let documentation = lint .documentation_lines() .map(|line| { // Toggle the code fence state if we encounter a boundary if line.starts_with("```") { in_code_fence = !in_code_fence; } if !in_code_fence && line.starts_with('#') { Cow::Owned(format!( "**{line}**\n", line = line.trim_start_matches('#').trim_start() )) } else { Cow::Borrowed(line) } }) .join("\n"); let status_text = match lint.status() { ty_python_semantic::lint::LintStatus::Stable { since } => { format!( r#"Added in <a href="https://github.com/astral-sh/ty/releases/tag/{since}">{since}</a>"# ) } ty_python_semantic::lint::LintStatus::Preview { since } => { format!( r#"Preview (since <a href="https://github.com/astral-sh/ty/releases/tag/{since}">{since}</a>)"# ) } ty_python_semantic::lint::LintStatus::Deprecated { since, .. } => { format!( r#"Deprecated (since <a href="https://github.com/astral-sh/ty/releases/tag/{since}">{since}</a>)"# ) } ty_python_semantic::lint::LintStatus::Removed { since, .. } => { format!( r#"Removed (since <a href="https://github.com/astral-sh/ty/releases/tag/{since}">{since}</a>)"# ) } }; let _ = writeln!( &mut output, r#"<small> Default level: <a href="../../rules#rule-levels" title="This lint has a default level of '{level}'."><code>{level}</code></a> · {status_text} · <a href="https://github.com/astral-sh/ty/issues?q=sort%3Aupdated-desc%20is%3Aissue%20is%3Aopen%20{encoded_name}" target="_blank">Related issues</a> · <a href="https://github.com/astral-sh/ruff/blob/main/{file}#L{line}" target="_blank">View source</a> </small> {documentation} "#, level = lint.default_level(), encoded_name = url::form_urlencoded::byte_serialize(lint.name().as_str().as_bytes()) .collect::<String>(), file = url::form_urlencoded::byte_serialize(lint.file().replace('\\', "/").as_bytes()) .collect::<String>(), line = lint.line(), ); } output } #[cfg(test)] mod tests { use anyhow::Result; use crate::generate_all::Mode; use super::{Args, main}; #[test] fn ty_rules_up_to_date() -> Result<()> { main(&Args { mode: Mode::Check }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_rules_table.rs
crates/ruff_dev/src/generate_rules_table.rs
//! Generate a Markdown-compatible table of supported lint rules. //! //! Used for <https://docs.astral.sh/ruff/rules/>. use itertools::Itertools; use ruff_linter::codes::RuleGroup; use std::borrow::Cow; use std::fmt::Write; use strum::IntoEnumIterator; use ruff_linter::FixAvailability; use ruff_linter::registry::{Linter, Rule, RuleNamespace}; use ruff_linter::upstream_categories::UpstreamCategoryAndPrefix; use ruff_options_metadata::OptionsMetadata; use ruff_workspace::options::Options; const FIX_SYMBOL: &str = "🛠️"; const PREVIEW_SYMBOL: &str = "🧪"; const REMOVED_SYMBOL: &str = "❌"; const WARNING_SYMBOL: &str = "⚠️"; const SPACER: &str = "&nbsp;&nbsp;&nbsp;&nbsp;"; /// Style for the rule's fixability and status icons. const SYMBOL_STYLE: &str = "style='width: 1em; display: inline-block;'"; /// Style for the container wrapping the fixability and status icons. const SYMBOLS_CONTAINER: &str = "style='display: flex; gap: 0.5rem; justify-content: end;'"; fn generate_table(table_out: &mut String, rules: impl IntoIterator<Item = Rule>, linter: &Linter) { table_out.push_str("| Code | Name | Message | |"); table_out.push('\n'); table_out.push_str("| ---- | ---- | ------- | -: |"); table_out.push('\n'); for rule in rules { let status_token = match rule.group() { RuleGroup::Removed { since } => { format!( "<span {SYMBOL_STYLE} title='Rule was removed in {since}'>{REMOVED_SYMBOL}</span>" ) } RuleGroup::Deprecated { since } => { format!( "<span {SYMBOL_STYLE} title='Rule has been deprecated since {since}'>{WARNING_SYMBOL}</span>" ) } RuleGroup::Preview { since } => { format!( "<span {SYMBOL_STYLE} title='Rule has been in preview since {since}'>{PREVIEW_SYMBOL}</span>" ) } RuleGroup::Stable { since } => { format!("<span {SYMBOL_STYLE} title='Rule has been stable since {since}'></span>") } }; let fix_token = match rule.fixable() { FixAvailability::Always | FixAvailability::Sometimes => { format!("<span {SYMBOL_STYLE} title='Automatic fix available'>{FIX_SYMBOL}</span>") } FixAvailability::None => format!("<span {SYMBOL_STYLE}></span>"), }; let rule_name = rule.name(); // If the message ends in a bracketed expression (like: "Use {replacement}"), escape the // brackets. Otherwise, it'll be interpreted as an HTML attribute via the `attr_list` // plugin. (Above, we'd convert to "Use {replacement\}".) let message = rule.message_formats()[0]; let message = if let Some(prefix) = message.strip_suffix('}') { Cow::Owned(format!("{prefix}\\}}")) } else { Cow::Borrowed(message) }; // Start and end of style spans let mut ss = ""; let mut se = ""; if rule.is_removed() { ss = "<span style='opacity: 0.5', title='This rule has been removed'>"; se = "</span>"; } else if rule.is_deprecated() { ss = "<span style='opacity: 0.8', title='This rule has been deprecated'>"; se = "</span>"; } #[expect(clippy::or_fun_call)] let _ = write!( table_out, "| {ss}{prefix}{code}{se} {{ #{prefix}{code} }} | {ss}{explanation}{se} | {ss}{message}{se} | <div {SYMBOLS_CONTAINER}>{status_token}{fix_token}</div>|", prefix = linter.common_prefix(), code = linter.code_for_rule(rule).unwrap(), explanation = rule .explanation() .is_some() .then_some(format_args!("[{rule_name}](rules/{rule_name}.md)")) .unwrap_or(format_args!("{rule_name}")), ); table_out.push('\n'); } table_out.push('\n'); } pub(crate) fn generate() -> String { // Generate the table string. let mut table_out = String::new(); table_out.push_str("### Legend"); table_out.push('\n'); let _ = write!( &mut table_out, "{SPACER}{PREVIEW_SYMBOL}{SPACER} The rule is unstable and is in [\"preview\"](faq.md#what-is-preview)." ); table_out.push_str("<br />"); let _ = write!( &mut table_out, "{SPACER}{WARNING_SYMBOL}{SPACER} The rule has been deprecated and will be removed in a future release." ); table_out.push_str("<br />"); let _ = write!( &mut table_out, "{SPACER}{REMOVED_SYMBOL}{SPACER} The rule has been removed only the documentation is available." ); table_out.push_str("<br />"); let _ = write!( &mut table_out, "{SPACER}{FIX_SYMBOL}{SPACER} The rule is automatically fixable by the `--fix` command-line option." ); table_out.push_str("\n\n"); table_out.push_str("All rules not marked as preview, deprecated or removed are stable."); table_out.push('\n'); for linter in Linter::iter() { let codes_csv: String = match linter.common_prefix() { "" => linter .upstream_categories() .unwrap() .iter() .map(|c| c.prefix) .join(", "), prefix => prefix.to_string(), }; let _ = write!(&mut table_out, "### {} ({codes_csv})", linter.name()); table_out.push('\n'); table_out.push('\n'); if let Some(url) = linter.url() { let host = url .trim_start_matches("https://") .split('/') .next() .unwrap(); let _ = write!( table_out, "For more, see [{}]({}) on {}.", linter.name(), url, match host { "pypi.org" => "PyPI", "github.com" => "GitHub", host => panic!( "unexpected host in URL of {}, expected pypi.org or github.com but found \ {host}", linter.name() ), } ); table_out.push('\n'); table_out.push('\n'); } if Options::metadata().has(&format!("lint.{}", linter.name())) { let _ = write!( table_out, "For related settings, see [{}](settings.md#lint{}).", linter.name(), linter.name(), ); table_out.push('\n'); table_out.push('\n'); } let rules_by_upstream_category = linter .all_rules() .map(|rule| (rule.upstream_category(&linter), rule)) .into_group_map(); let mut rules_by_upstream_category: Vec<_> = rules_by_upstream_category.iter().collect(); // Sort the upstream categories alphabetically by prefix. rules_by_upstream_category.sort_by(|(a, _), (b, _)| { a.as_ref() .map(|category| category.prefix) .unwrap_or_default() .cmp( b.as_ref() .map(|category| category.prefix) .unwrap_or_default(), ) }); if rules_by_upstream_category.len() > 1 { for (opt, rules) in rules_by_upstream_category { if opt.is_some() { let UpstreamCategoryAndPrefix { category, prefix } = opt.unwrap(); match codes_csv.as_str() { "PL" => { let _ = write!(table_out, "#### {category} ({codes_csv}{prefix})"); } _ => { let _ = write!(table_out, "#### {category} ({prefix})"); } } } table_out.push('\n'); table_out.push('\n'); generate_table(&mut table_out, rules.clone(), &linter); } } else { generate_table(&mut table_out, linter.all_rules(), &linter); } } table_out }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_dev/src/generate_ty_env_vars_reference.rs
crates/ruff_dev/src/generate_ty_env_vars_reference.rs
//! Generate the environment variables reference from `ty_static::EnvVars`. use std::collections::BTreeSet; use std::fs; use std::path::PathBuf; use anyhow::bail; use pretty_assertions::StrComparison; use ty_static::EnvVars; use crate::generate_all::Mode; #[derive(clap::Args)] pub(crate) struct Args { #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } pub(crate) fn main(args: &Args) -> anyhow::Result<()> { let reference_string = generate(); let filename = "environment.md"; let reference_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .parent() .unwrap() .parent() .unwrap() .join("crates") .join("ty") .join("docs") .join(filename); match args.mode { Mode::DryRun => { println!("{reference_string}"); } Mode::Check => match fs::read_to_string(&reference_path) { Ok(current) => { if current == reference_string { println!("Up-to-date: {filename}"); } else { let comparison = StrComparison::new(&current, &reference_string); bail!( "{filename} changed, please run `cargo dev generate-ty-env-vars-reference`:\n{comparison}" ); } } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { bail!( "{filename} not found, please run `cargo dev generate-ty-env-vars-reference`" ); } Err(err) => { bail!( "{filename} changed, please run `cargo dev generate-ty-env-vars-reference`:\n{err}" ); } }, Mode::Write => { // Ensure the docs directory exists if let Some(parent) = reference_path.parent() { fs::create_dir_all(parent)?; } match fs::read_to_string(&reference_path) { Ok(current) => { if current == reference_string { println!("Up-to-date: {filename}"); } else { println!("Updating: {filename}"); fs::write(&reference_path, reference_string.as_bytes())?; } } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { println!("Updating: {filename}"); fs::write(&reference_path, reference_string.as_bytes())?; } Err(err) => { bail!( "{filename} changed, please run `cargo dev generate-ty-env-vars-reference`:\n{err}" ); } } } } Ok(()) } fn generate() -> String { let mut output = String::new(); output.push_str("# Environment variables\n\n"); // Partition and sort environment variables into TY_ and external variables. let (ty_vars, external_vars): (BTreeSet<_>, BTreeSet<_>) = EnvVars::metadata() .iter() .partition(|(var, _)| var.starts_with("TY_")); output.push_str("ty defines and respects the following environment variables:\n\n"); for (var, doc) in ty_vars { output.push_str(&render(var, doc)); } output.push_str("## Externally-defined variables\n\n"); output.push_str("ty also reads the following externally defined environment variables:\n\n"); for (var, doc) in external_vars { output.push_str(&render(var, doc)); } output } /// Render an environment variable and its documentation. fn render(var: &str, doc: &str) -> String { format!("### `{var}`\n\n{doc}\n\n") }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_source_file/src/lib.rs
crates/ruff_source_file/src/lib.rs
use std::cmp::Ordering; use std::fmt::{Debug, Display, Formatter}; use std::hash::Hash; use std::sync::{Arc, OnceLock}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use ruff_text_size::{Ranged, TextRange, TextSize}; pub use crate::line_index::{LineIndex, OneIndexed, PositionEncoding}; pub use crate::line_ranges::LineRanges; pub use crate::newlines::{ Line, LineEnding, NewlineWithTrailingNewline, UniversalNewlineIterator, UniversalNewlines, find_newline, }; mod line_index; mod line_ranges; mod newlines; /// Gives access to the source code of a file and allows mapping between [`TextSize`] and [`LineColumn`]. #[derive(Debug)] pub struct SourceCode<'src, 'index> { text: &'src str, index: &'index LineIndex, } impl<'src, 'index> SourceCode<'src, 'index> { pub fn new(content: &'src str, index: &'index LineIndex) -> Self { Self { text: content, index, } } /// Computes the one indexed line and column numbers for `offset`, skipping any potential BOM. #[inline] pub fn line_column(&self, offset: TextSize) -> LineColumn { self.index.line_column(offset, self.text) } #[inline] pub fn source_location( &self, offset: TextSize, position_encoding: PositionEncoding, ) -> SourceLocation { self.index .source_location(offset, self.text, position_encoding) } #[inline] pub fn line_index(&self, offset: TextSize) -> OneIndexed { self.index.line_index(offset) } /// Take the source code up to the given [`TextSize`]. #[inline] pub fn up_to(&self, offset: TextSize) -> &'src str { &self.text[TextRange::up_to(offset)] } /// Take the source code after the given [`TextSize`]. #[inline] pub fn after(&self, offset: TextSize) -> &'src str { &self.text[usize::from(offset)..] } /// Take the source code between the given [`TextRange`]. pub fn slice<T: Ranged>(&self, ranged: T) -> &'src str { &self.text[ranged.range()] } pub fn line_start(&self, line: OneIndexed) -> TextSize { self.index.line_start(line, self.text) } pub fn line_end(&self, line: OneIndexed) -> TextSize { self.index.line_end(line, self.text) } pub fn line_end_exclusive(&self, line: OneIndexed) -> TextSize { self.index.line_end_exclusive(line, self.text) } pub fn line_range(&self, line: OneIndexed) -> TextRange { self.index.line_range(line, self.text) } /// Returns the source text of the line with the given index #[inline] pub fn line_text(&self, index: OneIndexed) -> &'src str { let range = self.index.line_range(index, self.text); &self.text[range] } /// Returns the source text pub fn text(&self) -> &'src str { self.text } /// Returns the number of lines #[inline] pub fn line_count(&self) -> usize { self.index.line_count() } } impl PartialEq<Self> for SourceCode<'_, '_> { fn eq(&self, other: &Self) -> bool { self.text == other.text } } impl Eq for SourceCode<'_, '_> {} /// A Builder for constructing a [`SourceFile`] pub struct SourceFileBuilder { name: Box<str>, code: Box<str>, index: Option<LineIndex>, } impl SourceFileBuilder { /// Creates a new builder for a file named `name`. pub fn new<Name: Into<Box<str>>, Code: Into<Box<str>>>(name: Name, code: Code) -> Self { Self { name: name.into(), code: code.into(), index: None, } } #[must_use] pub fn line_index(mut self, index: LineIndex) -> Self { self.index = Some(index); self } pub fn set_line_index(&mut self, index: LineIndex) { self.index = Some(index); } /// Consumes `self` and returns the [`SourceFile`]. pub fn finish(self) -> SourceFile { let index = if let Some(index) = self.index { OnceLock::from(index) } else { OnceLock::new() }; SourceFile { inner: Arc::new(SourceFileInner { name: self.name, code: self.code, line_index: index, }), } } } /// A source file that is identified by its name. Optionally stores the source code and [`LineIndex`]. /// /// Cloning a [`SourceFile`] is cheap, because it only requires bumping a reference count. #[derive(Clone, Eq, PartialEq, Hash)] #[cfg_attr(feature = "get-size", derive(get_size2::GetSize))] pub struct SourceFile { inner: Arc<SourceFileInner>, } impl Debug for SourceFile { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_struct("SourceFile") .field("name", &self.name()) .field("code", &self.source_text()) .finish() } } impl SourceFile { /// Returns the name of the source file (filename). #[inline] pub fn name(&self) -> &str { &self.inner.name } #[inline] pub fn slice(&self, range: TextRange) -> &str { &self.source_text()[range] } pub fn to_source_code(&self) -> SourceCode<'_, '_> { SourceCode { text: self.source_text(), index: self.index(), } } pub fn index(&self) -> &LineIndex { self.inner .line_index .get_or_init(|| LineIndex::from_source_text(self.source_text())) } /// Returns the source code. #[inline] pub fn source_text(&self) -> &str { &self.inner.code } } impl PartialOrd for SourceFile { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for SourceFile { fn cmp(&self, other: &Self) -> Ordering { // Short circuit if these are the same source files if Arc::ptr_eq(&self.inner, &other.inner) { Ordering::Equal } else { self.inner.name.cmp(&other.inner.name) } } } #[cfg_attr(feature = "get-size", derive(get_size2::GetSize))] struct SourceFileInner { name: Box<str>, code: Box<str>, line_index: OnceLock<LineIndex>, } impl PartialEq for SourceFileInner { fn eq(&self, other: &Self) -> bool { self.name == other.name && self.code == other.code } } impl Eq for SourceFileInner {} impl Hash for SourceFileInner { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.name.hash(state); self.code.hash(state); } } /// The line and column of an offset in a source file. /// /// See [`LineIndex::line_column`] for more information. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct LineColumn { /// The line in the source text. pub line: OneIndexed, /// The column (UTF scalar values) relative to the start of the line except any /// potential BOM on the first line. pub column: OneIndexed, } impl Default for LineColumn { fn default() -> Self { Self { line: OneIndexed::MIN, column: OneIndexed::MIN, } } } impl Debug for LineColumn { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_struct("LineColumn") .field("line", &self.line.get()) .field("column", &self.column.get()) .finish() } } impl std::fmt::Display for LineColumn { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{line}:{column}", line = self.line, column = self.column) } } /// A position into a source file represented by the line number and the offset to that character relative to the start of that line. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct SourceLocation { /// The line in the source text. pub line: OneIndexed, /// The offset from the start of the line to the character. /// /// This can be a byte offset, the number of UTF16 code points, or the UTF8 code units, depending on the /// [`PositionEncoding`] used. pub character_offset: OneIndexed, } impl Default for SourceLocation { fn default() -> Self { Self { line: OneIndexed::MIN, character_offset: OneIndexed::MIN, } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum SourceRow { /// A row within a cell in a Jupyter Notebook. Notebook { cell: OneIndexed, line: OneIndexed }, /// A row within a source file. SourceFile { line: OneIndexed }, } impl Display for SourceRow { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { SourceRow::Notebook { cell, line } => write!(f, "cell {cell}, line {line}"), SourceRow::SourceFile { line } => write!(f, "line {line}"), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_source_file/src/line_index.rs
crates/ruff_source_file/src/line_index.rs
use std::fmt; use std::fmt::{Debug, Formatter}; use std::num::{NonZeroUsize, ParseIntError}; use std::ops::Deref; use std::str::FromStr; use std::sync::Arc; use crate::{LineColumn, SourceLocation}; use ruff_text_size::{TextLen, TextRange, TextSize}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; /// Index for fast [byte offset](TextSize) to [`LineColumn`] conversions. /// /// Cloning a [`LineIndex`] is cheap because it only requires bumping a reference count. #[derive(Clone, Eq, PartialEq)] #[cfg_attr(feature = "get-size", derive(get_size2::GetSize))] pub struct LineIndex { inner: Arc<LineIndexInner>, } #[derive(Eq, PartialEq)] #[cfg_attr(feature = "get-size", derive(get_size2::GetSize))] struct LineIndexInner { line_starts: Vec<TextSize>, kind: IndexKind, } impl LineIndex { /// Builds the [`LineIndex`] from the source text of a file. pub fn from_source_text(text: &str) -> Self { let mut line_starts: Vec<TextSize> = Vec::with_capacity(text.len() / 88); line_starts.push(TextSize::default()); let bytes = text.as_bytes(); assert!(u32::try_from(bytes.len()).is_ok()); for i in memchr::memchr2_iter(b'\n', b'\r', bytes) { // Skip `\r` in `\r\n` sequences (only count the `\n`). if bytes[i] == b'\r' && bytes.get(i + 1) == Some(&b'\n') { continue; } // SAFETY: Assertion above guarantees `i <= u32::MAX` #[expect(clippy::cast_possible_truncation)] line_starts.push(TextSize::from(i as u32) + TextSize::from(1)); } // Determine whether the source text is ASCII. // // Empirically, this simple loop is auto-vectorized by LLVM and benchmarks faster than both // `str::is_ascii()` and hand-written SIMD. let mut has_non_ascii = false; for byte in bytes { has_non_ascii |= !byte.is_ascii(); } let kind = if has_non_ascii { IndexKind::Utf8 } else { IndexKind::Ascii }; Self { inner: Arc::new(LineIndexInner { line_starts, kind }), } } fn kind(&self) -> IndexKind { self.inner.kind } /// Returns the line and column number for an UTF-8 byte offset. /// /// The `column` number is the nth-character of the line, except for the first line /// where it doesn't include the UTF-8 BOM marker at the start of the file. /// /// ### BOM handling /// /// For files starting with a UTF-8 BOM marker, the byte offsets /// in the range `0...3` are all mapped to line 0 and column 0. /// Because of this, the conversion isn't losless. /// /// ## Examples /// /// ``` /// # use ruff_text_size::TextSize; /// # use ruff_source_file::{LineIndex, OneIndexed, LineColumn}; /// let source = format!("\u{FEFF}{}", "def a():\n pass"); /// let index = LineIndex::from_source_text(&source); /// /// // Before BOM, maps to after BOM /// assert_eq!( /// index.line_column(TextSize::from(0), &source), /// LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(0) } /// ); /// /// // After BOM, maps to after BOM /// assert_eq!( /// index.line_column(TextSize::from(3), &source), /// LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(0) } /// ); /// /// assert_eq!( /// index.line_column(TextSize::from(7), &source), /// LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(4) } /// ); /// assert_eq!( /// index.line_column(TextSize::from(16), &source), /// LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(4) } /// ); /// ``` /// /// ## Panics /// /// If the byte offset isn't within the bounds of `content`. pub fn line_column(&self, offset: TextSize, content: &str) -> LineColumn { let location = self.source_location(offset, content, PositionEncoding::Utf32); // Don't count the BOM character as a column, but only on the first line. let column = if location.line.to_zero_indexed() == 0 && content.starts_with('\u{feff}') { location.character_offset.saturating_sub(1) } else { location.character_offset }; LineColumn { line: location.line, column, } } /// Given a UTF-8 byte offset, returns the line and character offset according to the given encoding. /// /// ### BOM handling /// /// Unlike [`Self::line_column`], this method does not skip the BOM character at the start of the file. /// This allows for bidirectional mapping between [`SourceLocation`] and [`TextSize`] (see [`Self::offset`]). /// /// ## Examples /// /// ``` /// # use ruff_text_size::TextSize; /// # use ruff_source_file::{LineIndex, OneIndexed, LineColumn, SourceLocation, PositionEncoding, Line}; /// let source = format!("\u{FEFF}{}", "def a():\n pass"); /// let index = LineIndex::from_source_text(&source); /// /// // Before BOM, maps to character 0 /// assert_eq!( /// index.source_location(TextSize::from(0), &source, PositionEncoding::Utf32), /// SourceLocation { line: OneIndexed::from_zero_indexed(0), character_offset: OneIndexed::from_zero_indexed(0) } /// ); /// /// // After BOM, maps to after BOM /// assert_eq!( /// index.source_location(TextSize::from(3), &source, PositionEncoding::Utf32), /// SourceLocation { line: OneIndexed::from_zero_indexed(0), character_offset: OneIndexed::from_zero_indexed(1) } /// ); /// /// assert_eq!( /// index.source_location(TextSize::from(7), &source, PositionEncoding::Utf32), /// SourceLocation { line: OneIndexed::from_zero_indexed(0), character_offset: OneIndexed::from_zero_indexed(5) } /// ); /// assert_eq!( /// index.source_location(TextSize::from(16), &source, PositionEncoding::Utf32), /// SourceLocation { line: OneIndexed::from_zero_indexed(1), character_offset: OneIndexed::from_zero_indexed(4) } /// ); /// ``` /// /// ## Panics /// /// If the UTF-8 byte offset is out of bounds of `text`. pub fn source_location( &self, offset: TextSize, text: &str, encoding: PositionEncoding, ) -> SourceLocation { let line = self.line_index(offset); let line_start = self.line_start(line, text); let character_offset = self.characters_between(TextRange::new(line_start, offset), text, encoding); SourceLocation { line, character_offset: OneIndexed::from_zero_indexed(character_offset), } } fn characters_between( &self, range: TextRange, text: &str, encoding: PositionEncoding, ) -> usize { if self.is_ascii() { return (range.end() - range.start()).to_usize(); } match encoding { PositionEncoding::Utf8 => (range.end() - range.start()).to_usize(), PositionEncoding::Utf16 => { let up_to_character = &text[range]; up_to_character.encode_utf16().count() } PositionEncoding::Utf32 => { let up_to_character = &text[range]; up_to_character.chars().count() } } } /// Returns the length of the line in characters, respecting the given encoding pub fn line_len(&self, line: OneIndexed, text: &str, encoding: PositionEncoding) -> usize { let line_range = self.line_range(line, text); self.characters_between(line_range, text, encoding) } /// Return the number of lines in the source code. pub fn line_count(&self) -> usize { self.line_starts().len() } /// Returns `true` if the text only consists of ASCII characters pub fn is_ascii(&self) -> bool { self.kind().is_ascii() } /// Returns the row number for a given offset. /// /// ## Examples /// /// ``` /// # use ruff_text_size::TextSize; /// # use ruff_source_file::{LineIndex, OneIndexed, LineColumn}; /// let source = "def a():\n pass"; /// let index = LineIndex::from_source_text(source); /// /// assert_eq!(index.line_index(TextSize::from(0)), OneIndexed::from_zero_indexed(0)); /// assert_eq!(index.line_index(TextSize::from(4)), OneIndexed::from_zero_indexed(0)); /// assert_eq!(index.line_index(TextSize::from(13)), OneIndexed::from_zero_indexed(1)); /// ``` /// /// ## Panics /// /// If the offset is out of bounds. pub fn line_index(&self, offset: TextSize) -> OneIndexed { match self.line_starts().binary_search(&offset) { // Offset is at the start of a line Ok(row) => OneIndexed::from_zero_indexed(row), Err(row) => { // SAFETY: Safe because the index always contains an entry for the offset 0 OneIndexed::from_zero_indexed(row - 1) } } } /// Returns the [byte offset](TextSize) for the `line` with the given index. pub fn line_start(&self, line: OneIndexed, contents: &str) -> TextSize { let row_index = line.to_zero_indexed(); let starts = self.line_starts(); // If start-of-line position after last line if row_index == starts.len() { contents.text_len() } else { starts[row_index] } } /// Returns the [byte offset](TextSize) of the `line`'s end. /// The offset is the end of the line, up to and including the newline character ending the line (if any). pub fn line_end(&self, line: OneIndexed, contents: &str) -> TextSize { let row_index = line.to_zero_indexed(); let starts = self.line_starts(); // If start-of-line position after last line if row_index.saturating_add(1) >= starts.len() { contents.text_len() } else { starts[row_index + 1] } } /// Returns the [byte offset](TextSize) of the `line`'s end. /// The offset is the end of the line, excluding the newline character ending the line (if any). pub fn line_end_exclusive(&self, line: OneIndexed, contents: &str) -> TextSize { let row_index = line.to_zero_indexed(); let starts = self.line_starts(); // If start-of-line position after last line if row_index.saturating_add(1) >= starts.len() { contents.text_len() } else { starts[row_index + 1] - TextSize::new(1) } } /// Returns the [`TextRange`] of the `line` with the given index. /// The start points to the first character's [byte offset](TextSize), the end up to, and including /// the newline character ending the line (if any). pub fn line_range(&self, line: OneIndexed, contents: &str) -> TextRange { let starts = self.line_starts(); if starts.len() == line.to_zero_indexed() { TextRange::empty(contents.text_len()) } else { TextRange::new( self.line_start(line, contents), self.line_start(line.saturating_add(1), contents), ) } } /// Returns the [UTF-8 byte offset](TextSize) at `line` and `character` where character is counted using the given encoding. /// /// ## Examples /// /// ### ASCII only source text /// /// ``` /// # use ruff_source_file::{SourceLocation, LineIndex, OneIndexed, PositionEncoding}; /// # use ruff_text_size::TextSize; /// let source = r#"a = 4 /// c = "some string" /// x = b"#; /// /// let index = LineIndex::from_source_text(source); /// /// // First line, first character /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(0), /// character_offset: OneIndexed::from_zero_indexed(0) /// }, /// source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(0) /// ); /// /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(1), /// character_offset: OneIndexed::from_zero_indexed(4) /// }, /// source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(10) /// ); /// /// // Offset past the end of the first line /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(0), /// character_offset: OneIndexed::from_zero_indexed(10) /// }, /// source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(6) /// ); /// /// // Offset past the end of the file /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(3), /// character_offset: OneIndexed::from_zero_indexed(0) /// }, /// source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(29) /// ); /// ``` /// /// ### Non-ASCII source text /// /// ``` /// use ruff_source_file::{LineIndex, OneIndexed, SourceLocation, PositionEncoding}; /// use ruff_text_size::TextSize; /// let source = format!("\u{FEFF}{}", r#"a = 4 /// c = "❤️" /// x = b"#); /// /// let index = LineIndex::from_source_text(&source); /// /// // First line, first character, points at the BOM /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(0), /// character_offset: OneIndexed::from_zero_indexed(0) /// }, /// &source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(0) /// ); /// /// // First line, after the BOM /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(0), /// character_offset: OneIndexed::from_zero_indexed(1) /// }, /// &source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(3) /// ); /// /// // second line, 7th character, after emoji, UTF32 /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(1), /// character_offset: OneIndexed::from_zero_indexed(7) /// }, /// &source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(20) /// ); /// /// // Second line, 7th character, after emoji, UTF 16 /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(1), /// character_offset: OneIndexed::from_zero_indexed(7) /// }, /// &source, /// PositionEncoding::Utf16, /// ), /// TextSize::new(20) /// ); /// /// /// // Offset past the end of the second line /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(1), /// character_offset: OneIndexed::from_zero_indexed(10) /// }, /// &source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(22) /// ); /// /// // Offset past the end of the file /// assert_eq!( /// index.offset( /// SourceLocation { /// line: OneIndexed::from_zero_indexed(3), /// character_offset: OneIndexed::from_zero_indexed(0) /// }, /// &source, /// PositionEncoding::Utf32, /// ), /// TextSize::new(27) /// ); /// ``` pub fn offset( &self, position: SourceLocation, text: &str, position_encoding: PositionEncoding, ) -> TextSize { // If start-of-line position after last line if position.line.to_zero_indexed() > self.line_starts().len() { return text.text_len(); } let line_range = self.line_range(position.line, text); let character_offset = position.character_offset.to_zero_indexed(); let character_byte_offset = if self.is_ascii() { TextSize::try_from(character_offset).unwrap() } else { let line = &text[line_range]; match position_encoding { PositionEncoding::Utf8 => { TextSize::try_from(position.character_offset.to_zero_indexed()).unwrap() } PositionEncoding::Utf16 => { let mut byte_offset = TextSize::new(0); let mut utf16_code_unit_offset = 0; for c in line.chars() { if utf16_code_unit_offset >= character_offset { break; } // Count characters encoded as two 16 bit words as 2 characters. byte_offset += c.text_len(); utf16_code_unit_offset += c.len_utf16(); } byte_offset } PositionEncoding::Utf32 => line .chars() .take(position.character_offset.to_zero_indexed()) .map(ruff_text_size::TextLen::text_len) .sum(), } }; line_range.start() + character_byte_offset.clamp(TextSize::new(0), line_range.len()) } /// Returns the [byte offsets](TextSize) for every line pub fn line_starts(&self) -> &[TextSize] { &self.inner.line_starts } } impl Deref for LineIndex { type Target = [TextSize]; fn deref(&self) -> &Self::Target { self.line_starts() } } impl Debug for LineIndex { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.line_starts()).finish() } } #[derive(Debug, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "get-size", derive(get_size2::GetSize))] enum IndexKind { /// Optimized index for an ASCII only document Ascii, /// Index for UTF8 documents Utf8, } impl IndexKind { const fn is_ascii(self) -> bool { matches!(self, IndexKind::Ascii) } } /// Type-safe wrapper for a value whose logical range starts at `1`, for /// instance the line or column numbers in a file /// /// Internally this is represented as a [`NonZeroUsize`], this enables some /// memory optimizations #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct OneIndexed(NonZeroUsize); impl OneIndexed { /// The largest value that can be represented by this integer type pub const MAX: Self = Self::new(usize::MAX).unwrap(); // SAFETY: These constants are being initialized with non-zero values /// The smallest value that can be represented by this integer type. pub const MIN: Self = Self::new(1).unwrap(); pub const ONE: NonZeroUsize = NonZeroUsize::new(1).unwrap(); /// Creates a non-zero if the given value is not zero. pub const fn new(value: usize) -> Option<Self> { match NonZeroUsize::new(value) { Some(value) => Some(Self(value)), None => None, } } /// Construct a new [`OneIndexed`] from a zero-indexed value pub const fn from_zero_indexed(value: usize) -> Self { Self(Self::ONE.saturating_add(value)) } /// Returns the value as a primitive type. pub const fn get(self) -> usize { self.0.get() } /// Return the zero-indexed primitive value for this [`OneIndexed`] pub const fn to_zero_indexed(self) -> usize { self.0.get() - 1 } /// Saturating integer addition. Computes `self + rhs`, saturating at /// the numeric bounds instead of overflowing. #[must_use] pub const fn saturating_add(self, rhs: usize) -> Self { match NonZeroUsize::new(self.0.get().saturating_add(rhs)) { Some(value) => Self(value), None => Self::MAX, } } /// Saturating integer subtraction. Computes `self - rhs`, saturating /// at the numeric bounds instead of overflowing. #[must_use] pub const fn saturating_sub(self, rhs: usize) -> Self { match NonZeroUsize::new(self.0.get().saturating_sub(rhs)) { Some(value) => Self(value), None => Self::MIN, } } /// Checked addition. Returns `None` if overflow occurred. #[must_use] pub fn checked_add(self, rhs: Self) -> Option<Self> { self.0.checked_add(rhs.0.get()).map(Self) } /// Checked subtraction. Returns `None` if overflow occurred. #[must_use] pub fn checked_sub(self, rhs: Self) -> Option<Self> { self.0.get().checked_sub(rhs.get()).and_then(Self::new) } /// Calculate the number of digits in `self`. /// /// This is primarily intended for computing the length of the string representation for /// formatted printing. /// /// # Examples /// /// ``` /// use ruff_source_file::OneIndexed; /// /// let one = OneIndexed::new(1).unwrap(); /// assert_eq!(one.digits().get(), 1); /// /// let hundred = OneIndexed::new(100).unwrap(); /// assert_eq!(hundred.digits().get(), 3); /// /// let thousand = OneIndexed::new(1000).unwrap(); /// assert_eq!(thousand.digits().get(), 4); /// ``` pub const fn digits(self) -> NonZeroUsize { // Safety: the 1+ ensures this is always non-zero, and // `usize::MAX.ilog10()` << `usize::MAX`, so the result is always safe // to cast to a usize, even though it's returned as a u32 // (u64::MAX.ilog10() is 19). NonZeroUsize::new(1 + self.0.get().ilog10() as usize).unwrap() } } impl Default for OneIndexed { fn default() -> Self { Self::MIN } } impl fmt::Display for OneIndexed { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { std::fmt::Debug::fmt(&self.0.get(), f) } } impl FromStr for OneIndexed { type Err = ParseIntError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(OneIndexed(NonZeroUsize::from_str(s)?)) } } #[derive(Copy, Clone, Debug)] pub enum PositionEncoding { /// Character offsets count the number of bytes from the start of the line. Utf8, /// Character offsets count the number of UTF-16 code units from the start of the line. Utf16, /// Character offsets count the number of UTF-32 code points units (the same as number of characters in Rust) /// from the start of the line. Utf32, } #[cfg(test)] mod tests { use ruff_text_size::TextSize; use crate::line_index::LineIndex; use crate::{LineColumn, OneIndexed}; #[test] fn ascii_index() { let index = LineIndex::from_source_text(""); assert_eq!(index.line_starts(), &[TextSize::from(0)]); let index = LineIndex::from_source_text("x = 1"); assert_eq!(index.line_starts(), &[TextSize::from(0)]); let index = LineIndex::from_source_text("x = 1\n"); assert_eq!(index.line_starts(), &[TextSize::from(0), TextSize::from(6)]); let index = LineIndex::from_source_text("x = 1\ny = 2\nz = x + y\n"); assert_eq!( index.line_starts(), &[ TextSize::from(0), TextSize::from(6), TextSize::from(12), TextSize::from(22) ] ); } #[test] fn ascii_source_location() { let contents = "x = 1\ny = 2"; let index = LineIndex::from_source_text(contents); // First row. let loc = index.line_column(TextSize::from(2), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(2) } ); // Second row. let loc = index.line_column(TextSize::from(6), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(0) } ); let loc = index.line_column(TextSize::from(11), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(5) } ); } #[test] fn ascii_carriage_return() { let contents = "x = 4\ry = 3"; let index = LineIndex::from_source_text(contents); assert_eq!(index.line_starts(), &[TextSize::from(0), TextSize::from(6)]); assert_eq!( index.line_column(TextSize::from(4), contents), LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(4) } ); assert_eq!( index.line_column(TextSize::from(6), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(0) } ); assert_eq!( index.line_column(TextSize::from(7), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(1) } ); } #[test] fn ascii_carriage_return_newline() { let contents = "x = 4\r\ny = 3"; let index = LineIndex::from_source_text(contents); assert_eq!(index.line_starts(), &[TextSize::from(0), TextSize::from(7)]); assert_eq!( index.line_column(TextSize::from(4), contents), LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(4) } ); assert_eq!( index.line_column(TextSize::from(7), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(0) } ); assert_eq!( index.line_column(TextSize::from(8), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(1) } ); } #[test] fn utf8_index() { let index = LineIndex::from_source_text("x = '🫣'"); assert_eq!(index.line_count(), 1); assert_eq!(index.line_starts(), &[TextSize::from(0)]); let index = LineIndex::from_source_text("x = '🫣'\n"); assert_eq!(index.line_count(), 2); assert_eq!( index.line_starts(), &[TextSize::from(0), TextSize::from(11)] ); let index = LineIndex::from_source_text("x = '🫣'\ny = 2\nz = x + y\n"); assert_eq!(index.line_count(), 4); assert_eq!( index.line_starts(), &[ TextSize::from(0), TextSize::from(11), TextSize::from(17), TextSize::from(27) ] ); let index = LineIndex::from_source_text("# 🫣\nclass Foo:\n \"\"\".\"\"\""); assert_eq!(index.line_count(), 3); assert_eq!( index.line_starts(), &[TextSize::from(0), TextSize::from(7), TextSize::from(18)] ); } #[test] fn utf8_carriage_return() { let contents = "x = '🫣'\ry = 3"; let index = LineIndex::from_source_text(contents); assert_eq!(index.line_count(), 2); assert_eq!( index.line_starts(), &[TextSize::from(0), TextSize::from(11)] ); // Second ' assert_eq!( index.line_column(TextSize::from(9), contents), LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(6) } ); assert_eq!( index.line_column(TextSize::from(11), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(0) } ); assert_eq!( index.line_column(TextSize::from(12), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(1) } ); } #[test] fn utf8_carriage_return_newline() { let contents = "x = '🫣'\r\ny = 3"; let index = LineIndex::from_source_text(contents); assert_eq!(index.line_count(), 2); assert_eq!( index.line_starts(), &[TextSize::from(0), TextSize::from(12)] ); // Second ' assert_eq!( index.line_column(TextSize::from(9), contents), LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(6) } ); assert_eq!( index.line_column(TextSize::from(12), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(0) } ); assert_eq!( index.line_column(TextSize::from(13), contents), LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(1) } ); } #[test] fn utf8_byte_offset() { let contents = "x = '☃'\ny = 2"; let index = LineIndex::from_source_text(contents); assert_eq!( index.line_starts(), &[TextSize::from(0), TextSize::from(10)] ); // First row. let loc = index.line_column(TextSize::from(0), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(0) } ); let loc = index.line_column(TextSize::from(5), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(5) } ); let loc = index.line_column(TextSize::from(8), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(0), column: OneIndexed::from_zero_indexed(6) } ); // Second row. let loc = index.line_column(TextSize::from(10), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(0) } ); // One-past-the-end. let loc = index.line_column(TextSize::from(15), contents); assert_eq!( loc, LineColumn { line: OneIndexed::from_zero_indexed(1), column: OneIndexed::from_zero_indexed(5) } ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_source_file/src/line_ranges.rs
crates/ruff_source_file/src/line_ranges.rs
use crate::find_newline; use memchr::{memchr2, memrchr2}; use ruff_text_size::{TextLen, TextRange, TextSize}; use std::ops::Add; /// Extension trait for [`str`] that provides methods for working with ranges of lines. pub trait LineRanges { /// Computes the start position of the line of `offset`. /// /// ## Examples /// /// ``` /// # use ruff_text_size::TextSize; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\rthird line"; /// /// assert_eq!(text.line_start(TextSize::from(0)), TextSize::from(0)); /// assert_eq!(text.line_start(TextSize::from(4)), TextSize::from(0)); /// /// assert_eq!(text.line_start(TextSize::from(14)), TextSize::from(11)); /// assert_eq!(text.line_start(TextSize::from(28)), TextSize::from(23)); /// ``` /// /// ## Panics /// If `offset` is out of bounds. fn line_start(&self, offset: TextSize) -> TextSize; /// Computes the start position of the file contents: either the first byte, or the byte after /// the BOM. fn bom_start_offset(&self) -> TextSize; /// Returns `true` if `offset` is at the start of a line. fn is_at_start_of_line(&self, offset: TextSize) -> bool { self.line_start(offset) == offset } /// Computes the offset that is right after the newline character that ends `offset`'s line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!(text.full_line_end(TextSize::from(3)), TextSize::from(11)); /// assert_eq!(text.full_line_end(TextSize::from(14)), TextSize::from(24)); /// assert_eq!(text.full_line_end(TextSize::from(28)), TextSize::from(34)); /// ``` /// /// ## Panics /// /// If `offset` is passed the end of the content. fn full_line_end(&self, offset: TextSize) -> TextSize; /// Computes the offset that is right before the newline character that ends `offset`'s line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!(text.line_end(TextSize::from(3)), TextSize::from(10)); /// assert_eq!(text.line_end(TextSize::from(14)), TextSize::from(22)); /// assert_eq!(text.line_end(TextSize::from(28)), TextSize::from(34)); /// ``` /// /// ## Panics /// /// If `offset` is passed the end of the content. fn line_end(&self, offset: TextSize) -> TextSize; /// Computes the range of this `offset`s line. /// /// The range starts at the beginning of the line and goes up to, and including, the new line character /// at the end of the line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!(text.full_line_range(TextSize::from(3)), TextRange::new(TextSize::from(0), TextSize::from(11))); /// assert_eq!(text.full_line_range(TextSize::from(14)), TextRange::new(TextSize::from(11), TextSize::from(24))); /// assert_eq!(text.full_line_range(TextSize::from(28)), TextRange::new(TextSize::from(24), TextSize::from(34))); /// ``` /// /// ## Panics /// If `offset` is out of bounds. fn full_line_range(&self, offset: TextSize) -> TextRange { TextRange::new(self.line_start(offset), self.full_line_end(offset)) } /// Computes the range of this `offset`s line ending before the newline character. /// /// The range starts at the beginning of the line and goes up to, but excluding, the new line character /// at the end of the line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!(text.line_range(TextSize::from(3)), TextRange::new(TextSize::from(0), TextSize::from(10))); /// assert_eq!(text.line_range(TextSize::from(14)), TextRange::new(TextSize::from(11), TextSize::from(22))); /// assert_eq!(text.line_range(TextSize::from(28)), TextRange::new(TextSize::from(24), TextSize::from(34))); /// ``` /// /// ## Panics /// If `offset` is out of bounds. fn line_range(&self, offset: TextSize) -> TextRange { TextRange::new(self.line_start(offset), self.line_end(offset)) } /// Returns the text of the `offset`'s line. /// /// The line includes the newline characters at the end of the line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!(text.full_line_str(TextSize::from(3)), "First line\n"); /// assert_eq!(text.full_line_str(TextSize::from(14)), "second line\r\n"); /// assert_eq!(text.full_line_str(TextSize::from(28)), "third line"); /// ``` /// /// ## Panics /// If `offset` is out of bounds. fn full_line_str(&self, offset: TextSize) -> &str; /// Returns the text of the `offset`'s line. /// /// Excludes the newline characters at the end of the line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!(text.line_str(TextSize::from(3)), "First line"); /// assert_eq!(text.line_str(TextSize::from(14)), "second line"); /// assert_eq!(text.line_str(TextSize::from(28)), "third line"); /// ``` /// /// ## Panics /// If `offset` is out of bounds. fn line_str(&self, offset: TextSize) -> &str; /// Computes the range of all lines that this `range` covers. /// /// The range starts at the beginning of the line at `range.start()` and goes up to, and including, the new line character /// at the end of `range.ends()`'s line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!( /// text.full_lines_range(TextRange::new(TextSize::from(3), TextSize::from(5))), /// TextRange::new(TextSize::from(0), TextSize::from(11)) /// ); /// assert_eq!( /// text.full_lines_range(TextRange::new(TextSize::from(3), TextSize::from(14))), /// TextRange::new(TextSize::from(0), TextSize::from(24)) /// ); /// ``` /// /// ## Panics /// If the start or end of `range` is out of bounds. fn full_lines_range(&self, range: TextRange) -> TextRange { TextRange::new( self.line_start(range.start()), self.full_line_end(range.end()), ) } /// Computes the range of all lines that this `range` covers. /// /// The range starts at the beginning of the line at `range.start()` and goes up to, but excluding, the new line character /// at the end of `range.end()`'s line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!( /// text.lines_range(TextRange::new(TextSize::from(3), TextSize::from(5))), /// TextRange::new(TextSize::from(0), TextSize::from(10)) /// ); /// assert_eq!( /// text.lines_range(TextRange::new(TextSize::from(3), TextSize::from(14))), /// TextRange::new(TextSize::from(0), TextSize::from(22)) /// ); /// ``` /// /// ## Panics /// If the start or end of `range` is out of bounds. fn lines_range(&self, range: TextRange) -> TextRange { TextRange::new(self.line_start(range.start()), self.line_end(range.end())) } /// Returns true if the text of `range` contains any line break. /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert!( /// !text.contains_line_break(TextRange::new(TextSize::from(3), TextSize::from(5))), /// ); /// assert!( /// text.contains_line_break(TextRange::new(TextSize::from(3), TextSize::from(14))), /// ); /// ``` /// /// ## Panics /// If the `range` is out of bounds. fn contains_line_break(&self, range: TextRange) -> bool; /// Returns the text of all lines that include `range`. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!( /// text.lines_str(TextRange::new(TextSize::from(3), TextSize::from(5))), /// "First line" /// ); /// assert_eq!( /// text.lines_str(TextRange::new(TextSize::from(3), TextSize::from(14))), /// "First line\nsecond line" /// ); /// ``` /// /// ## Panics /// If the start or end of `range` is out of bounds. fn lines_str(&self, range: TextRange) -> &str; /// Returns the text of all lines that include `range`. /// /// Includes the newline characters of the last line. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_source_file::LineRanges; /// /// let text = "First line\nsecond line\r\nthird line"; /// /// assert_eq!( /// text.full_lines_str(TextRange::new(TextSize::from(3), TextSize::from(5))), /// "First line\n" /// ); /// assert_eq!( /// text.full_lines_str(TextRange::new(TextSize::from(3), TextSize::from(14))), /// "First line\nsecond line\r\n" /// ); /// ``` /// /// ## Panics /// If the start or end of `range` is out of bounds. fn full_lines_str(&self, range: TextRange) -> &str; /// The number of lines `range` spans. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange}; /// # use ruff_source_file::LineRanges; /// /// assert_eq!("a\nb".count_lines(TextRange::up_to(1.into())), 0); /// assert_eq!("a\nb\r\nc".count_lines(TextRange::up_to(3.into())), 1, "Up to the end of the second line"); /// assert_eq!("a\nb\r\nc".count_lines(TextRange::up_to(4.into())), 2, "In between the line break characters"); /// assert_eq!("a\nb\r\nc".count_lines(TextRange::up_to(5.into())), 2); /// assert_eq!("Single line".count_lines(TextRange::up_to(13.into())), 0); /// assert_eq!("out\nof\nbounds end".count_lines(TextRange::up_to(55.into())), 2); /// ``` fn count_lines(&self, range: TextRange) -> u32 { let mut count = 0; let mut line_end = self.line_end(range.start()); loop { let next_line_start = self.full_line_end(line_end); // Reached the end of the string if next_line_start == line_end { break count; } // Range ends at the line boundary if line_end >= range.end() { break count; } count += 1; line_end = self.line_end(next_line_start); } } } impl LineRanges for str { fn line_start(&self, offset: TextSize) -> TextSize { let bytes = self[TextRange::up_to(offset)].as_bytes(); if let Some(index) = memrchr2(b'\n', b'\r', bytes) { // SAFETY: Safe because `index < offset` TextSize::try_from(index).unwrap().add(TextSize::from(1)) } else { self.bom_start_offset() } } fn bom_start_offset(&self) -> TextSize { if self.starts_with('\u{feff}') { // Skip the BOM. '\u{feff}'.text_len() } else { // Start of file. TextSize::default() } } fn full_line_end(&self, offset: TextSize) -> TextSize { let slice = &self[usize::from(offset)..]; if let Some((index, line_ending)) = find_newline(slice) { offset + TextSize::try_from(index).unwrap() + line_ending.text_len() } else { self.text_len() } } fn line_end(&self, offset: TextSize) -> TextSize { let slice = &self[offset.to_usize()..]; if let Some(index) = memchr2(b'\n', b'\r', slice.as_bytes()) { offset + TextSize::try_from(index).unwrap() } else { self.text_len() } } fn full_line_str(&self, offset: TextSize) -> &str { &self[self.full_line_range(offset)] } fn line_str(&self, offset: TextSize) -> &str { &self[self.line_range(offset)] } fn contains_line_break(&self, range: TextRange) -> bool { memchr2(b'\n', b'\r', self[range].as_bytes()).is_some() } fn lines_str(&self, range: TextRange) -> &str { &self[self.lines_range(range)] } fn full_lines_str(&self, range: TextRange) -> &str { &self[self.full_lines_range(range)] } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_source_file/src/newlines.rs
crates/ruff_source_file/src/newlines.rs
use std::iter::FusedIterator; use std::ops::Deref; use memchr::{memchr2, memrchr2}; use ruff_text_size::{TextLen, TextRange, TextSize}; /// Extension trait for [`str`] that provides a [`UniversalNewlineIterator`]. pub trait UniversalNewlines { fn universal_newlines(&self) -> UniversalNewlineIterator<'_>; } impl UniversalNewlines for str { fn universal_newlines(&self) -> UniversalNewlineIterator<'_> { UniversalNewlineIterator::from(self) } } /// Like [`str::lines`], but accommodates LF, CRLF, and CR line endings, /// the latter of which are not supported by [`str::lines`]. /// /// ## Examples /// /// ```rust /// # use ruff_text_size::TextSize; /// # use ruff_source_file::{Line, UniversalNewlineIterator}; /// let mut lines = UniversalNewlineIterator::from("foo\nbar\n\r\nbaz\rbop"); /// /// assert_eq!(lines.next_back(), Some(Line::new("bop", TextSize::from(14)))); /// assert_eq!(lines.next(), Some(Line::new("foo\n", TextSize::from(0)))); /// assert_eq!(lines.next_back(), Some(Line::new("baz\r", TextSize::from(10)))); /// assert_eq!(lines.next(), Some(Line::new("bar\n", TextSize::from(4)))); /// assert_eq!(lines.next_back(), Some(Line::new("\r\n", TextSize::from(8)))); /// assert_eq!(lines.next(), None); /// ``` #[derive(Clone)] pub struct UniversalNewlineIterator<'a> { text: &'a str, offset: TextSize, offset_back: TextSize, } impl<'a> UniversalNewlineIterator<'a> { pub fn with_offset(text: &'a str, offset: TextSize) -> UniversalNewlineIterator<'a> { UniversalNewlineIterator { text, offset, offset_back: offset + text.text_len(), } } pub fn from(text: &'a str) -> UniversalNewlineIterator<'a> { Self::with_offset(text, TextSize::default()) } } /// Finds the next newline character. Returns its position and the [`LineEnding`]. #[inline] pub fn find_newline(text: &str) -> Option<(usize, LineEnding)> { let bytes = text.as_bytes(); if let Some(position) = memchr2(b'\n', b'\r', bytes) { let line_ending = match bytes[position] { // Explicit branch for `\n` as this is the most likely path b'\n' => LineEnding::Lf, // '\r\n' b'\r' if bytes.get(position.saturating_add(1)) == Some(&b'\n') => LineEnding::CrLf, // '\r' _ => LineEnding::Cr, }; Some((position, line_ending)) } else { None } } impl<'a> Iterator for UniversalNewlineIterator<'a> { type Item = Line<'a>; #[inline] fn next(&mut self) -> Option<Line<'a>> { if self.text.is_empty() { return None; } let line = if let Some((newline_position, line_ending)) = find_newline(self.text) { let (text, remainder) = self.text.split_at(newline_position + line_ending.len()); let line = Line { offset: self.offset, text, }; self.text = remainder; self.offset += text.text_len(); line } // Last line else { Line { offset: self.offset, text: std::mem::take(&mut self.text), } }; Some(line) } fn last(mut self) -> Option<Self::Item> { self.next_back() } } impl DoubleEndedIterator for UniversalNewlineIterator<'_> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.text.is_empty() { return None; } let len = self.text.len(); // Trim any trailing newlines. let haystack = match self.text.as_bytes()[len - 1] { b'\n' if len > 1 && self.text.as_bytes()[len - 2] == b'\r' => &self.text[..len - 2], b'\n' | b'\r' => &self.text[..len - 1], _ => self.text, }; // Find the end of the previous line. The previous line is the text up to, but not including // the newline character. let line = if let Some(line_end) = memrchr2(b'\n', b'\r', haystack.as_bytes()) { // '\n' or '\r' or '\r\n' let (remainder, line) = self.text.split_at(line_end + 1); self.text = remainder; self.offset_back -= line.text_len(); Line { text: line, offset: self.offset_back, } } else { // Last line let offset = self.offset_back - self.text.text_len(); Line { text: std::mem::take(&mut self.text), offset, } }; Some(line) } } impl FusedIterator for UniversalNewlineIterator<'_> {} /// Like [`UniversalNewlineIterator`], but includes a trailing newline as an empty line. pub struct NewlineWithTrailingNewline<'a> { trailing: Option<Line<'a>>, underlying: UniversalNewlineIterator<'a>, } impl<'a> NewlineWithTrailingNewline<'a> { pub fn from(input: &'a str) -> NewlineWithTrailingNewline<'a> { Self::with_offset(input, TextSize::default()) } pub fn with_offset(input: &'a str, offset: TextSize) -> Self { NewlineWithTrailingNewline { underlying: UniversalNewlineIterator::with_offset(input, offset), trailing: if input.ends_with(['\r', '\n']) { Some(Line { text: "", offset: offset + input.text_len(), }) } else { None }, } } } impl<'a> Iterator for NewlineWithTrailingNewline<'a> { type Item = Line<'a>; #[inline] fn next(&mut self) -> Option<Self::Item> { self.underlying.next().or_else(|| self.trailing.take()) } } impl DoubleEndedIterator for NewlineWithTrailingNewline<'_> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { self.trailing.take().or_else(|| self.underlying.next_back()) } } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Line<'a> { text: &'a str, offset: TextSize, } impl<'a> Line<'a> { pub fn new(text: &'a str, offset: TextSize) -> Self { Self { text, offset } } #[inline] pub const fn start(&self) -> TextSize { self.offset } /// Returns the byte offset where the line ends, including its terminating new line character. #[inline] pub fn full_end(&self) -> TextSize { self.offset + self.full_text_len() } /// Returns the byte offset where the line ends, excluding its new line character #[inline] pub fn end(&self) -> TextSize { self.offset + self.as_str().text_len() } /// Returns the range of the line, including its terminating new line character. #[inline] pub fn full_range(&self) -> TextRange { TextRange::at(self.offset, self.text.text_len()) } /// Returns the range of the line, excluding its terminating new line character #[inline] pub fn range(&self) -> TextRange { TextRange::new(self.start(), self.end()) } /// Returns the line's new line character, if any. #[inline] pub fn line_ending(&self) -> Option<LineEnding> { let mut bytes = self.text.bytes().rev(); match bytes.next() { Some(b'\n') => { if bytes.next() == Some(b'\r') { Some(LineEnding::CrLf) } else { Some(LineEnding::Lf) } } Some(b'\r') => Some(LineEnding::Cr), _ => None, } } /// Returns the text of the line, excluding the terminating new line character. #[inline] pub fn as_str(&self) -> &'a str { let newline_len = self .line_ending() .map_or(0, |line_ending| line_ending.len()); &self.text[..self.text.len() - newline_len] } /// Returns the line's text, including the terminating new line character. #[inline] pub fn as_full_str(&self) -> &'a str { self.text } #[inline] pub fn full_text_len(&self) -> TextSize { self.text.text_len() } } impl Deref for Line<'_> { type Target = str; fn deref(&self) -> &Self::Target { self.as_str() } } impl PartialEq<&str> for Line<'_> { fn eq(&self, other: &&str) -> bool { self.as_str() == *other } } impl PartialEq<Line<'_>> for &str { fn eq(&self, other: &Line<'_>) -> bool { *self == other.as_str() } } /// The line ending style used in Python source code. /// See <https://docs.python.org/3/reference/lexical_analysis.html#physical-lines> #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum LineEnding { Lf, Cr, CrLf, } impl Default for LineEnding { fn default() -> Self { if cfg!(windows) { LineEnding::CrLf } else { LineEnding::Lf } } } impl LineEnding { pub const fn as_str(&self) -> &'static str { match self { LineEnding::Lf => "\n", LineEnding::CrLf => "\r\n", LineEnding::Cr => "\r", } } #[expect(clippy::len_without_is_empty)] pub const fn len(&self) -> usize { match self { LineEnding::Lf | LineEnding::Cr => 1, LineEnding::CrLf => 2, } } pub const fn text_len(&self) -> TextSize { match self { LineEnding::Lf | LineEnding::Cr => TextSize::new(1), LineEnding::CrLf => TextSize::new(2), } } } impl Deref for LineEnding { type Target = str; fn deref(&self) -> &Self::Target { self.as_str() } } #[cfg(test)] mod tests { use ruff_text_size::TextSize; use super::{Line, UniversalNewlineIterator}; #[test] fn universal_newlines_empty_str() { let lines: Vec<_> = UniversalNewlineIterator::from("").collect(); assert_eq!(lines, Vec::<Line>::new()); let lines: Vec<_> = UniversalNewlineIterator::from("").rev().collect(); assert_eq!(lines, Vec::<Line>::new()); } #[test] fn universal_newlines_forward() { let lines: Vec<_> = UniversalNewlineIterator::from("foo\nbar\n\r\nbaz\rbop").collect(); assert_eq!( lines, vec![ Line::new("foo\n", TextSize::from(0)), Line::new("bar\n", TextSize::from(4)), Line::new("\r\n", TextSize::from(8)), Line::new("baz\r", TextSize::from(10)), Line::new("bop", TextSize::from(14)), ] ); let lines: Vec<_> = UniversalNewlineIterator::from("foo\nbar\n\r\nbaz\rbop\n").collect(); assert_eq!( lines, vec![ Line::new("foo\n", TextSize::from(0)), Line::new("bar\n", TextSize::from(4)), Line::new("\r\n", TextSize::from(8)), Line::new("baz\r", TextSize::from(10)), Line::new("bop\n", TextSize::from(14)), ] ); let lines: Vec<_> = UniversalNewlineIterator::from("foo\nbar\n\r\nbaz\rbop\n\n").collect(); assert_eq!( lines, vec![ Line::new("foo\n", TextSize::from(0)), Line::new("bar\n", TextSize::from(4)), Line::new("\r\n", TextSize::from(8)), Line::new("baz\r", TextSize::from(10)), Line::new("bop\n", TextSize::from(14)), Line::new("\n", TextSize::from(18)), ] ); } #[test] fn universal_newlines_backwards() { let lines: Vec<_> = UniversalNewlineIterator::from("foo\nbar\n\r\nbaz\rbop") .rev() .collect(); assert_eq!( lines, vec![ Line::new("bop", TextSize::from(14)), Line::new("baz\r", TextSize::from(10)), Line::new("\r\n", TextSize::from(8)), Line::new("bar\n", TextSize::from(4)), Line::new("foo\n", TextSize::from(0)), ] ); let lines: Vec<_> = UniversalNewlineIterator::from("foo\nbar\n\nbaz\rbop\n") .rev() .map(|line| line.as_str()) .collect(); assert_eq!( lines, vec![ Line::new("bop\n", TextSize::from(13)), Line::new("baz\r", TextSize::from(9)), Line::new("\n", TextSize::from(8)), Line::new("bar\n", TextSize::from(4)), Line::new("foo\n", TextSize::from(0)), ] ); } #[test] fn universal_newlines_mixed() { let mut lines = UniversalNewlineIterator::from("foo\nbar\n\r\nbaz\rbop"); assert_eq!( lines.next_back(), Some(Line::new("bop", TextSize::from(14))) ); assert_eq!(lines.next(), Some(Line::new("foo\n", TextSize::from(0)))); assert_eq!( lines.next_back(), Some(Line::new("baz\r", TextSize::from(10))) ); assert_eq!(lines.next(), Some(Line::new("bar\n", TextSize::from(4)))); assert_eq!( lines.next_back(), Some(Line::new("\r\n", TextSize::from(8))) ); assert_eq!(lines.next(), None); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/linter.rs
crates/ruff_linter/src/linter.rs
use std::borrow::Cow; use std::path::Path; use anyhow::{Result, anyhow}; use colored::Colorize; use itertools::Itertools; use ruff_python_parser::semantic_errors::SemanticSyntaxError; use rustc_hash::FxBuildHasher; use ruff_db::diagnostic::{Diagnostic, SecondaryCode}; use ruff_notebook::Notebook; use ruff_python_ast::{ModModule, PySourceType, PythonVersion}; use ruff_python_codegen::Stylist; use ruff_python_index::Indexer; use ruff_python_parser::{ParseError, ParseOptions, Parsed, UnsupportedSyntaxError}; use ruff_source_file::SourceFile; use crate::checkers::ast::{LintContext, check_ast}; use crate::checkers::filesystem::check_file_path; use crate::checkers::imports::check_imports; use crate::checkers::noqa::check_noqa; use crate::checkers::physical_lines::check_physical_lines; use crate::checkers::tokens::check_tokens; use crate::directives::Directives; use crate::doc_lines::{doc_lines_from_ast, doc_lines_from_tokens}; use crate::fix::{FixResult, fix_file}; use crate::noqa::add_noqa; use crate::package::PackageRoot; use crate::registry::Rule; #[cfg(any(feature = "test-rules", test))] use crate::rules::ruff::rules::test_rules::{self, TEST_RULES, TestRule}; use crate::settings::types::UnsafeFixes; use crate::settings::{LinterSettings, TargetVersion, flags}; use crate::source_kind::SourceKind; use crate::suppression::Suppressions; use crate::{Locator, directives, fs}; pub(crate) mod float; pub struct LinterResult { /// A collection of diagnostic messages generated by the linter. pub diagnostics: Vec<Diagnostic>, /// Flag indicating that the parsed source code does not contain any /// [`ParseError`]s has_valid_syntax: bool, } impl LinterResult { /// Returns `true` if the parsed source code is invalid i.e., it has [`ParseError`]s. /// /// Note that this does not include version-related [`UnsupportedSyntaxError`]s or /// [`SemanticSyntaxError`]s. pub fn has_invalid_syntax(&self) -> bool { !self.has_valid_syntax } } #[derive(Debug, Default, PartialEq)] struct FixCount { rule_name: &'static str, count: usize, } /// A mapping from a noqa code to the corresponding lint name and a count of applied fixes. #[derive(Debug, Default, PartialEq)] pub struct FixTable(hashbrown::HashMap<SecondaryCode, FixCount, rustc_hash::FxBuildHasher>); impl FixTable { pub fn counts(&self) -> impl Iterator<Item = usize> { self.0.values().map(|fc| fc.count) } pub fn entry<'a>(&'a mut self, code: &'a SecondaryCode) -> FixTableEntry<'a> { FixTableEntry(self.0.entry_ref(code)) } pub fn iter(&self) -> impl Iterator<Item = (&SecondaryCode, &'static str, usize)> { self.0 .iter() .map(|(code, FixCount { rule_name, count })| (code, *rule_name, *count)) } pub fn keys(&self) -> impl Iterator<Item = &SecondaryCode> { self.0.keys() } pub fn is_empty(&self) -> bool { self.0.is_empty() } } pub struct FixTableEntry<'a>( hashbrown::hash_map::EntryRef<'a, 'a, SecondaryCode, SecondaryCode, FixCount, FxBuildHasher>, ); impl<'a> FixTableEntry<'a> { pub fn or_default(self, rule_name: &'static str) -> &'a mut usize { &mut (self .0 .or_insert(FixCount { rule_name, count: 0, }) .count) } } pub struct FixerResult<'a> { /// The result returned by the linter, after applying any fixes. pub result: LinterResult, /// The resulting source code, after applying any fixes. pub transformed: Cow<'a, SourceKind>, /// The number of fixes applied for each [`Rule`]. pub fixed: FixTable, } /// Generate [`Diagnostic`]s from the source code contents at the given `Path`. #[expect(clippy::too_many_arguments)] pub fn check_path( path: &Path, package: Option<PackageRoot<'_>>, locator: &Locator, stylist: &Stylist, indexer: &Indexer, directives: &Directives, settings: &LinterSettings, noqa: flags::Noqa, source_kind: &SourceKind, source_type: PySourceType, parsed: &Parsed<ModModule>, target_version: TargetVersion, suppressions: &Suppressions, ) -> Vec<Diagnostic> { // Aggregate all diagnostics. let mut context = LintContext::new(path, locator.contents(), settings); // Aggregate all semantic syntax errors. let mut semantic_syntax_errors = vec![]; let tokens = parsed.tokens(); let comment_ranges = indexer.comment_ranges(); // Collect doc lines. This requires a rare mix of tokens (for comments) and AST // (for docstrings), which demands special-casing at this level. let use_doc_lines = context.is_rule_enabled(Rule::DocLineTooLong); let mut doc_lines = vec![]; if use_doc_lines { doc_lines.extend(doc_lines_from_tokens(tokens)); } // Run the token-based rules. if context .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_tokens()) { check_tokens( tokens, path, locator, indexer, stylist, source_type, source_kind.as_ipy_notebook().map(Notebook::cell_offsets), &mut context, ); } // Run the filesystem-based rules. if context .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_filesystem()) { check_file_path( path, package, locator, comment_ranges, settings, target_version.linter_version(), &context, ); } // Run the logical line-based rules. if context .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_logical_lines()) { crate::checkers::logical_lines::check_logical_lines( tokens, locator, indexer, stylist, settings, &context, ); } // Run the AST-based rules only if there are no syntax errors. if parsed.has_valid_syntax() { let cell_offsets = source_kind.as_ipy_notebook().map(Notebook::cell_offsets); let notebook_index = source_kind.as_ipy_notebook().map(Notebook::index); semantic_syntax_errors.extend(check_ast( parsed, locator, stylist, indexer, &directives.noqa_line_for, settings, noqa, path, package, source_type, cell_offsets, notebook_index, target_version, &context, )); let use_imports = !directives.isort.skip_file && context .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_imports()); if use_imports || use_doc_lines { if use_imports { check_imports( parsed, locator, indexer, &directives.isort, settings, stylist, package, source_type, cell_offsets, target_version.linter_version(), &context, ); } if use_doc_lines { doc_lines.extend(doc_lines_from_ast(parsed.suite(), locator)); } } } // Deduplicate and reorder any doc lines. if use_doc_lines { doc_lines.sort_unstable(); doc_lines.dedup(); } // Run the lines-based rules. if context .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_physical_lines()) { check_physical_lines(locator, stylist, indexer, &doc_lines, settings, &context); } // Raise violations for internal test rules #[cfg(any(feature = "test-rules", test))] { for test_rule in TEST_RULES { if !context.is_rule_enabled(*test_rule) { continue; } match test_rule { Rule::StableTestRule => { test_rules::StableTestRule::diagnostic(locator, comment_ranges, &context); } Rule::StableTestRuleSafeFix => { test_rules::StableTestRuleSafeFix::diagnostic( locator, comment_ranges, &context, ); } Rule::StableTestRuleUnsafeFix => test_rules::StableTestRuleUnsafeFix::diagnostic( locator, comment_ranges, &context, ), Rule::StableTestRuleDisplayOnlyFix => { test_rules::StableTestRuleDisplayOnlyFix::diagnostic( locator, comment_ranges, &context, ); } Rule::PreviewTestRule => { test_rules::PreviewTestRule::diagnostic(locator, comment_ranges, &context); } Rule::DeprecatedTestRule => { test_rules::DeprecatedTestRule::diagnostic(locator, comment_ranges, &context); } Rule::AnotherDeprecatedTestRule => { test_rules::AnotherDeprecatedTestRule::diagnostic( locator, comment_ranges, &context, ); } Rule::RemovedTestRule => { test_rules::RemovedTestRule::diagnostic(locator, comment_ranges, &context); } Rule::AnotherRemovedTestRule => test_rules::AnotherRemovedTestRule::diagnostic( locator, comment_ranges, &context, ), Rule::RedirectedToTestRule => { test_rules::RedirectedToTestRule::diagnostic(locator, comment_ranges, &context); } Rule::RedirectedFromTestRule => test_rules::RedirectedFromTestRule::diagnostic( locator, comment_ranges, &context, ), Rule::RedirectedFromPrefixTestRule => { test_rules::RedirectedFromPrefixTestRule::diagnostic( locator, comment_ranges, &context, ); } Rule::PanicyTestRule => { test_rules::PanicyTestRule::diagnostic(locator, comment_ranges, &context); } _ => unreachable!("All test rules must have an implementation"), } } } // Enforce `noqa` directives. if noqa.is_enabled() || context .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_noqa()) { let ignored = check_noqa( &mut context, path, locator, comment_ranges, &directives.noqa_line_for, parsed.has_valid_syntax(), settings, suppressions, ); if noqa.is_enabled() { for index in ignored.iter().rev() { context.as_mut_vec().swap_remove(*index); } } } let (mut diagnostics, source_file) = context.into_parts(); if !parsed.has_valid_syntax() { // Avoid fixing in case the source code contains syntax errors. for diagnostic in &mut diagnostics { diagnostic.remove_fix(); } } let syntax_errors = parsed.unsupported_syntax_errors(); diagnostics_to_messages( diagnostics, parsed.errors(), syntax_errors, &semantic_syntax_errors, directives, &source_file, ) } const MAX_ITERATIONS: usize = 100; /// Add any missing `# noqa` pragmas to the source code at the given `Path`. pub fn add_noqa_to_path( path: &Path, package: Option<PackageRoot<'_>>, source_kind: &SourceKind, source_type: PySourceType, settings: &LinterSettings, reason: Option<&str>, ) -> Result<usize> { // Parse once. let target_version = settings.resolve_target_version(path); let parsed = parse_unchecked_source(source_kind, source_type, target_version.parser_version()); // Map row and column locations to byte slices (lazily). let locator = Locator::new(source_kind.source_code()); // Detect the current code style (lazily). let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); // Extra indices from the code. let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); // Extract the `# noqa` and `# isort: skip` directives from the source. let directives = directives::extract_directives( parsed.tokens(), directives::Flags::from_settings(settings), &locator, &indexer, ); // Parse range suppression comments let suppressions = Suppressions::from_tokens(settings, locator.contents(), parsed.tokens()); // Generate diagnostics, ignoring any existing `noqa` directives. let diagnostics = check_path( path, package, &locator, &stylist, &indexer, &directives, settings, flags::Noqa::Disabled, source_kind, source_type, &parsed, target_version, &suppressions, ); // Add any missing `# noqa` pragmas. // TODO(dhruvmanila): Add support for Jupyter Notebooks add_noqa( path, &diagnostics, &locator, indexer.comment_ranges(), &settings.external, &directives.noqa_line_for, stylist.line_ending(), reason, &suppressions, ) } /// Generate a [`Diagnostic`] for each diagnostic triggered by the given source code. pub fn lint_only( path: &Path, package: Option<PackageRoot<'_>>, settings: &LinterSettings, noqa: flags::Noqa, source_kind: &SourceKind, source_type: PySourceType, source: ParseSource, ) -> LinterResult { let target_version = settings.resolve_target_version(path); let parsed = source.into_parsed(source_kind, source_type, target_version.parser_version()); // Map row and column locations to byte slices (lazily). let locator = Locator::new(source_kind.source_code()); // Detect the current code style (lazily). let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); // Extra indices from the code. let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); // Extract the `# noqa` and `# isort: skip` directives from the source. let directives = directives::extract_directives( parsed.tokens(), directives::Flags::from_settings(settings), &locator, &indexer, ); // Parse range suppression comments let suppressions = Suppressions::from_tokens(settings, locator.contents(), parsed.tokens()); // Generate diagnostics. let diagnostics = check_path( path, package, &locator, &stylist, &indexer, &directives, settings, noqa, source_kind, source_type, &parsed, target_version, &suppressions, ); LinterResult { has_valid_syntax: parsed.has_valid_syntax(), diagnostics, } } /// Convert various error types into a single collection of diagnostics. /// /// Also use `directives` to attach noqa offsets to lint diagnostics. fn diagnostics_to_messages( diagnostics: Vec<Diagnostic>, parse_errors: &[ParseError], unsupported_syntax_errors: &[UnsupportedSyntaxError], semantic_syntax_errors: &[SemanticSyntaxError], directives: &Directives, source_file: &SourceFile, ) -> Vec<Diagnostic> { parse_errors .iter() .map(|parse_error| { Diagnostic::invalid_syntax(source_file.clone(), &parse_error.error, parse_error) }) .chain(unsupported_syntax_errors.iter().map(|syntax_error| { Diagnostic::invalid_syntax(source_file.clone(), syntax_error, syntax_error) })) .chain( semantic_syntax_errors .iter() .map(|error| Diagnostic::invalid_syntax(source_file.clone(), error, error)), ) .chain(diagnostics.into_iter().map(|mut diagnostic| { if let Some(range) = diagnostic.range() { diagnostic.set_noqa_offset(directives.noqa_line_for.resolve(range.start())); } diagnostic })) .collect() } /// Generate `Diagnostic`s from source code content, iteratively fixing /// until stable. pub fn lint_fix<'a>( path: &Path, package: Option<PackageRoot<'_>>, noqa: flags::Noqa, unsafe_fixes: UnsafeFixes, settings: &LinterSettings, source_kind: &'a SourceKind, source_type: PySourceType, ) -> Result<FixerResult<'a>> { let mut transformed = Cow::Borrowed(source_kind); // Track the number of fixed errors across iterations. let mut fixed = FixTable::default(); // As an escape hatch, bail after 100 iterations. let mut iterations = 0; // Track whether the _initial_ source code has valid syntax. let mut has_valid_syntax = false; // Track whether the _initial_ source code has no unsupported syntax errors. let mut has_no_syntax_errors = false; let target_version = settings.resolve_target_version(path); // Continuously fix until the source code stabilizes. loop { // Parse once. let parsed = parse_unchecked_source(&transformed, source_type, target_version.parser_version()); // Map row and column locations to byte slices (lazily). let locator = Locator::new(transformed.source_code()); // Detect the current code style (lazily). let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); // Extra indices from the code. let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); // Extract the `# noqa` and `# isort: skip` directives from the source. let directives = directives::extract_directives( parsed.tokens(), directives::Flags::from_settings(settings), &locator, &indexer, ); // Parse range suppression comments let suppressions = Suppressions::from_tokens(settings, locator.contents(), parsed.tokens()); // Generate diagnostics. let diagnostics = check_path( path, package, &locator, &stylist, &indexer, &directives, settings, noqa, &transformed, source_type, &parsed, target_version, &suppressions, ); if iterations == 0 { has_valid_syntax = parsed.has_valid_syntax(); has_no_syntax_errors = !diagnostics.iter().any(Diagnostic::is_invalid_syntax); } else { // If the source code had no syntax errors on the first pass, but // does on a subsequent pass, then we've introduced a // syntax error. Return the original code. if has_valid_syntax && has_no_syntax_errors { if let Some(error) = parsed.errors().first() { report_fix_syntax_error(path, transformed.source_code(), error, fixed.keys()); return Err(anyhow!("Fix introduced a syntax error")); } } } // Apply fix. if let Some(FixResult { code: fixed_contents, fixes: applied, source_map, }) = fix_file(&diagnostics, &locator, unsafe_fixes) { if iterations < MAX_ITERATIONS { // Count the number of fixed errors. for (rule, name, count) in applied.iter() { *fixed.entry(rule).or_default(name) += count; } transformed = Cow::Owned(transformed.updated(fixed_contents, &source_map)); // Increment the iteration count. iterations += 1; // Re-run the linter pass (by avoiding the return). continue; } report_failed_to_converge_error(path, transformed.source_code(), &diagnostics); } return Ok(FixerResult { result: LinterResult { diagnostics, has_valid_syntax, }, transformed, fixed, }); } } fn collect_rule_codes<T>(rules: impl IntoIterator<Item = T>) -> String where T: Ord + PartialEq + std::fmt::Display, { rules.into_iter().sorted_unstable().dedup().join(", ") } #[expect(clippy::print_stderr)] fn report_failed_to_converge_error(path: &Path, transformed: &str, diagnostics: &[Diagnostic]) { let codes = collect_rule_codes(diagnostics.iter().filter_map(Diagnostic::secondary_code)); if cfg!(debug_assertions) { eprintln!( "{}{} Failed to converge after {} iterations in `{}` with rule codes {}:---\n{}\n---", "debug error".red().bold(), ":".bold(), MAX_ITERATIONS, fs::relativize_path(path), codes, transformed, ); } else { eprintln!( r#" {}{} Failed to converge after {} iterations. This indicates a bug in Ruff. If you could open an issue at: https://github.com/astral-sh/ruff/issues/new?title=%5BInfinite%20loop%5D ...quoting the contents of `{}`, the rule codes {}, along with the `pyproject.toml` settings and executed command, we'd be very appreciative! "#, "error".red().bold(), ":".bold(), MAX_ITERATIONS, fs::relativize_path(path), codes ); } } #[expect(clippy::print_stderr)] fn report_fix_syntax_error<'a>( path: &Path, transformed: &str, error: &ParseError, rules: impl IntoIterator<Item = &'a SecondaryCode>, ) { let codes = collect_rule_codes(rules); if cfg!(debug_assertions) { eprintln!( "{}{} Fix introduced a syntax error in `{}` with rule codes {}: {}\n---\n{}\n---", "error".red().bold(), ":".bold(), fs::relativize_path(path), codes, error, transformed, ); } else { eprintln!( r#" {}{} Fix introduced a syntax error. Reverting all changes. This indicates a bug in Ruff. If you could open an issue at: https://github.com/astral-sh/ruff/issues/new?title=%5BFix%20error%5D ...quoting the contents of `{}`, the rule codes {}, along with the `pyproject.toml` settings and executed command, we'd be very appreciative! "#, "error".red().bold(), ":".bold(), fs::relativize_path(path), codes, ); } } #[derive(Debug, Clone)] pub enum ParseSource { /// Parse the [`Parsed`] from the given source code. None, /// Use the precomputed [`Parsed`]. Precomputed(Parsed<ModModule>), } impl ParseSource { /// Consumes the [`ParseSource`] and returns the parsed [`Parsed`], parsing the source code if /// necessary. fn into_parsed( self, source_kind: &SourceKind, source_type: PySourceType, target_version: PythonVersion, ) -> Parsed<ModModule> { match self { ParseSource::None => parse_unchecked_source(source_kind, source_type, target_version), ParseSource::Precomputed(parsed) => parsed, } } } /// Like [`ruff_python_parser::parse_unchecked_source`] but with an additional [`PythonVersion`] /// argument. fn parse_unchecked_source( source_kind: &SourceKind, source_type: PySourceType, target_version: PythonVersion, ) -> Parsed<ModModule> { let options = ParseOptions::from(source_type).with_target_version(target_version); // SAFETY: Safe because `PySourceType` always parses to a `ModModule`. See // `ruff_python_parser::parse_unchecked_source`. We use `parse_unchecked` (and thus // have to unwrap) in order to pass the `PythonVersion` via `ParseOptions`. ruff_python_parser::parse_unchecked(source_kind.source_code(), options) .try_into_module() .expect("PySourceType always parses into a module") } #[cfg(test)] mod tests { use std::path::Path; use anyhow::Result; use ruff_python_ast::{PySourceType, PythonVersion}; use ruff_python_codegen::Stylist; use ruff_python_index::Indexer; use ruff_python_parser::ParseOptions; use ruff_python_trivia::textwrap::dedent; use test_case::test_case; use ruff_db::diagnostic::Diagnostic; use ruff_notebook::{Notebook, NotebookError}; use crate::linter::check_path; use crate::registry::Rule; use crate::settings::LinterSettings; use crate::source_kind::SourceKind; use crate::suppression::Suppressions; use crate::test::{TestedNotebook, assert_notebook_path, test_contents, test_snippet}; use crate::{Locator, assert_diagnostics, directives, settings}; /// Construct a path to a Jupyter notebook in the `resources/test/fixtures/jupyter` directory. fn notebook_path(path: impl AsRef<Path>) -> std::path::PathBuf { Path::new("../ruff_notebook/resources/test/fixtures/jupyter").join(path) } #[test] fn test_import_sorting() -> Result<(), NotebookError> { let actual = notebook_path("isort.ipynb"); let expected = notebook_path("isort_expected.ipynb"); let TestedNotebook { diagnostics, source_notebook, .. } = assert_notebook_path( &actual, expected, &LinterSettings::for_rule(Rule::UnsortedImports), )?; assert_diagnostics!(diagnostics, actual, source_notebook); Ok(()) } #[test] fn test_ipy_escape_command() -> Result<(), NotebookError> { let actual = notebook_path("ipy_escape_command.ipynb"); let expected = notebook_path("ipy_escape_command_expected.ipynb"); let TestedNotebook { diagnostics, source_notebook, .. } = assert_notebook_path( &actual, expected, &LinterSettings::for_rule(Rule::UnusedImport), )?; assert_diagnostics!(diagnostics, actual, source_notebook); Ok(()) } #[test] fn test_unused_variable() -> Result<(), NotebookError> { let actual = notebook_path("unused_variable.ipynb"); let expected = notebook_path("unused_variable_expected.ipynb"); let TestedNotebook { diagnostics, source_notebook, .. } = assert_notebook_path( &actual, expected, &LinterSettings::for_rule(Rule::UnusedVariable), )?; assert_diagnostics!(diagnostics, actual, source_notebook); Ok(()) } #[test] fn test_undefined_name() -> Result<(), NotebookError> { let actual = notebook_path("undefined_name.ipynb"); let expected = notebook_path("undefined_name.ipynb"); let TestedNotebook { diagnostics, source_notebook, .. } = assert_notebook_path( &actual, expected, &LinterSettings::for_rule(Rule::UndefinedName), )?; assert_diagnostics!(diagnostics, actual, source_notebook); Ok(()) } #[test] fn test_json_consistency() -> Result<()> { let actual_path = notebook_path("before_fix.ipynb"); let expected_path = notebook_path("after_fix.ipynb"); let TestedNotebook { linted_notebook: fixed_notebook, .. } = assert_notebook_path( actual_path, &expected_path, &LinterSettings::for_rule(Rule::UnusedImport), )?; let mut writer = Vec::new(); fixed_notebook.write(&mut writer)?; let actual = String::from_utf8(writer)?; let expected = std::fs::read_to_string(expected_path)?; assert_eq!(actual, expected); Ok(()) } #[test] fn test_vscode_language_id() -> Result<()> { let actual = notebook_path("vscode_language_id.ipynb"); let expected = notebook_path("vscode_language_id_expected.ipynb"); let TestedNotebook { diagnostics, source_notebook, .. } = assert_notebook_path( &actual, expected, &LinterSettings::for_rule(Rule::UnusedImport), )?; assert_diagnostics!(diagnostics, actual, source_notebook); Ok(()) } #[test_case(Path::new("before_fix.ipynb"), true; "trailing_newline")] #[test_case(Path::new("no_trailing_newline.ipynb"), false; "no_trailing_newline")] fn test_trailing_newline(path: &Path, trailing_newline: bool) -> Result<()> { let notebook = Notebook::from_path(&notebook_path(path))?; assert_eq!(notebook.trailing_newline(), trailing_newline); let mut writer = Vec::new(); notebook.write(&mut writer)?; let string = String::from_utf8(writer)?; assert_eq!(string.ends_with('\n'), trailing_newline); Ok(()) } // Version <4.5, don't emit cell ids #[test_case(Path::new("no_cell_id.ipynb"), false; "no_cell_id")] // Version 4.5, cell ids are missing and need to be added #[test_case(Path::new("add_missing_cell_id.ipynb"), true; "add_missing_cell_id")] fn test_cell_id(path: &Path, has_id: bool) -> Result<()> { let source_notebook = Notebook::from_path(&notebook_path(path))?; let source_kind = SourceKind::ipy_notebook(source_notebook); let (_, transformed) = test_contents( &source_kind, path, &LinterSettings::for_rule(Rule::UnusedImport), ); let linted_notebook = transformed.into_owned().expect_ipy_notebook(); let mut writer = Vec::new(); linted_notebook.write(&mut writer)?; let actual = String::from_utf8(writer)?; if has_id { assert!(actual.contains(r#""id": ""#)); } else { assert!(!actual.contains(r#""id":"#)); } Ok(()) } /// A custom test runner that prints syntax errors in addition to other diagnostics. Adapted /// from `flakes` in pyflakes/mod.rs. fn test_contents_syntax_errors( source_kind: &SourceKind, path: &Path, settings: &LinterSettings, ) -> Vec<Diagnostic> { let source_type = PySourceType::from(path); let target_version = settings.resolve_target_version(path); let options = ParseOptions::from(source_type).with_target_version(target_version.parser_version()); let parsed = ruff_python_parser::parse_unchecked(source_kind.source_code(), options) .try_into_module() .expect("PySourceType always parses into a module"); let locator = Locator::new(source_kind.source_code()); let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); let directives = directives::extract_directives( parsed.tokens(), directives::Flags::from_settings(settings), &locator, &indexer, ); let suppressions = Suppressions::from_tokens(settings, locator.contents(), parsed.tokens()); let mut diagnostics = check_path( path, None, &locator, &stylist, &indexer, &directives, settings, settings::flags::Noqa::Enabled, source_kind, source_type, &parsed, target_version, &suppressions, ); diagnostics.sort_by(Diagnostic::ruff_start_ordering); diagnostics } #[test_case( Path::new("async_comprehension_outside_async_function.py"), PythonVersion::PY311 )] #[test_case( Path::new("async_comprehension_outside_async_function.py"), PythonVersion::PY310 )] #[test_case(Path::new("rebound_comprehension.py"), PythonVersion::PY310)]
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/text_helpers.rs
crates/ruff_linter/src/text_helpers.rs
use std::borrow::Cow; pub(crate) trait ShowNonprinting { fn show_nonprinting(&self) -> Cow<'_, str>; } macro_rules! impl_show_nonprinting { ($(($from:expr, $to:expr)),+) => { impl ShowNonprinting for str { fn show_nonprinting(&self) -> Cow<'_, str> { if self.find(&[$($from),*][..]).is_some() { Cow::Owned( self.$(replace($from, $to)).* ) } else { Cow::Borrowed(self) } } } }; } impl_show_nonprinting!(('\x07', "␇"), ('\x08', "␈"), ('\x1b', "␛"), ('\x7f', "␡"));
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/test.rs
crates/ruff_linter/src/test.rs
#![cfg(any(test, fuzzing))] //! Helper functions for the tests of rule implementations. use std::borrow::Cow; use std::fmt; use std::path::Path; #[cfg(not(fuzzing))] use anyhow::Result; use itertools::Itertools; use rustc_hash::FxHashMap; use ruff_db::diagnostic::{ Diagnostic, DiagnosticFormat, DisplayDiagnosticConfig, DisplayDiagnostics, Span, }; use ruff_notebook::Notebook; #[cfg(not(fuzzing))] use ruff_notebook::NotebookError; use ruff_python_ast::PySourceType; use ruff_python_codegen::Stylist; use ruff_python_index::Indexer; use ruff_python_parser::{ParseError, ParseOptions}; use ruff_python_trivia::textwrap::dedent; use ruff_source_file::SourceFileBuilder; use crate::codes::Rule; use crate::fix::{FixResult, fix_file}; use crate::linter::check_path; use crate::message::EmitterContext; use crate::package::PackageRoot; use crate::packaging::detect_package_root; use crate::settings::types::UnsafeFixes; use crate::settings::{LinterSettings, flags}; use crate::source_kind::SourceKind; use crate::suppression::Suppressions; use crate::{Applicability, FixAvailability}; use crate::{Locator, directives}; /// Represents the difference between two diagnostic runs. #[derive(Debug)] pub(crate) struct DiagnosticsDiff { /// Diagnostics that were removed (present in 'before' but not in 'after') removed: Vec<Diagnostic>, /// Diagnostics that were added (present in 'after' but not in 'before') added: Vec<Diagnostic>, /// Settings used before the change settings_before: LinterSettings, /// Settings used after the change settings_after: LinterSettings, } impl fmt::Display for DiagnosticsDiff { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "--- Linter settings ---")?; let settings_before_str = format!("{}", self.settings_before); let settings_after_str = format!("{}", self.settings_after); let diff = similar::TextDiff::from_lines(&settings_before_str, &settings_after_str); for change in diff.iter_all_changes() { match change.tag() { similar::ChangeTag::Delete => write!(f, "-{change}")?, similar::ChangeTag::Insert => write!(f, "+{change}")?, similar::ChangeTag::Equal => (), } } writeln!(f)?; writeln!(f, "--- Summary ---")?; writeln!(f, "Removed: {}", self.removed.len())?; writeln!(f, "Added: {}", self.added.len())?; writeln!(f)?; if !self.removed.is_empty() { writeln!(f, "--- Removed ---")?; for diagnostic in &self.removed { writeln!(f, "{}", print_messages(std::slice::from_ref(diagnostic)))?; } writeln!(f)?; } if !self.added.is_empty() { writeln!(f, "--- Added ---")?; for diagnostic in &self.added { writeln!(f, "{}", print_messages(std::slice::from_ref(diagnostic)))?; } writeln!(f)?; } Ok(()) } } /// Compare two sets of diagnostics and return the differences fn diff_diagnostics( before: Vec<Diagnostic>, after: Vec<Diagnostic>, settings_before: &LinterSettings, settings_after: &LinterSettings, ) -> DiagnosticsDiff { let mut removed = Vec::new(); let mut added = after; for old_diag in before { let Some(pos) = added.iter().position(|diag| diag == &old_diag) else { removed.push(old_diag); continue; }; added.remove(pos); } DiagnosticsDiff { removed, added, settings_before: settings_before.clone(), settings_after: settings_after.clone(), } } #[cfg(not(fuzzing))] pub(crate) fn test_resource_path(path: impl AsRef<Path>) -> std::path::PathBuf { Path::new("./resources/test/").join(path) } /// Run [`check_path`] on a Python file in the `resources/test/fixtures` directory. #[cfg(not(fuzzing))] pub(crate) fn test_path( path: impl AsRef<Path>, settings: &LinterSettings, ) -> Result<Vec<Diagnostic>> { let path = test_resource_path("fixtures").join(path); let source_type = PySourceType::from(&path); let source_kind = SourceKind::from_path(path.as_ref(), source_type)?.expect("valid source"); Ok(test_contents(&source_kind, &path, settings).0) } /// Test a file with two different settings and return the differences #[cfg(not(fuzzing))] pub(crate) fn test_path_with_settings_diff( path: impl AsRef<Path>, settings_before: &LinterSettings, settings_after: &LinterSettings, ) -> Result<DiagnosticsDiff> { assert!( format!("{settings_before}") != format!("{settings_after}"), "Settings must be different for differential testing" ); let diagnostics_before = test_path(&path, settings_before)?; let diagnostic_after = test_path(&path, settings_after)?; let diff = diff_diagnostics( diagnostics_before, diagnostic_after, settings_before, settings_after, ); Ok(diff) } #[cfg(not(fuzzing))] pub(crate) struct TestedNotebook { pub(crate) diagnostics: Vec<Diagnostic>, pub(crate) source_notebook: Notebook, pub(crate) linted_notebook: Notebook, } #[cfg(not(fuzzing))] pub(crate) fn assert_notebook_path( path: impl AsRef<Path>, expected: impl AsRef<Path>, settings: &LinterSettings, ) -> Result<TestedNotebook, NotebookError> { let source_notebook = Notebook::from_path(path.as_ref())?; let source_kind = SourceKind::ipy_notebook(source_notebook); let (messages, transformed) = test_contents(&source_kind, path.as_ref(), settings); let expected_notebook = Notebook::from_path(expected.as_ref())?; let linted_notebook = transformed.into_owned().expect_ipy_notebook(); assert_eq!( linted_notebook.cell_offsets(), expected_notebook.cell_offsets() ); assert_eq!(linted_notebook.index(), expected_notebook.index()); assert_eq!( linted_notebook.source_code(), expected_notebook.source_code() ); Ok(TestedNotebook { diagnostics: messages, source_notebook: source_kind.expect_ipy_notebook(), linted_notebook, }) } /// Run [`check_path`] on a snippet of Python code. pub fn test_snippet(contents: &str, settings: &LinterSettings) -> Vec<Diagnostic> { let path = Path::new("<filename>"); let contents = dedent(contents); test_contents(&SourceKind::Python(contents.into_owned()), path, settings).0 } thread_local! { static MAX_ITERATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(10) }; } pub fn set_max_iterations(max: usize) { MAX_ITERATIONS.with(|iterations| iterations.set(max)); } pub(crate) fn max_iterations() -> usize { MAX_ITERATIONS.with(std::cell::Cell::get) } /// A convenient wrapper around [`check_path`], that additionally /// asserts that fixes converge after a fixed number of iterations. pub(crate) fn test_contents<'a>( source_kind: &'a SourceKind, path: &Path, settings: &LinterSettings, ) -> (Vec<Diagnostic>, Cow<'a, SourceKind>) { let source_type = PySourceType::from(path); let target_version = settings.resolve_target_version(path); let options = ParseOptions::from(source_type).with_target_version(target_version.parser_version()); let parsed = ruff_python_parser::parse_unchecked(source_kind.source_code(), options.clone()) .try_into_module() .expect("PySourceType always parses into a module"); let locator = Locator::new(source_kind.source_code()); let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); let directives = directives::extract_directives( parsed.tokens(), directives::Flags::from_settings(settings), &locator, &indexer, ); let suppressions = Suppressions::from_tokens(settings, locator.contents(), parsed.tokens()); let messages = check_path( path, path.parent() .and_then(|parent| detect_package_root(parent, &settings.namespace_packages)) .map(|path| PackageRoot::Root { path }), &locator, &stylist, &indexer, &directives, settings, flags::Noqa::Enabled, source_kind, source_type, &parsed, target_version, &suppressions, ); let source_has_errors = parsed.has_invalid_syntax(); // Detect fixes that don't converge after multiple iterations. let mut iterations = 0; let mut transformed = Cow::Borrowed(source_kind); if messages.iter().any(|message| message.fix().is_some()) { let mut messages = messages.clone(); while let Some(FixResult { code: fixed_contents, source_map, .. }) = fix_file( &messages, &Locator::new(transformed.source_code()), UnsafeFixes::Enabled, ) { if iterations < max_iterations() { iterations += 1; } else { let output = print_diagnostics(messages, path, &transformed); panic!( "Failed to converge after {} iterations. This likely \ indicates a bug in the implementation of the fix. Last diagnostics:\n{}", max_iterations(), output ); } transformed = Cow::Owned(transformed.updated(fixed_contents, &source_map)); let parsed = ruff_python_parser::parse_unchecked(transformed.source_code(), options.clone()) .try_into_module() .expect("PySourceType always parses into a module"); let locator = Locator::new(transformed.source_code()); let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); let directives = directives::extract_directives( parsed.tokens(), directives::Flags::from_settings(settings), &locator, &indexer, ); let suppressions = Suppressions::from_tokens(settings, locator.contents(), parsed.tokens()); let fixed_messages = check_path( path, None, &locator, &stylist, &indexer, &directives, settings, flags::Noqa::Enabled, &transformed, source_type, &parsed, target_version, &suppressions, ); if parsed.has_invalid_syntax() && !source_has_errors { // Previous fix introduced a syntax error, abort let fixes = print_diagnostics(messages, path, source_kind); let syntax_errors = print_syntax_errors(parsed.errors(), path, &transformed); panic!( "Fixed source has a syntax error where the source document does not. This is a bug in one of the generated fixes: {syntax_errors} Last generated fixes: {fixes} Source with applied fixes: {}", transformed.source_code() ); } messages = fixed_messages; } } let source_code = SourceFileBuilder::new( path.file_name().unwrap().to_string_lossy().as_ref(), source_kind.source_code(), ) .finish(); let messages = messages .into_iter() .filter_map(|msg| Some((msg.secondary_code()?.to_string(), msg))) .map(|(code, mut diagnostic)| { let rule = Rule::from_code(&code).unwrap(); let fixable = diagnostic.fix().is_some_and(|fix| { matches!( fix.applicability(), Applicability::Safe | Applicability::Unsafe ) }); match (fixable, rule.fixable()) { (true, FixAvailability::Sometimes | FixAvailability::Always) | (false, FixAvailability::None | FixAvailability::Sometimes) => { // Ok } (true, FixAvailability::None) => { panic!( "Rule {rule:?} is marked as non-fixable but it created a fix. Change the `Violation::FIX_AVAILABILITY` to either \ `FixAvailability::Sometimes` or `FixAvailability::Always`" ); } (false, FixAvailability::Always) if source_has_errors => { // Ok } (false, FixAvailability::Always) => { panic!( "\ Rule {rule:?} is marked to always-fixable but the diagnostic has no fix. Either ensure you always emit a fix or change `Violation::FIX_AVAILABILITY` to either \ `FixAvailability::Sometimes` or `FixAvailability::None`" ) } } assert!( !(fixable && diagnostic.first_help_text().is_none()), "Diagnostic emitted by {rule:?} is fixable but \ `Violation::fix_title` returns `None`" ); // Not strictly necessary but adds some coverage for this code path by overriding the // noqa offset and the source file if let Some(range) = diagnostic.range() { diagnostic.set_noqa_offset(directives.noqa_line_for.resolve(range.start())); } // This part actually is necessary to avoid long relative paths in snapshots. for annotation in diagnostic.annotations_mut() { if let Some(range) = annotation.get_span().range() { annotation.set_span(Span::from(source_code.clone()).with_range(range)); } } for sub in diagnostic.sub_diagnostics_mut() { for annotation in sub.annotations_mut() { if let Some(range) = annotation.get_span().range() { annotation.set_span(Span::from(source_code.clone()).with_range(range)); } } } diagnostic }) .chain(parsed.errors().iter().map(|parse_error| { Diagnostic::invalid_syntax(source_code.clone(), &parse_error.error, parse_error) })) .sorted_by(Diagnostic::ruff_start_ordering) .collect(); (messages, transformed) } fn print_syntax_errors(errors: &[ParseError], path: &Path, source: &SourceKind) -> String { let filename = path.file_name().unwrap().to_string_lossy(); let source_file = SourceFileBuilder::new(filename.as_ref(), source.source_code()).finish(); let messages: Vec<_> = errors .iter() .map(|parse_error| { Diagnostic::invalid_syntax(source_file.clone(), &parse_error.error, parse_error) }) .collect(); if let Some(notebook) = source.as_ipy_notebook() { print_jupyter_messages(&messages, path, notebook) } else { print_messages(&messages) } } /// Print the lint diagnostics in `diagnostics`. fn print_diagnostics(mut diagnostics: Vec<Diagnostic>, path: &Path, source: &SourceKind) -> String { diagnostics.retain(|msg| !msg.is_invalid_syntax()); if let Some(notebook) = source.as_ipy_notebook() { print_jupyter_messages(&diagnostics, path, notebook) } else { print_messages(&diagnostics) } } pub(crate) fn print_jupyter_messages( diagnostics: &[Diagnostic], path: &Path, notebook: &Notebook, ) -> String { let config = DisplayDiagnosticConfig::default() .format(DiagnosticFormat::Full) .hide_severity(true) .with_show_fix_status(true) .show_fix_diff(true) .with_fix_applicability(Applicability::DisplayOnly); DisplayDiagnostics::new( &EmitterContext::new(&FxHashMap::from_iter([( path.file_name().unwrap().to_string_lossy().to_string(), notebook.index().clone(), )])), &config, diagnostics, ) .to_string() } pub(crate) fn print_messages(diagnostics: &[Diagnostic]) -> String { let config = DisplayDiagnosticConfig::default() .format(DiagnosticFormat::Full) .hide_severity(true) .with_show_fix_status(true) .show_fix_diff(true) .with_fix_applicability(Applicability::DisplayOnly); DisplayDiagnostics::new( &EmitterContext::new(&FxHashMap::default()), &config, diagnostics, ) .to_string() } #[macro_export] macro_rules! assert_diagnostics { ($value:expr, $path:expr, $notebook:expr) => {{ insta::with_settings!({ omit_expression => true }, { insta::assert_snapshot!( $crate::test::print_jupyter_messages(&$value, &$path, &$notebook) ); }); }}; ($value:expr, @$snapshot:literal) => {{ insta::with_settings!({ omit_expression => true }, { insta::assert_snapshot!($crate::test::print_messages(&$value), @$snapshot); }); }}; ($name:expr, $value:expr) => {{ insta::with_settings!({ omit_expression => true }, { insta::assert_snapshot!($name, $crate::test::print_messages(&$value)); }); }}; ($value:expr) => {{ insta::with_settings!({ omit_expression => true }, { insta::assert_snapshot!($crate::test::print_messages(&$value)); }); }}; } #[macro_export] macro_rules! assert_diagnostics_diff { ($snapshot:expr, $path:expr, $settings_before:expr, $settings_after:expr $(,)?) => {{ let diff = $crate::test::test_path_with_settings_diff($path, $settings_before, $settings_after)?; insta::with_settings!({ omit_expression => true }, { insta::assert_snapshot!($snapshot, format!("{}", diff)); }); }}; ($path:expr, $settings_before:expr, $settings_after:expr $(,)?) => {{ let diff = $crate::test::test_path_with_settings_diff($path, $settings_before, $settings_after)?; insta::with_settings!({ omit_expression => true }, { insta::assert_snapshot!(format!("{}", diff)); }); }}; } #[cfg(test)] mod tests { use super::*; #[test] fn test_diff_diagnostics() -> Result<()> { use crate::codes::Rule; use ruff_db::diagnostic::{DiagnosticId, LintName}; let settings_before = LinterSettings::for_rule(Rule::Print); let settings_after = LinterSettings::for_rule(Rule::UnusedImport); let test_code = r#" import sys import unused_module def main(): print(sys.version) "#; let temp_dir = std::env::temp_dir(); let test_file = temp_dir.join("test_diff.py"); std::fs::write(&test_file, test_code)?; let diff = super::test_path_with_settings_diff(&test_file, &settings_before, &settings_after)?; assert_eq!(diff.removed.len(), 1, "Should remove 1 print diagnostic"); assert_eq!( diff.removed[0].id(), DiagnosticId::Lint(LintName::of("print")), "Should remove the print diagnostic" ); assert_eq!(diff.added.len(), 1, "Should add 1 unused import diagnostic"); assert_eq!( diff.added[0].id(), DiagnosticId::Lint(LintName::of("unused-import")), "Should add the unused import diagnostic" ); std::fs::remove_file(test_file)?; Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/lib.rs
crates/ruff_linter/src/lib.rs
//! This is the library for the [Ruff] Python linter. //! //! **The API is currently completely unstable** //! and subject to change drastically. //! //! [Ruff]: https://github.com/astral-sh/ruff pub use locator::Locator; pub use noqa::generate_noqa_edits; #[cfg(feature = "clap")] pub use registry::clap_completion::RuleParser; pub use rule_selector::RuleSelector; #[cfg(feature = "clap")] pub use rule_selector::clap_completion::RuleSelectorParser; pub use rules::pycodestyle::rules::IOError; pub(crate) use ruff_diagnostics::{Applicability, Edit, Fix}; pub use violation::{AlwaysFixableViolation, FixAvailability, Violation, ViolationMetadata}; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); mod checkers; pub mod codes; mod comments; mod cst; pub mod directives; mod doc_lines; mod docstrings; mod fix; pub mod fs; mod importer; pub mod line_width; pub mod linter; mod locator; pub mod logging; pub mod message; mod noqa; pub mod package; pub mod packaging; pub mod preview; pub mod pyproject_toml; pub mod registry; mod renamer; mod rule_redirects; pub mod rule_selector; pub mod rules; pub mod settings; pub mod source_kind; pub mod suppression; mod text_helpers; pub mod upstream_categories; mod violation; #[cfg(any(test, fuzzing))] pub mod test; pub const RUFF_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg(test)] mod tests { use std::path::Path; use ruff_python_ast::PySourceType; use crate::codes::Rule; use crate::settings::LinterSettings; use crate::source_kind::SourceKind; use crate::test::{print_messages, test_contents}; /// Test for ad-hoc debugging. #[test] #[ignore] fn linter_quick_test() { let code = r#"class Platform: """ Remove sampler Args:     Returns: """ "#; let source_type = PySourceType::Python; let rule = Rule::OverIndentation; let source_kind = SourceKind::from_source_code(code.to_string(), source_type) .expect("Source code should be valid") .expect("Notebook to contain python code"); let (diagnostics, fixed) = test_contents( &source_kind, Path::new("ruff_linter/rules/quick_test"), &LinterSettings::for_rule(rule), ); assert_eq!(print_messages(&diagnostics), ""); assert_eq!(fixed.source_code(), code); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/upstream_categories.rs
crates/ruff_linter/src/upstream_categories.rs
//! This module should probably not exist in this shape or form. use crate::codes::Rule; use crate::registry::Linter; #[derive(Hash, Eq, PartialEq, Copy, Clone, Debug)] pub struct UpstreamCategoryAndPrefix { pub category: &'static str, pub prefix: &'static str, } const C: UpstreamCategoryAndPrefix = UpstreamCategoryAndPrefix { category: "Convention", prefix: "C", }; const E: UpstreamCategoryAndPrefix = UpstreamCategoryAndPrefix { category: "Error", prefix: "E", }; const R: UpstreamCategoryAndPrefix = UpstreamCategoryAndPrefix { category: "Refactor", prefix: "R", }; const W: UpstreamCategoryAndPrefix = UpstreamCategoryAndPrefix { category: "Warning", prefix: "W", }; impl Rule { pub fn upstream_category(&self, linter: &Linter) -> Option<UpstreamCategoryAndPrefix> { let code = linter.code_for_rule(*self).unwrap(); match linter { Linter::Pycodestyle => { if code.starts_with('E') { Some(E) } else if code.starts_with('W') { Some(W) } else { None } } Linter::Pylint => { if code.starts_with('C') { Some(C) } else if code.starts_with('E') { Some(E) } else if code.starts_with('R') { Some(R) } else if code.starts_with('W') { Some(W) } else { None } } _ => None, } } } impl Linter { pub const fn upstream_categories(&self) -> Option<&'static [UpstreamCategoryAndPrefix]> { match self { Linter::Pycodestyle => Some(&[E, W]), Linter::Pylint => Some(&[C, E, R, W]), _ => None, } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/doc_lines.rs
crates/ruff_linter/src/doc_lines.rs
//! Doc line extraction. In this context, a doc line is a line consisting of a //! standalone comment or a constant string statement. use std::iter::FusedIterator; use std::slice::Iter; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; use ruff_python_ast::token::{Token, TokenKind, Tokens}; use ruff_python_ast::{self as ast, Stmt, Suite}; use ruff_source_file::UniversalNewlineIterator; use ruff_text_size::{Ranged, TextSize}; use crate::Locator; /// Extract doc lines (standalone comments) from a token sequence. pub(crate) fn doc_lines_from_tokens(tokens: &Tokens) -> DocLines<'_> { DocLines::new(tokens) } pub(crate) struct DocLines<'a> { inner: Iter<'a, Token>, prev: TextSize, } impl<'a> DocLines<'a> { fn new(tokens: &'a Tokens) -> Self { Self { inner: tokens.iter(), prev: TextSize::default(), } } } impl Iterator for DocLines<'_> { type Item = TextSize; fn next(&mut self) -> Option<Self::Item> { let mut at_start_of_line = true; loop { let token = self.inner.next()?; match token.kind() { TokenKind::Comment => { if at_start_of_line { break Some(token.start()); } } TokenKind::Newline | TokenKind::NonLogicalNewline => { at_start_of_line = true; } TokenKind::Indent | TokenKind::Dedent => { // ignore } _ => { at_start_of_line = false; } } self.prev = token.end(); } } } impl FusedIterator for DocLines<'_> {} struct StringLinesVisitor<'a> { string_lines: Vec<TextSize>, locator: &'a Locator<'a>, } impl StatementVisitor<'_> for StringLinesVisitor<'_> { fn visit_stmt(&mut self, stmt: &Stmt) { if let Stmt::Expr(ast::StmtExpr { value: expr, range: _, node_index: _, }) = stmt { if expr.is_string_literal_expr() { for line in UniversalNewlineIterator::with_offset( self.locator.slice(expr.as_ref()), expr.start(), ) { self.string_lines.push(line.start()); } } } walk_stmt(self, stmt); } } impl<'a> StringLinesVisitor<'a> { fn new(locator: &'a Locator<'a>) -> Self { Self { string_lines: Vec::new(), locator, } } } /// Extract doc lines (standalone strings) start positions from an AST. pub(crate) fn doc_lines_from_ast(python_ast: &Suite, locator: &Locator) -> Vec<TextSize> { let mut visitor = StringLinesVisitor::new(locator); visitor.visit_body(python_ast); visitor.string_lines }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rule_redirects.rs
crates/ruff_linter/src/rule_redirects.rs
use std::collections::HashMap; use std::sync::LazyLock; /// Returns the redirect target for the given code. pub(crate) fn get_redirect_target(code: &str) -> Option<&'static str> { REDIRECTS.get(code).copied() } /// Returns the code and the redirect target if the given code is a redirect. /// (The same code is returned to obtain it with a static lifetime). pub(crate) fn get_redirect(code: &str) -> Option<(&'static str, &'static str)> { REDIRECTS.get_key_value(code).map(|(k, v)| (*k, *v)) } static REDIRECTS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| { HashMap::from_iter([ // The following are here because we don't yet have the many-to-one mapping enabled. ("SIM111", "SIM110"), // The following are deprecated. ("C9", "C90"), ("T1", "T10"), ("T2", "T20"), // TODO(charlie): Remove by 2023-02-01. ("R", "RET"), ("R5", "RET5"), ("R50", "RET50"), ("R501", "RET501"), ("R502", "RET502"), ("R503", "RET503"), ("R504", "RET504"), ("R505", "RET505"), ("R506", "RET506"), ("R507", "RET507"), ("R508", "RET508"), ("IC", "ICN"), ("IC0", "ICN0"), ("IC00", "ICN00"), ("IC001", "ICN001"), ("IC002", "ICN001"), ("IC003", "ICN001"), ("IC004", "ICN001"), // TODO(charlie): Remove by 2023-01-01. ("U", "UP"), ("U0", "UP0"), ("U00", "UP00"), ("U001", "UP001"), ("U003", "UP003"), ("U004", "UP004"), ("U005", "UP005"), ("U006", "UP006"), ("U007", "UP007"), ("U008", "UP008"), ("U009", "UP009"), ("U01", "UP01"), ("U010", "UP010"), ("U011", "UP011"), ("U012", "UP012"), ("U013", "UP013"), ("U014", "UP014"), ("U015", "UP015"), ("U016", "UP016"), ("U017", "UP017"), ("U019", "UP019"), // TODO(charlie): Remove by 2023-02-01. ("I2", "TID2"), ("I25", "TID25"), ("I252", "TID252"), ("M", "RUF100"), ("M0", "RUF100"), ("M001", "RUF100"), // TODO(charlie): Remove by 2023-02-01. ("PDV", "PD"), ("PDV0", "PD0"), ("PDV002", "PD002"), ("PDV003", "PD003"), ("PDV004", "PD004"), ("PDV007", "PD007"), ("PDV008", "PD008"), ("PDV009", "PD009"), ("PDV01", "PD01"), ("PDV010", "PD010"), ("PDV011", "PD011"), ("PDV012", "PD012"), ("PDV013", "PD013"), ("PDV015", "PD015"), ("PDV9", "PD9"), ("PDV90", "PD90"), ("PDV901", "PD901"), // TODO(charlie): Remove by 2023-04-01. ("TYP", "TC"), ("TYP001", "TC001"), // TODO(charlie): Remove by 2023-06-01. ("RUF004", "B026"), ("PIE802", "C419"), ("PLW0130", "B033"), ("T001", "FIX001"), ("T002", "FIX002"), ("T003", "FIX003"), ("T004", "FIX004"), ("RUF011", "B035"), ("TRY200", "B904"), ("PGH001", "S307"), ("PGH002", "G010"), // flake8-trio and flake8-async merged with name flake8-async ("TRIO", "ASYNC1"), ("TRIO1", "ASYNC1"), ("TRIO10", "ASYNC10"), ("TRIO100", "ASYNC100"), ("TRIO105", "ASYNC105"), ("TRIO109", "ASYNC109"), ("TRIO11", "ASYNC11"), ("TRIO110", "ASYNC110"), ("TRIO115", "ASYNC115"), // Removed in v0.5 ("PLR1701", "SIM101"), // Test redirect by exact code #[cfg(any(feature = "test-rules", test))] ("RUF940", "RUF950"), // Test redirect by prefix #[cfg(any(feature = "test-rules", test))] ("RUF96", "RUF95"), // See: https://github.com/astral-sh/ruff/issues/10791 ("PLW0117", "PLW0177"), // See: https://github.com/astral-sh/ruff/issues/12110 ("RUF025", "C420"), // See: https://github.com/astral-sh/ruff/issues/13492 ("TRY302", "TRY203"), // TCH renamed to TC to harmonize with flake8 plugin ("TCH", "TC"), ("TCH001", "TC001"), ("TCH002", "TC002"), ("TCH003", "TC003"), ("TCH004", "TC004"), ("TCH005", "TC005"), ("TCH006", "TC010"), ("TCH010", "TC010"), ("RUF035", "S704"), ]) }); #[cfg(test)] mod tests { use crate::codes::{Rule, RuleGroup}; use crate::rule_redirects::REDIRECTS; use strum::IntoEnumIterator; /// Tests for rule codes that overlap with a redirect. #[test] fn overshadowing_redirects() { for rule in Rule::iter() { let (code, group) = (rule.noqa_code(), rule.group()); if matches!(group, RuleGroup::Removed { .. }) { continue; } if let Some(redirect_target) = REDIRECTS.get(&*code.to_string()) { panic!( "Rule {code} is overshadowed by a redirect, which points to {redirect_target}." ); } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/suppression.rs
crates/ruff_linter/src/suppression.rs
use compact_str::CompactString; use core::fmt; use ruff_db::diagnostic::Diagnostic; use ruff_diagnostics::{Edit, Fix}; use ruff_python_ast::token::{TokenKind, Tokens}; use ruff_python_ast::whitespace::indentation; use rustc_hash::FxHashSet; use std::cell::Cell; use std::{error::Error, fmt::Formatter}; use thiserror::Error; use ruff_python_trivia::Cursor; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize, TextSlice}; use smallvec::{SmallVec, smallvec}; use crate::Locator; use crate::checkers::ast::LintContext; use crate::codes::Rule; use crate::fix::edits::delete_comment; use crate::preview::is_range_suppressions_enabled; use crate::rule_redirects::get_redirect_target; use crate::rules::ruff::rules::{ InvalidRuleCode, InvalidRuleCodeKind, InvalidSuppressionComment, InvalidSuppressionCommentKind, UnmatchedSuppressionComment, UnusedCodes, UnusedNOQA, UnusedNOQAKind, code_is_valid, }; use crate::settings::LinterSettings; #[derive(Clone, Debug, Eq, PartialEq)] enum SuppressionAction { Disable, Enable, } #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct SuppressionComment { /// Range containing the entire suppression comment range: TextRange, /// The action directive action: SuppressionAction, /// Ranges containing the lint codes being suppressed codes: SmallVec<[TextRange; 2]>, /// Range containing the reason for the suppression reason: TextRange, } impl SuppressionComment { /// Return the suppressed codes as strings fn codes_as_str<'src>(&self, source: &'src str) -> impl Iterator<Item = &'src str> { self.codes.iter().map(|range| source.slice(range)) } } #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct PendingSuppressionComment<'a> { /// How indented an own-line comment is, or None for trailing comments indent: &'a str, /// The suppression comment comment: SuppressionComment, } impl PendingSuppressionComment<'_> { /// Whether the comment "matches" another comment, based on indentation and suppressed codes /// Expects a "forward search" for matches, ie, will only match if the current comment is a /// "disable" comment and other is the matching "enable" comment. fn matches(&self, other: &PendingSuppressionComment, source: &str) -> bool { self.comment.action == SuppressionAction::Disable && other.comment.action == SuppressionAction::Enable && self.indent == other.indent && self .comment .codes_as_str(source) .eq(other.comment.codes_as_str(source)) } } #[derive(Debug)] pub(crate) struct Suppression { /// The lint code being suppressed code: CompactString, /// Range for which the suppression applies range: TextRange, /// Any comments associated with the suppression comments: SmallVec<[SuppressionComment; 2]>, /// Whether this suppression actually suppressed a diagnostic used: Cell<bool>, } #[derive(Copy, Clone, Debug)] pub(crate) enum InvalidSuppressionKind { /// Trailing suppression not supported Trailing, /// No matching enable or disable suppression found Unmatched, /// Suppression does not match surrounding indentation Indentation, } #[allow(unused)] #[derive(Clone, Debug)] pub(crate) struct InvalidSuppression { kind: InvalidSuppressionKind, comment: SuppressionComment, } #[allow(unused)] #[derive(Debug, Default)] pub struct Suppressions { /// Valid suppression ranges with associated comments valid: Vec<Suppression>, /// Invalid suppression comments invalid: Vec<InvalidSuppression>, /// Parse errors from suppression comments errors: Vec<ParseError>, } impl Suppressions { pub fn from_tokens(settings: &LinterSettings, source: &str, tokens: &Tokens) -> Suppressions { if is_range_suppressions_enabled(settings) { let builder = SuppressionsBuilder::new(source); builder.load_from_tokens(tokens) } else { Suppressions::default() } } pub(crate) fn is_empty(&self) -> bool { self.valid.is_empty() && self.invalid.is_empty() && self.errors.is_empty() } /// Check if a diagnostic is suppressed by any known range suppressions pub(crate) fn check_diagnostic(&self, diagnostic: &Diagnostic) -> bool { if self.valid.is_empty() { return false; } let Some(code) = diagnostic.secondary_code() else { return false; }; let Some(span) = diagnostic.primary_span() else { return false; }; let Some(range) = span.range() else { return false; }; for suppression in &self.valid { let suppression_code = get_redirect_target(suppression.code.as_str()).unwrap_or(suppression.code.as_str()); if *code == suppression_code && suppression.range.contains_range(range) { suppression.used.set(true); return true; } } false } pub(crate) fn check_suppressions(&self, context: &LintContext, locator: &Locator) { let mut unmatched_ranges = FxHashSet::default(); for suppression in &self.valid { if !code_is_valid(&suppression.code, &context.settings().external) { // InvalidRuleCode if context.is_rule_enabled(Rule::InvalidRuleCode) { for comment in &suppression.comments { let (range, edit) = Suppressions::delete_code_or_comment( locator, suppression, comment, true, ); context .report_diagnostic( InvalidRuleCode { rule_code: suppression.code.to_string(), kind: InvalidRuleCodeKind::Suppression, }, range, ) .set_fix(Fix::safe_edit(edit)); } } } else if !suppression.used.get() { // UnusedNOQA if context.is_rule_enabled(Rule::UnusedNOQA) { let Ok(rule) = Rule::from_code( get_redirect_target(&suppression.code).unwrap_or(&suppression.code), ) else { continue; // "external" lint code, don't treat it as unused }; for comment in &suppression.comments { let (range, edit) = Suppressions::delete_code_or_comment( locator, suppression, comment, false, ); let codes = if context.is_rule_enabled(rule) { UnusedCodes { unmatched: vec![suppression.code.to_string()], ..Default::default() } } else { UnusedCodes { disabled: vec![suppression.code.to_string()], ..Default::default() } }; context .report_diagnostic( UnusedNOQA { codes: Some(codes), kind: UnusedNOQAKind::Suppression, }, range, ) .set_fix(Fix::safe_edit(edit)); } } } else if suppression.comments.len() == 1 { // UnmatchedSuppressionComment let range = suppression.comments[0].range; if unmatched_ranges.insert(range) { context.report_diagnostic_if_enabled(UnmatchedSuppressionComment {}, range); } } } if context.is_rule_enabled(Rule::InvalidSuppressionComment) { for error in &self.errors { context .report_diagnostic( InvalidSuppressionComment { kind: InvalidSuppressionCommentKind::Error(error.kind), }, error.range, ) .set_fix(Fix::unsafe_edit(delete_comment(error.range, locator))); } } if context.is_rule_enabled(Rule::InvalidSuppressionComment) { for invalid in &self.invalid { context .report_diagnostic( InvalidSuppressionComment { kind: InvalidSuppressionCommentKind::Invalid(invalid.kind), }, invalid.comment.range, ) .set_fix(Fix::unsafe_edit(delete_comment( invalid.comment.range, locator, ))); } } } fn delete_code_or_comment( locator: &Locator<'_>, suppression: &Suppression, comment: &SuppressionComment, highlight_only_code: bool, ) -> (TextRange, Edit) { let mut range = comment.range; let edit = if comment.codes.len() == 1 { if highlight_only_code { range = comment.codes[0]; } delete_comment(comment.range, locator) } else { let code_index = comment .codes .iter() .position(|range| locator.slice(range) == suppression.code) .unwrap(); range = comment.codes[code_index]; let code_range = if code_index < (comment.codes.len() - 1) { TextRange::new( comment.codes[code_index].start(), comment.codes[code_index + 1].start(), ) } else { TextRange::new( comment.codes[code_index - 1].end(), comment.codes[code_index].end(), ) }; Edit::range_deletion(code_range) }; (range, edit) } } #[derive(Default)] pub(crate) struct SuppressionsBuilder<'a> { source: &'a str, valid: Vec<Suppression>, invalid: Vec<InvalidSuppression>, errors: Vec<ParseError>, pending: Vec<PendingSuppressionComment<'a>>, } impl<'a> SuppressionsBuilder<'a> { pub(crate) fn new(source: &'a str) -> Self { Self { source, ..Default::default() } } pub(crate) fn load_from_tokens(mut self, tokens: &Tokens) -> Suppressions { let default_indent = ""; let mut indents: Vec<&str> = vec![]; // Iterate through tokens, tracking indentation, filtering trailing comments, and then // looking for matching comments from the previous block when reaching a dedent token. for (token_index, token) in tokens.iter().enumerate() { match token.kind() { TokenKind::Indent => { indents.push(self.source.slice(token)); } TokenKind::Dedent => { self.match_comments(indents.last().copied().unwrap_or_default(), token.range()); indents.pop(); } TokenKind::Comment => { let mut parser = SuppressionParser::new(self.source, token.range()); match parser.parse_comment() { Ok(comment) => { let indent = indentation(self.source, &comment.range); let Some(indent) = indent else { // trailing suppressions are not supported self.invalid.push(InvalidSuppression { kind: InvalidSuppressionKind::Trailing, comment, }); continue; }; // comment matches current block's indentation, or precedes an indent/dedent token if indent == indents.last().copied().unwrap_or_default() || tokens[token_index..] .iter() .find(|t| !t.kind().is_trivia()) .is_some_and(|t| { matches!(t.kind(), TokenKind::Dedent | TokenKind::Indent) }) { self.pending .push(PendingSuppressionComment { indent, comment }); } else { // weirdly indented? ¯\_(ツ)_/¯ self.invalid.push(InvalidSuppression { kind: InvalidSuppressionKind::Indentation, comment, }); } } Err(ParseError { kind: ParseErrorKind::NotASuppression, .. }) => {} Err(error) => { self.errors.push(error); } } } _ => {} } } self.match_comments(default_indent, TextRange::up_to(self.source.text_len())); Suppressions { valid: self.valid, invalid: self.invalid, errors: self.errors, } } fn match_comments(&mut self, current_indent: &str, dedent_range: TextRange) { let mut comment_index = 0; // for each pending comment, search for matching comments at the same indentation level, // generate range suppressions for any matches, and then discard any unmatched comments // from the outgoing indentation block while comment_index < self.pending.len() { let comment = &self.pending[comment_index]; // skip comments from an outer indentation level if comment.indent.text_len() < current_indent.text_len() { comment_index += 1; continue; } // find the first matching comment if let Some(other_index) = self.pending[comment_index + 1..] .iter() .position(|other| comment.matches(other, self.source)) { // offset from current candidate let other_index = comment_index + 1 + other_index; let other = &self.pending[other_index]; // record a combined range suppression from the matching comments let combined_range = TextRange::new(comment.comment.range.start(), other.comment.range.end()); for code in comment.comment.codes_as_str(self.source) { self.valid.push(Suppression { code: code.into(), range: combined_range, comments: smallvec![comment.comment.clone(), other.comment.clone()], used: false.into(), }); } // remove both comments from further consideration self.pending.remove(other_index); self.pending.remove(comment_index); } else if matches!(comment.comment.action, SuppressionAction::Disable) { // treat "disable" comments without a matching "enable" as *implicitly* matched // to the end of the current indentation level let implicit_range = TextRange::new(comment.comment.range.start(), dedent_range.end()); for code in comment.comment.codes_as_str(self.source) { self.valid.push(Suppression { code: code.into(), range: implicit_range, comments: smallvec![comment.comment.clone()], used: false.into(), }); } self.pending.remove(comment_index); } else { self.invalid.push(InvalidSuppression { kind: InvalidSuppressionKind::Unmatched, comment: self.pending.remove(comment_index).comment.clone(), }); } } } } #[derive(Copy, Clone, Debug, Eq, Error, PartialEq)] pub(crate) enum ParseErrorKind { #[error("not a suppression comment")] NotASuppression, #[error("comment doesn't start with `#`")] CommentWithoutHash, #[error("unknown ruff directive")] UnknownAction, #[error("missing suppression codes like `[E501, ...]`")] MissingCodes, #[error("missing closing bracket")] MissingBracket, #[error("missing comma between codes")] MissingComma, #[error("invalid error code")] InvalidCode, } #[derive(Clone, Debug, Eq, PartialEq)] struct ParseError { kind: ParseErrorKind, range: TextRange, } impl ParseError { fn new(kind: ParseErrorKind, range: TextRange) -> Self { Self { kind, range } } } impl fmt::Display for ParseError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.kind.fmt(f) } } impl Error for ParseError {} struct SuppressionParser<'src> { cursor: Cursor<'src>, range: TextRange, } impl<'src> SuppressionParser<'src> { fn new(source: &'src str, range: TextRange) -> Self { let cursor = Cursor::new(&source[range]); Self { cursor, range } } fn parse_comment(&mut self) -> Result<SuppressionComment, ParseError> { self.cursor.start_token(); if !self.cursor.eat_char('#') { return self.error(ParseErrorKind::CommentWithoutHash); } self.eat_whitespace(); let action = self.eat_action()?; let codes = self.eat_codes()?; if codes.is_empty() { return Err(ParseError::new(ParseErrorKind::MissingCodes, self.range)); } self.eat_whitespace(); let reason = TextRange::new(self.offset(), self.range.end()); Ok(SuppressionComment { range: self.range, action, codes, reason, }) } fn eat_action(&mut self) -> Result<SuppressionAction, ParseError> { if !self.cursor.as_str().starts_with("ruff") { return self.error(ParseErrorKind::NotASuppression); } self.cursor.skip_bytes("ruff".len()); self.eat_whitespace(); if !self.cursor.eat_char(':') { return self.error(ParseErrorKind::NotASuppression); } self.eat_whitespace(); if self.cursor.as_str().starts_with("disable") { self.cursor.skip_bytes("disable".len()); Ok(SuppressionAction::Disable) } else if self.cursor.as_str().starts_with("enable") { self.cursor.skip_bytes("enable".len()); Ok(SuppressionAction::Enable) } else if self.cursor.as_str().starts_with("noqa") || self.cursor.as_str().starts_with("isort") { // alternate suppression variants, ignore for now self.error(ParseErrorKind::NotASuppression) } else { self.error(ParseErrorKind::UnknownAction) } } fn eat_codes(&mut self) -> Result<SmallVec<[TextRange; 2]>, ParseError> { self.eat_whitespace(); if !self.cursor.eat_char('[') { return self.error(ParseErrorKind::MissingCodes); } let mut codes: SmallVec<[TextRange; 2]> = smallvec![]; loop { if self.cursor.is_eof() { return self.error(ParseErrorKind::MissingBracket); } self.eat_whitespace(); if self.cursor.eat_char(']') { break Ok(codes); } let code_start = self.offset(); if !self.eat_word() { return self.error(ParseErrorKind::InvalidCode); } codes.push(TextRange::new(code_start, self.offset())); self.eat_whitespace(); if !self.cursor.eat_char(',') { if self.cursor.eat_char(']') { break Ok(codes); } return if self.cursor.is_eof() { self.error(ParseErrorKind::MissingBracket) } else { self.error(ParseErrorKind::MissingComma) }; } } } fn eat_whitespace(&mut self) -> bool { if self.cursor.eat_if(char::is_whitespace) { self.cursor.eat_while(char::is_whitespace); true } else { false } } fn eat_word(&mut self) -> bool { if self.cursor.eat_if(char::is_alphabetic) { // Allow `:` for better error recovery when someone uses `lint:code` instead of just `code`. self.cursor .eat_while(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | ':')); true } else { false } } fn offset(&self) -> TextSize { self.range.start() + self.range.len() - self.cursor.text_len() } fn error<T>(&self, kind: ParseErrorKind) -> Result<T, ParseError> { Err(ParseError::new(kind, self.range)) } } #[cfg(test)] mod tests { use std::fmt::{self, Formatter}; use insta::assert_debug_snapshot; use itertools::Itertools; use ruff_python_parser::{Mode, ParseOptions, parse}; use ruff_text_size::{TextRange, TextSize}; use similar::DiffableStr; use crate::{ settings::LinterSettings, suppression::{ InvalidSuppression, ParseError, Suppression, SuppressionAction, SuppressionComment, SuppressionParser, Suppressions, }, }; #[test] fn no_suppression() { let source = " # this is a comment print('hello') "; assert_debug_snapshot!( Suppressions::debug(source), @r" Suppressions { valid: [], invalid: [], errors: [], } ", ); } #[test] fn file_level_suppression() { let source = " # ruff: noqa F401 print('hello') "; assert_debug_snapshot!( Suppressions::debug(source), @r" Suppressions { valid: [], invalid: [], errors: [], } ", ); } #[test] fn single_range_suppression() { let source = " # ruff: disable[foo] print('hello') # ruff: enable[foo] "; assert_debug_snapshot!( Suppressions::debug(source), @r##" Suppressions { valid: [ Suppression { covered_source: "# ruff: disable[foo]\nprint('hello')\n# ruff: enable[foo]", code: "foo", comments: [ SuppressionComment { text: "# ruff: disable[foo]", action: Disable, codes: [ "foo", ], reason: "", }, SuppressionComment { text: "# ruff: enable[foo]", action: Enable, codes: [ "foo", ], reason: "", }, ], }, ], invalid: [], errors: [], } "##, ); } #[test] fn single_range_suppression_implicit_match() { let source = " # ruff: disable[foo] print('hello') def foo(): # ruff: disable[bar] print('hello') "; assert_debug_snapshot!( Suppressions::debug(source), @r##" Suppressions { valid: [ Suppression { covered_source: "# ruff: disable[bar]\n print('hello')\n\n", code: "bar", comments: [ SuppressionComment { text: "# ruff: disable[bar]", action: Disable, codes: [ "bar", ], reason: "", }, ], }, Suppression { covered_source: "# ruff: disable[foo]\nprint('hello')\n\ndef foo():\n # ruff: disable[bar]\n print('hello')\n\n", code: "foo", comments: [ SuppressionComment { text: "# ruff: disable[foo]", action: Disable, codes: [ "foo", ], reason: "", }, ], }, ], invalid: [], errors: [], } "##, ); } #[test] fn nested_range_suppressions() { let source = " class Foo: # ruff: disable[foo] def bar(self): # ruff: disable[bar] print('hello') # ruff: enable[bar] # ruff: enable[foo] "; assert_debug_snapshot!( Suppressions::debug(source), @r##" Suppressions { valid: [ Suppression { covered_source: "# ruff: disable[bar]\n print('hello')\n # ruff: enable[bar]", code: "bar", comments: [ SuppressionComment { text: "# ruff: disable[bar]", action: Disable, codes: [ "bar", ], reason: "", }, SuppressionComment { text: "# ruff: enable[bar]", action: Enable, codes: [ "bar", ], reason: "", }, ], }, Suppression { covered_source: "# ruff: disable[foo]\n def bar(self):\n # ruff: disable[bar]\n print('hello')\n # ruff: enable[bar]\n # ruff: enable[foo]", code: "foo", comments: [ SuppressionComment { text: "# ruff: disable[foo]", action: Disable, codes: [ "foo", ], reason: "", }, SuppressionComment { text: "# ruff: enable[foo]", action: Enable, codes: [ "foo", ], reason: "", }, ], }, ], invalid: [], errors: [], } "##, ); } #[test] fn interleaved_range_suppressions() { let source = " def foo(): # ruff: disable[foo] print('hello') # ruff: disable[bar] print('hello') # ruff: enable[foo] print('hello') # ruff: enable[bar] "; assert_debug_snapshot!( Suppressions::debug(source), @r##" Suppressions { valid: [ Suppression { covered_source: "# ruff: disable[foo]\n print('hello')\n # ruff: disable[bar]\n print('hello')\n # ruff: enable[foo]", code: "foo", comments: [ SuppressionComment { text: "# ruff: disable[foo]", action: Disable, codes: [ "foo", ], reason: "", }, SuppressionComment { text: "# ruff: enable[foo]", action: Enable, codes: [ "foo", ], reason: "", }, ], }, Suppression { covered_source: "# ruff: disable[bar]\n print('hello')\n # ruff: enable[foo]\n print('hello')\n # ruff: enable[bar]", code: "bar", comments: [ SuppressionComment { text: "# ruff: disable[bar]", action: Disable, codes: [ "bar", ], reason: "", }, SuppressionComment { text: "# ruff: enable[bar]", action: Enable, codes: [ "bar", ], reason: "", }, ], }, ], invalid: [], errors: [], } "##, ); } #[test] fn range_suppression_two_codes() { let source = " # ruff: disable[foo, bar] print('hello') # ruff: enable[foo, bar] "; assert_debug_snapshot!( Suppressions::debug(source), @r##" Suppressions { valid: [ Suppression { covered_source: "# ruff: disable[foo, bar]\nprint('hello')\n# ruff: enable[foo, bar]", code: "foo", comments: [ SuppressionComment { text: "# ruff: disable[foo, bar]", action: Disable, codes: [ "foo", "bar", ], reason: "", }, SuppressionComment { text: "# ruff: enable[foo, bar]", action: Enable, codes: [ "foo", "bar", ], reason: "", }, ], }, Suppression { covered_source: "# ruff: disable[foo, bar]\nprint('hello')\n# ruff: enable[foo, bar]", code: "bar", comments: [ SuppressionComment { text: "# ruff: disable[foo, bar]", action: Disable, codes: [ "foo", "bar", ], reason: "", }, SuppressionComment {
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/packaging.rs
crates/ruff_linter/src/packaging.rs
//! Detect Python package roots and file associations. use std::path::{Path, PathBuf}; // If we have a Python package layout like: // - root/ // - foo/ // - __init__.py // - bar.py // - baz/ // - __init__.py // - qux.py // // Then today, if you run with defaults (`src = ["."]`) from `root`, we'll // detect that `foo.bar`, `foo.baz`, and `foo.baz.qux` are first-party modules // (since, if you're in `root`, you can see `foo`). // // However, we'd also like it to be the case that, even if you run this command // from `foo`, we still consider `foo.baz.qux` to be first-party when linting // `foo/bar.py`. More specifically, for each Python file, we should find the // root of the current package. // // Thus, for each file, we iterate up its ancestors, returning the last // directory containing an `__init__.py`. /// Return `true` if the directory at the given `Path` appears to be a Python /// package. pub fn is_package(path: &Path, namespace_packages: &[PathBuf]) -> bool { namespace_packages .iter() .any(|namespace_package| path.starts_with(namespace_package)) || path.join("__init__.py").is_file() } /// Return the package root for the given path to a directory with Python file. pub fn detect_package_root<'a>(path: &'a Path, namespace_packages: &[PathBuf]) -> Option<&'a Path> { let mut current = None; for parent in path.ancestors() { if !is_package(parent, namespace_packages) { return current; } current = Some(parent); } current } #[cfg(test)] mod tests { use std::path::PathBuf; use crate::packaging::detect_package_root; use crate::test::test_resource_path; #[test] fn package_detection() { assert_eq!( detect_package_root(&test_resource_path("package/src/package"), &[],), Some(test_resource_path("package/src/package").as_path()) ); assert_eq!( detect_package_root(&test_resource_path("project/python_modules/core/core"), &[],), Some(test_resource_path("project/python_modules/core/core").as_path()) ); assert_eq!( detect_package_root( &test_resource_path("project/examples/docs/docs/concepts"), &[], ), Some(test_resource_path("project/examples/docs/docs").as_path()) ); assert_eq!( detect_package_root( PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("setup.py") .as_path(), &[], ), None, ); } #[test] fn package_detection_with_namespace_packages() { assert_eq!( detect_package_root(&test_resource_path("project/python_modules/core/core"), &[],), Some(test_resource_path("project/python_modules/core/core").as_path()) ); assert_eq!( detect_package_root( &test_resource_path("project/python_modules/core/core"), &[test_resource_path("project/python_modules/core"),], ), Some(test_resource_path("project/python_modules/core").as_path()) ); assert_eq!( detect_package_root( &test_resource_path("project/python_modules/core/core"), &[ test_resource_path("project/python_modules/core"), test_resource_path("project/python_modules"), ], ), Some(test_resource_path("project/python_modules").as_path()) ); assert_eq!( detect_package_root( &test_resource_path("project/python_modules/core/core"), &[test_resource_path("project/python_modules"),], ), Some(test_resource_path("project/python_modules").as_path()) ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/locator.rs
crates/ruff_linter/src/locator.rs
//! Struct used to efficiently slice source code at (row, column) Locations. use std::cell::OnceCell; use ruff_source_file::{LineColumn, LineIndex, LineRanges, OneIndexed, SourceCode}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; #[derive(Debug)] pub struct Locator<'a> { contents: &'a str, index: OnceCell<LineIndex>, } impl<'a> Locator<'a> { pub const fn new(contents: &'a str) -> Self { Self { contents, index: OnceCell::new(), } } pub fn with_index(contents: &'a str, index: LineIndex) -> Self { Self { contents, index: OnceCell::from(index), } } #[deprecated( note = "This is expensive, avoid using outside of the diagnostic phase. Prefer the other `Locator` methods instead." )] pub fn compute_line_index(&self, offset: TextSize) -> OneIndexed { self.to_index().line_index(offset) } #[deprecated( note = "This is expensive, avoid using outside of the diagnostic phase. Prefer the other `Locator` methods instead." )] pub fn compute_source_location(&self, offset: TextSize) -> LineColumn { self.to_source_code().line_column(offset) } pub fn to_index(&self) -> &LineIndex { self.index .get_or_init(|| LineIndex::from_source_text(self.contents)) } pub fn line_index(&self) -> Option<&LineIndex> { self.index.get() } pub fn to_source_code(&self) -> SourceCode<'_, '_> { SourceCode::new(self.contents, self.to_index()) } /// Take the source code up to the given [`TextSize`]. #[inline] pub fn up_to(&self, offset: TextSize) -> &'a str { &self.contents[TextRange::up_to(offset)] } /// Take the source code after the given [`TextSize`]. #[inline] pub fn after(&self, offset: TextSize) -> &'a str { &self.contents[usize::from(offset)..] } /// Finds the closest [`TextSize`] not exceeding the offset for which `is_char_boundary` is /// `true`. /// /// Can be replaced with `str::floor_char_boundary` once it's stable. /// /// ## Examples /// /// ``` /// # use ruff_text_size::{Ranged, TextRange, TextSize}; /// # use ruff_linter::Locator; /// /// let locator = Locator::new("Hello"); /// /// assert_eq!( /// locator.floor_char_boundary(TextSize::from(0)), /// TextSize::from(0) /// ); /// /// assert_eq!( /// locator.floor_char_boundary(TextSize::from(5)), /// TextSize::from(5) /// ); /// /// let locator = Locator::new("α"); /// /// assert_eq!( /// locator.floor_char_boundary(TextSize::from(0)), /// TextSize::from(0) /// ); /// /// assert_eq!( /// locator.floor_char_boundary(TextSize::from(1)), /// TextSize::from(0) /// ); /// /// assert_eq!( /// locator.floor_char_boundary(TextSize::from(2)), /// TextSize::from(2) /// ); /// ``` pub fn floor_char_boundary(&self, offset: TextSize) -> TextSize { if offset >= self.text_len() { self.text_len() } else { // We know that the character boundary is within four bytes. (0u32..=3u32) .map(TextSize::from) .filter_map(|index| offset.checked_sub(index)) .find(|offset| self.contents.is_char_boundary(offset.to_usize())) .unwrap_or_default() } } /// Take the source code between the given [`TextRange`]. #[inline] pub fn slice<T: Ranged>(&self, ranged: T) -> &'a str { &self.contents[ranged.range()] } /// Return the underlying source code. pub const fn contents(&self) -> &'a str { self.contents } /// Return the number of bytes in the source code. pub const fn len(&self) -> usize { self.contents.len() } pub fn text_len(&self) -> TextSize { self.contents.text_len() } /// Return `true` if the source code is empty. pub const fn is_empty(&self) -> bool { self.contents.is_empty() } } // Override the `_str` methods from [`LineRanges`] to extend the lifetime to `'a`. impl<'a> Locator<'a> { /// Returns the text of the `offset`'s line. /// /// See [`LineRanges::full_lines_str`]. pub fn full_line_str(&self, offset: TextSize) -> &'a str { self.contents.full_line_str(offset) } /// Returns the text of the `offset`'s line. /// /// See [`LineRanges::line_str`]. pub fn line_str(&self, offset: TextSize) -> &'a str { self.contents.line_str(offset) } /// Returns the text of all lines that include `range`. /// /// See [`LineRanges::lines_str`]. pub fn lines_str(&self, range: TextRange) -> &'a str { self.contents.lines_str(range) } /// Returns the text of all lines that include `range`. /// /// See [`LineRanges::full_lines_str`]. pub fn full_lines_str(&self, range: TextRange) -> &'a str { self.contents.full_lines_str(range) } } // Allow calling [`LineRanges`] methods on [`Locator`] directly. impl LineRanges for Locator<'_> { #[inline] fn line_start(&self, offset: TextSize) -> TextSize { self.contents.line_start(offset) } #[inline] fn bom_start_offset(&self) -> TextSize { self.contents.bom_start_offset() } #[inline] fn full_line_end(&self, offset: TextSize) -> TextSize { self.contents.full_line_end(offset) } #[inline] fn line_end(&self, offset: TextSize) -> TextSize { self.contents.line_end(offset) } #[inline] fn full_line_str(&self, offset: TextSize) -> &str { self.contents.full_line_str(offset) } #[inline] fn line_str(&self, offset: TextSize) -> &str { self.contents.line_str(offset) } #[inline] fn contains_line_break(&self, range: TextRange) -> bool { self.contents.contains_line_break(range) } #[inline] fn lines_str(&self, range: TextRange) -> &str { self.contents.lines_str(range) } #[inline] fn full_lines_str(&self, range: TextRange) -> &str { self.contents.full_lines_str(range) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/fs.rs
crates/ruff_linter/src/fs.rs
use std::path::{Path, PathBuf}; use path_absolutize::Absolutize; use crate::registry::RuleSet; use crate::settings::types::CompiledPerFileIgnoreList; /// Return the current working directory. /// /// On WASM this just returns `.`. Otherwise, defer to [`path_absolutize::path_dedot::CWD`]. pub fn get_cwd() -> &'static Path { #[cfg(target_arch = "wasm32")] { Path::new(".") } #[cfg(not(target_arch = "wasm32"))] path_absolutize::path_dedot::CWD.as_path() } /// Create a set with codes matching the pattern/code pairs. pub(crate) fn ignores_from_path(path: &Path, ignore_list: &CompiledPerFileIgnoreList) -> RuleSet { if ignore_list.is_empty() { return RuleSet::empty(); } ignore_list .iter_matches(path, "Adding per-file ignores") .flatten() .collect() } /// Convert any path to an absolute path (based on the current working /// directory). pub fn normalize_path<P: AsRef<Path>>(path: P) -> PathBuf { let path = path.as_ref(); if let Ok(path) = path.absolutize() { return path.to_path_buf(); } path.to_path_buf() } /// Convert any path to an absolute path (based on the specified project root). pub fn normalize_path_to<P: AsRef<Path>, R: AsRef<Path>>(path: P, project_root: R) -> PathBuf { let path = path.as_ref(); if let Ok(path) = path.absolutize_from(project_root.as_ref()) { return path.to_path_buf(); } path.to_path_buf() } /// Convert an absolute path to be relative to the current working directory. pub fn relativize_path<P: AsRef<Path>>(path: P) -> String { let path = path.as_ref(); let cwd = get_cwd(); if let Ok(path) = path.strip_prefix(cwd) { return format!("{}", path.display()); } format!("{}", path.display()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/codes.rs
crates/ruff_linter/src/codes.rs
/// In this module we generate [`Rule`], an enum of all rules, and [`RuleCodePrefix`], an enum of /// all rules categories. A rule category is something like pyflakes or flake8-todos. Each rule /// category contains all rules and their common prefixes, i.e. everything you can specify in /// `--select`. For pylint this is e.g. C0414 and E0118 but also C and E01. use std::fmt::Formatter; use ruff_db::diagnostic::SecondaryCode; use serde::Serialize; use strum_macros::EnumIter; use crate::registry::Linter; use crate::rule_selector::is_single_rule_selector; use crate::rules; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct NoqaCode(&'static str, &'static str); impl NoqaCode { /// Return the prefix for the [`NoqaCode`], e.g., `SIM` for `SIM101`. pub fn prefix(&self) -> &str { self.0 } /// Return the suffix for the [`NoqaCode`], e.g., `101` for `SIM101`. pub fn suffix(&self) -> &str { self.1 } } impl std::fmt::Debug for NoqaCode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(self, f) } } impl std::fmt::Display for NoqaCode { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { write!(f, "{}{}", self.0, self.1) } } impl PartialEq<&str> for NoqaCode { fn eq(&self, other: &&str) -> bool { match other.strip_prefix(self.0) { Some(suffix) => suffix == self.1, None => false, } } } impl PartialEq<NoqaCode> for &str { fn eq(&self, other: &NoqaCode) -> bool { other.eq(self) } } impl PartialEq<NoqaCode> for SecondaryCode { fn eq(&self, other: &NoqaCode) -> bool { &self.as_str() == other } } impl PartialEq<SecondaryCode> for NoqaCode { fn eq(&self, other: &SecondaryCode) -> bool { other.eq(self) } } impl serde::Serialize for NoqaCode { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(&self.to_string()) } } #[derive(Debug, Copy, Clone, Serialize)] pub enum RuleGroup { /// The rule is stable since the provided Ruff version. Stable { since: &'static str }, /// The rule has been unstable since the provided Ruff version, and preview mode must be enabled /// for usage. Preview { since: &'static str }, /// The rule has been deprecated since the provided Ruff version, warnings will be displayed /// during selection in stable and errors will be raised if used with preview mode enabled. Deprecated { since: &'static str }, /// The rule was removed in the provided Ruff version, and errors will be displayed on use. Removed { since: &'static str }, } #[ruff_macros::map_codes] pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> { #[expect(clippy::enum_glob_use)] use Linter::*; #[rustfmt::skip] Some(match (linter, code) { // pycodestyle errors (Pycodestyle, "E101") => rules::pycodestyle::rules::MixedSpacesAndTabs, (Pycodestyle, "E111") => rules::pycodestyle::rules::logical_lines::IndentationWithInvalidMultiple, (Pycodestyle, "E112") => rules::pycodestyle::rules::logical_lines::NoIndentedBlock, (Pycodestyle, "E113") => rules::pycodestyle::rules::logical_lines::UnexpectedIndentation, (Pycodestyle, "E114") => rules::pycodestyle::rules::logical_lines::IndentationWithInvalidMultipleComment, (Pycodestyle, "E115") => rules::pycodestyle::rules::logical_lines::NoIndentedBlockComment, (Pycodestyle, "E116") => rules::pycodestyle::rules::logical_lines::UnexpectedIndentationComment, (Pycodestyle, "E117") => rules::pycodestyle::rules::logical_lines::OverIndented, (Pycodestyle, "E201") => rules::pycodestyle::rules::logical_lines::WhitespaceAfterOpenBracket, (Pycodestyle, "E202") => rules::pycodestyle::rules::logical_lines::WhitespaceBeforeCloseBracket, (Pycodestyle, "E203") => rules::pycodestyle::rules::logical_lines::WhitespaceBeforePunctuation, (Pycodestyle, "E204") => rules::pycodestyle::rules::WhitespaceAfterDecorator, (Pycodestyle, "E211") => rules::pycodestyle::rules::logical_lines::WhitespaceBeforeParameters, (Pycodestyle, "E221") => rules::pycodestyle::rules::logical_lines::MultipleSpacesBeforeOperator, (Pycodestyle, "E222") => rules::pycodestyle::rules::logical_lines::MultipleSpacesAfterOperator, (Pycodestyle, "E223") => rules::pycodestyle::rules::logical_lines::TabBeforeOperator, (Pycodestyle, "E224") => rules::pycodestyle::rules::logical_lines::TabAfterOperator, (Pycodestyle, "E225") => rules::pycodestyle::rules::logical_lines::MissingWhitespaceAroundOperator, (Pycodestyle, "E226") => rules::pycodestyle::rules::logical_lines::MissingWhitespaceAroundArithmeticOperator, (Pycodestyle, "E227") => rules::pycodestyle::rules::logical_lines::MissingWhitespaceAroundBitwiseOrShiftOperator, (Pycodestyle, "E228") => rules::pycodestyle::rules::logical_lines::MissingWhitespaceAroundModuloOperator, (Pycodestyle, "E231") => rules::pycodestyle::rules::logical_lines::MissingWhitespace, (Pycodestyle, "E241") => rules::pycodestyle::rules::logical_lines::MultipleSpacesAfterComma, (Pycodestyle, "E242") => rules::pycodestyle::rules::logical_lines::TabAfterComma, (Pycodestyle, "E251") => rules::pycodestyle::rules::logical_lines::UnexpectedSpacesAroundKeywordParameterEquals, (Pycodestyle, "E252") => rules::pycodestyle::rules::logical_lines::MissingWhitespaceAroundParameterEquals, (Pycodestyle, "E261") => rules::pycodestyle::rules::logical_lines::TooFewSpacesBeforeInlineComment, (Pycodestyle, "E262") => rules::pycodestyle::rules::logical_lines::NoSpaceAfterInlineComment, (Pycodestyle, "E265") => rules::pycodestyle::rules::logical_lines::NoSpaceAfterBlockComment, (Pycodestyle, "E266") => rules::pycodestyle::rules::logical_lines::MultipleLeadingHashesForBlockComment, (Pycodestyle, "E271") => rules::pycodestyle::rules::logical_lines::MultipleSpacesAfterKeyword, (Pycodestyle, "E272") => rules::pycodestyle::rules::logical_lines::MultipleSpacesBeforeKeyword, (Pycodestyle, "E273") => rules::pycodestyle::rules::logical_lines::TabAfterKeyword, (Pycodestyle, "E274") => rules::pycodestyle::rules::logical_lines::TabBeforeKeyword, (Pycodestyle, "E275") => rules::pycodestyle::rules::logical_lines::MissingWhitespaceAfterKeyword, (Pycodestyle, "E301") => rules::pycodestyle::rules::BlankLineBetweenMethods, (Pycodestyle, "E302") => rules::pycodestyle::rules::BlankLinesTopLevel, (Pycodestyle, "E303") => rules::pycodestyle::rules::TooManyBlankLines, (Pycodestyle, "E304") => rules::pycodestyle::rules::BlankLineAfterDecorator, (Pycodestyle, "E305") => rules::pycodestyle::rules::BlankLinesAfterFunctionOrClass, (Pycodestyle, "E306") => rules::pycodestyle::rules::BlankLinesBeforeNestedDefinition, (Pycodestyle, "E401") => rules::pycodestyle::rules::MultipleImportsOnOneLine, (Pycodestyle, "E402") => rules::pycodestyle::rules::ModuleImportNotAtTopOfFile, (Pycodestyle, "E501") => rules::pycodestyle::rules::LineTooLong, (Pycodestyle, "E502") => rules::pycodestyle::rules::logical_lines::RedundantBackslash, (Pycodestyle, "E701") => rules::pycodestyle::rules::MultipleStatementsOnOneLineColon, (Pycodestyle, "E702") => rules::pycodestyle::rules::MultipleStatementsOnOneLineSemicolon, (Pycodestyle, "E703") => rules::pycodestyle::rules::UselessSemicolon, (Pycodestyle, "E711") => rules::pycodestyle::rules::NoneComparison, (Pycodestyle, "E712") => rules::pycodestyle::rules::TrueFalseComparison, (Pycodestyle, "E713") => rules::pycodestyle::rules::NotInTest, (Pycodestyle, "E714") => rules::pycodestyle::rules::NotIsTest, (Pycodestyle, "E721") => rules::pycodestyle::rules::TypeComparison, (Pycodestyle, "E722") => rules::pycodestyle::rules::BareExcept, (Pycodestyle, "E731") => rules::pycodestyle::rules::LambdaAssignment, (Pycodestyle, "E741") => rules::pycodestyle::rules::AmbiguousVariableName, (Pycodestyle, "E742") => rules::pycodestyle::rules::AmbiguousClassName, (Pycodestyle, "E743") => rules::pycodestyle::rules::AmbiguousFunctionName, (Pycodestyle, "E902") => rules::pycodestyle::rules::IOError, #[allow(deprecated)] (Pycodestyle, "E999") => rules::pycodestyle::rules::SyntaxError, // pycodestyle warnings (Pycodestyle, "W191") => rules::pycodestyle::rules::TabIndentation, (Pycodestyle, "W291") => rules::pycodestyle::rules::TrailingWhitespace, (Pycodestyle, "W292") => rules::pycodestyle::rules::MissingNewlineAtEndOfFile, (Pycodestyle, "W293") => rules::pycodestyle::rules::BlankLineWithWhitespace, (Pycodestyle, "W391") => rules::pycodestyle::rules::TooManyNewlinesAtEndOfFile, (Pycodestyle, "W505") => rules::pycodestyle::rules::DocLineTooLong, (Pycodestyle, "W605") => rules::pycodestyle::rules::InvalidEscapeSequence, // pyflakes (Pyflakes, "401") => rules::pyflakes::rules::UnusedImport, (Pyflakes, "402") => rules::pyflakes::rules::ImportShadowedByLoopVar, (Pyflakes, "403") => rules::pyflakes::rules::UndefinedLocalWithImportStar, (Pyflakes, "404") => rules::pyflakes::rules::LateFutureImport, (Pyflakes, "405") => rules::pyflakes::rules::UndefinedLocalWithImportStarUsage, (Pyflakes, "406") => rules::pyflakes::rules::UndefinedLocalWithNestedImportStarUsage, (Pyflakes, "407") => rules::pyflakes::rules::FutureFeatureNotDefined, (Pyflakes, "501") => rules::pyflakes::rules::PercentFormatInvalidFormat, (Pyflakes, "502") => rules::pyflakes::rules::PercentFormatExpectedMapping, (Pyflakes, "503") => rules::pyflakes::rules::PercentFormatExpectedSequence, (Pyflakes, "504") => rules::pyflakes::rules::PercentFormatExtraNamedArguments, (Pyflakes, "505") => rules::pyflakes::rules::PercentFormatMissingArgument, (Pyflakes, "506") => rules::pyflakes::rules::PercentFormatMixedPositionalAndNamed, (Pyflakes, "507") => rules::pyflakes::rules::PercentFormatPositionalCountMismatch, (Pyflakes, "508") => rules::pyflakes::rules::PercentFormatStarRequiresSequence, (Pyflakes, "509") => rules::pyflakes::rules::PercentFormatUnsupportedFormatCharacter, (Pyflakes, "521") => rules::pyflakes::rules::StringDotFormatInvalidFormat, (Pyflakes, "522") => rules::pyflakes::rules::StringDotFormatExtraNamedArguments, (Pyflakes, "523") => rules::pyflakes::rules::StringDotFormatExtraPositionalArguments, (Pyflakes, "524") => rules::pyflakes::rules::StringDotFormatMissingArguments, (Pyflakes, "525") => rules::pyflakes::rules::StringDotFormatMixingAutomatic, (Pyflakes, "541") => rules::pyflakes::rules::FStringMissingPlaceholders, (Pyflakes, "601") => rules::pyflakes::rules::MultiValueRepeatedKeyLiteral, (Pyflakes, "602") => rules::pyflakes::rules::MultiValueRepeatedKeyVariable, (Pyflakes, "621") => rules::pyflakes::rules::ExpressionsInStarAssignment, (Pyflakes, "622") => rules::pyflakes::rules::MultipleStarredExpressions, (Pyflakes, "631") => rules::pyflakes::rules::AssertTuple, (Pyflakes, "632") => rules::pyflakes::rules::IsLiteral, (Pyflakes, "633") => rules::pyflakes::rules::InvalidPrintSyntax, (Pyflakes, "634") => rules::pyflakes::rules::IfTuple, (Pyflakes, "701") => rules::pyflakes::rules::BreakOutsideLoop, (Pyflakes, "702") => rules::pyflakes::rules::ContinueOutsideLoop, (Pyflakes, "704") => rules::pyflakes::rules::YieldOutsideFunction, (Pyflakes, "706") => rules::pyflakes::rules::ReturnOutsideFunction, (Pyflakes, "707") => rules::pyflakes::rules::DefaultExceptNotLast, (Pyflakes, "722") => rules::pyflakes::rules::ForwardAnnotationSyntaxError, (Pyflakes, "811") => rules::pyflakes::rules::RedefinedWhileUnused, (Pyflakes, "821") => rules::pyflakes::rules::UndefinedName, (Pyflakes, "822") => rules::pyflakes::rules::UndefinedExport, (Pyflakes, "823") => rules::pyflakes::rules::UndefinedLocal, (Pyflakes, "841") => rules::pyflakes::rules::UnusedVariable, (Pyflakes, "842") => rules::pyflakes::rules::UnusedAnnotation, (Pyflakes, "901") => rules::pyflakes::rules::RaiseNotImplemented, // pylint (Pylint, "C0105") => rules::pylint::rules::TypeNameIncorrectVariance, (Pylint, "C0131") => rules::pylint::rules::TypeBivariance, (Pylint, "C0132") => rules::pylint::rules::TypeParamNameMismatch, (Pylint, "C0205") => rules::pylint::rules::SingleStringSlots, (Pylint, "C0206") => rules::pylint::rules::DictIndexMissingItems, (Pylint, "C0207") => rules::pylint::rules::MissingMaxsplitArg, (Pylint, "C0208") => rules::pylint::rules::IterationOverSet, (Pylint, "C0414") => rules::pylint::rules::UselessImportAlias, (Pylint, "C0415") => rules::pylint::rules::ImportOutsideTopLevel, (Pylint, "C1802") => rules::pylint::rules::LenTest, (Pylint, "C1901") => rules::pylint::rules::CompareToEmptyString, (Pylint, "C2401") => rules::pylint::rules::NonAsciiName, (Pylint, "C2403") => rules::pylint::rules::NonAsciiImportName, (Pylint, "C2701") => rules::pylint::rules::ImportPrivateName, (Pylint, "C2801") => rules::pylint::rules::UnnecessaryDunderCall, (Pylint, "C3002") => rules::pylint::rules::UnnecessaryDirectLambdaCall, (Pylint, "E0100") => rules::pylint::rules::YieldInInit, (Pylint, "E0101") => rules::pylint::rules::ReturnInInit, (Pylint, "E0115") => rules::pylint::rules::NonlocalAndGlobal, (Pylint, "E0116") => rules::pylint::rules::ContinueInFinally, (Pylint, "E0117") => rules::pylint::rules::NonlocalWithoutBinding, (Pylint, "E0118") => rules::pylint::rules::LoadBeforeGlobalDeclaration, (Pylint, "E0237") => rules::pylint::rules::NonSlotAssignment, (Pylint, "E0241") => rules::pylint::rules::DuplicateBases, (Pylint, "E0302") => rules::pylint::rules::UnexpectedSpecialMethodSignature, (Pylint, "E0303") => rules::pylint::rules::InvalidLengthReturnType, (Pylint, "E0304") => rules::pylint::rules::InvalidBoolReturnType, (Pylint, "E0305") => rules::pylint::rules::InvalidIndexReturnType, (Pylint, "E0307") => rules::pylint::rules::InvalidStrReturnType, (Pylint, "E0308") => rules::pylint::rules::InvalidBytesReturnType, (Pylint, "E0309") => rules::pylint::rules::InvalidHashReturnType, (Pylint, "E0604") => rules::pylint::rules::InvalidAllObject, (Pylint, "E0605") => rules::pylint::rules::InvalidAllFormat, (Pylint, "E0643") => rules::pylint::rules::PotentialIndexError, (Pylint, "E0704") => rules::pylint::rules::MisplacedBareRaise, (Pylint, "E1132") => rules::pylint::rules::RepeatedKeywordArgument, (Pylint, "E1141") => rules::pylint::rules::DictIterMissingItems, (Pylint, "E1142") => rules::pylint::rules::AwaitOutsideAsync, (Pylint, "E1205") => rules::pylint::rules::LoggingTooManyArgs, (Pylint, "E1206") => rules::pylint::rules::LoggingTooFewArgs, (Pylint, "E1300") => rules::pylint::rules::BadStringFormatCharacter, (Pylint, "E1307") => rules::pylint::rules::BadStringFormatType, (Pylint, "E1310") => rules::pylint::rules::BadStrStripCall, (Pylint, "E1507") => rules::pylint::rules::InvalidEnvvarValue, (Pylint, "E1519") => rules::pylint::rules::SingledispatchMethod, (Pylint, "E1520") => rules::pylint::rules::SingledispatchmethodFunction, (Pylint, "E1700") => rules::pylint::rules::YieldFromInAsyncFunction, (Pylint, "E2502") => rules::pylint::rules::BidirectionalUnicode, (Pylint, "E2510") => rules::pylint::rules::InvalidCharacterBackspace, (Pylint, "E2512") => rules::pylint::rules::InvalidCharacterSub, (Pylint, "E2513") => rules::pylint::rules::InvalidCharacterEsc, (Pylint, "E2514") => rules::pylint::rules::InvalidCharacterNul, (Pylint, "E2515") => rules::pylint::rules::InvalidCharacterZeroWidthSpace, (Pylint, "E4703") => rules::pylint::rules::ModifiedIteratingSet, (Pylint, "R0124") => rules::pylint::rules::ComparisonWithItself, (Pylint, "R0133") => rules::pylint::rules::ComparisonOfConstant, (Pylint, "R0202") => rules::pylint::rules::NoClassmethodDecorator, (Pylint, "R0203") => rules::pylint::rules::NoStaticmethodDecorator, (Pylint, "R0206") => rules::pylint::rules::PropertyWithParameters, (Pylint, "R0402") => rules::pylint::rules::ManualFromImport, (Pylint, "R0904") => rules::pylint::rules::TooManyPublicMethods, (Pylint, "R0911") => rules::pylint::rules::TooManyReturnStatements, (Pylint, "R0912") => rules::pylint::rules::TooManyBranches, (Pylint, "R0913") => rules::pylint::rules::TooManyArguments, (Pylint, "R0914") => rules::pylint::rules::TooManyLocals, (Pylint, "R0915") => rules::pylint::rules::TooManyStatements, (Pylint, "R0916") => rules::pylint::rules::TooManyBooleanExpressions, (Pylint, "R0917") => rules::pylint::rules::TooManyPositionalArguments, (Pylint, "R1701") => rules::pylint::rules::RepeatedIsinstanceCalls, (Pylint, "R1702") => rules::pylint::rules::TooManyNestedBlocks, (Pylint, "R1704") => rules::pylint::rules::RedefinedArgumentFromLocal, (Pylint, "R1706") => rules::pylint::rules::AndOrTernary, (Pylint, "R1708") => rules::pylint::rules::StopIterationReturn, (Pylint, "R1711") => rules::pylint::rules::UselessReturn, (Pylint, "R1714") => rules::pylint::rules::RepeatedEqualityComparison, (Pylint, "R1722") => rules::pylint::rules::SysExitAlias, (Pylint, "R1730") => rules::pylint::rules::IfStmtMinMax, (Pylint, "R1716") => rules::pylint::rules::BooleanChainedComparison, (Pylint, "R1733") => rules::pylint::rules::UnnecessaryDictIndexLookup, (Pylint, "R1736") => rules::pylint::rules::UnnecessaryListIndexLookup, (Pylint, "R2004") => rules::pylint::rules::MagicValueComparison, (Pylint, "R2044") => rules::pylint::rules::EmptyComment, (Pylint, "R5501") => rules::pylint::rules::CollapsibleElseIf, (Pylint, "R6104") => rules::pylint::rules::NonAugmentedAssignment, (Pylint, "R6201") => rules::pylint::rules::LiteralMembership, (Pylint, "R6301") => rules::pylint::rules::NoSelfUse, #[cfg(any(feature = "test-rules", test))] (Pylint, "W0101") => rules::pylint::rules::UnreachableCode, (Pylint, "W0108") => rules::pylint::rules::UnnecessaryLambda, (Pylint, "W0177") => rules::pylint::rules::NanComparison, (Pylint, "W0120") => rules::pylint::rules::UselessElseOnLoop, (Pylint, "W0127") => rules::pylint::rules::SelfAssigningVariable, (Pylint, "W0128") => rules::pylint::rules::RedeclaredAssignedName, (Pylint, "W0129") => rules::pylint::rules::AssertOnStringLiteral, (Pylint, "W0131") => rules::pylint::rules::NamedExprWithoutContext, (Pylint, "W0133") => rules::pylint::rules::UselessExceptionStatement, (Pylint, "W0211") => rules::pylint::rules::BadStaticmethodArgument, (Pylint, "W0244") => rules::pylint::rules::RedefinedSlotsInSubclass, (Pylint, "W0245") => rules::pylint::rules::SuperWithoutBrackets, (Pylint, "W0406") => rules::pylint::rules::ImportSelf, (Pylint, "W0602") => rules::pylint::rules::GlobalVariableNotAssigned, (Pylint, "W0603") => rules::pylint::rules::GlobalStatement, (Pylint, "W0604") => rules::pylint::rules::GlobalAtModuleLevel, (Pylint, "W0642") => rules::pylint::rules::SelfOrClsAssignment, (Pylint, "W0711") => rules::pylint::rules::BinaryOpException, (Pylint, "W1501") => rules::pylint::rules::BadOpenMode, (Pylint, "W1507") => rules::pylint::rules::ShallowCopyEnviron, (Pylint, "W1508") => rules::pylint::rules::InvalidEnvvarDefault, (Pylint, "W1509") => rules::pylint::rules::SubprocessPopenPreexecFn, (Pylint, "W1510") => rules::pylint::rules::SubprocessRunWithoutCheck, (Pylint, "W1514") => rules::pylint::rules::UnspecifiedEncoding, (Pylint, "W1641") => rules::pylint::rules::EqWithoutHash, (Pylint, "W2101") => rules::pylint::rules::UselessWithLock, (Pylint, "W2901") => rules::pylint::rules::RedefinedLoopName, (Pylint, "W3201") => rules::pylint::rules::BadDunderMethodName, (Pylint, "W3301") => rules::pylint::rules::NestedMinMax, // flake8-async (Flake8Async, "100") => rules::flake8_async::rules::CancelScopeNoCheckpoint, (Flake8Async, "105") => rules::flake8_async::rules::TrioSyncCall, (Flake8Async, "109") => rules::flake8_async::rules::AsyncFunctionWithTimeout, (Flake8Async, "110") => rules::flake8_async::rules::AsyncBusyWait, (Flake8Async, "115") => rules::flake8_async::rules::AsyncZeroSleep, (Flake8Async, "116") => rules::flake8_async::rules::LongSleepNotForever, (Flake8Async, "210") => rules::flake8_async::rules::BlockingHttpCallInAsyncFunction, (Flake8Async, "212") => rules::flake8_async::rules::BlockingHttpCallHttpxInAsyncFunction, (Flake8Async, "220") => rules::flake8_async::rules::CreateSubprocessInAsyncFunction, (Flake8Async, "221") => rules::flake8_async::rules::RunProcessInAsyncFunction, (Flake8Async, "222") => rules::flake8_async::rules::WaitForProcessInAsyncFunction, (Flake8Async, "230") => rules::flake8_async::rules::BlockingOpenCallInAsyncFunction, (Flake8Async, "240") => rules::flake8_async::rules::BlockingPathMethodInAsyncFunction, (Flake8Async, "250") => rules::flake8_async::rules::BlockingInputInAsyncFunction, (Flake8Async, "251") => rules::flake8_async::rules::BlockingSleepInAsyncFunction, // flake8-builtins (Flake8Builtins, "001") => rules::flake8_builtins::rules::BuiltinVariableShadowing, (Flake8Builtins, "002") => rules::flake8_builtins::rules::BuiltinArgumentShadowing, (Flake8Builtins, "003") => rules::flake8_builtins::rules::BuiltinAttributeShadowing, (Flake8Builtins, "004") => rules::flake8_builtins::rules::BuiltinImportShadowing, (Flake8Builtins, "005") => rules::flake8_builtins::rules::StdlibModuleShadowing, (Flake8Builtins, "006") => rules::flake8_builtins::rules::BuiltinLambdaArgumentShadowing, // flake8-bugbear (Flake8Bugbear, "002") => rules::flake8_bugbear::rules::UnaryPrefixIncrementDecrement, (Flake8Bugbear, "003") => rules::flake8_bugbear::rules::AssignmentToOsEnviron, (Flake8Bugbear, "004") => rules::flake8_bugbear::rules::UnreliableCallableCheck, (Flake8Bugbear, "005") => rules::flake8_bugbear::rules::StripWithMultiCharacters, (Flake8Bugbear, "006") => rules::flake8_bugbear::rules::MutableArgumentDefault, (Flake8Bugbear, "007") => rules::flake8_bugbear::rules::UnusedLoopControlVariable, (Flake8Bugbear, "008") => rules::flake8_bugbear::rules::FunctionCallInDefaultArgument, (Flake8Bugbear, "009") => rules::flake8_bugbear::rules::GetAttrWithConstant, (Flake8Bugbear, "010") => rules::flake8_bugbear::rules::SetAttrWithConstant, (Flake8Bugbear, "011") => rules::flake8_bugbear::rules::AssertFalse, (Flake8Bugbear, "012") => rules::flake8_bugbear::rules::JumpStatementInFinally, (Flake8Bugbear, "013") => rules::flake8_bugbear::rules::RedundantTupleInExceptionHandler, (Flake8Bugbear, "014") => rules::flake8_bugbear::rules::DuplicateHandlerException, (Flake8Bugbear, "015") => rules::flake8_bugbear::rules::UselessComparison, (Flake8Bugbear, "016") => rules::flake8_bugbear::rules::RaiseLiteral, (Flake8Bugbear, "017") => rules::flake8_bugbear::rules::AssertRaisesException, (Flake8Bugbear, "018") => rules::flake8_bugbear::rules::UselessExpression, (Flake8Bugbear, "019") => rules::flake8_bugbear::rules::CachedInstanceMethod, (Flake8Bugbear, "020") => rules::flake8_bugbear::rules::LoopVariableOverridesIterator, (Flake8Bugbear, "021") => rules::flake8_bugbear::rules::FStringDocstring, (Flake8Bugbear, "022") => rules::flake8_bugbear::rules::UselessContextlibSuppress, (Flake8Bugbear, "023") => rules::flake8_bugbear::rules::FunctionUsesLoopVariable, (Flake8Bugbear, "024") => rules::flake8_bugbear::rules::AbstractBaseClassWithoutAbstractMethod, (Flake8Bugbear, "025") => rules::flake8_bugbear::rules::DuplicateTryBlockException, (Flake8Bugbear, "026") => rules::flake8_bugbear::rules::StarArgUnpackingAfterKeywordArg, (Flake8Bugbear, "027") => rules::flake8_bugbear::rules::EmptyMethodWithoutAbstractDecorator, (Flake8Bugbear, "028") => rules::flake8_bugbear::rules::NoExplicitStacklevel, (Flake8Bugbear, "029") => rules::flake8_bugbear::rules::ExceptWithEmptyTuple, (Flake8Bugbear, "030") => rules::flake8_bugbear::rules::ExceptWithNonExceptionClasses, (Flake8Bugbear, "031") => rules::flake8_bugbear::rules::ReuseOfGroupbyGenerator, (Flake8Bugbear, "032") => rules::flake8_bugbear::rules::UnintentionalTypeAnnotation, (Flake8Bugbear, "033") => rules::flake8_bugbear::rules::DuplicateValue, (Flake8Bugbear, "034") => rules::flake8_bugbear::rules::ReSubPositionalArgs, (Flake8Bugbear, "035") => rules::flake8_bugbear::rules::StaticKeyDictComprehension, (Flake8Bugbear, "039") => rules::flake8_bugbear::rules::MutableContextvarDefault, (Flake8Bugbear, "901") => rules::flake8_bugbear::rules::ReturnInGenerator, (Flake8Bugbear, "903") => rules::flake8_bugbear::rules::ClassAsDataStructure, (Flake8Bugbear, "904") => rules::flake8_bugbear::rules::RaiseWithoutFromInsideExcept, (Flake8Bugbear, "905") => rules::flake8_bugbear::rules::ZipWithoutExplicitStrict, (Flake8Bugbear, "909") => rules::flake8_bugbear::rules::LoopIteratorMutation, (Flake8Bugbear, "911") => rules::flake8_bugbear::rules::BatchedWithoutExplicitStrict, (Flake8Bugbear, "912") => rules::flake8_bugbear::rules::MapWithoutExplicitStrict, // flake8-blind-except (Flake8BlindExcept, "001") => rules::flake8_blind_except::rules::BlindExcept, // flake8-comprehensions (Flake8Comprehensions, "00") => rules::flake8_comprehensions::rules::UnnecessaryGeneratorList, (Flake8Comprehensions, "01") => rules::flake8_comprehensions::rules::UnnecessaryGeneratorSet, (Flake8Comprehensions, "02") => rules::flake8_comprehensions::rules::UnnecessaryGeneratorDict, (Flake8Comprehensions, "03") => rules::flake8_comprehensions::rules::UnnecessaryListComprehensionSet, (Flake8Comprehensions, "04") => rules::flake8_comprehensions::rules::UnnecessaryListComprehensionDict, (Flake8Comprehensions, "05") => rules::flake8_comprehensions::rules::UnnecessaryLiteralSet, (Flake8Comprehensions, "06") => rules::flake8_comprehensions::rules::UnnecessaryLiteralDict, (Flake8Comprehensions, "08") => rules::flake8_comprehensions::rules::UnnecessaryCollectionCall, (Flake8Comprehensions, "09") => rules::flake8_comprehensions::rules::UnnecessaryLiteralWithinTupleCall, (Flake8Comprehensions, "10") => rules::flake8_comprehensions::rules::UnnecessaryLiteralWithinListCall, (Flake8Comprehensions, "11") => rules::flake8_comprehensions::rules::UnnecessaryListCall, (Flake8Comprehensions, "13") => rules::flake8_comprehensions::rules::UnnecessaryCallAroundSorted, (Flake8Comprehensions, "14") => rules::flake8_comprehensions::rules::UnnecessaryDoubleCastOrProcess, (Flake8Comprehensions, "15") => rules::flake8_comprehensions::rules::UnnecessarySubscriptReversal, (Flake8Comprehensions, "16") => rules::flake8_comprehensions::rules::UnnecessaryComprehension, (Flake8Comprehensions, "17") => rules::flake8_comprehensions::rules::UnnecessaryMap, (Flake8Comprehensions, "18") => rules::flake8_comprehensions::rules::UnnecessaryLiteralWithinDictCall, (Flake8Comprehensions, "19") => rules::flake8_comprehensions::rules::UnnecessaryComprehensionInCall, (Flake8Comprehensions, "20") => rules::flake8_comprehensions::rules::UnnecessaryDictComprehensionForIterable, // flake8-debugger (Flake8Debugger, "0") => rules::flake8_debugger::rules::Debugger, // mccabe (McCabe, "1") => rules::mccabe::rules::ComplexStructure, // flake8-tidy-imports (Flake8TidyImports, "251") => rules::flake8_tidy_imports::rules::BannedApi, (Flake8TidyImports, "252") => rules::flake8_tidy_imports::rules::RelativeImports, (Flake8TidyImports, "253") => rules::flake8_tidy_imports::rules::BannedModuleLevelImports, // flake8-return (Flake8Return, "501") => rules::flake8_return::rules::UnnecessaryReturnNone, (Flake8Return, "502") => rules::flake8_return::rules::ImplicitReturnValue, (Flake8Return, "503") => rules::flake8_return::rules::ImplicitReturn, (Flake8Return, "504") => rules::flake8_return::rules::UnnecessaryAssign, (Flake8Return, "505") => rules::flake8_return::rules::SuperfluousElseReturn, (Flake8Return, "506") => rules::flake8_return::rules::SuperfluousElseRaise, (Flake8Return, "507") => rules::flake8_return::rules::SuperfluousElseContinue, (Flake8Return, "508") => rules::flake8_return::rules::SuperfluousElseBreak, // flake8-gettext (Flake8GetText, "001") => rules::flake8_gettext::rules::FStringInGetTextFuncCall, (Flake8GetText, "002") => rules::flake8_gettext::rules::FormatInGetTextFuncCall, (Flake8GetText, "003") => rules::flake8_gettext::rules::PrintfInGetTextFuncCall, // flake8-implicit-str-concat (Flake8ImplicitStrConcat, "001") => rules::flake8_implicit_str_concat::rules::SingleLineImplicitStringConcatenation, (Flake8ImplicitStrConcat, "002") => rules::flake8_implicit_str_concat::rules::MultiLineImplicitStringConcatenation, (Flake8ImplicitStrConcat, "003") => rules::flake8_implicit_str_concat::rules::ExplicitStringConcatenation, (Flake8ImplicitStrConcat, "004") => rules::flake8_implicit_str_concat::rules::ImplicitStringConcatenationInCollectionLiteral, // flake8-print (Flake8Print, "1") => rules::flake8_print::rules::Print, (Flake8Print, "3") => rules::flake8_print::rules::PPrint, // flake8-quotes (Flake8Quotes, "000") => rules::flake8_quotes::rules::BadQuotesInlineString, (Flake8Quotes, "001") => rules::flake8_quotes::rules::BadQuotesMultilineString, (Flake8Quotes, "002") => rules::flake8_quotes::rules::BadQuotesDocstring, (Flake8Quotes, "003") => rules::flake8_quotes::rules::AvoidableEscapedQuote, (Flake8Quotes, "004") => rules::flake8_quotes::rules::UnnecessaryEscapedQuote, // flake8-annotations (Flake8Annotations, "001") => rules::flake8_annotations::rules::MissingTypeFunctionArgument, (Flake8Annotations, "002") => rules::flake8_annotations::rules::MissingTypeArgs, (Flake8Annotations, "003") => rules::flake8_annotations::rules::MissingTypeKwargs, #[allow(deprecated)] (Flake8Annotations, "101") => rules::flake8_annotations::rules::MissingTypeSelf, #[allow(deprecated)] (Flake8Annotations, "102") => rules::flake8_annotations::rules::MissingTypeCls, (Flake8Annotations, "201") => rules::flake8_annotations::rules::MissingReturnTypeUndocumentedPublicFunction, (Flake8Annotations, "202") => rules::flake8_annotations::rules::MissingReturnTypePrivateFunction, (Flake8Annotations, "204") => rules::flake8_annotations::rules::MissingReturnTypeSpecialMethod, (Flake8Annotations, "205") => rules::flake8_annotations::rules::MissingReturnTypeStaticMethod, (Flake8Annotations, "206") => rules::flake8_annotations::rules::MissingReturnTypeClassMethod, (Flake8Annotations, "401") => rules::flake8_annotations::rules::AnyType, // flake8-future-annotations
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/renamer.rs
crates/ruff_linter/src/renamer.rs
//! Code modification struct to support symbol renaming within a scope. use anyhow::{Result, anyhow}; use itertools::Itertools; use ruff_python_ast as ast; use ruff_python_codegen::Stylist; use ruff_python_semantic::{Binding, BindingKind, Scope, ScopeId, SemanticModel}; use ruff_python_stdlib::{builtins::is_python_builtin, keyword::is_keyword}; use ruff_text_size::Ranged; use crate::Edit; use crate::checkers::ast::Checker; pub(crate) struct Renamer; impl Renamer { /// Rename a symbol (from `name` to `target`). /// /// ## How it works /// /// The renaming algorithm is as follows: /// /// 1. Determine the scope in which the rename should occur. This is typically the scope passed /// in by the caller. However, if a symbol is `nonlocal` or `global`, then the rename needs /// to occur in the scope in which the symbol is declared. For example, attempting to rename /// `x` in `foo` below should trigger a rename in the module scope: /// /// ```python /// x = 1 /// /// def foo(): /// global x /// x = 2 /// ``` /// /// 1. Determine whether the symbol is rebound in another scope. This is effectively the inverse /// of the previous step: when attempting to rename `x` in the module scope, we need to /// detect that `x` is rebound in the `foo` scope. Determine every scope in which the symbol /// is rebound, and add it to the set of scopes in which the rename should occur. /// /// 1. Start with the first scope in the stack. Take the first [`Binding`] in the scope, for the /// given name. For example, in the following snippet, we'd start by examining the `x = 1` /// binding: /// /// ```python /// if True: /// x = 1 /// print(x) /// else: /// x = 2 /// print(x) /// /// print(x) /// ``` /// /// 1. Rename the [`Binding`]. In most cases, this is a simple replacement. For example, /// renaming `x` to `y` above would require replacing `x = 1` with `y = 1`. After the /// first replacement in the snippet above, we'd have: /// /// ```python /// if True: /// y = 1 /// print(x) /// else: /// x = 2 /// print(x) /// /// print(x) /// ``` /// /// Note that, when renaming imports, we need to instead rename (or add) an alias. For /// example, to rename `pandas` to `pd`, we may need to rewrite `import pandas` to /// `import pandas as pd`, rather than `import pd`. /// /// 1. Check to see if the binding is assigned to a known special call where the first argument /// must be a string that is the same as the binding's name. For example, /// `T = TypeVar("_T")` will be rejected by a type checker; only `T = TypeVar("T")` will do. /// If it *is* one of these calls, we rename the relevant argument as well. /// /// 1. Rename every reference to the [`Binding`]. For example, renaming the references to the /// `x = 1` binding above would give us: /// /// ```python /// if True: /// y = 1 /// print(y) /// else: /// x = 2 /// print(x) /// /// print(x) /// ``` /// /// 1. Rename every delayed annotation. (See [`SemanticModel::delayed_annotations`].) /// /// 1. Repeat the above process for every [`Binding`] in the scope with the given name. /// After renaming the `x = 2` binding, we'd have: /// /// ```python /// if True: /// y = 1 /// print(y) /// else: /// y = 2 /// print(y) /// /// print(y) /// ``` /// /// 1. Repeat the above process for every scope in the stack. pub(crate) fn rename( name: &str, target: &str, scope: &Scope, semantic: &SemanticModel, stylist: &Stylist, ) -> Result<(Edit, Vec<Edit>)> { let mut edits = vec![]; // Determine whether the symbol is `nonlocal` or `global`. (A symbol can't be both; Python // raises a `SyntaxError`.) If the symbol is `nonlocal` or `global`, we need to rename it in // the scope in which it's declared, rather than the current scope. For example, given: // // ```python // x = 1 // // def foo(): // global x // ``` // // When renaming `x` in `foo`, we detect that `x` is a global, and back out to the module // scope. let scope_id = scope.get_all(name).find_map(|binding_id| { let binding = semantic.binding(binding_id); match binding.kind { BindingKind::Global(_) => Some(ScopeId::global()), BindingKind::Nonlocal(_, scope_id) => Some(scope_id), _ => None, } }); let scope = scope_id.map_or(scope, |scope_id| &semantic.scopes[scope_id]); edits.extend(Renamer::rename_in_scope( name, target, scope, semantic, stylist, )); // Find any scopes in which the symbol is referenced as `nonlocal` or `global`. For example, // given: // // ```python // x = 1 // // def foo(): // global x // // def bar(): // global x // ``` // // When renaming `x` in `foo`, we detect that `x` is a global, and back out to the module // scope. But we need to rename `x` in `bar` too. // // Note that it's impossible for a symbol to be referenced as both `nonlocal` and `global` // in the same program. If a symbol is referenced as `global`, then it must be defined in // the module scope. If a symbol is referenced as `nonlocal`, then it _can't_ be defined in // the module scope (because `nonlocal` can only be used in a nested scope). for scope_id in scope .get_all(name) .filter_map(|binding_id| semantic.rebinding_scopes(binding_id)) .flatten() .dedup() .copied() { let scope = &semantic.scopes[scope_id]; edits.extend(Renamer::rename_in_scope( name, target, scope, semantic, stylist, )); } // Deduplicate any edits. edits.sort(); edits.dedup(); let edit = edits .pop() .ok_or(anyhow!("Unable to rename any references to `{name}`"))?; Ok((edit, edits)) } /// Rename a symbol in a single [`Scope`]. fn rename_in_scope( name: &str, target: &str, scope: &Scope, semantic: &SemanticModel, stylist: &Stylist, ) -> Vec<Edit> { let mut edits = vec![]; // Iterate over every binding to the name in the scope. for binding_id in scope.get_all(name) { let binding = semantic.binding(binding_id); // Rename the binding. if let Some(edit) = Renamer::rename_binding(binding, name, target) { edits.push(edit); if let Some(edit) = Renamer::fixup_assigned_value(binding, semantic, stylist, name, target) { edits.push(edit); } // Rename any delayed annotations. if let Some(annotations) = semantic.delayed_annotations(binding_id) { edits.extend(annotations.iter().filter_map(|annotation_id| { let annotation = semantic.binding(*annotation_id); Renamer::rename_binding(annotation, name, target) })); } // Rename the references to the binding. edits.extend(binding.references().map(|reference_id| { let reference = semantic.reference(reference_id); let replacement = { if reference.in_dunder_all_definition() { debug_assert!(!reference.range().is_empty()); let quote = stylist.quote(); format!("{quote}{target}{quote}") } else { target.to_string() } }; Edit::range_replacement(replacement, reference.range()) })); } } // Deduplicate any edits. In some cases, a reference can be both a read _and_ a write. For // example, `x += 1` is both a read of and a write to `x`. edits.sort(); edits.dedup(); edits } /// If the r.h.s. of a call expression is a call expression, /// we may need to fixup some arguments passed to that call expression. /// /// It's impossible to do this entirely rigorously; /// we only special-case some common standard-library constructors here. /// /// For example, in this `TypeVar` definition: /// ```py /// from typing import TypeVar /// /// _T = TypeVar("_T") /// ``` /// /// If we're renaming it from `_T` to `T`, we want this to be the end result: /// ```py /// from typing import TypeVar /// /// T = TypeVar("T") /// ``` /// /// Not this, which a type checker will reject: /// ```py /// from typing import TypeVar /// /// T = TypeVar("_T") /// ``` fn fixup_assigned_value( binding: &Binding, semantic: &SemanticModel, stylist: &Stylist, name: &str, target: &str, ) -> Option<Edit> { let statement = binding.statement(semantic)?; let (ast::Stmt::Assign(ast::StmtAssign { value, .. }) | ast::Stmt::AnnAssign(ast::StmtAnnAssign { value: Some(value), .. })) = statement else { return None; }; let ast::ExprCall { func, arguments, .. } = value.as_call_expr()?; let qualified_name = semantic.resolve_qualified_name(func)?; let name_argument = match qualified_name.segments() { ["collections", "namedtuple"] => arguments.find_argument_value("typename", 0), [ "typing" | "typing_extensions", "TypeVar" | "ParamSpec" | "TypeVarTuple" | "NewType" | "TypeAliasType", ] => arguments.find_argument_value("name", 0), [ "enum", "Enum" | "IntEnum" | "StrEnum" | "ReprEnum" | "Flag" | "IntFlag", ] | ["typing" | "typing_extensions", "NamedTuple" | "TypedDict"] => { arguments.find_positional(0) } ["builtins" | "", "type"] if arguments.len() == 3 => arguments.find_positional(0), _ => None, }?; let name_argument = name_argument.as_string_literal_expr()?; if name_argument.value.to_str() != name { return None; } let quote = stylist.quote(); Some(Edit::range_replacement( format!("{quote}{target}{quote}"), name_argument.range(), )) } /// Rename a [`Binding`] reference. fn rename_binding(binding: &Binding, name: &str, target: &str) -> Option<Edit> { match &binding.kind { BindingKind::Import(_) | BindingKind::FromImport(_) => { if binding.is_alias() { // Ex) Rename `import pandas as alias` to `import pandas as pd`. Some(Edit::range_replacement(target.to_string(), binding.range())) } else { // Ex) Rename `import pandas` to `import pandas as pd`. Some(Edit::range_replacement( format!("{name} as {target}"), binding.range(), )) } } BindingKind::SubmoduleImport(import) => { // Ex) Rename `import pandas.core` to `import pandas as pd`. let module_name = import.qualified_name.segments().first().unwrap(); Some(Edit::range_replacement( format!("{module_name} as {target}"), binding.range(), )) } // Avoid renaming builtins and other "special" bindings. BindingKind::FutureImport | BindingKind::Builtin | BindingKind::Export(_) | BindingKind::DunderClassCell => None, // By default, replace the binding's name with the target name. BindingKind::Annotation | BindingKind::Argument | BindingKind::TypeParam | BindingKind::NamedExprAssignment | BindingKind::Assignment | BindingKind::BoundException | BindingKind::LoopVar | BindingKind::WithItemVar | BindingKind::Global(_) | BindingKind::Nonlocal(_, _) | BindingKind::ClassDefinition(_) | BindingKind::FunctionDefinition(_) | BindingKind::Deletion | BindingKind::ConditionalDeletion(_) | BindingKind::UnboundException(_) => { Some(Edit::range_replacement(target.to_string(), binding.range())) } } } } /// Enumeration of various ways in which a binding can shadow other variables #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub(crate) enum ShadowedKind { /// The variable shadows a global, nonlocal or local symbol Some, /// The variable shadows a builtin symbol BuiltIn, /// The variable shadows a keyword Keyword, /// The variable does not shadow any other symbols None, } impl ShadowedKind { /// Determines the kind of shadowing or conflict for the proposed new name of a given [`Binding`]. /// /// This function is useful for checking whether or not the `target` of a [`Renamer::rename`] /// will shadow another binding. pub(crate) fn new(binding: &Binding, new_name: &str, checker: &Checker) -> ShadowedKind { // Check the kind in order of precedence if is_keyword(new_name) { return ShadowedKind::Keyword; } if is_python_builtin( new_name, checker.target_version().minor, checker.source_type.is_ipynb(), ) { return ShadowedKind::BuiltIn; } let semantic = checker.semantic(); if !semantic.is_available_in_scope(new_name, binding.scope) { return ShadowedKind::Some; } if binding .references() .map(|reference_id| semantic.reference(reference_id).scope_id()) .dedup() .any(|scope| !semantic.is_available_in_scope(new_name, scope)) { return ShadowedKind::Some; } // Default to no shadowing ShadowedKind::None } /// Returns `true` if `self` shadows any global, nonlocal, or local symbol, keyword, or builtin. pub(crate) const fn shadows_any(self) -> bool { matches!( self, ShadowedKind::Some | ShadowedKind::BuiltIn | ShadowedKind::Keyword ) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/line_width.rs
crates/ruff_linter/src/line_width.rs
use std::error::Error; use std::fmt; use std::hash::Hasher; use std::num::{NonZeroU8, NonZeroU16, ParseIntError}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use unicode_width::UnicodeWidthChar; use ruff_cache::{CacheKey, CacheKeyHasher}; use ruff_macros::CacheKey; use ruff_text_size::TextSize; /// The length of a line of text that is considered too long. /// /// The allowed range of values is 1..=320 #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct LineLength( #[cfg_attr(feature = "schemars", schemars(range(min = 1, max = 320)))] NonZeroU16, ); impl LineLength { /// Maximum allowed value for a valid [`LineLength`] pub const MAX: u16 = 320; /// Return the numeric value for this [`LineLength`] pub fn value(&self) -> u16 { self.0.get() } pub fn text_len(&self) -> TextSize { TextSize::from(u32::from(self.value())) } } impl Default for LineLength { fn default() -> Self { Self(NonZeroU16::new(88).unwrap()) } } impl fmt::Display for LineLength { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl<'de> serde::Deserialize<'de> for LineLength { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = i64::deserialize(deserializer)?; u16::try_from(value) .ok() .and_then(|u16_value| Self::try_from(u16_value).ok()) .ok_or_else(|| { serde::de::Error::custom(format!( "line-length must be between 1 and {} (got {value})", Self::MAX, )) }) } } impl CacheKey for LineLength { fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u16(self.0.get()); } } /// Error type returned when parsing a [`LineLength`] from a string fails pub enum ParseLineWidthError { /// The string could not be parsed as a valid [u16] ParseError(ParseIntError), /// The [u16] value of the string is not a valid [`LineLength`] TryFromIntError(LineLengthFromIntError), } impl std::fmt::Debug for ParseLineWidthError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(self, f) } } impl std::fmt::Display for ParseLineWidthError { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ParseLineWidthError::ParseError(err) => std::fmt::Display::fmt(err, fmt), ParseLineWidthError::TryFromIntError(err) => std::fmt::Display::fmt(err, fmt), } } } impl Error for ParseLineWidthError {} impl FromStr for LineLength { type Err = ParseLineWidthError; fn from_str(s: &str) -> Result<Self, Self::Err> { let value = u16::from_str(s).map_err(ParseLineWidthError::ParseError)?; let value = Self::try_from(value).map_err(ParseLineWidthError::TryFromIntError)?; Ok(value) } } /// Error type returned when converting a u16 to a [`LineLength`] fails #[derive(Clone, Copy, Debug)] pub struct LineLengthFromIntError(pub u16); impl TryFrom<u16> for LineLength { type Error = LineLengthFromIntError; fn try_from(value: u16) -> Result<Self, Self::Error> { match NonZeroU16::try_from(value) { Ok(value) if value.get() <= Self::MAX => Ok(LineLength(value)), Ok(_) | Err(_) => Err(LineLengthFromIntError(value)), } } } impl std::fmt::Display for LineLengthFromIntError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!( f, "The line width must be a value between 1 and {}.", LineLength::MAX ) } } impl From<LineLength> for u16 { fn from(value: LineLength) -> Self { value.0.get() } } impl From<LineLength> for NonZeroU16 { fn from(value: LineLength) -> Self { value.0 } } /// A measure of the width of a line of text. /// /// This is used to determine if a line is too long. /// It should be compared to a [`LineLength`]. #[derive(Clone, Copy, Debug)] pub struct LineWidthBuilder { /// The width of the line. width: usize, /// The column of the line. /// This is used to calculate the width of tabs. column: usize, /// The tab size to use when calculating the width of tabs. tab_size: IndentWidth, } impl Default for LineWidthBuilder { fn default() -> Self { Self::new(IndentWidth::default()) } } impl PartialEq for LineWidthBuilder { fn eq(&self, other: &Self) -> bool { self.width == other.width } } impl Eq for LineWidthBuilder {} impl PartialOrd for LineWidthBuilder { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for LineWidthBuilder { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.width.cmp(&other.width) } } impl LineWidthBuilder { pub fn get(&self) -> usize { self.width } /// Creates a new `LineWidth` with the given tab size. pub fn new(tab_size: IndentWidth) -> Self { LineWidthBuilder { width: 0, column: 0, tab_size, } } fn update(mut self, chars: impl Iterator<Item = char>) -> Self { let tab_size: usize = self.tab_size.as_usize(); for c in chars { match c { '\t' => { let tab_offset = tab_size - (self.column % tab_size); self.width += tab_offset; self.column += tab_offset; } '\n' | '\r' => { self.width = 0; self.column = 0; } _ => { self.width += c.width().unwrap_or(0); self.column += 1; } } } self } /// Adds the given text to the line width. #[must_use] pub fn add_str(self, text: &str) -> Self { self.update(text.chars()) } /// Adds the given character to the line width. #[must_use] pub fn add_char(self, c: char) -> Self { self.update(std::iter::once(c)) } /// Adds the given width to the line width. /// Also adds the given width to the column. /// It is generally better to use [`LineWidthBuilder::add_str`] or [`LineWidthBuilder::add_char`]. /// The width and column should be the same for the corresponding text. /// Currently, this is only used to add spaces. #[must_use] pub fn add_width(mut self, width: usize) -> Self { self.width += width; self.column += width; self } } impl PartialEq<LineLength> for LineWidthBuilder { fn eq(&self, other: &LineLength) -> bool { self.width == (other.value() as usize) } } impl PartialOrd<LineLength> for LineWidthBuilder { fn partial_cmp(&self, other: &LineLength) -> Option<std::cmp::Ordering> { self.width.partial_cmp(&(other.value() as usize)) } } /// The size of a tab. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, CacheKey)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct IndentWidth(NonZeroU8); impl IndentWidth { pub(crate) fn as_usize(self) -> usize { self.0.get() as usize } } impl Default for IndentWidth { fn default() -> Self { Self(NonZeroU8::new(4).unwrap()) } } impl fmt::Display for IndentWidth { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl From<NonZeroU8> for IndentWidth { fn from(tab_size: NonZeroU8) -> Self { Self(tab_size) } } impl From<IndentWidth> for NonZeroU8 { fn from(value: IndentWidth) -> Self { value.0 } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/noqa.rs
crates/ruff_linter/src/noqa.rs
use std::collections::BTreeMap; use std::error::Error; use std::fmt::Display; use std::fs; use std::ops::Add; use std::path::Path; use anyhow::Result; use itertools::Itertools; use log::warn; use ruff_db::diagnostic::{Diagnostic, SecondaryCode}; use ruff_python_trivia::{CommentRanges, Cursor, indentation_at_offset}; use ruff_source_file::{LineEnding, LineRanges}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use rustc_hash::FxHashSet; use crate::Edit; use crate::Locator; use crate::fs::relativize_path; use crate::registry::Rule; use crate::rule_redirects::get_redirect_target; use crate::suppression::Suppressions; /// Generates an array of edits that matches the length of `messages`. /// Each potential edit in the array is paired, in order, with the associated diagnostic. /// Each edit will add a `noqa` comment to the appropriate line in the source to hide /// the diagnostic. These edits may conflict with each other and should not be applied /// simultaneously. #[expect(clippy::too_many_arguments)] pub fn generate_noqa_edits( path: &Path, diagnostics: &[Diagnostic], locator: &Locator, comment_ranges: &CommentRanges, external: &[String], noqa_line_for: &NoqaMapping, line_ending: LineEnding, suppressions: &Suppressions, ) -> Vec<Option<Edit>> { let file_directives = FileNoqaDirectives::extract(locator, comment_ranges, external, path); let exemption = FileExemption::from(&file_directives); let directives = NoqaDirectives::from_commented_ranges(comment_ranges, external, path, locator); let comments = find_noqa_comments( diagnostics, locator, &exemption, &directives, noqa_line_for, suppressions, ); build_noqa_edits_by_diagnostic(comments, locator, line_ending, None) } /// A directive to ignore a set of rules either for a given line of Python source code or an entire file (e.g., /// `# noqa: F401, F841` or `#ruff: noqa: F401, F841`). #[derive(Debug)] pub(crate) enum Directive<'a> { /// The `noqa` directive ignores all rules (e.g., `# noqa`). All(All), /// The `noqa` directive ignores specific rules (e.g., `# noqa: F401, F841`). Codes(Codes<'a>), } #[derive(Debug)] pub(crate) struct All { range: TextRange, } impl Ranged for All { /// The range of the `noqa` directive. fn range(&self) -> TextRange { self.range } } /// An individual rule code in a `noqa` directive (e.g., `F401`). #[derive(Debug)] pub(crate) struct Code<'a> { code: &'a str, range: TextRange, } impl<'a> Code<'a> { /// The code that is ignored by the `noqa` directive. pub(crate) fn as_str(&self) -> &'a str { self.code } } impl Display for Code<'_> { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fmt.write_str(self.code) } } impl Ranged for Code<'_> { /// The range of the rule code. fn range(&self) -> TextRange { self.range } } #[derive(Debug)] pub(crate) struct Codes<'a> { range: TextRange, codes: Vec<Code<'a>>, } impl Codes<'_> { /// Returns an iterator over the [`Code`]s in the `noqa` directive. pub(crate) fn iter(&self) -> std::slice::Iter<'_, Code<'_>> { self.codes.iter() } /// Returns `true` if the string list of `codes` includes `code` (or an alias /// thereof). pub(crate) fn includes<T: for<'a> PartialEq<&'a str>>(&self, needle: &T) -> bool { self.iter() .any(|code| *needle == get_redirect_target(code.as_str()).unwrap_or(code.as_str())) } } impl Ranged for Codes<'_> { /// The range of the `noqa` directive. fn range(&self) -> TextRange { self.range } } /// Returns `true` if the given [`Rule`] is ignored at the specified `lineno`. pub(crate) fn rule_is_ignored( code: Rule, offset: TextSize, noqa_line_for: &NoqaMapping, comment_ranges: &CommentRanges, locator: &Locator, ) -> bool { let offset = noqa_line_for.resolve(offset); let line_range = locator.line_range(offset); let &[comment_range] = comment_ranges.comments_in_range(line_range) else { return false; }; match lex_inline_noqa(comment_range, locator.contents()) { Ok(Some(NoqaLexerOutput { directive: Directive::All(_), .. })) => true, Ok(Some(NoqaLexerOutput { directive: Directive::Codes(codes), .. })) => codes.includes(&code.noqa_code()), _ => false, } } /// A summary of the file-level exemption as extracted from [`FileNoqaDirectives`]. #[derive(Debug)] pub(crate) enum FileExemption { /// The file is exempt from all rules. All(Vec<Rule>), /// The file is exempt from the given rules. Codes(Vec<Rule>), } impl FileExemption { /// Returns `true` if the file is exempt from the given rule, as identified by its noqa code. pub(crate) fn contains_secondary_code(&self, needle: &SecondaryCode) -> bool { match self { FileExemption::All(_) => true, FileExemption::Codes(codes) => codes.iter().any(|code| *needle == code.noqa_code()), } } /// Returns `true` if the file is exempt from the given rule. pub(crate) fn includes(&self, needle: Rule) -> bool { match self { FileExemption::All(_) => true, FileExemption::Codes(codes) => codes.contains(&needle), } } /// Returns `true` if the file exemption lists the rule directly, rather than via a blanket /// exemption. pub(crate) fn enumerates(&self, needle: Rule) -> bool { let codes = match self { FileExemption::All(codes) => codes, FileExemption::Codes(codes) => codes, }; codes.contains(&needle) } } impl<'a> From<&'a FileNoqaDirectives<'a>> for FileExemption { fn from(directives: &'a FileNoqaDirectives) -> Self { let codes = directives .lines() .iter() .flat_map(|line| &line.matches) .copied() .collect(); if directives .lines() .iter() .any(|line| matches!(line.parsed_file_exemption, Directive::All(_))) { FileExemption::All(codes) } else { FileExemption::Codes(codes) } } } /// The directive for a file-level exemption (e.g., `# ruff: noqa`) from an individual line. #[derive(Debug)] pub(crate) struct FileNoqaDirectiveLine<'a> { /// The range of the text line for which the noqa directive applies. pub(crate) range: TextRange, /// The blanket noqa directive. pub(crate) parsed_file_exemption: Directive<'a>, /// The codes that are ignored by the parsed exemptions. pub(crate) matches: Vec<Rule>, } impl Ranged for FileNoqaDirectiveLine<'_> { /// The range of the `noqa` directive. fn range(&self) -> TextRange { self.range } } /// All file-level exemptions (e.g., `# ruff: noqa`) from a given Python file. #[derive(Debug)] pub(crate) struct FileNoqaDirectives<'a>(Vec<FileNoqaDirectiveLine<'a>>); impl<'a> FileNoqaDirectives<'a> { /// Extract the [`FileNoqaDirectives`] for a given Python source file, enumerating any rules /// that are globally ignored within the file. pub(crate) fn extract( locator: &Locator<'a>, comment_ranges: &CommentRanges, external: &[String], path: &Path, ) -> Self { let mut lines = vec![]; for range in comment_ranges { let lexed = lex_file_exemption(range, locator.contents()); match lexed { Ok(Some(NoqaLexerOutput { warnings, directive, })) => { let no_indentation_at_offset = indentation_at_offset(range.start(), locator.contents()).is_none(); if !warnings.is_empty() || no_indentation_at_offset { #[expect(deprecated)] let line = locator.compute_line_index(range.start()); let path_display = relativize_path(path); for warning in warnings { warn!( "Missing or joined rule code(s) at {path_display}:{line}: {warning}" ); } if no_indentation_at_offset { warn!( "Unexpected `# ruff: noqa` directive at {path_display}:{line}. File-level suppression comments must appear on their own line. For line-level suppression, omit the `ruff:` prefix." ); continue; } } let matches = match &directive { Directive::All(_) => { vec![] } Directive::Codes(codes) => { codes.iter().filter_map(|code| { let code = code.as_str(); // Ignore externally-defined rules. if external.iter().any(|external| code.starts_with(external)) { return None; } if let Ok(rule) = Rule::from_code(get_redirect_target(code).unwrap_or(code)) { Some(rule) } else { #[expect(deprecated)] let line = locator.compute_line_index(range.start()); let path_display = relativize_path(path); warn!("Invalid rule code provided to `# ruff: noqa` at {path_display}:{line}: {code}"); None } }).collect() } }; lines.push(FileNoqaDirectiveLine { range, parsed_file_exemption: directive, matches, }); } Err(err) => { #[expect(deprecated)] let line = locator.compute_line_index(range.start()); let path_display = relativize_path(path); warn!("Invalid `# ruff: noqa` directive at {path_display}:{line}: {err}"); } Ok(None) => {} } } Self(lines) } pub(crate) fn lines(&self) -> &[FileNoqaDirectiveLine<'_>] { &self.0 } pub(crate) fn is_empty(&self) -> bool { self.0.is_empty() } } /// Output of lexing a `noqa` directive. #[derive(Debug)] pub(crate) struct NoqaLexerOutput<'a> { warnings: Vec<LexicalWarning>, directive: Directive<'a>, } /// Lexes in-line `noqa` comment, e.g. `# noqa: F401` fn lex_inline_noqa( comment_range: TextRange, source: &str, ) -> Result<Option<NoqaLexerOutput<'_>>, LexicalError> { let lexer = NoqaLexer::in_range(comment_range, source); lexer.lex_inline_noqa() } /// Lexes file-level exemption comment, e.g. `# ruff: noqa: F401` fn lex_file_exemption( comment_range: TextRange, source: &str, ) -> Result<Option<NoqaLexerOutput<'_>>, LexicalError> { let lexer = NoqaLexer::in_range(comment_range, source); lexer.lex_file_exemption() } pub(crate) fn lex_codes(text: &str) -> Result<Vec<Code<'_>>, LexicalError> { let mut lexer = NoqaLexer::in_range(TextRange::new(TextSize::new(0), text.text_len()), text); lexer.lex_codes()?; Ok(lexer.codes) } /// Lexer for `noqa` comment lines. /// /// Assumed to be initialized with range or offset starting /// at the `#` at the beginning of a `noqa` comment. #[derive(Debug)] struct NoqaLexer<'a> { /// Length between offset and end of comment range line_length: TextSize, /// Contains convenience methods for lexing cursor: Cursor<'a>, /// Byte offset of the start of putative `noqa` comment /// /// Note: This is updated in the course of lexing in the case /// where there are multiple comments in a comment range. /// Ex) `# comment # noqa: F401` /// start^ ^-- changed to here during lexing offset: TextSize, /// Non-fatal warnings collected during lexing warnings: Vec<LexicalWarning>, /// Tracks whether we are lexing in a context with a missing delimiter /// e.g. at `C` in `F401C402`. missing_delimiter: bool, /// Rule codes collected during lexing codes: Vec<Code<'a>>, } impl<'a> NoqaLexer<'a> { /// Initialize [`NoqaLexer`] in the given range of source text. fn in_range(range: TextRange, source: &'a str) -> Self { Self { line_length: range.len(), offset: range.start(), cursor: Cursor::new(&source[range]), warnings: Vec::new(), missing_delimiter: false, codes: Vec::new(), } } fn lex_inline_noqa(mut self) -> Result<Option<NoqaLexerOutput<'a>>, LexicalError> { while !self.cursor.is_eof() { // Skip over any leading content. self.cursor.eat_while(|c| c != '#'); // This updates the offset and line length in the case of // multiple comments in a range, e.g. // `# First # Second # noqa` self.offset += self.cursor.token_len(); self.line_length -= self.cursor.token_len(); self.cursor.start_token(); if !self.cursor.eat_char('#') { continue; } self.eat_whitespace(); if !is_noqa_uncased(self.cursor.as_str()) { continue; } self.cursor.skip_bytes("noqa".len()); return Ok(Some(self.lex_directive()?)); } Ok(None) } fn lex_file_exemption(mut self) -> Result<Option<NoqaLexerOutput<'a>>, LexicalError> { while !self.cursor.is_eof() { // Skip over any leading content self.cursor.eat_while(|c| c != '#'); // This updates the offset and line length in the case of // multiple comments in a range, e.g. // # First # Second # noqa self.offset += self.cursor.token_len(); self.line_length -= self.cursor.token_len(); self.cursor.start_token(); // The remaining logic implements a simple regex // `#\s*(?:ruff|flake8)\s*:\s*(?i)noqa` // ^ if !self.cursor.eat_char('#') { continue; } // `#\s*(?:ruff|flake8)\s*:\s*(?i)noqa` // ^^^ self.eat_whitespace(); // `#\s*(?:ruff|flake8)\s*:\s*(?i)noqa` // ^^^^^^^^^^^^^ if self.cursor.as_str().starts_with("ruff") { self.cursor.skip_bytes("ruff".len()); } else if self.cursor.as_str().starts_with("flake8") { self.cursor.skip_bytes("flake8".len()); } else { continue; } // `#\s*(?:ruff|flake8)\s*:\s*(?i)noqa` // ^^^ self.eat_whitespace(); // `#\s*(?:ruff|flake8)\s*:\s*(?i)noqa` // ^ if !self.cursor.eat_char(':') { continue; } // `#\s*(?:ruff|flake8)\s*:\s*(?i)noqa` // ^^^ self.eat_whitespace(); // `#\s*(?:ruff|flake8)\s*:\s*(?i)noqa` // ^^^^^^^ if !is_noqa_uncased(self.cursor.as_str()) { continue; } self.cursor.skip_bytes("noqa".len()); return Ok(Some(self.lex_directive()?)); } Ok(None) } /// Collect codes in `noqa` comment. fn lex_directive(mut self) -> Result<NoqaLexerOutput<'a>, LexicalError> { let range = TextRange::at(self.offset, self.position()); match self.cursor.bump() { // End of comment // Ex) # noqa# A comment None | Some('#') => { return Ok(NoqaLexerOutput { warnings: self.warnings, directive: Directive::All(All { range }), }); } // Ex) # noqa: F401,F842 Some(':') => self.lex_codes()?, // Ex) # noqa A comment // Ex) # noqa : F401 Some(c) if c.is_whitespace() => { self.eat_whitespace(); match self.cursor.bump() { Some(':') => self.lex_codes()?, _ => { return Ok(NoqaLexerOutput { warnings: self.warnings, directive: Directive::All(All { range }), }); } } } // Ex) #noqaA comment // Ex) #noqaF401 _ => { return Err(LexicalError::InvalidSuffix); } } let Some(last) = self.codes.last() else { return Err(LexicalError::MissingCodes); }; Ok(NoqaLexerOutput { warnings: self.warnings, directive: Directive::Codes(Codes { range: TextRange::new(self.offset, last.range.end()), codes: self.codes, }), }) } fn lex_codes(&mut self) -> Result<(), LexicalError> { // SAFETY: Every call to `lex_code` advances the cursor at least once. while !self.cursor.is_eof() { self.lex_code()?; } Ok(()) } fn lex_code(&mut self) -> Result<(), LexicalError> { self.cursor.start_token(); self.eat_whitespace(); // Ex) # noqa: F401, ,F841 // ^^^^ if self.cursor.first() == ',' { self.warnings.push(LexicalWarning::MissingItem( self.token_range().add(self.offset), )); self.cursor.eat_char(','); return Ok(()); } let before_code = self.cursor.as_str(); // Reset start of token so it does not include whitespace self.cursor.start_token(); match self.cursor.bump() { // Ex) # noqa: F401 // ^ Some(c) if c.is_ascii_uppercase() => { self.cursor.eat_while(|chr| chr.is_ascii_uppercase()); if !self.cursor.eat_if(|c| c.is_ascii_digit()) { // Fail hard if we're already attempting // to lex squashed codes, e.g. `F401Fabc` if self.missing_delimiter { return Err(LexicalError::InvalidCodeSuffix); } // Otherwise we've reached the first invalid code, // so it could be a comment and we just stop parsing. // Ex) #noqa: F401 A comment // we're here^ self.cursor.skip_bytes(self.cursor.as_str().len()); return Ok(()); } self.cursor.eat_while(|chr| chr.is_ascii_digit()); let code = &before_code[..self.cursor.token_len().to_usize()]; self.push_code(code); if self.cursor.is_eof() { return Ok(()); } self.missing_delimiter = match self.cursor.first() { ',' => { self.cursor.eat_char(','); false } // Whitespace is an allowed delimiter or the end of the `noqa`. c if c.is_whitespace() => false, // e.g. #noqa:F401F842 // ^ // Push a warning and update the `missing_delimiter` // state but don't consume the character since it's // part of the next code. c if c.is_ascii_uppercase() => { self.warnings .push(LexicalWarning::MissingDelimiter(TextRange::empty( self.offset + self.position(), ))); true } // Start of a new comment // e.g. #noqa: F401#A comment // ^ '#' => false, _ => return Err(LexicalError::InvalidCodeSuffix), }; } Some(_) => { // The first time we hit an evidently invalid code, // it's probably a trailing comment. So stop lexing, // but don't push an error. // Ex) // # noqa: F401 we import this for a reason // ^----- stop lexing but no error self.cursor.skip_bytes(self.cursor.as_str().len()); } None => {} } Ok(()) } /// Push current token to stack of [`Code`] objects fn push_code(&mut self, code: &'a str) { self.codes.push(Code { code, range: self.token_range().add(self.offset), }); } /// Consume whitespace #[inline] fn eat_whitespace(&mut self) { self.cursor.eat_while(char::is_whitespace); } /// Current token range relative to offset #[inline] fn token_range(&self) -> TextRange { let end = self.position(); let len = self.cursor.token_len(); TextRange::at(end - len, len) } /// Retrieves the current position of the cursor within the line. #[inline] fn position(&self) -> TextSize { self.line_length - self.cursor.text_len() } } /// Helper to check if "noqa" (case-insensitive) appears at the given position #[inline] fn is_noqa_uncased(text: &str) -> bool { matches!( text.as_bytes(), [b'n' | b'N', b'o' | b'O', b'q' | b'Q', b'a' | b'A', ..] ) } /// Indicates recoverable error encountered while lexing with [`NoqaLexer`] #[derive(Debug, Clone, Copy)] enum LexicalWarning { MissingItem(TextRange), MissingDelimiter(TextRange), } impl Display for LexicalWarning { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::MissingItem(_) => f.write_str("expected rule code between commas"), Self::MissingDelimiter(_) => { f.write_str("expected comma or space delimiter between codes") } } } } impl Ranged for LexicalWarning { fn range(&self) -> TextRange { match *self { LexicalWarning::MissingItem(text_range) => text_range, LexicalWarning::MissingDelimiter(text_range) => text_range, } } } /// Fatal error occurring while lexing a `noqa` comment as in [`NoqaLexer`] #[derive(Debug)] pub(crate) enum LexicalError { /// The `noqa` directive was missing valid codes (e.g., `# noqa: unused-import` instead of `# noqa: F401`). MissingCodes, /// The `noqa` directive used an invalid suffix (e.g., `# noqa; F401` instead of `# noqa: F401`). InvalidSuffix, /// The `noqa` code matched the regex "[A-Z]+[0-9]+" with text remaining /// (e.g. `# noqa: F401abc`) InvalidCodeSuffix, } impl Display for LexicalError { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { LexicalError::MissingCodes => fmt.write_str("expected a comma-separated list of codes (e.g., `# noqa: F401, F841`)."), LexicalError::InvalidSuffix => { fmt.write_str("expected `:` followed by a comma-separated list of codes (e.g., `# noqa: F401, F841`).") } LexicalError::InvalidCodeSuffix => { fmt.write_str("expected code to consist of uppercase letters followed by digits only (e.g. `F401`)") } } } } impl Error for LexicalError {} /// Adds noqa comments to suppress all messages of a file. #[expect(clippy::too_many_arguments)] pub(crate) fn add_noqa( path: &Path, diagnostics: &[Diagnostic], locator: &Locator, comment_ranges: &CommentRanges, external: &[String], noqa_line_for: &NoqaMapping, line_ending: LineEnding, reason: Option<&str>, suppressions: &Suppressions, ) -> Result<usize> { let (count, output) = add_noqa_inner( path, diagnostics, locator, comment_ranges, external, noqa_line_for, line_ending, reason, suppressions, ); fs::write(path, output)?; Ok(count) } #[expect(clippy::too_many_arguments)] fn add_noqa_inner( path: &Path, diagnostics: &[Diagnostic], locator: &Locator, comment_ranges: &CommentRanges, external: &[String], noqa_line_for: &NoqaMapping, line_ending: LineEnding, reason: Option<&str>, suppressions: &Suppressions, ) -> (usize, String) { let mut count = 0; // Whether the file is exempted from all checks. let directives = FileNoqaDirectives::extract(locator, comment_ranges, external, path); let exemption = FileExemption::from(&directives); let directives = NoqaDirectives::from_commented_ranges(comment_ranges, external, path, locator); let comments = find_noqa_comments( diagnostics, locator, &exemption, &directives, noqa_line_for, suppressions, ); let edits = build_noqa_edits_by_line(comments, locator, line_ending, reason); let contents = locator.contents(); let mut output = String::with_capacity(contents.len()); let mut last_append = TextSize::default(); for (_, edit) in edits { output.push_str(&contents[TextRange::new(last_append, edit.start())]); edit.write(&mut output); count += 1; last_append = edit.end(); } output.push_str(&contents[TextRange::new(last_append, TextSize::of(contents))]); (count, output) } fn build_noqa_edits_by_diagnostic( comments: Vec<Option<NoqaComment>>, locator: &Locator, line_ending: LineEnding, reason: Option<&str>, ) -> Vec<Option<Edit>> { let mut edits = Vec::default(); for comment in comments { match comment { Some(comment) => { if let Some(noqa_edit) = generate_noqa_edit( comment.directive, comment.line, FxHashSet::from_iter([comment.code]), locator, line_ending, reason, ) { edits.push(Some(noqa_edit.into_edit())); } } None => edits.push(None), } } edits } fn build_noqa_edits_by_line<'a>( comments: Vec<Option<NoqaComment<'a>>>, locator: &Locator, line_ending: LineEnding, reason: Option<&'a str>, ) -> BTreeMap<TextSize, NoqaEdit<'a>> { let mut comments_by_line = BTreeMap::default(); for comment in comments.into_iter().flatten() { comments_by_line .entry(comment.line) .or_insert_with(Vec::default) .push(comment); } let mut edits = BTreeMap::default(); for (offset, matches) in comments_by_line { let Some(first_match) = matches.first() else { continue; }; let directive = first_match.directive; if let Some(edit) = generate_noqa_edit( directive, offset, matches .into_iter() .map(|NoqaComment { code, .. }| code) .collect(), locator, line_ending, reason, ) { edits.insert(offset, edit); } } edits } struct NoqaComment<'a> { line: TextSize, code: &'a SecondaryCode, directive: Option<&'a Directive<'a>>, } fn find_noqa_comments<'a>( diagnostics: &'a [Diagnostic], locator: &'a Locator, exemption: &'a FileExemption, directives: &'a NoqaDirectives, noqa_line_for: &NoqaMapping, suppressions: &'a Suppressions, ) -> Vec<Option<NoqaComment<'a>>> { // List of noqa comments, ordered to match up with `messages` let mut comments_by_line: Vec<Option<NoqaComment<'a>>> = vec![]; // Mark any non-ignored diagnostics. for message in diagnostics { let Some(code) = message.secondary_code() else { comments_by_line.push(None); continue; }; if exemption.contains_secondary_code(code) { comments_by_line.push(None); continue; } // Apply ranged suppressions next if suppressions.check_diagnostic(message) { comments_by_line.push(None); continue; } // Is the violation ignored by a `noqa` directive on the parent line? if let Some(parent) = message.parent() { if let Some(directive_line) = directives.find_line_with_directive(noqa_line_for.resolve(parent)) { match &directive_line.directive { Directive::All(_) => { comments_by_line.push(None); continue; } Directive::Codes(codes) => { if codes.includes(code) { comments_by_line.push(None); continue; } } } } } let noqa_offset = message .range() .map(|range| noqa_line_for.resolve(range.start())) .unwrap_or_default(); // Or ignored by the directive itself? if let Some(directive_line) = directives.find_line_with_directive(noqa_offset) { match &directive_line.directive { Directive::All(_) => { comments_by_line.push(None); continue; } directive @ Directive::Codes(codes) => { if !codes.includes(code) { comments_by_line.push(Some(NoqaComment { line: directive_line.start(), code, directive: Some(directive), })); } continue; } } } // There's no existing noqa directive that suppresses the diagnostic. comments_by_line.push(Some(NoqaComment { line: locator.line_start(noqa_offset), code, directive: None, })); } comments_by_line } struct NoqaEdit<'a> { edit_range: TextRange, noqa_codes: FxHashSet<&'a SecondaryCode>, codes: Option<&'a Codes<'a>>, line_ending: LineEnding, reason: Option<&'a str>, } impl NoqaEdit<'_> { fn into_edit(self) -> Edit { let mut edit_content = String::new(); self.write(&mut edit_content); Edit::range_replacement(edit_content, self.edit_range) } fn write(&self, writer: &mut impl std::fmt::Write) { write!(writer, " # noqa: ").unwrap(); match self.codes { Some(codes) => { push_codes( writer, self.noqa_codes .iter() .map(|code| code.as_str()) .chain(codes.iter().map(Code::as_str)) .sorted_unstable(), ); } None => { push_codes(writer, self.noqa_codes.iter().sorted_unstable()); } } if let Some(reason) = self.reason { write!(writer, " {reason}").unwrap(); } write!(writer, "{}", self.line_ending.as_str()).unwrap(); } } impl Ranged for NoqaEdit<'_> { fn range(&self) -> TextRange { self.edit_range } } fn generate_noqa_edit<'a>( directive: Option<&'a Directive>, offset: TextSize, noqa_codes: FxHashSet<&'a SecondaryCode>, locator: &Locator,
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rule_selector.rs
crates/ruff_linter/src/rule_selector.rs
use std::str::FromStr; use serde::de::{self, Visitor}; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; use strum_macros::EnumIter; use crate::codes::RuleIter; use crate::codes::{RuleCodePrefix, RuleGroup}; use crate::registry::{Linter, Rule, RuleNamespace}; use crate::rule_redirects::get_redirect; use crate::settings::types::PreviewMode; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum RuleSelector { /// Select all rules (includes rules in preview if enabled) All, /// Legacy category to select both the `mccabe` and `flake8-comprehensions` linters /// via a single selector. C, /// Legacy category to select both the `flake8-debugger` and `flake8-print` linters /// via a single selector. T, /// Select all rules for a given linter. Linter(Linter), /// Select all rules for a given linter with a given prefix. Prefix { prefix: RuleCodePrefix, redirected_from: Option<&'static str>, }, /// Select an individual rule with a given prefix. Rule { prefix: RuleCodePrefix, redirected_from: Option<&'static str>, }, } impl From<Linter> for RuleSelector { fn from(linter: Linter) -> Self { Self::Linter(linter) } } impl Ord for RuleSelector { fn cmp(&self, other: &Self) -> std::cmp::Ordering { // TODO(zanieb): We ought to put "ALL" and "Linter" selectors // above those that are rule specific but it's not critical for now self.prefix_and_code().cmp(&other.prefix_and_code()) } } impl PartialOrd for RuleSelector { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl FromStr for RuleSelector { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { // **Changes should be reflected in `parse_no_redirect` as well** match s { "ALL" => Ok(Self::All), "C" => Ok(Self::C), "T" => Ok(Self::T), _ => { let (s, redirected_from) = match get_redirect(s) { Some((from, target)) => (target, Some(from)), None => (s, None), }; let (linter, code) = Linter::parse_code(s).ok_or_else(|| ParseError::Unknown(s.to_string()))?; if code.is_empty() { return Ok(Self::Linter(linter)); } let prefix = RuleCodePrefix::parse(&linter, code) .map_err(|_| ParseError::Unknown(s.to_string()))?; if is_single_rule_selector(&prefix) { Ok(Self::Rule { prefix, redirected_from, }) } else { Ok(Self::Prefix { prefix, redirected_from, }) } } } } } /// Returns `true` if the [`RuleCodePrefix`] matches a single rule exactly /// (e.g., `E225`, as opposed to `E2`). pub(crate) fn is_single_rule_selector(prefix: &RuleCodePrefix) -> bool { let mut rules = prefix.rules(); // The selector must match a single rule. let Some(rule) = rules.next() else { return false; }; if rules.next().is_some() { return false; } // The rule must match the selector exactly. rule.noqa_code().suffix() == prefix.short_code() } #[derive(Debug, thiserror::Error)] pub enum ParseError { #[error("Unknown rule selector: `{0}`")] // TODO(martin): tell the user how to discover rule codes via the CLI once such a command is // implemented (but that should of course be done only in ruff and not here) Unknown(String), } impl RuleSelector { pub fn prefix_and_code(&self) -> (&'static str, &'static str) { match self { RuleSelector::All => ("", "ALL"), RuleSelector::C => ("", "C"), RuleSelector::T => ("", "T"), RuleSelector::Prefix { prefix, .. } | RuleSelector::Rule { prefix, .. } => { (prefix.linter().common_prefix(), prefix.short_code()) } RuleSelector::Linter(l) => (l.common_prefix(), ""), } } } impl Serialize for RuleSelector { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let (prefix, code) = self.prefix_and_code(); serializer.serialize_str(&format!("{prefix}{code}")) } } impl<'de> Deserialize<'de> for RuleSelector { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { // We are not simply doing: // let s: &str = Deserialize::deserialize(deserializer)?; // FromStr::from_str(s).map_err(de::Error::custom) // here because the toml crate apparently doesn't support that // (as of toml v0.6.0 running `cargo test` failed with the above two lines) deserializer.deserialize_str(SelectorVisitor) } } struct SelectorVisitor; impl Visitor<'_> for SelectorVisitor { type Value = RuleSelector; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str( "expected a string code identifying a linter or specific rule, or a partial rule code or ALL to refer to all rules", ) } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { FromStr::from_str(v).map_err(de::Error::custom) } } impl RuleSelector { /// Return all matching rules, regardless of rule group filters like preview and deprecated. pub fn all_rules(&self) -> impl Iterator<Item = Rule> + '_ { match self { RuleSelector::All => RuleSelectorIter::All(Rule::iter()), RuleSelector::C => RuleSelectorIter::Chain( Linter::Flake8Comprehensions .rules() .chain(Linter::McCabe.rules()), ), RuleSelector::T => RuleSelectorIter::Chain( Linter::Flake8Debugger .rules() .chain(Linter::Flake8Print.rules()), ), RuleSelector::Linter(linter) => RuleSelectorIter::Vec(linter.rules()), RuleSelector::Prefix { prefix, .. } | RuleSelector::Rule { prefix, .. } => { RuleSelectorIter::Vec(prefix.clone().rules()) } } } /// Returns rules matching the selector, taking into account rule groups like preview and deprecated. pub fn rules<'a>(&'a self, preview: &PreviewOptions) -> impl Iterator<Item = Rule> + use<'a> { let preview_enabled = preview.mode.is_enabled(); let preview_require_explicit = preview.require_explicit; self.all_rules().filter(move |rule| { match rule.group() { // Always include stable rules RuleGroup::Stable { .. } => true, // Enabling preview includes all preview rules unless explicit selection is turned on RuleGroup::Preview { .. } => { preview_enabled && (self.is_exact() || !preview_require_explicit) } // Deprecated rules are excluded by default unless explicitly selected RuleGroup::Deprecated { .. } => !preview_enabled && self.is_exact(), // Removed rules are included if explicitly selected but will error downstream RuleGroup::Removed { .. } => self.is_exact(), } }) } /// Returns true if this selector is exact i.e. selects a single rule by code pub fn is_exact(&self) -> bool { matches!(self, Self::Rule { .. }) } } pub enum RuleSelectorIter { All(RuleIter), Chain(std::iter::Chain<std::vec::IntoIter<Rule>, std::vec::IntoIter<Rule>>), Vec(std::vec::IntoIter<Rule>), } impl Iterator for RuleSelectorIter { type Item = Rule; fn next(&mut self) -> Option<Self::Item> { match self { RuleSelectorIter::All(iter) => iter.next(), RuleSelectorIter::Chain(iter) => iter.next(), RuleSelectorIter::Vec(iter) => iter.next(), } } } #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct PreviewOptions { pub mode: PreviewMode, /// If true, preview rule selection requires explicit codes e.g. not prefixes. /// Generally this should be derived from the user-facing `explicit-preview-rules` option. pub require_explicit: bool, } #[cfg(feature = "schemars")] mod schema { use itertools::Itertools; use schemars::{JsonSchema, Schema, SchemaGenerator}; use serde_json::Value; use strum::IntoEnumIterator; use crate::RuleSelector; use crate::registry::RuleNamespace; use crate::rule_selector::{Linter, RuleCodePrefix}; impl JsonSchema for RuleSelector { fn schema_name() -> std::borrow::Cow<'static, str> { std::borrow::Cow::Borrowed("RuleSelector") } fn json_schema(_gen: &mut SchemaGenerator) -> Schema { let enum_values: Vec<String> = [ // Include the non-standard "ALL" selectors. "ALL".to_string(), // Include the legacy "C" and "T" selectors. "C".to_string(), "T".to_string(), // Include some common redirect targets for those legacy selectors. "C9".to_string(), "T1".to_string(), "T2".to_string(), ] .into_iter() .chain( RuleCodePrefix::iter() .map(|p| { let prefix = p.linter().common_prefix(); let code = p.short_code(); format!("{prefix}{code}") }) .chain(Linter::iter().filter_map(|l| { let prefix = l.common_prefix(); (!prefix.is_empty()).then(|| prefix.to_string()) })), ) .filter(|p| { // Exclude any prefixes where all of the rules are removed if let Ok(Self::Rule { prefix, .. } | Self::Prefix { prefix, .. }) = RuleSelector::parse_no_redirect(p) { !prefix.rules().all(|rule| rule.is_removed()) } else { true } }) .filter(|_rule| { // Filter out all test-only rules #[cfg(any(feature = "test-rules", test))] #[expect(clippy::used_underscore_binding)] if _rule.starts_with("RUF9") || _rule == "PLW0101" { return false; } true }) .sorted() .collect(); let mut schema = schemars::json_schema!({ "type": "string" }); schema.ensure_object().insert( "enum".to_string(), Value::Array(enum_values.into_iter().map(Value::String).collect()), ); schema } } } impl RuleSelector { pub fn specificity(&self) -> Specificity { match self { RuleSelector::All => Specificity::All, RuleSelector::T => Specificity::LinterGroup, RuleSelector::C => Specificity::LinterGroup, RuleSelector::Linter(..) => Specificity::Linter, RuleSelector::Rule { .. } => Specificity::Rule, RuleSelector::Prefix { prefix, .. } => { let prefix: &'static str = prefix.short_code(); match prefix.len() { 1 => Specificity::Prefix1Char, 2 => Specificity::Prefix2Chars, 3 => Specificity::Prefix3Chars, 4 => Specificity::Prefix4Chars, _ => panic!( "RuleSelector::specificity doesn't yet support codes with so many characters" ), } } } } /// Parse [`RuleSelector`] from a string; but do not follow redirects. pub fn parse_no_redirect(s: &str) -> Result<Self, ParseError> { // **Changes should be reflected in `from_str` as well** match s { "ALL" => Ok(Self::All), "C" => Ok(Self::C), "T" => Ok(Self::T), _ => { let (linter, code) = Linter::parse_code(s).ok_or_else(|| ParseError::Unknown(s.to_string()))?; if code.is_empty() { return Ok(Self::Linter(linter)); } let prefix = RuleCodePrefix::parse(&linter, code) .map_err(|_| ParseError::Unknown(s.to_string()))?; if is_single_rule_selector(&prefix) { Ok(Self::Rule { prefix, redirected_from: None, }) } else { Ok(Self::Prefix { prefix, redirected_from: None, }) } } } } } #[derive(EnumIter, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)] pub enum Specificity { /// The specificity when selecting all rules (e.g., `--select ALL`). All, /// The specificity when selecting a legacy linter group (e.g., `--select C` or `--select T`). LinterGroup, /// The specificity when selecting a linter (e.g., `--select PLE` or `--select UP`). Linter, /// The specificity when selecting via a rule prefix with a one-character code (e.g., `--select PLE1`). Prefix1Char, /// The specificity when selecting via a rule prefix with a two-character code (e.g., `--select PLE12`). Prefix2Chars, /// The specificity when selecting via a rule prefix with a three-character code (e.g., `--select PLE123`). Prefix3Chars, /// The specificity when selecting via a rule prefix with a four-character code (e.g., `--select PLE1234`). Prefix4Chars, /// The specificity when selecting an individual rule (e.g., `--select PLE1205`). Rule, } #[cfg(feature = "clap")] pub mod clap_completion { use clap::builder::{PossibleValue, TypedValueParser, ValueParserFactory}; use strum::IntoEnumIterator; use crate::{ RuleSelector, codes::RuleCodePrefix, registry::{Linter, RuleNamespace}, rule_selector::is_single_rule_selector, }; #[derive(Clone)] pub struct RuleSelectorParser; impl ValueParserFactory for RuleSelector { type Parser = RuleSelectorParser; fn value_parser() -> Self::Parser { RuleSelectorParser } } impl TypedValueParser for RuleSelectorParser { type Value = RuleSelector; fn parse_ref( &self, cmd: &clap::Command, arg: Option<&clap::Arg>, value: &std::ffi::OsStr, ) -> Result<Self::Value, clap::Error> { let value = value .to_str() .ok_or_else(|| clap::Error::new(clap::error::ErrorKind::InvalidUtf8))?; value.parse().map_err(|_| { let mut error = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd); if let Some(arg) = arg { error.insert( clap::error::ContextKind::InvalidArg, clap::error::ContextValue::String(arg.to_string()), ); } error.insert( clap::error::ContextKind::InvalidValue, clap::error::ContextValue::String(value.to_string()), ); error }) } fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> { Some(Box::new( std::iter::once(PossibleValue::new("ALL").help("all rules")).chain( Linter::iter() .filter_map(|l| { let prefix = l.common_prefix(); (!prefix.is_empty()).then(|| PossibleValue::new(prefix).help(l.name())) }) .chain(RuleCodePrefix::iter().filter_map(|prefix| { // Ex) `UP` if prefix.short_code().is_empty() { let code = prefix.linter().common_prefix(); let name = prefix.linter().name(); return Some(PossibleValue::new(code).help(name)); } // Ex) `UP004` if is_single_rule_selector(&prefix) { let rule = prefix.rules().next()?; let code = format!( "{}{}", prefix.linter().common_prefix(), prefix.short_code() ); return Some(PossibleValue::new(code).help(rule.name().as_str())); } None })), ), )) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/registry.rs
crates/ruff_linter/src/registry.rs
//! Remnant of the registry of all [`Rule`] implementations, now it's reexporting from codes.rs //! with some helper symbols use ruff_db::diagnostic::LintName; use strum_macros::EnumIter; pub use codes::Rule; use ruff_macros::RuleNamespace; pub use rule_set::{RuleSet, RuleSetIterator}; use crate::codes::{self}; mod rule_set; pub trait AsRule { fn rule(&self) -> Rule; } impl Rule { pub fn from_code(code: &str) -> Result<Self, FromCodeError> { let (linter, code) = Linter::parse_code(code).ok_or(FromCodeError::Unknown)?; linter .all_rules() .find(|rule| rule.noqa_code().suffix() == code) .ok_or(FromCodeError::Unknown) } } #[derive(thiserror::Error, Debug)] pub enum FromCodeError { #[error("unknown rule code")] Unknown, } #[derive(EnumIter, Debug, PartialEq, Eq, Clone, Hash, RuleNamespace)] pub enum Linter { /// [Airflow](https://pypi.org/project/apache-airflow/) #[prefix = "AIR"] Airflow, /// [eradicate](https://pypi.org/project/eradicate/) #[prefix = "ERA"] Eradicate, /// [FastAPI](https://pypi.org/project/fastapi/) #[prefix = "FAST"] FastApi, /// [flake8-2020](https://pypi.org/project/flake8-2020/) #[prefix = "YTT"] Flake82020, /// [flake8-annotations](https://pypi.org/project/flake8-annotations/) #[prefix = "ANN"] Flake8Annotations, /// [flake8-async](https://pypi.org/project/flake8-async/) #[prefix = "ASYNC"] Flake8Async, /// [flake8-bandit](https://pypi.org/project/flake8-bandit/) #[prefix = "S"] Flake8Bandit, /// [flake8-blind-except](https://pypi.org/project/flake8-blind-except/) #[prefix = "BLE"] Flake8BlindExcept, /// [flake8-boolean-trap](https://pypi.org/project/flake8-boolean-trap/) #[prefix = "FBT"] Flake8BooleanTrap, /// [flake8-bugbear](https://pypi.org/project/flake8-bugbear/) #[prefix = "B"] Flake8Bugbear, /// [flake8-builtins](https://pypi.org/project/flake8-builtins/) #[prefix = "A"] Flake8Builtins, /// [flake8-commas](https://pypi.org/project/flake8-commas/) #[prefix = "COM"] Flake8Commas, /// [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/) #[prefix = "C4"] Flake8Comprehensions, /// [flake8-copyright](https://pypi.org/project/flake8-copyright/) #[prefix = "CPY"] Flake8Copyright, /// [flake8-datetimez](https://pypi.org/project/flake8-datetimez/) #[prefix = "DTZ"] Flake8Datetimez, /// [flake8-debugger](https://pypi.org/project/flake8-debugger/) #[prefix = "T10"] Flake8Debugger, /// [flake8-django](https://pypi.org/project/flake8-django/) #[prefix = "DJ"] Flake8Django, /// [flake8-errmsg](https://pypi.org/project/flake8-errmsg/) #[prefix = "EM"] Flake8ErrMsg, /// [flake8-executable](https://pypi.org/project/flake8-executable/) #[prefix = "EXE"] Flake8Executable, /// [flake8-fixme](https://github.com/tommilligan/flake8-fixme) #[prefix = "FIX"] Flake8Fixme, /// [flake8-future-annotations](https://pypi.org/project/flake8-future-annotations/) #[prefix = "FA"] Flake8FutureAnnotations, /// [flake8-gettext](https://pypi.org/project/flake8-gettext/) #[prefix = "INT"] Flake8GetText, /// [flake8-implicit-str-concat](https://pypi.org/project/flake8-implicit-str-concat/) #[prefix = "ISC"] Flake8ImplicitStrConcat, /// [flake8-import-conventions](https://github.com/joaopalmeiro/flake8-import-conventions) #[prefix = "ICN"] Flake8ImportConventions, /// [flake8-logging](https://pypi.org/project/flake8-logging/) #[prefix = "LOG"] Flake8Logging, /// [flake8-logging-format](https://pypi.org/project/flake8-logging-format/) #[prefix = "G"] Flake8LoggingFormat, /// [flake8-no-pep420](https://pypi.org/project/flake8-no-pep420/) #[prefix = "INP"] Flake8NoPep420, /// [flake8-pie](https://pypi.org/project/flake8-pie/) #[prefix = "PIE"] Flake8Pie, /// [flake8-print](https://pypi.org/project/flake8-print/) #[prefix = "T20"] Flake8Print, /// [flake8-pyi](https://pypi.org/project/flake8-pyi/) #[prefix = "PYI"] Flake8Pyi, /// [flake8-pytest-style](https://pypi.org/project/flake8-pytest-style/) #[prefix = "PT"] Flake8PytestStyle, /// [flake8-quotes](https://pypi.org/project/flake8-quotes/) #[prefix = "Q"] Flake8Quotes, /// [flake8-raise](https://pypi.org/project/flake8-raise/) #[prefix = "RSE"] Flake8Raise, /// [flake8-return](https://pypi.org/project/flake8-return/) #[prefix = "RET"] Flake8Return, /// [flake8-self](https://pypi.org/project/flake8-self/) #[prefix = "SLF"] Flake8Self, /// [flake8-simplify](https://pypi.org/project/flake8-simplify/) #[prefix = "SIM"] Flake8Simplify, /// [flake8-slots](https://pypi.org/project/flake8-slots/) #[prefix = "SLOT"] Flake8Slots, /// [flake8-tidy-imports](https://pypi.org/project/flake8-tidy-imports/) #[prefix = "TID"] Flake8TidyImports, /// [flake8-todos](https://github.com/orsinium-labs/flake8-todos/) #[prefix = "TD"] Flake8Todos, /// [flake8-type-checking](https://pypi.org/project/flake8-type-checking/) #[prefix = "TC"] Flake8TypeChecking, /// [flake8-unused-arguments](https://pypi.org/project/flake8-unused-arguments/) #[prefix = "ARG"] Flake8UnusedArguments, /// [flake8-use-pathlib](https://pypi.org/project/flake8-use-pathlib/) #[prefix = "PTH"] Flake8UsePathlib, /// [flynt](https://pypi.org/project/flynt/) #[prefix = "FLY"] Flynt, /// [isort](https://pypi.org/project/isort/) #[prefix = "I"] Isort, /// [mccabe](https://pypi.org/project/mccabe/) #[prefix = "C90"] McCabe, /// NumPy-specific rules #[prefix = "NPY"] Numpy, /// [pandas-vet](https://pypi.org/project/pandas-vet/) #[prefix = "PD"] PandasVet, /// [pep8-naming](https://pypi.org/project/pep8-naming/) #[prefix = "N"] PEP8Naming, /// [Perflint](https://pypi.org/project/perflint/) #[prefix = "PERF"] Perflint, /// [pycodestyle](https://pypi.org/project/pycodestyle/) #[prefix = "E"] #[prefix = "W"] Pycodestyle, /// [pydoclint](https://pypi.org/project/pydoclint/) #[prefix = "DOC"] Pydoclint, /// [pydocstyle](https://pypi.org/project/pydocstyle/) #[prefix = "D"] Pydocstyle, /// [Pyflakes](https://pypi.org/project/pyflakes/) #[prefix = "F"] Pyflakes, /// [pygrep-hooks](https://github.com/pre-commit/pygrep-hooks) #[prefix = "PGH"] PygrepHooks, /// [Pylint](https://pypi.org/project/pylint/) #[prefix = "PL"] Pylint, /// [pyupgrade](https://pypi.org/project/pyupgrade/) #[prefix = "UP"] Pyupgrade, /// [refurb](https://pypi.org/project/refurb/) #[prefix = "FURB"] Refurb, /// Ruff-specific rules #[prefix = "RUF"] Ruff, /// [tryceratops](https://pypi.org/project/tryceratops/) #[prefix = "TRY"] Tryceratops, } pub trait RuleNamespace: Sized { /// Returns the prefix that every single code that ruff uses to identify /// rules from this linter starts with. In the case that multiple /// `#[prefix]`es are configured for the variant in the `Linter` enum /// definition this is the empty string. fn common_prefix(&self) -> &'static str; /// Attempts to parse the given rule code. If the prefix is recognized /// returns the respective variant along with the code with the common /// prefix stripped. fn parse_code(code: &str) -> Option<(Self, &str)>; fn name(&self) -> &'static str; fn url(&self) -> Option<&'static str>; } #[derive(is_macro::Is, Copy, Clone)] pub enum LintSource { Ast, Io, PhysicalLines, LogicalLines, Tokens, Imports, Noqa, Filesystem, PyprojectToml, } impl Rule { /// The source for the diagnostic (either the AST, the filesystem, or the /// physical lines). pub const fn lint_source(&self) -> LintSource { match self { Rule::InvalidPyprojectToml => LintSource::PyprojectToml, Rule::BlanketNOQA | Rule::RedirectedNOQA | Rule::UnusedNOQA => LintSource::Noqa, Rule::BidirectionalUnicode | Rule::BlankLineWithWhitespace | Rule::DocLineTooLong | Rule::IndentedFormFeed | Rule::LineTooLong | Rule::MissingCopyrightNotice | Rule::MissingNewlineAtEndOfFile | Rule::MixedSpacesAndTabs | Rule::TrailingWhitespace => LintSource::PhysicalLines, Rule::AmbiguousUnicodeCharacterComment | Rule::BlanketTypeIgnore | Rule::BlankLineAfterDecorator | Rule::BlankLineBetweenMethods | Rule::BlankLinesAfterFunctionOrClass | Rule::BlankLinesBeforeNestedDefinition | Rule::BlankLinesTopLevel | Rule::CommentedOutCode | Rule::EmptyComment | Rule::ExtraneousParentheses | Rule::InvalidCharacterBackspace | Rule::InvalidCharacterEsc | Rule::InvalidCharacterNul | Rule::InvalidCharacterSub | Rule::InvalidCharacterZeroWidthSpace | Rule::InvalidTodoCapitalization | Rule::InvalidTodoTag | Rule::LineContainsFixme | Rule::LineContainsHack | Rule::LineContainsTodo | Rule::LineContainsXxx | Rule::MissingSpaceAfterTodoColon | Rule::MissingTodoAuthor | Rule::MissingTodoColon | Rule::MissingTodoDescription | Rule::MissingTodoLink | Rule::MissingTrailingComma | Rule::MultiLineImplicitStringConcatenation | Rule::MultipleStatementsOnOneLineColon | Rule::MultipleStatementsOnOneLineSemicolon | Rule::ProhibitedTrailingComma | Rule::ShebangLeadingWhitespace | Rule::ShebangMissingExecutableFile | Rule::ShebangMissingPython | Rule::ShebangNotExecutable | Rule::ShebangNotFirstLine | Rule::SingleLineImplicitStringConcatenation | Rule::TabIndentation | Rule::TooManyBlankLines | Rule::TooManyNewlinesAtEndOfFile | Rule::TrailingCommaOnBareTuple | Rule::TypeCommentInStub | Rule::UselessSemicolon | Rule::UTF8EncodingDeclaration => LintSource::Tokens, Rule::IOError => LintSource::Io, Rule::UnsortedImports | Rule::MissingRequiredImport => LintSource::Imports, Rule::ImplicitNamespacePackage | Rule::InvalidModuleName | Rule::StdlibModuleShadowing => LintSource::Filesystem, Rule::IndentationWithInvalidMultiple | Rule::IndentationWithInvalidMultipleComment | Rule::MissingWhitespace | Rule::MissingWhitespaceAfterKeyword | Rule::MissingWhitespaceAroundArithmeticOperator | Rule::MissingWhitespaceAroundBitwiseOrShiftOperator | Rule::MissingWhitespaceAroundModuloOperator | Rule::MissingWhitespaceAroundOperator | Rule::MissingWhitespaceAroundParameterEquals | Rule::MultipleLeadingHashesForBlockComment | Rule::MultipleSpacesAfterComma | Rule::MultipleSpacesAfterKeyword | Rule::MultipleSpacesAfterOperator | Rule::MultipleSpacesBeforeKeyword | Rule::MultipleSpacesBeforeOperator | Rule::NoIndentedBlock | Rule::NoIndentedBlockComment | Rule::NoSpaceAfterBlockComment | Rule::NoSpaceAfterInlineComment | Rule::OverIndented | Rule::RedundantBackslash | Rule::TabAfterComma | Rule::TabAfterKeyword | Rule::TabAfterOperator | Rule::TabBeforeKeyword | Rule::TabBeforeOperator | Rule::TooFewSpacesBeforeInlineComment | Rule::UnexpectedIndentation | Rule::UnexpectedIndentationComment | Rule::UnexpectedSpacesAroundKeywordParameterEquals | Rule::WhitespaceAfterOpenBracket | Rule::WhitespaceBeforeCloseBracket | Rule::WhitespaceBeforeParameters | Rule::WhitespaceBeforePunctuation => LintSource::LogicalLines, _ => LintSource::Ast, } } /// Return the URL for the rule documentation, if it exists. pub fn url(&self) -> Option<String> { self.explanation().is_some().then(|| { format!( "{}/rules/{name}", env!("CARGO_PKG_HOMEPAGE"), name = self.name() ) }) } pub fn name(&self) -> LintName { let name: &'static str = self.into(); LintName::of(name) } } /// Pairs of checks that shouldn't be enabled together. pub const INCOMPATIBLE_CODES: &[(Rule, Rule, &str); 2] = &[ ( Rule::BlankLineBeforeClass, Rule::IncorrectBlankLineBeforeClass, "`incorrect-blank-line-before-class` (D203) and `no-blank-line-before-class` (D211) are \ incompatible. Ignoring `incorrect-blank-line-before-class`.", ), ( Rule::MultiLineSummaryFirstLine, Rule::MultiLineSummarySecondLine, "`multi-line-summary-first-line` (D212) and `multi-line-summary-second-line` (D213) are \ incompatible. Ignoring `multi-line-summary-second-line`.", ), ]; #[cfg(feature = "clap")] pub mod clap_completion { use clap::builder::{PossibleValue, TypedValueParser, ValueParserFactory}; use strum::IntoEnumIterator; use crate::registry::Rule; #[derive(Clone)] pub struct RuleParser; impl ValueParserFactory for Rule { type Parser = RuleParser; fn value_parser() -> Self::Parser { RuleParser } } impl TypedValueParser for RuleParser { type Value = Rule; fn parse_ref( &self, cmd: &clap::Command, arg: Option<&clap::Arg>, value: &std::ffi::OsStr, ) -> Result<Self::Value, clap::Error> { let value = value .to_str() .ok_or_else(|| clap::Error::new(clap::error::ErrorKind::InvalidUtf8))?; Rule::from_code(value).map_err(|_| { let mut error = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd); if let Some(arg) = arg { error.insert( clap::error::ContextKind::InvalidArg, clap::error::ContextValue::String(arg.to_string()), ); } error.insert( clap::error::ContextKind::InvalidValue, clap::error::ContextValue::String(value.to_string()), ); error }) } fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> { Some(Box::new(Rule::iter().map(|rule| { let name = rule.noqa_code().to_string(); let help = rule.name().as_str(); PossibleValue::new(name).help(help) }))) } } } #[cfg(test)] mod tests { use itertools::Itertools; use std::mem::size_of; use strum::IntoEnumIterator; use super::{Linter, Rule, RuleNamespace}; #[test] fn documentation() { for rule in Rule::iter() { assert!( rule.explanation().is_some(), "Rule {} is missing documentation", rule.name() ); } } #[test] fn rule_naming_convention() { // The disallowed rule names are defined in a separate file so that they can also be picked up by add_rule.py. let patterns: Vec<_> = include_str!("../resources/test/disallowed_rule_names.txt") .trim() .split('\n') .map(|line| { glob::Pattern::new(line).expect("malformed pattern in disallowed_rule_names.txt") }) .collect(); for rule in Rule::iter() { let rule_name = rule.name(); for pattern in &patterns { assert!( !pattern.matches(&rule_name), "{rule_name} does not match naming convention, see CONTRIBUTING.md" ); } } } #[test] fn check_code_serialization() { for rule in Rule::iter() { assert!( Rule::from_code(&format!("{}", rule.noqa_code())).is_ok(), "{rule:?} could not be round-trip serialized." ); } } #[test] fn linter_parse_code() { for rule in Rule::iter() { let code = format!("{}", rule.noqa_code()); let (linter, rest) = Linter::parse_code(&code).unwrap_or_else(|| panic!("couldn't parse {code:?}")); assert_eq!(code, format!("{}{rest}", linter.common_prefix())); } } #[test] fn rule_size() { assert_eq!(2, size_of::<Rule>()); } #[test] fn linter_sorting() { let names: Vec<_> = Linter::iter() .map(|linter| linter.name().to_lowercase()) .collect(); let sorted: Vec<_> = names.iter().cloned().sorted().collect(); assert_eq!( &names[..], &sorted[..], "Linters are not sorted alphabetically (case insensitive)" ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/directives.rs
crates/ruff_linter/src/directives.rs
//! Extract `# noqa`, `# isort: skip`, and `# TODO` directives from tokenized source. use std::iter::Peekable; use std::str::FromStr; use bitflags::bitflags; use ruff_python_ast::token::{TokenKind, Tokens}; use ruff_python_index::Indexer; use ruff_python_trivia::CommentRanges; use ruff_source_file::LineRanges; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use crate::Locator; use crate::noqa::NoqaMapping; use crate::settings::LinterSettings; bitflags! { #[derive(Debug, Copy, Clone)] pub struct Flags: u8 { const NOQA = 1 << 0; const ISORT = 1 << 1; } } impl Flags { pub fn from_settings(settings: &LinterSettings) -> Self { if settings .rules .iter_enabled() .any(|rule_code| rule_code.lint_source().is_imports()) { Self::NOQA | Self::ISORT } else { Self::NOQA } } } #[derive(Default, Debug)] pub struct IsortDirectives { /// Ranges for which sorting is disabled pub exclusions: Vec<TextRange>, /// Text positions at which splits should be inserted pub splits: Vec<TextSize>, pub skip_file: bool, } pub struct Directives { pub noqa_line_for: NoqaMapping, pub isort: IsortDirectives, } pub fn extract_directives( tokens: &Tokens, flags: Flags, locator: &Locator, indexer: &Indexer, ) -> Directives { Directives { noqa_line_for: if flags.intersects(Flags::NOQA) { extract_noqa_line_for(tokens, locator, indexer) } else { NoqaMapping::default() }, isort: if flags.intersects(Flags::ISORT) { extract_isort_directives(locator, indexer.comment_ranges()) } else { IsortDirectives::default() }, } } struct SortedMergeIter<L, R, Item> where L: Iterator<Item = Item>, R: Iterator<Item = Item>, { left: Peekable<L>, right: Peekable<R>, } impl<L, R, Item> Iterator for SortedMergeIter<L, R, Item> where L: Iterator<Item = Item>, R: Iterator<Item = Item>, Item: Ranged, { type Item = Item; fn next(&mut self) -> Option<Self::Item> { match (self.left.peek(), self.right.peek()) { (Some(left), Some(right)) => { if left.start() <= right.start() { Some(self.left.next().unwrap()) } else { Some(self.right.next().unwrap()) } } (Some(_), None) => Some(self.left.next().unwrap()), (None, Some(_)) => Some(self.right.next().unwrap()), (None, None) => None, } } } /// Extract a mapping from logical line to noqa line. fn extract_noqa_line_for(tokens: &Tokens, locator: &Locator, indexer: &Indexer) -> NoqaMapping { let mut string_mappings = Vec::new(); for token in tokens { match token.kind() { // For multi-line strings, we expect `noqa` directives on the last line of the string. TokenKind::String if token.is_triple_quoted_string() => { if locator.contains_line_break(token.range()) { string_mappings.push(TextRange::new( locator.line_start(token.start()), token.end(), )); } } _ => {} } } // The capacity allocated here might be more than we need if there are // nested interpolated strings. let mut interpolated_string_mappings = Vec::with_capacity(indexer.interpolated_string_ranges().len()); // For nested interpolated strings, we expect `noqa` directives on the last line of the // outermost interpolated string. The last interpolated string range will be used to skip over // the inner interpolated strings. let mut last_interpolated_string_range: TextRange = TextRange::default(); for interpolated_string_range in indexer.interpolated_string_ranges().values() { if !locator.contains_line_break(*interpolated_string_range) { continue; } if last_interpolated_string_range.contains_range(*interpolated_string_range) { continue; } let new_range = TextRange::new( locator.line_start(interpolated_string_range.start()), interpolated_string_range.end(), ); interpolated_string_mappings.push(new_range); last_interpolated_string_range = new_range; } let mut continuation_mappings = Vec::new(); // For continuations, we expect `noqa` directives on the last line of the // continuation. let mut last: Option<TextRange> = None; for continuation_line in indexer.continuation_line_starts() { let line_end = locator.full_line_end(*continuation_line); if let Some(last_range) = last.take() { if last_range.end() == *continuation_line { last = Some(TextRange::new(last_range.start(), line_end)); continue; } // new continuation continuation_mappings.push(last_range); } last = Some(TextRange::new(*continuation_line, line_end)); } if let Some(last_range) = last.take() { continuation_mappings.push(last_range); } // Merge the mappings in sorted order let mut mappings = NoqaMapping::with_capacity( continuation_mappings.len() + string_mappings.len() + interpolated_string_mappings.len(), ); let string_mappings = SortedMergeIter { left: interpolated_string_mappings.into_iter().peekable(), right: string_mappings.into_iter().peekable(), }; let all_mappings = SortedMergeIter { left: string_mappings.peekable(), right: continuation_mappings.into_iter().peekable(), }; for mapping in all_mappings { mappings.push_mapping(mapping); } mappings } /// Extract a set of ranges over which to disable isort. fn extract_isort_directives(locator: &Locator, comment_ranges: &CommentRanges) -> IsortDirectives { let mut exclusions: Vec<TextRange> = Vec::default(); let mut splits: Vec<TextSize> = Vec::default(); let mut off: Option<TextSize> = None; for range in comment_ranges { let comment_text = locator.slice(range); // `isort` allows for `# isort: skip` and `# isort: skip_file` to include or // omit a space after the colon. The remaining action comments are // required to include the space, and must appear on their own lines. let comment_text = comment_text.trim_end(); if matches!(comment_text, "# isort: split" | "# ruff: isort: split") { splits.push(range.start()); } else if matches!( comment_text, "# isort: skip_file" | "# isort:skip_file" | "# ruff: isort: skip_file" | "# ruff: isort:skip_file" ) { return IsortDirectives { skip_file: true, ..IsortDirectives::default() }; } else if off.is_some() { if comment_text == "# isort: on" || comment_text == "# ruff: isort: on" { if let Some(exclusion_start) = off { exclusions.push(TextRange::new(exclusion_start, range.start())); } off = None; } } else { if comment_text.contains("isort: skip") || comment_text.contains("isort:skip") { exclusions.push(locator.line_range(range.start())); } else if comment_text == "# isort: off" || comment_text == "# ruff: isort: off" { off = Some(range.start()); } } } if let Some(start) = off { // Enforce unterminated `isort: off`. exclusions.push(TextRange::new(start, locator.contents().text_len())); } IsortDirectives { exclusions, splits, ..IsortDirectives::default() } } /// A comment that contains a [`TodoDirective`] pub(crate) struct TodoComment<'a> { /// The comment's text pub(crate) content: &'a str, /// The directive found within the comment. pub(crate) directive: TodoDirective<'a>, /// The comment's actual [`TextRange`]. pub(crate) range: TextRange, /// The comment range's position in [`Indexer::comment_ranges`] pub(crate) range_index: usize, } impl<'a> TodoComment<'a> { /// Attempt to transform a normal comment into a [`TodoComment`]. pub(crate) fn from_comment( content: &'a str, range: TextRange, range_index: usize, ) -> Option<Self> { TodoDirective::from_comment(content, range).map(|directive| Self { content, directive, range, range_index, }) } } #[derive(Debug, PartialEq)] pub(crate) struct TodoDirective<'a> { /// The actual directive pub(crate) content: &'a str, /// The directive's [`TextRange`] in the file. pub(crate) range: TextRange, /// The directive's kind: HACK, XXX, FIXME, or TODO. pub(crate) kind: TodoDirectiveKind, } impl<'a> TodoDirective<'a> { /// Extract a [`TodoDirective`] from a comment. pub(crate) fn from_comment(comment: &'a str, comment_range: TextRange) -> Option<Self> { // The directive's offset from the start of the comment. let mut relative_offset = TextSize::new(0); let mut subset = comment; // Loop over `#`-delimited sections of the comment to check for directives. This will // correctly handle cases like `# foo # TODO`. loop { let trimmed = subset.trim_start_matches('#').trim_start(); let offset = subset.text_len() - trimmed.text_len(); relative_offset += offset; // Find the first word. Don't use split by whitespace because that would include the `:` character // in `TODO:` let first_word = trimmed.split(|c: char| !c.is_alphanumeric()).next()?; // If we detect a TodoDirectiveKind variant substring in the comment, construct and // return the appropriate TodoDirective if let Ok(directive_kind) = first_word.parse::<TodoDirectiveKind>() { let len = directive_kind.len(); return Some(Self { content: &comment[TextRange::at(relative_offset, len)], range: TextRange::at(comment_range.start() + relative_offset, len), kind: directive_kind, }); } // Shrink the subset to check for the next phrase starting with "#". if let Some(new_offset) = trimmed.find('#') { relative_offset += TextSize::try_from(new_offset).unwrap(); subset = &comment[relative_offset.to_usize()..]; } else { break; } } None } } #[derive(Debug, PartialEq)] pub(crate) enum TodoDirectiveKind { Todo, Fixme, Xxx, Hack, } impl FromStr for TodoDirectiveKind { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().as_str() { "fixme" => Ok(TodoDirectiveKind::Fixme), "hack" => Ok(TodoDirectiveKind::Hack), "todo" => Ok(TodoDirectiveKind::Todo), "xxx" => Ok(TodoDirectiveKind::Xxx), _ => Err(()), } } } impl TodoDirectiveKind { fn len(&self) -> TextSize { match self { TodoDirectiveKind::Xxx => TextSize::new(3), TodoDirectiveKind::Hack | TodoDirectiveKind::Todo => TextSize::new(4), TodoDirectiveKind::Fixme => TextSize::new(5), } } } #[cfg(test)] mod tests { use ruff_python_index::Indexer; use ruff_python_parser::parse_module; use ruff_python_trivia::CommentRanges; use ruff_text_size::{TextLen, TextRange, TextSize}; use crate::Locator; use crate::directives::{ TodoDirective, TodoDirectiveKind, extract_isort_directives, extract_noqa_line_for, }; use crate::noqa::NoqaMapping; use super::IsortDirectives; fn noqa_mappings(contents: &str) -> NoqaMapping { let parsed = parse_module(contents).unwrap(); let locator = Locator::new(contents); let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); extract_noqa_line_for(parsed.tokens(), &locator, &indexer) } #[test] fn noqa_extraction() { let contents = "x = 1 y = 2 \ + 1 z = x + 1"; assert_eq!(noqa_mappings(contents), NoqaMapping::default()); let contents = " x = 1 y = 2 z = x + 1"; assert_eq!(noqa_mappings(contents), NoqaMapping::default()); let contents = "x = 1 y = 2 z = x + 1 "; assert_eq!(noqa_mappings(contents), NoqaMapping::default()); let contents = "x = 1 y = 2 z = x + 1 "; assert_eq!(noqa_mappings(contents), NoqaMapping::default()); let contents = "x = '''abc def ghi ''' y = 2 z = x + 1"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(22))]) ); let contents = "x = 1 y = '''abc def ghi ''' z = 2"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(28))]) ); let contents = "x = 1 y = '''abc def ghi '''"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(28))]) ); let contents = "x = f'abc { a * b }' y = 2 "; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(32))]) ); let contents = "x = f'''abc def ghi ''' y = 2 z = x + 1"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(23))]) ); let contents = "x = 1 y = f'''abc def ghi ''' z = 2"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(29))]) ); let contents = "x = 1 y = f'''abc def ghi '''"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(29))]) ); let contents = "x = 1 y = f'''abc def {f'''nested fstring''' f'another nested'} end''' "; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(70))]) ); let contents = "x = 1 y = t'''abc def {f'''nested interpolated string''' f'another nested'} end''' "; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(6), TextSize::from(82))]) ); let contents = "x = 1 y = f'normal' z = f'another but {f'nested but {f'still single line'} nested'}' "; assert_eq!(noqa_mappings(contents), NoqaMapping::default()); let contents = "x = 1 y = t'normal' z = t'another but {t'nested but {t'still single line'} nested'}' "; assert_eq!(noqa_mappings(contents), NoqaMapping::default()); let contents = "x = 1 y = f'normal' z = f'another but {t'nested but {f'still single line'} nested'}' "; assert_eq!(noqa_mappings(contents), NoqaMapping::default()); let contents = r"x = \ 1"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(6))]) ); let contents = r"from foo import \ bar as baz, \ qux as quux"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(36))]) ); let contents = r" # Foo from foo import \ bar as baz, \ qux as quux # Baz x = \ 1 y = \ 2"; assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([ TextRange::new(TextSize::from(7), TextSize::from(43)), TextRange::new(TextSize::from(65), TextSize::from(71)), TextRange::new(TextSize::from(77), TextSize::from(83)), ]) ); // https://github.com/astral-sh/ruff/issues/7530 let contents = r" assert foo, \ '''triple-quoted string''' " .trim(); assert_eq!( noqa_mappings(contents), NoqaMapping::from_iter([TextRange::new(TextSize::from(0), TextSize::from(48))]) ); } fn isort_directives(contents: &str) -> IsortDirectives { let parsed = parse_module(contents).unwrap(); let locator = Locator::new(contents); let comment_ranges = CommentRanges::from(parsed.tokens()); extract_isort_directives(&locator, &comment_ranges) } #[test] fn isort_exclusions() { let contents = "x = 1 y = 2 z = x + 1"; assert_eq!(isort_directives(contents).exclusions, Vec::default()); let contents = "# isort: off x = 1 y = 2 # isort: on z = x + 1"; assert_eq!( isort_directives(contents).exclusions, Vec::from_iter([TextRange::new(TextSize::from(0), TextSize::from(25))]) ); let contents = "# isort: off x = 1 # isort: off y = 2 # isort: on z = x + 1 # isort: on"; assert_eq!( isort_directives(contents).exclusions, Vec::from_iter([TextRange::new(TextSize::from(0), TextSize::from(38))]) ); let contents = "# isort: off x = 1 y = 2 z = x + 1"; assert_eq!( isort_directives(contents).exclusions, Vec::from_iter([TextRange::at(TextSize::from(0), contents.text_len())]) ); let contents = "# isort: skip_file x = 1 y = 2 z = x + 1"; assert_eq!(isort_directives(contents).exclusions, Vec::default()); let contents = "# isort: off x = 1 # isort: on y = 2 # isort: skip_file z = x + 1"; assert_eq!(isort_directives(contents).exclusions, Vec::default()); } #[test] fn isort_splits() { let contents = "x = 1 y = 2 z = x + 1"; assert_eq!(isort_directives(contents).splits, Vec::new()); let contents = "x = 1 y = 2 # isort: split z = x + 1"; assert_eq!(isort_directives(contents).splits, vec![TextSize::from(12)]); let contents = "x = 1 y = 2 # isort: split z = x + 1"; assert_eq!(isort_directives(contents).splits, vec![TextSize::from(13)]); } #[test] fn todo_directives() { let test_comment = "# TODO: todo tag"; let test_comment_range = TextRange::at(TextSize::new(0), test_comment.text_len()); let expected = TodoDirective { content: "TODO", range: TextRange::new(TextSize::new(2), TextSize::new(6)), kind: TodoDirectiveKind::Todo, }; assert_eq!( expected, TodoDirective::from_comment(test_comment, test_comment_range).unwrap() ); let test_comment = "#TODO: todo tag"; let test_comment_range = TextRange::at(TextSize::new(0), test_comment.text_len()); let expected = TodoDirective { content: "TODO", range: TextRange::new(TextSize::new(1), TextSize::new(5)), kind: TodoDirectiveKind::Todo, }; assert_eq!( expected, TodoDirective::from_comment(test_comment, test_comment_range).unwrap() ); let test_comment = "# fixme: fixme tag"; let test_comment_range = TextRange::at(TextSize::new(0), test_comment.text_len()); let expected = TodoDirective { content: "fixme", range: TextRange::new(TextSize::new(2), TextSize::new(7)), kind: TodoDirectiveKind::Fixme, }; assert_eq!( expected, TodoDirective::from_comment(test_comment, test_comment_range).unwrap() ); let test_comment = "# noqa # TODO: todo"; let test_comment_range = TextRange::at(TextSize::new(0), test_comment.text_len()); let expected = TodoDirective { content: "TODO", range: TextRange::new(TextSize::new(9), TextSize::new(13)), kind: TodoDirectiveKind::Todo, }; assert_eq!( expected, TodoDirective::from_comment(test_comment, test_comment_range).unwrap() ); let test_comment = "# no directive"; let test_comment_range = TextRange::at(TextSize::new(0), test_comment.text_len()); assert_eq!( None, TodoDirective::from_comment(test_comment, test_comment_range) ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/source_kind.rs
crates/ruff_linter/src/source_kind.rs
use std::fmt::Formatter; use std::io; use std::io::Write; use std::path::Path; use anyhow::Result; use similar::{ChangeTag, TextDiff}; use thiserror::Error; use ruff_diagnostics::SourceMap; use ruff_notebook::{Cell, Notebook, NotebookError}; use ruff_python_ast::PySourceType; use colored::Colorize; use crate::fs; use crate::text_helpers::ShowNonprinting; #[derive(Clone, Debug, PartialEq)] pub enum SourceKind { /// The source contains Python source code. Python(String), /// The source contains a Jupyter notebook. IpyNotebook(Box<Notebook>), } impl SourceKind { pub fn ipy_notebook(notebook: Notebook) -> Self { SourceKind::IpyNotebook(Box::new(notebook)) } pub fn as_ipy_notebook(&self) -> Option<&Notebook> { match self { SourceKind::IpyNotebook(notebook) => Some(notebook), SourceKind::Python(_) => None, } } pub fn as_python(&self) -> Option<&str> { match self { SourceKind::Python(code) => Some(code), SourceKind::IpyNotebook(_) => None, } } pub fn expect_python(self) -> String { match self { SourceKind::Python(code) => code, SourceKind::IpyNotebook(_) => panic!("expected python code"), } } pub fn expect_ipy_notebook(self) -> Notebook { match self { SourceKind::IpyNotebook(notebook) => *notebook, SourceKind::Python(_) => panic!("expected ipy notebook"), } } #[must_use] pub(crate) fn updated(&self, new_source: String, source_map: &SourceMap) -> Self { match self { SourceKind::IpyNotebook(notebook) => { let mut cloned = notebook.clone(); cloned.update(source_map, new_source); SourceKind::IpyNotebook(cloned) } SourceKind::Python(_) => SourceKind::Python(new_source), } } /// Returns the Python source code for this source kind. pub fn source_code(&self) -> &str { match self { SourceKind::Python(source) => source, SourceKind::IpyNotebook(notebook) => notebook.source_code(), } } /// Read the [`SourceKind`] from the given path. Returns `None` if the source is not a Python /// source file. pub fn from_path(path: &Path, source_type: PySourceType) -> Result<Option<Self>, SourceError> { if source_type.is_ipynb() { let notebook = Notebook::from_path(path)?; Ok(notebook .is_python_notebook() .then_some(Self::IpyNotebook(Box::new(notebook)))) } else { let contents = std::fs::read_to_string(path)?; Ok(Some(Self::Python(contents))) } } /// Read the [`SourceKind`] from the given source code. Returns `None` if the source is not /// Python source code. pub fn from_source_code( source_code: String, source_type: PySourceType, ) -> Result<Option<Self>, SourceError> { if source_type.is_ipynb() { let notebook = Notebook::from_source_code(&source_code)?; Ok(notebook .is_python_notebook() .then_some(Self::IpyNotebook(Box::new(notebook)))) } else { Ok(Some(Self::Python(source_code))) } } /// Write the transformed source file to the given writer. /// /// For Jupyter notebooks, this will write out the notebook as JSON. pub fn write(&self, writer: &mut dyn Write) -> Result<(), SourceError> { match self { SourceKind::Python(source) => { writer.write_all(source.as_bytes())?; Ok(()) } SourceKind::IpyNotebook(notebook) => { notebook.write(writer)?; Ok(()) } } } /// Returns a diff between the original and modified source code. /// /// Returns `None` if `self` and `other` are not of the same kind. pub fn diff<'a>( &'a self, other: &'a Self, path: Option<&'a Path>, ) -> Option<SourceKindDiff<'a>> { match (self, other) { (SourceKind::Python(src), SourceKind::Python(dst)) => Some(SourceKindDiff { kind: DiffKind::Python(src, dst), path, }), (SourceKind::IpyNotebook(src), SourceKind::IpyNotebook(dst)) => Some(SourceKindDiff { kind: DiffKind::IpyNotebook(src, dst), path, }), _ => None, } } } #[derive(Clone, Debug)] pub struct SourceKindDiff<'a> { kind: DiffKind<'a>, path: Option<&'a Path>, } impl std::fmt::Display for SourceKindDiff<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self.kind { DiffKind::Python(original, modified) => { let mut diff = CodeDiff::new(original, modified); let relative_path = self.path.map(fs::relativize_path); if let Some(relative_path) = &relative_path { diff.header(relative_path, relative_path); } writeln!(f, "{diff}")?; } DiffKind::IpyNotebook(original, modified) => { // Cell indices are 1-based. for ((idx, src_cell), dst_cell) in (1u32..).zip(original.cells()).zip(modified.cells()) { let (Cell::Code(src_cell), Cell::Code(dst_cell)) = (src_cell, dst_cell) else { continue; }; let src_source_code = src_cell.source.to_string(); let dst_source_code = dst_cell.source.to_string(); let header = self.path.map_or_else( || (format!("cell {idx}"), format!("cell {idx}")), |path| { ( format!("{}:cell {}", &fs::relativize_path(path), idx), format!("{}:cell {}", &fs::relativize_path(path), idx), ) }, ); let mut diff = CodeDiff::new(&src_source_code, &dst_source_code); diff.header(&header.0, &header.1); // Jupyter notebook cells don't necessarily have a newline // at the end. For example, // // ```python // print("hello") // ``` // // For a cell containing the above code, there'll only be one line, // and it won't have a newline at the end. If it did, there'd be // two lines, and the second line would be empty: // // ```python // print("hello") // // ``` diff.missing_newline_hint(false); write!(f, "{diff}")?; } writeln!(f)?; } } Ok(()) } } #[derive(Debug, Clone, Copy)] enum DiffKind<'a> { Python(&'a str, &'a str), IpyNotebook(&'a Notebook, &'a Notebook), } struct CodeDiff<'a> { diff: TextDiff<'a, 'a, 'a, str>, header: Option<(&'a str, &'a str)>, missing_newline_hint: bool, } impl<'a> CodeDiff<'a> { fn new(original: &'a str, modified: &'a str) -> Self { let diff = TextDiff::from_lines(original, modified); Self { diff, header: None, missing_newline_hint: true, } } fn header(&mut self, original: &'a str, modified: &'a str) { self.header = Some((original, modified)); } fn missing_newline_hint(&mut self, missing_newline_hint: bool) { self.missing_newline_hint = missing_newline_hint; } } impl std::fmt::Display for CodeDiff<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some((original, modified)) = self.header { writeln!(f, "--- {}", original.show_nonprinting().red())?; writeln!(f, "+++ {}", modified.show_nonprinting().green())?; } let mut unified = self.diff.unified_diff(); unified.missing_newline_hint(self.missing_newline_hint); // Individual hunks (section of changes) for hunk in unified.iter_hunks() { writeln!(f, "{}", hunk.header())?; // individual lines for change in hunk.iter_changes() { let value = change.value().show_nonprinting(); match change.tag() { ChangeTag::Equal => write!(f, " {value}")?, ChangeTag::Delete => write!(f, "{}{}", "-".red(), value.red())?, ChangeTag::Insert => write!(f, "{}{}", "+".green(), value.green())?, } if !self.diff.newline_terminated() { writeln!(f)?; } else if change.missing_newline() { if self.missing_newline_hint { writeln!(f, "{}", "\n\\ No newline at end of file".red())?; } else { writeln!(f)?; } } } } Ok(()) } } #[derive(Error, Debug)] pub enum SourceError { #[error(transparent)] Io(#[from] io::Error), #[error(transparent)] Notebook(#[from] NotebookError), }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/pyproject_toml.rs
crates/ruff_linter/src/pyproject_toml.rs
use colored::Colorize; use log::warn; use pyproject_toml::PyProjectToml; use ruff_text_size::{TextRange, TextSize}; use ruff_db::diagnostic::Diagnostic; use ruff_source_file::SourceFile; use crate::registry::Rule; use crate::rules::ruff::rules::InvalidPyprojectToml; use crate::settings::LinterSettings; use crate::{IOError, Violation}; /// RUF200 pub fn lint_pyproject_toml(source_file: &SourceFile, settings: &LinterSettings) -> Vec<Diagnostic> { let Some(err) = toml::from_str::<PyProjectToml>(source_file.source_text()).err() else { return Vec::default(); }; let mut messages = Vec::new(); let range = match err.span() { // This is bad but sometimes toml and/or serde just don't give us spans // TODO(konstin,micha): https://github.com/astral-sh/ruff/issues/4571 None => TextRange::default(), Some(range) => { let Ok(end) = TextSize::try_from(range.end) else { let message = format!( "{} is larger than 4GB, but ruff assumes all files to be smaller", source_file.name(), ); if settings.rules.enabled(Rule::IOError) { let diagnostic = IOError { message }.into_diagnostic(TextRange::default(), source_file); messages.push(diagnostic); } else { warn!( "{}{}{} {message}", "Failed to lint ".bold(), source_file.name().bold(), ":".bold() ); } return messages; }; TextRange::new( // start <= end, so if end < 4GB follows start < 4GB TextSize::try_from(range.start).unwrap(), end, ) } }; if settings.rules.enabled(Rule::InvalidPyprojectToml) { let toml_err = err.message().to_string(); let diagnostic = InvalidPyprojectToml { message: toml_err }.into_diagnostic(range, source_file); messages.push(diagnostic); } messages }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/violation.rs
crates/ruff_linter/src/violation.rs
use std::fmt::{Debug, Display}; use serde::Serialize; use ruff_db::diagnostic::Diagnostic; use ruff_source_file::SourceFile; use ruff_text_size::TextRange; use crate::{ codes::{Rule, RuleGroup}, message::create_lint_diagnostic, }; #[derive(Debug, Copy, Clone, Serialize)] pub enum FixAvailability { Sometimes, Always, None, } impl Display for FixAvailability { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { FixAvailability::Sometimes => write!(f, "Fix is sometimes available."), FixAvailability::Always => write!(f, "Fix is always available."), FixAvailability::None => write!(f, "Fix is not available."), } } } pub trait ViolationMetadata { /// Returns the rule for this violation fn rule() -> Rule; /// Returns an explanation of what this violation catches, /// why it's bad, and what users should do instead. fn explain() -> Option<&'static str>; /// Returns the rule group for this violation. fn group() -> RuleGroup; /// Returns the file where the violation is declared. fn file() -> &'static str; /// Returns the 1-based line where the violation is declared. fn line() -> u32; } pub trait Violation: ViolationMetadata + Sized { /// `None` in the case a fix is never available or otherwise Some /// [`FixAvailability`] describing the available fix. const FIX_AVAILABILITY: FixAvailability = FixAvailability::None; /// The message used to describe the violation. fn message(&self) -> String; // TODO(micha): Move `fix_title` to `Fix`, add new `advice` method that is shown as an advice. // Change the `Diagnostic` renderer to show the advice, and render the fix message after the `Suggested fix: <here>` /// Returns the title for the fix. The message is also shown as an advice as part of the diagnostics. /// /// Required for rules that have fixes. fn fix_title(&self) -> Option<String> { None } /// Returns the format strings used by [`message`](Violation::message). fn message_formats() -> &'static [&'static str]; /// Convert the violation into a [`Diagnostic`]. fn into_diagnostic(self, range: TextRange, file: &SourceFile) -> Diagnostic { create_lint_diagnostic( self.message(), self.fix_title(), range, None, None, file.clone(), None, Self::rule(), ) } } /// This trait exists just to make implementing the [`Violation`] trait more /// convenient for violations that can always be fixed. pub trait AlwaysFixableViolation: ViolationMetadata { /// The message used to describe the violation. fn message(&self) -> String; /// The title displayed for the available fix. fn fix_title(&self) -> String; /// Returns the format strings used by /// [`message`](AlwaysFixableViolation::message). fn message_formats() -> &'static [&'static str]; } /// A blanket implementation. impl<V: AlwaysFixableViolation> Violation for V { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always; fn message(&self) -> String { <Self as AlwaysFixableViolation>::message(self) } fn fix_title(&self) -> Option<String> { Some(<Self as AlwaysFixableViolation>::fix_title(self)) } fn message_formats() -> &'static [&'static str] { <Self as AlwaysFixableViolation>::message_formats() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/logging.rs
crates/ruff_linter/src/logging.rs
use std::fmt::{Display, Formatter}; use std::path::{Path, PathBuf}; use std::sync::{LazyLock, Mutex}; use anyhow::Result; use colored::Colorize; use fern; use log::Level; use ruff_python_parser::ParseError; use rustc_hash::FxHashSet; use ruff_source_file::{LineColumn, LineIndex, OneIndexed, SourceCode}; use crate::fs; use crate::source_kind::SourceKind; use ruff_notebook::Notebook; pub static IDENTIFIERS: LazyLock<Mutex<Vec<&'static str>>> = LazyLock::new(Mutex::default); /// Warn a user once, with uniqueness determined by the given ID. #[macro_export] macro_rules! warn_user_once_by_id { ($id:expr, $($arg:tt)*) => { use colored::Colorize; use log::warn; if let Ok(mut states) = $crate::logging::IDENTIFIERS.lock() { if !states.contains(&$id) { let message = format!("{}", format_args!($($arg)*)); warn!("{}", message.bold()); states.push($id); } } }; } pub static MESSAGES: LazyLock<Mutex<FxHashSet<String>>> = LazyLock::new(Mutex::default); /// Warn a user once, if warnings are enabled, with uniqueness determined by the content of the /// message. #[macro_export] macro_rules! warn_user_once_by_message { ($($arg:tt)*) => { use colored::Colorize; use log::warn; if let Ok(mut states) = $crate::logging::MESSAGES.lock() { let message = format!("{}", format_args!($($arg)*)); if !states.contains(&message) { warn!("{}", message.bold()); states.insert(message); } } }; } /// Warn a user once, with uniqueness determined by the calling location itself. #[macro_export] macro_rules! warn_user_once { ($($arg:tt)*) => { use colored::Colorize; use log::warn; static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !WARNED.swap(true, std::sync::atomic::Ordering::SeqCst) { let message = format!("{}", format_args!($($arg)*)); warn!("{}", message.bold()); } }; } #[macro_export] macro_rules! warn_user { ($($arg:tt)*) => {{ use colored::Colorize; use log::warn; let message = format!("{}", format_args!($($arg)*)); warn!("{}", message.bold()); }}; } #[macro_export] macro_rules! notify_user { ($($arg:tt)*) => { println!( "[{}] {}", jiff::Zoned::now() .strftime("%H:%M:%S %p") .to_string() .dimmed(), format_args!($($arg)*) ) } } #[derive(Debug, Default, PartialOrd, Ord, PartialEq, Eq, Copy, Clone)] pub enum LogLevel { /// No output ([`log::LevelFilter::Off`]). Silent, /// Only show lint violations, with no decorative output /// ([`log::LevelFilter::Off`]). Quiet, /// All user-facing output ([`log::LevelFilter::Info`]). #[default] Default, /// All user-facing output ([`log::LevelFilter::Debug`]). Verbose, } impl LogLevel { #[expect(clippy::trivially_copy_pass_by_ref)] const fn level_filter(&self) -> log::LevelFilter { match self { LogLevel::Default => log::LevelFilter::Info, LogLevel::Verbose => log::LevelFilter::Debug, LogLevel::Quiet => log::LevelFilter::Off, LogLevel::Silent => log::LevelFilter::Off, } } } pub fn set_up_logging(level: LogLevel) -> Result<()> { fern::Dispatch::new() .format(|out, message, record| match record.level() { Level::Error => { out.finish(format_args!( "{}{} {}", "error".red().bold(), ":".bold(), message )); } Level::Warn => { out.finish(format_args!( "{}{} {}", "warning".yellow().bold(), ":".bold(), message )); } Level::Info | Level::Debug | Level::Trace => { out.finish(format_args!( "{}[{}][{}] {}", jiff::Zoned::now().strftime("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )); } }) .level(level.level_filter()) .level_for("globset", log::LevelFilter::Warn) .level_for("ty_python_semantic", log::LevelFilter::Warn) .level_for("salsa", log::LevelFilter::Warn) .chain(std::io::stderr()) .apply()?; Ok(()) } /// A wrapper around [`ParseError`] to translate byte offsets to user-facing /// source code locations (typically, line and column numbers). #[derive(Debug)] pub struct DisplayParseError { error: ParseError, path: Option<PathBuf>, location: ErrorLocation, } impl DisplayParseError { /// Create a [`DisplayParseError`] from a [`ParseError`] and a [`SourceKind`]. pub fn from_source_kind( error: ParseError, path: Option<PathBuf>, source_kind: &SourceKind, ) -> Self { Self::from_source_code( error, path, &SourceCode::new( source_kind.source_code(), &LineIndex::from_source_text(source_kind.source_code()), ), source_kind, ) } /// Create a [`DisplayParseError`] from a [`ParseError`] and a [`SourceCode`]. pub fn from_source_code( error: ParseError, path: Option<PathBuf>, source_code: &SourceCode, source_kind: &SourceKind, ) -> Self { // Translate the byte offset to a location in the originating source. let location = if let Some(jupyter_index) = source_kind.as_ipy_notebook().map(Notebook::index) { let source_location = source_code.line_column(error.location.start()); ErrorLocation::Cell( jupyter_index .cell(source_location.line) .unwrap_or(OneIndexed::MIN), LineColumn { line: jupyter_index .cell_row(source_location.line) .unwrap_or(OneIndexed::MIN), column: source_location.column, }, ) } else { ErrorLocation::File(source_code.line_column(error.location.start())) }; Self { error, path, location, } } /// Return the path of the file in which the error occurred. pub fn path(&self) -> Option<&Path> { self.path.as_deref() } /// Return the underlying [`ParseError`]. pub fn error(&self) -> &ParseError { &self.error } } impl std::error::Error for DisplayParseError {} impl Display for DisplayParseError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { if let Some(path) = self.path.as_ref() { write!( f, "{header} {path}{colon}", header = "Failed to parse".bold(), path = fs::relativize_path(path).bold(), colon = ":".cyan(), )?; } else { write!(f, "{header}", header = "Failed to parse at ".bold())?; } match &self.location { ErrorLocation::File(location) => { write!( f, "{row}{colon}{column}{colon} {inner}", row = location.line, column = location.column, colon = ":".cyan(), inner = self.error.error ) } ErrorLocation::Cell(cell, location) => { write!( f, "{cell}{colon}{row}{colon}{column}{colon} {inner}", cell = cell, row = location.line, column = location.column, colon = ":".cyan(), inner = self.error.error ) } } } } #[derive(Debug)] enum ErrorLocation { /// The error occurred in a Python file. File(LineColumn), /// The error occurred in a Jupyter cell. Cell(OneIndexed, LineColumn), } #[cfg(test)] mod tests { use crate::logging::LogLevel; #[test] fn ordering() { assert!(LogLevel::Default > LogLevel::Silent); assert!(LogLevel::Default >= LogLevel::Default); assert!(LogLevel::Quiet > LogLevel::Silent); assert!(LogLevel::Verbose > LogLevel::Default); assert!(LogLevel::Verbose > LogLevel::Silent); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/package.rs
crates/ruff_linter/src/package.rs
use std::path::Path; /// The root directory of a Python package. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PackageRoot<'a> { /// A normal package root. Root { path: &'a Path }, /// A nested package root. That is, a package root that's a subdirectory (direct or indirect) of /// another Python package root. /// /// For example, `foo/bar/baz` in: /// ```text /// foo/ /// ├── __init__.py /// └── bar/ /// └── baz/ /// └── __init__.py /// ``` Nested { path: &'a Path }, } impl<'a> PackageRoot<'a> { /// Create a [`PackageRoot::Root`] variant. pub fn root(path: &'a Path) -> Self { Self::Root { path } } /// Create a [`PackageRoot::Nested`] variant. pub fn nested(path: &'a Path) -> Self { Self::Nested { path } } /// Return the [`Path`] of the package root. pub fn path(self) -> &'a Path { match self { Self::Root { path } => path, Self::Nested { path } => path, } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/preview.rs
crates/ruff_linter/src/preview.rs
//! Helpers to test if a specific preview style is enabled or not. //! //! The motivation for these functions isn't to avoid code duplication but to ease promoting preview behavior //! to stable. The challenge with directly checking the `preview` attribute of [`LinterSettings`] is that it is unclear //! which specific feature this preview check is for. Having named functions simplifies the promotion: //! Simply delete the function and let Rust tell you which checks you have to remove. use crate::settings::LinterSettings; // Rule-specific behavior // https://github.com/astral-sh/ruff/pull/21382 pub(crate) const fn is_custom_exception_checking_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/15541 pub(crate) const fn is_suspicious_function_reference_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/10759 pub(crate) const fn is_comprehension_with_min_max_sum_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/12657 pub(crate) const fn is_check_comprehensions_in_tuple_call_enabled( settings: &LinterSettings, ) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/issues/15347 pub(crate) const fn is_bad_version_info_in_non_stub_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } /// <https://github.com/astral-sh/ruff/pull/19303> pub(crate) const fn is_fix_f_string_logging_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/16719 pub(crate) const fn is_fix_manual_dict_comprehension_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/13919 pub(crate) const fn is_fix_manual_list_comprehension_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/18763 pub(crate) const fn is_fix_os_path_getsize_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/18922 pub(crate) const fn is_fix_os_path_getmtime_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/18922 pub(crate) const fn is_fix_os_path_getatime_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/18922 pub(crate) const fn is_fix_os_path_getctime_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_abspath_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_rmdir_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_unlink_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_remove_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_exists_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_expanduser_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_isdir_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_isfile_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_islink_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_isabs_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_readlink_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_basename_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19213 pub(crate) const fn is_fix_os_path_dirname_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19404 pub(crate) const fn is_fix_os_chmod_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19404 pub(crate) const fn is_fix_os_rename_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19404 pub(crate) const fn is_fix_os_replace_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19404 pub(crate) const fn is_fix_os_path_samefile_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19245 pub(crate) const fn is_fix_os_getcwd_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19514 pub(crate) const fn is_fix_os_mkdir_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19514 pub(crate) const fn is_fix_os_makedirs_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20009 pub(crate) const fn is_fix_os_symlink_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/11436 // https://github.com/astral-sh/ruff/pull/11168 pub(crate) const fn is_dunder_init_fix_unused_import_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/8473 pub(crate) const fn is_unicode_to_unicode_confusables_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/11370 pub(crate) const fn is_undefined_export_in_dunder_init_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/14236 pub(crate) const fn is_allow_nested_roots_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/18572 pub(crate) const fn is_optional_as_none_in_union_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20659 pub(crate) const fn is_future_required_preview_generics_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/18683 pub(crate) const fn is_safe_super_call_with_parameters_fix_enabled( settings: &LinterSettings, ) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19851 pub(crate) const fn is_maxsplit_without_separator_fix_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20027 pub(crate) const fn is_unnecessary_default_type_args_stubs_enabled( settings: &LinterSettings, ) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20343 pub(crate) const fn is_sim910_expanded_key_support_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20169 pub(crate) const fn is_fix_builtin_open_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20178 pub(crate) const fn is_a003_class_scope_shadowing_expansion_enabled( settings: &LinterSettings, ) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20200 pub(crate) const fn is_refined_submodule_import_match_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/20660 pub(crate) const fn is_type_var_default_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // github.com/astral-sh/ruff/issues/20004 pub(crate) const fn is_b006_check_guaranteed_mutable_expr_enabled( settings: &LinterSettings, ) -> bool { settings.preview.is_enabled() } // github.com/astral-sh/ruff/issues/20004 pub(crate) const fn is_b006_unsafe_fix_preserve_assignment_expr_enabled( settings: &LinterSettings, ) -> bool { settings.preview.is_enabled() } pub(crate) const fn is_typing_extensions_str_alias_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/19045 pub(crate) const fn is_extended_i18n_function_matching_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/21374 pub(crate) const fn is_extended_snmp_api_path_detection_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/21395 pub(crate) const fn is_enumerate_for_loop_int_index_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/21469 pub(crate) const fn is_s310_resolve_string_literal_bindings_enabled( settings: &LinterSettings, ) -> bool { settings.preview.is_enabled() } // https://github.com/astral-sh/ruff/pull/21623 pub(crate) const fn is_range_suppressions_enabled(settings: &LinterSettings) -> bool { settings.preview.is_enabled() }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/docstrings/numpy.rs
crates/ruff_linter/src/docstrings/numpy.rs
//! Abstractions for NumPy-style docstrings. use crate::docstrings::sections::SectionKind; pub(crate) static NUMPY_SECTIONS: &[SectionKind] = &[ SectionKind::Attributes, SectionKind::Examples, SectionKind::Methods, SectionKind::Notes, SectionKind::Raises, SectionKind::References, SectionKind::Returns, SectionKind::SeeAlso, SectionKind::Warnings, SectionKind::Warns, SectionKind::Yields, // NumPy-only SectionKind::ExtendedSummary, SectionKind::OtherParams, SectionKind::OtherParameters, SectionKind::Parameters, SectionKind::Receives, SectionKind::ShortSummary, ];
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false