[syntax-errors] Fix star annotation before Python 3.11 (#16878)

Summary
--

Fixes #16874. I previously emitted a syntax error when starred
annotations were _allowed_ rather than when they were actually used.
This caused false positives for any starred parameter name because these
are allowed to have starred annotations but not required to. The fix is
to check if the annotation is actually starred after parsing it.

Test Plan
--

New inline parser tests derived from the initial report and more
examples from the comments, although I think the first case should cover
them all.
This commit is contained in:
Brent Westbrook 2025-03-20 17:44:52 -04:00 committed by GitHub
parent 67602512b6
commit 42cbce538b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 415 additions and 4 deletions

View file

@ -2959,13 +2959,26 @@ impl<'src> Parser<'src> {
// # parse_options: {"target-version": "3.11"}
// def foo(*args: *Ts): ...
// test_ok param_with_star_annotation_py310
// # parse_options: {"target-version": "3.10"}
// # regression tests for https://github.com/astral-sh/ruff/issues/16874
// # starred parameters are fine, just not the annotation
// from typing import Annotated, Literal
// def foo(*args: Ts): ...
// def foo(*x: Literal["this should allow arbitrary strings"]): ...
// def foo(*x: Annotated[str, "this should allow arbitrary strings"]): ...
// def foo(*args: str, **kwds: int): ...
// def union(*x: A | B): ...
// test_err param_with_star_annotation_py310
// # parse_options: {"target-version": "3.10"}
// def foo(*args: *Ts): ...
self.add_unsupported_syntax_error(
UnsupportedSyntaxErrorKind::StarAnnotation,
parsed_expr.range(),
);
if parsed_expr.is_starred_expr() {
self.add_unsupported_syntax_error(
UnsupportedSyntaxErrorKind::StarAnnotation,
parsed_expr.range(),
);
}
parsed_expr
}