Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[syntax-errors] Parenthesized keyword argument names after Python 3.8 #16482

Merged
merged 18 commits into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# parse_options: {"target-version": "3.8"}
f((a)=1)
f((a) = 1)
f( ( a ) = 1)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# parse_options: {"target-version": "3.7"}
f((a)=1)
66 changes: 52 additions & 14 deletions crates/ruff_python_parser/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,11 +436,6 @@ pub struct UnsupportedSyntaxError {
pub kind: UnsupportedSyntaxErrorKind,
pub range: TextRange,
/// The target [`PythonVersion`] for which this error was detected.
///
/// This is different from the version reported by the
/// [`minimum_version`](UnsupportedSyntaxErrorKind::minimum_version) method, which is the
/// earliest allowed version for this piece of syntax. The `target_version` is primarily used
/// for user-facing error messages.
pub target_version: PythonVersion,
}

Expand All @@ -449,6 +444,7 @@ pub enum UnsupportedSyntaxErrorKind {
Match,
Walrus,
ExceptStar,
ParenthesizedKeywordArgumentName,
TypeAliasStatement,
TypeParamDefault,
}
Expand All @@ -459,29 +455,71 @@ impl Display for UnsupportedSyntaxError {
UnsupportedSyntaxErrorKind::Match => "Cannot use `match` statement",
UnsupportedSyntaxErrorKind::Walrus => "Cannot use named assignment expression (`:=`)",
UnsupportedSyntaxErrorKind::ExceptStar => "Cannot use `except*`",
UnsupportedSyntaxErrorKind::ParenthesizedKeywordArgumentName => {
"Cannot use parenthesized keyword argument name"
}
UnsupportedSyntaxErrorKind::TypeAliasStatement => "Cannot use `type` alias statement",
UnsupportedSyntaxErrorKind::TypeParamDefault => {
"Cannot set default type for a type parameter"
}
};

let (changed, changed_version) = self.kind.changed_version();

write!(
f,
"{kind} on Python {} (syntax was added in Python {})",
"{kind} on Python {} (syntax was {changed} in Python {changed_version})",
self.target_version,
self.kind.minimum_version(),
)
}
}

/// Represents the kind of change in Python syntax between versions.
///
/// Most changes so far have been additions (e.g. `match` and `type` statements), but others are
/// removals (e.g. parenthesized keyword argument names).
enum Change {
Added,
Removed,
}

impl Display for Change {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Change::Added => f.write_str("added"),
Change::Removed => f.write_str("removed"),
}
}
}

impl UnsupportedSyntaxErrorKind {
/// The earliest allowed version for the syntax associated with this error.
pub const fn minimum_version(&self) -> PythonVersion {
/// Returns the Python version when the syntax associated with this error was changed, and the
/// type of [`Change`] (added or removed).
const fn changed_version(self) -> (Change, PythonVersion) {
match self {
UnsupportedSyntaxErrorKind::Match => (Change::Added, PythonVersion::PY310),
UnsupportedSyntaxErrorKind::Walrus => (Change::Added, PythonVersion::PY38),
UnsupportedSyntaxErrorKind::ExceptStar => (Change::Added, PythonVersion::PY311),
UnsupportedSyntaxErrorKind::ParenthesizedKeywordArgumentName => {
(Change::Removed, PythonVersion::PY38)
}
UnsupportedSyntaxErrorKind::TypeAliasStatement => (Change::Added, PythonVersion::PY312),
UnsupportedSyntaxErrorKind::TypeParamDefault => (Change::Added, PythonVersion::PY313),
}
}

/// Returns whether or not this kind of syntax is unsupported on `target_version`.
pub(crate) fn is_unsupported(self, target_version: PythonVersion) -> bool {
let (_, version) = self.changed_version();
match self {
UnsupportedSyntaxErrorKind::Match => PythonVersion::PY310,
UnsupportedSyntaxErrorKind::Walrus => PythonVersion::PY38,
UnsupportedSyntaxErrorKind::ExceptStar => PythonVersion::PY311,
UnsupportedSyntaxErrorKind::TypeAliasStatement => PythonVersion::PY312,
UnsupportedSyntaxErrorKind::TypeParamDefault => PythonVersion::PY313,
UnsupportedSyntaxErrorKind::Match
| UnsupportedSyntaxErrorKind::Walrus
| UnsupportedSyntaxErrorKind::ExceptStar
| UnsupportedSyntaxErrorKind::TypeAliasStatement
| UnsupportedSyntaxErrorKind::TypeParamDefault => target_version < version,
UnsupportedSyntaxErrorKind::ParenthesizedKeywordArgumentName => {
target_version >= version
}
}
}
}
Expand Down
51 changes: 39 additions & 12 deletions crates/ruff_python_parser/src/parser/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ impl<'src> Parser<'src> {

ParsedExpr {
expr: self.parse_postfix_expression(lhs.expr, start),
is_parenthesized: lhs.is_parenthesized,
end_parenthesis: lhs.end_parenthesis,
}
}

Expand All @@ -419,7 +419,7 @@ impl<'src> Parser<'src> {
fn parse_expression_with_bitwise_or_precedence(&mut self) -> ParsedExpr {
let parsed_expr = self.parse_conditional_expression_or_higher();

if parsed_expr.is_parenthesized {
if parsed_expr.is_parenthesized() {
// Parentheses resets the precedence, so we don't need to validate it.
return parsed_expr;
}
Expand Down Expand Up @@ -703,7 +703,28 @@ impl<'src> Parser<'src> {

if parser.eat(TokenKind::Equal) {
seen_keyword_argument = true;
let arg = if let Expr::Name(ident_expr) = parsed_expr.expr {
let arg = if let ParsedExpr {
expr: Expr::Name(ident_expr),
end_parenthesis,
} = parsed_expr
{
// test_ok parenthesized_kwarg_py37
// # parse_options: {"target-version": "3.7"}
// f((a)=1)

// test_err parenthesized_kwarg_py38
// # parse_options: {"target-version": "3.8"}
// f((a)=1)
// f((a) = 1)
// f( ( a ) = 1)

if let Some(end) = end_parenthesis {
parser.add_unsupported_syntax_error(
UnsupportedSyntaxErrorKind::ParenthesizedKeywordArgumentName,
TextRange::new(start, end),
);
}

ast::Identifier {
id: ident_expr.id,
range: ident_expr.range,
Expand Down Expand Up @@ -857,7 +878,7 @@ impl<'src> Parser<'src> {
return lower.expr;
}

if !lower.is_parenthesized {
if !lower.is_parenthesized() {
match lower.expr {
Expr::Starred(_) => {
self.add_error(ParseErrorType::InvalidStarredExpressionUsage, &lower);
Expand Down Expand Up @@ -1403,7 +1424,7 @@ impl<'src> Parser<'src> {
// f"{*yield x}"
let value = self.parse_expression_list(ExpressionContext::yield_or_starred_bitwise_or());

if !value.is_parenthesized && value.expr.is_lambda_expr() {
if !value.is_parenthesized() && value.expr.is_lambda_expr() {
// TODO(dhruvmanila): This requires making some changes in lambda expression
// parsing logic to handle the emitted `FStringMiddle` token in case the
// lambda expression is not parenthesized.
Expand Down Expand Up @@ -1614,7 +1635,7 @@ impl<'src> Parser<'src> {
TokenKind::Colon => {
// Now, we know that it's either a dictionary expression or a dictionary comprehension.
// In either case, the key is limited to an `expression`.
if !key_or_element.is_parenthesized {
if !key_or_element.is_parenthesized() {
match key_or_element.expr {
Expr::Starred(_) => self.add_error(
ParseErrorType::InvalidStarredExpressionUsage,
Expand Down Expand Up @@ -1693,7 +1714,7 @@ impl<'src> Parser<'src> {

ParsedExpr {
expr: tuple.into(),
is_parenthesized: false,
end_parenthesis: None,
}
}
TokenKind::Async | TokenKind::For => {
Expand All @@ -1713,7 +1734,7 @@ impl<'src> Parser<'src> {

ParsedExpr {
expr: generator,
is_parenthesized: false,
end_parenthesis: None,
}
}
_ => {
Expand All @@ -1724,7 +1745,7 @@ impl<'src> Parser<'src> {

self.expect(TokenKind::Rpar);

parsed_expr.is_parenthesized = true;
parsed_expr.end_parenthesis = Some(self.node_range(start).end());
parsed_expr
}
}
Expand Down Expand Up @@ -2330,13 +2351,19 @@ impl<'src> Parser<'src> {
#[derive(Debug)]
pub(super) struct ParsedExpr {
pub(super) expr: Expr,
pub(super) is_parenthesized: bool,
/// Contains the location of the closing parenthesis, if the expression is parenthesized
pub(super) end_parenthesis: Option<TextSize>,
}

impl ParsedExpr {
#[inline]
pub(super) const fn is_unparenthesized_starred_expr(&self) -> bool {
!self.is_parenthesized && self.expr.is_starred_expr()
!self.is_parenthesized() && self.expr.is_starred_expr()
}

#[inline]
pub(super) const fn is_parenthesized(&self) -> bool {
self.end_parenthesis.is_some()
}
}

Expand All @@ -2345,7 +2372,7 @@ impl From<Expr> for ParsedExpr {
fn from(expr: Expr) -> Self {
ParsedExpr {
expr,
is_parenthesized: false,
end_parenthesis: None,
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_python_parser/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ impl<'src> Parser<'src> {
/// Add an [`UnsupportedSyntaxError`] with the given [`UnsupportedSyntaxErrorKind`] and
/// [`TextRange`] if its minimum version is less than [`Parser::target_version`].
fn add_unsupported_syntax_error(&mut self, kind: UnsupportedSyntaxErrorKind, range: TextRange) {
if self.options.target_version < kind.minimum_version() {
if kind.is_unsupported(self.options.target_version) {
self.unsupported_syntax_errors.push(UnsupportedSyntaxError {
kind,
range,
Expand Down
6 changes: 3 additions & 3 deletions crates/ruff_python_parser/src/parser/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,7 @@ impl<'src> Parser<'src> {
IpyEscapeKind::Help
};

if parsed_expr.is_parenthesized {
if parsed_expr.is_parenthesized() {
let token_range = self.node_range(start);
self.add_error(
ParseErrorType::OtherError(
Expand Down Expand Up @@ -1150,7 +1150,7 @@ impl<'src> Parser<'src> {
// (a): int
// a.b: int
// a[0]: int
let simple = target.is_name_expr() && !target.is_parenthesized;
let simple = target.is_name_expr() && !target.is_parenthesized();

// test_err ann_assign_stmt_invalid_annotation
// x: *int = 1
Expand Down Expand Up @@ -2170,7 +2170,7 @@ impl<'src> Parser<'src> {
.then(|| Box::new(self.parse_with_item_optional_vars().expr));

ParsedWithItem {
is_parenthesized: context_expr.is_parenthesized,
is_parenthesized: context_expr.is_parenthesized(),
item: ast::WithItem {
range: self.node_range(start),
context_expr: context_expr.expr,
Expand Down
Loading
Loading