Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,15 +262,17 @@ Under `includeSymbols`, a binding names a variable rather than describing it: `{
| Field | Type | Description |
|---|---|---|
| `name` | `string` | The variable's name |
| `definedIn` | `string` | Module holding the variable, as in `BindingInfo`. Absent for a file that resolves to no module, such as `my-script.py` |
| `qualifiedName` | `string` | As in `BindingInfo`. Absent with `definedIn` |
| `definedIn` | `string` | Module holding the variable, as in `BindingInfo`. Absent for a file that resolves to no module, such as `my-script.py`, and for an import ty cannot follow |
| `qualifiedName` | `string` | As in `BindingInfo`, with lambda and comprehension scopes spelled too, and a type param's own scope: `m.<locals of lambda>.c`, `m.<locals of list comprehension>.x`, `m.<type params of class 'C'>.T`. Absent with `definedIn` |

An id stands for a variable, not an assignment: two references share an id exactly when they read the same variable, whichever assignment reaches each. `x = 1` and `x = 2` in one scope are one variable. Two functions' locals named `r` are two, even where their `qualifiedName`s coincide, as for a property's getter and setter. Key a variable by its id, not by `qualifiedName`.
An id stands for a variable, not an assignment: two references share an id exactly when they read the same variable, whichever assignment reaches each, except for an import ty cannot follow, described below. `x = 1` and `x = 2` in one scope are one variable. Two functions' locals named `r` are two, even where their `qualifiedName`s coincide, as for a property's getter and setter. Key a variable by its id, not by `qualifiedName`.

Ids hold for the session. Like a type descriptor, a symbol is described only in the first response that mentions it, so a client keeps the table it has received.

Every kind of variable resolves: parameters, loop and `with` and `except` targets, walrus and comprehension variables, and match captures, besides what `BindingInfo` covers. A parameter's declaration node carries the same id as its uses. A `global` or `nonlocal` name, and a closure's read of an enclosing variable, get the id of the scope that owns the variable. An attribute assigned only in a method body (`self.x = ...`) is no variable and has no binding. Where the class body also binds `x`, `self.x`, `obj.x` and `C.x` all name that class variable.

A reference to an imported name gets the symbol of the definition the import names. Where ty cannot follow the import (`from lib import gone` with `lib` declaring no `gone`, or `import nosuchmod`), the import is a symbol of its own, described by `name` alone, since it declares nothing in the scope it stands in. A name that scope also binds some other way is a second symbol, with `definedIn` and `qualifiedName`. In module `m`, `from lib import gone` / `gone()` / `gone = None` / `gone()` gives the first call the import's id, and the assignment target and the second call `m.gone`'s. A reference both reach, as after `try: from lib import gone` / `except ImportError: def gone(): ...`, gets the one `BindingInfo` resolves to, which is the one first in the source.

Over a 71-file project, a symbol binding with its share of the table costs about 63 bytes against 120 for a `BindingInfo`. `includeSymbols` reports 75% more bindings than `includeBindings` and still adds slightly less payload: 19% over no bindings, against 20%.

### CallSignatureInfo
Expand Down
108 changes: 102 additions & 6 deletions src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ use ruff_text_size::Ranged;
use ty_python_core::ProgramFile;
use ty_python_core::definition::{Definition, DefinitionKind};
use ty_python_core::place::ScopedPlaceId;
use ty_python_core::place_table;
use ty_python_core::scope::NodeWithScopeKind;
use ty_python_core::symbol::ScopedSymbolId;
use ty_python_core::{place_table, semantic_index};
use ty_python_semantic::types::call::CallArguments;
use ty_python_semantic::types::call::bind::CheckTypesMode;
use ty_python_semantic::types::constraints::ConstraintSetBuilder;
Expand Down Expand Up @@ -193,6 +194,12 @@ impl<'db> TypeCollector<'db, '_, '_> {
.filter_map(only_definition)
.collect();

if matches!(self.bindings, BindingMode::Symbols(_))
&& let Some(created) = self.definition_created_at(expr, &candidates)
{
return Some(created);
}

// A symbol another module binds under `if sys.platform == ...` reaches here as
// one definition per branch, in source order and unfiltered by reachability.
// The live branch is the one matching the type this file binds the symbol to,
Expand All @@ -214,6 +221,29 @@ impl<'db> TypeCollector<'db, '_, '_> {
}
}

/// The definition an assignment, loop, `with` or walrus target creates, so that
/// the target and the reads it reaches share one symbol. Matching by type would
/// pick an earlier binding of the name whose type the scope also holds, as an
/// unfollowed import's `Unknown` always is.
fn definition_created_at(
&self,
expr: &ast::Expr,
candidates: &[Definition<'db>],
) -> Option<Definition<'db>> {
let db = self.db;
let ast::Expr::Name(name) = expr else {
return None;
};
if !name.ctx.is_store() {
return None;
}
let module = ruff_db::parsed::parsed_module(db, self.model.python_file()).load(db);
candidates.iter().copied().find(|definition| {
definition.program_file(db) == self.model.program_file()
&& definition.kind(db).target_range(&module) == name.range()
})
}

fn named_binding(&self, definition: Definition<'db>) -> Option<BindingInfo> {
let db = self.db;
Some(BindingInfo::Named {
Expand All @@ -234,8 +264,17 @@ impl<'db> TypeCollector<'db, '_, '_> {
let BindingMode::Symbols(symbols) = &mut self.bindings else {
return None;
};
let key = (definition.file(db), definition.file_scope(db), place);
let symbol_id = symbols.intern(key, || describe_symbol(db, env, definition, symbol));
// `resolve_definition` follows every import it can, so one reaching here it could not.
let unfollowed_import = definition.kind(db).is_import();
let key = (
definition.file(db),
definition.file_scope(db),
place,
unfollowed_import,
);
let symbol_id = symbols.intern(key, || {
describe_symbol(db, env, definition, symbol, unfollowed_import)
});
Some(BindingInfo::Symbol { symbol_id })
}

Expand Down Expand Up @@ -651,12 +690,16 @@ fn describe_symbol<'db>(
env: &ProgramEnvironment<'db>,
definition: Definition<'db>,
symbol: ScopedSymbolId,
unfollowed_import: bool,
) -> SymbolInfo {
let scope = definition.scope(db);
let name = place_table(db, scope).symbol(symbol).name().to_string();
let defined_in = module_name_of(db, env, definition.file(db));
let qualified_name = defined_in.is_some().then(|| {
let mut components = qualified_name_components_from_scope(db, scope);
let defined_in = (!unfollowed_import)
.then(|| module_name_of(db, env, definition.file(db)))
.flatten();
let qualified_name = defined_in.as_ref().map(|module| {
let mut components = vec![module.clone()];
components.extend(symbol_scope_components(db, definition));
components.push(name.clone());
components.join(".")
});
Expand All @@ -667,6 +710,59 @@ fn describe_symbol<'db>(
}
}

/// The scopes between the module and the variable `definition` binds, outermost
/// first. Class and function scopes read as ty spells them in `qualifiedName`.
/// A type-params scope reads only for its own type params, since it also encloses
/// the generic class's or function's body, whose names ty spells without it.
fn symbol_scope_components<'db>(db: &'db dyn Db, definition: Definition<'db>) -> Vec<String> {
let module = ruff_db::parsed::parsed_module(db, definition.python_file(db)).load(db);
let index = semantic_index(db, definition.program_file(db));
let own = definition.file_scope(db);
let mut components: Vec<String> = index
.ancestor_scopes(own)
.filter_map(|(id, scope)| match scope.node() {
NodeWithScopeKind::Module | NodeWithScopeKind::TypeAlias(_) => None,
NodeWithScopeKind::Class(class) => Some(class.node(&module).name.to_string()),
NodeWithScopeKind::Function(function) => Some(format!(
"<locals of function '{}'>",
function.node(&module).name
)),
NodeWithScopeKind::Lambda(_) => Some("<locals of lambda>".to_string()),
NodeWithScopeKind::ListComprehension(_) => {
Some("<locals of list comprehension>".to_string())
}
NodeWithScopeKind::SetComprehension(_) => {
Some("<locals of set comprehension>".to_string())
}
NodeWithScopeKind::DictComprehension(_) => {
Some("<locals of dict comprehension>".to_string())
}
NodeWithScopeKind::GeneratorExpression(_) => {
Some("<locals of generator expression>".to_string())
}
_ if id != own => None,
NodeWithScopeKind::ClassTypeParameters(class) => Some(format!(
"<type params of class '{}'>",
class.node(&module).name
)),
NodeWithScopeKind::FunctionTypeParameters(function) => Some(format!(
"<type params of function '{}'>",
function.node(&module).name
)),
NodeWithScopeKind::TypeAliasTypeParameters(alias) => {
let alias = alias.node(&module);
let name = alias
.name
.as_name_expr()
.map_or("", |name| name.id.as_str());
Some(format!("<type params of type alias '{name}'>"))
}
})
.collect();
components.reverse();
components
}

fn expr_kind_name(expr: &ast::Expr) -> &'static str {
match expr {
ast::Expr::BoolOp(_) => "ExprBoolOp",
Expand Down
6 changes: 5 additions & 1 deletion src/symbols.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ use crate::protocol::{SymbolId, SymbolInfo};
/// A variable: the place a scope of a file binds. Every assignment to `x` in one
/// scope shares it, unlike the salsa id of a `Definition`, which is per assignment
/// and may change between revisions.
pub type SymbolKey = (File, FileScopeId, ScopedPlaceId);
///
/// The flag marks an import ty could not follow. It declares nothing where it
/// stands, so references reaching it get a symbol apart from the place's other
/// bindings, one without a defining module.
pub type SymbolKey = (File, FileScopeId, ScopedPlaceId, bool);

/// Gives each variable a session-stable id, and reports each symbol's description
/// only in the first response that mentions it.
Expand Down
90 changes: 90 additions & 0 deletions tests/integration/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3348,6 +3348,96 @@ fn a_file_outside_any_module_still_gets_symbols() {
assert_eq!(symbol_entry(script, x), serde_json::json!({"name": "x"}));
}

#[test]
fn a_symbol_in_a_lambda_comprehension_or_type_params_scope_names_that_scope() {
let results = symbol_results(
&[(
"m.py",
concat!(
"lam = lambda c: [x for x in c]\n",
"s = {e for e in lam([])}\n",
"d = {k: 1 for k in s}\n",
"g = (y for y in d)\n",
"def f[T](a: T) -> T:\n",
" return a\n",
"class C[U]:\n",
" item: U\n",
"type A[V] = list[V]\n",
),
)],
&["m.py"],
);
let m = &results[0];
for (name, expected) in [
("c", "m.<locals of lambda>.c"),
("x", "m.<locals of lambda>.<locals of list comprehension>.x"),
("e", "m.<locals of set comprehension>.e"),
("k", "m.<locals of dict comprehension>.k"),
("y", "m.<locals of generator expression>.y"),
("T", "m.<type params of function 'f'>.T"),
("a", "m.<locals of function 'f'>.a"),
("U", "m.<type params of class 'C'>.U"),
("V", "m.<type params of type alias 'A'>.V"),
] {
let id = one_symbol(m, name);
assert_eq!(symbol_entry(m, id)["qualifiedName"], expected, "{name}");
}
}

#[test]
fn an_import_ty_cannot_follow_names_no_defining_module() {
let results = symbol_results(
&[
("lib.py", "def present():\n return 1\n"),
(
"m.py",
concat!(
"from lib import gone\n",
"import nosuchmod\n",
"gone()\n",
"gone()\n",
"nosuchmod.f()\n",
),
),
],
&["m.py"],
);
let m = &results[0];
for name in ["gone", "nosuchmod"] {
let id = one_symbol(m, name);
assert_eq!(symbol_entry(m, id), serde_json::json!({"name": name}));
}
}

#[test]
fn a_failed_import_and_another_binding_of_the_name_get_separate_symbols() {
let results = symbol_results(
&[
("lib.py", "def present():\n return 1\n"),
(
"m.py",
"from lib import gone\ngone()\ndef f(a=(gone := 1)):\n pass\ngone\n",
),
],
&["m.py"],
);
let m = &results[0];
// The call reaches only the import. The walrus target and the last read are the
// walrus's, which binds at module scope.
let ids = symbol_ids(m, "ExprName", "gone");
let (imported, bound) = (ids[0].unwrap(), ids[1].unwrap());
assert_ne!(imported, bound);
assert_eq!(ids, [Some(imported), Some(bound), Some(bound)]);
assert_eq!(
symbol_entry(m, imported),
serde_json::json!({"name": "gone"})
);
assert_eq!(
symbol_entry(m, bound),
serde_json::json!({"name": "gone", "definedIn": "m", "qualifiedName": "m.gone"}),
);
}

#[test]
fn one_shot_symbols_takes_precedence_over_bindings() {
let dir = create_test_project(&[("m.py", "x = 1\nprint(x)\n")]);
Expand Down