This repository was archived by the owner on Oct 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathcontrol_flow.py
More file actions
1426 lines (1202 loc) · 55.1 KB
/
Copy pathcontrol_flow.py
File metadata and controls
1426 lines (1202 loc) · 55.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
# Copyright (C) 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Computes the control flow graph for a Python program from its AST."""
import itertools
import uuid
from absl import logging # pylint: disable=unused-import
import gast as ast
from python_graphs import instruction as instruction_module
from python_graphs import program_utils
import six
def get_control_flow_graph(program):
"""Get a ControlFlowGraph for the provided AST node.
Args:
program: Either an AST node, source string, or a function.
Returns:
A ControlFlowGraph.
"""
control_flow_visitor = ControlFlowVisitor()
node = program_utils.program_to_ast(program)
control_flow_visitor.run(node)
return control_flow_visitor.graph
class ControlFlowGraph(object):
"""A control flow graph for a Python program.
Attributes:
blocks: All blocks contained in the control flow graph.
nodes: All control flow nodes in the control flow graph.
start_block: The entry point to the program.
"""
def __init__(self):
self.blocks = []
self.nodes = []
self.start_block = self.new_block(prunable=False)
self.start_block.label = '<start>'
def add_node(self, control_flow_node):
self.nodes.append(control_flow_node)
def new_block(self, node=None, label=None, prunable=True):
block = BasicBlock(node=node, label=label, prunable=prunable)
block.graph = self
self.blocks.append(block)
return block
def move_block_to_rear(self, block):
self.blocks.remove(block)
self.blocks.append(block)
def get_control_flow_nodes(self):
return self.nodes
def get_enter_blocks(self):
"""Returns entry blocks for all functions."""
return six.moves.filter(
lambda block: block.label.startswith('<entry:'), self.blocks)
def get_enter_control_flow_nodes(self):
"""Yields all ControlFlowNodes without any prev nodes."""
for block in self.blocks:
if (block.label is not None
and block.label.startswith('<entry')
and not block.control_flow_nodes):
# The entry block does't have nodes itself, but rather has a next block
# with control flow nodes.
next_block = next(iter(block.next))
if next_block.control_flow_nodes:
yield next_block.control_flow_nodes[0]
elif block.control_flow_nodes:
node = block.control_flow_nodes[0]
if not node.prev:
yield node
def get_exit_blocks(self):
"""Yields all blocks without any next blocks."""
for block in self.blocks:
if not block.next:
yield block
def get_instructions(self):
"""Yields all instructions in the control flow graph."""
for block in self.blocks:
for node in block.control_flow_nodes:
yield node.instruction
def get_start_control_flow_node(self):
if self.start_block.control_flow_nodes:
return self.start_block.control_flow_nodes[0]
if self.start_block.exits_from_end:
assert len(self.start_block.exits_from_end) == 1
first_block = next(iter(self.start_block.exits_from_end))
if first_block.control_flow_nodes:
return first_block.control_flow_nodes[0]
else:
return first_block.label
def get_control_flow_nodes_by_ast_node(self, node):
return six.moves.filter(
lambda control_flow_node: control_flow_node.instruction.node == node,
self.get_control_flow_nodes())
def get_control_flow_node_by_ast_node(self, node):
return next(self.get_control_flow_nodes_by_ast_node(node))
def get_blocks_by_ast_node(self, node):
for block in self.blocks:
for control_flow_node in block.control_flow_nodes:
if node == control_flow_node.instruction.node:
yield block
break
def get_block_by_ast_node(self, node):
return next(self.get_blocks_by_ast_node(node))
def get_blocks_by_function_name(self, name):
"""Returns entry blocks for any functions named `name`."""
return six.moves.filter(
lambda block: block.label == '<entry:{name}>'.format(name=name),
self.blocks)
def get_block_by_function_name(self, name):
return next(self.get_blocks_by_function_name(name))
def get_control_flow_nodes_by_source(self, source):
module = ast.parse(source, mode='exec') # TODO(dbieber): Factor out 4 lines
node = module.body[0]
if isinstance(node, ast.Expr):
node = node.value
return six.moves.filter(
lambda cfn: cfn.instruction.contains_subprogram(node),
self.get_control_flow_nodes())
def get_control_flow_node_by_source(self, source):
return next(self.get_control_flow_nodes_by_source(source))
def get_control_flow_nodes_by_source_and_identifier(self, source, name):
for control_flow_node in self.get_control_flow_nodes_by_source(source):
for node in ast.walk(control_flow_node.instruction.node):
if isinstance(node, ast.Name) and node.id == name:
for i2 in self.get_control_flow_nodes_by_ast_node(node):
yield i2
def get_control_flow_node_by_source_and_identifier(self, source, name):
return next(
self.get_control_flow_nodes_by_source_and_identifier(source, name))
def get_blocks_by_source(self, source):
"""Yields blocks that contain instructions matching the query source."""
module = ast.parse(source, mode='exec')
node = module.body[0]
if isinstance(node, ast.Expr):
node = node.value
for block in self.blocks:
for control_flow_node in block.control_flow_nodes:
if control_flow_node.instruction.contains_subprogram(node):
yield block
break
def get_block_by_source(self, source):
return next(self.get_blocks_by_source(source))
def get_blocks_by_source_and_ast_node_type(self, source, node_type):
"""Blocks with an Instruction matching node_type and containing source."""
module = ast.parse(source, mode='exec')
node = module.body[0]
if isinstance(node, ast.Expr):
node = node.value
for block in self.blocks:
for instruction in block.instructions:
if (isinstance(instruction.node, node_type)
and instruction.contains_subprogram(node)):
yield block
break
def get_block_by_source_and_ast_node_type(self, source, node_type):
"""A block with an Instruction matching node_type and containing source."""
return next(self.get_blocks_by_source_and_ast_node_type(source, node_type))
def get_block_by_ast_node_and_label(self, node, label):
"""Gets the block corresponding to `node` having label `label`."""
for block in self.blocks:
if block.node is node and block.label == label:
return block
def get_blocks_by_ast_node_type_and_label(self, node_type, label):
"""Gets the blocks with node type `node_type` having label `label`."""
for block in self.blocks:
if isinstance(block.node, node_type) and block.label == label:
yield block
def get_block_by_ast_node_type_and_label(self, node_type, label):
"""Gets a block with node type `node_type` having label `label`."""
return next(self.get_blocks_by_ast_node_type_and_label(node_type, label))
def prune(self):
"""Prunes all prunable blocks from the graph."""
progress = True
while progress:
progress = False
for block in iter(self.blocks):
if block.can_prune():
to_remove = block.prune()
self.blocks.remove(to_remove)
progress = True
def compact(self):
"""Prunes unused blocks and merges blocks when possible."""
self.prune()
for block in iter(self.blocks):
while block.can_merge():
to_remove = block.merge()
self.blocks.remove(to_remove)
for block in self.blocks:
block.compact()
class Frame(object):
"""A Frame indicates how statements affect control flow in parts of a program.
Frames are introduced when the program enters a new loop, function definition,
or try/except/finally block.
A Frame indicates how an exit such as a continue, break, exception, or return
affects control flow. For example, a continue statement inside of a loop sends
control back to the loop's condition. In nested loops, a continue statement
sends control back to the condition of the innermost loop containing the
continue statement.
Attributes:
kind: One of LOOP, FUNCTION, TRY_EXCEPT, or TRY_FINALLY.
blocks: A dictionary with the blocks relevant to the frame.
"""
# Kinds:
MODULE = 'module'
LOOP = 'loop'
FUNCTION = 'function'
TRY_EXCEPT = 'try-except'
TRY_FINALLY = 'try-finally'
def __init__(self, kind, **blocks):
self.kind = kind
self.blocks = blocks
class BasicBlock(object):
"""A basic block in a control flow graph.
All instructions (generally, AST nodes) in a basic block are either executed
or none are (with the exception of blocks interrupted by exceptions). These
instructions are executed in a straight-line manner.
Attributes:
graph: The control flow graph which this basic block is a part of.
next: Indicates which basic blocks may be executed after this basic block.
prev: Indicates which basic blocks may lead to the execution of this basic
block in a Python program.
control_flow_nodes: A list of the ControlFlowNodes contained in this basic
block. Each ControlFlowNode corresponds to a single Instruction.
control_flow_node_indexes: Maps from id(control_flow_node) to the
ControlFlowNode's index in self.control_flow_nodes. Only available once
the block is compacted.
branches: A map from booleans to the basic block reachable by making the
branch decision indicated by that boolean.
exits_from_middle: These basic blocks may be exited to at any point during
the execution of this basic block.
exits_from_end: These basic blocks may only be exited to at the end of
the execution of this basic block.
node: The AST node this basic block is associated with.
prunable: Whether this basic block may be pruned from the control flow graph
if empty. Set to False for special blocks, such as enter and exit blocks.
label: A label for the basic block.
identities: A list of (node, label) pairs that refer to this basic block.
This starts as (self.node, self.label), but old identities are preserved
during merging and pruning. Allows lookup of blocks by node and label,
e.g. for finding the after block of a particular if statement.
labels: Labels, used for example by data flow analyses. Maps from label name
to value.
"""
def __init__(self, node=None, label=None, prunable=True):
self.graph = None
self.next = set()
self.prev = set()
self.control_flow_nodes = []
self.control_flow_node_indexes = None
self.branches = {}
self.except_branches = {}
self.reraise_branches = {}
self.exits_from_middle = set()
self.exits_from_end = set()
self.node = node
self.prunable = prunable
self.label = label
self.identities = [(node, label)]
self.labels = {}
def has_label(self, label):
"""Returns whether this BasicBlock has the specified label."""
return label in self.labels
def set_label(self, label, value):
"""Sets the value of a label on the BasicBlock."""
self.labels[label] = value
def get_label(self, label):
"""Gets the value of a label on the BasicBlock."""
return self.labels[label]
def is_empty(self):
"""Whether this block is empty."""
return not self.control_flow_nodes
def exits_to(self, block):
"""Whether this block exits to `block`."""
return block in self.next
def raises_to(self, block):
"""Whether this block exits to `block` in the case of an exception."""
return block in self.next and block in self.exits_from_middle
def add_exit(self, block, interrupting=False,
branch=None, except_branch=None, reraise_branch=None):
"""Adds an exit from this block to `block`."""
self.next.add(block)
block.prev.add(self)
if branch is not None:
self.branches[branch] = block
if except_branch is not None:
self.except_branches[except_branch] = block
if reraise_branch is not None:
self.reraise_branches[reraise_branch] = block
if interrupting:
self.exits_from_middle.add(block)
else:
self.exits_from_end.add(block)
def remove_exit(self, block):
"""Removes the exit from this block to `block`."""
self.next.remove(block)
block.prev.remove(self)
if block in self.exits_from_middle:
self.exits_from_middle.remove(block)
if block in self.exits_from_end:
self.exits_from_end.remove(block)
for branch_decision, branch_exit in self.branches.copy().items():
if branch_exit is block:
del self.branches[branch_decision]
for branch_decision, branch_exit in self.except_branches.copy().items():
if branch_exit is block:
del self.except_branches[branch_decision]
for branch_decision, branch_exit in self.reraise_branches.copy().items():
if branch_exit is block:
del self.reraise_branches[branch_decision]
def can_prune(self):
return self.is_empty() and self.prunable
def prune(self):
"""Prunes the empty block from its control flow graph.
A block is prunable if it has no control flow nodes and has not been marked
as unprunable (e.g. because it's the exit block, or a return block, etc).
Returns:
The block removed by the prune operation. That is, self.
"""
assert self.can_prune()
prevs = self.prev.copy()
nexts = self.next.copy()
for prev_block in prevs:
exits_from_middle = prev_block.exits_from_middle.copy()
exits_from_end = prev_block.exits_from_end.copy()
branches = prev_block.branches.copy()
except_branches = prev_block.except_branches.copy()
reraise_branches = prev_block.reraise_branches.copy()
for next_block in nexts:
if self in exits_from_middle:
prev_block.add_exit(next_block, interrupting=True)
if self in exits_from_end:
prev_block.add_exit(next_block, interrupting=False)
for branch_decision, branch_exit in branches.items():
if branch_exit is self:
prev_block.branches[branch_decision] = next_block
for branch_decision, branch_exit in except_branches.items():
if branch_exit is self:
prev_block.except_branches[branch_decision] = next_block
for branch_decision, branch_exit in reraise_branches.items():
if branch_exit is self:
prev_block.reraise_branches[branch_decision] = next_block
for prev_block in prevs:
prev_block.remove_exit(self)
for next_block in nexts:
self.remove_exit(next_block)
next_block.identities = next_block.identities + self.identities
return self
def can_merge(self):
if len(self.exits_from_end) != 1:
return False
next_block = next(iter(self.exits_from_end))
if not next_block.prunable:
return False
if self.exits_from_middle != next_block.exits_from_middle:
return False
if len(next_block.prev) == 1:
return True
def merge(self):
"""Merge this block with its one successor.
Returns:
The successor block removed by the merge operation.
"""
assert self.can_merge()
next_block = next(iter(self.exits_from_end))
exits_from_middle = next_block.exits_from_middle.copy()
exits_from_end = next_block.exits_from_end.copy()
for branch_decision, branch_exit in next_block.branches.items():
self.branches[branch_decision] = branch_exit
for branch_decision, branch_exit in next_block.except_branches.items():
self.except_branches[branch_decision] = branch_exit
for branch_decision, branch_exit in next_block.reraise_branches.items():
self.reraise_branches[branch_decision] = branch_exit
self.remove_exit(next_block)
for block in next_block.next.copy():
next_block.remove_exit(block)
if block in exits_from_middle:
self.add_exit(block, interrupting=True)
if block in exits_from_end:
self.add_exit(block, interrupting=False)
for control_flow_node in next_block.control_flow_nodes:
control_flow_node.block = self
self.control_flow_nodes.append(control_flow_node)
self.prunable = self.prunable and next_block.prunable
self.label = self.label or next_block.label
self.identities = self.identities + next_block.identities
# Note: self.exits_from_middle is unchanged.
return next_block
def add_instruction(self, instruction):
assert isinstance(instruction, instruction_module.Instruction)
control_flow_node = ControlFlowNode(graph=self.graph,
block=self,
instruction=instruction)
self.graph.add_node(control_flow_node)
self.control_flow_nodes.append(control_flow_node)
def compact(self):
self.control_flow_node_indexes = {}
for index, control_flow_node in enumerate(self.control_flow_nodes):
self.control_flow_node_indexes[control_flow_node.uuid] = index
def index_of(self, control_flow_node):
"""Returns the index of the Instruction in this BasicBlock."""
return self.control_flow_node_indexes[control_flow_node.uuid]
class ControlFlowNode(object):
"""A node in a control flow graph.
Corresponds to a single Instruction contained in a single BasicBlock.
Attributes:
graph: The ControlFlowGraph which this node is a part of.
block: The BasicBlock in which this node's instruction resides.
instruction: The Instruction corresponding to this node.
labels: Metadata attached to this node, for example for use by data flow
analyses.
uuid: A unique identifier for the ControlFlowNode.
"""
def __init__(self, graph, block, instruction):
self.graph = graph
self.block = block
self.instruction = instruction
self.labels = {}
self.uuid = uuid.uuid4()
@property
def next(self):
"""Returns the set of possible next instructions.
This allows for taking exits from the middle (exceptions).
"""
if self.block is None:
return None
index_in_block = self.block.index_of(self)
if len(self.block.control_flow_nodes) > index_in_block + 1:
return {self.block.control_flow_nodes[index_in_block + 1]}
control_flow_nodes = set()
for next_block in self.block.next:
if next_block.control_flow_nodes:
control_flow_nodes.add(next_block.control_flow_nodes[0])
else:
# If next_block is empty, it isn't the case that some downstream block
# is nonempty. This is guaranteed by the pruning phase of control flow
# graph construction.
assert not next_block.next
return control_flow_nodes
@property
def next_from_end(self):
"""Returns the set of possible next instructions.
This does not allow for taking exits from the middle (exceptions).
"""
if self.block is None:
return None
index_in_block = self.block.index_of(self)
if len(self.block.control_flow_nodes) > index_in_block + 1:
return {self.block.control_flow_nodes[index_in_block + 1]}
control_flow_nodes = set()
for next_block in self.block.exits_from_end:
if next_block.control_flow_nodes:
control_flow_nodes.add(next_block.control_flow_nodes[0])
else:
# If next_block is empty, it isn't the case that some downstream block
# is nonempty. This is guaranteed by the pruning phase of control flow
# graph construction.
assert not next_block.next
control_flow_nodes.add(next_block.label)
return control_flow_nodes
@property
def prev(self):
"""Returns the set of possible previous instructions."""
if self.block is None:
return None
index_in_block = self.block.index_of(self)
if index_in_block - 1 >= 0:
return {self.block.control_flow_nodes[index_in_block - 1]}
control_flow_nodes = set()
for prev_block in self.block.prev:
if prev_block.control_flow_nodes:
control_flow_nodes.add(prev_block.control_flow_nodes[-1])
else:
# If prev_block is empty, it isn't the case that some upstream block
# is nonempty. This is guaranteed by the pruning phase of control flow
# graph construction.
assert not prev_block.prev
return control_flow_nodes
@property
def branches(self):
"""Returns the branch options available at the end of this node.
Returns:
A dictionary with possible keys True and False, and values given by the
node that is reached by taking the True/False branch. An empty dictionary
indicates that there are no branches to take, and so self.next gives the
next node (in a set of size 1). A value of None indicates that taking that
branch leads to the exit, since there are no exit ControlFlowNodes in a
ControlFlowGraph.
"""
return self.get_branches(
include_except_branches=False,
include_reraise_branches=False)
def get_branches(self, include_except_branches=False, include_reraise_branches=False):
"""Returns the branch options available at the end of this node.
Returns:
A dictionary with possible keys True and False, and values given by the
node that is reached by taking the True/False branch. An empty dictionary
indicates that there are no branches to take, and so self.next gives the
next node (in a set of size 1). A value of '<exit>' or '<raise>' indicates that
taking that branch leads to the exit or raise block, since there are no exit
ControlFlowNodes in a ControlFlowGraph.
"""
if self.block is None:
return {} # We're not in a block. No branch decision.
index_in_block = self.block.index_of(self)
if len(self.block.control_flow_nodes) > index_in_block + 1:
return {} # We're not yet at the end of the block. No branch decision.
branches = {} # We're at the end of the block.
all_branches = [self.block.branches.items()]
if include_except_branches:
all_branches.append(self.block.except_branches.items())
if include_reraise_branches:
all_branches.append(self.block.reraise_branches.items())
for key, next_block in itertools.chain(*all_branches):
if next_block.control_flow_nodes:
branches[key] = next_block.control_flow_nodes[0]
else:
# If next_block is empty, it isn't the case that some downstream block
# is nonempty. This is guaranteed by the pruning phase of control flow
# graph construction.
assert not next_block.next
branches[key] = next_block.label # Indicates exit or raise; there is no node to return.
return branches
def has_label(self, label):
"""Returns whether this Instruction has the specified label."""
return label in self.labels
def set_label(self, label, value):
"""Sets the value of a label on the Instruction."""
self.labels[label] = value
def get_label(self, label):
"""Gets the value of a label on the Instruction."""
return self.labels[label]
# pylint: disable=invalid-name,g-doc-return-or-yield,g-doc-args
class ControlFlowVisitor(object):
"""A visitor for determining the control flow of a Python program from an AST.
The main function of interest here is `visit`, which causes the visitor to
construct the control flow graph for the node passed to visit.
Basic control flow:
The state of the Visitor consists of a sequence of frames, and a current
basic block. When an AST node is visited by `visit`, it is added to the
current basic block. When a node can indicate a possible change in control,
new basic blocks are created and exits between the basic blocks are added
as appropriate.
For example, an If statement introduces two possibilities for control flow.
Consider the program:
if a > b:
c = 1
else:
c = 2
return c
There are four basic blocks in this program: let's call them `compare`,
`c = 1`, `c = 2`, and `return`. The exits between the blocks are:
`compare` -> `c = 1`, `compare` -> `c = 2`, `c = 1` -> `return`, and
`c = 2` -> `return`.
Frames:
There are four kinds of frames: function frames, loop frames, try-except, and
try-finally frames. All AST nodes in a function definition are in that
function's function frame. All AST nodes in the body of a loop are in that
loop's loop frame. And all AST nodes in the try and except blocks of a
try/except/finally are in that try's try-finally frame.
A function frame contains information about where control should flow to in
the case of a return statement or an uncaught exception.
A loop frame contains information about where control should pass to in the
case of a continue or break statement.
A try-except frame contains information about where control should flow to in
the case of an exception.
A try-finally frame contains information about where control should flow to
in the case of an exit (such as a finally block that must run before a return,
continue, or break statement can be executed).
Attributes:
graph: The control flow graph being generated by the visitor.
frames: The current frames. Each frame in this list contains all frames that
come after it in the list.
"""
def __init__(self):
self.graph = ControlFlowGraph()
self.frames = []
def run(self, node):
start_block = self.graph.start_block
end_block = self.visit(node, start_block)
self.graph.compact()
def visit(self, node, current_block):
"""Visit node, either an AST node or a list.
Args:
node: The AST node being visited. Not necessarily an instance of ast.AST;
node may also be a list, primitive, or Instruction.
current_block: The basic block whose execution necessarily precedes the
execution of `node`.
Returns:
The final basic block for the node.
"""
assert isinstance(node, ast.AST)
if isinstance(node, instruction_module.INSTRUCTION_AST_NODES):
self.add_new_instruction(current_block, node)
method_name = 'visit_' + node.__class__.__name__
method = getattr(self, method_name, None)
if method is not None:
current_block = method(node, current_block)
return current_block
def visit_list(self, items, current_block):
"""Visit each of the items in a list from the AST."""
for item in items:
current_block = self.visit(item, current_block)
return current_block
def add_new_instruction(self, block, node, accesses=None, source=None):
assert isinstance(node, ast.AST)
instruction = instruction_module.Instruction(
node, accesses=accesses, source=source)
self.add_instruction(block, instruction)
def add_instruction(self, block, instruction):
assert isinstance(instruction, instruction_module.Instruction)
block.add_instruction(instruction)
# Any instruction may raise an exception.
if not block.exits_from_middle:
self.raise_through_frames(block, interrupting=True)
def raise_through_frames(self, block, interrupting=True, except_branch=None):
"""Adds exits for the control flow of a raised exception.
`interrupting` means the exit can occur at any point (exit_from_middle).
`not interrupting` means the exit can only occur at the end of the block.
The reason to raise_through_frames with interrupting=False is for an
exception that already has been partially raised, but has passed control to
a finally block, and is now being raised at the end of that finally block.
Args:
block: The block where the exception's control flow begins.
interrupting: Whether the exception can be raised from any point in block.
If False, the exception is only raised from the end of block.
except_branch: False indicates the node raising is doing so the because an exception
header did not match the raised error. None indicates otherwise.
"""
frames = self.get_current_exception_handling_frames()
if frames is None:
return
# reraise_branch indicates whether the a raise is a reraise of an earlier exception.
# This is True after raising through a finally block, and None otherwise.
reraise_branch = None
for frame in frames:
if frame.kind == Frame.TRY_FINALLY:
# Exit to finally and have finally exit to whatever's next...
final_block = frame.blocks['final_block']
block.add_exit(final_block, interrupting=interrupting, except_branch=except_branch, reraise_branch=reraise_branch)
block = frame.blocks['final_block_end']
interrupting = False
# "True" indicates the path taken after finally if an error has been raised.
except_branch = None
reraise_branch = True
elif frame.kind == Frame.TRY_EXCEPT:
handler_block = frame.blocks['handler_block']
block.add_exit(handler_block, interrupting=interrupting, except_branch=except_branch, reraise_branch=reraise_branch)
# This will be the last frame in frames.
elif frame.kind == Frame.FUNCTION:
raise_block = frame.blocks['raise_block']
block.add_exit(raise_block, interrupting=interrupting, except_branch=except_branch, reraise_branch=reraise_branch)
# This will be the last frame in frames.
elif frame.kind == Frame.MODULE:
raise_block = frame.blocks['raise_block']
block.add_exit(raise_block, interrupting=interrupting, except_branch=except_branch, reraise_branch=reraise_branch)
# This will be the last frame in frames.
def new_block(self, node=None, label=None, prunable=True):
"""Create a new block."""
return self.graph.new_block(node=node, label=label, prunable=prunable)
def enter_module_frame(self, exit_block, raise_block):
# The entire module is in the interior of the frame.
# The exit block and raise block are the exits from the frame.
self.frames.append(Frame(Frame.MODULE,
exit_block=exit_block,
raise_block=raise_block))
def enter_loop_frame(self, continue_block, break_block):
# The loop body is the interior of the frame.
# The continue block (loop condition) and break block (loop's after block)
# are the exits from the frame.
self.frames.append(Frame(Frame.LOOP,
continue_block=continue_block,
break_block=break_block))
def enter_function_frame(self, return_block, raise_block):
# The function body is the interior of the frame.
# The return block and raise block are the exits from the frame.
self.frames.append(Frame(Frame.FUNCTION,
return_block=return_block,
raise_block=raise_block))
def enter_try_except_frame(self, handler_block):
# The try block is the interior of the frame.
# handler_block is where the frame exits to on an exception.
self.frames.append(Frame(Frame.TRY_EXCEPT,
handler_block=handler_block))
def enter_try_finally_frame(self, final_block, final_block_end):
# The try block and handler blocks are the interior of the frame.
# The finally block is the exit from the frame.
self.frames.append(Frame(Frame.TRY_FINALLY,
final_block=final_block,
final_block_end=final_block_end))
def exit_frame(self):
"""Exits the innermost current frame.
Note: Each enter_* function must be matched to exactly one exit_frame call
in reverse order.
Returns:
The frame being exited.
"""
return self.frames.pop()
def get_current_loop_frame(self):
"""Gets the current loop frame and contained current try-finally frames.
In order to exit the current loop frame, we must first enter the finally
blocks of all current contained try-finally frames.
Returns:
A list of frames, all of which are try-finally frames except for the last,
which is the current loop frame. Each of the returned try-finally
frames is contained within the current loop frame.
"""
frames = []
for frame in reversed(self.frames):
if frame.kind == Frame.TRY_FINALLY:
frames.append(frame)
if frame.kind == Frame.LOOP:
frames.append(frame)
return frames
# There are no loop frames.
return None
def get_current_function_frame(self):
"""Gets the current function frame and contained current try-finally frames.
In order to exit the current function frame, we must first enter the finally
blocks of all current contained try-finally frames.
Returns:
A list of frames, all of which are try-finally frames except for the last,
which is the current function frame. Each of the returned try-finally
frames is contained within the current function frame.
"""
frames = []
for frame in reversed(self.frames):
if frame.kind == Frame.TRY_FINALLY:
frames.append(frame)
if frame.kind == Frame.FUNCTION:
frames.append(frame)
return frames
# There are no function frames.
return None
def get_current_exception_handling_frames(self):
"""Get all exception handling frames containing the current block.
Returns:
A list of frames, all of which are exception handling frames containing
the current block. Any instruction contained in a try-except frame may
exit to the frame's exception handling block, with the caveat that an
instruction cannot exit through a TRY_FINALLY frame without passing first
through the frame's finally block. (The instruction will exit to the
finally block, and the finally block in turn will exit to the exception
handler.) A function frame's raise block serves to catch exceptions as
well.
"""
frames = []
# Traverse frames from innermost to outermost until a frame that fully
# catches the exception is found.
for frame in reversed(self.frames):
if frame.kind == Frame.TRY_FINALLY:
frames.append(frame)
if frame.kind == Frame.TRY_EXCEPT:
# A try-except frame catches any exception, even if the frame's except
# statements do not match the exception. In this case, the final except
# will reraise the exception to higher frames.
frames.append(frame)
return frames
if frame.kind == Frame.FUNCTION:
# A function frame's raise_block catches any exception that reaches it.
frames.append(frame)
return frames
if frame.kind == Frame.MODULE:
# A module frame's raise_block catches any exception that reaches it.
frames.append(frame)
return frames
# There is no frame to fully catch the exception.
raise ValueError('No frame exists to catch the exception.')
def visit_Module(self, node, current_block):
exit_block = self.new_block(node=node, label='<exit>', prunable=False)
raise_block = self.new_block(node=node, label='<raise>', prunable=False)
self.enter_module_frame(exit_block, raise_block)
end_block = self.visit_list(node.body, current_block)
end_block.add_exit(exit_block)
self.exit_frame()
# Move exit and raise blocks to the end of the block list.
self.graph.move_block_to_rear(exit_block)
self.graph.move_block_to_rear(raise_block)
return end_block
def visit_ClassDef(self, node, current_block):
"""Visit a ClassDef node of the AST.
Blocks:
current_block: The block in which the class is defined.
"""
# TODO(dbieber): Make sure all statements are handled, such as base classes.
# http://greentreesnakes.readthedocs.io/en/latest/nodes.html#ClassDef
# The body is executed before the decorators.
current_block = self.visit_list(node.body, current_block)
for decorator in node.decorator_list:
self.add_new_instruction(current_block, decorator)
assert isinstance(node.name, six.string_types)
self.add_new_instruction(
current_block,
node,
accesses=instruction_module.create_writes(node.name, node),
source=instruction_module.CLASS)
return current_block
def visit_FunctionDef(self, node, current_block):
"""Visit a FunctionDef node of the AST.
Blocks:
current_block: The block in which the function is defined.
"""
# First defaults are computed, then decorators are run, then the functiondef
# is assigned to the function name.
current_block = self.handle_argument_defaults(node.args, current_block)
for decorator in node.decorator_list:
self.add_new_instruction(current_block, decorator)
assert isinstance(node.name, six.string_types)
self.add_new_instruction(
current_block,
node,
accesses=instruction_module.create_writes(node.name, node),
source=instruction_module.FUNCTION)
self.handle_function_definition(node, node.name, node.args, node.body)
return current_block
def visit_Lambda(self, node, current_block):
"""Visit a Lambda node of the AST.
Blocks:
current_block: The block in which the lambda is defined.
"""
current_block = self.handle_argument_defaults(node.args, current_block)
self.handle_function_definition(node, 'lambda', node.args, node.body)
return current_block
def handle_function_definition(self, node, name, args, body):
"""A helper fn for Lambda and FunctionDef.
Note that this function doesn't require a block as input, since it doesn't
modify the blocks where the function definition resides.
Blocks:
entry_block: The block where control flow starts when the function is
called.
return_block: The block the function returns to.
raise_block: The block the function raises uncaught exceptions to.
fn_block: The first used block of the FunctionDef.