|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
| 5 | +from collections.abc import Mapping |
5 | 6 | from dataclasses import fields, is_dataclass, replace |
6 | 7 | from typing import Any, ClassVar |
7 | 8 |
|
@@ -31,7 +32,10 @@ def __init__(self, block_id: BlockId) -> None: |
31 | 32 |
|
32 | 33 |
|
33 | 34 | class _Builder: |
34 | | - def __init__(self, function: nodes.Function) -> None: |
| 35 | + def __init__( |
| 36 | + self, function: nodes.Function, match_args: Mapping[str, tuple[str, ...]] | None = None |
| 37 | + ) -> None: |
| 38 | + self.match_args = dict(match_args or {}) |
35 | 39 | self.function = function |
36 | 40 | self.blocks: dict[BlockId, BasicBlock] = {} |
37 | 41 | self.counters: dict[str, int] = {} |
@@ -59,12 +63,28 @@ def desugared(self, node: nodes.Statement, block: _Open) -> tuple[nodes.Statemen |
59 | 63 |
|
60 | 64 | pending: list[nodes.Statement] = [] |
61 | 65 | if isinstance(node, nodes.While): |
62 | | - if _has_control_flow(node.condition): |
63 | | - raise CFGError( |
64 | | - f"{node.span.display()}: conditional expressions and comprehensions in a " |
65 | | - "loop condition are not supported yet" |
66 | | - ) |
67 | | - return node, block |
| 66 | + if not _has_control_flow(node.condition): |
| 67 | + return node, block |
| 68 | + # ``while <control flow>:`` recomputes its condition every iteration: it |
| 69 | + # becomes ``while True`` with the condition laid out at the top of the body |
| 70 | + # and a ``break``; the ``else`` clause runs before that ``break``. |
| 71 | + inner: list[nodes.Statement] = [] |
| 72 | + condition = self.hoist(node.condition, inner) |
| 73 | + stop = nodes.If( |
| 74 | + nodes.UnaryOp("not", condition, node.span), |
| 75 | + (*node.orelse, nodes.Break(node.span)), |
| 76 | + (), |
| 77 | + node.span, |
| 78 | + ) |
| 79 | + return ( |
| 80 | + replace( |
| 81 | + node, |
| 82 | + condition=nodes.Constant(True, node.span), |
| 83 | + body=(*inner, stop, *node.body), |
| 84 | + orelse=(), |
| 85 | + ), |
| 86 | + block, |
| 87 | + ) |
68 | 88 | if isinstance(node, nodes.Assign | nodes.AugAssign): |
69 | 89 | node = replace(node, target=self.hoist(node.target, pending), value=self.hoist(node.value, pending)) |
70 | 90 | elif isinstance(node, nodes.ExpressionStatement): |
@@ -430,16 +450,17 @@ def class_pattern( |
430 | 450 | """``Cls(name=pattern)``: an instance of the class whose attributes match.""" |
431 | 451 |
|
432 | 452 | span = node.span |
433 | | - if node.patterns: |
434 | | - raise CFGError( |
435 | | - f"{span.display()}: positional class patterns need the class's __match_args__ " |
436 | | - "and are not supported yet" |
437 | | - ) |
438 | 453 | conditions: list[nodes.Expression] = [ |
439 | 454 | nodes.Call(nodes.Name("isinstance", span), (subject, node.cls), (), span) |
440 | 455 | ] |
441 | 456 | bindings: list[nodes.Statement] = [] |
442 | | - for name, sub in zip(node.keyword_names, node.keyword_patterns, strict=True): |
| 457 | + # Positional sub-patterns match the attributes ``__match_args__`` names, known |
| 458 | + # for the module's classes; an unknown class gets a conservative position. |
| 459 | + known = self.match_args.get(node.cls.identifier, ()) if isinstance(node.cls, nodes.Name) else () |
| 460 | + positional = [ |
| 461 | + (known[i] if i < len(known) else f"_match_arg_{i}", sub) for i, sub in enumerate(node.patterns) |
| 462 | + ] |
| 463 | + for name, sub in (*positional, *zip(node.keyword_names, node.keyword_patterns, strict=True)): |
443 | 464 | condition, inner = self.pattern(sub, nodes.Attribute(subject, name, span)) |
444 | 465 | conditions.append(condition) |
445 | 466 | bindings.extend(inner) |
@@ -521,13 +542,48 @@ def _rename_target(target: nodes.Target, renames: dict[str, str]) -> nodes.Targe |
521 | 542 | return renamed |
522 | 543 |
|
523 | 544 |
|
524 | | -def build_cfg(function: nodes.Function) -> CFG: |
525 | | - return _Builder(function).build() |
| 545 | +def build_cfg(function: nodes.Function, match_args: Mapping[str, tuple[str, ...]] | None = None) -> CFG: |
| 546 | + return _Builder(function, match_args).build() |
| 547 | + |
| 548 | + |
| 549 | +def match_args_of(module: nodes.Module) -> dict[str, tuple[str, ...]]: |
| 550 | + """``__match_args__`` of the module's classes: explicit, or the field order of a |
| 551 | + dataclass (bare annotated declarations and assignments, in order).""" |
| 552 | + |
| 553 | + found: dict[str, tuple[str, ...]] = {} |
| 554 | + for statement in module.body: |
| 555 | + if not isinstance(statement, nodes.Class): |
| 556 | + continue |
| 557 | + explicit = None |
| 558 | + fields: list[str] = [] |
| 559 | + for member in statement.body: |
| 560 | + if isinstance(member, nodes.Assign) and isinstance(member.target, nodes.Name): |
| 561 | + if member.target.identifier == "__match_args__" and isinstance(member.value, nodes.Tuple | nodes.List): |
| 562 | + explicit = tuple( |
| 563 | + e.value for e in member.value.elements if isinstance(e, nodes.Constant) and isinstance(e.value, str) |
| 564 | + ) |
| 565 | + elif not member.target.identifier.startswith("_"): |
| 566 | + fields.append(member.target.identifier) |
| 567 | + elif isinstance(member, nodes.Declaration): |
| 568 | + fields.append(member.name) |
| 569 | + if explicit is not None: |
| 570 | + found[statement.name] = explicit |
| 571 | + elif any(_is_dataclass(d) for d in statement.decorators): |
| 572 | + found[statement.name] = tuple(fields) |
| 573 | + return found |
| 574 | + |
| 575 | + |
| 576 | +def _is_dataclass(decorator: nodes.Expression) -> bool: |
| 577 | + if isinstance(decorator, nodes.Call): |
| 578 | + decorator = decorator.callee |
| 579 | + if isinstance(decorator, nodes.Name): |
| 580 | + return decorator.identifier == "dataclass" |
| 581 | + return isinstance(decorator, nodes.Attribute) and decorator.name == "dataclass" |
526 | 582 |
|
527 | 583 |
|
528 | 584 | class CFGAnalysis(FunctionAnalysis[CFG]): |
529 | 585 | name: ClassVar[str] = "cfg.function" |
530 | 586 |
|
531 | 587 | @classmethod |
532 | 588 | def compute(cls, ctx: AnalysisContext, function: nodes.Function) -> CFG: |
533 | | - return build_cfg(function) |
| 589 | + return build_cfg(function, match_args_of(ctx.module)) |
0 commit comments