Skip to content

Commit

Permalink
Short-circuit typing matches based on imports
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Feb 2, 2024
1 parent ee5b07d commit fdf8598
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions crates/ruff_python_semantic/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,13 @@ impl<'a> SemanticModel<'a> {

/// Return `true` if the `Expr` is a reference to `typing.${target}`.
pub fn match_typing_expr(&self, expr: &Expr, target: &str) -> bool {
// If we haven't seen any typing imports, short-circuit.
if !self.seen_module(Modules::TYPING | Modules::TYPESHED | Modules::TYPING_EXTENSIONS) {
if self.typing_modules.is_empty() {
return false;
}
}

self.resolve_call_path(expr)
.is_some_and(|call_path| self.match_typing_call_path(&call_path, target))
}
Expand Down Expand Up @@ -1088,22 +1095,23 @@ impl<'a> SemanticModel<'a> {
/// the need to resolve symbols from these modules if they haven't been seen.
pub fn add_module(&mut self, module: &str) {
match module {
"trio" => self.seen.insert(Modules::TRIO),
"_typeshed" => self.seen.insert(Modules::TYPESHED),
"collections" => self.seen.insert(Modules::COLLECTIONS),
"datetime" => self.seen.insert(Modules::DATETIME),
"django" => self.seen.insert(Modules::DJANGO),
"logging" => self.seen.insert(Modules::LOGGING),
"mock" => self.seen.insert(Modules::MOCK),
"numpy" => self.seen.insert(Modules::NUMPY),
"os" => self.seen.insert(Modules::OS),
"pandas" => self.seen.insert(Modules::PANDAS),
"pytest" => self.seen.insert(Modules::PYTEST),
"django" => self.seen.insert(Modules::DJANGO),
"re" => self.seen.insert(Modules::RE),
"six" => self.seen.insert(Modules::SIX),
"logging" => self.seen.insert(Modules::LOGGING),
"subprocess" => self.seen.insert(Modules::SUBPROCESS),
"tarfile" => self.seen.insert(Modules::TARFILE),
"trio" => self.seen.insert(Modules::TRIO),
"typing" => self.seen.insert(Modules::TYPING),
"typing_extensions" => self.seen.insert(Modules::TYPING_EXTENSIONS),
"tarfile" => self.seen.insert(Modules::TARFILE),
"re" => self.seen.insert(Modules::RE),
"collections" => self.seen.insert(Modules::COLLECTIONS),
"mock" => self.seen.insert(Modules::MOCK),
"os" => self.seen.insert(Modules::OS),
"datetime" => self.seen.insert(Modules::DATETIME),
"subprocess" => self.seen.insert(Modules::SUBPROCESS),
_ => {}
}
}
Expand Down Expand Up @@ -1563,7 +1571,7 @@ impl ShadowedBinding {
bitflags! {
/// A select list of Python modules that the semantic model can explicitly track.
#[derive(Debug)]
pub struct Modules: u16 {
pub struct Modules: u32 {
const COLLECTIONS = 1 << 0;
const DATETIME = 1 << 1;
const DJANGO = 1 << 2;
Expand All @@ -1580,6 +1588,7 @@ bitflags! {
const TRIO = 1 << 13;
const TYPING = 1 << 14;
const TYPING_EXTENSIONS = 1 << 15;
const TYPESHED = 1 << 16;
}
}

Expand Down

0 comments on commit fdf8598

Please sign in to comment.