Commit Graph
371 Commits
Author SHA1 Message Date
Charlie Marsh 5e90790d11 Compute the lexer keyword hash at compile time (#29677)
## Summary

Changing the lexer's keyword set now takes one edit to the Rust list.
The compiler finds a collision-free multiplier and builds the 64-slot
table, so we can remove the Python generator and its lockfile.

A two-byte keyword like `if` packs to `0x6669_0000_0000_0000`. Only the
low two bytes of the multiplier affect its slot. We place keywords from
shortest to longest, choosing each new byte of the multiplier without
disturbing the shorter keywords. The lexer still selects a slot with one
multiply and shift, then compares the full word.
2026-10-23 15:29:49 -04:00
Charlie Marsh e3304857ec Specialize ASCII identifier lexing (#29503)
## Summary

We give ASCII identifiers a dedicated path, avoiding Unicode bookkeeping
and checking string prefixes only when a one- or two-letter name reaches
a quote. Both paths share the existing batched ASCII scanner, preserving
fast scanning for Unicode names with long ASCII suffixes.

Stacked on #29463 to measure the incremental improvement. [CodSpeed
reports](https://github.com/astral-sh/ruff/pull/29503/checks?check_run_id=118300735426)
6.6–9.8% greater efficiency across all five lexer benchmarks, with no
reported regressions. We preserve the existing scanner and add no
inlining attributes or unsafe code.
2026-10-23 13:58:34 -04:00
Charlie Marsh de9d86e245 Speed up identifier and keyword lexing (#29463)
## Summary

We scan ASCII identifier continuations in sixteen-byte batches using a
byte lookup table, avoiding per-character decoding. Keyword lookup
filters by length and initial byte, then uses a compact hash table with
a full-word comparison to reject collisions. Non-ASCII suffixes retain
the existing Unicode path.
2026-10-23 13:58:33 -04:00
Micha Reiser 3e3f22dcc4 Make stacker an opt-in feature (#29505) 2026-10-19 18:02:19 -07:00
Charlie Marsh 85430a958b Share postfix parsing and reduce expression copies (#29480)
## Summary

We skip prefix-operator dispatch for identifiers and parse atoms together with their postfix chains. Keeping this work in `parse_primary_expression` makes the grouping-parenthesis flag local and avoids passing an intermediate `ParsedExpr` between atom and postfix parsing.
2026-10-19 20:35:16 +00:00
Charlie Marsh 2e696c7c86 [ty] Fix panic on completions past the end of a notebook's last cell (#29306)
## Summary

This PR fixes a completion panic in a notebook with an empty last cell.

To analyze a notebook, we combine its Python cells into one source
string, adding a newline after each cell:

```text
First cell:       "x = 1"       at offsets 0..5
Empty last cell:  ""            at offsets 6..6
Combined source:  "x = 1\n\n"  at offsets 0..7
```

We parse the cells separately, but the resulting module describes the
combined source. Previously, we ended that module at offset 6, where the
empty cell's content ends. Position conversion uses the combined source,
so a request for character 1 of the empty cell can resolve to offset 7.
That is the end of the source, but it was outside the module's range.
Looking up the completion position then panicked with `Range is not
contained within root`.

We now give the module the range 0..7, as we would when parsing the same
source as a whole. This makes positions at the end of the combined
source safe to look up. #29307 separately corrects position conversion
so the same request resolves to offset 6, the end of the requested
cell's content.

Closes https://github.com/astral-sh/ty/issues/4687.
2026-10-13 09:15:13 -04:00
Charlie Marsh 598f4bdfd5 Adopt Rust 1.97 integer APIs and Cargo warning policy (#29048)
## Summary

- Use the integer bit APIs stabilized in Rust 1.97 for packed node
indices, token capacity, rule iteration, and type-variable support sets.
- Use Cargo's warning policy in our native and WASM Clippy checks,
keeping warnings fatal without changing compiler flags and invalidating
the build cache. Update the contributing guides to match.

Preserves the Rust 1.97 MSRV. The warning policy change follows
https://github.com/astral-sh/uv/pull/22122.
2026-10-01 14:01:44 -04:00
Micha Reiser 689dc812f3 Rename TokenKind::Name to Identifier (#28667) 2026-09-17 15:47:10 +02:00
Charlie Marsh 7b13f01ba1 [ty] Reduce retained AST memory by shrinking expressions (#28335)
## Summary

We reduce `Expr` from 64 to 56 bytes on 64-bit targets. The largest
variants determine the enum's size, so shrinking those variants saves
eight bytes in every `Expr` value, including expressions in the parsed
modules retained by ty.

The changes are:

- Store positional call arguments in `ThinVec`, reducing `Arguments` and
`ExprCall` by eight bytes.
- Store all comparison operands in one boxed slice. This removes the
separate left-operand allocation and reduces `ExprCompare` by eight
bytes while keeping operators in a boxed slice.
- Store dictionary-comprehension generators in a boxed slice, reducing
`ExprDictComp` by eight bytes.
- Store f-string and t-string elements in boxed slices, and represent a
single f-string directly as `FString`. This keeps single parts inline
and reduces `ExprFString` and `ExprTString` by eight bytes.

The parser, AST visitors, formatter, lint rules, and type inference use
the updated layouts. Size assertions cover the 56-byte enum and its
affected variants.
2026-09-10 15:39:14 -04:00
Micha Reiser a99b96b9ac Expose hidden lexer token metadata accessors (#28443) 2026-09-09 09:02:54 +02:00
Charlie Marsh e7adf82ff0 Reuse parser name lookups when interning (#28399)
Use hashbrown's borrowed-entry insertion for long parser names so a
missing name reuses its lookup when it is inserted. Construct the
heap-backed `Name` only on a miss, while preserving the inline bypass
and shared allocations for repeated long names.
2026-09-07 19:00:20 -04:00
Brent Westbrook 0ecff87790 Validate unary expressions when parsing (#28233)
Summary
--

While reviewing #28231, Codex found a preexisting bug shared with our
unary minus handling. Namely, CPython emits an error for code like this,
where the unary expression is part of a longer expression:

```pycon
>>> match foo:
...     case -1**2: ...
...
  File "<python-input-0>", line 2
    case -1**2: ...
           ^^
SyntaxError: invalid syntax
```

but Ruff does not:

```console
$ ruff check --ignore ALL - <<EOF
match foo:
    case -1**2: ...
EOF
All checks passed!
```

We now verify that the parsed unary expression is a number literal and
emit an error if not.

Test Plan
--

New inline snapshots
2026-09-02 09:34:51 -04:00
Brent Westbrook eff1c88d70 Allow unary plus in match patterns on Python 3.15 (#28231)
Summary
--

As added in https://github.com/python/cpython/pull/148566, CPython now
allows unary plus in match
patterns, mirroring the support for unary minus. We already had a
special case for this for improved
error reporting and recovery, so I just swapped out the `add_error` call
for
`add_unsupported_syntax_error` with a new error kind.

Part of https://github.com/astral-sh/ruff/issues/28206

Test Plan
--

New inline parser tests
2026-09-02 09:16:08 -04:00
Alex Waygood d5a6394425 Fix compiler warnings seen in CI jobs (#28066) 2026-08-26 14:21:42 +01:00
Charlie Marsh 88d56e5feb Use stabilized Rust pattern assertion macros (#27955)
## Summary

- Use Rust 1.96's stabilized `assert_matches!` and
`debug_assert_matches!` macros throughout Ruff and ty.
- Include mismatched values in assertion failures and remove redundant
manual debug formatting.
- Preserve existing assertions for values that do not implement `Debug`.
2026-08-21 09:29:39 -04:00
Augustin BouverotandMicha Reiser 3ea20f6161 Align t-string/bytes mix error with CPython 3.14 (#27766)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-08-19 12:35:23 +02:00
Eduardo Rittner CoelhoandBrent Westbrook e96caa26b7 [syntax-errors] Detect duplicate keyword arguments (#17804)
## Summary

Part of https://github.com/astral-sh/ruff/issues/17412

Detects duplicate keyword arguments in function call.

## Test Plan

Added inline tests to validate intended behavior

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-08-18 13:39:19 -04:00
Ross Titmarsh 4d813d53cd Fix broken link to Python docs (#27757)
Fixed a link to `frozen.discard` in the Python docs this was a valid
link in older Python docs but has been broken.

While I was there I noticed a few other uncanonical links so replaced
them with more canonical versions and removed some links to specific
Python versions that are unnecessary.
2026-08-14 16:08:37 +00:00
Micha Reiser 7a9aed24ff Guarantee minimum stack size when parsing a module, standalone expression, and suites (#25464) 2026-08-14 14:01:30 +02:00
Swayam Mhaskar d332d20d3f [syntax-errors] Name is parameter and nonlocal (#27628)
## Summary
Part of #17412
Detects semantic syntax error where name is parameter and nonlocal

## Test Plan
Added tests in `nonlocal_parameter.py`
2026-08-13 13:48:40 -04:00
Alex Waygood c0824de94a Enable rustfmt on more files (#27630) 2026-08-10 15:30:41 +01:00
Charlie MarshandCharlie Marsh c56aad17fd [ty] Reduce Expr size to 64 bytes (#27591)
## Summary

This PR reduces the size of `Expr` from 72 to 64 bytes by storing only
the start offset on `ExprCall` (64 to 56 bytes) and boxing the uncommon
implicitly concatenated string representation in `ExprStringLiteral` (64
to 48 bytes). Both changes are required to reduce the size of the
containing `Expr` enum.

`ExprCall` derives its end offset from its argument list; parser and
error-recovery paths assert that their ranges share the same end.

---------

Co-authored-by: Charlie Marsh <charliemarsh@openai.com>
2026-08-09 13:41:24 +00:00
Charlie Marsh 6cfeb8aa07 Narrow internal visibility with Hawk (#27339)
## Summary

This PR uses Hawk 0.1.11 to narrow internal declarations to the
visibility they actually need.

Here, I've intentionally _only_ made visibility changes; unused API
removals are split into follow-up PRs. In total, 1,201 declaration
visibility modifiers are narrowed. Public generated formatter APIs and
other declarations whose narrower visibility would activate dead-code or
API-shape lints remain unchanged.
2026-07-31 22:08:13 -04:00
Ed Page 34d0944f3b Reduce syntax error noise by swallowing dedents like indents 2026-07-24 14:42:57 -05:00
Alex Waygood c5aa9063e2 Prefer let guards and direct pattern matching (#26975) 2026-07-19 15:07:15 +01:00
Charlie Marsh 301b7ed4d6 [ty] Share heap-backed parser names with CharStr (#26594)
## Summary

This PR changes `ruff_python_ast::Name` from a 24-byte `CompactString`
to a 16-byte immutable `CharStr` from
[`astral-sh/char_str`](https://github.com/astral-sh/char_str).

`char_str` is an Astral-maintained fork of
[`lean_string`](https://github.com/ryota2357/lean_string) that provides
compact owned strings with mutable and immutable variants: growable
`CharString` for construction and immutable, exactly allocated `CharStr`
for storage. (It also provides Salsa and get-size features.)

Names up to 16 UTF-8 bytes remain inline, static names remain
allocation-free, and longer names use an exactly sized,
reference-counted allocation with no unused capacity.

Removing eight bytes from every `Name` also shrinks common AST nodes.
For example, `Identifier` and `ExprName` drop from 40 to 32 bytes, while
`ExprAttribute`, `StmtFunctionDef`, `StmtClassDef`, and several other
variants each drop by eight bytes.

The parser interns names that exceed the inline capacity, so repeated
longer names share one backing allocation within a parser invocation.

## Why 16 bytes?

Across the full `mypy_primer` corpus, there 20.8 million name
occurrences:

| UTF-8 length | Occurrences | Share | Unique name/file pairs | Share |
|---|---:|---:|---:|---:|
| 1–16 bytes | 18,955,757 | 91.02% | 3,192,424 | 79.42% |
| 17–24 bytes | 1,348,894 | 6.48% | 529,826 | 13.18% |
| 25+ bytes | 522,376 | 2.51% | 297,575 | 7.40% |
| Total | 20,827,027 | 100% | 4,019,825 | 100% |

The 16-byte cutoff keeps 91% of occurrences inline while saving eight
bytes for every occurrence. The 1–16-byte bucket alone removes 151.6 MB
of handle storage across the corpus.

The tradeoff is the 17–24-byte bucket: `CompactString` stored those
names inline, while `CharStr` allocates once per unique name within a
file. But the interning amortizes that cost when a name repeats. Names
longer than 24 bytes already allocated on `main`; for those names, this
change both reduces the handle size and deduplicates repeated backing
allocations.

## Memory impact

Accounting for the observed per-file multiplicities and structural
sharing, modeled `Name` storage across the corpus changes as follows:

| | `main` | This PR | Difference |
|---|---:|---:|---:|
| `Name` handles and backing storage | 526.18 MB | 366.27 MB | -159.91
MB (-30.4%) |

The current [instrumented memory
report](https://github.com/astral-sh/ruff/pull/26594#issuecomment-4906725175)
shows a consistent reduction in total retained memory:

| Project | `main` | This PR | Difference |
|---|---:|---:|---:|
| flake8 | 29.21 MB | 28.71 MB | -1.69% |
| trio | 71.01 MB | 70.01 MB | -1.41% |
| sphinx | 168.81 MB | 166.82 MB | -1.18% |
| prefect | 454.75 MB | 449.06 MB | -1.25% |

Within those totals, `parsed_module` decreases by roughly 2.1% and
`semantic_index` by 2.4–2.7%. Several name-heavy collections decrease by
considerably more.
2026-07-16 14:53:48 -04:00
Micha Reiser 9a5220ecdb Reuse parser scratch buffers (#26798)
## Summary

Use scratch buffers instead of allocating new `Vec`s and shrinking them
when constructing the AST node. While this doesn't remove the need for
copying the elements, it reduces the allocations within our parser
(`shrink_to_fit` often needs to allocate a new buffer and move all
elements). One shared scratch buffer per node type is sufficient,
because our parser is recursive (more nested parse rule always push to
the end, and parse function drain from the end as they complete).


## Performance

Very consistent perf improvement

## Codspeed memory regression

This can cause the parser's peak memory to increase, because we retain
the scratch buffer allocation after parsing a clause completed. However,
that memory is only temporary and released as soon as the parser
completes. Most project-level memory reports show a memory reduction.
It's only specific parser benchmarks that show a memory increase
2026-07-15 17:09:07 -07:00
Charlie Marsh bdf1320bba Update Rust toolchain to 1.97 and MSRV to 1.95 (#26844) 2026-07-15 08:12:16 +02:00
Charlie MarshandMicha Reiser 6e29838d4b Avoid redundant pending-indentation writes (#26774)
## Summary

The lexer checks `pending_indentation` for every token. `Option::take`
writes `None` even on the common path where no indentation is pending,
so we now read the field first and clear it only when a value is
present. This avoids a redundant write in the hot lexer loop while
preserving the existing indentation behavior.

This PR is stacked on #26765 so that CodSpeed can measure the
pending-indentation optimization independently.

---------

Co-authored-by: Micha Reiser <micha@reiser.io>
2026-07-14 17:47:07 +00:00
Charlie Marsh 25b10f9d01 Avoid redundant lexer token bookkeeping (#26765)
## Summary

`Lexer::next_token` previously marked the token start before every
token, and the common lexing path marked it again after optional
whitespace handling even when the cursor had not moved. We now track
token starts only on paths that actually lex a token:
interpolated-string and indentation paths mark their ranges explicitly,
while the common path marks the start immediately before consuming the
token. Whitespace-at-EOF errors use an explicit start offset instead of
depending on the current token range.
2026-07-14 10:40:42 -07:00
Lérè c87ba51052 [ty] Consolidate tab stop offset calculations (#26707)
<!--
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

Following up on [prior review
feedback](https://github.com/astral-sh/ruff/pull/26679#discussion_r3557123788),
this introduces a shared helper (`ruff_python_trivia::tab_offset`) that
we use to consolidate the calculation for advancing a column to the next
tab stop.

## Test Plan

See included tests for the new helper. Otherwise, since this is a pure
refactor, we rely on existing test coverage.
<!-- How was it tested? -->
2026-07-14 16:34:34 +00:00
Charlie Marsh 6fd508aa62 Avoid unnecessary identifier lookahead (#26525)
## Summary

Identifier lexing previously inspected the following one or two
characters for a quote before checking whether the identifier could be a
string prefix. Gate those lookaheads behind a shared string-prefix
check, so ordinary identifiers avoid unnecessary cursor reads while
string-prefix flags continue through the existing path.
2026-07-13 09:52:50 -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
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
Micha Reiser aa894ffa41 Reserve AST Vec's with correct capacity for common cases (#25451) 2026-06-05 07:00:32 +01:00