Skip to content

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

Merged
JelleZijlstra merged 8 commits into
python:mainfrom
Twix1288:fix-unary-add-ast-match
Sep 24, 2026
Merged

JelleZijlstra merged 8 commits into
python:mainfrom
Twix1288:fix-unary-add-ast-match

Conversation

@Twix1288

@Twix1288 Twix1288 commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

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 Jun 30, 2026
@ZeroIntensity
ZeroIntensity requested a review from johnslavik July 1, 2026 08:14
@JelleZijlstra

Copy link
Copy Markdown
Member

Does this affect the bytecode generated for this code? If so, we likely shouldn't change this in 3.15.

@Twix1288

Twix1288 commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Yeah, I'm 100% sure. Basically, the parser used to just silently drop the + in stuff like +1 in match cases, and now we make it properly keep it as a UnaryOp node. Then, in ast_preprocess.c, we just fold that node back into a plain number. Because the optimizer ends up seeing the exact same value it always did, it spits out the exact same LOAD_CONST bytecode.

@johnslavik johnslavik self-assigned this Jul 7, 2026
@Eclips4

Eclips4 commented Jul 8, 2026

Copy link
Copy Markdown
Member

Can you please provide dis output?

@Twix1288

Twix1288 commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor Author

From what we can see about dis output below, the AST optimizer automatically folds the unary + before bytecode generation, resolving both +1 and 1 + +2j into identical constants as if the + were omitted.

import dis

def test_match(x):
    match x:
        case +1:
            pass
        case 1 + +2j:
            pass

dis.dis(test_match)

Output:

  4           RESUME                   0

  5           LOAD_FAST                0 (x)

  6           COPY                     1
              LOAD_SMALL_INT           1         <--- +1 is folded cleanly
              COMPARE_OP              88 (bool(==))
              POP_JUMP_IF_FALSE        4 (to L1)
              NOT_TAKEN
              POP_TOP
              LOAD_COMMON_CONSTANT     7 (None)
              RETURN_VALUE

  7   L1:     LOAD_CONST               1 ((1+2j)) <--- 1 + +2j is folded cleanly
              COMPARE_OP              88 (bool(==))
              POP_JUMP_IF_FALSE        3 (to L2)
              NOT_TAKEN
              LOAD_COMMON_CONSTANT     7 (None)
              RETURN_VALUE
      L2:     LOAD_COMMON_CONSTANT     7 (None)
              RETURN_VALUE

Because the values are perfectly folded to the same underlying numeric objects (LOAD_SMALL_INT 1 and LOAD_CONST (1+2j)), the compiled execution path is entirely identical. It is perfectly safe for 3.15.

@johnslavik

Copy link
Copy Markdown
Member

Thank you so much for tackling this.

Support for 1 + +2j was reverted (see #154776).

@johnslavik

Copy link
Copy Markdown
Member

@Twix1288 would you like to fix the conflicts, or do you want some help?

@15r10nk

15r10nk commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

@Twix1288 @johnslavik, how likely is it that this will become part of 3.15?

@johnslavik

Copy link
Copy Markdown
Member

@15r10nk it's a bugfix, so very likely. Just waiting on the conflicts to be resolved. After some time I can take this over.

@encukou

encukou commented Aug 24, 2026

Copy link
Copy Markdown
Member

@johnslavik, do you still want to take this over?

@johnslavik

Copy link
Copy Markdown
Member

@encukou, yes. I'll push final touches to this PR soon and ping you. Ok?

@encukou

encukou commented Aug 25, 2026

Copy link
Copy Markdown
Member

Sounds good. Or I can do it.

@encukou

encukou commented Sep 7, 2026

Copy link
Copy Markdown
Member

I did -- fixed conflicts; added a test.

Comment thread Python/ast_preprocess.c Resolved
Comment thread Python/ast_preprocess.c Resolved
Comment thread Python/ast_preprocess.c Resolved
Comment thread Python/ast.c Resolved
@johnslavik

Copy link
Copy Markdown
Member

Since I approved this, I'll address @pablogsal review.

@johnslavik
johnslavik requested a review from pablogsal September 8, 2026 00:06
@15r10nk

15r10nk commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

@johnslavik what is the state of this pr? can I help somehow?

@JelleZijlstra
JelleZijlstra merged commit 7884f48 into python:main Sep 24, 2026
55 checks passed
@15r10nk

15r10nk commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

@JelleZijlstra will this fix be backported to 3.15? I ask because I see no special tag anywhere, but it reported the original bug for 3.15.

@JelleZijlstra JelleZijlstra added the needs backport to 3.15 bugs and security fixes label Sep 24, 2026
@miss-islington-app

Copy link
Copy Markdown

Thanks @Twix1288 for the PR, and @JelleZijlstra for merging it 🌮🎉.. I'm working now to backport this PR to: 3.15.
🐍🍒⛏🤖

@bedevere-app

bedevere-app Bot commented Sep 24, 2026

Copy link
Copy Markdown

GH-158079 is a backport of this pull request to the 3.15 branch.

@bedevere-app bedevere-app Bot removed the needs backport to 3.15 bugs and security fixes label Sep 24, 2026
pablogsal pushed a commit that referenced this pull request Sep 24, 2026
…match statements (GH-152712) (#158079)

gh-152708: Fix AST generation asymmetry for unary positive in match statements (GH-152712)
(cherry picked from commit 7884f48)

Co-authored-by: Rishit Agnihotri <67520802+Twix1288@users.noreply.github.com>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Co-authored-by: johnslavik <bartosz@ilikepython.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

7 participants