Skip to content

gh-152708: Fix AST generation asymmetry for unary positive in match statements#152712

Open
Twix1288 wants to merge 3 commits into
python:mainfrom
Twix1288:fix-unary-add-ast-match
Open

gh-152708: Fix AST generation asymmetry for unary positive in match statements#152712
Twix1288 wants to merge 3 commits into
python:mainfrom
Twix1288:fix-unary-add-ast-match

Conversation

@Twix1288

@Twix1288 Twix1288 commented Jun 30, 2026

Copy link
Copy Markdown

This PR fixes an asymmetry in AST generation where a unary positive in a pattern match expression (e.g., case +0:) was parsed directly as a Constant (implicitly dropping the + sign), whereas a unary negative (e.g., case -0:) correctly generated a UnaryOp(USub, Constant). This led to round-trip parsing inconsistencies with ast.unparse.

Changes:

  1. Grammar/python.gram: Updated the rules for signed_number, signed_real_number, and imaginary_number to retain + prefixes as _PyAST_UnaryOp(UAdd, ...), restoring parity with - behavior.
  2. Python/ast.c: Refactored the AST pattern matching validator ensure_literal_negative into ensure_literal_signed to permit both USub and UAdd unary operations in literal matching.
  3. Python/ast_preprocess.c: Added support for folding UAdd operations recursively within fold_const_match_patterns so that the compiler optimizer correctly resolves unary additions to positive constants without triggering compiler validation syntax errors.

Fixes #148566

@bedevere-app

bedevere-app Bot commented Jun 30, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

1 similar comment
@bedevere-app

bedevere-app Bot commented Jun 30, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@Twix1288 Twix1288 force-pushed the fix-unary-add-ast-match branch 2 times, most recently from a3d05fc to fe42b12 Compare June 30, 2026 21:54
@Twix1288 Twix1288 force-pushed the fix-unary-add-ast-match branch from fe42b12 to 6a7d2f2 Compare June 30, 2026 21:54
@Twix1288 Twix1288 changed the title gh-148566: Fix AST generation asymmetry for unary positive in match statements gh-152708: Fix AST generation asymmetry for unary positive in match statements Jun 30, 2026
@ZeroIntensity ZeroIntensity requested a review from johnslavik July 1, 2026 08:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant