Skip to content

wake.analysis.cfg module #

TransitionConditionKind class #

Bases: StrEnum

Source code in wake/analysis/cfg.py
class TransitionConditionKind(StrEnum):
    IS_TRUE = "is true"
    """
    Associated expression evaluates to true.
    """
    IS_FALSE = "is false"
    """
    Associated expression evaluates to false.
    """
    ALWAYS = "always"
    """
    Transition is always taken.
    """
    NEVER = "never"
    """
    Transition is never taken.
    """
    TRY_SUCCEEDED = "try succeeded"
    """
    Try call succeeded.
    """
    TRY_REVERTED = "try reverted"
    """
    Try call reverted with a string reason.
    """
    TRY_PANICKED = "try panicked"
    """
    Try call panicked with an uint256 error code.
    """
    TRY_FAILED = "try failed"
    """
    Try call failed with a bytes memory reason.
    """
    SWITCH_MATCHED = "switch matched"
    """
    Yul switch case value matched the switch expression.
    """
    SWITCH_DEFAULT = "switch default"
    """
    None of the Yul switch case values matched the switch expression.
    """

IS_TRUE = 'is true' class-attribute instance-attribute #

Associated expression evaluates to true.

IS_FALSE = 'is false' class-attribute instance-attribute #

Associated expression evaluates to false.

ALWAYS = 'always' class-attribute instance-attribute #

Transition is always taken.

NEVER = 'never' class-attribute instance-attribute #

Transition is never taken.

TRY_SUCCEEDED = 'try succeeded' class-attribute instance-attribute #

Try call succeeded.

TRY_REVERTED = 'try reverted' class-attribute instance-attribute #

Try call reverted with a string reason.

TRY_PANICKED = 'try panicked' class-attribute instance-attribute #

Try call panicked with an uint256 error code.

TRY_FAILED = 'try failed' class-attribute instance-attribute #

Try call failed with a bytes memory reason.

SWITCH_MATCHED = 'switch matched' class-attribute instance-attribute #

Yul switch case value matched the switch expression.

SWITCH_DEFAULT = 'switch default' class-attribute instance-attribute #

None of the Yul switch case values matched the switch expression.

ControlFlowGraph class #

Control flow graph for a function or a modifier. Uses NetworkX DiGraph as the underlying data structure.

Holds the following invariants:

Tip

The Tools for Solidity VS Code extension provides a visualizer for CFGs. The visualized CFGs are stripped of empty nodes, so they may slightly differ from the CFGs constructed by this class.

Source code in wake/analysis/cfg.py
class ControlFlowGraph:
    """
    Control flow graph for a function or a modifier. Uses NetworkX [DiGraph](https://networkx.org/documentation/stable/reference/classes/digraph.html) as the underlying data structure.

    Holds the following invariants:

    - all nodes are of [CfgNode][wake.analysis.cfg.CfgNode] type,
    - [start_node][wake.analysis.cfg.ControlFlowGraph.start_node], [success_end_node][wake.analysis.cfg.ControlFlowGraph.success_end_node] and [revert_end_node][wake.analysis.cfg.ControlFlowGraph.revert_end_node] are always present and empty (i.e. they contain no statements),
    - all edges have a `condition` attribute holding a 2-item tuple:
        - the first item is a [TransitionConditionKind][wake.analysis.cfg.TransitionConditionKind] enum value,
        - the second item is an optional [ExpressionAbc][wake.ir.expressions.abc.ExpressionAbc] instance.

    !!! tip
        The [Tools for Solidity](https://marketplace.visualstudio.com/items?itemName=AckeeBlockchain.tools-for-solidity) VS Code extension provides a visualizer for CFGs.
        The visualized CFGs are stripped of empty nodes, so they may slightly differ from the CFGs constructed by this class.
    """

    _graph: nx.DiGraph
    _declaration: Union[FunctionDefinition, ModifierDefinition, YulFunctionDefinition]
    _statements_lookup: Dict[Union[StatementAbc, YulStatementAbc], CfgNode]
    _start_node: CfgNode
    _success_end_node: CfgNode
    _revert_end_node: CfgNode

    def __init__(
        self,
        declaration: Union[
            FunctionDefinition, ModifierDefinition, YulFunctionDefinition
        ],
    ):
        if declaration.body is None:
            raise ValueError("Function body is None.")
        self._declaration = declaration

        self._graph = nx.DiGraph()
        self._start_node = CfgNode()
        self._graph.add_node(self._start_node)
        next_node = CfgNode()
        self._graph.add_node(next_node)
        self._graph.add_edge(
            self._start_node,
            next_node,
            condition=(TransitionConditionKind.ALWAYS, None),
        )
        self._success_end_node = CfgNode()
        self._graph.add_node(self._success_end_node)
        self._revert_end_node = CfgNode()
        self._graph.add_node(self._revert_end_node)

        tmp = CfgNode.from_statement(
            self._graph,
            next_node,
            self._success_end_node,
            self._revert_end_node,
            None,
            None,
            declaration.body,
        )
        self._graph.add_edge(
            tmp,
            self._success_end_node,
            condition=(TransitionConditionKind.ALWAYS, None),
        )

        while _normalize(
            self._graph,
            self._start_node,
            self._success_end_node,
            self._revert_end_node,
        ):
            pass

        self._statements_lookup = {
            stmt: node for node in self._graph.nodes for stmt in node.statements
        }
        for node in self._graph.nodes:
            for stmt in node.statements:
                self._statements_lookup[stmt] = node
            if node.control_statement is not None:
                self._statements_lookup[node.control_statement] = node

    @property
    def graph(self) -> nx.DiGraph:
        """
        Returns:
            Read-only view of the underlying NetworkX DiGraph.
        """
        return self._graph.copy(as_view=True)

    @property
    def declaration(
        self,
    ) -> Union[FunctionDefinition, ModifierDefinition, YulFunctionDefinition]:
        """
        Returns:
            Function or modifier definition for which this CFG was constructed.
        """
        return self._declaration

    @property
    def start_node(self) -> CfgNode:
        """
        Start node is guaranteed to be empty, i.e. it has no statements.

        Returns:
            Start node of this CFG, i.e. the node that is always executed first.
        """
        return self._start_node

    @property
    def success_end_node(self) -> CfgNode:
        """
        Success end node is guaranteed to be empty, i.e. it has no statements.

        Returns:
            Success end node of this CFG, i.e. the node that is always executed last if the function or modifier does not revert.
        """
        return self._success_end_node

    @property
    def revert_end_node(self) -> CfgNode:
        """
        Revert end node is guaranteed to be empty, i.e. it has no statements.

        Returns:
            Revert end node of this CFG, signaling that the function or modifier reverted under some condition.
        """
        return self._revert_end_node

    def get_cfg_node(self, statement: Union[StatementAbc, YulStatementAbc]) -> CfgNode:
        """
        Raises:
            KeyError: If the given statement is not contained in this CFG or if the statement is of the
                [Block][wake.ir.statements.block.Block], [UncheckedBlock][wake.ir.statements.unchecked_block.UncheckedBlock],
                [YulBlock][wake.ir.yul.block.YulBlock] or [InlineAssembly][wake.ir.statements.inline_assembly.InlineAssembly] type.


        [Block][wake.ir.statements.block.Block], [UncheckedBlock][wake.ir.statements.block.UncheckedBlock], [YulBlock][wake.ir.yul.block.YulBlock] and [InlineAssembly][wake.ir.statements.inline_assembly.InlineAssembly] statements
        serve as containers for other statements and so may be contained in multiple CFG nodes. For this reason, a single [CfgNode][wake.analysis.cfg.CfgNode] cannot be returned for these statements.

        Args:
            statement: Statement for which to get the CFG node.

        Returns:
            CFG node that contains the given statement.
        """
        return self._statements_lookup[statement]

    def is_reachable(
        self,
        start: Union[StatementAbc, YulStatementAbc],
        end: Union[StatementAbc, YulStatementAbc],
    ) -> bool:
        """
        Args:
            start: Statement that is expected to be executed before `end`.
            end: Statement that is expected to be executed after `start`.

        Returns:
            True if there is an execution path from `start` to `end` in this CFG, False otherwise.
        """
        start_node = self._statements_lookup[start]
        end_node = self._statements_lookup[end]
        if start_node == end_node:
            if end == end_node.control_statement:
                return True
            start_index = start_node.statements.index(start)
            end_index = end_node.statements.index(end)
            if start_index <= end_index:  # also EQUAL?
                return True
            try:
                nx.find_cycle(self._graph, start_node)
                return True
            except nx.NetworkXNoCycle:
                return False
        else:
            return nx.has_path(self._graph, start_node, end_node)

graph: nx.DiGraph property #

Returns:

Type Description
DiGraph

Read-only view of the underlying NetworkX DiGraph.

declaration: Union[FunctionDefinition, ModifierDefinition, YulFunctionDefinition] property #

Returns:

Type Description
Union[FunctionDefinition, ModifierDefinition, YulFunctionDefinition]

Function or modifier definition for which this CFG was constructed.

start_node: CfgNode property #

Start node is guaranteed to be empty, i.e. it has no statements.

Returns:

Type Description
CfgNode

Start node of this CFG, i.e. the node that is always executed first.

success_end_node: CfgNode property #

Success end node is guaranteed to be empty, i.e. it has no statements.

Returns:

Type Description
CfgNode

Success end node of this CFG, i.e. the node that is always executed last if the function or modifier does not revert.

revert_end_node: CfgNode property #

Revert end node is guaranteed to be empty, i.e. it has no statements.

Returns:

Type Description
CfgNode

Revert end node of this CFG, signaling that the function or modifier reverted under some condition.

get_cfg_node(statement) #

Raises:

Type Description
KeyError

If the given statement is not contained in this CFG or if the statement is of the Block, UncheckedBlock, YulBlock or InlineAssembly type.

Block, UncheckedBlock, YulBlock and InlineAssembly statements serve as containers for other statements and so may be contained in multiple CFG nodes. For this reason, a single CfgNode cannot be returned for these statements.

Parameters:

Name Type Description Default
statement Union[StatementAbc, YulStatementAbc]

Statement for which to get the CFG node.

required

Returns:

Type Description
CfgNode

CFG node that contains the given statement.

Source code in wake/analysis/cfg.py
def get_cfg_node(self, statement: Union[StatementAbc, YulStatementAbc]) -> CfgNode:
    """
    Raises:
        KeyError: If the given statement is not contained in this CFG or if the statement is of the
            [Block][wake.ir.statements.block.Block], [UncheckedBlock][wake.ir.statements.unchecked_block.UncheckedBlock],
            [YulBlock][wake.ir.yul.block.YulBlock] or [InlineAssembly][wake.ir.statements.inline_assembly.InlineAssembly] type.


    [Block][wake.ir.statements.block.Block], [UncheckedBlock][wake.ir.statements.block.UncheckedBlock], [YulBlock][wake.ir.yul.block.YulBlock] and [InlineAssembly][wake.ir.statements.inline_assembly.InlineAssembly] statements
    serve as containers for other statements and so may be contained in multiple CFG nodes. For this reason, a single [CfgNode][wake.analysis.cfg.CfgNode] cannot be returned for these statements.

    Args:
        statement: Statement for which to get the CFG node.

    Returns:
        CFG node that contains the given statement.
    """
    return self._statements_lookup[statement]

is_reachable(start, end) #

Parameters:

Name Type Description Default
start Union[StatementAbc, YulStatementAbc]

Statement that is expected to be executed before end.

required
end Union[StatementAbc, YulStatementAbc]

Statement that is expected to be executed after start.

required

Returns:

Type Description
bool

True if there is an execution path from start to end in this CFG, False otherwise.

Source code in wake/analysis/cfg.py
def is_reachable(
    self,
    start: Union[StatementAbc, YulStatementAbc],
    end: Union[StatementAbc, YulStatementAbc],
) -> bool:
    """
    Args:
        start: Statement that is expected to be executed before `end`.
        end: Statement that is expected to be executed after `start`.

    Returns:
        True if there is an execution path from `start` to `end` in this CFG, False otherwise.
    """
    start_node = self._statements_lookup[start]
    end_node = self._statements_lookup[end]
    if start_node == end_node:
        if end == end_node.control_statement:
            return True
        start_index = start_node.statements.index(start)
        end_index = end_node.statements.index(end)
        if start_index <= end_index:  # also EQUAL?
            return True
        try:
            nx.find_cycle(self._graph, start_node)
            return True
        except nx.NetworkXNoCycle:
            return False
    else:
        return nx.has_path(self._graph, start_node, end_node)

CfgNode class #

