|
| 1 | +import ast |
| 2 | + |
| 3 | + |
| 4 | +def is_wildcard_pattern(case: ast.match_case) -> bool: |
| 5 | + """Returns True only for `case _:`.""" |
| 6 | + pattern = case.pattern |
| 7 | + return ( |
| 8 | + isinstance(pattern, ast.MatchAs) |
| 9 | + and pattern.pattern is None |
| 10 | + and pattern.name is None |
| 11 | + ) |
| 12 | + |
| 13 | + |
| 14 | +def is_simple_pattern(pattern: ast.pattern) -> bool: |
| 15 | + """Returns True if the pattern is simple enough to replace with `==`.""" |
| 16 | + return _is_simple_value_or_singleton(pattern) or _is_simple_composite( |
| 17 | + pattern |
| 18 | + ) |
| 19 | + |
| 20 | + |
| 21 | +def _is_simple_composite(pattern: ast.pattern) -> bool: |
| 22 | + """Returns True/False for MatchOr and MatchAs, None otherwise.""" |
| 23 | + if isinstance(pattern, ast.MatchOr): |
| 24 | + return all(is_simple_pattern(sub) for sub in pattern.patterns) |
| 25 | + if isinstance(pattern, ast.MatchAs): |
| 26 | + inner = pattern.pattern |
| 27 | + return inner is not None and is_simple_pattern(inner) |
| 28 | + return False |
| 29 | + |
| 30 | + |
| 31 | +def _is_simple_value_or_singleton(pattern: ast.pattern) -> bool: |
| 32 | + """ |
| 33 | + Checks if a pattern is a simple literal or singleton. |
| 34 | +
|
| 35 | + Supports: |
| 36 | + - Single values: ``1``, ``"text"``, ``ns.CONST``. |
| 37 | + - Singleton values: ``True``, ``False``, ``None``. |
| 38 | + """ |
| 39 | + if isinstance(pattern, ast.MatchSingleton): |
| 40 | + return True |
| 41 | + if isinstance(pattern, ast.MatchValue): |
| 42 | + return isinstance( |
| 43 | + pattern.value, (ast.Constant, ast.Name, ast.Attribute) |
| 44 | + ) |
| 45 | + return False |
| 46 | + |
| 47 | + |
| 48 | +def is_irrefutable_binding(pattern: ast.pattern) -> bool: |
| 49 | + """ |
| 50 | + Returns True for patterns like ``case x:`` or ``case data:``. |
| 51 | +
|
| 52 | + These always match and just bind the subject to a name. |
| 53 | + """ |
| 54 | + return ( |
| 55 | + isinstance(pattern, ast.MatchAs) |
| 56 | + and pattern.pattern is None |
| 57 | + and pattern.name is not None |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def is_simple_sequence_or_mapping_pattern(pattern: ast.pattern) -> bool: |
| 62 | + """ |
| 63 | + Check that all elements in sequence/mapping are simple. |
| 64 | +
|
| 65 | + Simple is (literals, constants, names). |
| 66 | + """ |
| 67 | + if isinstance(pattern, ast.MatchSequence): |
| 68 | + return all(is_simple_pattern(pattern) for pattern in pattern.patterns) |
| 69 | + if isinstance(pattern, ast.MatchMapping): |
| 70 | + return all(is_simple_pattern(pattern) for pattern in pattern.patterns) |
| 71 | + return False |
0 commit comments