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 pathcyclomatic_complexity.py
More file actions
79 lines (65 loc) · 2.45 KB
/
Copy pathcyclomatic_complexity.py
File metadata and controls
79 lines (65 loc) · 2.45 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
# 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 cyclomatic complexity of a program or control flow graph."""
def cyclomatic_complexity(control_flow_graph):
"""Computes the cyclomatic complexity of a function from its cfg."""
enter_block = next(control_flow_graph.get_enter_blocks())
new_blocks = []
seen_block_ids = set()
new_blocks.append(enter_block)
seen_block_ids.add(id(enter_block))
num_edges = 0
while new_blocks:
block = new_blocks.pop()
for next_block in block.exits_from_end:
num_edges += 1
if id(next_block) not in seen_block_ids:
new_blocks.append(next_block)
seen_block_ids.add(id(next_block))
num_nodes = len(seen_block_ids)
p = 1 # num_connected_components
e = num_edges
n = num_nodes
return e - n + 2 * p
def cyclomatic_complexity2(control_flow_graph):
"""Computes the cyclomatic complexity of a program from its cfg."""
# Assumes a single connected component.
p = 1 # num_connected_components
e = sum(len(block.exits_from_end) for block in control_flow_graph.blocks)
n = len(control_flow_graph.blocks)
return e - n + 2 * p
def cyclomatic_complexity3(control_flow_graph):
"""Computes the cyclomatic complexity of a program from its cfg."""
start_block = control_flow_graph.start_block
enter_blocks = control_flow_graph.get_enter_blocks()
new_blocks = [start_block]
seen_block_ids = {id(start_block)}
num_connected_components = 1
num_edges = 0
for enter_block in enter_blocks:
new_blocks.append(enter_block)
seen_block_ids.add(id(enter_block))
num_connected_components += 1
while new_blocks:
block = new_blocks.pop()
for next_block in block.exits_from_end:
num_edges += 1
if id(next_block) not in seen_block_ids:
new_blocks.append(next_block)
seen_block_ids.add(id(next_block))
num_nodes = len(seen_block_ids)
p = num_connected_components
e = num_edges
n = num_nodes
return e - n + 2 * p