Commit Graph
370 Commits
Author SHA1 Message Date
Brent Westbrook 3e1f636451 Bump 0.15.21 (#26676) 2026-07-09 15:42:27 -04:00
Omar Yusuf AbdiandMicha Reiser 311158e260 [ruff] Detect syntax errors in individual notebook cells (#26419)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-07-07 11:28:10 +02:00
Brent Westbrook f82a36b6ba Bump 0.15.20 (#26376) 2026-06-25 10:00:55 -07:00
Dhruv Manilawala c24ded8ef6 Update ruff_python_parser README for crates.io (#26315)
## Summary

This PR updates the parser README to:
1. Link the parser README's AST reference to the published
`ruff_python_ast` crate
2. Remove the obsolete "Python version support" section now that version
specific syntax errors are implemented

Additionally, I've also updated the README generator to add a
"Versioning" section while preserving the rest of the handwritten README
and updated the generator to refresh marker-delimited versioning
sections. Maybe this is not worth doing, let me know if that's the case.

### Review

-
https://github.com/astral-sh/ruff/pull/26315/commits/5a4145a37436872c197c7de9771a04e91f4f0500
- updates the README manually as mentioned in (1) and (2) above
-
https://github.com/astral-sh/ruff/pull/26315/commits/dcb59253c41ecbebacd919defcbb725461a95478
- updates the README generator to add the versioning section

## Test plan

Here's the [Rendered
README](https://github.com/astral-sh/ruff/blob/dcb59253c41ecbebacd919defcbb725461a95478/crates/ruff_python_parser/README.md)
for preview.

Ran `uv run --script scripts/generate-crate-readmes.py` twice and
verified idempotent output
2026-06-24 12:07:14 +05:30
Charlie Marsh 7f0436561d Bump version to 0.15.19 (#26291) 2026-06-23 20:42:26 -04:00
Charlie Marsh dff016b7a4 Publish Ruff crates to crates.io (#26271)
## Summary

Publish Ruff's production Rust crates to crates.io as part of the
existing release workflow. This follows uv's setup: workspace
dependencies carry registry-compatible version pins, internal crates
receive generated READMEs and an explicit versioning policy, CI dry-runs
the full workspace publish, and release jobs publish missing crate
versions idempotently through crates.io trusted publishing.

The publishing set contains 32 packages: Ruff's CLI, WASM package,
server, linter, formatter, parser, and the internal Ruff component
crates required by them. It also includes `ty_module_resolver`,
`ty_site_packages`, and `ty_static`, because those three crates are part
of Ruff's normal dependency closure.

The publishing set deliberately excludes:

- Test-only crates: `mdtest`, `ruff_mdtest`,
`ruff_python_ast_integration_tests`, and
`ruff_python_trivia_integration_tests`.
- Benchmark and development crates: `ruff_benchmark` and `ruff_dev`.
- All remaining `ty_*` crates.

These packages retain `publish = false`, so bootstrap, version bumping,
README generation, CI dry-runs, and release publishing skip them through
Cargo metadata instead of a separate hard-coded allowlist.

The crates.io job is intentionally independent of release announcement,
so a crates.io outage cannot block the existing binary, PyPI, npm, or
GitHub release outputs. A bootstrap script reserves new crate names,
configures the release workflow as each crate's trusted publisher,
enables trusted-publishing-only releases, and records configured crates
for idempotent reruns.

The full workspace publish dry-run packages and verifies all 32 selected
crates.

Closes https://github.com/astral-sh/ruff/issues/43.
2026-06-23 12:49:23 -04:00
Micha Reiser b8ae5978c2 Avoid reallocating singleton call arguments (#26223) 2026-06-22 17:53:33 +02:00
Micha Reiser ae306a059e Avoid allocating when parsing single string literals (#26200) 2026-06-22 07:53:17 +02:00
Micha Reiser 4fda309ba2 Inline parser recovery context checks (#26038) 2026-06-16 15:43:32 +02:00
Micha Reiser bcae1b70fd Match parser keywords as bytes (#26037) 2026-06-16 15:13:33 +02:00
Charlie Marsh 3cef3416c5 Reject yield expressions after commas (#26024)
## Summary

Reject unparenthesized `yield` expressions after the first element of an
expression list:

```python
def generator():
    1, yield 2
```

The parser previously reused the yield-enabled expression context for
every tuple element. Python's grammar only allows the initial
simple-statement alternative to be a `yield` expression; later
comma-separated elements use the ordinary starred-expression grammar.

This clears the yield allowance for subsequent elements while preserving
valid parenthesized nested yields.
2026-06-16 09:28:12 +00:00
Charlie Marsh 841fb339d3 Reject starred comprehension targets (#26023)
## Summary

Reject bare starred targets in comprehensions:

```python
[item for *items in source]
```

The semantic syntax checker already rejects a bare starred target in an
ordinary `for` statement. This applies the same validation to
comprehension clauses while preserving valid tuple and list unpacking
targets such as `for *items, in source`.
2026-06-16 05:20:45 -04:00
Charlie Marsh 4b93e63a9d Reject __debug__ lambda parameters (#26022)
## Summary

Reject `__debug__` as a lambda parameter name:

```python
lambda __debug__: 0
```

Function parameters already use the semantic syntax check that prevents
assignments to `__debug__`, but lambda parameters only checked for
duplicate names. This applies the existing identifier validation
consistently to both forms.
2026-06-15 17:02:00 -04:00
Charlie Marsh a50dc58628 Reject parenthesized star imports (#26021)
## Summary

Reject parenthesized star imports such as:

```python
from module import (*)
```

Python only permits a bare star in `from` imports. The parser previously
accepted the parenthesized form because star aliases were parsed
independently of the surrounding import-list delimiters.

This adds the missing parser validation while preserving ordinary
parenthesized imports and bare star imports.
2026-06-15 17:01:37 -04:00
Charlie Marsh 8de183b907 Detect equivalent numeric mapping keys (#26009)
## Summary

Mapping-pattern duplicate detection and F601 compare keys through
`HashableExpr`, but numeric normalization previously only recognized
values equivalent to `True` or `False`. This meant that other values
Python treats as the same dictionary key were considered distinct:

```python
match value:
    case {2: first, 2.0: second}: ...
```

This adds a dedicated numeric representation for integer, float,
boolean, and complex literals so that exactly integral floats compare
with equivalent integers, including signed forms and zero-imaginary
complex values. Tuple normalization is limited to statically known
values so dynamic tuple elements do not introduce false-positive F601
diagnostics.

Numeric normalization uses the existing `u64` integer representation.
Larger integers retain structural comparison, avoiding
arbitrary-precision conversion in parser and linter hot paths.
2026-06-15 19:17:13 +00:00
Charlie Marsh b6ab2b32fb Reject _ as a match-pattern target (#25977)
## Summary

Python reserves `_` for wildcard patterns and does not allow it as the
binding target in either of these forms:

```python
match value:
    case 1 as _:
        pass
    case {**_}:
        pass
```

We currently recover an AST for both forms without reporting a parser
error. Both are grammar errors in CPython, so this change validates the
capture target while parsing `as` and mapping patterns and reports
`cannot use '_' as a target` on the underscore.

We previously tried to address the mapping-pattern case in
[#6838](https://github.com/astral-sh/ruff/pull/6838) by representing the
rest target as a general `PatternMatchAs` node. This keeps the existing
`Identifier` representation and recovered AST, including statements
after the invalid match, while rejecting the invalid target at the
parser boundary.
2026-06-15 13:47:21 +00:00
Charlie Marsh 7a7bfd84c4 Reject unparenthesized generator expressions in class bases (#25978)
## Summary

Class definitions do not allow a bare generator expression as a base,
even though the same syntax is valid as the sole argument in a function
call. We currently parse the class form without an error:

```python
class C(base for base in bases):
    pass
```

This change reuses the existing unparenthesized-generator diagnostic for
class arguments while continuing to accept explicitly parenthesized or
unpacked generator expressions:

```python
class C((base for base in bases)): ...
class C(*(base for base in bases)): ...
```
2026-06-15 13:34:24 +00:00
Charlie Marsh a9de595e40 Detect mapping keys equivalent to booleans (#25982)
## Summary

Mapping patterns reject duplicate literal keys, but duplicate detection
compared AST shapes instead of Python hash equality. As a result, values
that Python treats as the same key were accepted:

```python
match value:
    case {1.0: first, True: second}: ...
```

This switches mapping-key detection to `HashableExpr` and extends
boolean-equivalent normalization through signed numeric expressions and
complex values with a zero imaginary part. We now report duplicate-key
syntax errors for `0`/`False`, `1.0`/`True`, `-0`/`False`, and `1 +
0j`/`True`, matching CPython.
2026-06-15 09:30:48 -04:00
Charlie Marsh b0a887e367 Use ThinVec for call keywords (#25999)
## Summary

Using ThinVec here is impactful because it reduces the size of `Expr`:

```
Arguments: 48 → 40 bytes
ExprCall:  72 → 64 bytes
Expr:      80 → 72 bytes
```

In profiling, it was empty about 80% of the time.
2026-06-15 09:29:14 -04:00
Micha Reiser 32a86842a6 Move value parsing out of lexing (#25360) 2026-06-15 13:15:35 +02:00
Charlie Marsh 39b09a9d69 Validate function type parameter default order (#25981)
## Summary

Function type parameter lists did not run the same default-order
validation as class and type-alias parameter lists. As a result, we
accepted functions with a required type parameter after one with a
default:

```python
def f[T = int, U](): ...
```

This reuses the existing type-parameter ordering check for function
definitions, so we now report the same semantic syntax error that we
already emit for equivalent classes and type aliases.
2026-06-14 18:54:47 -04:00
Charlie Marsh ded6c002f9 Reject multiple starred names in sequence patterns (#25976)
## Summary

Python permits at most one starred name in a sequence pattern, but our
parser currently accepts multiple:

```python
match value:
    case [*head, middle, *tail]:
        pass
```

This tracks whether a sequence pattern already contains a star and
reports `invalid-syntax` on each later starred name. The diagnostic
points to the additional starred pattern and uses CPython's error
message, while keeping the recovered AST available to downstream tools.
2026-06-14 14:10:13 -04:00
Charlie Marsh 948359fd97 Enable Clippy's iter_over_hash_type lint (#25732)
## Summary

Stacks on #25726 and enables Clippy's `iter_over_hash_type` restriction
lint across the workspace, so new hash-map and hash-set iterations must
make their ordering assumptions explicit.

Most existing loops are order-independent and use a site-local
`#[expect(clippy::iter_over_hash_type)]`. At the order-sensitive sites,
this sorts before iteration. (In practice, that should stabilize some
parser fixtures, configuration diagnostics, union normalization, etc.).

This lint is kind of annoying, but given how much we want to crack down
on non-determinism in ty, it seems worthwhile to enable IMO.
2026-06-09 16:35:09 +00:00
Micha Reiser aa894ffa41 Reserve AST Vec's with correct capacity for common cases (#25451) 2026-06-05 07:00:32 +01:00
Micha Reiser 10ccd511e9 Shrink additional parser AST collections (#25465) 2026-06-04 10:14:51 +01:00
Micha Reiser 1518f1d5fd Drop excess capacity from Suites during parsing (#25368)
## Summary

Shrink Suite vectors to drop the excess capacity during parsing. 

I excluded other nodes for now to get a better sense of the performance
and memory impact.

I'm a bit conflicted on this. This is a pretty huge memory improvement
for ty, but there are a few linter benchmarks that regress by 1-2%
because some vectors need to be copied to smaller allocations, which
hurts performance. For the linter and formatter, it's also not important
to shrink the vectors, because the AST is never stored for long. But
this is different for ty where we cache the AST.

I'm curious to hear what others think on this. I could also try to
reduce the places where we call `shrink_to_fit`, e.g., only for
statements?
2026-05-29 18:17:16 +00:00
Alex WaygoodandMicha Reiser 366fe21ba3 [ty] Improve diagnostics for syntax errors in forward annotations (#25158)
## Summary

Fixes https://github.com/astral-sh/ty/issues/1627.

Here's an example diagnostic with the current release of ty:

<img width="2286" height="286" alt="image"
src="https://github.com/user-attachments/assets/46ab9154-aaf0-4451-b301-5ff12fcd8507"
/>

On this branch, this diagnostic becomes:

<img width="1464" height="408" alt="image"
src="https://github.com/user-attachments/assets/449e0b6c-58d2-4501-91df-c267db6f48ca"
/>

The exact span of the node that creates the syntax error is now retained
and highlighted in the diagnostic.

## Implementation

Propagating the range of the node inside the string annotation into the
diagnostic is trivial. However, naively implementing that quickly
revealed that this would make diagnostics like this unsuppressable:

```py
x: """list[
    yield from range(42)
]"""
```

The primary range of the diagnostic is now specifically the `yield from
range(42)` part of the string rather than the string node as a whole.
But I cannot add a `ty: ignore` comment that is either on or above the
`yield from range(42)` part of the string -- the "comment" there would
just become part of the string.

This PR also improves the consistency of our parser error messages in
general when it comes to capitalization.

## Test Plan

Mdtests extended and updated

---------

Co-authored-by: Micha Reiser <micha@reiser.io>
2026-05-28 10:51:20 +00:00
Charlie Marsh 574e10752f Expand semantic syntax errors for invalid walruses (#25415)
## Summary

Python rejects assignment expressions in several comprehension contexts,
but we previously only reported the case in which a walrus rebound a
comprehension variable.

As a result, we accepted invalid walruses in the iterable and class-body
portions clause of a comprehension, and missed some rebinding cases in
filter clauses and nested comprehensions. It turns out the rules are
really complicated!

For example, we now report the two newly modeled syntax errors:

```py
# error: [invalid-syntax] "assignment expression cannot be used in a comprehension iterable expression"
[x for x in (values := [1])]

class C:
    # error: [invalid-syntax] "assignment expression within a comprehension cannot be used in a class body"
    [(value := item) for item in [1]]
```

We also catch previously missed instances of the existing rebinding
error:

```py
# error: [invalid-syntax] "assignment expression cannot rebind comprehension variable"
[x for x in [1] if (x := 0)]
```

In general, I decided not to worry about emitting multiple diagnostics
for a single error. These are rare, they're fatal, and it added a lot of
complexity (so in some cases we may emit two errors for a walrus that is
invalid for two reasons).
2026-05-27 21:39:41 +01:00
Micha ReiserandDhruv Manilawala 38562889b9 Reduce memory usage by dropping token-excess capacity and improve performance by approximating the initial tokens vec size (#25354)
Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
2026-05-26 18:08:12 +01:00
Micha Reiser 6ab8b737c5 Use ThinVec in AST to shrink Stmt (#25361) 2026-05-24 16:23:36 +01:00
Micha Reiser 5f284d1f52 Recover incomplete list comprehension elements (#25326) 2026-05-23 10:03:56 +01:00
Charlie Marsh 2fd7ed0a16 Avoid redundant TokenValue drops in the lexer (#25300)
## Summary

If we avoid resetting the lexer value slot when it's already empty, this
apparently improves performance by 1-2%. (In optimized builds, this
keeps the common case to a discriminant branch instead of re-entering
the `TokenValue` drop path.)
2026-05-21 19:30:48 +01:00
Charlie Marsh aea5ed4d27 Avoid unnecessary parser lookahead for operators (#25290)
## Summary

We only need to peek ahead two tokens if the first token is `not` or
`in`. We can avoid the `peek` in the majority of cases, which apparently
speeds up the parser by 20-30%.
2026-05-21 14:13:20 +01:00
Samuel ColvinandCharlie Marsh c423054dc0 Add a recursion limit to the parser (#24810)
## Summary

Partial fix for #22930.

Without this malicious or machine generated code could cause a stack
overflow with something as simple as `'(' * 5000 + '1' + ')' * 5000`.

I decided to do the simplest thing and have a limit that's always
applied with a reasonable default. Since:
* the overhead of this check will be tiny
* it seems inconceivable that anyone will want to have no limit 

## Test Plan

PR includes tests.

---------

Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
2026-05-21 09:34:53 +01:00
Jelle Zijlstra 409c13f3ec Add full PEP 798 support (#25104)
Fixes #25098.

This adds full support for PEP 798 through the parser, linter,
formatter, and type checker.
There are a lot of changes but they are mostly straightforward. Let me
know though if it's better to split this up.
2026-05-16 16:32:57 +01:00
Eyüp Can AkmanandMicha Reiser f32733c063 [flake8-pyi] Fix PYI016 false positive for f-string debug specifier (#24098)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-04-30 11:14:25 +02:00
David Peter cf14481f44 Semantic syntax errors: better error message for global vs parameter (#24902)
## Summary

This is an attempt to improve the error message for something like
```py
a = 1

def f(a):
    global a
```

I realize that the previous wording ("name 'a' is parameter and global")
is used by CPython itself, but unless we are trying to be consistent
with CPython, I think we can improve upon this? The previous version
seemed a bit cryptic to me when I first saw it.

## Test Plan

Updated snapshot tests
2026-04-29 08:46:57 +02:00
Alex Waygood 581b3fa230 Update Rust toolchain to 1.95 and MSRV to 1.93 (#24677) 2026-04-17 11:39:14 +01:00
Micha Reiser ad30af4cd0 Force update insta snapshots (#24495) 2026-04-08 17:33:19 +02:00
Charlie Marsh 9a55bc6568 Reject multi-line f-string elements before Python 3.12 (#24355)
## Summary

Before Python 3.12, a replacement field in an f-string can span multiple
lines only if the outer f-string is triple-quoted. This was relaxed in
Python 3.12, but we weren't rejecting these as syntactically invalid on
earlier versions.

Closes https://github.com/astral-sh/ruff/issues/24348.
2026-04-05 15:09:26 +00:00
Dylan 5f88756ee1 Disallow starred expressions as values of starred expressions (#24280)
Part of #19077
2026-04-02 14:57:28 +00:00
Charlie Marsh fcef46ccdf Fix %foo? parsing in IPython assignment expressions (#24152)
## Summary

We now distinguish between IPython escape commands lexed after an `=`
sign from those at the start of a logical line, which allows `x = %foo?`
to be interpreted as "assign the result of running a line magic named
`foo?`", matching the IPython assignment-magic transform.

See:
https://github.com/astral-sh/ruff/issues/21705#issuecomment-4085099342.
2026-03-24 13:14:53 +00:00
Charlie Marsh 8bc437ef90 Add support for star-unpacking of comprehensions (PEP 798) (#23788)
## Summary

In Python 3.15, you can star-unpack comprehensions (e.g., `[*x for x in
y]`) via [PEP
798](https://docs.python.org/3.15/whatsnew/3.15.html#whatsnew315-unpacking-in-comprehensions).
This PR adds support to the parser.
2026-03-09 10:23:52 -04:00
Alex Waygood 0d84a0654a [ty] Add validation for type parameters with defaults after TypeVarTuple (#23807) 2026-03-08 18:28:16 +00:00
Charlie Marsh 735da8b415 Reject semantic syntax errors for lazy imports (#23757)
## Summary

We now reject cases like:

- `lazy import ...` inside functions, including `async def`
- `lazy from ... import ...` inside functions, including `async def`
- `lazy import ...` and `lazy from ... import ...` inside class bodies
- `lazy import ...` and `lazy from ... import ...` anywhere inside a
`try` statement, including `except` / `except*`
- `lazy from ... import *` anywhere
- `lazy from __future__ import ...` anywhere

A follow-up to #23755.

See: https://github.com/astral-sh/ruff/issues/21305.
2026-03-06 14:25:13 +00:00
Charlie Marsh 8a10b6743c Add support for lazy import parsing (#23755)
## Summary

This PR adds `is_lazy` to the AST and parser, and supports `lazy` import
formatting in the formatter. The name `is_lazy` matches the [CPython
AST](https://github.com/python/cpython/blob/c3fb0d9d96902774c08b199dda0479a8d31398a5/Parser/Python.asdl#L48),
though we could modify it if there's demand.

There are no further changes to Ruff rules or even to Ruff import
sorting, since those deserve separate design discussions.

I've also omitted support for flagging semantic syntax errors (e.g.,
`lazy import` inside `def`).

See: https://github.com/astral-sh/ruff/issues/21305.
2026-03-06 09:12:21 -05:00
Dhruv ManilawalaandKartik Ganapathi 6551438942 [parser] Fix indentation tracking after line continuations (#23417)
## Summary

fixes: https://github.com/astral-sh/ruff/issues/19301

## Test Plan

Add new lexer and parser test cases.

---------

Co-authored-by: Kartik Ganapathi <kartikganapathi@icloud.com>
2026-02-19 12:52:14 +00:00
Charlie Marsh 8fb1123c54 [ty] Visit parameters in source order (#23403)
## Summary

Previously, `Parameters::visit_source_order` used `ParametersIterator`
which visits in type-based order. For well-formed Python code, this
matches source order; but error recovery can produce ASTs like `def
foo(**kwargs, a):`.
2026-02-19 02:46:06 +00:00
kar-ganap 038235c6db [parser] Fix false syntax error for match-like annotated assignments (#23297)
## Summary

Fixes #22528.

The parser incorrectly treats `match[0]: int` and `match [x, y, z]:
{dict}` as the start of a `match` statement, producing a false syntax
error. The issue is that the parser checks only for a colon after the
subject expression to confirm a match statement, but annotated
assignments with `match` as a variable name also have a colon.

This PR adds a `self.peek() == TokenKind::Newline` guard to the colon
check, so that `match` is only treated as a keyword when the colon is
followed by a newline (which is required for a match statement's body).
When the colon is followed by something else (like a type annotation
value), it falls through to the soft-keyword-as-identifier path.

## Test Plan

All 42 existing match-related parser tests pass. No snapshot changes
needed. Clippy clean.

Reproduction from the issue:

```python
# These should parse without error:
match[0]: int
match [x, y, z]: {0: "a", 1: "b"}
```
2026-02-18 15:15:35 +05:30
Brent Westbrook 6ded4bed16 Fix f-string middle panic when parsing t-strings (#23232)
Summary
--

This PR fixes #23198 by copying Dylan's changes from #19183 to the other
`InterpolatedStringElementsKind` variant, in line with Micha's prophetic
comment
(https://github.com/astral-sh/ruff/pull/19183/changes#r2217325217).

Test Plan
--

Two new tests derived from the issue
2026-02-12 14:27:53 +00:00