Commit Graph

13197 Commits

Author SHA1 Message Date
Brent Westbrook 97850661fd
add too-eagerly parenthesized case from ecosystem
the initial code here is only 83 characters wide, so the call expression should
fit without wrapping the whole body in parens
2025-12-02 15:34:32 -05:00
Brent Westbrook 2e9500209f
avoid nesting groups 2025-12-02 15:30:12 -05:00
Brent Westbrook 972129c0ef
create id only in indented case, update group name 2025-12-02 15:24:31 -05:00
Brent Westbrook 18a3d59352
use write!
Co-authored-by: Micha Reiser <micha@reiser.io>
2025-12-02 15:20:57 -05:00
Alex Waygood 392a8e4e50
[ty] Improve diagnostics for unsupported comparison operations (#21737) 2025-12-02 19:58:45 +00:00
Micha Reiser 515de2d062
Move `Token`, `TokenKind` and `Tokens` to `ruff-python-ast` (#21760) 2025-12-02 20:10:46 +01:00
Douglas Creager 508c0a0861
[ty] Don't confuse multiple occurrences of `typing.Self` when binding bound methods (#21754)
In the following example, there are two occurrences of `typing.Self`,
one for `Foo.foo` and one for `Bar.bar`:

```py
from typing import Self, reveal_type

class Foo[T]:
    def foo(self: Self) -> T:
        raise NotImplementedError

class Bar:
    def bar(self: Self, x: Foo[Self]):
        # SHOULD BE: bound method Foo[Self@bar].foo() -> Self@bar
        # revealed: bound method Foo[Self@bar].foo() -> Foo[Self@bar]
        reveal_type(x.foo)

def f[U: Bar](x: Foo[U]):
    # revealed: bound method Foo[U@f].foo() -> U@f
    reveal_type(x.foo)
```

When accessing a bound method, we replace any occurrences of `Self` with
the bound `self` type.

We were doing this correctly for the second reveal. We would first apply
the specialization, getting `(self: Self@foo) -> U@F` as the signature
of `x.foo`. We would then bind the `self` parameter, substituting
`Self@foo` with `Foo[U@F]` as part of that. The return type was already
specialized to `U@F`, so that substitution had no further affect on the
type that we revealed.

In the first reveal, we would follow the same process, but we confused
the two occurrences of `Self`. We would first apply the specialization,
getting `(self: Self@foo) -> Self@bar` as the method signature. We would
then try to bind the `self` parameter, substituting `Self@foo` with
`Foo[Self@bar]`. However, because we didn't distinguish the two separate
`Self`s, and applied the substitution to the return type as well as to
the `self` parameter.

The fix is to track which particular `Self` we're trying to substitute
when applying the type mapping.

Fixes https://github.com/astral-sh/ty/issues/1713
2025-12-02 13:15:09 -05:00
William Woodruff 0d2792517d
Use our org-wide Renovate preset (#21759) 2025-12-02 13:05:26 -05:00
Brent Westbrook 89dc1ada39
add a couple more test cases
I tried to get Claude to come up with tests, but most of them weren't very
interesting. I think these two additional types of assignments might be worth
having, though.
2025-12-02 11:47:41 -05:00
Brent Westbrook e9f9507dc8
add some assignment tests with parentheses and comments 2025-12-02 11:47:04 -05:00
Brent Westbrook 0a41abed52
avoid lambda special-casing in maybe_parenthesize_expression 2025-12-02 11:28:27 -05:00
Brent Westbrook 24e15bfd95
exclude call and subscript expressions from has_own_parentheses 2025-12-02 11:28:19 -05:00
Brent Westbrook 9db5d43e18
possibly bad test for triple-quoted f-strings
parenthesizing these seems redundant. I would prefer our old formatting more
like this:

```py
def ddb():
    sql = (
        lambda var, table, n=N: f"""
        CREATE TABLE {table} AS
        SELECT ROW_NUMBER() OVER () AS id, {var}
        FROM (
            SELECT {var}
            FROM RANGE({n}) _ ({var})
            ORDER BY RANDOM()
        )
        """
    )
```

where the `f"""` serves as the parentheses, instead of the current:

```py
def ddb():
    sql = lambda var, table, n=N: (
        f"""
        CREATE TABLE {table} AS
        SELECT ROW_NUMBER() OVER () AS id, {var}
        FROM (
            SELECT {var}
            FROM RANGE({n}) _ ({var})
            ORDER BY RANDOM()
        )
        """
    )
```
2025-12-02 11:22:55 -05:00
Brent Westbrook ad3147703d
another bad test for long bodies with their own parens
this case ends up too long at 108 columns:

```py
class C:
    def foo():
        if True:
            transaction_count = self._query_txs_for_range(
                get_count_fn=lambda from_ts, to_ts, _chain_id=chain_id: db_evmtx.count_transactions_in_range(
                    chain_id=_chain_id,
                    from_ts=from_ts,
                    to_ts=to_ts,
                ),
            )
```

instead, it should be formatted like this, fitting within 88 columns:

```py
class C:
    def foo():
        if True:
            transaction_count = self._query_txs_for_range(
                get_count_fn=lambda from_ts, to_ts, _chain_id=chain_id: (
				    db_evmtx.count_transactions_in_range(
                        chain_id=_chain_id,
                        from_ts=from_ts,
                        to_ts=to_ts,
					)
                ),
            )
```

we can fix this by removing the `has_own_parentheses` check in the new lambda
formatting, but this breaks other cases. we might want to preserve this? in this
specific ecosystem case, the project has a `noqa: E501` comment, so this seems
to be what they want anyway, although we don't know that when formatting
2025-12-02 11:22:55 -05:00
Brent Westbrook f634bb5247
propagate lambda layout for annotated assignments 2025-12-02 11:22:55 -05:00
Brent Westbrook 6b47664019
add another bad test case from the ecosystem report
I would expect this to format as:

```py
class C:
    _is_recognized_dtype: Callable[[DtypeObj], bool] = lambda x: (
        lib.is_np_dtype(x, "M") or isinstance(x, DatetimeTZDtype)
    )
```

instead of the current:

```py
class C:
    _is_recognized_dtype: Callable[[DtypeObj], bool] = (
        lambda x: lib.is_np_dtype(x, "M") or isinstance(x, DatetimeTZDtype)
    )
```
2025-12-02 11:22:55 -05:00
Brent Westbrook 07bcf41a34
fix binary expression in lambda in return 2025-12-02 11:22:55 -05:00
Brent Westbrook d68a03a519
add another bad case from the ecosystem check
this should format like:

```py
def foo():
    if True:
        if True:
            return lambda x: (
                np.exp(cs(np.log(x.to(u.MeV).value))) * u.MeV * u.cm**2 / u.g
            )
```

instead of the current snapshot:

```diff
 def foo():
     if True:
         if True:
-            return (
-                lambda x: np.exp(cs(np.log(x.to(u.MeV).value))) * u.MeV * u.cm**2 / u.g
-            )
+            return lambda x: np.exp(
+                cs(np.log(x.to(u.MeV).value))
+            ) * u.MeV * u.cm**2 / u.g
```
2025-12-02 11:22:55 -05:00
Brent Westbrook 62c968c826
rough draft of ExprLambdaLayout::Assignment 2025-12-02 11:22:55 -05:00
Brent Westbrook a5e13cf140
add an unstable test case from ecosystem report
```diff
-name = re.sub(r"[^\x21\x23-\x5b\x5d-\x7e]...............", lambda m: (
-        f"\\{m.group(0)}"
-    ), p["name"])
+name = re.sub(
+    r"[^\x21\x23-\x5b\x5d-\x7e]...............",
+    lambda m: (f"\\{m.group(0)}"),
+    p["name"],
+)
```

the second format is actually fine, but the first one obviously looks horrible,
even if it were stable
2025-12-02 11:22:55 -05:00
Brent Westbrook 74093bdb50
add a poorly formatted case from the ecosystem report
this formats as:

```py
class C:
    function_dict: Dict[Text, Callable[[CRFToken], Any]] = {
        CRFEntityExtractorOptions.POS2: lambda crf_token: crf_token.pos_tag[
            :2
        ] if crf_token.pos_tag is not None else None,
    }
```

when I think it should look like:

```py
class C:
    function_dict: Dict[Text, Callable[[CRFToken], Any]] = {
        CRFEntityExtractorOptions.POS2: lambda crf_token: (
		    crf_token.pos_tag[:2] if crf_token.pos_tag is not None else None,
		)
    }
```
2025-12-02 11:22:55 -05:00
Brent Westbrook 1b58643040
wip: parenthesize long lambda bodies 2025-12-02 11:22:55 -05:00
Brent Westbrook 8cc884428d
keep lambda parameters on a single line 2025-12-02 11:22:55 -05:00
Brent Westbrook 1e70c991a2
baseline test cases 2025-12-02 11:22:55 -05:00
Alex Waygood 05d053376b
Delete `my-script.py` (#21751) 2025-12-02 14:48:01 +00:00
Alex Waygood ac2552b11b
[ty] Move `all_members`, and related types/routines, out of `ide_support.rs` (#21695) 2025-12-02 14:45:24 +00:00
Micha Reiser 644096ea8a
[ty] Fix find-references for import aliases (#21736) 2025-12-02 14:37:50 +01:00
Aria Desires 015ab9e576
[ty] add tests for workspaces (#21741)
Here are a bunch of (variously failing and passing) mdtests that reflect
the kinds of issues people encounter when running ty over an entire
workspace without sufficient hand-holding (especially because in the IDE
it is unclear *how* to provide that hand-holding).
2025-12-02 06:43:41 -05:00
Douglas Creager cf4196466c
[ty] Stop testing the (brittle) constraint set display implementation (#21743)
The `Display` implementation for constraint sets is brittle, and
deserves a rethink. But later! It's perfectly fine for printf debugging;
we just shouldn't be writing mdtests that depend on any particular
rendering details. Most of these tests can be replaced with an
equivalence check that actually validates that the _behavior_ of two
constraint sets are identical.
2025-12-02 09:17:29 +01:00
Micha Reiser 2182c750db
[ty] Use generator over list comprehension to avoid cast (#21748) 2025-12-02 08:47:47 +01:00
Charlie Marsh 72304b01eb
[ty] Add a diagnostic for prohibited `NamedTuple` attribute overrides (#21717)
## Summary

Closes https://github.com/astral-sh/ty/issues/1684.
2025-12-01 21:46:58 -05:00
Ibraheem Ahmed ec854c7199
[ty] Fix subtyping with `type[T]` and unions (#21740)
## Summary

Resolves
https://github.com/astral-sh/ruff/pull/21685#issuecomment-3591695954.
2025-12-01 18:20:13 -05:00
William Woodruff edc6ed5077
Use `npm ci --ignore-scripts` everywhere (#21742) 2025-12-01 17:13:52 -05:00
Dan Parizher f052bd644c
[`flake8-simplify`] Fix truthiness assumption for non-iterable arguments in tuple/list/set calls (`SIM222`, `SIM223`) (#21479)
## Summary

Fixes false positives in SIM222 and SIM223 where truthiness was
incorrectly assumed for `tuple(x)`, `list(x)`, `set(x)` when `x` is not
iterable.

Fixes #21473.

## Problem

`Truthiness::from_expr` recursively called itself on arguments to
iterable initializers (`tuple`, `list`, `set`) without checking if the
argument is iterable, causing false positives for cases like `tuple(0)
or True` and `tuple("") or True`.

## Approach

Added `is_definitely_not_iterable` helper and updated
`Truthiness::from_expr` to return `Unknown` for non-iterable arguments
(numbers, booleans, None) and string literals when called with iterable
initializers, preventing incorrect truthiness assumptions.

## Test Plan

Added test cases to `SIM222.py` and `SIM223.py` for `tuple("")`,
`tuple(0)`, `tuple(1)`, `tuple(False)`, and `tuple(None)` with `or True`
and `and False` patterns.

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2025-12-01 16:57:51 -05:00
Dan Parizher bc44dc2afb
[`flake8-use-pathlib`] Mark fixes unsafe for return type changes (`PTH104`, `PTH105`, `PTH109`, `PTH115`) (#21440)
## Summary

Marks fixes as unsafe when they change return types (`None` → `Path`,
`str`/`bytes` → `Path`, `str` → `Path`), except when the call is a
top-level expression.

Fixes #21431.

## Problem

Fixes for `os.rename`, `os.replace`, `os.getcwd`/`os.getcwdb`, and
`os.readlink` were marked safe despite changing return types, which can
break code that uses the return value.

## Approach

Added `is_top_level_expression_call` helper to detect when a call is a
top-level expression (return value unused). Updated
`check_os_pathlib_two_arg_calls` and `check_os_pathlib_single_arg_calls`
to mark fixes as unsafe unless the call is a top-level expression.
Updated PTH109 to use the helper for applicability determination.

## Test Plan

Updated snapshots for `preview_full_name.py`, `preview_import_as.py`,
`preview_import_from.py`, and `preview_import_from_as.py` to reflect
unsafe markers.

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2025-12-01 15:26:55 -05:00
Andrew Gallant 52f59c5c39 [ty] Fix auto-import code action to handle pre-existing import
Previously, the code action to do auto-import on a pre-existing symbol
assumed that the auto-importer would always generate an import
statement. But sometimes an import statement already exists.

A good example of this is the following snippet:

```
import warnings

@deprecated
def myfunc(): pass
```

Specifically, `deprecated` exists in `warnings` but isn't currently
imported. A code action to fix this could feasibly do two
transformations here. One is:

```
import warnings

@warnings.deprecated
def myfunc(): pass
```

Another is:

```
from warnings import deprecated
import warnings

@deprecated
def myfunc(): pass
```

The existing auto-import infrastructure chooses the former, since it
reuses a pre-existing import statement. But this PR chooses the latter
for the case of a code action. I'm not 100% sure this is the correct
choice, but it seems to defer more strongly to what the user has typed.
That is, that they want to use it unqualified because it's what has been
typed. So we should add the necessary import statement to make that
work.

Fixes astral-sh/ty#1668
2025-12-01 14:20:47 -05:00
William Woodruff 53299cbff4
Enable PEP 740 attestations when publishing to PyPI (#21735) 2025-12-01 13:15:20 -05:00
Micha Reiser 3738ab1c46
[ty] Fix find references for type defined in stub (#21732) 2025-12-01 17:53:45 +01:00
Micha Reiser b4f618e180
Use OIDC instead of codspeed token (#21719) 2025-12-01 17:51:34 +01:00
Andrew Gallant a561e6659d [ty] Exclude `typing_extensions` from completions unless it's really available
This works by adding a third module resolution mode that lets the caller
opt into _some_ shadowing of modules that is otherwise not allowed (for
`typing` and `typing_extensions`).

Fixes astral-sh/ty#1658
2025-12-01 11:24:16 -05:00
Alex Waygood 0e651b50b7
[ty] Fix false positives for `class F(Generic[*Ts]): ...` (#21723) 2025-12-01 13:24:07 +00:00
David Peter 116fd7c7af
[ty] Remove `GenericAlias`-related todo type (#21728)
## Summary

If you manage to create an `typing.GenericAlias` instance without us
knowing how that was created, then we don't know what to do with this in
a type annotation. So it's better to be explicit and show an error
instead of failing silently with a `@Todo` type.

## Test Plan

* New Markdown tests
* Zero ecosystem impact
2025-12-01 13:02:38 +00:00
David Peter 5358ddae88
[ty] Exhaustiveness checking for generic classes (#21726)
## Summary

We had tests for this already, but they used generic classes that were
bivariant in their type parameter, and so this case wasn't captured.

closes https://github.com/astral-sh/ty/issues/1702

## Test Plan

Updated Markdown tests
2025-12-01 13:52:36 +01:00
Alex Waygood 3a11e714c6
[ty] Show the user where the type variable was defined in `invalid-type-arguments` diagnostics (#21727) 2025-12-01 12:25:49 +00:00
Alex Waygood a2096ee2cb
[ty] Emit `invalid-named-tuple` on namedtuple classes that have field names starting with underscores (#21697) 2025-12-01 11:36:02 +00:00
Micha Reiser 2e229aa8cb
[ty] LSP Benchmarks (#21625) 2025-12-01 11:33:53 +00:00
Carl Meyer c2773b4c6f
[ty] support `type[tuple[...]]` (#21652)
Fixes https://github.com/astral-sh/ty/issues/1649

## Summary

We missed this when adding support for `type[]` of a specialized
generic.

## Test Plan

Added mdtests.
2025-12-01 11:49:26 +01:00
David Peter bc6517a807
[ty] Add missing projects to `good.txt` (#21721)
## Summary

These projects from `mypy_primer` were missing from both `good.txt` and
`bad.txt` for some reason. I thought about writing a script that would
verify that `good.txt` + `bad.txt` = `mypy_primer.projects`, but that's
not completely trivial since there are projects like `cpython` only
appear once in `good.txt`. Given that we can hopefully soon get rid of
both of these files (and always run on all projects), it's probably not
worth the effort. We are usually notified of all `mypy_primer` changes.

## Test Plan

CI on this PR
2025-12-01 11:18:41 +01:00
Kieran Ryan 4686c36079
docs: Output file option with GitLab integration (#21706)
Co-authored-by: Micha Reiser <micha@reiser.io>
2025-12-01 10:07:25 +00:00
Shunsuke Shibayama a6cbc138d2
[ty] remove the `visitor` parameter in the `recursive_type_normalized_impl` method (#21701) 2025-12-01 08:48:43 +01:00