Basic building block of a control flow graph. Holds a list of statements and an optional control statement that is always executed last (if set). Solidity and Yul statements may be mixed in the same CFG node.

Source code in wake/analysis/cfg.py
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
class CfgNode:
    """
    Basic building block of a control flow graph. Holds a list of statements and an optional control statement that is always
    executed last (if set). Solidity and Yul statements may be mixed in the same CFG node.
    """

    _id_counter: int = 0
    _id: int
    _statements: List[Union[StatementAbc, YulStatementAbc]]
    # control statement is always the last statement
    _control_statement: Optional[
        Union[
            DoWhileStatement,
            ForStatement,
            IfStatement,
            TryStatement,
            WhileStatement,
            YulForLoop,
            YulIf,
            YulSwitch,
        ]
    ]

    def __init__(self):
        self._id = self.__class__._id_counter
        self.__class__._id_counter += 1
        self._statements = []
        self._control_statement = None

    def __str__(self):
        return (
            "\n".join(statement.source for statement in self.statements)
            if len(self.statements) > 0
            else ""
        )

    @property
    def id(self) -> int:
        """
        The concrete value should not be relied upon, it is only guaranteed to be unique within a single CFG.

        Returns:
            Unique ID of this CFG node.
        """
        return self._id

    @property
    def statements(self) -> Tuple[Union[StatementAbc, YulStatementAbc], ...]:
        """
        Returns:
            Statements contained in this CFG node.
        """
        return tuple(self._statements)

    @property
    def control_statement(
        self,
    ) -> Optional[
        Union[
            DoWhileStatement,
            ForStatement,
            IfStatement,
            TryStatement,
            WhileStatement,
            YulForLoop,
            YulIf,
            YulSwitch,
        ]
    ]:
        """
        Control statements are handled specially in CFG construction, because they contain sub-statements that are not
        part of the current CFG node. At the same time, control statements are always nearest parent statements for
        some expressions and so must be indexed.

        !!! example
            For example, [IfStatement][wake.ir.statements.if_statement.IfStatement] is the nearest parent statement
            of the [IfStatement.condition][wake.ir.statements.if_statement.IfStatement.condition] expression.

        A control statement is always the last statement in a CFG node.

        Returns:
            Control statement of this CFG node, if any.
        """
        return self._control_statement

    @classmethod
    def from_statement(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        loop_body_post: Optional[CfgNode],
        loop_body_next: Optional[CfgNode],
        statement: Union[StatementAbc, YulStatementAbc],
    ) -> CfgNode:
        if isinstance(statement, (Block, UncheckedBlock, YulBlock)):
            for body_statement in statement.statements:
                prev = cls.from_statement(
                    graph,
                    prev,
                    success_end,
                    revert_end,
                    loop_body_post,
                    loop_body_next,
                    body_statement,
                )
            return prev
        elif isinstance(statement, InlineAssembly):
            return cls.from_statement(
                graph,
                prev,
                success_end,
                revert_end,
                loop_body_post,
                loop_body_next,
                statement.yul_block,
            )
        elif (
            isinstance(statement, YulExpressionStatement)
            and isinstance(statement.expression, YulFunctionCall)
            and statement.expression.function_name.name == "revert"
        ):
            prev._statements.append(statement)
            next = CfgNode()
            graph.add_node(next)
            graph.add_edge(
                prev, revert_end, condition=(TransitionConditionKind.ALWAYS, None)
            )
            graph.add_edge(prev, next, condition=(TransitionConditionKind.NEVER, None))
            return next
        elif (
            isinstance(statement, YulExpressionStatement)
            and isinstance(statement.expression, YulFunctionCall)
            and statement.expression.function_name.name == "return"
        ):
            prev._statements.append(statement)
            next = CfgNode()
            graph.add_node(next)
            graph.add_edge(
                prev, success_end, condition=(TransitionConditionKind.ALWAYS, None)
            )
            graph.add_edge(prev, next, condition=(TransitionConditionKind.NEVER, None))
            return next
        elif isinstance(statement, (Break, YulBreak)):
            prev._statements.append(statement)
            next = CfgNode()
            assert loop_body_next is not None
            graph.add_node(next)
            graph.add_edge(
                prev, loop_body_next, condition=(TransitionConditionKind.ALWAYS, None)
            )
            graph.add_edge(prev, next, condition=(TransitionConditionKind.NEVER, None))
            return next
        elif isinstance(statement, (Continue, YulContinue)):
            prev._statements.append(statement)
            next = CfgNode()
            assert loop_body_post is not None
            graph.add_node(next)
            graph.add_edge(
                prev, loop_body_post, condition=(TransitionConditionKind.ALWAYS, None)
            )
            graph.add_edge(prev, next, condition=(TransitionConditionKind.NEVER, None))
            return next
        elif isinstance(statement, DoWhileStatement):
            return cls.from_do_while_statement(
                graph, prev, success_end, revert_end, statement
            )
        elif isinstance(statement, ForStatement):
            return cls.from_for_statement(
                graph, prev, success_end, revert_end, statement
            )
        elif isinstance(statement, IfStatement):
            return cls.from_if_statement(
                graph,
                prev,
                success_end,
                revert_end,
                loop_body_post,
                loop_body_next,
                statement,
            )
        elif isinstance(statement, (Return, YulLeave)):
            prev._statements.append(statement)
            next = CfgNode()
            graph.add_node(next)
            graph.add_edge(
                prev, success_end, condition=(TransitionConditionKind.ALWAYS, None)
            )
            graph.add_edge(prev, next, condition=(TransitionConditionKind.NEVER, None))
            return next
        elif isinstance(statement, RevertStatement):
            prev._statements.append(statement)
            next = CfgNode()
            graph.add_node(next)
            graph.add_edge(
                prev, revert_end, condition=(TransitionConditionKind.ALWAYS, None)
            )
            graph.add_edge(prev, next, condition=(TransitionConditionKind.NEVER, None))
            return next
        elif isinstance(statement, ExpressionStatement):

            def process_expression(expression: ExpressionAbc, node: CfgNode) -> bool:
                if isinstance(expression, Conditional):
                    true_node = CfgNode()
                    graph.add_node(true_node)
                    false_node = CfgNode()
                    graph.add_node(false_node)

                    graph.add_edge(
                        node,
                        true_node,
                        condition=(
                            TransitionConditionKind.IS_TRUE,
                            expression.condition,
                        ),
                    )
                    graph.add_edge(
                        node,
                        false_node,
                        condition=(
                            TransitionConditionKind.IS_FALSE,
                            expression.condition,
                        ),
                    )

                    true_is_control = process_expression(
                        expression.true_expression, true_node
                    )
                    false_is_control = process_expression(
                        expression.false_expression, false_node
                    )

                    if not true_is_control:
                        graph.remove_node(true_node)
                        if false_is_control:
                            graph.add_edge(
                                node,
                                next,
                                condition=(
                                    TransitionConditionKind.IS_TRUE,
                                    expression.condition,
                                ),
                            )

                    if not false_is_control:
                        graph.remove_node(false_node)
                        if true_is_control:
                            graph.add_edge(
                                node,
                                next,
                                condition=(
                                    TransitionConditionKind.IS_FALSE,
                                    expression.condition,
                                ),
                            )

                    return true_is_control or false_is_control
                elif isinstance(expression, FunctionCall):
                    func_called = expression.function_called
                    if func_called == GlobalSymbol.REVERT:
                        graph.add_edge(
                            node,
                            revert_end,
                            condition=(TransitionConditionKind.ALWAYS, None),
                        )
                        graph.add_edge(
                            node, next, condition=(TransitionConditionKind.NEVER, None)
                        )
                        return True
                    elif func_called in {
                        GlobalSymbol.REQUIRE,
                        GlobalSymbol.ASSERT,
                    }:
                        graph.add_edge(
                            node,
                            next,
                            condition=(
                                TransitionConditionKind.IS_TRUE,
                                expression.arguments[0],
                            ),
                        )
                        graph.add_edge(
                            node,
                            revert_end,
                            condition=(
                                TransitionConditionKind.IS_FALSE,
                                expression.arguments[0],
                            ),
                        )
                        return True
                    else:
                        return False

            prev._statements.append(statement)
            next = CfgNode()
            graph.add_node(next)

            if process_expression(statement.expression, prev):
                return next
            else:
                graph.remove_node(next)
                return prev
        elif isinstance(statement, TryStatement):
            return cls.from_try_statement(
                graph,
                prev,
                success_end,
                revert_end,
                loop_body_post,
                loop_body_next,
                statement,
            )
        elif isinstance(statement, WhileStatement):
            return cls.from_while_statement(
                graph, prev, success_end, revert_end, statement
            )
        elif isinstance(statement, YulCase):
            raise NotImplementedError()  # should be handled by YulSwitch
        elif isinstance(statement, YulForLoop):
            return cls.from_yul_for_loop(
                graph, prev, success_end, revert_end, statement
            )
        elif isinstance(statement, YulIf):
            return cls.from_yul_if(
                graph,
                prev,
                success_end,
                revert_end,
                loop_body_post,
                loop_body_next,
                statement,
            )
        elif isinstance(statement, YulSwitch):
            return cls.from_yul_switch(graph, prev, success_end, revert_end, statement)
        else:
            prev._statements.append(statement)
            return prev

    @classmethod
    def from_if_statement(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        loop_body_post: Optional[CfgNode],
        loop_body_next: Optional[CfgNode],
        if_statement: IfStatement,
    ) -> CfgNode:
        assert prev._control_statement is None
        prev._control_statement = if_statement
        true_node = CfgNode()
        graph.add_node(true_node)
        true_node_end = cls.from_statement(
            graph,
            true_node,
            success_end,
            revert_end,
            loop_body_post,
            loop_body_next,
            if_statement.true_body,
        )

        false_node = CfgNode()
        graph.add_node(false_node)

        if if_statement.false_body is None:
            false_node_end = false_node
        else:
            false_node_end = cls.from_statement(
                graph,
                false_node,
                success_end,
                revert_end,
                loop_body_post,
                loop_body_next,
                if_statement.false_body,
            )

        next = CfgNode()
        graph.add_node(next)
        graph.add_edge(
            prev,
            true_node,
            condition=(TransitionConditionKind.IS_TRUE, if_statement.condition),
        )
        graph.add_edge(
            prev,
            false_node,
            condition=(TransitionConditionKind.IS_FALSE, if_statement.condition),
        )
        graph.add_edge(
            true_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
        )
        graph.add_edge(
            false_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
        )
        return next

    @classmethod
    def from_yul_if(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        loop_body_post: Optional[CfgNode],
        loop_body_next: Optional[CfgNode],
        if_statement: YulIf,
    ):
        assert prev._control_statement is None
        prev._control_statement = if_statement
        true_node = CfgNode()
        graph.add_node(true_node)
        true_node_end = cls.from_statement(
            graph,
            true_node,
            success_end,
            revert_end,
            loop_body_post,
            loop_body_next,
            if_statement.body,
        )
        next = CfgNode()
        graph.add_node(next)
        graph.add_edge(
            prev,
            true_node,
            condition=(TransitionConditionKind.IS_TRUE, if_statement.condition),
        )
        graph.add_edge(
            prev,
            next,
            condition=(TransitionConditionKind.IS_FALSE, if_statement.condition),
        )
        graph.add_edge(
            true_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
        )
        return next

    @classmethod
    def from_do_while_statement(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        do_while_statement: DoWhileStatement,
    ) -> CfgNode:
        body = CfgNode()
        graph.add_node(body)
        next = CfgNode()
        graph.add_node(next)
        body_end = cls.from_statement(
            graph, body, success_end, revert_end, body, next, do_while_statement.body
        )
        assert body_end._control_statement is None
        body_end._control_statement = do_while_statement

        graph.add_edge(prev, body, condition=(TransitionConditionKind.ALWAYS, None))
        graph.add_edge(
            body_end,
            next,
            condition=(TransitionConditionKind.IS_FALSE, do_while_statement.condition),
        )
        graph.add_edge(
            body_end,
            body,
            condition=(TransitionConditionKind.IS_TRUE, do_while_statement.condition),
        )
        return next

    @classmethod
    def from_for_statement(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        for_statement: ForStatement,
    ) -> CfgNode:
        if for_statement.initialization_expression is not None:
            prev = cls.from_statement(
                graph,
                prev,
                success_end,
                revert_end,
                None,
                None,
                for_statement.initialization_expression,
            )
        assert prev._control_statement is None
        prev._control_statement = for_statement

        body = CfgNode()
        graph.add_node(body)
        next = CfgNode()
        graph.add_node(next)
        loop_post = CfgNode()
        graph.add_node(loop_post)
        if for_statement.loop_expression is not None:
            loop_post_end = cls.from_statement(
                graph,
                loop_post,
                success_end,
                revert_end,
                loop_post,
                next,
                for_statement.loop_expression,
            )
        else:
            loop_post_end = loop_post
        body_end = cls.from_statement(
            graph, body, success_end, revert_end, loop_post, next, for_statement.body
        )

        graph.add_edge(
            body_end, loop_post, condition=(TransitionConditionKind.ALWAYS, None)
        )
        graph.add_edge(
            prev,
            body,
            condition=(TransitionConditionKind.IS_TRUE, for_statement.condition),
        )
        graph.add_edge(
            prev,
            next,
            condition=(TransitionConditionKind.IS_FALSE, for_statement.condition),
        )
        graph.add_edge(
            loop_post_end,
            body,
            condition=(TransitionConditionKind.IS_TRUE, for_statement.condition),
        )
        graph.add_edge(
            loop_post_end,
            next,
            condition=(TransitionConditionKind.IS_FALSE, for_statement.condition),
        )
        return next

    @classmethod
    def from_yul_for_loop(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        for_loop: YulForLoop,
    ) -> CfgNode:
        assert prev._control_statement is None
        prev = cls.from_statement(
            graph, prev, success_end, revert_end, None, None, for_loop.pre
        )
        assert prev._control_statement is None
        prev._control_statement = for_loop

        body = CfgNode()
        graph.add_node(body)
        next = CfgNode()
        graph.add_node(next)
        loop_post = CfgNode()
        graph.add_node(loop_post)
        body_end = cls.from_statement(
            graph, body, success_end, revert_end, loop_post, next, for_loop.body
        )
        loop_post_end = cls.from_statement(
            graph, loop_post, success_end, revert_end, loop_post, next, for_loop.post
        )

        graph.add_edge(
            body_end, loop_post, condition=(TransitionConditionKind.ALWAYS, None)
        )
        graph.add_edge(
            prev, body, condition=(TransitionConditionKind.IS_TRUE, for_loop.condition)
        )
        graph.add_edge(
            prev,
            next,
            condition=(TransitionConditionKind.IS_FALSE, for_loop.condition),
        )
        graph.add_edge(
            loop_post_end,
            body,
            condition=(TransitionConditionKind.IS_TRUE, for_loop.condition),
        )
        graph.add_edge(
            loop_post_end,
            next,
            condition=(TransitionConditionKind.IS_FALSE, for_loop.condition),
        )
        return next

    @classmethod
    def from_try_statement(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        loop_body_post: Optional[CfgNode],
        loop_body_next: Optional[CfgNode],
        try_statement: TryStatement,
    ) -> CfgNode:
        assert prev._control_statement is None
        prev._control_statement = try_statement

        success_node = CfgNode()
        graph.add_node(success_node)
        success_node_end = cls.from_statement(
            graph,
            success_node,
            success_end,
            revert_end,
            loop_body_post,
            loop_body_next,
            try_statement.clauses[0].block,
        )

        revert_node = None
        revert_node_end = None
        panic_node = None
        panic_node_end = None
        fail_node = None
        fail_node_end = None
        for clause in try_statement.clauses[1:]:
            if clause.error_name == "Error":
                revert_node = CfgNode()
                graph.add_node(revert_node)
                revert_node_end = cls.from_statement(
                    graph,
                    revert_node,
                    success_end,
                    revert_end,
                    loop_body_post,
                    loop_body_next,
                    clause.block,
                )
            elif clause.error_name == "Panic":
                panic_node = CfgNode()
                graph.add_node(panic_node)
                panic_node_end = cls.from_statement(
                    graph,
                    panic_node,
                    success_end,
                    revert_end,
                    loop_body_post,
                    loop_body_next,
                    clause.block,
                )
            elif clause.error_name == "":
                fail_node = CfgNode()
                graph.add_node(fail_node)
                fail_node_end = cls.from_statement(
                    graph,
                    fail_node,
                    success_end,
                    revert_end,
                    loop_body_post,
                    loop_body_next,
                    clause.block,
                )
            else:
                raise NotImplementedError(f"Unknown error name: {clause.error_name}")

        next = CfgNode()
        graph.add_node(next)

        graph.add_edge(
            prev,
            success_node,
            condition=(
                TransitionConditionKind.TRY_SUCCEEDED,
                try_statement.external_call,
            ),
        )
        graph.add_edge(
            success_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
        )
        if revert_node is not None:
            graph.add_edge(
                prev,
                revert_node,
                condition=(
                    TransitionConditionKind.TRY_REVERTED,
                    try_statement.external_call,
                ),
            )
            graph.add_edge(
                revert_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
            )
        if panic_node is not None:
            graph.add_edge(
                prev,
                panic_node,
                condition=(
                    TransitionConditionKind.TRY_PANICKED,
                    try_statement.external_call,
                ),
            )
            graph.add_edge(
                panic_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
            )
        if fail_node is not None:
            graph.add_edge(
                prev,
                fail_node,
                condition=(
                    TransitionConditionKind.TRY_FAILED,
                    try_statement.external_call,
                ),
            )
            graph.add_edge(
                fail_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
            )
        else:
            graph.add_edge(
                prev,
                revert_end,
                condition=(
                    TransitionConditionKind.TRY_FAILED,
                    try_statement.external_call,
                ),
            )
        return next

    @classmethod
    def from_yul_switch(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        switch: YulSwitch,
    ) -> CfgNode:
        assert prev._control_statement is None
        prev._control_statement = switch

        next = CfgNode()
        graph.add_node(next)

        for case_statement in switch.cases:
            case_node = CfgNode()
            graph.add_node(case_node)
            graph.add_edge(
                prev,
                case_node,
                condition=(TransitionConditionKind.SWITCH_MATCHED, case_statement.value)
                if case_statement.value != "default"
                else (TransitionConditionKind.SWITCH_DEFAULT, None),
            )
            case_node_end = cls.from_statement(
                graph,
                case_node,
                success_end,
                revert_end,
                case_node,
                next,
                case_statement.body,
            )
            graph.add_edge(
                case_node_end, next, condition=(TransitionConditionKind.ALWAYS, None)
            )

        if not any(case.value == "default" for case in switch.cases):
            graph.add_edge(
                prev,
                next,
                condition=(TransitionConditionKind.SWITCH_DEFAULT, None),
            )

        return next

    @classmethod
    def from_while_statement(
        cls,
        graph: nx.DiGraph,
        prev: CfgNode,
        success_end: CfgNode,
        revert_end: CfgNode,
        while_statement: WhileStatement,
    ) -> CfgNode:
        assert prev._control_statement is None
        prev._control_statement = while_statement

        body = CfgNode()
        graph.add_node(body)
        next = CfgNode()
        graph.add_node(next)
        body_end = cls.from_statement(
            graph, body, success_end, revert_end, body, next, while_statement.body
        )

        graph.add_edge(
            prev,
            body,
            condition=(TransitionConditionKind.IS_TRUE, while_statement.condition),
        )
        graph.add_edge(
            prev,
            next,
            condition=(TransitionConditionKind.IS_FALSE, while_statement.condition),
        )
        graph.add_edge(
            body_end,
            body,
            condition=(TransitionConditionKind.IS_TRUE, while_statement.condition),
        )
        graph.add_edge(
            body_end,
            next,
            condition=(TransitionConditionKind.IS_FALSE, while_statement.condition),
        )
        return next

id: int property #

The concrete value should not be relied upon, it is only guaranteed to be unique within a single CFG.

Returns:

Type Description
int

Unique ID of this CFG node.

statements: Tuple[Union[StatementAbc, YulStatementAbc], ...] property #

Returns:

Type Description
Tuple[Union[StatementAbc, YulStatementAbc], ...]

Statements contained in this CFG node.

control_statement: Optional[Union[DoWhileStatement, ForStatement, IfStatement, TryStatement, WhileStatement, YulForLoop, YulIf, YulSwitch]] property #

Control statements are handled specially in CFG construction, because they contain sub-statements that are not part of the current CFG node. At the same time, control statements are always nearest parent statements for some expressions and so must be indexed.

Example

For example, IfStatement is the nearest parent statement of the IfStatement.condition expression.

A control statement is always the last statement in a CFG node.

Returns:

Type Description
Optional[Union[DoWhileStatement, ForStatement, IfStatement, TryStatement, WhileStatement, YulForLoop, YulIf, YulSwitch]]

Control statement of this CFG node, if any.