smelt-cli 0.2.0__py3-none-win_amd64.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.
Files changed (133) hide show
  1. smelt/__init__.py +6 -0
  2. smelt/__main__.py +5 -0
  3. smelt/analysis/__init__.py +45 -0
  4. smelt/analysis/annotations.py +105 -0
  5. smelt/analysis/cache.py +168 -0
  6. smelt/analysis/context.py +147 -0
  7. smelt/analysis/contracts.py +210 -0
  8. smelt/analysis/coverage.py +377 -0
  9. smelt/analysis/definition_blocks.py +569 -0
  10. smelt/analysis/enum_values.py +217 -0
  11. smelt/analysis/errors.py +11 -0
  12. smelt/analysis/exports.py +166 -0
  13. smelt/analysis/files.py +279 -0
  14. smelt/analysis/function_usage.py +123 -0
  15. smelt/analysis/graphs.py +77 -0
  16. smelt/analysis/identity.py +64 -0
  17. smelt/analysis/import_cache.py +98 -0
  18. smelt/analysis/imports.py +452 -0
  19. smelt/analysis/literals.py +17 -0
  20. smelt/analysis/member_state.py +108 -0
  21. smelt/analysis/members.py +975 -0
  22. smelt/analysis/ordering.py +399 -0
  23. smelt/analysis/ordering_rewrite.py +232 -0
  24. smelt/analysis/package_exports.py +58 -0
  25. smelt/analysis/parsing.py +126 -0
  26. smelt/analysis/python_version.py +164 -0
  27. smelt/analysis/retained.py +84 -0
  28. smelt/analysis/syntax.py +109 -0
  29. smelt/analysis/test_awaits.py +91 -0
  30. smelt/analysis/test_cases.py +84 -0
  31. smelt/analysis/test_deadlines.py +90 -0
  32. smelt/analysis/test_outcomes.py +71 -0
  33. smelt/analysis/test_subprocesses.py +107 -0
  34. smelt/analysis/test_syntax.py +1425 -0
  35. smelt/analysis/test_timing.py +76 -0
  36. smelt/analysis/type_dispatch.py +193 -0
  37. smelt/analysis/workspace.py +146 -0
  38. smelt/cli/__init__.py +3 -0
  39. smelt/cli/app.py +300 -0
  40. smelt/cli/commands/__init__.py +62 -0
  41. smelt/cli/commands/adopt.py +274 -0
  42. smelt/cli/commands/check.py +151 -0
  43. smelt/cli/commands/discover.py +51 -0
  44. smelt/cli/commands/info.py +112 -0
  45. smelt/cli/session.py +163 -0
  46. smelt/cli/session_slots.py +43 -0
  47. smelt/cli/support.py +90 -0
  48. smelt/config/__init__.py +36 -0
  49. smelt/config/discovery.py +93 -0
  50. smelt/config/errors.py +51 -0
  51. smelt/config/loader.py +282 -0
  52. smelt/config/models.py +717 -0
  53. smelt/config/patterns.py +47 -0
  54. smelt/config/schema.py +23 -0
  55. smelt/config/source.py +56 -0
  56. smelt/config/validation.py +180 -0
  57. smelt/diagnostics/__init__.py +0 -0
  58. smelt/diagnostics/debt.py +226 -0
  59. smelt/diagnostics/dedupe.py +41 -0
  60. smelt/diagnostics/groups.py +109 -0
  61. smelt/diagnostics/render/__init__.py +0 -0
  62. smelt/diagnostics/render/machine.py +237 -0
  63. smelt/diagnostics/render/text.py +321 -0
  64. smelt/diagnostics/report.py +104 -0
  65. smelt/diagnostics/suppressions.py +80 -0
  66. smelt/diagnostics/violation.py +120 -0
  67. smelt/docs.py +98 -0
  68. smelt/engine/__init__.py +0 -0
  69. smelt/engine/briefing.py +630 -0
  70. smelt/engine/cache.py +65 -0
  71. smelt/engine/changes.py +260 -0
  72. smelt/engine/check.py +724 -0
  73. smelt/engine/coverage.py +151 -0
  74. smelt/engine/evaluation.py +291 -0
  75. smelt/engine/file_checks.py +94 -0
  76. smelt/engine/git_source.py +140 -0
  77. smelt/engine/inference.py +854 -0
  78. smelt/engine/mirror_inference.py +95 -0
  79. smelt/engine/native_git.py +190 -0
  80. smelt/engine/ordering_fixes.py +132 -0
  81. smelt/engine/paths.py +163 -0
  82. smelt/engine/result_cache.py +208 -0
  83. smelt/engine/rule_settings.py +164 -0
  84. smelt/engine/schema.py +58 -0
  85. smelt/engine/staged.py +75 -0
  86. smelt/engine/workspace.py +5 -0
  87. smelt/model/__init__.py +9 -0
  88. smelt/model/architecture.py +234 -0
  89. smelt/py.typed +0 -0
  90. smelt/rules/__init__.py +0 -0
  91. smelt/rules/activation.py +129 -0
  92. smelt/rules/base.py +131 -0
  93. smelt/rules/catalog.json +600 -0
  94. smelt/rules/common.py +164 -0
  95. smelt/rules/dependencies/__init__.py +0 -0
  96. smelt/rules/dependencies/composition_root.py +86 -0
  97. smelt/rules/dependencies/cycles.py +329 -0
  98. smelt/rules/dependencies/fanout.py +81 -0
  99. smelt/rules/dependencies/features.py +165 -0
  100. smelt/rules/dependencies/interfaces.py +84 -0
  101. smelt/rules/dependencies/layers.py +138 -0
  102. smelt/rules/dependencies/third_party.py +132 -0
  103. smelt/rules/member_names.py +13 -0
  104. smelt/rules/meta.py +74 -0
  105. smelt/rules/registry.py +132 -0
  106. smelt/rules/structure/__init__.py +0 -0
  107. smelt/rules/structure/assignments.py +114 -0
  108. smelt/rules/structure/contracts.py +71 -0
  109. smelt/rules/structure/coverage.py +100 -0
  110. smelt/rules/structure/enum_values.py +50 -0
  111. smelt/rules/structure/headers.py +143 -0
  112. smelt/rules/structure/import_style.py +145 -0
  113. smelt/rules/structure/layout.py +202 -0
  114. smelt/rules/structure/members.py +116 -0
  115. smelt/rules/structure/naming.py +132 -0
  116. smelt/rules/structure/ordering.py +83 -0
  117. smelt/rules/structure/package_imports.py +117 -0
  118. smelt/rules/structure/type_dispatch.py +79 -0
  119. smelt/rules/testing/__init__.py +0 -0
  120. smelt/rules/testing/awaits.py +46 -0
  121. smelt/rules/testing/cases.py +47 -0
  122. smelt/rules/testing/location.py +537 -0
  123. smelt/rules/testing/mocking.py +140 -0
  124. smelt/rules/testing/outcomes.py +119 -0
  125. smelt/rules/testing/private_access.py +93 -0
  126. smelt/rules/testing/public_attributes.py +62 -0
  127. smelt/rules/testing/public_functions.py +52 -0
  128. smelt/rules/testing/timing.py +62 -0
  129. smelt_cli-0.2.0.data/scripts/smelt.exe +0 -0
  130. smelt_cli-0.2.0.dist-info/METADATA +103 -0
  131. smelt_cli-0.2.0.dist-info/RECORD +133 -0
  132. smelt_cli-0.2.0.dist-info/WHEEL +4 -0
  133. smelt_cli-0.2.0.dist-info/sboms/smelt-cli.cyclonedx.json +5462 -0
