assert-cpp-definition-is-used 20261130053311__py3-none-any.whl

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.
File without changes
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,270 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING, NoReturn
8
+
9
+ from .scanner import Request, ScanError, display, load, read_units, scan
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Sequence
13
+
14
+ from .scanner import Definition, Scan, Unit
15
+
16
+ EXIT_SUCCESS = 0
17
+ EXIT_FINDINGS = 1
18
+ EXIT_ERROR = 2
19
+
20
+ DEFAULT_ROOT = "main"
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Plan:
25
+ units: list[Unit]
26
+ request: Request
27
+ database: str
28
+
29
+
30
+ def positive(value: str) -> int:
31
+ number = int(value)
32
+ if number < 1:
33
+ raise argparse.ArgumentTypeError(f"{value} is not a positive count")
34
+ return number
35
+
36
+
37
+ def create_parser() -> argparse.ArgumentParser:
38
+ parser = argparse.ArgumentParser(
39
+ prog="assert-cpp-definition-is-used",
40
+ description=(
41
+ "Assert that every C++ definition in the given trees is reached from a root of "
42
+ "the program. A definition nothing the program runs can reach keeps its tests "
43
+ "and its coverage, so nothing else reports it."
44
+ ),
45
+ )
46
+
47
+ parser.add_argument(
48
+ "trees",
49
+ nargs="+",
50
+ metavar="TREE",
51
+ help=(
52
+ "The trees whose definitions are checked. A definition outside them is "
53
+ "followed when working out what is reachable but is never reported."
54
+ ),
55
+ )
56
+
57
+ parser.add_argument(
58
+ "--build-dir",
59
+ required=True,
60
+ metavar="DIR",
61
+ help="A directory holding compile_commands.json, as CMake writes it.",
62
+ )
63
+
64
+ parser.add_argument(
65
+ "--sources",
66
+ action="append",
67
+ default=None,
68
+ metavar="TREE",
69
+ help=(
70
+ "Parse only the translation units whose source file lies under this tree, "
71
+ "repeatable. Together they make up the program. Defaults to the trees."
72
+ ),
73
+ )
74
+
75
+ parser.add_argument(
76
+ "--root",
77
+ action="append",
78
+ default=None,
79
+ dest="roots",
80
+ metavar="NAME",
81
+ help=(
82
+ "The fully qualified name of a function the program is entered through, "
83
+ "repeatable. Defaults to main."
84
+ ),
85
+ )
86
+
87
+ parser.add_argument(
88
+ "--roots-declared-in",
89
+ action="append",
90
+ default=None,
91
+ metavar="HEADER",
92
+ help="Every function this header declares is a root, repeatable.",
93
+ )
94
+
95
+ parser.add_argument(
96
+ "--libclang",
97
+ metavar="PATH",
98
+ help="The libclang shared library to parse with. Defaults to the bundled one.",
99
+ )
100
+
101
+ parser.add_argument(
102
+ "--jobs",
103
+ type=positive,
104
+ default=os.cpu_count() or 1,
105
+ metavar="N",
106
+ help="How many translation units are parsed at once. Defaults to the processors.",
107
+ )
108
+
109
+ parser.add_argument(
110
+ "--exclude",
111
+ metavar="PATTERNS",
112
+ help=(
113
+ "Comma-separated glob patterns. A matching source file is not parsed, and a "
114
+ "definition in a matching file is not reported."
115
+ ),
116
+ )
117
+
118
+ output_group = parser.add_mutually_exclusive_group()
119
+ output_group.add_argument(
120
+ "--quiet",
121
+ action="store_true",
122
+ help="Suppress all output. Exit code indicates success (0) or findings (1).",
123
+ )
124
+ output_group.add_argument(
125
+ "--count",
126
+ action="store_true",
127
+ help="Output only the count of findings.",
128
+ )
129
+ output_group.add_argument(
130
+ "--verbose",
131
+ action="store_true",
132
+ help=(
133
+ "Show the translation units parsed, each place a dependent name falls back "
134
+ "to every entity of that name, the findings and a summary."
135
+ ),
136
+ )
137
+
138
+ behavior_group = parser.add_mutually_exclusive_group()
139
+ behavior_group.add_argument(
140
+ "--fail-fast",
141
+ action="store_true",
142
+ help="Report only the first dead definition.",
143
+ )
144
+ behavior_group.add_argument(
145
+ "--warn-only",
146
+ action="store_true",
147
+ help="Always exit with code 0, even if findings exist.",
148
+ )
149
+
150
+ return parser
151
+
152
+
153
+ def parse_patterns(patterns_str: str | None) -> list[str]:
154
+ if not patterns_str:
155
+ return []
156
+ return [pattern.strip() for pattern in patterns_str.split(",") if pattern.strip()]
157
+
158
+
159
+ def existing(paths: Sequence[str]) -> list[str]:
160
+ for path in paths:
161
+ if not os.path.exists(path):
162
+ raise ScanError(f"Path not found: {path}")
163
+ return [os.path.realpath(path) for path in paths]
164
+
165
+
166
+ def root_names(roots: Sequence[str] | None) -> list[str]:
167
+ return [name.removeprefix("::") for name in roots] if roots else [DEFAULT_ROOT]
168
+
169
+
170
+ def prepare(args: argparse.Namespace) -> Plan:
171
+ trees = existing(args.trees)
172
+ sources = existing(args.sources or args.trees)
173
+ exclude = parse_patterns(args.exclude)
174
+ libclang = load(args.libclang)
175
+ database = os.path.join(args.build_dir, "compile_commands.json")
176
+ units = read_units(args.build_dir, sources, exclude)
177
+ if not units:
178
+ shown = ", ".join(display(source) for source in sources)
179
+ raise ScanError(f"{database} lists no translation unit under {shown}")
180
+ request = Request(
181
+ libclang=libclang,
182
+ trees=tuple(trees),
183
+ root_names=tuple(root_names(args.roots)),
184
+ root_headers=tuple(os.path.realpath(h) for h in args.roots_declared_in or ()),
185
+ exclude=tuple(exclude),
186
+ )
187
+ return Plan(units=units, request=request, database=database)
188
+
189
+
190
+ def unnamed_roots(args: argparse.Namespace, result: Scan) -> list[str]:
191
+ problems = [
192
+ f"--root {name} names nothing"
193
+ for name, wanted in zip(args.roots or (), root_names(args.roots))
194
+ if not result.roots.named.get(wanted)
195
+ ]
196
+ problems.extend(
197
+ f"--roots-declared-in {header} declares no function"
198
+ for header in args.roots_declared_in or ()
199
+ if not result.roots.declared.get(os.path.realpath(header))
200
+ )
201
+ return problems
202
+
203
+
204
+ def describe(definition: Definition) -> str:
205
+ where = f"{display(definition.path)}:{definition.line}:{definition.column}"
206
+ return f"{where}: {definition.kind} {definition.name} is reached from no root"
207
+
208
+
209
+ def fail(problems: Sequence[str]) -> NoReturn:
210
+ for problem in problems:
211
+ print(f"Error: {problem}", file=sys.stderr)
212
+ sys.exit(EXIT_ERROR)
213
+
214
+
215
+ def announce(plan: Plan) -> None:
216
+ request = plan.request
217
+ print(f"Reading {len(plan.units)} translation unit(s) from {plan.database}.")
218
+ print(f"Checking definitions under: {', '.join(display(t) for t in request.trees)}")
219
+ print(f"Roots: {', '.join(request.root_names)}")
220
+ for header in request.root_headers:
221
+ print(f"Roots declared in: {display(header)}")
222
+ if request.exclude:
223
+ print(f"Excluding patterns: {', '.join(request.exclude)}")
224
+ print()
225
+ for unit in plan.units:
226
+ print(f"Parsing: {display(unit.path)}")
227
+
228
+
229
+ def summarize(plan: Plan, result: Scan, findings: Sequence[Definition]) -> None:
230
+ for site in sorted(result.sites, key=lambda s: (s.path, s.line, s.column, s.name)):
231
+ where = f"{display(site.path)}:{site.line}:{site.column}"
232
+ print(f"Falling back to every entity named {site.name}: {where}")
233
+ print()
234
+ print(f"Translation units parsed: {len(plan.units)}")
235
+ print(f"Definitions checked: {len(result.definitions)}")
236
+ print(f"Roots: {len(result.roots.keys())}")
237
+ print(f"Findings: {len(findings)}")
238
+ for finding in findings:
239
+ print(f" Dead: {describe(finding)}")
240
+
241
+
242
+ def report(
243
+ args: argparse.Namespace, plan: Plan, result: Scan, findings: Sequence[Definition]
244
+ ) -> None:
245
+ if args.verbose:
246
+ summarize(plan, result, findings)
247
+ elif args.count:
248
+ print(len(findings))
249
+ elif not args.quiet:
250
+ for finding in findings:
251
+ print(describe(finding))
252
+
253
+
254
+ def main(argv: Sequence[str] | None = None) -> None:
255
+ args = create_parser().parse_args(argv)
256
+ try:
257
+ plan = prepare(args)
258
+ except ScanError as error:
259
+ fail([str(error)])
260
+ if args.verbose:
261
+ announce(plan)
262
+ result = scan(plan.units, plan.request, args.jobs)
263
+ problems = [*result.errors, *unnamed_roots(args, result)]
264
+ if problems:
265
+ fail(problems)
266
+ findings = result.dead()
267
+ if args.fail_fast:
268
+ findings = findings[:1]
269
+ report(args, plan, result, findings)
270
+ sys.exit(EXIT_SUCCESS if args.warn_only or not findings else EXIT_FINDINGS)
File without changes