## Summary
attrs classes have a feature where the leading underscores for a private
field like `_id` are stripped for the parameter name that corresponds to
this field, i.e. the constructor takes a keyword parameter `id` instead.
The attribute is still accessed through the original name:
Here, we implement this feature in ty:
```py
from attrs import define
@define
class User:
_id: int
name: str
user = User(id=1, name="John Doe") # ty now accepts this (previously emitted two errors)
```
Closes astral-sh/ty#1742
Closes astral-sh/ty#2474
Stacked on #30823.
## Ecosystem
There are no projects in the ecosystem that would profit from this new
feature. I tested on two other projects:
jsonschema:
```diff
--- before
+++ after
@@ -16,3 +15,0 @@
-jsonschema/benchmarks/issue232.py:15:12: error[missing-argument] No arguments provided for required parameters `_path`, `_remotes`
-jsonschema/benchmarks/issue232.py:16:5: error[unknown-argument] Argument `path` does not match any known parameter
-jsonschema/benchmarks/issue232.py:17:5: error[unknown-argument] Argument `remotes` does not match any known parameter
@@ -38,4 +34,0 @@
-jsonschema/tests/_suite.py:73:16: error[missing-argument] No arguments provided for required parameters `_path`, `_remotes`
-jsonschema/tests/_suite.py:75:13: error[unknown-argument] Argument `path` does not match any known parameter
-jsonschema/tests/_suite.py:76:13: error[unknown-argument] Argument `remotes` does not match any known parameter
-jsonschema/tests/_suite.py:152:17: error[unknown-argument] Argument `remotes` does not match any known parameter
@@ -195 +188 @@
-Found 194 diagnostics
+Found 187 diagnostics
```
cattrs:
```diff
--- before
+++ after
@@ -262,2 +261,0 @@
-tests/test_converter.py:412:12: error[missing-argument] No argument provided for required parameter `_a`
-tests/test_converter.py:412:14: error[unknown-argument] Argument `a` does not match any known parameter
@@ -480 +478 @@
-Found 479 diagnostics
+Found 477 diagnostics
```
## Summary
Towards refining our [recent support for the LSP's file rename
refactor](https://github.com/astral-sh/ty/issues/1560), this updates the
`will_rename.rs` helper module to compute import and reference edits for
same-parent renames of (1) regular packages and (2) namespace packages
supplied by one directory. For example, renaming `pkg/old/` to
`pkg/new/` updates references such as `pkg.old.helpers` to
`pkg.new.helpers`.
/xref https://github.com/astral-sh/ty/issues/4945
## Approach
Map each import name that resolves to the renamed directory to its new
package name. The existing import and reference passes use those
mappings for resolved descendants. When a file and a folder in the same
batch would acquire the same import name, skip the conflicting edits.
## Test Plan
See included tests.
## Summary
This PR provides a new method that uses our module resolver to answer
the question of which directories contribute to a single importable
Python package. This is used in [upcoming support of package directory
renames](https://github.com/astral-sh/ty/issues/4945) to validate that
the rename is supported (when a single directory provides the entire
package; renames for split namespace packages are not supported).
## Notes to reviewers
`Module::package_directories` returns the local directories supplying a
resolved package in the requested resolution mode. It follows the
resolver's search order, returning the selected directory for a regular
package or all contributing directories for a namespace package. It
returns `None` for single-file modules, vendored packages, or when the
requested mode selects a different module.
See included tests.
## Summary
This adds an (as of yet unused) IDE operation called
[`will_rename_files`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L140)
that computes edits to update import statements and imported module
references when a Python file is renamed. For example, renaming
`pkg/old.py` to `pkg/new.py` changes `from pkg import old` to `from pkg
import new` and `old.C` to `new.C`.
I have deliberately restricted the scope of renames that we support such
that we do *not* support the following in this delivery:
- Requests that rename a directory
- Requests that change a module parent (e.g., renaming `a.old` to
`b.new` or `new`)
- Requests that rename an `__init__.py` or `__init__.pyi` file
- Requests that change the extension of a module (e.g., from `.py` to
`.pyi`)
Those are all challenging to support, and not uniformly supported by
other language servers, so I think they are reasonable scope cuts. This
initial delivery was also large enough as it is.
All of the edits we compute are best-effort: we do as much as we can
safely but we may decline to rewrite some references or imports that
should in fact be rewritten. That policy is worth debate, but I think
it's the right thing to do in the face of the fact that the [language
server
protocol](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/lsp/3.17/workspace/willRenameFiles.md)
does not guarantee that `workspace/willRenameFiles` can cancel the
underlying file rename request, so there's no reliable way to outright
reject requests that we can't handle. As a result, the user will be
forced into fixing their code no matter what, so we might as well get
them as far along as possible. This approach is also consistent with
other language servers.
## Approach
`will_rename_files` maps file paths to module names, then calls
[`edits_for_file`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L230)
in parallel to plan edits in two AST passes over each candidate file:
1.
[`ImportStatementVisitor`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L300)
plans alias name and module field rewrites and records bound name
changes.
2.
[`ModuleReferenceVisitor`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L855)
uses reaching definitions and module types to find references to renamed
modules, including references in string annotations.
Thanks to @abcvav for the initial implementation of these ideas in
#25095; we adopt their design of building a single mapping from old
module names to new ones for the whole batch, then using that mapping
and the semantic model to plan import and reference edits as we walk
each file’s syntax tree.
## Test Plan
See included tests.
## Summary
Stop scanning a package initializer once ty recognizes a legacy
namespace declaration. The resolver examines only module-level
statements and accepts the existing `pkgutil.extend_path` and
`pkg_resources.declare_namespace` forms.
On the large parser fixture, the declaration check used the following
instruction counts. These cover the top-level scan and pattern matching,
excluding the calls to obtain and load the parsed module.
| Declaration in `__init__.py` | Top-level statements | Visitor (before)
| Iterator (after) | Reduction |
| --- | ---: | ---: | ---: | ---: |
| First statement | 113 | 2,595 | 454 | 2,141 (82.5%) |
| Absent | 112 | 3,189 | 1,290 | 1,899 (59.5%) |
All three paired runs produced the same counts. The full `ty check` used
0.004% fewer instructions with the declaration first.
## Test Plan
The legacy namespace and partial stub package import mdtests passed.
## Summary
This PR adds support for the `<field>_id` attributes that Django
generates for foreign keys. Their types follow the related model's
primary key, or the field specified by `to_field`.
Example:
```py
from django.db import models
class Author(models.Model):
pass
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
def _(book: Book):
reveal_type(book.author) # Author
reveal_type(book.author_id) # int
```
Towards https://github.com/astral-sh/ty/issues/1018.
## Test Plan
New Markdown tests. I checked against Django runtime behavior.
## Summary
This PR adds basic tests for Django support in ty, and adds a first
customization point where we now synthesize `.id` and `.pk` attributes
for primary keys on Django models. Django support currently relies on
`django-types`, a fork of `django-stubs` which requires less
special-casing in type checkers.
Example
```py
from django.db import models
class Book(models.Model):
isbn = models.CharField(max_length=13, primary_key=True)
title = models.CharField()
pages = models.IntegerField(null=True)
def _(book: Book):
reveal_type(book.isbn) # str
reveal_type(book.title) # str
reveal_type(book.pages) # int | None (because null=True)
reveal_type(book.pk) # str (because `isbn` is the primary key)
book.id # error: no automatic `id` with a custom primary key
```
## Test Plan
I wrote new Markdown test and also verified all of our assertions
against Django's runtime behavior.
Partial stub packages could hide runtime submodules when the
corresponding package used `pkgutil.extend_path` or was an implicit
namespace package. Preserve runtime namespace candidates while resolving
descendants so modules missing from partial stubs can fall back to the
implementation.
Track concrete stub packages separately from ordinary packages,
preserving normal namespace shadowing, complete-stub behavior, and
partial subpackages.
Closes https://github.com/astral-sh/ty/issues/4767.
## Summary
Do not suggest "baking in" types like `Unknown` that come from
`ty_extensions`, since (1) this is certainly not what you want, and (2)
it wouldn't work at runtime without `if TYPE_CHECKING` or similar. Do
the same for types from typeshed-internal modules.
Addresses
https://github.com/astral-sh/ruff/pull/29437#discussion_r4298527405
## Test plan
New and changed snapshot tests
## Summary
- Update the Rust toolchain to 1.99.0 and the MSRV to 1.97, following
our N-2 support policy.
- Address the new Clippy warnings and preserve our existing assertion
and formatting macro conventions.
- Update Hawk to 0.1.15 and run it with Rust 1.99.0.
## Summary
This avoids unnecessary submodule enumeration when recursively
enumerating all modules for auto-import completions. It recovers most of
the performance penalty incurred by its
[predecessor](https://github.com/astral-sh/ruff/pull/28202).
## Approach
I updated `ModuleSearchCursor::list_modules` to use the directory
entries it already reads during name discovery to track whether each
name is supplied by a non-symlink directory specifically. It then
records the corresponding resolved modules in
`ModuleListing::modules_with_possible_children`, which
`resolve::list_all_modules` uses to select modules for recursion.
## Test Plan
This is a behaviour-preserving refactor that relies on existing tests.
## Summary
This adds (dormant) support for namespace-aware module enumeration that
reuses ordinary import resolution rules (to help ensure consistency and
correctness). https://github.com/astral-sh/ruff/pull/28202 uses this
capability to support namespace packages in auto-imports, missing-import
fixes, and import statement completions.
## Approach
The first two commits implement new Salsa queries that are necessary for
the new enumeration algorithm:
1. The first commit refactors the `ResolvedModule` enum to collapse the
`LegacyNamespacePackage` and `RegularPackage` variants into a single
`Package` variant. That new variant represents all packages that contain
initializers, deferring classification of that package until resolution
actually needs to make the distinction. Additionally,
`has_legacy_namespace_declaration` now caches the classification. This
makes the later Salsa queries that cache module listings less prone to
invalidation from irrelevant initializer changes.
2. The second commit introduces a `module_search_snapshot` query which
caches the candidates for a module name prefix (e.g., the prefix
"acme.tools" of the names "acme.tools.power" and "acme.tools.manual").
This avoids repeated resolution work for an ancestor (i.e., for
"acme.tools") that would otherwise occur across sibling modules (i.e.,
for "acme.tools.power" and "acme.tools.manual").
3. The last commit introduces `ModuleSearchCursor::list_modules`, which
collects distinct names from eligible directories and resolves each
through the existing resolver. As part of this change, we implement a
symlink policy that is designed to prevent cycles during recursive
enumeration: we allow symlinked search roots, but otherwise do not
discover names from directories whose relative path from a search root
crosses a symlink. This new policy formalizes our method for cycle
prevention; the code that it will replace also prevented cycles, but did
so in a way that does not appear to have been designed intentionally.
## Test Plan
See included tests.
## Summary
Repeated auto-import requests traverse and sort the same module tree. We
now cache the flattened, sorted module list per resolver environment,
and Salsa invalidates it when module listings change. The cache retains
one boxed list per environment.
## Summary
This PR is a first step towards updating the project's uv metadata when
the virtual environment changes. The scope of this PR is to add the
non-uv specific virtual environment file watching. That is, it adds the
necessary file watching handling to update the detected virtual
environment and its Python version when:
* a `pyenv.cfg` changes
* the default `.venv` or the explicitly specified `environment.python`
virtual environment gets created or deleted.
Unfortunately, this does require storing the path to the resolved
virtual environment in `ProgramSettings`. Otherwise, we'd have to
resolve it every time we see a related file watcher event. It's
unfortunate because it doesn't feel like a setting. But there isn't
really any better to carry forward this information.
I recommend reviewing this PR commit by commit.
## Test Plan
Native file-watching regression tests pass.
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This makes it easier to configure extra search paths for module
resolution test cases.
## Test Plan
This is is a refactor that relies on existing test coverage.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This moves `ModuleDebugSnapshot` to a central location where it can more
easily be shared across module resolver tests in the future.
## Test Plan
This is a refactor that relies on existing test coverage.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
In response to feedback on https://github.com/astral-sh/ruff/pull/28201,
this renames the `enter_package` method from `ModuleSearchCursor` to
`advance`. I've factored it out from
https://github.com/astral-sh/ruff/pull/28201 to reduce noise from
trivial changes.
## Test Plan
This is a refactor that relies on existing test coverage.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
Our approach to supporting auto-imports for namespace packages is to
make our module enumeration code namespace-aware. In order to do that
correctly, we need to refactor module resolution such that it is able to
resolve several children of the same package using ordinary import
resolution rules.
## Background
_What follows discusses context relevant to this particular PR. For more
background on namespace packages more generally, please see [this
document](https://gist.github.com/lerebear/399114b087d03c0860bf2cde0509e519)._
Consider enumerating modules for a namespace package named `acme`, which
is spread across two search roots:
```text
/project/src/ /venv/site-packages/
└── acme/ └── acme/
└── reports.py ├── tools.py
└── tools.pyi
```
The modules that are available for the namespace `acme` are
`acme.reports` and `acme.tools`, and the correct outcome of enumeration
of `acme` is to select `/project/src/acme/reports.py` and
`/venv/site-packages/acme/tools.pyi` as the files that provide the
symbols that are to be made available for auto-import for their
respective modules.
We already have a module resolver that implements that algorithm
correctly (and it's a complex algorithm, so we want to reuse it!), but
it is designed for resolution of a single, complete module name (i.e.,
`acme.reports`), rather than enumeration of several modules under a
common prefix (e.g., all modules under `acme`).
For instance, we can ask the current resolver to resolve `acme.reports`,
at which point it will:
1. List each search root looking for the name `acme`, and discover
`/project/src/acme/` and `/venv/site-packages/acme/`.
2. Probe each of those directories for an initializer (to determine
whether it is an ordinary package, or a namespace package). Upon
determining that both directories contribute to the same namespace
package, it will retain both directories for the rest of the search.
3. List each remaining candidate directory looking for the name
`reports`.
If we were to just use that same interface for enumeration, then
resolving `acme.tools` separately would repeat that traversal and
reconstruct the same set of candidate directories in order to look for
the name `tools`.
Instead, we want to establish all of that search state[^1] just once,
and reuse it for both children of `acme`. That way, we achieve our
primary goal of reusing the existing, correct implementation of module
resolution, and we also achieve our secondary goal of reducing
unnecessary work in a performance-sensitive operation.
[^1]: i.e., The directory names and associated listings described in the
numbered list above.
## Approach
This refactors our ordinary module resolution code (`resolve_name`) to
use a `ModuleSearch` abstraction internally. `ModuleSearch` is a cursor
that stores the search state of a module name prefix (e.g., `acme`) for
reuse during enumeration of all module name suffixes (i.e., `reports`
and `tools`). Hence we achieve our goal of reusing our existing module
resolution code for correctness, but making it more efficient for module
enumeration.
`ModuleSearch` works by providing an interface that describes traversal
of the components of the module name:
- `ModuleSearch::enter_package` (e.g.,
`ModuleSearch::enter_package("acme")`) returns search state for
resolving descendants of `acme`.
- `ModuleSearch::resolve_child` (e.g.,
`ModuleSearch::resolve_child("tools")`) selects the module candidates
for `acme.tools` while leaving the `ModuleSearch` object reusable for
another child.
The [next PR in this
stack](https://github.com/astral-sh/ruff/pull/28201) will build on this
foundation to implement namespace-aware module enumeration.
## Test Plan
This is primarily a behaviour-preserving refactor that relies on
existing tests, but it also includes new tests for new functionality
that we will build on in subsequent PRs.
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This makes a few small changes to some names and comments to improve
clarity. It was factored out from
https://github.com/astral-sh/ruff/pull/28199 to improve the
signal-to-noise ratio for that PR (which will receive a proper review).
## Test Plan
This is a refactor that relies on existing tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This is a small step towards the [larger
refactor](https://github.com/astral-sh/ruff/pull/28199) that will allow
us to share ordinary module resolution rules with the module enumeration
process required to [support namespace packages for auto
imports](https://github.com/astral-sh/ty/issues/2273) (please see that
refactor PR for a detailed description of our motivations). It refactors
the `desperately_resolve_name` method (used for ordinary module
resolution) to use methods of `NameResolver` that can be shared with
module enumeration.
## Test Plan
This is a pure refactor that relies on existing tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This is a small step towards the [larger
refactor](https://github.com/astral-sh/ruff/pull/28199) that will allow
us to share ordinary module resolution rules with the module enumeration
process required to [support namespace packages for auto
imports](https://github.com/astral-sh/ty/issues/2273) (please see that
refactor PR for a detailed description of our motivations). It factors
out a helper method (`NameResolver::advance_candidates`) for a small
part of the ordinary module resolution process such that it can more
easily be reused for module enumeration in the future.
## Test Plan
This is a pure refactor that relies on existing tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
https://github.com/astral-sh/ruff/pull/28531 incorrectly went a bit too
far in turning `NameResolver::discover_roots` into a free function. That
isn't actually necessary for the refactor we're aiming for; we just need
to widen its interface to accept new arguments that allows it to apply
to new contexts. This restores the private method but retains the wider
interface.
## Test Plan
This is a behaviour-preserving refactor that relies on existing tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This is a small step towards the [larger
refactor](https://github.com/astral-sh/ruff/pull/28199) that will allow
us to share ordinary module resolution rules with the module enumeration
process required to [support namespace packages for auto
imports](https://github.com/astral-sh/ty/issues/2273) (please see that
refactor PR for a detailed description of our motivations). It refactors
the previously associated `NameResolver::discover_roots` method into a
free function, such that it can more easily be reused for both ordinary
module resolution and module enumeration.
## Test Plan
This is a pure refactor that relies on existing tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
This retains directory listings between successive steps of module
resolution, using the `ModuleDirectory` abstraction introduced in
[#28418](https://github.com/astral-sh/ruff/pull/28418).
For example, when resolving `acme.tools`:
```text
acme/
├── __init__.py
└── tools.py
```
Resolving `acme` retrieves its directory listing to find `__init__.py`.
Resolving the next component, `tools`, needs that same listing.
Previously, each resolution candidate retained only the directory’s
path, so the next step reconstructed a `ModuleDirectory` and retrieved
the listing again.
Candidates now retain the `ModuleDirectory` itself, preserving both its
path and its listing, so the resolution for `acme` and `acme.tools` can
both reuse the directory listing for `acme/`. Note that directory
listings are already cached with Salsa, but this avoids repeated cache
retrieval and the path construction needed to perform that retrieval.
Resolution rules remain unchanged.
Downstream, retaining these listings will also allow namespace-package
enumeration to discover child names and resolve them using the same
directory information, as part of [namespace-package auto-import
support](https://github.com/astral-sh/ty/issues/2273).
## Test Plan
This is a behaviour-preserving refactor that relies on existing tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This refactors our module resolution code in order to introduce a
`ModuleDirectory` abstraction. The purpose of that new abstraction is to
make it easier to reuse a single directory listing to resolve _multiple_
modules, as is required for the symbol enumeration that will power
[namespace package import
completions](https://github.com/astral-sh/ty/issues/2273). For more
background on this problem, please see [this
document](https://gist.github.com/lerebear/399114b087d03c0860bf2cde0509e519).
Downstream, this new abstraction allows for the following improvements
that continue building towards symbol enumeration that supports
namespace packages:
1. A [quick performance
optimization](https://github.com/astral-sh/ruff/pull/28419) that
immediately benefits ordinary module resolution, and hence will also
benefit symbol enumeration once it shares ordinary module resolution
code.
2. The [ability to retain directory listings across resolution
steps](https://github.com/astral-sh/ruff/pull/28278), so that we
maintain efficiency while considering all of the directories that might
contribute to a namespace package.
## Motivation
Consider trying to provide the import completion `from acme.reports
import Report` for `x = Re<CURSOR>` given the following namespace
package layout:
```text
/project/src/acme
└── reports.py # defines `Report`
```
```text
/venv/site-packages/acme/
├── tools.py # defines `Tool` and `ImplementationDetail`
└── tools.pyi # exposes only `Tool` to type checkers
```
In order to discover the `Report` symbol, we must enumerate _all_
symbols exposed by the `acme`. That requires us to must first enumerate
all of `acme`'s module names (i.e. `acme.reports` and `acme.tools`), and
then to resolve each of those names to determine which file actually
exposes the relevant symbols (for `acme.tools` there are two choices,
but the correct one for the purposes of import suggestions is
`tools.pyi`).
Enumerating `acme`'s module names requires us to retrieve directory
listings for `/project/src/acme` and `/venv/site-packages/acme/`.
Subsequently, resolving the name `acme.tools` requires consulting _those
same directory listings_ in order to answer the following questions that
determine the outcome of the module resolution process:
1. Does `/project/src/acme` contain an entry named `tools`? (No.)
2. Does `/venv/site-packages/acme/` contain an ordinary package named
`tools`? (No.)
3. Does `/venv/site-packages/acme/` contain only a runtime module
(`tools.py`) or does it also contain a stub (`tools.pyi`)? (Both.)
So it would be useful to be able to reuse the directory listings from
the enumeration process for the module resolution process.
As a first step towards that vision, this introduces a `ModuleDirectory`
struct, which encapsulates the (1) path to a directory that participates
in module resolution, (2) its directory listing as retrieved from the
filesystem, (3) the existing validations for resolving an exact filename
within that directory.
## Approach
I defined a new [`ModuleDirectory`
struct](https://github.com/astral-sh/ruff/blob/304661fb5d0a6539585b9dd75df74231a6dc9bc8/crates/ty_module_resolver/src/path.rs#L331-L338),
and replaced previous calls to
[`ModulePath::to_file`](https://github.com/astral-sh/ruff/blob/77f653825800ddaf3bc221ae6db49a500e1002d5/crates/ty_module_resolver/src/path.rs#L229-L230)
with calls to
[`ModuleDirectory::resolve_file`](https://github.com/astral-sh/ruff/blob/304661fb5d0a6539585b9dd75df74231a6dc9bc8/crates/ty_module_resolver/src/path.rs#L382-L384).
That new method implements the same checks that were previously spread
across several methods (please see inline comments).
`ModuleDirectory` also provides a few more convenience methods that
should be self-explanatory.
## Test Plan
See included tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
As previewed in
https://github.com/astral-sh/ruff/pull/27834#discussion_r3833665878,
this introduces a semantic model of the tests that pytest recognizes in
a particular file or for a particular candidate function. This model
will ultimately be shared by several features (e.g.,
https://github.com/astral-sh/ty/issues/4119 and
https://github.com/astral-sh/ty/issues/4041), and it is [immediately
integrated into our semantic model for pytest
fixtures](https://github.com/astral-sh/ruff/pull/27974) (which powers
"Go to definition" and "Find references" in the language server).
## Test Plan
See included tests.
<!-- How was it tested? -->
This PR replaces #25027. It adds an opt-in check for imports of
installed distributions that the current project does not declare
directly in `pyproject.toml`.
## Overview
The check uses ty's existing uv workspace integration (`TY_UV=1`) to
call `uv workspace metadata --frozen --active`. uv now provides module
ownership without synchronizing the environment, so ty can read the
metadata without installing packages or updating `uv.lock`.
The metadata provides:
1. Each workspace project's runtime and optional dependencies.
2. Dependencies declared in dependency groups.
3. Importable modules and their owning distributions, including source
paths for editable installs.
During import inference, ty maps each resolved import to its
distribution and compares it against the importing project's direct
declarations. If the declaration is missing, ty emits
`missing-direct-dependency`, naming the distribution to add. Each
distribution is reported once per file, at its first unsuppressed
import.
The rule is disabled by default and requires an existing, synchronized
environment. Unavailable or incompatible dependency metadata disables
the check; rejected dependency metadata produces a debug message.
## Nuances
- Editable installs may lack entries in uv's module-owner map. ty uses
their source paths to attribute resolved imports.
- Files identified as package code require runtime or optional
dependencies. Non-package files, such as tests and scripts, can also use
dependency groups, but those groups' transitive dependencies still need
direct declarations.
- For `from package import child`, a resolved child module is checked
against its own distribution rather than the parent's. Imports with
unknown or ambiguous ownership are skipped.
- Ownership metadata is used only when the explicitly selected Python
environment matches uv's environment.
- The current integration covers directory checks. Explicit file
arguments, `--config-file`, and standalone PEP 723 scripts do not use
the workspace's dependency declarations.
The schema and rule documentation are regenerated. Most of the
rule-documentation diff consists of updated source-line links.
## Summary
We now run Hawk 0.1.13 with Rust 1.98.0 in CI, following the pattern
used by uv. The configuration preserves intentional public APIs and
generated interfaces while checking all configured production binaries
and workspace non-production targets with `-D warnings`.
The accompanying cleanup narrows internal visibility, removes unused
benchmark classification state and accessors, and records intentional
public interfaces as audited Hawk expectations. The resulting
configuration reports zero Hawk findings across the configured targets.
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This extends the pytest fixture model from
https://github.com/astral-sh/ruff/pull/27540 to resolve fixtures
supplied by pytest's [built-in
plugins](https://docs.pytest.org/en/stable/reference/fixtures.html).
Pytest makes these fixtures available without an import or a local
`conftest.py`, so ty currently cannot connect requests such as
`tmp_path` or `monkeypatch` to their declarations.
ty now reads the statically known `default_plugins` registration from
the installed `_pytest.config`, resolves those plugins from the same
pytest installation, and searches them in pytest's precedence order
after project providers. This preserves local fixture shadowing and also
models the dynamic `LegacyTmpdirPlugin` registration that supplies the
legacy `tmpdir` fixtures. Registries that cannot be determined
statically remain unresolved.
This implementation intentionally supports pytest 8.x and newer; earlier
pytest versions are outside the supported scope.
## Test Plan
See included tests.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
Building on https://github.com/astral-sh/ruff/pull/27443, this extends
the model for recognizing the pytest fixture bound to a test parameter
to support imported fixtures (as opposed to only fixtures defined in
that same module). Specifically, we now attempt to traverse recursively
through the local name bound by an import to find an underlying pytest
fixture.
The entire semantic model in `pytest.rs` remains unused until
https://github.com/astral-sh/ruff/pull/27444.
## Approach
The implementation proceeds in three stages:
1. (4fcaf2af93) Introduces a new interface
for resolving the bindings that supply a module global in a way that
respects control flow and shadowing. This is general infrastructure,
hence its centralization (it will be used again in
[#26677](https://github.com/astral-sh/ruff/pull/26677) towards
[astral-sh/ty#1560](https://github.com/astral-sh/ty/issues/1560) and
[astral-sh/ty#3410](https://github.com/astral-sh/ty/issues/3410)), but
it is immediately necessary here for correct import resolution.
2. (3056c8c6e9f5cbb60d5261aa75ae1538dc1ebb44) Implements a small
refactor to make a loop clearer.
3. (a1f9f6b1c24a81fae821d5557e63b644c5186c0c) Implements the actual
fixture import resolution logic.
## Test Plan
See included tests.
<!-- How was it tested? -->