pycdc/tests/input/match_statement.py
Mario Penterman 7ff27dfec5 Reconstruct 3.10+ match/case (structural pattern matching)
pycdc did not reconstruct `match` statements: class patterns hit the
unhandled MATCH_CLASS opcode and bailed to "# WARNING: Decompyle incomplete",
and value patterns were mis-rendered as an if/elif chain.

This adds reconstruction of the common, statically-recognizable shapes:

  * Class patterns - `case Cls(a, b):` - including positional captures and
    `_` wildcard sub-patterns (`case Cls(_):`).
  * Value patterns - `case 0:` / `case 'x':` - compiled as a COPY-threaded
    COMPARE_OP chain rather than MATCH_CLASS.
  * The `case _:` wildcard (which carries no test opcode).

A pre-scan over the code object recognizes the simple, guard-free shape of
each case and records it; the MATCH_CLASS handler and a small guarded hook in
COMPARE_OP open ASTMatchBlock/ASTCaseBlock and skip the pattern-test
machinery, and the block-close logic closes each case at its fail-target and
the match at its merge. Anything outside the recognized shape (kwarg patterns,
guards, sequence/mapping patterns) is left unregistered and still bails
honestly, so no incorrect output is produced.

New AST nodes: ASTMatchBlock (subject) and ASTCaseBlock (pattern), rendered
via the existing block-header machinery (type_str + print_src). PycBuffer
gains setPos() so the reconstructor can skip to a case body.

All hooks are guarded by per-offset match tables that are empty for code
without a match statement, so non-match input is unaffected.

Test: tests/input/match_statement.py exercises class patterns, a wildcard
sub-pattern, value patterns and `case _`. Full existing suite still passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 17:37:02 +02:00

25 lines
579 B
Python

# 3.10+ structural pattern matching (match/case) reconstruction.
def describe_point(command):
match command:
case Point(x, y):
return f'point {x},{y}'
case Rect(w, h):
return f'rect {w}x{h}'
case Wrapper(_):
return 'wrapped'
case _:
return 'unknown'
def classify(value):
match value:
case 0:
result = 'zero'
case 1:
result = 'one'
case 'hello':
result = 'greeting'
case _:
result = 'other'
return result