graphlore 0.7.0__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.
graphlore/review.py ADDED
@@ -0,0 +1,1121 @@
1
+ """Review analyses over the graph: unreferenced code, same-named symbols, layer rules.
2
+
3
+ Each is exact and needs no embedding model. They read the graph's own edges and,
4
+ where a claim needs checking against the source (a decorator that registers a
5
+ function, a name mentioned in a template or a config file), the files under
6
+ ``config.PROJECT_DIR`` through the confined readers of :mod:`graphlore.spans`.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import hashlib
12
+ import os
13
+ import re
14
+ from collections import Counter
15
+ from typing import Any
16
+
17
+ from . import config
18
+ from .graph import (
19
+ _IMPORT_RELATIONS,
20
+ _NON_DEPENDENCY_RELATIONS,
21
+ _bare_name,
22
+ _edge_ends,
23
+ _file_import_edges,
24
+ _is_file_hub_node,
25
+ _is_test_path,
26
+ _lang_family,
27
+ _node_file,
28
+ _node_id,
29
+ _node_label,
30
+ _node_line,
31
+ _rel,
32
+ )
33
+ from .imports import ImportChecker
34
+ from .scope import _clean_pattern, _path_matches, _vendored_by_path
35
+ from .spans import (
36
+ _cached_file_analysis,
37
+ _is_test_node,
38
+ _is_ts_symbol,
39
+ _norm_relpath,
40
+ _resolve_in_project,
41
+ _span_of_definition,
42
+ _spans_for_file,
43
+ _ts_bound_function,
44
+ _ts_parser_for,
45
+ _ts_skeleton,
46
+ )
47
+
48
+ # Extensions whose nodes are source definitions (not config keys or doc headings).
49
+ _CODE_EXTS = frozenset({
50
+ ".py", ".pyi", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts",
51
+ ".go", ".java", ".kt", ".kts", ".rs", ".c", ".h", ".cc", ".cpp", ".hpp",
52
+ ".cxx", ".hxx", ".cs", ".rb", ".php", ".swift", ".scala", ".m", ".mm",
53
+ ".lua", ".zig", ".ex", ".exs",
54
+ })
55
+ _IDENT = re.compile(r"[A-Za-z_$][A-Za-z0-9_$]*")
56
+ # A decorator / annotation / attribute at the start of a line: `@app.route`,
57
+ # Java `@Test`, C# `[Fact]`, Rust `#[test]`.
58
+ _DECORATOR_LINE = re.compile(r"^\s*(?:@\s*|#\s*\[\s*|\[\s*)([A-Za-z_][\w.:]*)")
59
+ # How far below the first line of a definition its name may sit: Java, C#, Swift
60
+ # and Kotlin count the annotations as part of the declaration.
61
+ _DECORATOR_REACH = 12
62
+ # An identifier, and whether it is reached as an attribute (`obj.name`).
63
+ _MENTION = re.compile(r"(\.\s*)?([A-Za-z_$][A-Za-z0-9_$]*)")
64
+
65
+
66
+ def _int_line(n: dict) -> int:
67
+ try:
68
+ return int(_node_line(n))
69
+ except (TypeError, ValueError):
70
+ return 0
71
+
72
+
73
+ class _Definitions:
74
+ """Which nodes are definitions, of what kind, and how they nest.
75
+
76
+ ``kind`` is "function", "method" or "class". graphify >= 0.9 marks callables
77
+ (``_callable`` / ``_callable_class``); older graphs are read from the label
78
+ convention (``name()``, ``.method()``) and from containment — a class is an
79
+ identifier-labelled code node that a file contains or that has methods.
80
+ """
81
+
82
+ def __init__(self, nodes: list[dict], edges: list[dict]) -> None:
83
+ self.byid: dict[str, dict] = {_node_id(n): n for n in nodes}
84
+ self.parent: dict[str, str] = {}
85
+ self.members: dict[str, list[str]] = {}
86
+ self.incoming: dict[str, list[tuple[str, dict]]] = {}
87
+ has_methods: set[str] = set()
88
+ contained: set[str] = set()
89
+ for e in edges:
90
+ s, t = _edge_ends(e)
91
+ rel = _rel(e)
92
+ if rel == "method":
93
+ has_methods.add(s)
94
+ self.parent.setdefault(t, s)
95
+ self.members.setdefault(s, []).append(t)
96
+ elif rel == "contains":
97
+ contained.add(t)
98
+ self.parent.setdefault(t, s)
99
+ elif s != t and rel not in _NON_DEPENDENCY_RELATIONS:
100
+ self.incoming.setdefault(t, []).append((s, e))
101
+ self._classes: dict[str, list[str]] | None = None
102
+ self._member_names: dict[str, frozenset[str]] = {}
103
+ # _hook_base's answers, per (method name, bases, depth), for this graph
104
+ self.hooks: dict[tuple[str, tuple[str, ...], int], str | None] = {}
105
+ self.kind: dict[str, str] = {}
106
+ for nid, n in self.byid.items():
107
+ k = self._kind(n, nid in has_methods, nid in contained)
108
+ if k:
109
+ self.kind[nid] = k
110
+
111
+ @staticmethod
112
+ def _kind(n: dict, has_methods: bool, contained: bool) -> str:
113
+ f = _node_file(n)
114
+ dot = f.rfind(".")
115
+ if not f or dot < 0 or f[dot:].lower() not in _CODE_EXTS or _is_file_hub_node(n):
116
+ return ""
117
+ if str(n.get("file_type") or "code").lower() != "code":
118
+ return ""
119
+ label = _node_label(n)
120
+ # the native engine says what a node is: a variable, a field or a
121
+ # constant is no class, however it hangs off its file
122
+ if str(n.get("kind", "")).lower() in ("variable", "property", "constant", "heading"):
123
+ return ""
124
+ if n.get("_callable_class"):
125
+ return "class"
126
+ if label.endswith("()"):
127
+ return "method" if label.startswith(".") else "function"
128
+ if n.get("_callable"):
129
+ return "function"
130
+ if (has_methods or contained) and _IDENT.fullmatch(label):
131
+ return "class"
132
+ return ""
133
+
134
+ def classes_named(self, name: str) -> list[str]:
135
+ """Ids of the project's class definitions with this bare name."""
136
+ if self._classes is None:
137
+ self._classes = {}
138
+ for nid, kind in self.kind.items():
139
+ if kind == "class":
140
+ self._classes.setdefault(
141
+ _bare_name(_node_label(self.byid[nid])), []
142
+ ).append(nid)
143
+ return self._classes.get(name, [])
144
+
145
+ def member_names(self, nid: str) -> frozenset[str]:
146
+ """Bare names of the members (``method`` edges) of ``nid``."""
147
+ got = self._member_names.get(nid)
148
+ if got is None:
149
+ got = frozenset(_bare_name(_node_label(self.byid[m]))
150
+ for m in self.members.get(nid, ()) if m in self.byid)
151
+ self._member_names[nid] = got
152
+ return got
153
+
154
+ def is_top_level(self, nid: str) -> bool:
155
+ """Defined directly in a file (not a method, not nested in a function)."""
156
+ parent = self.byid.get(self.parent.get(nid, ""))
157
+ return parent is None or _is_file_hub_node(parent)
158
+
159
+ def referencing_files(self, nid: str, relations: frozenset[str] | None = None) -> set[str]:
160
+ """Other files with an edge into ``nid`` (or, for a class, into its members)."""
161
+ own = _node_file(self.byid[nid])
162
+ family = {nid, *self.members.get(nid, ())}
163
+ out: set[str] = set()
164
+ for target in family:
165
+ for src, e in self.incoming.get(target, ()):
166
+ if src in family or (relations is not None and _rel(e) not in relations):
167
+ continue
168
+ n = self.byid.get(src)
169
+ f = (_node_file(n) if n else "") or str(e.get("source_file") or "")
170
+ if f and f != own:
171
+ out.add(f)
172
+ return out
173
+
174
+
175
+ # ---------------------------------------------------------------------------
176
+ # Unreferenced code
177
+ # ---------------------------------------------------------------------------
178
+
179
+ # Decorators that change how a function behaves but hand it to no one: a function
180
+ # carrying only these is still dead when nothing references it. Compared against
181
+ # the last dotted segment, lower-cased. Any OTHER decorator is taken to register
182
+ # the function somewhere the graph cannot see (a route table, a CLI group, a
183
+ # validator list, a pytest fixture registry).
184
+ _NEUTRAL_DECORATORS = frozenset({
185
+ "staticmethod", "classmethod", "wraps", "lru_cache", "cache", "cached",
186
+ "contextmanager", "asynccontextmanager", "dataclass", "total_ordering",
187
+ "overload", "final", "override", "abstractmethod", "deprecated",
188
+ "no_type_check", "suppresswarnings", "safevarargs", "functionalinterface",
189
+ "inline", "noinline", "nonnull", "nullable", "notnull",
190
+ # Rust / C# / Swift / Kotlin attributes that say how to compile or lint a
191
+ # definition, not that something will call it
192
+ "must_use", "derive", "doc", "allow", "warn", "deny", "cfg", "cfg_attr", "repr",
193
+ "non_exhaustive", "track_caller", "obsolete", "methodimpl", "attributeusage",
194
+ "serializable", "debuggerdisplay", "available", "discardableresult", "sendable",
195
+ "jvmstatic", "jvmoverloads", "jvmfield", "jvmname", "throws", "suppress", "optin",
196
+ })
197
+ _MENTION_SKIP_DIRS = frozenset({
198
+ "node_modules", "venv", "env", "__pycache__", "dist", "build", "target",
199
+ "site-packages",
200
+ })
201
+ _MENTION_MAX_BYTES = 1_000_000
202
+ _MENTION_MAX_FILES = 20_000
203
+
204
+
205
+ # The line opening a class: `class V(ast.NodeVisitor):`, `class Handler extends
206
+ # Base {`, `class Repo : IRepo`. Group 1 is the class name, group 2 what follows it.
207
+ _CLASS_LINE = re.compile(
208
+ r"^\s*(?:(?:export|public|private|protected|abstract|final|default|static|open|"
209
+ r"sealed|data)\s+)*class\s+([\w$]+)\s*(?:<[^>]*>)?\s*(.*)$"
210
+ )
211
+ _INHERITANCE_RELATIONS = frozenset({"inherits", "extends", "implements", "mixes_in"})
212
+ # Bases that never call back into a subclass's ordinary methods: markers, data
213
+ # containers and the exception hierarchy. A method under only these is not a hook.
214
+ _NON_HOOK_BASES = frozenset({
215
+ "ABC", "ABCMeta", "object", "Object", "Protocol", "Generic", "BaseModel", "Enum",
216
+ "IntEnum", "StrEnum", "Flag", "IntFlag", "NamedTuple", "TypedDict", "Exception",
217
+ "BaseException", "Any",
218
+ })
219
+ _NON_HOOK_SUFFIXES = ("Error", "Exception", "Warning")
220
+
221
+
222
+ def _class_bases(text: str) -> list[str]:
223
+ """Base-class names on a class line, last dotted segment, generics stripped.
224
+
225
+ ``class X(A, b.C[T], metaclass=M):`` -> [A, C]; ``class X extends A implements
226
+ I, J {`` -> [A, I, J]; ``class X : A(), B`` -> [A, B]. [] when it names none.
227
+ """
228
+ m = _CLASS_LINE.match(text)
229
+ if not m:
230
+ return []
231
+ rest = m.group(2).strip()
232
+ raw: list[str] = []
233
+ if rest.startswith("("):
234
+ depth, cur = 0, ""
235
+ for ch in rest[1:]:
236
+ if ch in "([{":
237
+ depth += 1
238
+ elif ch in ")]}":
239
+ if depth == 0:
240
+ break
241
+ depth -= 1
242
+ if ch == "," and depth == 0:
243
+ raw.append(cur)
244
+ cur = ""
245
+ else:
246
+ cur += ch
247
+ raw.append(cur)
248
+ raw = [r for r in raw if "=" not in r] # metaclass=..., total=...
249
+ elif rest.startswith(("extends", "implements")):
250
+ for part in re.split(r"\bextends\b|\bimplements\b", rest.split("{")[0]):
251
+ raw += part.split(",")
252
+ elif rest.startswith(":"):
253
+ raw = rest[1:].split("{")[0].split(",")
254
+ out: list[str] = []
255
+ for r in raw:
256
+ name = re.split(r"[\[<(]", r.strip())[0].strip().split()[-1:] or [""]
257
+ last = name[0].rsplit(".", 1)[-1]
258
+ if last and _IDENT.fullmatch(last):
259
+ out.append(last)
260
+ return out
261
+
262
+
263
+ def _is_non_hook_base(name: str) -> bool:
264
+ return name in _NON_HOOK_BASES or name.endswith(_NON_HOOK_SUFFIXES)
265
+
266
+
267
+ def _enclosing_class_bases(file: str, line: int, lines: _SourceLines) -> list[str] | None:
268
+ """Bases of the class the definition at ``line`` is written directly inside.
269
+
270
+ None when it is not inside a class. Read from the source, because graphify
271
+ gives no node to a class nested in a function — exactly where visitor and
272
+ event-handler subclasses tend to live.
273
+ """
274
+ at = lines.spans_at(file, line)
275
+ if not at:
276
+ return None
277
+ own = at[0]
278
+ spans = lines.spans(file)
279
+ outer = [s for s in spans if s[0] <= own[0] and s[1] >= own[1] and s is not own]
280
+ if not outer:
281
+ return None
282
+ parent = min(outer, key=lambda s: s[1] - s[0])
283
+ text = lines.get(file)
284
+ if not 0 < parent[2] <= len(text) or not _CLASS_LINE.match(text[parent[2] - 1]):
285
+ return None
286
+ return _class_bases(text[parent[2] - 1])
287
+
288
+
289
+ def _hook_base(
290
+ name: str, bases: list[str], defs: _Definitions, lines: _SourceLines, depth: int = 0
291
+ ) -> str | None:
292
+ """The base class that may call a subclass's method ``name``, if any.
293
+
294
+ A base outside the project (a framework class such as ``ast.NodeVisitor``)
295
+ may: its code is not here to read. A base inside the project does only if it
296
+ defines or mentions a method of that name, or one of ITS bases may. Marker
297
+ and data bases (``ABC``, ``Protocol``, ``BaseModel``, exceptions) never do.
298
+ """
299
+ # Memoized per call (``defs`` is): a popular base (Django's ``TestCase``,
300
+ # ``Model``) is asked about once per method of every subclass, and the same
301
+ # base chain is reached again through each class that shares a name.
302
+ key = (name, tuple(bases), depth)
303
+ if key not in defs.hooks:
304
+ defs.hooks[key] = _hook_base_uncached(name, bases, defs, lines, depth)
305
+ return defs.hooks[key]
306
+
307
+
308
+ def _hook_base_uncached(
309
+ name: str, bases: list[str], defs: _Definitions, lines: _SourceLines, depth: int
310
+ ) -> str | None:
311
+ for base in bases:
312
+ if _is_non_hook_base(base):
313
+ continue
314
+ project = defs.classes_named(base)
315
+ if not project:
316
+ return base
317
+ for nid in project:
318
+ n = defs.byid[nid]
319
+ file, line = _node_file(n), _int_line(n)
320
+ if name in defs.member_names(nid):
321
+ return base
322
+ span = _span_for(file, line, lines)
323
+ if span is not None and name in lines.tokens(file, span):
324
+ return base
325
+ text = lines.get(file)
326
+ if depth < 4 and 0 < line <= len(text):
327
+ above = _hook_base(name, _class_bases(text[line - 1]), defs, lines, depth + 1)
328
+ if above:
329
+ return above
330
+ return None
331
+
332
+
333
+ def _span_for(
334
+ file: str, line: int, lines: _SourceLines | None = None
335
+ ) -> tuple[int, int] | None:
336
+ """(region_start, end) of the definition at ``line``, from the span engine.
337
+
338
+ With ``lines``, the file's spans come from that per-call index.
339
+ """
340
+ if line <= 0:
341
+ return None
342
+ if lines is not None:
343
+ exact = lines.spans_at(file, line)
344
+ spans = lines.spans(file) if not exact else []
345
+ else:
346
+ spans = _spans_for_file(file)
347
+ exact = [s for s in spans if s[2] == line]
348
+ here = exact or [s for s in spans if s[0] <= line <= s[1]]
349
+ if not here:
350
+ return None
351
+ rs, end, _dl, _q = min(here, key=lambda s: s[1] - s[0])
352
+ return rs, end
353
+
354
+
355
+ class _SourceLines:
356
+ """Per-call cache of file lines and spans, read through the project confinement.
357
+
358
+ An analysis asks for the same file's spans once per candidate it holds, and the
359
+ same class body once per subclass method: on a graph of Django's size that is
360
+ hundreds of thousands of asks. Each file's spans are read once here (indexed by
361
+ definition line), and each span's identifiers tokenized once.
362
+ """
363
+
364
+ def __init__(self) -> None:
365
+ self._files: dict[str, list[str]] = {}
366
+ self._spans: dict[str, tuple[
367
+ list[tuple[int, int, int, str]], dict[int, list[tuple[int, int, int, str]]]
368
+ ]] = {}
369
+ self._tokens: dict[tuple[str, int, int], frozenset[str]] = {}
370
+ self._children: dict[str, dict[str, list[str]]] = {}
371
+
372
+ def spans(self, file: str) -> list[tuple[int, int, int, str]]:
373
+ return self._indexed(file)[0]
374
+
375
+ def spans_at(self, file: str, line: int) -> list[tuple[int, int, int, str]]:
376
+ """The spans whose definition line is ``line``, in the file's span order."""
377
+ return self._indexed(file)[1].get(line, [])
378
+
379
+ def _indexed(self, file: str) -> tuple[
380
+ list[tuple[int, int, int, str]], dict[int, list[tuple[int, int, int, str]]]
381
+ ]:
382
+ got = self._spans.get(file)
383
+ if got is None:
384
+ spans = _spans_for_file(file)
385
+ by_line: dict[int, list[tuple[int, int, int, str]]] = {}
386
+ for s in spans:
387
+ by_line.setdefault(s[2], []).append(s)
388
+ got = (spans, by_line)
389
+ self._spans[file] = got
390
+ return got
391
+
392
+ def children(self, file: str) -> dict[str, list[str]]:
393
+ """Qualified name -> the last names of the spans directly under it."""
394
+ got = self._children.get(file)
395
+ if got is None:
396
+ got = {}
397
+ for _rs, _e, _dl, q in self.spans(file):
398
+ if "." in q:
399
+ parent, last = q.rsplit(".", 1)
400
+ got.setdefault(parent, []).append(last)
401
+ self._children[file] = got
402
+ return got
403
+
404
+ def tokens(self, file: str, span: tuple[int, int]) -> frozenset[str]:
405
+ """The identifiers written in lines ``span[0]..span[1]`` of ``file``."""
406
+ key = (file, span[0], span[1])
407
+ got = self._tokens.get(key)
408
+ if got is None:
409
+ got = frozenset(_IDENT.findall("\n".join(self.get(file)[span[0] - 1:span[1]])))
410
+ self._tokens[key] = got
411
+ return got
412
+
413
+ def get(self, file: str) -> list[str]:
414
+ got = self._files.get(file)
415
+ if got is None:
416
+ got = []
417
+ full = _resolve_in_project(file)
418
+ if full is not None:
419
+ try:
420
+ got = full.read_text(encoding="utf-8", errors="replace").splitlines()
421
+ except OSError:
422
+ got = []
423
+ self._files[file] = got
424
+ return got
425
+
426
+
427
+ def _decorators(
428
+ n: dict, nid: str, edges_out: dict[str, list[tuple[str, dict]]], byid: dict[str, dict],
429
+ lines: _SourceLines,
430
+ ) -> list[str]:
431
+ """Decorator / annotation names on a definition.
432
+
433
+ From the graph where it recorded them (a ``references`` edge whose context is
434
+ ``decorator``), and from the source lines above the definition, which works in
435
+ any language the span engine reads.
436
+ """
437
+ found: list[str] = []
438
+ for target, e in edges_out.get(nid, ()):
439
+ if str(e.get("context") or "").lower() == "decorator":
440
+ t = byid.get(target)
441
+ found.append(_node_label(t) if t else target)
442
+ file, line = _node_file(n), _int_line(n)
443
+ span = _span_for(file, line, lines)
444
+ if span is not None:
445
+ text_lines = lines.get(file)
446
+ # Above the definition (Python, JS, Rust: decorators are siblings) and from
447
+ # its first line down to the one that names it (Java `@Test` / C# `[Fact]`
448
+ # start the declaration itself).
449
+ name = _bare_name(_node_label(n))
450
+ below = text_lines[line - 1:line - 1 + _DECORATOR_REACH]
451
+ stop = next((i for i, text in enumerate(below) if name and name in text), 0)
452
+ in_comment = False
453
+ for text in text_lines[span[0] - 1:line - 1] + below[:stop + 1]:
454
+ # a doc comment's `@param` / `@default` tag is no decorator, with or
455
+ # without the leading `*`. Only a line that starts a comment opens
456
+ # one: `@Test("matches */*")` holds the characters in a string.
457
+ stripped = text.lstrip()
458
+ if in_comment:
459
+ in_comment = "*/" not in text
460
+ continue
461
+ if stripped.startswith("/*"):
462
+ in_comment = "*/" not in stripped[2:]
463
+ continue
464
+ m = _DECORATOR_LINE.match(text)
465
+ if m:
466
+ found.append(m.group(1))
467
+ seen: set[str] = set()
468
+ out: list[str] = []
469
+ for d in found:
470
+ short = d.replace("::", ".").rsplit(".", 1)[-1].rstrip("()")
471
+ if short and short.lower() not in seen:
472
+ seen.add(short.lower())
473
+ out.append(short)
474
+ return out
475
+
476
+
477
+ def _count_mentions(
478
+ names: set[str],
479
+ ) -> tuple[dict[str, Counter[str]], dict[str, Counter[str]], int, bool]:
480
+ """How often each name occurs as a whole identifier, per text file of the project.
481
+
482
+ Walks ``config.PROJECT_DIR`` once: templates, configs and docs count too, since
483
+ a function named in ``pyproject.toml`` or called from an HTML attribute is not
484
+ dead. Hidden directories, dependency and build trees, vendored or oversized
485
+ files and binaries are skipped. Returns ({name: {file: count}}, the same for
486
+ attribute accesses only (``obj.name``), files read, hit the file cap) — per
487
+ file and per form, so that a second definition of the same name and its bare
488
+ uses can be told apart from uses of the candidate.
489
+ """
490
+ counts: dict[str, Counter[str]] = {}
491
+ attrs: dict[str, Counter[str]] = {}
492
+ if not names:
493
+ return counts, attrs, 0, False
494
+ root = config.PROJECT_DIR.resolve()
495
+ scanned = 0
496
+ capped = False
497
+ for dirpath, dirnames, filenames in os.walk(root):
498
+ dirnames[:] = [
499
+ d for d in dirnames
500
+ if not d.startswith(".") and d not in _MENTION_SKIP_DIRS
501
+ and d != config.OUT_DIR_NAME
502
+ ]
503
+ for name in filenames:
504
+ full = os.path.join(dirpath, name)
505
+ rel = os.path.relpath(full, root).replace(os.sep, "/")
506
+ if _vendored_by_path(rel) or os.path.islink(full):
507
+ continue # a link may point outside the project: never follow it
508
+ try:
509
+ if os.path.getsize(full) > _MENTION_MAX_BYTES:
510
+ continue
511
+ with open(full, "rb") as fh:
512
+ raw = fh.read()
513
+ except OSError:
514
+ continue
515
+ if b"\0" in raw[:2048]:
516
+ continue # binary
517
+ if scanned >= _MENTION_MAX_FILES:
518
+ capped = True
519
+ break
520
+ scanned += 1
521
+ for m in _MENTION.finditer(raw.decode("utf-8", "replace")):
522
+ tok = m.group(2)
523
+ if tok in names:
524
+ counts.setdefault(tok, Counter())[rel] += 1
525
+ if m.group(1):
526
+ attrs.setdefault(tok, Counter())[rel] += 1
527
+ if capped:
528
+ break
529
+ return counts, attrs, scanned, capped
530
+
531
+
532
+ def _is_test_definition(name: str, file: str) -> bool:
533
+ """A test the runner collects by naming convention, never by reference:
534
+ ``test_x`` / ``TestX``, googletest's ``TEST`` / ``TEST_F``, Go's ``BenchmarkX`` /
535
+ ``ExampleX`` / ``FuzzX``, the ``XTest`` / ``XTests`` / ``XTestCase`` classes of
536
+ the JVM, .NET, PHP and Swift, and the ``setUp`` / ``tearDown`` fixtures."""
537
+ return _is_test_path(file) and (
538
+ name.startswith(("test", "Test", "TEST", "Benchmark", "Example", "Fuzz"))
539
+ or name.endswith(("Test", "Tests", "TestCase"))
540
+ # xUnit fixtures: `setUp`, `tearDown`, `setUpBeforeClass`
541
+ or name.lower().startswith(("setup", "teardown"))
542
+ )
543
+
544
+
545
+ # googletest's `TEST(Suite, Name)` / `TEST_F(Fixture, Name)` / `TYPED_TEST(…)`:
546
+ # the native engine's rule for a test macro (a name in capitals given two bare
547
+ # names, `generic::test_macro_name`), which names the test `Suite.Name`
548
+ _TEST_MACRO_LINE = re.compile(r"^\s*[A-Z][A-Z0-9_]*\s*\(\s*\w+\s*,\s*\w+\s*\)")
549
+ _C_FAMILY_SUFFIXES = (".c", ".cc", ".cpp", ".cxx", ".c++", ".h", ".hh", ".hpp", ".hxx")
550
+
551
+
552
+ def _is_test_macro_case(n: dict, lines: _SourceLines) -> bool:
553
+ """A C / C++ test written with a test macro, which the native engine names
554
+ after the test (`Suite.Name`) rather than after the macro: the runner
555
+ registers it, nothing calls it by name."""
556
+ file = _node_file(n)
557
+ if not file.lower().endswith(_C_FAMILY_SUFFIXES) or not _is_test_path(file):
558
+ return False
559
+ text = lines.get(file)
560
+ line = _int_line(n)
561
+ return 0 < line <= len(text) and bool(_TEST_MACRO_LINE.match(text[line - 1]))
562
+
563
+
564
+ _TYPE_ARGUMENTS = re.compile(r"<[^<>]*>")
565
+
566
+
567
+ def _never_called_by_name(name: str, label: str, parent_label: str) -> bool:
568
+ """A definition no caller writes the name of, so "nothing refers to it" says
569
+ nothing: an anonymous function (``{closure#3}``, ``<lambda>``), an operator
570
+ (C++ ``operator[]``, Ruby ``[]=``), a constructor or destructor — used
571
+ whenever its class is."""
572
+ if not name or name[0] in "{<(~" or not any(ch.isalnum() or ch == "_" for ch in name):
573
+ return True
574
+ if name.startswith("operator") and not (name[8:9].isalnum() or name[8:9] == "_"):
575
+ return True
576
+ plain = _TYPE_ARGUMENTS.sub("", name)
577
+ if parent_label and _TYPE_ARGUMENTS.sub("", _bare_name(parent_label)) == plain:
578
+ return True # `.Foo()` under class Foo
579
+ scope = _TYPE_ARGUMENTS.sub("", label.strip().removesuffix("()")).replace("::", ".")
580
+ parts = scope.lstrip(".").split(".")
581
+ return len(parts) > 1 and parts[-2] == parts[-1] # `Foo::Foo()`
582
+
583
+
584
+ def _is_anonymous_class(n: dict, lines: _SourceLines) -> bool:
585
+ """A class graphify made of an anonymous class body, named after the type it
586
+ implements: Java ``new TypeToken<List<String>>() { … }``, Kotlin
587
+ ``object : Callback<T> { … }``. Nothing can refer to it by that name."""
588
+ text = lines.get(_node_file(n))
589
+ line = _int_line(n)
590
+ if not 0 < line <= len(text):
591
+ return False
592
+ src = text[line - 1]
593
+ label = _node_label(n).split("<", 1)[0]
594
+ return bool(label) and (f"new {label}" in src or bool(
595
+ re.search(rf"\bobject\s*:\s*{re.escape(label)}\b", src)))
596
+
597
+
598
+ def _unreferenced(
599
+ scoped_nodes: list[dict],
600
+ all_nodes: list[dict],
601
+ all_edges: list[dict],
602
+ count_test_references: bool = True,
603
+ ) -> dict[str, Any]:
604
+ """Definitions in ``scoped_nodes`` that nothing in the graph or the text refers to.
605
+
606
+ References are counted over the WHOLE graph, whatever the scope: the scope
607
+ picks which definitions to examine, not who may refer to them.
608
+ """
609
+ defs = _Definitions(all_nodes, all_edges)
610
+ edges_out: dict[str, list[tuple[str, dict]]] = {}
611
+ for e in all_edges:
612
+ s, t = _edge_ends(e)
613
+ edges_out.setdefault(s, []).append((t, e))
614
+
615
+ examined = 0
616
+ no_graph_ref: list[tuple[str, dict, str, str]] = [] # (id, node, kind, bare name)
617
+ lines = _SourceLines()
618
+ for n in scoped_nodes:
619
+ nid = _node_id(n)
620
+ kind = defs.kind.get(nid)
621
+ if not kind:
622
+ continue
623
+ # Ruby `success?` / `save!` / `body=` are written `success?`, `body = x`:
624
+ # the identifier a caller types is the name without the suffix
625
+ name = _bare_name(_node_label(n)).rstrip("?!=")
626
+ file = _node_file(n)
627
+ if not name or (name.startswith("__") and (
628
+ name.endswith("__") or file.lower().endswith(".php"))):
629
+ # Python dunders and PHP magic methods (`__invoke`, `__get`) are
630
+ # called by the language, not by name
631
+ continue
632
+ if _is_test_definition(name, file) or _is_test_macro_case(n, lines):
633
+ continue
634
+ owner = defs.byid.get(defs.parent.get(nid, ""))
635
+ if _never_called_by_name(name, _node_label(n), _node_label(owner) if owner else ""):
636
+ continue
637
+ if kind == "class" and _is_anonymous_class(n, lines):
638
+ continue # `new Callback<T>() { … }` / `object : Callback<T> { … }`
639
+ examined += 1
640
+ family = {nid, *defs.members.get(nid, ())}
641
+ referenced = False
642
+ for target in family:
643
+ for src, _e in defs.incoming.get(target, ()):
644
+ if src in family:
645
+ continue
646
+ if not count_test_references:
647
+ sn = defs.byid.get(src)
648
+ if sn is not None and _is_test_node(sn):
649
+ continue
650
+ referenced = True
651
+ break
652
+ if referenced:
653
+ break
654
+ if not referenced:
655
+ no_graph_ref.append((nid, n, kind, name))
656
+
657
+ registered: Counter[str] = Counter()
658
+ remaining: list[tuple[str, dict, str, str]] = []
659
+ for nid, n, kind, name in no_graph_ref:
660
+ decos = [
661
+ d for d in _decorators(n, nid, edges_out, defs.byid, lines)
662
+ if d.lower() not in _NEUTRAL_DECORATORS
663
+ ]
664
+ if decos:
665
+ registered[decos[0]] += 1
666
+ else:
667
+ remaining.append((nid, n, kind, name))
668
+
669
+ names = {name for _nid, _n, _kind, name in remaining}
670
+ # A class can be used only through its members: a C# extension class's
671
+ # methods are called on the extended type (`client.BuildUri(...)`) and the
672
+ # class is never named. Its members come from the span engine, since the
673
+ # graph may not see them (C# 14 `extension(...)` blocks).
674
+ graph_names = {_bare_name(_node_label(defs.byid[d])) for d in defs.kind}
675
+ members_of: dict[str, list[str]] = {}
676
+ for nid, n, kind, _name in remaining:
677
+ if kind != "class":
678
+ continue
679
+ cls_span = _span_of_definition(_node_file(n), _int_line(n), _name)
680
+ if cls_span is None:
681
+ continue
682
+ cls_qual = cls_span[3]
683
+ members_of[nid] = sorted({
684
+ m for m in lines.children(_node_file(n)).get(cls_qual, ())
685
+ if len(m) >= 4 and m not in names
686
+ })
687
+ member_names = {m for ms in members_of.values() for m in ms}
688
+ per_file, per_file_attrs, files_scanned, capped = _count_mentions(names | member_names)
689
+ graph_bases: dict[str, list[str]] = {} # class id -> base names the graph recorded
690
+ for e in all_edges:
691
+ if _rel(e) in _INHERITANCE_RELATIONS:
692
+ src, dst = _edge_ends(e)
693
+ base = defs.byid.get(dst)
694
+ graph_bases.setdefault(src, []).append(
695
+ _bare_name(_node_label(base)) if base else dst
696
+ )
697
+ # Where each candidate name is defined (any kind). In a file that has its OWN
698
+ # symbol of that name, the `def` line and every bare use (`name(...)`,
699
+ # `x: name`) belong to that symbol: a candidate has no incoming import edge,
700
+ # so the file cannot be using this one by its bare name. An attribute access
701
+ # (`obj.name`, `mod.name`) can never mean the file's own module-level symbol,
702
+ # and is how a method is called: it still counts.
703
+ defined_in: dict[str, dict[str, list[int]]] = {}
704
+ for other in defs.kind:
705
+ on = defs.byid[other]
706
+ bare = _bare_name(_node_label(on)).rstrip("?!=")
707
+ if bare in names:
708
+ defined_in.setdefault(bare, {}).setdefault(_node_file(on), []).append(
709
+ _int_line(on)
710
+ )
711
+ items: list[dict[str, Any]] = []
712
+ homes_sorted: dict[str, list[tuple[str, str, int]]] = {}
713
+ has_referencing_files: dict[str, bool] = {}
714
+ for nid, n, kind, name in remaining:
715
+ file, line = _node_file(n), _int_line(n)
716
+ own = 1
717
+ span = _span_for(file, line, lines)
718
+ if span is not None:
719
+ body = "\n".join(lines.get(file)[span[0] - 1:span[1]])
720
+ own = max(1, sum(1 for tok in _IDENT.findall(body) if tok == name))
721
+ homes = defined_in.get(name, {})
722
+ mentions = 0
723
+ for where, count in per_file.get(name, {}).items():
724
+ if where == file:
725
+ # its own body, and the `def` line of any namesake next to it
726
+ count -= own + max(0, len(homes.get(file, ())) - 1)
727
+ elif where in homes:
728
+ attrs_here = per_file_attrs.get(name)
729
+ count = attrs_here[where] if attrs_here else 0
730
+ mentions += max(0, count)
731
+ via = [
732
+ m for m in members_of.get(nid, ())
733
+ if m not in graph_names # a name the graph knows can mean that other symbol
734
+ and any(f != file and c for f, c in (per_file_attrs.get(m) or {}).items())
735
+ ]
736
+ if via and not mentions:
737
+ mentions = sum(c for m in via for f, c in per_file_attrs[m].items() if f != file)
738
+ item: dict[str, Any] = {
739
+ "id": nid, "name": name, "kind": kind, "file": file, "line": line or None,
740
+ "mentions": mentions,
741
+ }
742
+ if via and mentions:
743
+ item["used_through_members"] = via[:5]
744
+ # sorted once per name: a name defined in hundreds of files (Django's
745
+ # `get_queryset`) is a candidate in many of them
746
+ everywhere = homes_sorted.get(name)
747
+ if everywhere is None:
748
+ everywhere = homes_sorted[name] = sorted(
749
+ (f"{f}:{ln}", f, ln) for f, lns in homes.items() for ln in lns
750
+ )
751
+ namesakes = []
752
+ for where_at, f, ln in everywhere:
753
+ if (f, ln) != (file, line):
754
+ namesakes.append(where_at)
755
+ if len(namesakes) == 5:
756
+ break
757
+ if namesakes:
758
+ item["also_defined"] = namesakes
759
+ parent = defs.parent.get(nid, "")
760
+ bases = list(graph_bases.get(parent, ()))
761
+ bases += _enclosing_class_bases(file, line, lines) or []
762
+ hook = _hook_base(name, bases, defs, lines) if bases else None
763
+ if hook:
764
+ # called through the base class, which the graph cannot follow
765
+ item["note"] = (
766
+ f"method of a subclass of {hook}: may override a hook its base class calls"
767
+ )
768
+ elif kind == "method" and not name.startswith("_") and parent in defs.byid:
769
+ used = has_referencing_files.get(parent)
770
+ if used is None:
771
+ used = has_referencing_files[parent] = bool(defs.referencing_files(parent))
772
+ if used:
773
+ item["note"] = "public method of a class used elsewhere: unused here, may be API"
774
+ items.append(item)
775
+ items.sort(key=lambda it: (it["mentions"], "note" in it, it["file"], it["line"] or 0))
776
+ return {
777
+ "examined": examined,
778
+ "no_graph_reference": len(no_graph_ref),
779
+ "registered_by_decorator": dict(registered.most_common()),
780
+ "items": items,
781
+ "files_scanned_for_mentions": files_scanned,
782
+ "mention_scan_capped": capped,
783
+ }
784
+
785
+
786
+ # ---------------------------------------------------------------------------
787
+ # Same-named symbols
788
+ # ---------------------------------------------------------------------------
789
+
790
+ # Names every script or module is expected to repeat.
791
+ _CONVENTIONAL_NAMES = frozenset({"main", "setup", "teardown"})
792
+
793
+
794
+ def _is_nested_definition(n: dict) -> bool:
795
+ """Written inside another function or class, by the source's own nesting.
796
+
797
+ The graph's containment is not enough: graphify sometimes hangs a closure
798
+ directly on its file. The span engine's qualified name does not lie.
799
+ """
800
+ line = _int_line(n)
801
+ span = next((sp for sp in _spans_for_file(_node_file(n)) if sp[2] == line), None)
802
+ return span is not None and "." in span[3]
803
+
804
+
805
+ def _used_in_own_file(nid: str, n: dict, defs: _Definitions, lines: _SourceLines) -> bool:
806
+ """Does the definition's own file refer to it, by a graph edge or by name?"""
807
+ file, line = _node_file(n), _int_line(n)
808
+ family = {nid, *defs.members.get(nid, ())}
809
+ for target in family:
810
+ for src, _e in defs.incoming.get(target, ()):
811
+ sn = defs.byid.get(src)
812
+ if src not in family and sn is not None and _node_file(sn) == file:
813
+ return True
814
+ name = _bare_name(_node_label(n))
815
+ text = lines.get(file)
816
+ span = _span_for(file, line, lines)
817
+ if not text or span is None:
818
+ return False
819
+ outside = text[:span[0] - 1] + text[span[1]:]
820
+ return any(tok == name for tok in _IDENT.findall("\n".join(outside)))
821
+
822
+
823
+ def _same_named(
824
+ scoped_nodes: list[dict], all_nodes: list[dict], all_edges: list[dict],
825
+ kinds: frozenset[str] = frozenset({"class", "function"}),
826
+ across_languages: bool = False,
827
+ ) -> list[dict[str, Any]]:
828
+ """Top-level classes / functions that share a name across different files.
829
+
830
+ Names are compared within one language family unless ``across_languages``: a
831
+ Python function and a JavaScript function of the same name are not copies of
832
+ each other.
833
+ """
834
+ defs = _Definitions(all_nodes, all_edges)
835
+ lines = _SourceLines()
836
+ groups: dict[tuple[str, str], list[tuple[str, dict, str]]] = {}
837
+ for n in scoped_nodes:
838
+ nid = _node_id(n)
839
+ kind = defs.kind.get(nid)
840
+ if kind not in kinds or not defs.is_top_level(nid) or _is_nested_definition(n):
841
+ continue
842
+ name = _bare_name(_node_label(n))
843
+ if not name or name in _CONVENTIONAL_NAMES or (
844
+ name.startswith("__") and name.endswith("__")
845
+ ):
846
+ continue
847
+ family = "" if across_languages else (_lang_family(_node_file(n)) or "")
848
+ groups.setdefault((name, family), []).append((nid, n, kind))
849
+ out: list[dict[str, Any]] = []
850
+ for (name, family), members in groups.items():
851
+ if len({_node_file(n) for _nid, n, _k in members}) < 2:
852
+ continue
853
+ definitions: list[dict[str, Any]] = []
854
+ for nid, n, kind in members:
855
+ definitions.append({
856
+ "id": nid, "kind": kind, "file": _node_file(n), "line": _int_line(n) or None,
857
+ "imported_by": len(defs.referencing_files(nid, _IMPORT_RELATIONS)),
858
+ "referenced_by": len(defs.referencing_files(nid)),
859
+ "used_in_own_file": _used_in_own_file(nid, n, defs, lines),
860
+ })
861
+ definitions.sort(key=lambda d: (-d["imported_by"], -d["referenced_by"], d["file"]))
862
+ out.append({
863
+ "name": name,
864
+ "language": family or None,
865
+ "kinds": sorted({d["kind"] for d in definitions}),
866
+ "modules": len({d["file"] for d in definitions}),
867
+ "definitions": definitions,
868
+ })
869
+ out.sort(key=lambda g: (
870
+ "class" not in g["kinds"],
871
+ -sum(d["imported_by"] for d in g["definitions"]),
872
+ -g["modules"],
873
+ g["name"],
874
+ ))
875
+ return out
876
+
877
+
878
+ # ---------------------------------------------------------------------------
879
+ # Identical bodies
880
+ # ---------------------------------------------------------------------------
881
+
882
+ # A body smaller than this says nothing when it repeats: `return self.x`, `pass`,
883
+ # `raise NotImplementedError`. Counted in AST nodes (Python, operators and load /
884
+ # store contexts aside) or leaf tokens (tree-sitter, punctuation included).
885
+ _BODY_MIN_NODES = 8
886
+ _BODY_MIN_TOKENS = 14
887
+ _AST_NOISE = (ast.expr_context, ast.operator, ast.boolop, ast.unaryop, ast.cmpop)
888
+ _TS_FUNCTION_HINTS = ("function", "method", "arrow", "constructor", "func", "lambda")
889
+
890
+ # rel path -> (mtime, {def line: (digest, body lines)}); the span cache's scheme.
891
+ _BODY_CACHE: dict[str, tuple[float, Any]] = {}
892
+
893
+
894
+ def _digest(text: str) -> str:
895
+ return hashlib.sha1(text.encode("utf-8", "replace"), usedforsecurity=False).hexdigest()
896
+
897
+
898
+ def _python_bodies(src: bytes) -> dict[int, tuple[str, int]]:
899
+ try:
900
+ tree = ast.parse(src)
901
+ except Exception: # noqa: BLE001 - unparseable file: no fingerprints
902
+ return {}
903
+ out: dict[int, tuple[str, int]] = {}
904
+ for node in ast.walk(tree):
905
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
906
+ continue
907
+ body = list(node.body)
908
+ if (body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant)
909
+ and isinstance(body[0].value.value, str)):
910
+ body = body[1:] # the docstring is not the body
911
+ size = sum(
912
+ 1 for stmt in body for x in ast.walk(stmt) if not isinstance(x, _AST_NOISE)
913
+ )
914
+ if size < _BODY_MIN_NODES:
915
+ continue
916
+ # ast.dump carries no positions or comments, so two copies that differ
917
+ # only in layout, comments or docstring dump identically.
918
+ dumped = "\n".join(ast.dump(stmt) for stmt in body)
919
+ end = getattr(node, "end_lineno", None) or node.lineno
920
+ out[node.lineno] = (_digest(dumped), end - body[0].lineno + 1)
921
+ return out
922
+
923
+
924
+ def _treesitter_bodies(src: bytes, rel: str) -> dict[int, tuple[str, int]]:
925
+ parser, _lang = _ts_parser_for(rel, src)
926
+ if parser is None:
927
+ return {}
928
+ try:
929
+ root = parser.parse(src).root_node
930
+ except Exception: # noqa: BLE001
931
+ return {}
932
+ out: dict[int, tuple[str, int]] = {}
933
+
934
+ def record(fn: Any) -> None:
935
+ body = fn.child_by_field_name("body")
936
+ if body is None:
937
+ return
938
+ skeleton = _ts_skeleton(body) # comments dropped, whitespace is no token
939
+ if skeleton is None or sum(1 for part in skeleton if len(part) == 2) < _BODY_MIN_TOKENS:
940
+ return
941
+ out[fn.start_point[0] + 1] = (
942
+ _digest(repr(skeleton)), body.end_point[0] - body.start_point[0] + 1
943
+ )
944
+
945
+ def walk(node: Any) -> None:
946
+ for child in node.named_children:
947
+ bound = _ts_bound_function(child)
948
+ if bound is not None:
949
+ record(bound[1])
950
+ elif _is_ts_symbol(child.type) and any(
951
+ h in child.type.lower() for h in _TS_FUNCTION_HINTS
952
+ ):
953
+ record(child)
954
+ walk(child)
955
+
956
+ try:
957
+ walk(root)
958
+ except RecursionError:
959
+ pass
960
+ return out
961
+
962
+
963
+ def _body_fingerprints(file: str) -> dict[int, tuple[str, int]]:
964
+ """{def line: (digest of the normalized body, body line count)} for one file.
965
+
966
+ Normalized means: whitespace, comments and (Python) the docstring do not
967
+ count, and neither does the function's own name or signature — a renamed copy
968
+ still matches. Python via ``ast``, other languages via tree-sitter when
969
+ present. Bodies too small to mean anything are left out.
970
+ """
971
+ def compute(src: bytes, rel: str) -> dict[int, tuple[str, int]]:
972
+ if rel.lower().endswith((".py", ".pyi")):
973
+ return _python_bodies(src)
974
+ return _treesitter_bodies(src, rel)
975
+
976
+ return _cached_file_analysis(_BODY_CACHE, file, compute, dict)
977
+
978
+
979
+ def _identical_bodies(
980
+ scoped_nodes: list[dict], all_nodes: list[dict], all_edges: list[dict],
981
+ include_tests: bool = False,
982
+ ) -> list[dict[str, Any]]:
983
+ """Functions and methods whose normalized bodies are identical, as groups.
984
+
985
+ Exact and model-free, and it covers every size the semantic tier's
986
+ largest-first seeding never reaches: small helpers are what gets copied.
987
+ """
988
+ defs = _Definitions(all_nodes, all_edges)
989
+ groups: dict[str, list[dict[str, Any]]] = {}
990
+ for n in scoped_nodes:
991
+ nid = _node_id(n)
992
+ if defs.kind.get(nid) not in ("function", "method"):
993
+ continue
994
+ file, line = _node_file(n), _int_line(n)
995
+ if not include_tests and _is_test_path(file):
996
+ continue
997
+ fp = _body_fingerprints(file).get(line)
998
+ if fp is None:
999
+ continue
1000
+ groups.setdefault(fp[0], []).append(
1001
+ {"id": nid, "file": file, "line": line, "lines": fp[1]}
1002
+ )
1003
+ out: list[dict[str, Any]] = []
1004
+ for members in groups.values():
1005
+ if len(members) < 2:
1006
+ continue
1007
+ members.sort(key=lambda d: (d["file"], d["line"]))
1008
+ out.append({
1009
+ "copies": len(members),
1010
+ "lines": max(d["lines"] for d in members),
1011
+ "definitions": [{"id": d["id"], "file": d["file"], "line": d["line"]}
1012
+ for d in members],
1013
+ })
1014
+ out.sort(key=lambda g: (-g["copies"] * g["lines"], g["definitions"][0]["file"]))
1015
+ return out
1016
+
1017
+
1018
+ # ---------------------------------------------------------------------------
1019
+ # Layer rules
1020
+ # ---------------------------------------------------------------------------
1021
+
1022
+
1023
+ def _normalize_rules(raw: object) -> dict[str, list[str]] | str:
1024
+ """Validate ``{layer prefix: [prefixes it may import]}``; str = error message."""
1025
+ if isinstance(raw, dict) and isinstance(raw.get("layers"), dict):
1026
+ raw = raw["layers"] # the file form may wrap the mapping
1027
+ if not isinstance(raw, dict) or not raw:
1028
+ return (
1029
+ "ERROR: layer rules must be a non-empty object mapping a path prefix to the "
1030
+ 'prefixes it may import, e.g. {"src/app/api": ["src/app/core"], '
1031
+ '"src/app/core": []}.'
1032
+ )
1033
+ rules: dict[str, list[str]] = {}
1034
+ for key, allowed in raw.items():
1035
+ layer = _clean_pattern(str(key))
1036
+ if not layer:
1037
+ return f"ERROR: empty layer prefix in the rules ({key!r})."
1038
+ if isinstance(allowed, str):
1039
+ allowed = [allowed]
1040
+ if not isinstance(allowed, list | tuple):
1041
+ return f"ERROR: the rule for '{key}' must be a list of path prefixes."
1042
+ rules[layer] = [
1043
+ a for a in ("*" if str(x).strip() == "*" else _clean_pattern(str(x)) for x in allowed)
1044
+ if a
1045
+ ]
1046
+ return rules
1047
+
1048
+
1049
+ def _layer_of(path: str, rules: dict[str, list[str]]) -> str | None:
1050
+ """The most specific declared layer holding ``path`` (longest matching prefix)."""
1051
+ best: str | None = None
1052
+ for layer in rules:
1053
+ if _path_matches(layer, path) and (best is None or len(layer) > len(best)):
1054
+ best = layer
1055
+ return best
1056
+
1057
+
1058
+ def _layer_violations(
1059
+ nodes: list[dict], edges: list[dict], rules: dict[str, list[str]], strict: bool = False
1060
+ ) -> dict[str, Any]:
1061
+ """Import edges that break ``rules``, grouped by the importing layer.
1062
+
1063
+ An import is allowed inside one layer, into any prefix the layer lists, and —
1064
+ unless ``strict`` — into files that belong to no declared layer. Imports of
1065
+ external packages are never checked. Each edge is first checked against the
1066
+ importing file's own statements: one the source contradicts (``import yaml``
1067
+ linked to a first-party ``yaml.py``) is dropped and listed under
1068
+ ``rejected_imports``, and a violation says when its import runs.
1069
+ """
1070
+ checker = ImportChecker()
1071
+ files = sorted({_norm_relpath(_node_file(n)) for n in nodes} - {""})
1072
+ layers: dict[str, dict[str, Any]] = {
1073
+ layer: {"layer": layer, "may_import": allowed, "files": 0,
1074
+ "imports_checked": 0, "violations": []}
1075
+ for layer, allowed in rules.items()
1076
+ }
1077
+ for f in files:
1078
+ layer = _layer_of(f, rules)
1079
+ if layer is not None:
1080
+ layers[layer]["files"] += 1
1081
+ seen: set[tuple[str, str, str]] = set()
1082
+ for sf, tf, e, dst, kind in _file_import_edges(nodes, edges, checker.kind):
1083
+ src_layer = _layer_of(sf, rules)
1084
+ if src_layer is None:
1085
+ continue
1086
+ entry = layers[src_layer]
1087
+ loc = str(e.get("source_location") or "")
1088
+ key = (sf, tf, loc)
1089
+ if key in seen:
1090
+ continue
1091
+ seen.add(key)
1092
+ entry["imports_checked"] += 1
1093
+ dst_layer = _layer_of(tf, rules)
1094
+ if dst_layer == src_layer:
1095
+ continue
1096
+ allowed = rules[src_layer]
1097
+ if "*" in allowed or any(_path_matches(a, tf) for a in allowed):
1098
+ continue
1099
+ if dst_layer is None and not strict:
1100
+ continue
1101
+ violation: dict[str, Any] = {
1102
+ "from_file": sf, "to_file": tf, "to_layer": dst_layer,
1103
+ "site": f"{sf}:{loc}" if loc else sf, "import": kind,
1104
+ }
1105
+ if not _is_file_hub_node(dst):
1106
+ violation["imported"] = _node_label(dst)
1107
+ entry["violations"].append(violation)
1108
+ for entry in layers.values():
1109
+ entry["violations"].sort(key=lambda v: (v["from_file"], v["site"], v["to_file"]))
1110
+ unmatched = sorted(
1111
+ {layer for layer, entry in layers.items() if entry["files"] == 0}
1112
+ | {a for allowed in rules.values() for a in allowed
1113
+ if a != "*" and not any(_path_matches(a, f) for f in files)}
1114
+ )
1115
+ return {
1116
+ "layers": list(layers.values()),
1117
+ "violation_count": sum(len(entry["violations"]) for entry in layers.values()),
1118
+ "imports_checked": sum(entry["imports_checked"] for entry in layers.values()),
1119
+ "unmatched_prefixes": unmatched,
1120
+ "rejected_imports": checker.rejected,
1121
+ }