wayward-eagle 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wayward_eagle-0.1.0/LICENSE +201 -0
- wayward_eagle-0.1.0/PKG-INFO +41 -0
- wayward_eagle-0.1.0/README.md +19 -0
- wayward_eagle-0.1.0/pyproject.toml +34 -0
- wayward_eagle-0.1.0/setup.cfg +4 -0
- wayward_eagle-0.1.0/tests/test_reduce.py +248 -0
- wayward_eagle-0.1.0/wayward_eagle/__init__.py +51 -0
- wayward_eagle-0.1.0/wayward_eagle/cost.py +31 -0
- wayward_eagle-0.1.0/wayward_eagle/reduce.py +332 -0
- wayward_eagle-0.1.0/wayward_eagle/tree.py +143 -0
- wayward_eagle-0.1.0/wayward_eagle.egg-info/PKG-INFO +41 -0
- wayward_eagle-0.1.0/wayward_eagle.egg-info/SOURCES.txt +13 -0
- wayward_eagle-0.1.0/wayward_eagle.egg-info/dependency_links.txt +1 -0
- wayward_eagle-0.1.0/wayward_eagle.egg-info/requires.txt +7 -0
- wayward_eagle-0.1.0/wayward_eagle.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wayward-eagle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lower the cognitive complexity of C function bodies, keeping what they do
|
|
5
|
+
Author: Josh Bailey
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/anarkiwi/wayward-eagle
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
12
|
+
Requires-Python: >=3.12
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest; extra == "dev"
|
|
17
|
+
Requires-Dist: pytest-xdist; extra == "dev"
|
|
18
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
19
|
+
Requires-Dist: black; extra == "dev"
|
|
20
|
+
Requires-Dist: pylint; extra == "dev"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# wayward-eagle
|
|
24
|
+
|
|
25
|
+
Lowers the cognitive complexity (SonarSource's metric, as clang-tidy's
|
|
26
|
+
`readability-function-cognitive-complexity` counts it) of C function bodies held as statement
|
|
27
|
+
trees, keeping what each function does. Each rewrite is made only where it lowers the cost.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from wayward_eagle import Function, reduced
|
|
31
|
+
|
|
32
|
+
pieces, sections = reduced(body, "f", Function(params=["a"], local={"v1", "v2"}, void=True))
|
|
33
|
+
for name, args, items in pieces:
|
|
34
|
+
... # print each function: its name, parameters and statements
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
- [Statement trees](docs/trees.md): the input and output.
|
|
38
|
+
- [Rewrites](docs/rewrites.md): what each rewrite does and when it applies.
|
|
39
|
+
|
|
40
|
+
Install: `pip install wayward-eagle`. Development: `pip install -e .[dev]`, then
|
|
41
|
+
`pytest -n auto --cov=wayward_eagle`.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# wayward-eagle
|
|
2
|
+
|
|
3
|
+
Lowers the cognitive complexity (SonarSource's metric, as clang-tidy's
|
|
4
|
+
`readability-function-cognitive-complexity` counts it) of C function bodies held as statement
|
|
5
|
+
trees, keeping what each function does. Each rewrite is made only where it lowers the cost.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from wayward_eagle import Function, reduced
|
|
9
|
+
|
|
10
|
+
pieces, sections = reduced(body, "f", Function(params=["a"], local={"v1", "v2"}, void=True))
|
|
11
|
+
for name, args, items in pieces:
|
|
12
|
+
... # print each function: its name, parameters and statements
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- [Statement trees](docs/trees.md): the input and output.
|
|
16
|
+
- [Rewrites](docs/rewrites.md): what each rewrite does and when it applies.
|
|
17
|
+
|
|
18
|
+
Install: `pip install wayward-eagle`. Development: `pip install -e .[dev]`, then
|
|
19
|
+
`pytest -n auto --cov=wayward_eagle`.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "wayward-eagle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Lower the cognitive complexity of C function bodies, keeping what they do"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "Josh Bailey" }]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3.12",
|
|
16
|
+
"Programming Language :: Python :: 3.13",
|
|
17
|
+
"Operating System :: POSIX :: Linux",
|
|
18
|
+
]
|
|
19
|
+
dependencies = []
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
dev = ["pytest", "pytest-xdist", "pytest-cov", "black", "pylint"]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Repository = "https://github.com/anarkiwi/wayward-eagle"
|
|
26
|
+
|
|
27
|
+
[tool.setuptools]
|
|
28
|
+
packages = ["wayward_eagle"]
|
|
29
|
+
|
|
30
|
+
[tool.black]
|
|
31
|
+
line-length = 100
|
|
32
|
+
|
|
33
|
+
[tool.pylint.format]
|
|
34
|
+
max-line-length = 100
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Rewrites of a C statement tree: sections, tails, early exits, flattened arms, extraction."""
|
|
2
|
+
|
|
3
|
+
from wayward_eagle import (
|
|
4
|
+
Function,
|
|
5
|
+
assigned_first,
|
|
6
|
+
reduced,
|
|
7
|
+
CONTINUE,
|
|
8
|
+
RETURN,
|
|
9
|
+
THRESHOLD,
|
|
10
|
+
cost,
|
|
11
|
+
extracted,
|
|
12
|
+
flattened,
|
|
13
|
+
guarded,
|
|
14
|
+
returning,
|
|
15
|
+
sections,
|
|
16
|
+
tails,
|
|
17
|
+
walk,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def a(name, *reads):
|
|
22
|
+
"""An assignment of ``name`` reading ``reads``."""
|
|
23
|
+
return ("a", name, " + ".join(reads) or "0", frozenset(reads))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def s(text, *reads):
|
|
27
|
+
"""A statement reading ``reads``."""
|
|
28
|
+
return ("s", text, frozenset(reads))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def goto(name):
|
|
32
|
+
"""A jump to label ``name``."""
|
|
33
|
+
return ("j", f"goto {name};", frozenset())
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def label(name):
|
|
37
|
+
"""The label ``name``."""
|
|
38
|
+
return ("l", f"{name}:;", frozenset())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def iff(cond, then, els=(), neg=None):
|
|
42
|
+
"""An ``if`` of ``cond`` (``neg`` its negation)."""
|
|
43
|
+
return ("if", cond, frozenset(), list(then), list(els), neg or f"!({cond})")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_a_label_no_local_crosses_cuts_the_body():
|
|
47
|
+
"""What follows a label no local is used across and no goto crosses (but into it from
|
|
48
|
+
before) is a section of its own."""
|
|
49
|
+
body = [a("v1", "p"), iff("v1", [goto("L1")]), s("w(v1);", "v1"), label("L1"), a("v2", "p")]
|
|
50
|
+
assert sections(body, {"v1", "v2"}) == [("L1", body[:3]), (None, body[4:])]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_a_local_used_across_a_label_keeps_one_section():
|
|
54
|
+
"""A local read after the label it is set before keeps the body whole."""
|
|
55
|
+
body = [a("v1", "p"), label("L1"), s("w(v1);", "v1")]
|
|
56
|
+
assert sections(body, {"v1"}) == [(None, body)]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_a_goto_past_the_label_keeps_one_section():
|
|
60
|
+
"""A goto from before the label to one after it, or back from after it, keeps the body
|
|
61
|
+
whole."""
|
|
62
|
+
past = [iff("p", [goto("L2")]), label("L1"), s("x();"), label("L2"), s("y();")]
|
|
63
|
+
back = [label("L0"), s("x();"), label("L1"), iff("p", [goto("L0")])]
|
|
64
|
+
assert len(sections(past, set())) == 2 and sections(past, set())[0][0] == "L2"
|
|
65
|
+
assert len(sections(back, set())) == 1
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_gotos_to_the_label_ending_a_section_return():
|
|
69
|
+
"""Each goto to the label ending a section, nested ones included, is a return."""
|
|
70
|
+
got = returning([iff("p", [goto("L1")], [goto("L9")])], "L1")
|
|
71
|
+
assert got[0][3] == [RETURN] and got[0][4] == [goto("L9")]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_a_last_if_is_a_guard_where_that_costs_less():
|
|
75
|
+
"""A function's last ``if`` returns first and holds its statements after it where that
|
|
76
|
+
lowers the cognitive complexity (it holds nested control); of one with an ``else``, the
|
|
77
|
+
arm with more nested control is after it; a last ``if`` holding none stays."""
|
|
78
|
+
inner = iff("q", [s("y();")], neg="!q")
|
|
79
|
+
got = guarded([s("x();"), iff("p", [s("z();"), inner], neg="!p")])
|
|
80
|
+
assert got == [s("x();"), ("if", "!p", frozenset(), [RETURN], [], "p"), s("z();"), inner]
|
|
81
|
+
both = [iff("p", [s("x();")], [iff("q", [s("y();"), inner], neg="!q")], neg="!p")]
|
|
82
|
+
assert guarded(both) == [
|
|
83
|
+
("if", "p", frozenset(), [s("x();"), RETURN], [], "!p"),
|
|
84
|
+
("if", "!q", frozenset(), [RETURN], [], "q"),
|
|
85
|
+
s("y();"),
|
|
86
|
+
inner,
|
|
87
|
+
]
|
|
88
|
+
flat = [iff("p", [s("x();")], neg="!p")]
|
|
89
|
+
assert guarded(flat) == flat
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_an_arm_leaving_first_is_the_lighter():
|
|
93
|
+
"""An ``if`` whose arm returns before the rest of a function holds more nested control
|
|
94
|
+
than the rest leaves first by the rest, the arm after it."""
|
|
95
|
+
heavy = [s("x();"), iff("q", [s("y();")], neg="!q"), RETURN]
|
|
96
|
+
got = guarded([iff("p", heavy, neg="!p"), s("z();")])
|
|
97
|
+
assert got == [("if", "!p", frozenset(), [s("z();"), RETURN], [], "p"), *heavy]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_costs_follow_the_cognitive_complexity_rules():
|
|
101
|
+
"""An ``if`` costs one plus its depth, an ``else if`` and an ``else`` one, a ``goto`` one."""
|
|
102
|
+
chain = iff("p", [goto("L1")], [iff("q", [s("x();")], [s("y();")])])
|
|
103
|
+
assert cost([chain]) == 1 + 1 + 1 + 1
|
|
104
|
+
assert cost([iff("p", [iff("q", [])])], 2) == (1 + 2) + (1 + 3)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_an_else_ending_in_a_jump_is_tested_first():
|
|
108
|
+
"""An ``if`` whose ``else`` ends in a jump and whose ``then`` does not tests the other
|
|
109
|
+
way, the jump first and the ``then`` after it, nested ones included; one whose ``then``
|
|
110
|
+
jumps stays."""
|
|
111
|
+
got = flattened(
|
|
112
|
+
[iff("p", [s("x();"), iff("q", [s("y();")], [RETURN], neg="!q")], [RETURN], neg="!p")]
|
|
113
|
+
)
|
|
114
|
+
assert got == [
|
|
115
|
+
("if", "!p", frozenset(), [RETURN], [], "p"),
|
|
116
|
+
s("x();"),
|
|
117
|
+
("if", "!q", frozenset(), [RETURN], [], "q"),
|
|
118
|
+
s("y();"),
|
|
119
|
+
]
|
|
120
|
+
kept = [iff("p", [RETURN], [RETURN])]
|
|
121
|
+
assert flattened(kept) == kept
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def test_a_loop_body_ending_in_an_if_continues():
|
|
125
|
+
"""A loop body's last ``if`` holding nested control continues the loop when its
|
|
126
|
+
condition fails, its statements after it."""
|
|
127
|
+
inner = iff("q", [s("w();")], neg="!q")
|
|
128
|
+
loop = ("loop", "for", "", frozenset(), [s("x();"), iff("p", [s("y();"), inner], neg="!p")])
|
|
129
|
+
body = flattened([loop])[0][4]
|
|
130
|
+
assert body == [s("x();"), ("if", "!p", frozenset(), [CONTINUE], [], "p"), s("y();"), inner]
|
|
131
|
+
switch = ("switch", "k", frozenset(), [((1,), [iff("p", [inner], [RETURN], neg="!p")])])
|
|
132
|
+
assert flattened([switch])[0][3][0][1][0][3] == [RETURN]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_a_label_the_rest_of_a_function_follows_is_a_tail():
|
|
136
|
+
"""From the last top-level label back, each label nothing after it jumps back before
|
|
137
|
+
starts a tail; its parameters are the variables it reads before setting them, the next
|
|
138
|
+
tail's included, and a variable it sets first is none."""
|
|
139
|
+
|
|
140
|
+
def call(t, ps):
|
|
141
|
+
return ("s", f"t_{t}({', '.join(ps)});", frozenset(ps))
|
|
142
|
+
|
|
143
|
+
body = [
|
|
144
|
+
a("v1", "p"),
|
|
145
|
+
a("v2", "p"),
|
|
146
|
+
iff("p", [goto("L2")]),
|
|
147
|
+
label("L1"),
|
|
148
|
+
a("v2", "v1"),
|
|
149
|
+
label("L2"),
|
|
150
|
+
s("w(v2);", "v2"),
|
|
151
|
+
]
|
|
152
|
+
head, chain = tails(body, {"v1", "v2"}, call)
|
|
153
|
+
assert head == body[:3]
|
|
154
|
+
assert chain == [("L1", [body[4]], ["v1"]), ("L2", [body[6]], ["v2"])]
|
|
155
|
+
back = [label("L1"), s("x();"), iff("p", [goto("L1")])]
|
|
156
|
+
assert tails(back, set(), call) == (back, [])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def traps(st):
|
|
160
|
+
"""Whether ``st`` is a call of ``trap``, which never returns."""
|
|
161
|
+
return st[0] == "s" and st[1].startswith("trap(")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def deep(n, *body):
|
|
165
|
+
"""``n`` nested ``if`` statements around ``body``."""
|
|
166
|
+
out = list(body)
|
|
167
|
+
for k in range(n):
|
|
168
|
+
out = [iff(f"c{k}", out)]
|
|
169
|
+
return out
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def test_a_function_above_the_threshold_has_its_deepest_saving_block_extracted():
|
|
173
|
+
"""Above :data:`THRESHOLD`, the nested block that saves the most moves to a function of
|
|
174
|
+
the variables it reads that are used outside it; under it nothing moves."""
|
|
175
|
+
items = [a("v1", "p"), iff("p", deep(6, s("w(v1);", "v1")))]
|
|
176
|
+
got = extracted("f", ["p"], items, {"v1", "p"})
|
|
177
|
+
assert cost(items) > THRESHOLD >= cost(got[0][2]) and got[0][1] == ["p"]
|
|
178
|
+
assert sum(cost(x) for _, _, x in got) < cost(items)
|
|
179
|
+
assert [(n, args) for n, args, _ in got[1:]] == [("f_x1", ["v1"])]
|
|
180
|
+
assert ("s", "f_x1(v1);", frozenset({"v1"})) in walk(got[0][2])
|
|
181
|
+
small = [iff("p", deep(2, s("x();")))]
|
|
182
|
+
assert extracted("g", [], small, set()) == [("g", [], small)]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def test_a_block_control_leaves_early_or_a_goto_enters_stays():
|
|
186
|
+
"""A block a return (but one after a call ``noreturn`` names), a ``break`` of an
|
|
187
|
+
enclosing loop or a fall into the next case leaves, or a goto from outside enters, or
|
|
188
|
+
that sets a variable used outside it, is not extracted."""
|
|
189
|
+
for leave in (
|
|
190
|
+
RETURN,
|
|
191
|
+
("j", "break;", frozenset()),
|
|
192
|
+
("j", "__attribute__((fallthrough));", frozenset()),
|
|
193
|
+
):
|
|
194
|
+
items = [iff("p", deep(6, s("x();"), leave))]
|
|
195
|
+
assert len(extracted("f", [], items, set())) == 1
|
|
196
|
+
trapped = [iff("p", deep(6, s("trap(1);"), RETURN))]
|
|
197
|
+
assert len(extracted("f", [], trapped, set())) == 1
|
|
198
|
+
assert len(extracted("f", [], trapped, set(), traps)) == 2
|
|
199
|
+
entered = [iff("p", deep(6, label("L1"), s("x();"))), goto("L1")]
|
|
200
|
+
assert len(extracted("f", [], entered, set())) == 1
|
|
201
|
+
sets = [iff("p", deep(6, a("v1", "p"))), s("w(v1);", "v1")]
|
|
202
|
+
assert len(extracted("f", [], sets, {"v1"})) == 1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def test_a_function_reduces_to_sections_tails_and_extractions():
|
|
206
|
+
"""A function returning nothing: its independent sections called in turn, a section's
|
|
207
|
+
tail a function its gotos call, and each piece flattened."""
|
|
208
|
+
body = [
|
|
209
|
+
a("v1", "p"),
|
|
210
|
+
iff("v1", [goto("L1")]),
|
|
211
|
+
s("w(v1);", "v1"),
|
|
212
|
+
label("L1"),
|
|
213
|
+
s("x();"),
|
|
214
|
+
label("L2"),
|
|
215
|
+
a("v2", "p"),
|
|
216
|
+
iff("v2", [goto("L3")]),
|
|
217
|
+
s("y(v2);", "v2"),
|
|
218
|
+
label("L3"),
|
|
219
|
+
s("z(v2);", "v2"),
|
|
220
|
+
]
|
|
221
|
+
pieces, sections_ = reduced(body, "f", Function(["p"], {"v1", "v2"}, True))
|
|
222
|
+
assert sections_ == 3
|
|
223
|
+
names = [n for n, _, _ in pieces]
|
|
224
|
+
assert names == ["f_1", "f_2", "f_3", "f_3_L3"]
|
|
225
|
+
tail = dict((n, (args, items)) for n, args, items in pieces)["f_3_L3"]
|
|
226
|
+
assert tail == (["p", "v2"], [s("z(v2);", "v2")])
|
|
227
|
+
kept, one = reduced([RETURN], "g", Function([], set(), False))
|
|
228
|
+
assert one == 1 and kept == [("g", [], [RETURN])]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def test_assignment_comes_before_every_read_on_every_path():
|
|
232
|
+
"""A variable is set before every read when each path sets it first: through both arms
|
|
233
|
+
of an ``if``, not through one, nor across a label control may reach from anywhere."""
|
|
234
|
+
both = [iff("p", [a("v1", "p")], [a("v1", "q")]), s("w(v1);", "v1")]
|
|
235
|
+
one = [iff("p", [a("v1", "p")]), s("w(v1);", "v1")]
|
|
236
|
+
past = [a("v1", "p"), label("L1"), s("w(v1);", "v1")]
|
|
237
|
+
loop = [("loop", "while", "c", frozenset({"v1"}), [a("v1", "p")])]
|
|
238
|
+
switch = [("switch", "k", frozenset(), [((None,), [a("v1", "p")])]), s("w(v1);", "v1")]
|
|
239
|
+
assert assigned_first(both, "v1") and not assigned_first(one, "v1")
|
|
240
|
+
assert not assigned_first(past, "v1") and not assigned_first(loop, "v1")
|
|
241
|
+
assert assigned_first(switch, "v1")
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def test_loops_and_switches_cost_one_plus_their_depth():
|
|
245
|
+
"""A loop or ``switch`` costs one plus its depth, its body one level deeper."""
|
|
246
|
+
loop = ("loop", "for", "", frozenset(), [iff("p", [s("x();")])])
|
|
247
|
+
switch = ("switch", "k", frozenset(), [((1,), [loop])])
|
|
248
|
+
assert cost([loop]) == 1 + 2 and cost([switch], 1) == 2 + 3 + 4
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""wayward-eagle: lower the cognitive complexity of C function bodies, keeping what they do."""
|
|
2
|
+
|
|
3
|
+
from .cost import cost
|
|
4
|
+
from .reduce import (
|
|
5
|
+
THRESHOLD,
|
|
6
|
+
Function,
|
|
7
|
+
calling,
|
|
8
|
+
ending,
|
|
9
|
+
extracted,
|
|
10
|
+
flattened,
|
|
11
|
+
guarded,
|
|
12
|
+
reduced,
|
|
13
|
+
returning,
|
|
14
|
+
sections,
|
|
15
|
+
tails,
|
|
16
|
+
)
|
|
17
|
+
from .tree import (
|
|
18
|
+
CONTINUE,
|
|
19
|
+
RETURN,
|
|
20
|
+
assigned_first,
|
|
21
|
+
children,
|
|
22
|
+
ends_in_jump,
|
|
23
|
+
names_in,
|
|
24
|
+
order,
|
|
25
|
+
own,
|
|
26
|
+
walk,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"CONTINUE",
|
|
31
|
+
"Function",
|
|
32
|
+
"RETURN",
|
|
33
|
+
"THRESHOLD",
|
|
34
|
+
"assigned_first",
|
|
35
|
+
"calling",
|
|
36
|
+
"children",
|
|
37
|
+
"cost",
|
|
38
|
+
"ending",
|
|
39
|
+
"ends_in_jump",
|
|
40
|
+
"extracted",
|
|
41
|
+
"flattened",
|
|
42
|
+
"guarded",
|
|
43
|
+
"names_in",
|
|
44
|
+
"order",
|
|
45
|
+
"own",
|
|
46
|
+
"reduced",
|
|
47
|
+
"returning",
|
|
48
|
+
"sections",
|
|
49
|
+
"tails",
|
|
50
|
+
"walk",
|
|
51
|
+
]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Cognitive complexity of a statement tree (SonarSource's rules, as clang-tidy's
|
|
2
|
+
``readability-function-cognitive-complexity`` counts them)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from .tree import children
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def cost(items, depth=0):
|
|
10
|
+
"""The cognitive complexity of ``items`` at nesting ``depth`` (SonarSource's rules on
|
|
11
|
+
the statements, clang-tidy's ``readability-function-cognitive-complexity``): an ``if``,
|
|
12
|
+
loop or ``switch`` one plus its depth, an ``else if`` and an ``else`` one, a ``goto``
|
|
13
|
+
one; a statement's arms one level deeper. Conditions count the same either way."""
|
|
14
|
+
out = 0
|
|
15
|
+
for st in items:
|
|
16
|
+
if st[0] == "j" and st[1].startswith("goto "):
|
|
17
|
+
out += 1
|
|
18
|
+
elif st[0] == "if":
|
|
19
|
+
out += 1 + depth + _arms(st, depth + 1)
|
|
20
|
+
elif st[0] in ("loop", "switch"):
|
|
21
|
+
out += 1 + depth + sum(cost(sub, depth + 1) for sub in children(st))
|
|
22
|
+
return out
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _arms(st, depth):
|
|
26
|
+
"""The cost of an ``if``'s arms, an ``else`` holding one ``if`` an ``else if``."""
|
|
27
|
+
out, els = cost(st[3], depth), st[4]
|
|
28
|
+
while len(els) == 1 and els[0][0] == "if":
|
|
29
|
+
out += 1 + cost(els[0][3], depth)
|
|
30
|
+
els = els[0][4]
|
|
31
|
+
return out + (1 + cost(els, depth) if els else 0)
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""Rewrites of a C function's statement tree that lower its cognitive complexity and keep
|
|
2
|
+
what it does: sections, tails, early exits, flattened arms and extracted blocks."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import Callable, NamedTuple
|
|
7
|
+
|
|
8
|
+
from .cost import cost
|
|
9
|
+
from .tree import (
|
|
10
|
+
CONTINUE,
|
|
11
|
+
RETURN,
|
|
12
|
+
assigned_first,
|
|
13
|
+
children,
|
|
14
|
+
ends_in_jump,
|
|
15
|
+
labels,
|
|
16
|
+
names_in,
|
|
17
|
+
order,
|
|
18
|
+
targets,
|
|
19
|
+
walk,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
#: The cognitive complexity a function is left at (SonarQube's default for C): above it,
|
|
23
|
+
#: nested blocks are extracted (:func:`extracted`).
|
|
24
|
+
THRESHOLD = 25
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def sections(items, local):
|
|
28
|
+
"""``[(label, items)]`` of a function body cut at each top-level label no variable of
|
|
29
|
+
``local`` is used across and no goto crosses but into it from before: what follows
|
|
30
|
+
the label runs the same whatever ran before it, so each section is a function of its
|
|
31
|
+
own (the label ending the section before it, none after the last)."""
|
|
32
|
+
out, start = [], 0
|
|
33
|
+
for i, st in enumerate(items):
|
|
34
|
+
if st[0] != "l":
|
|
35
|
+
continue
|
|
36
|
+
before, after, lab = items[start:i], items[i + 1 :], st[1][:-2]
|
|
37
|
+
shared = names_in(before) & names_in(after) & local
|
|
38
|
+
if shared or targets(before) & (labels(after) - {lab}):
|
|
39
|
+
continue
|
|
40
|
+
if targets(after) & (labels(before) | {lab}):
|
|
41
|
+
continue
|
|
42
|
+
out.append((lab, before))
|
|
43
|
+
start = i + 1
|
|
44
|
+
return out + [(None, items[start:])]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def tails(items, local, call):
|
|
48
|
+
"""``(head, [(label, items, params)])`` of a function body: from its last top-level
|
|
49
|
+
label back, each label nothing after it jumps back before is the start of a tail, the
|
|
50
|
+
statements after it to the next one, ``params`` the variables of ``local`` the tail
|
|
51
|
+
reads before it sets them (:func:`assigned_first`), the gotos to later tails and the
|
|
52
|
+
fall into the next read as those tails' calls (``call(label, params)``)."""
|
|
53
|
+
out, refs = [], {}
|
|
54
|
+
while True:
|
|
55
|
+
i = next((i for i in range(len(items) - 1, -1, -1) if items[i][0] == "l"), None)
|
|
56
|
+
if i is None:
|
|
57
|
+
return items, out
|
|
58
|
+
before, after, lab = items[:i], items[i + 1 :], items[i][1][:-2]
|
|
59
|
+
if targets(after) & (labels(before) | {lab}) or targets(before) & labels(after):
|
|
60
|
+
return items, out
|
|
61
|
+
body = calling(after, {t: call(t, ps) for t, ps in refs.items()})
|
|
62
|
+
if out:
|
|
63
|
+
body = [*body, call(out[0][0], refs[out[0][0]])]
|
|
64
|
+
live = names_in(body) & names_in(before) & local
|
|
65
|
+
params = sorted((v for v in live if not assigned_first(body, v)), key=order)
|
|
66
|
+
refs[lab] = params
|
|
67
|
+
out.insert(0, (lab, after, params))
|
|
68
|
+
items = before
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def never(_st):
|
|
72
|
+
"""No statement is a call that never returns."""
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Function(NamedTuple):
|
|
77
|
+
"""What the rewrites know of a C function: its parameters, its other variables, whether
|
|
78
|
+
it returns nothing, and whether a statement is a call that never returns."""
|
|
79
|
+
|
|
80
|
+
params: list
|
|
81
|
+
local: set
|
|
82
|
+
void: bool
|
|
83
|
+
noreturn: Callable = never
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def reduced(body, name, fn):
|
|
87
|
+
"""``([(function name, parameters, items)], sections)`` of the statements ``body`` of C
|
|
88
|
+
function ``name`` (:class:`Function` ``fn``), each rewrite lowering cognitive
|
|
89
|
+
complexity: a function returning nothing cut into sections (:func:`sections`,
|
|
90
|
+
``NAME_K``, called in turn), each section's pieces (:func:`_pieces`) then."""
|
|
91
|
+
parts = sections(body, fn.local) if fn.void else [(None, body)]
|
|
92
|
+
pieces = []
|
|
93
|
+
for k, (lab, items) in enumerate(parts, 1):
|
|
94
|
+
sec = name if len(parts) == 1 else f"{name}_{k}"
|
|
95
|
+
pieces += _pieces(sec, returning(items, lab) if lab else items, fn)
|
|
96
|
+
return pieces, len(parts)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _pieces(sec, items, fn):
|
|
100
|
+
"""The functions of section ``sec``: its tails (:func:`tails`, ``SECTION_LABEL``) when
|
|
101
|
+
it returns nothing, each flattened (:func:`flattened`), ended (:func:`guarded`) when it
|
|
102
|
+
returns nothing, and its nested blocks extracted while above :data:`THRESHOLD`
|
|
103
|
+
(:func:`extracted`, ``PIECE_xK``)."""
|
|
104
|
+
params = fn.params
|
|
105
|
+
|
|
106
|
+
def call(t, ps):
|
|
107
|
+
return ("s", f"{sec}_{t}({', '.join(params + ps)});", frozenset(params + ps))
|
|
108
|
+
|
|
109
|
+
first, chain = tails(items, fn.local, call) if fn.void else (items, [])
|
|
110
|
+
calls = {t: call(t, ps) for t, _, ps in chain}
|
|
111
|
+
seq = [(sec, params, first), *((f"{sec}_{t}", params + ps, b) for t, b, ps in chain)]
|
|
112
|
+
out = []
|
|
113
|
+
for j, (name, args, body) in enumerate(seq):
|
|
114
|
+
body = calling(body, calls)
|
|
115
|
+
if j < len(chain) and not ends_in_jump(body):
|
|
116
|
+
body = [*body, calls[chain[j][0]]]
|
|
117
|
+
body = guarded(flattened(body)) if fn.void else flattened(body)
|
|
118
|
+
out += extracted(name, args, body, fn.local | set(params), fn.noreturn)
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _leaves(st, k, items, ctx):
|
|
123
|
+
"""Whether jump ``st``, statement ``k`` of ``items``, leaves them (:func:`_escapes`,
|
|
124
|
+
``ctx`` its ``(noreturn, loops, switches, labels)``)."""
|
|
125
|
+
noreturn, loops, switches, inside = ctx
|
|
126
|
+
text = st[1]
|
|
127
|
+
return (
|
|
128
|
+
"fallthrough" in text
|
|
129
|
+
or (text.startswith("return") and not (k and noreturn(items[k - 1])))
|
|
130
|
+
or (text.startswith("goto ") and text[5:-1] not in inside)
|
|
131
|
+
or (text == "break;" and not loops + switches)
|
|
132
|
+
or (text == "continue;" and not loops)
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _escapes(items, noreturn, loops=0, switches=0, inside=frozenset()):
|
|
137
|
+
"""Whether control may leave ``items`` but by falling off their end: a return (not
|
|
138
|
+
right after a statement ``noreturn`` holds of, a call that never returns), a fall into
|
|
139
|
+
the next case, a ``break`` or ``continue`` of no loop or ``switch`` within them, a goto
|
|
140
|
+
to a label outside them."""
|
|
141
|
+
inside = inside or frozenset(labels(items))
|
|
142
|
+
ctx = (noreturn, loops, switches, inside)
|
|
143
|
+
for k, st in enumerate(items):
|
|
144
|
+
if st[0] == "j":
|
|
145
|
+
hit = _leaves(st, k, items, ctx)
|
|
146
|
+
elif st[0] == "loop":
|
|
147
|
+
hit = _escapes(st[4], noreturn, loops + 1, switches, inside)
|
|
148
|
+
elif st[0] == "switch":
|
|
149
|
+
hit = any(_escapes(b, noreturn, loops, switches + 1, inside) for _, b in st[3])
|
|
150
|
+
else:
|
|
151
|
+
hit = st[0] == "if" and any(
|
|
152
|
+
_escapes(a, noreturn, loops, switches, inside) for a in st[3:5]
|
|
153
|
+
)
|
|
154
|
+
if hit:
|
|
155
|
+
return True
|
|
156
|
+
return False
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _blocks(items, depth=0):
|
|
160
|
+
"""``(block, depth)`` of each statement list nested in ``items``: arms, loop and case
|
|
161
|
+
bodies, at the nesting of their statements."""
|
|
162
|
+
for st in items:
|
|
163
|
+
for sub in children(st):
|
|
164
|
+
yield sub, depth + 1
|
|
165
|
+
yield from _blocks(sub, depth + 1)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _swap(items, block, new):
|
|
169
|
+
"""``items`` with the nested statement list ``block`` (by identity) replaced by ``new``."""
|
|
170
|
+
|
|
171
|
+
def f(st):
|
|
172
|
+
if st[0] == "if":
|
|
173
|
+
return (
|
|
174
|
+
*st[:3],
|
|
175
|
+
new if st[3] is block else _swap(st[3], block, new),
|
|
176
|
+
new if st[4] is block else _swap(st[4], block, new),
|
|
177
|
+
*st[5:],
|
|
178
|
+
)
|
|
179
|
+
if st[0] == "loop":
|
|
180
|
+
return (*st[:4], new if st[4] is block else _swap(st[4], block, new))
|
|
181
|
+
if st[0] == "switch":
|
|
182
|
+
return (
|
|
183
|
+
*st[:3],
|
|
184
|
+
[(lab, new if b is block else _swap(b, block, new)) for lab, b in st[3]],
|
|
185
|
+
)
|
|
186
|
+
return st
|
|
187
|
+
|
|
188
|
+
return [f(st) for st in items]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def extracted(name, args, items, local, noreturn=never):
|
|
192
|
+
"""``[(function name, parameters, items)]`` of function ``name`` (``args`` its
|
|
193
|
+
parameters) and the functions extracted from it: while its cognitive complexity is above
|
|
194
|
+
:data:`THRESHOLD`, the nested block whose statements save the most nesting moved to
|
|
195
|
+
depth 0 that control leaves only by its end (:func:`_escapes` with ``noreturn``), no
|
|
196
|
+
goto outside it enters, and sets no variable used outside it becomes ``NAME_xK`` of the
|
|
197
|
+
variables it reads that are used outside it, and its call; each extracted function in
|
|
198
|
+
turn."""
|
|
199
|
+
out, k = [], 0
|
|
200
|
+
while cost(items) > THRESHOLD:
|
|
201
|
+
best, gain = None, 0
|
|
202
|
+
for block, depth in _blocks(items):
|
|
203
|
+
g = cost(block, depth) - cost(block)
|
|
204
|
+
if g <= gain or _escapes(block, noreturn):
|
|
205
|
+
continue
|
|
206
|
+
rest = _swap(items, block, [])
|
|
207
|
+
if labels(block) & targets(rest):
|
|
208
|
+
continue
|
|
209
|
+
if {st[1] for st in walk(block) if st[0] == "a"} & names_in(rest) & local:
|
|
210
|
+
continue
|
|
211
|
+
best, gain = block, g
|
|
212
|
+
if best is None:
|
|
213
|
+
break
|
|
214
|
+
k += 1
|
|
215
|
+
xname, inputs = f"{name}_x{k}", sorted(
|
|
216
|
+
names_in(best) & names_in(_swap(items, best, [])) & local, key=order
|
|
217
|
+
)
|
|
218
|
+
items = _swap(items, best, [("s", f"{xname}({', '.join(inputs)});", frozenset(inputs))])
|
|
219
|
+
out += extracted(xname, inputs, guarded(best), local, noreturn)
|
|
220
|
+
return [(name, args, items), *out]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _splice(items, f):
|
|
224
|
+
"""``items`` with each statement, nested ones included, replaced by the list ``f``
|
|
225
|
+
gives for it."""
|
|
226
|
+
out = []
|
|
227
|
+
for st in items:
|
|
228
|
+
if st[0] == "if":
|
|
229
|
+
st = (*st[:3], _splice(st[3], f), _splice(st[4], f), *st[5:])
|
|
230
|
+
elif st[0] == "loop":
|
|
231
|
+
st = (*st[:4], _splice(st[4], f))
|
|
232
|
+
elif st[0] == "switch":
|
|
233
|
+
st = (*st[:3], [(lab, _splice(b, f)) for lab, b in st[3]])
|
|
234
|
+
out += f(st)
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def calling(items, calls):
|
|
239
|
+
"""``items`` with each goto to a label of ``calls`` (``{label: call statement}``) the
|
|
240
|
+
call and a return."""
|
|
241
|
+
|
|
242
|
+
def f(st):
|
|
243
|
+
if st[0] == "j" and st[1].startswith("goto ") and st[1][5:-1] in calls:
|
|
244
|
+
return [calls[st[1][5:-1]], RETURN]
|
|
245
|
+
return [st]
|
|
246
|
+
|
|
247
|
+
return _splice(items, f)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _map(items, f):
|
|
251
|
+
"""``items`` with each statement, nested ones included, replaced by ``f`` of it."""
|
|
252
|
+
out = []
|
|
253
|
+
for st in items:
|
|
254
|
+
st = f(st)
|
|
255
|
+
if st[0] == "if":
|
|
256
|
+
st = (*st[:3], _map(st[3], f), _map(st[4], f), *st[5:])
|
|
257
|
+
elif st[0] == "loop":
|
|
258
|
+
st = (*st[:4], _map(st[4], f))
|
|
259
|
+
elif st[0] == "switch":
|
|
260
|
+
st = (*st[:3], [(lab, _map(b, f)) for lab, b in st[3]])
|
|
261
|
+
out.append(st)
|
|
262
|
+
return out
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def returning(items, label):
|
|
266
|
+
"""``items`` of a section, each goto to the ``label`` ending it a return."""
|
|
267
|
+
jump = ("j", f"goto {label};")
|
|
268
|
+
return _map(items, lambda st: RETURN if st[:2] == jump else st)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _exits(items, i, jump):
|
|
272
|
+
"""The rewrites of ``if`` statement ``i`` of ``items`` that leave by ``jump`` first."""
|
|
273
|
+
st, last = items[i], i == len(items) - 1
|
|
274
|
+
if last:
|
|
275
|
+
pairs = [(st[4], st[3], st[5], st[1]), (st[3], st[4], st[1], st[5])]
|
|
276
|
+
elif not st[4] and ends_in_jump(st[3]):
|
|
277
|
+
pairs = [(items[i + 1 :], st[3], st[5], st[1])]
|
|
278
|
+
else:
|
|
279
|
+
return []
|
|
280
|
+
out = []
|
|
281
|
+
for first, rest, cond, neg in pairs:
|
|
282
|
+
first = first if ends_in_jump(first) else [*first, jump]
|
|
283
|
+
out.append(([*items[:i], ("if", cond, st[2], first, [], neg)], rest))
|
|
284
|
+
return out
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def ending(items, jump, depth=0):
|
|
288
|
+
"""``items`` ending a function or loop body at nesting ``depth`` (``jump`` its ``return``
|
|
289
|
+
or ``continue``), each ``if`` that ends this level either way leaving first by one arm,
|
|
290
|
+
ending in ``jump``, and the other after it at this level, wherever that lowers the
|
|
291
|
+
cognitive complexity (:func:`cost`) once the statements moved up end the level in turn: a
|
|
292
|
+
last ``if`` either way round, one whose arm leaves before the rest with the rest as the
|
|
293
|
+
arm leaving first. Each rewrite lowers the cost and recurs only into the statements of
|
|
294
|
+
one ``if``, so the rewrites end."""
|
|
295
|
+
while True:
|
|
296
|
+
low, best = cost(items, depth), None
|
|
297
|
+
for i in range(len(items) - 1, -1, -1):
|
|
298
|
+
for head, rest in _exits(items, i, jump) if items[i][0] == "if" else ():
|
|
299
|
+
got = [*head, *ending(rest, jump, depth)]
|
|
300
|
+
c = cost(got, depth)
|
|
301
|
+
if c < low:
|
|
302
|
+
low, best = c, got
|
|
303
|
+
if best is None:
|
|
304
|
+
return items
|
|
305
|
+
items = best
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def guarded(items):
|
|
309
|
+
"""``items`` ending a function that returns nothing (:func:`ending` with ``return``)."""
|
|
310
|
+
return ending(items, RETURN)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def flattened(items, depth=0):
|
|
314
|
+
"""``items`` at nesting ``depth`` with each ``if`` whose ``else`` ends in a jump and whose
|
|
315
|
+
``then`` does not tested the other way, its ``else`` the jumping arm and its ``then``
|
|
316
|
+
after it, wherever that lowers the cognitive complexity (:func:`cost`), and each loop
|
|
317
|
+
body ending in an ``if`` rewritten to continue first (:func:`ending`)."""
|
|
318
|
+
out = []
|
|
319
|
+
for st in items:
|
|
320
|
+
if st[0] == "if":
|
|
321
|
+
st = (*st[:3], flattened(st[3], depth + 1), flattened(st[4], depth + 1), *st[5:])
|
|
322
|
+
if st[4] and ends_in_jump(st[4]) and not ends_in_jump(st[3]):
|
|
323
|
+
alt = [("if", st[5], st[2], st[4], [], st[1]), *st[3]]
|
|
324
|
+
if cost(alt, depth) < cost([st], depth):
|
|
325
|
+
out += alt
|
|
326
|
+
continue
|
|
327
|
+
elif st[0] == "loop":
|
|
328
|
+
st = (*st[:4], ending(flattened(st[4], depth + 1), CONTINUE, depth + 1))
|
|
329
|
+
elif st[0] == "switch":
|
|
330
|
+
st = (*st[:3], [(lab, flattened(b, depth + 1)) for lab, b in st[3]])
|
|
331
|
+
out.append(st)
|
|
332
|
+
return out
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""The statement tree of a C function body and what it reads, writes and jumps to.
|
|
2
|
+
|
|
3
|
+
Statements: ``("a", name, text, refs)`` an assignment, ``("s", text, refs)``, ``("j", text,
|
|
4
|
+
refs)`` a jump, ``("l", text, refs)`` a label, ``("if", cond, refs, then, else, negated
|
|
5
|
+
cond)``, ``("loop", kind, cond, refs, body)`` (kind ``for``, ``while`` or ``do``) and
|
|
6
|
+
``("switch", sel, refs, [(labels, body)])``; ``refs`` the variables a statement reads.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
RETURN = ("j", "return;", frozenset())
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
CONTINUE = ("j", "continue;", frozenset())
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def own(st):
|
|
18
|
+
"""The variables statement ``st`` reads or writes outside its nested statements."""
|
|
19
|
+
if st[0] == "a":
|
|
20
|
+
return st[3] | {st[1]}
|
|
21
|
+
return st[2] if st[0] in ("s", "j", "l", "if", "switch") else st[3]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def children(st):
|
|
25
|
+
"""The statement lists nested in ``st``."""
|
|
26
|
+
if st[0] == "if":
|
|
27
|
+
return [st[3], st[4]]
|
|
28
|
+
if st[0] == "loop":
|
|
29
|
+
return [st[4]]
|
|
30
|
+
if st[0] == "switch":
|
|
31
|
+
return [b for _, b in st[3]]
|
|
32
|
+
return []
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def walk(items):
|
|
36
|
+
"""Every statement of ``items``, nested ones included, in order."""
|
|
37
|
+
for st in items:
|
|
38
|
+
yield st
|
|
39
|
+
for sub in children(st):
|
|
40
|
+
yield from walk(sub)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def names_in(items):
|
|
44
|
+
"""Every variable ``items`` read or write."""
|
|
45
|
+
out = set()
|
|
46
|
+
for st in items:
|
|
47
|
+
out |= own(st)
|
|
48
|
+
for sub in children(st):
|
|
49
|
+
out |= names_in(sub)
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def assigned_first(items, v):
|
|
54
|
+
"""Whether every read of ``v`` in ``items`` follows an assignment on every path."""
|
|
55
|
+
return _da(items, v, False)[1]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _da(items, v, done): # pylint: disable=too-many-return-statements,too-many-branches
|
|
59
|
+
"""``(definitely assigned after, no read before assignment)`` over ``items``; control
|
|
60
|
+
reaching a label may come from anywhere, so nothing is assigned there."""
|
|
61
|
+
gone = False
|
|
62
|
+
for st in items:
|
|
63
|
+
kind = st[0]
|
|
64
|
+
if kind == "l":
|
|
65
|
+
done, gone = False, False
|
|
66
|
+
continue
|
|
67
|
+
if gone:
|
|
68
|
+
continue
|
|
69
|
+
if kind == "a":
|
|
70
|
+
if v in st[3] and not done:
|
|
71
|
+
return done, False
|
|
72
|
+
done = done or st[1] == v
|
|
73
|
+
elif kind == "d":
|
|
74
|
+
if v in st[3] and not done:
|
|
75
|
+
return done, False
|
|
76
|
+
done = done or any(n == v and e is not None for n, e in st[2])
|
|
77
|
+
elif kind in ("s", "j"):
|
|
78
|
+
if v in st[2] and not done:
|
|
79
|
+
return done, False
|
|
80
|
+
if kind == "j":
|
|
81
|
+
done, gone = True, True
|
|
82
|
+
elif kind == "if":
|
|
83
|
+
if v in st[2] and not done:
|
|
84
|
+
return done, False
|
|
85
|
+
a, ok = _da(st[3], v, done)
|
|
86
|
+
b, ok2 = _da(st[4], v, done)
|
|
87
|
+
if not (ok and ok2):
|
|
88
|
+
return done, False
|
|
89
|
+
done = a and b
|
|
90
|
+
elif kind == "loop":
|
|
91
|
+
if v in st[3] and not done and st[1] == "while":
|
|
92
|
+
return done, False
|
|
93
|
+
after, ok = _da(st[4], v, done)
|
|
94
|
+
if not ok or (v in st[3] and not after and st[1] == "do"):
|
|
95
|
+
return done, False
|
|
96
|
+
else:
|
|
97
|
+
if v in st[2] and not done:
|
|
98
|
+
return done, False
|
|
99
|
+
arms = [_da(b, v, done) for _, b in st[3]]
|
|
100
|
+
if not all(ok for _, ok in arms):
|
|
101
|
+
return done, False
|
|
102
|
+
dflt = any(None in labels for labels, _ in st[3])
|
|
103
|
+
done = done or (dflt and all(a for a, _ in arms))
|
|
104
|
+
return done, True
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def ends_in_jump(items):
|
|
108
|
+
"""Whether control never falls off the end of ``items``."""
|
|
109
|
+
if not items:
|
|
110
|
+
return False
|
|
111
|
+
last = items[-1]
|
|
112
|
+
if last[0] == "j":
|
|
113
|
+
return True
|
|
114
|
+
if last[0] == "if":
|
|
115
|
+
return bool(last[4]) and ends_in_jump(last[3]) and ends_in_jump(last[4])
|
|
116
|
+
return last[0] == "loop" and last[1] == "for" and not _breaks(last[4])
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _breaks(items):
|
|
120
|
+
"""Whether ``items`` break out of their loop."""
|
|
121
|
+
for st in items:
|
|
122
|
+
if st[0] == "j" and st[1] == "break;":
|
|
123
|
+
return True
|
|
124
|
+
if st[0] == "if" and (_breaks(st[3]) or _breaks(st[4])):
|
|
125
|
+
return True
|
|
126
|
+
if st[0] == "switch" and any(_breaks(b) for _, b in st[3]):
|
|
127
|
+
return True
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def targets(items):
|
|
132
|
+
"""The labels the gotos of ``items`` jump to, nested ones included."""
|
|
133
|
+
return {st[1][5:-1] for st in walk(items) if st[0] == "j" and st[1].startswith("goto ")}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def labels(items):
|
|
137
|
+
"""The labels of ``items``, nested ones included."""
|
|
138
|
+
return {st[1][:-2] for st in walk(items) if st[0] == "l"}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def order(name):
|
|
142
|
+
"""A variable's sort key: its number after the prefix letter."""
|
|
143
|
+
return (len(name), name)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wayward-eagle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lower the cognitive complexity of C function bodies, keeping what they do
|
|
5
|
+
Author: Josh Bailey
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/anarkiwi/wayward-eagle
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
12
|
+
Requires-Python: >=3.12
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest; extra == "dev"
|
|
17
|
+
Requires-Dist: pytest-xdist; extra == "dev"
|
|
18
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
19
|
+
Requires-Dist: black; extra == "dev"
|
|
20
|
+
Requires-Dist: pylint; extra == "dev"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# wayward-eagle
|
|
24
|
+
|
|
25
|
+
Lowers the cognitive complexity (SonarSource's metric, as clang-tidy's
|
|
26
|
+
`readability-function-cognitive-complexity` counts it) of C function bodies held as statement
|
|
27
|
+
trees, keeping what each function does. Each rewrite is made only where it lowers the cost.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from wayward_eagle import Function, reduced
|
|
31
|
+
|
|
32
|
+
pieces, sections = reduced(body, "f", Function(params=["a"], local={"v1", "v2"}, void=True))
|
|
33
|
+
for name, args, items in pieces:
|
|
34
|
+
... # print each function: its name, parameters and statements
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
- [Statement trees](docs/trees.md): the input and output.
|
|
38
|
+
- [Rewrites](docs/rewrites.md): what each rewrite does and when it applies.
|
|
39
|
+
|
|
40
|
+
Install: `pip install wayward-eagle`. Development: `pip install -e .[dev]`, then
|
|
41
|
+
`pytest -n auto --cov=wayward_eagle`.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
tests/test_reduce.py
|
|
5
|
+
wayward_eagle/__init__.py
|
|
6
|
+
wayward_eagle/cost.py
|
|
7
|
+
wayward_eagle/reduce.py
|
|
8
|
+
wayward_eagle/tree.py
|
|
9
|
+
wayward_eagle.egg-info/PKG-INFO
|
|
10
|
+
wayward_eagle.egg-info/SOURCES.txt
|
|
11
|
+
wayward_eagle.egg-info/dependency_links.txt
|
|
12
|
+
wayward_eagle.egg-info/requires.txt
|
|
13
|
+
wayward_eagle.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
wayward_eagle
|