Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[red-knot] Distribute intersections on negation #13962

Merged
merged 5 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/red_knot_python_semantic/src/stdlib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::Db;
enum CoreStdlibModule {
Builtins,
Types,
Typing,
Typeshed,
TypingExtensions,
}
Expand All @@ -19,6 +20,7 @@ impl CoreStdlibModule {
let module_name = match self {
Self::Builtins => "builtins",
Self::Types => "types",
Self::Typing => "typing",
Self::Typeshed => "_typeshed",
Self::TypingExtensions => "typing_extensions",
};
Expand Down Expand Up @@ -63,6 +65,13 @@ pub(crate) fn types_symbol_ty<'db>(db: &'db dyn Db, symbol: &str) -> Type<'db> {
core_module_symbol_ty(db, CoreStdlibModule::Types, symbol)
}

/// Lookup the type of `symbol` in the `typing` module namespace.
///
/// Returns `Unbound` if the `types` module isn't available for some reason.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Returns `Unbound` if the `types` module isn't available for some reason.
/// Returns `Unbound` if the `typing` module isn't available for some reason.

#[inline]
pub(crate) fn typing_symbol_ty<'db>(db: &'db dyn Db, symbol: &str) -> Type<'db> {
core_module_symbol_ty(db, CoreStdlibModule::Typing, symbol)
}
/// Lookup the type of `symbol` in the `_typeshed` module namespace.
///
/// Returns `Unbound` if the `_typeshed` module isn't available for some reason.
Expand Down
17 changes: 16 additions & 1 deletion crates/red_knot_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::semantic_index::{
};
use crate::stdlib::{
builtins_symbol_ty, types_symbol_ty, typeshed_symbol_ty, typing_extensions_symbol_ty,
typing_symbol_ty,
};
use crate::types::narrow::narrowing_constraint;
use crate::{Db, FxOrderSet, HasTy, Module, SemanticModel};
Expand Down Expand Up @@ -740,7 +741,9 @@ impl<'db> Type<'db> {
| KnownClass::Dict
| KnownClass::GenericAlias
| KnownClass::ModuleType
| KnownClass::FunctionType,
| KnownClass::FunctionType
| KnownClass::Sized
| KnownClass::Hashable,
) => false,
None => false,
},
Expand Down Expand Up @@ -1132,6 +1135,9 @@ pub enum KnownClass {
GenericAlias,
ModuleType,
FunctionType,
// Typing
Sized,
Hashable,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry to catch this only after you'd done the work, but I don't see any reason for these to be known classes? We should only use KnownClass when either a) the type has special-cased behavior that is not reflected in its typeshed definition, or b) we will commonly need to conjure this type "from thin air" within the type inference code itself, usually because the type is builtin and sometimes created "from thin air" by the runtime (e.g. bool) or because it is closely related to other special-cased types (e.g. KnownClass::Int and Type::IntLiteral, etc.)

I don't think Sized or Hashable meet either of those criteria.

If you want to use these types (or any other typeshed type) in tests, you don't need it to be a KnownClass; that's just a minor convenience. You can just use typing_symbol_ty (added in this PR, and something we'll definitely want) directly in the test.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hadn't quite internalized that I only actually really need typing_symbol_ty, thanks for pointing that out. Will remove theKnownClass entries

// Typeshed
NoneType, // Part of `types` for Python >= 3.10
}
Expand All @@ -1153,6 +1159,8 @@ impl<'db> KnownClass {
Self::GenericAlias => "GenericAlias",
Self::ModuleType => "ModuleType",
Self::FunctionType => "FunctionType",
Self::Sized => "Sized",
Self::Hashable => "Hashable",
Self::NoneType => "NoneType",
}
}
Expand All @@ -1177,6 +1185,8 @@ impl<'db> KnownClass {
Self::GenericAlias | Self::ModuleType | Self::FunctionType => {
types_symbol_ty(db, self.as_str())
}
Self::Sized | Self::Hashable => typing_symbol_ty(db, self.as_str()),