@@ -0,0 +1,569 @@
1
+ """Statements that can be considered together without executing source code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from collections import Counter
7
+ from dataclasses import dataclass
8
+ from typing import TYPE_CHECKING
9
+
10
+ if TYPE_CHECKING:
11
+ from smelt.config.models import OrderingConfig
12
+
13
+ type ScopeNode = ast.Module | ast.ClassDef
14
+ type FunctionNode = ast.FunctionDef | ast.AsyncFunctionDef
15
+
16
+ _TYPE_FACTORIES = frozenset(
17
+ {
18
+ f"{root}.{name}"
19
+ for root in ("typing", "typing_extensions")
20
+ for name in ("TypeVar", "TypeVarTuple", "ParamSpec")
21
+ }
22
+ )
23
+ _OVERLOAD = frozenset({"typing.overload", "typing_extensions.overload"})
24
+ _WRAPPERS = frozenset(
25
+ {"builtins.property", "builtins.staticmethod", "builtins.classmethod"}
26
+ )
27
+ _INIT = frozenset({"__init__", "__new__", "__post_init__"})
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class DefinitionBlock:
32
+ nodes: tuple[ast.stmt, ...]
33
+ first: int
34
+ stop: int
35
+ label: str
36
+ key: str
37
+ category: str
38
+ binds: frozenset[str]
39
+ reads: frozenset[str]
40
+ barrier: str | None = None
41
+ fix_reason: str | None = None
42
+ fix_node: ast.expr | None = None
43
+
44
+ @property
45
+ def line(self) -> int:
46
+ return min(statement_line(node) for node in self.nodes)
47
+
48
+ @property
49
+ def end_line(self) -> int:
50
+ return max(node.end_lineno or node.lineno for node in self.nodes)
51
+
52
+
53
+ def statement_line(node: ast.stmt) -> int:
54
+ decorators = (
55
+ node.decorator_list
56
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef)
57
+ else []
58
+ )
59
+ return min([node.lineno, *(decorator.lineno for decorator in decorators)])
60
+
61
+
62
+ def is_main_guard(node: ast.stmt) -> bool:
63
+ if not isinstance(node, ast.If) or not isinstance(node.test, ast.Compare):
64
+ return False
65
+ test = node.test
66
+ if len(test.ops) != 1 or not isinstance(test.ops[0], ast.Eq):
67
+ return False
68
+ left, right = test.left, test.comparators[0]
69
+ return (
70
+ isinstance(left, ast.Name)
71
+ and left.id == "__name__"
72
+ and isinstance(right, ast.Constant)
73
+ and right.value == "__main__"
74
+ ) or (
75
+ isinstance(right, ast.Name)
76
+ and right.id == "__name__"
77
+ and isinstance(left, ast.Constant)
78
+ and left.value == "__main__"
79
+ )
80
+
81
+
82
+ def _extra_bound_names(node: ast.stmt) -> frozenset[str]:
83
+ if isinstance(node, ast.AugAssign):
84
+ return (
85
+ frozenset({node.target.id})
86
+ if isinstance(node.target, ast.Name)
87
+ else frozenset()
88
+ )
89
+ if isinstance(node, ast.TypeAlias):
90
+ return frozenset({node.name.id})
91
+ if isinstance(node, ast.Delete):
92
+ return frozenset(
93
+ child.id
94
+ for target in node.targets
95
+ for child in ast.walk(target)
96
+ if isinstance(child, ast.Name)
97
+ )
98
+ return frozenset()
99
+
100
+
101
+ def _bound_names(node: ast.stmt) -> frozenset[str]:
102
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
103
+ return frozenset({node.name})
104
+ if isinstance(node, ast.Assign):
105
+ return frozenset(
106
+ child.id
107
+ for target in node.targets
108
+ for child in ast.walk(target)
109
+ if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store)
110
+ )
111
+ if (
112
+ isinstance(node, ast.AnnAssign)
113
+ and isinstance(node.target, ast.Name)
114
+ and node.value is not None
115
+ ):
116
+ return frozenset({node.target.id})
117
+ if isinstance(node, ast.Import | ast.ImportFrom):
118
+ return frozenset(
119
+ alias.asname
120
+ or (
121
+ alias.name.split(".")[0] if isinstance(node, ast.Import) else alias.name
122
+ )
123
+ for alias in node.names
124
+ if alias.name != "*"
125
+ )
126
+ return _extra_bound_names(node)
127
+
128
+
129
+ def _forget_conditional_aliases(node: ast.stmt, aliases: dict[str, str]) -> None:
130
+ for child in ast.walk(node):
131
+ if isinstance(child, ast.stmt):
132
+ for name in _bound_names(child):
133
+ aliases.pop(name, None)
134
+ if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store | ast.Del):
135
+ aliases.pop(child.id, None)
136
+ if isinstance(child, ast.ImportFrom) and any(
137
+ alias.name == "*" for alias in child.names
138
+ ):
139
+ aliases.clear()
140
+
141
+
142
+ def _namespace_mutation(node: ast.stmt) -> bool:
143
+ targets = (
144
+ node.targets
145
+ if isinstance(node, ast.Assign | ast.Delete)
146
+ else [node.target]
147
+ if isinstance(node, ast.AnnAssign | ast.AugAssign)
148
+ else []
149
+ )
150
+ return any(
151
+ isinstance(child, ast.Attribute | ast.Subscript)
152
+ for target in targets
153
+ for child in ast.walk(target)
154
+ )
155
+
156
+
157
+ def _update_aliases(node: ast.stmt, aliases: dict[str, str]) -> None:
158
+ for name in _bound_names(node):
159
+ aliases.pop(name, None)
160
+ if _namespace_mutation(node):
161
+ aliases.clear()
162
+ return
163
+ for expression in _eager_expressions(node, deferred=False):
164
+ for child in ast.walk(expression):
165
+ if isinstance(child, ast.NamedExpr) and isinstance(child.target, ast.Name):
166
+ aliases.pop(child.target.id, None)
167
+ if isinstance(node, ast.ImportFrom) and any(
168
+ alias.name == "*" for alias in node.names
169
+ ):
170
+ aliases.clear()
171
+ return
172
+ if isinstance(node, ast.Import):
173
+ for alias in node.names:
174
+ aliases[alias.asname or alias.name.split(".")[0]] = (
175
+ alias.name if alias.asname else alias.name.split(".")[0]
176
+ )
177
+ elif isinstance(node, ast.ImportFrom) and node.level == 0:
178
+ for alias in node.names:
179
+ if alias.name != "*":
180
+ aliases[alias.asname or alias.name] = f"{node.module}.{alias.name}"
181
+ elif isinstance(
182
+ node,
183
+ ast.If | ast.Try | ast.TryStar | ast.With | ast.For | ast.While | ast.Match,
184
+ ):
185
+ _forget_conditional_aliases(node, aliases)
186
+
187
+
188
+ def _qualified_name(node: ast.expr, aliases: dict[str, str]) -> str | None:
189
+ if isinstance(node, ast.Name):
190
+ return aliases.get(node.id)
191
+ if isinstance(node, ast.Attribute):
192
+ parent = _qualified_name(node.value, aliases)
193
+ return f"{parent}.{node.attr}" if parent else None
194
+ return None
195
+
196
+
197
+ def _eager_expressions(node: ast.stmt, *, deferred: bool) -> list[ast.expr]:
198
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
199
+ args = node.args
200
+ found = [
201
+ *node.decorator_list,
202
+ *args.defaults,
203
+ *(item for item in args.kw_defaults if item is not None),
204
+ ]
205
+ if not deferred:
206
+ parameters = [
207
+ *args.posonlyargs,
208
+ *args.args,
209
+ *args.kwonlyargs,
210
+ *([args.vararg] if args.vararg else []),
211
+ *([args.kwarg] if args.kwarg else []),
212
+ ]
213
+ found.extend(
214
+ arg.annotation for arg in parameters if arg.annotation is not None
215
+ )
216
+ if node.returns is not None:
217
+ found.append(node.returns)
218
+ return found
219
+ if isinstance(node, ast.ClassDef):
220
+ return [
221
+ *node.decorator_list,
222
+ *node.bases,
223
+ *(item.value for item in node.keywords),
224
+ ]
225
+ if isinstance(node, ast.Assign):
226
+ return [node.value]
227
+ if isinstance(node, ast.AnnAssign):
228
+ return [
229
+ *([node.value] if node.value is not None else []),
230
+ *([node.annotation] if not deferred else []),
231
+ ]
232
+ return []
233
+
234
+
235
+ class _Reads(ast.NodeVisitor):
236
+ def __init__(self) -> None:
237
+ self.names: set[str] = set()
238
+
239
+ def visit_Name(self, node: ast.Name) -> None:
240
+ if isinstance(node.ctx, ast.Load):
241
+ self.names.add(node.id)
242
+
243
+ def visit_Lambda(self, node: ast.Lambda) -> None:
244
+ for value in [
245
+ *node.args.defaults,
246
+ *(item for item in node.args.kw_defaults if item is not None),
247
+ ]:
248
+ self.visit(value)
249
+
250
+
251
+ def build_blocks(
252
+ owner: ScopeNode,
253
+ *,
254
+ scope: str,
255
+ config: OrderingConfig,
256
+ aliases: dict[str, str],
257
+ deferred: bool,
258
+ ) -> tuple[list[DefinitionBlock], list[tuple[ast.ClassDef, dict[str, str]]]]:
259
+ body = owner.body
260
+ in_class = isinstance(owner, ast.ClassDef)
261
+ blocks: list[DefinitionBlock] = []
262
+ children: list[tuple[ast.ClassDef, dict[str, str]]] = []
263
+ counts: Counter[str] = Counter()
264
+ index = 0
265
+ while index < len(body):
266
+ first = index
267
+ node = body[index]
268
+ group = _family(body, first)
269
+ index += len(group) - 1
270
+ if isinstance(node, ast.ClassDef):
271
+ children.append((node, dict(aliases)))
272
+ category = (
273
+ "docstring"
274
+ if first == 0
275
+ and isinstance(node, ast.Expr)
276
+ and isinstance(node.value, ast.Constant)
277
+ and isinstance(node.value.value, str)
278
+ else _category(node, in_class=in_class, config=config, aliases=aliases)
279
+ )
280
+ label = (
281
+ node.name
282
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef)
283
+ else _assignment_name(node) or ast.unparse(node).splitlines()[0]
284
+ )
285
+ key = f"{scope}.{label}#{counts[label]}"
286
+ counts[label] += 1
287
+ binds: set[str] = set()
288
+ reads: set[str] = set()
289
+ reason = None
290
+ member_aliases = dict(aliases)
291
+ for member in group:
292
+ reads.update(_definition_reads(member, deferred=deferred) - binds)
293
+ binds.update(_bound_names(member))
294
+ reason = reason or _barrier(member, member_aliases, deferred=deferred)
295
+ property_member = isinstance(
296
+ member, ast.FunctionDef | ast.AsyncFunctionDef
297
+ ) and any(
298
+ _qualified_name(decorator, member_aliases) == "builtins.property"
299
+ or (
300
+ isinstance(decorator, ast.Attribute)
301
+ and isinstance(decorator.value, ast.Name)
302
+ and decorator.value.id == member.name
303
+ and member_aliases.get(member.name) == "builtins.property-instance"
304
+ )
305
+ for decorator in member.decorator_list
306
+ )
307
+ _update_aliases(member, member_aliases)
308
+ if property_member and isinstance(
309
+ member, ast.FunctionDef | ast.AsyncFunctionDef
310
+ ):
311
+ member_aliases[member.name] = "builtins.property-instance"
312
+ if in_class and isinstance(node, ast.ClassDef):
313
+ reason = "nested class creation is an execution boundary"
314
+ if category == "docstring":
315
+ reason = "docstring position is fixed"
316
+ if (
317
+ first > 0
318
+ and (body[first - 1].end_lineno or body[first - 1].lineno)
319
+ >= statement_line(node)
320
+ ) or (
321
+ index + 1 < len(body)
322
+ and (group[-1].end_lineno or group[-1].lineno)
323
+ >= statement_line(body[index + 1])
324
+ ):
325
+ reason = "statements share a physical line"
326
+ fix_node = _factory_fix_node(node, aliases)
327
+ fix_reason = (
328
+ "nonliteral type-variable construction requires review"
329
+ if fix_node
330
+ else None
331
+ )
332
+ blocks.append(
333
+ DefinitionBlock(
334
+ tuple(group),
335
+ first,
336
+ index + 1,
337
+ label,
338
+ key,
339
+ category,
340
+ frozenset(binds),
341
+ frozenset(reads),
342
+ reason,
343
+ fix_reason,
344
+ fix_node,
345
+ )
346
+ )
347
+ aliases.clear()
348
+ aliases.update(member_aliases)
349
+ index += 1
350
+ return blocks, children
351
+
352
+
353
+ def _expression_reads(expressions: list[ast.expr]) -> frozenset[str]:
354
+ visitor = _Reads()
355
+ for expression in expressions:
356
+ visitor.visit(expression)
357
+ return frozenset(visitor.names)
358
+
359
+
360
+ def _definition_reads(node: ast.stmt, *, deferred: bool) -> frozenset[str]:
361
+ reads = set(_expression_reads(_eager_expressions(node, deferred=deferred)))
362
+ if isinstance(node, ast.ClassDef):
363
+ local: set[str] = set()
364
+ for child in node.body:
365
+ reads.update(_definition_reads(child, deferred=deferred) - local)
366
+ local.update(_bound_names(child))
367
+ return frozenset(reads)
368
+
369
+
370
+ def _pure_expression(node: ast.expr) -> bool:
371
+ if isinstance(node, ast.Name | ast.Constant):
372
+ return True
373
+ if isinstance(node, ast.Tuple | ast.List):
374
+ return all(_pure_expression(item) for item in node.elts)
375
+ if isinstance(node, ast.Dict):
376
+ return all(isinstance(key, ast.Constant) for key in node.keys) and all(
377
+ _pure_expression(value) for value in node.values
378
+ )
379
+ if isinstance(node, ast.Set):
380
+ return all(isinstance(item, ast.Constant) for item in node.elts)
381
+ if isinstance(node, ast.Lambda):
382
+ return all(
383
+ _pure_expression(item)
384
+ for item in [
385
+ *node.args.defaults,
386
+ *(value for value in node.args.kw_defaults if value is not None),
387
+ ]
388
+ )
389
+ return False
390
+
391
+
392
+ def _wrapper(node: ast.expr, function: FunctionNode, aliases: dict[str, str]) -> bool:
393
+ if _qualified_name(node, aliases) in _OVERLOAD | _WRAPPERS:
394
+ return True
395
+ return (
396
+ isinstance(node, ast.Attribute)
397
+ and isinstance(node.value, ast.Name)
398
+ and node.value.id == function.name
399
+ and aliases.get(function.name) == "builtins.property-instance"
400
+ and node.attr in {"getter", "setter", "deleter"}
401
+ )
402
+
403
+
404
+ def _safe_function(
405
+ node: FunctionNode, aliases: dict[str, str], *, deferred: bool
406
+ ) -> str | None:
407
+ if node.type_params:
408
+ return "generic type parameters are an execution boundary"
409
+ if not all(_wrapper(decorator, node, aliases) for decorator in node.decorator_list):
410
+ return "unrecognized decorators execute at definition time"
411
+ expressions = _eager_expressions(node, deferred=deferred)[
412
+ len(node.decorator_list) :
413
+ ]
414
+ return (
415
+ None
416
+ if all(_pure_expression(value) for value in expressions)
417
+ else "default or eager annotation evaluation may execute code"
418
+ )
419
+
420
+
421
+ def _assignment_name(node: ast.stmt) -> str | None:
422
+ target = (
423
+ node.targets[0]
424
+ if isinstance(node, ast.Assign) and len(node.targets) == 1
425
+ else node.target
426
+ if isinstance(node, ast.AnnAssign)
427
+ else None
428
+ )
429
+ return target.id if isinstance(target, ast.Name) else None
430
+
431
+
432
+ def _type_factory(node: ast.stmt, aliases: dict[str, str]) -> bool:
433
+ return (
434
+ isinstance(node, ast.Assign | ast.AnnAssign)
435
+ and isinstance(node.value, ast.Call)
436
+ and _qualified_name(node.value.func, aliases) in _TYPE_FACTORIES
437
+ )
438
+
439
+
440
+ def _visibility(name: str) -> str:
441
+ return (
442
+ "private"
443
+ if name.startswith("_") and not (name.startswith("__") and name.endswith("__"))
444
+ else "public"
445
+ )
446
+
447
+
448
+ def _assignment_category(
449
+ node: ast.Assign | ast.AnnAssign,
450
+ *,
451
+ in_class: bool,
452
+ config: OrderingConfig,
453
+ aliases: dict[str, str],
454
+ ) -> str:
455
+ name = _assignment_name(node)
456
+ if in_class:
457
+ return "class-attributes"
458
+ if name and name.startswith("__") and name.endswith("__"):
459
+ return "dunder-assignments"
460
+ if _type_factory(node, aliases):
461
+ return "type-vars"
462
+ if name and config.constants_exempt and name.lstrip("_").isupper():
463
+ return "public"
464
+ return _visibility(name or "_")
465
+
466
+
467
+ def _definition_category(
468
+ node: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef, *, in_class: bool
469
+ ) -> str:
470
+ if in_class and isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
471
+ if node.name in _INIT:
472
+ return "init"
473
+ if node.name.startswith("__") and node.name.endswith("__"):
474
+ return "dunders"
475
+ return _visibility(node.name)
476
+
477
+
478
+ def _category(
479
+ node: ast.stmt, *, in_class: bool, config: OrderingConfig, aliases: dict[str, str]
480
+ ) -> str:
481
+ if (
482
+ isinstance(node, ast.ImportFrom)
483
+ and node.module == "__future__"
484
+ and node.level == 0
485
+ ):
486
+ return "future-imports"
487
+ if isinstance(node, ast.Import | ast.ImportFrom):
488
+ return "imports"
489
+ if is_main_guard(node):
490
+ return "main-guard"
491
+ if isinstance(node, ast.Assign | ast.AnnAssign):
492
+ return _assignment_category(
493
+ node, in_class=in_class, config=config, aliases=aliases
494
+ )
495
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
496
+ return _definition_category(node, in_class=in_class)
497
+ return "barrier"
498
+
499
+
500
+ def _class_barrier(
501
+ node: ast.ClassDef, aliases: dict[str, str], *, deferred: bool
502
+ ) -> str | None:
503
+ if node.bases or node.keywords or node.decorator_list or node.type_params:
504
+ return "class creation may execute bases, decorators or metaclass behavior"
505
+ for child in node.body:
506
+ if isinstance(child, ast.ClassDef):
507
+ return "nested class creation is an execution boundary"
508
+ if isinstance(child, ast.Pass) or (
509
+ isinstance(child, ast.Expr)
510
+ and isinstance(child.value, ast.Constant)
511
+ and isinstance(child.value.value, str)
512
+ ):
513
+ continue
514
+ if _barrier(child, aliases, deferred=deferred) is not None:
515
+ return "class body contains an execution boundary"
516
+ return None
517
+
518
+
519
+ def _barrier(node: ast.stmt, aliases: dict[str, str], *, deferred: bool) -> str | None:
520
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
521
+ return _safe_function(node, aliases, deferred=deferred)
522
+ if isinstance(node, ast.ClassDef):
523
+ return _class_barrier(node, aliases, deferred=deferred)
524
+ if isinstance(node, ast.Assign | ast.AnnAssign):
525
+ if _assignment_name(node) is None:
526
+ return "mutation or multiple assignment targets"
527
+ if _type_factory(node, aliases) and isinstance(node.value, ast.Call):
528
+ call = node.value
529
+ safe = all(_pure_expression(value) for value in call.args) and all(
530
+ item.arg is not None and _pure_expression(item.value)
531
+ for item in call.keywords
532
+ )
533
+ return None if safe else "type-variable arguments may execute code"
534
+ return (
535
+ None
536
+ if all(
537
+ _pure_expression(value)
538
+ for value in _eager_expressions(node, deferred=deferred)
539
+ )
540
+ else "assignment may execute calls, operators or protocols"
541
+ )
542
+ return "import, control flow, registration or other executable statement"
543
+
544
+
545
+ def _family(body: list[ast.stmt], first: int) -> list[ast.stmt]:
546
+ node = body[first]
547
+ group = [node]
548
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
549
+ for following in body[first + 1 :]:
550
+ if (
551
+ not isinstance(following, ast.FunctionDef | ast.AsyncFunctionDef)
552
+ or following.name != node.name
553
+ ):
554
+ break
555
+ group.append(following)
556
+ return group
557
+
558
+
559
+ def _factory_fix_node(node: ast.stmt, aliases: dict[str, str]) -> ast.expr | None:
560
+ if (
561
+ not _type_factory(node, aliases)
562
+ or not isinstance(node, ast.Assign | ast.AnnAssign)
563
+ or not isinstance(node.value, ast.Call)
564
+ ):
565
+ return None
566
+ values = [*node.value.args, *(item.value for item in node.value.keywords)]
567
+ return next(
568
+ (value for value in values if not isinstance(value, ast.Constant)), None
569
+ )