Self::NoneType => typeshed_symbol_ty(db, self.as_str()),
}
}
Expand Down Expand Up @@ -1210,6 +1220,8 @@ impl<'db> KnownClass {
"NoneType" => Some(Self::NoneType),
"ModuleType" => Some(Self::ModuleType),
"FunctionType" => Some(Self::FunctionType),
"Sized" => Some(Self::Sized),
"Hashable" => Some(Self::Hashable),
_ => None,
}
}
Expand All @@ -1232,6 +1244,9 @@ impl<'db> KnownClass {
| Self::Set
| Self::Dict => module.name() == "builtins",
Self::GenericAlias | Self::ModuleType | Self::FunctionType => module.name() == "types",
Self::Sized | Self::Hashable => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

basically all of the "interesting" protocols in typing are deprecated aliases at this point to members of collections.abc.

matches!(module.name().as_str(), "typing" | "collections.abc")
}
Self::NoneType => matches!(module.name().as_str(), "_typeshed" | "types"),
}
}
Expand Down
60 changes: 60 additions & 0 deletions crates/red_knot_python_semantic/src/types/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,33 @@ impl<'db> IntersectionBuilder<'db> {
self = self.add_negative(*elem);
}
self
} else if let Type::Intersection(intersection) = ty {
// (A | B) & !(C & !D) -> (A | B) & (!C | D)
// -> ((A | B) & !C) | ((A | B) & D)
//
// i.e. if we have an intersection of positive constraints C
// and negative constraints D, then our new intersection
// is (existing & !C) | (existing & D)

let positive_side = intersection
.positive(self.db)
.iter()
// we negate all the positive constraints while distributing
.map(|elem| self.clone().add_negative(*elem));

let negative_side = intersection
.negative(self.db)
.iter()
// all negative constraints end up becoming positive constraints
.map(|elem| self.clone().add_positive(*elem));

positive_side.chain(negative_side).fold(
IntersectionBuilder::empty(self.db),
|mut builder, sub| {
builder.intersections.extend(sub.intersections);
builder
},
)
} else {
for inner in &mut self.intersections {
inner.add_negative(self.db, ty);
Expand Down Expand Up @@ -368,10 +395,17 @@ mod tests {
use crate::program::{Program, SearchPathSettings};
use crate::python_version::PythonVersion;
use crate::types::{KnownClass, StringLiteralType, UnionBuilder};
use crate::Db;
use crate::ProgramSettings;
use ruff_db::system::{DbWithTestSystem, SystemPathBuf};
use test_case::test_case;

impl<'db> IntersectionBuilder<'db> {
fn negation_of(db: &'db dyn Db, ty: Type<'db>) -> Type<'db> {
rtpg marked this conversation as resolved.
Show resolved Hide resolved
IntersectionBuilder::new(db).add_negative(ty).build()
}
}

fn setup_db() -> TestDb {
let db = TestDb::new();

Expand Down Expand Up @@ -591,6 +625,32 @@ mod tests {
assert_eq!(i1.pos_vec(&db), &[ta, t1]);
}

#[test]
fn intersection_negation_distributes_over_union() {
let db = setup_db();
let st = KnownClass::Sized.to_instance(&db);
let ht = KnownClass::Hashable.to_instance(&db);
// sh_t: Sized & Hashable
let sh_t = IntersectionBuilder::new(&db)
.add_positive(st)
.add_positive(ht)
.build()
.expect_intersection();
assert_eq!(sh_t.pos_vec(&db), &[st, ht]);
assert_eq!(sh_t.neg_vec(&db), &[]);

// !sh_t => not Sized or not Hashable
let not_s_h_t = IntersectionBuilder::new(&db)
.add_negative(Type::Intersection(sh_t))
.build()
.expect_union();

// should have (not Sized) or (not Hashable)
let not_st = IntersectionBuilder::negation_of(&db, st);
let not_ht = IntersectionBuilder::negation_of(&db, ht);

assert_eq!(not_s_h_t.elements(&db), &[not_st, not_ht]);
}
#[test]
fn build_intersection_self_negation() {
let db = setup_db();
Expand Down
Loading