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/spans.py ADDED
@@ -0,0 +1,1254 @@
1
+ """Code-analysis engine: per-file symbol spans + chunk→node join + structural diff.
2
+
3
+ Resolves a semble chunk ``(file, line[..end])`` to the graph node whose *real* line
4
+ range contains it — Python via the stdlib ``ast`` (decorator-aware), every other
5
+ language via an optional tree-sitter backend with automatic language detection. Also
6
+ provides the comment-stripped structural comparison behind cosmetic-vs-structural
7
+ freshness. Reads the project root from :mod:`graphlore.config`.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import re
13
+ from collections.abc import Callable
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from . import config, engine
18
+ from .graph import _is_test_path, _node_file, _node_line
19
+
20
+ # Per-file span index, keyed by absolute path -> (mtime, spans). A span is
21
+ # ``(region_start, end_line, def_line, qualname)`` for each def/class:
22
+ # ``region_start`` absorbs decorator / doc-comment / attribute lines, ``def_line``
23
+ # is where the graph node's ``source_location`` points. Used to resolve a semble
24
+ # chunk to its *containing* symbol by a real line range instead of graphify's single
25
+ # point.
26
+ _SPAN_CACHE: dict[str, tuple[float, list[tuple[int, int, int, str]]]] = {}
27
+ # Bound _SPAN_CACHE: under a long-lived HTTP transport with file churn (branch
28
+ # switches, generated files, multiple projects) it would otherwise grow for the
29
+ # life of the process, retaining entries for deleted/renamed files.
30
+ _SPAN_CACHE_MAX = 4096
31
+
32
+
33
+ def _resolve_in_project(file_path: object) -> Path | None:
34
+ """Resolve a (possibly hostile) path to an absolute path confined to PROJECT_DIR.
35
+
36
+ This is the single security boundary for every per-file analyzer: an empty,
37
+ absolute-outside, or ``..``-escaping path returns None, so no engine ever
38
+ reads a file outside the project — even though most outputs are only
39
+ line/name metadata.
40
+ """
41
+ rel = _norm_relpath(file_path)
42
+ if not rel:
43
+ return None
44
+ try:
45
+ full = (config.PROJECT_DIR / rel).resolve()
46
+ full.relative_to(config.PROJECT_DIR.resolve())
47
+ except (ValueError, OSError):
48
+ return None
49
+ return full
50
+
51
+
52
+ def _cached_file_analysis(
53
+ cache: dict[str, tuple[float, Any]],
54
+ file_path: object,
55
+ compute: Callable[[bytes, str], Any],
56
+ empty: Callable[[], Any],
57
+ cache_max: int | None = None,
58
+ ) -> Any:
59
+ """Shared per-file pipeline behind the span / API / route indexes.
60
+
61
+ Confine to PROJECT_DIR, stat the mtime, serve the ``(path, mtime)`` cache,
62
+ else read bytes and call ``compute(src, rel)`` — caching the result (or
63
+ ``empty()`` on a read failure) with bounded-FIFO eviction so a long-lived
64
+ process with file churn doesn't retain entries for deleted files forever.
65
+ """
66
+ full = _resolve_in_project(file_path)
67
+ if full is None:
68
+ return empty()
69
+ try:
70
+ mtime = full.stat().st_mtime
71
+ except OSError:
72
+ return empty()
73
+ key = str(full)
74
+ cached = cache.get(key)
75
+ if cached is not None and cached[0] == mtime:
76
+ return cached[1]
77
+ try:
78
+ src = full.read_bytes()
79
+ except OSError:
80
+ result = empty()
81
+ else:
82
+ result = compute(src, _norm_relpath(file_path))
83
+ # Resolved at call time (not a frozen default) so tests can shrink the bound.
84
+ limit = _SPAN_CACHE_MAX if cache_max is None else cache_max
85
+ if key not in cache and len(cache) >= limit:
86
+ cache.pop(next(iter(cache)), None) # FIFO: drop the oldest entry
87
+ cache[key] = (mtime, result)
88
+ return result
89
+
90
+
91
+ def _norm_relpath(p: object) -> str:
92
+ s = str(p or "").strip()
93
+ return s[2:] if s.startswith("./") else s
94
+
95
+
96
+ # tree-sitter symbol node-type hints (generic across languages). A node counts as
97
+ # a definition only if its type matches one of these AND it names itself — through
98
+ # a "name" field, a declarator chain (C/C++) or, in grammars that have neither
99
+ # (Kotlin), an identifier child — which filters out look-alikes (function_type,
100
+ # class_body, ...).
101
+ _TS_SYMBOL_HINTS = (
102
+ "function", "method", "constructor", "class", "struct", "interface",
103
+ "enum", "trait", "module", "object", "type", "subroutine",
104
+ "procedure", "package", "namespace", "record", "protocol",
105
+ )
106
+ # Hints that must be a whole word of the node type: as a substring "impl" also
107
+ # sits in PHP's `simple_parameter` and Kotlin's `simple_identifier`.
108
+ _TS_SYMBOL_WORD_HINTS = frozenset({"impl", "mod"})
109
+ # NB: no "_expression" (function_expression is a named def) and no "_specifier"
110
+ # (C++ class_specifier / struct_specifier / enum_specifier ARE definitions when
111
+ # they have a body). The excluded nodes match a hint substring but name a use of a
112
+ # symbol, never its definition: a type written in a signature (`React.FC`,
113
+ # `io::Result`, Swift `x: Foo`) or a parameter (Scala `class_parameter`).
114
+ _TS_NON_SYMBOL_SUFFIXES = (
115
+ "_type", "_body", "_parameters", "_clause",
116
+ "_identifier", "_annotation", "_parameter",
117
+ )
118
+ # Nodes that match a hint substring ("function"/"type") but are NOT definitions:
119
+ # C/C++ calls/sub-declarators (`holds_alternative<T>(x)` -> template_function, a real
120
+ # name under a nested function_declarator), and type-level constructs — generic
121
+ # parameters (`<T>`, Go `[T any]`), associated-type bindings (`impl Iterator<Item = X>`),
122
+ # a Swift tuple member, a TypeScript `x is T` predicate, a Rust struct literal
123
+ # (`Foo { a: 1 }`) and a C macro mistaken for a type — that carry a `name` field
124
+ # yet name no symbol.
125
+ _TS_CALL_TYPES = frozenset({
126
+ "template_function", "template_method", "call_expression", "function_declarator",
127
+ "type_binding", "type_parameter", "constrained_type_parameter",
128
+ "optional_type_parameter", "type_argument", "type_arguments",
129
+ "type_parameter_declaration", "type_predicate", "tuple_type_item",
130
+ "struct_expression", "macro_type_specifier",
131
+ })
132
+ # Definitions whose grammar gives them a keyword, not a name.
133
+ _TS_KEYWORD_NAMES = {
134
+ "init_declaration": "init", "deinit_declaration": "deinit", # Swift
135
+ "subscript_declaration": "subscript", # Swift
136
+ "secondary_constructor": "constructor", # Kotlin
137
+ "indexer_declaration": "this[]", # C#
138
+ }
139
+ # C# operators: named by the operator (`operator+`) or the type a conversion
140
+ # gives (`operator string`), as C++'s `operator_name` is.
141
+ _TS_OPERATOR_TYPES = frozenset({"operator_declaration", "conversion_operator_declaration"})
142
+ # Definitions whose name is written with a mark the language calls them by:
143
+ # a Rust macro is `name!` (and never answers a lookup of `name`).
144
+ _TS_NAME_SUFFIX = {"macro_definition": "!"}
145
+ # The child that names a declaration in a grammar without a `name` field (Kotlin:
146
+ # `function_declaration > simple_identifier`, `class_declaration > type_identifier`).
147
+ _TS_NAME_CHILD_TYPES = frozenset({"simple_identifier", "type_identifier", "identifier"})
148
+ # C/C++ declarations with no body of their own: a prototype in a header, a method
149
+ # declared in its class. They are spans only when they declare a function.
150
+ _TS_PROTOTYPE_TYPES = frozenset({"declaration", "field_declaration"})
151
+ # A `.h` file is C to the language pack; with one of these at the start of a line
152
+ # it is a C++ header, and the C grammar reads its classes as errors.
153
+ _CPP_HEADER_MARK = re.compile(
154
+ rb"^[ \t]*(?:class\s+\w|namespace\b|template\s*<|using\s+namespace\b"
155
+ rb"|(?:public|private|protected)\s*:)", re.M)
156
+ # Parser cache keyed by language name; value is a parser or None (unavailable).
157
+ _TS_PARSERS: dict[str, Any] = {}
158
+ # The span walk visits every named node, so what it decides per node type is
159
+ # cached: whether the type can be a definition (`_ts_is_symbol_type`), and per
160
+ # language the ids of the fields it reads (None: the grammar has no such field,
161
+ # so the lookup can be skipped).
162
+ _TS_SYMBOL_CACHE: dict[str, bool] = {}
163
+ _TS_FIELD_NAMES = ("name", "key", "property", "value", "left", "right", "body",
164
+ "receiver", "type")
165
+ _TS_FIELDS: dict[str, dict[str, int | None]] = {}
166
+ # The only node types `_ts_anonymous_class` can name.
167
+ _TS_ANON_CLASS_TYPES = frozenset({"object_creation_expression", "object_literal", "assignment"})
168
+
169
+
170
+ def _ts_parser_for(rel: str, src: bytes | None = None) -> tuple[Any, str | None]:
171
+ """(parser, language) for a path via the optional tree-sitter backend.
172
+
173
+ Returns (None, None) when tree-sitter / the language pack is not installed or
174
+ the language is unknown. tree-sitter ships with graphify, so it's usually
175
+ present; declared as the ``[treesitter]`` extra otherwise. Cached per language.
176
+ With ``src``, a ``.h`` file that reads as C++ gets the C++ grammar.
177
+ """
178
+ try:
179
+ # Build a parser from the core API (Parser + Language) rather than the
180
+ # language pack's get_parser() wrapper — the wrapper's parse() signature
181
+ # has churned across pack releases, while Parser(language).parse(bytes) is
182
+ # stable. tree-sitter ships with graphify.
183
+ from tree_sitter import Parser
184
+ from tree_sitter_language_pack import detect_language_from_path, get_language
185
+ except Exception:
186
+ return None, None
187
+ try:
188
+ lang = detect_language_from_path(rel)
189
+ except Exception:
190
+ lang = None
191
+ if not lang:
192
+ return None, None
193
+ if lang == "c" and src is not None and _CPP_HEADER_MARK.search(src):
194
+ lang = "cpp"
195
+ if lang not in _TS_PARSERS:
196
+ if config.offline() and not _grammar_cached(lang):
197
+ # get_language downloads an uncached grammar; offline, do without it
198
+ # (not cached as None, so it is tried once the switch is off)
199
+ return None, None
200
+ try:
201
+ # Some pack releases type get_language's argument as a Literal of
202
+ # every grammar name, while detect_language_from_path returns str.
203
+ _TS_PARSERS[lang] = Parser(get_language(lang)) # type: ignore[arg-type]
204
+ except Exception:
205
+ _TS_PARSERS[lang] = None
206
+ return _TS_PARSERS[lang], lang
207
+
208
+
209
+ def _grammar_cached(lang: str) -> bool:
210
+ """Whether tree-sitter-language-pack has ``lang`` on disk already. A pack too
211
+ old to say (no ``downloaded_languages``) is trusted, since it then bundles its
212
+ grammars rather than downloading them."""
213
+ try:
214
+ from tree_sitter_language_pack import downloaded_languages
215
+ except ImportError:
216
+ return True
217
+ try:
218
+ return lang in set(downloaded_languages())
219
+ except Exception: # noqa: BLE001 - a cache probe that fails reads as "not cached"
220
+ return False
221
+
222
+
223
+ # Definitions whose node type has no hint word: C++ `using AsyncResponse =
224
+ # AsyncWrapper<Response>;` (not every `alias`: Python's `aliased_import` names a
225
+ # module it imports).
226
+ # C# `delegate void Cb(…);`, Rust `macro_rules! name`, C# operators.
227
+ _TS_SYMBOL_TYPES = frozenset({"alias_declaration", "delegate_declaration", "macro_definition",
228
+ "operator_declaration", "conversion_operator_declaration"})
229
+
230
+
231
+ def _is_ts_symbol(node_type: str) -> bool:
232
+ t = node_type.lower()
233
+ if t in _TS_CALL_TYPES or t.endswith(_TS_NON_SYMBOL_SUFFIXES):
234
+ return False
235
+ if t in _TS_SYMBOL_TYPES:
236
+ return True
237
+ # Calls/invocations expose the callee under a `name` field but define nothing —
238
+ # Java `method_invocation`, C# `invocation_expression`, Ruby `method_call`, PHP
239
+ # `function_call_expression`, etc. Match by substring so we don't have to
240
+ # enumerate every grammar's spelling (`call_expression` is also caught here).
241
+ if "invocation" in t or "call" in t:
242
+ return False
243
+ if any(h in t for h in _TS_SYMBOL_HINTS):
244
+ return True
245
+ return not _TS_SYMBOL_WORD_HINTS.isdisjoint(t.split("_"))
246
+
247
+
248
+ def _ts_is_symbol_type(node_type: str) -> bool:
249
+ """`_is_ts_symbol`, or a keyword-named definition; cached per type."""
250
+ hit = _TS_SYMBOL_CACHE.get(node_type)
251
+ if hit is None:
252
+ hit = _is_ts_symbol(node_type) or node_type in _TS_KEYWORD_NAMES
253
+ _TS_SYMBOL_CACHE[node_type] = hit
254
+ return hit
255
+
256
+
257
+ def _ts_fields(lang: str, language: Any) -> dict[str, int | None]:
258
+ """Field ids of `_TS_FIELD_NAMES` in a grammar, cached per language."""
259
+ fields = _TS_FIELDS.get(lang)
260
+ if fields is None:
261
+ fields = {}
262
+ for name in _TS_FIELD_NAMES:
263
+ try:
264
+ fields[name] = language.field_id_for_name(name)
265
+ except Exception: # noqa: BLE001 - an unknown field reads as absent
266
+ fields[name] = None
267
+ _TS_FIELDS[lang] = fields
268
+ return fields
269
+
270
+
271
+ def _ts_field(node: Any, name: str, fields: dict[str, int | None] | None) -> Any:
272
+ """``node.child_by_field_name(name)``; with ``fields`` (from `_ts_fields`) by
273
+ id, and None without a lookup when the grammar has no such field."""
274
+ if fields is None:
275
+ return node.child_by_field_name(name)
276
+ fid = fields.get(name)
277
+ return None if fid is None else node.child_by_field_id(fid)
278
+
279
+
280
+ def _spans_python(src: bytes) -> list[tuple[int, int, int, str]]:
281
+ """Decorator-aware def/class spans from Python source (stdlib ast).
282
+
283
+ ``region_start`` includes decorator lines; ``def_line`` is the ``def``/``class``
284
+ line a graph node's ``source_location`` points at.
285
+ """
286
+ spans: list[tuple[int, int, int, str]] = []
287
+ try:
288
+ tree = ast.parse(src)
289
+ except Exception:
290
+ return spans
291
+
292
+ def walk(node: ast.AST, prefix: str) -> None:
293
+ for child in ast.iter_child_nodes(node):
294
+ if isinstance(child, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
295
+ qual = f"{prefix}{child.name}"
296
+ def_line = child.lineno
297
+ decos = [d.lineno for d in getattr(child, "decorator_list", [])]
298
+ region_start = min([def_line, *decos])
299
+ end = getattr(child, "end_lineno", def_line) or def_line
300
+ spans.append((region_start, end, def_line, qual))
301
+ walk(child, qual + ".")
302
+ else:
303
+ walk(child, prefix)
304
+
305
+ try:
306
+ walk(tree, "")
307
+ except RecursionError:
308
+ pass
309
+ return spans
310
+
311
+
312
+ def _ts_region_start(child: Any, def_line: int) -> int:
313
+ """Extend a symbol's region upward over its leading doc-comment / decorator /
314
+ annotation / attribute siblings (Go/Java/JS/Rust doc style), mirroring Python's
315
+ decorator-aware region — so a chunk that starts on the doc comment still resolves
316
+ to the symbol it documents (instead of falling outside the span)."""
317
+ start = def_line
318
+ prev = child.prev_named_sibling
319
+ while prev is not None:
320
+ ptype = prev.type.lower()
321
+ if not any(h in ptype for h in ("comment", "decorator", "annotation", "attribute")):
322
+ break
323
+ prev_end = prev.end_point[0] + 1
324
+ if prev_end < start - 1: # a blank-line gap -> detached, not a doc comment
325
+ break
326
+ start = prev.start_point[0] + 1
327
+ prev = prev.prev_named_sibling
328
+ return start
329
+
330
+
331
+ def _ts_receiver_type(recv: Any) -> str | None:
332
+ """The receiver's type name in a method receiver, e.g. Go ``(c *Client)`` -> ``Client``."""
333
+ stack = list(recv.named_children)
334
+ while stack:
335
+ n = stack.pop(0)
336
+ if n.type == "type_identifier":
337
+ return n.text.decode("utf-8", "replace")
338
+ stack.extend(n.named_children)
339
+ return None
340
+
341
+
342
+ def _ts_bound_function(node: Any,
343
+ fields: dict[str, int | None] | None = None) -> tuple[str, Any] | None:
344
+ """An *anonymous* function bound to a name, so the binding name becomes the
345
+ qualname (the arrow/closure carries no ``name`` field of its own). Covers
346
+ ``const f = () => …`` / ``var h = func(){}`` (name+value), object properties
347
+ ``{ foo: () => … }`` (key+value), class fields ``handler = (r) => …``
348
+ (property+value) and assignments ``exports.send = function () {…}`` /
349
+ ``res.send = …`` (left+right, named by the member assigned to). ``None`` for
350
+ non-function bindings or a function that already has its own name (handled by
351
+ the normal path). ``fields`` (from `_ts_fields`) only speeds up the lookups."""
352
+ name = (_ts_field(node, "name", fields)
353
+ or _ts_field(node, "key", fields)
354
+ or _ts_field(node, "property", fields))
355
+ value = _ts_field(node, "value", fields)
356
+ if name is None and value is None:
357
+ left = _ts_field(node, "left", fields)
358
+ if left is not None and left.type == "member_expression":
359
+ left = _ts_field(left, "property", fields)
360
+ name, value = left, _ts_field(node, "right", fields)
361
+ if name is None or value is None or not name.type.endswith("identifier"):
362
+ return None
363
+ if value.type == "call_expression":
364
+ value = _ts_wrapped_function(value)
365
+ if value is None:
366
+ return None
367
+ vt = value.type.lower()
368
+ if not any(h in vt for h in ("function", "arrow", "lambda", "closure", "func")):
369
+ return None
370
+ if vt.endswith("_type"):
371
+ return None # a type written out (Go `map[string]func() int`), not a function
372
+ if _ts_field(value, "name", fields) is not None:
373
+ return None
374
+ return name.text.decode("utf-8", "replace"), value
375
+
376
+
377
+ # Callees that take a function to run later, not to return a wrapped version of it.
378
+ _TS_SCHEDULERS = frozenset({"setTimeout", "setInterval", "setImmediate", "queueMicrotask"})
379
+ _TS_FUNCTION_VALUES = frozenset({
380
+ "arrow_function", "function_expression", "function", "generator_function",
381
+ })
382
+
383
+
384
+ def _ts_wrapped_function(call: Any) -> Any | None:
385
+ """The function in a one-call wrapper: ``async(function* () {…})``,
386
+ ``wrap(async (req, res) => {…})`` — a plain-named callee given exactly one
387
+ anonymous function. ``users.map(u => …)`` and ``setTimeout(() => …)`` are
388
+ not wrappers."""
389
+ fn = call.child_by_field_name("function")
390
+ args = call.child_by_field_name("arguments")
391
+ if fn is None or args is None or fn.type != "identifier":
392
+ return None
393
+ if fn.text.decode("utf-8", "replace") in _TS_SCHEDULERS:
394
+ return None
395
+ found = [a for a in args.named_children if a.type in _TS_FUNCTION_VALUES]
396
+ if len(found) != 1 or found[0].child_by_field_name("name") is not None:
397
+ return None
398
+ return found[0]
399
+
400
+
401
+ def _ts_anonymous_class(node: Any) -> str | None:
402
+ """The name a class with no name of its own goes by: Java
403
+ ``new Callback<Void>() { … }`` and Kotlin ``object : Callback<T> { … }`` by
404
+ the type they implement, Ruby ``Request = Struct.new(:a) do … end`` by the
405
+ constant it is assigned to."""
406
+ t = node.type
407
+ if t == "object_creation_expression":
408
+ if not any(c.type == "class_body" for c in node.named_children):
409
+ return None
410
+ typ = node.child_by_field_name("type")
411
+ return typ.text.decode("utf-8", "replace") if typ is not None else None
412
+ if t == "object_literal":
413
+ spec = next((c for c in node.named_children if c.type == "delegation_specifier"), None)
414
+ user = None if spec is None else next(
415
+ (c for c in spec.named_children if c.type == "user_type"), None)
416
+ if user is None or not any(c.type == "class_body" for c in node.named_children):
417
+ return None
418
+ return user.text.decode("utf-8", "replace").split("<", 1)[0]
419
+ if t == "assignment":
420
+ left, right = node.child_by_field_name("left"), node.child_by_field_name("right")
421
+ if (left is not None and left.type == "constant" and right is not None
422
+ and right.type == "call" and right.child_by_field_name("block") is not None):
423
+ return left.text.decode("utf-8", "replace")
424
+ return None
425
+
426
+
427
+ def _ts_declarator_name(node: Any) -> str | None:
428
+ """C/C++ function name, which lives in a declarator chain rather than a ``name``
429
+ field: ``function_definition > function_declarator > identifier /
430
+ qualified_identifier / field_identifier``. ``Session::Get`` -> ``Session.Get``.
431
+ The chain is followed through the wrappers that carry no ``declarator`` field
432
+ (``const T& f()`` is a reference_declarator around the function_declarator)."""
433
+ decl = node.child_by_field_name("declarator")
434
+ for _ in range(8): # bounded unwrap
435
+ if decl is None:
436
+ return None
437
+ if decl.type in ("identifier", "field_identifier", "destructor_name",
438
+ "type_identifier", "operator_name"):
439
+ return decl.text.decode("utf-8", "replace")
440
+ if decl.type == "qualified_identifier":
441
+ return decl.text.decode("utf-8", "replace").replace("::", ".")
442
+ decl = decl.child_by_field_name("declarator") or next(
443
+ (c for c in decl.named_children
444
+ if c.type.endswith("declarator") or c.type == "qualified_identifier"
445
+ # (`typedef void (Cb)(int);`: the name in parentheses)
446
+ or decl.type == "parenthesized_declarator"), None)
447
+ return None
448
+
449
+
450
+ def _ts_declares_function(node: Any) -> bool:
451
+ """Whether a C/C++ ``declaration`` / ``field_declaration`` declares a function
452
+ (``int f(void);``) rather than a variable or a field."""
453
+ decl = node.child_by_field_name("declarator")
454
+ for _ in range(8):
455
+ if decl is None:
456
+ return False
457
+ if decl.type == "function_declarator":
458
+ return True
459
+ decl = decl.child_by_field_name("declarator") or next(
460
+ (c for c in decl.named_children if c.type.endswith("declarator")), None)
461
+ return False
462
+
463
+
464
+ def _ts_macro_statement(node: Any) -> bool:
465
+ """A ``declaration`` whose type is a macro call the parser could not read
466
+ (``TEST_ASSERT_EQUAL(p0, p1, 4);`` followed by another, in a function the
467
+ parser lost): two statements, no declaration."""
468
+ typ = node.child_by_field_name("type")
469
+ return typ is not None and typ.type == "macro_type_specifier" and typ.has_error
470
+
471
+
472
+ _CAPITALS = re.compile(r"[A-Z][A-Z0-9_]{2,}")
473
+
474
+
475
+ def _ts_test_macro_name(node: Any) -> str | None:
476
+ """C++ ``TEST(Suite, Name) { … }``, ``TEST_F(Fixture, Name) { … }``: a
477
+ function with no return type, named in capitals, given two bare names. The
478
+ test is ``Suite.Name``, a method of the fixture when the file defines one."""
479
+ if node.type != "function_definition" or node.child_by_field_name("type") is not None:
480
+ return None
481
+ decl = node.child_by_field_name("declarator")
482
+ if decl is None or decl.type != "function_declarator":
483
+ return None
484
+ name = decl.child_by_field_name("declarator")
485
+ params = decl.child_by_field_name("parameters")
486
+ if name is None or name.type != "identifier" or params is None \
487
+ or not _CAPITALS.fullmatch(name.text.decode("utf-8", "replace")):
488
+ return None
489
+ parts = []
490
+ for p in params.named_children:
491
+ inner = p.named_children
492
+ if p.type != "parameter_declaration" or len(inner) != 1 \
493
+ or inner[0].type != "type_identifier":
494
+ return None
495
+ parts.append(inner[0].text.decode("utf-8", "replace"))
496
+ return ".".join(parts) if len(parts) == 2 else None
497
+
498
+
499
+ def _ts_child_name(node: Any) -> str | None:
500
+ """The name of a declaration whose grammar has no ``name`` field: its keyword
501
+ (Swift ``init``), or its first identifier child (Kotlin)."""
502
+ fixed = _TS_KEYWORD_NAMES.get(node.type)
503
+ if fixed is not None:
504
+ return fixed
505
+ if node.type in _TS_OPERATOR_TYPES:
506
+ return _ts_operator_name(node)
507
+ t = node.type.lower()
508
+ if not t.endswith(("_declaration", "_entry", "type_alias")) or "package" in t:
509
+ return None
510
+ for c in node.named_children:
511
+ if c.type in _TS_NAME_CHILD_TYPES:
512
+ return c.text.decode("utf-8", "replace")
513
+ return None
514
+
515
+
516
+ def _ts_operator_name(node: Any) -> str | None:
517
+ """C# `operator +` -> ``operator+``; `implicit operator string(…)` ->
518
+ ``operator string``."""
519
+ if node.type == "conversion_operator_declaration":
520
+ typ = node.child_by_field_name("type")
521
+ return None if typ is None else "operator " + typ.text.decode("utf-8", "replace")
522
+ seen = False
523
+ for c in node.children:
524
+ if seen:
525
+ return "operator" + c.text.decode("utf-8", "replace")
526
+ seen = c.type == "operator"
527
+ return None
528
+
529
+
530
+ _PP_SPACE = b" \t\n\x0c\r" # what Rust's `is_ascii_whitespace` strips
531
+ _PP_ENDS = b";{}],)" # what ends a statement, a block, an attribute or an item of a list
532
+
533
+
534
+ def _blank_expression_branches(src: bytes) -> bytes:
535
+ """C#: an ``#if`` … ``#else`` … ``#endif`` that opens in the middle of an
536
+ expression or a declaration (the code line before it ends none: ``? null``
537
+ before ``#if NET`` / ``: new A(x)`` / ``#else`` / ``: new A()``) is one
538
+ piece of code written once per configuration; the parser, seeing every
539
+ branch, loses the type around. The source with the directive lines and
540
+ every branch but the first blanked (each byte but a newline or carriage
541
+ return a space), else ``src``. Of a group with one branch only the two
542
+ directive lines go: its lines are part of the expression. A group whose
543
+ first branch leaves a brace open, or closes one it did not open (``#if
544
+ NET`` / ``if (!OperatingSystem.IsBrowser()) {`` / ``#endif``, closed by a
545
+ ``}`` in a later group), is treated the same: the parser, pairing the
546
+ brace inside the group, loses the members after it.
547
+
548
+ The native engine's ``parse::blank_expression_branches`` is the same rule.
549
+ """
550
+ if b"#if" not in src:
551
+ return src
552
+ lines = src.split(b"\n")
553
+ blank: list[tuple[int, int]] = []
554
+ # (opened inside an expression, its directive lines, the braces its first
555
+ # branch leaves open)
556
+ stack: list[list[Any]] = []
557
+ last = b"" # the last line of code, without its comment
558
+ for li, line in enumerate(lines):
559
+ t = line.strip(_PP_SPACE)
560
+ if t.startswith(b"#"):
561
+ word = t[1:].lstrip(_PP_SPACE)
562
+ n = 0
563
+ while n < len(word) and word[n:n + 1].isalpha():
564
+ n += 1
565
+ word = word[:n]
566
+ if word == b"if":
567
+ inside = bool(last) and last[-1:] not in _PP_ENDS
568
+ stack.append([inside, [li], 0])
569
+ elif word in (b"elif", b"else"):
570
+ if stack:
571
+ stack[-1][1].append(li)
572
+ elif word == b"endif":
573
+ if stack:
574
+ inside, directives, opened = stack.pop()
575
+ if inside or opened:
576
+ blank.append((directives[0], directives[0]))
577
+ blank.append((directives[1] if len(directives) >= 2 else li, li))
578
+ continue
579
+ cut = t.find(b"//")
580
+ code = (t if cut < 0 else t[:cut]).rstrip(_PP_SPACE)
581
+ if code:
582
+ last = code
583
+ opened = code.count(b"{") - code.count(b"}")
584
+ for g in stack:
585
+ if len(g[1]) == 1:
586
+ g[2] += opened
587
+ if not blank:
588
+ return src
589
+ for lo, hi in blank:
590
+ for i in range(lo, hi + 1):
591
+ lines[i] = bytes(c if c == 0x0D else 0x20 for c in lines[i])
592
+ return b"\n".join(lines)
593
+
594
+
595
+
596
+ _CLASS_MACRO = re.compile(
597
+ rb"\b(?:class|struct|union)[ \t]+([A-Z][A-Z0-9_]{2,})[ \t]+[A-Za-z_][A-Za-z0-9_]*"
598
+ rb"[ \t\r\n]*(?:\{|:[^:]|final\b)")
599
+
600
+
601
+ def _blank_class_macros(src: bytes) -> bytes:
602
+ """C, C++: `class LEVELDB_EXPORT Env {` with the macro blanked.
603
+
604
+ A macro between the keyword and the name is nothing to the language once
605
+ expanded, but the parser takes it for the type's name and the rest for a
606
+ function, so the members belong to no class. Each byte of the macro becomes
607
+ a space (bytes and lines stay where they were). The engine's
608
+ `parse::blank_class_macros` is the same rule.
609
+ """
610
+ out: bytearray | None = None
611
+ for m in _CLASS_MACRO.finditer(src):
612
+ if out is None:
613
+ out = bytearray(src)
614
+ out[m.start(1):m.end(1)] = b" " * (m.end(1) - m.start(1))
615
+ return bytes(out) if out is not None else src
616
+
617
+
618
+ _ANNOTATION_MACRO = re.compile(
619
+ rb"(?m)^([^#\n]*?)([A-Za-z_][A-Za-z0-9_]*|\)|\])(?:[ \t]+|[ \t]*\r?\n[ \t]*)"
620
+ rb"([A-Z][A-Z0-9_]{2,}[ \t]*\(([^()\n]*)\))[ \t]*(?:;|\{|=|,)")
621
+ # Words a declarator name is never: what stands before a call statement
622
+ # (`return FOO(x);`) and the words of a type (`static int ADD(int a);`).
623
+ _NOT_DECLARATOR = frozenset(
624
+ b"return case throw else do goto co_return co_yield co_await sizeof alignof new delete "
625
+ b"typedef using namespace struct class union enum if while for switch catch int char void "
626
+ b"long short unsigned signed float double bool auto static inline extern volatile constexpr "
627
+ b"consteval constinit virtual explicit register mutable thread_local friend operator "
628
+ b"template typename public private protected const override final noexcept".split())
629
+ # Of those, the words that end a function's declarator (`void g() const LOCKS_EXCLUDED(mu)`).
630
+ _AFTER_PARAMS = frozenset((b"const", b"override", b"final", b"noexcept"))
631
+ _LOOKBACK = 2000 # how far back the `(` a parameter list opens with is looked for
632
+ _CONTROL = frozenset(
633
+ b"if while for switch catch return sizeof alignof decltype typeof defined".split())
634
+ # A macro alone on an indented line, before a line that starts with a call.
635
+ _STATEMENT_MACRO = re.compile(
636
+ rb"(?m)^[ \t]+([A-Z][A-Z0-9_]{2,})[ \t]*\r?\n[ \t]*[A-Za-z_][A-Za-z0-9_]*[ \t]*\(")
637
+ _PARAM_DECL = re.compile(rb"[A-Za-z_][A-Za-z0-9_]*[ \t*&]+[A-Za-z_]")
638
+
639
+
640
+ def _blank_annotation_macros(src: bytes) -> bytes:
641
+ """C, C++: `int count GUARDED_BY(mu);` and `void f() REQUIRES(mu);` with the
642
+ macro blanked.
643
+
644
+ An all-capital macro written after a declaration's name or parameters
645
+ (clang's thread-safety annotations, `ABSL_GUARDED_BY`) expands to an
646
+ attribute, but the parser takes it for the declarator: the field is lost
647
+ and a function named after the macro is made up. A macro counts when what
648
+ stands before it is a declarator name (an identifier after a type, not a
649
+ keyword) or a parameter list (`)` not closing an `if`, a `while`, …),
650
+ optionally followed by `const` / `override` / `noexcept`, on its line or
651
+ at the start of the next, and when its
652
+ arguments declare no parameter (`ADD(int a)` is a function). Each byte of
653
+ the macro becomes a space. So does a macro alone on an indented line
654
+ before a line that starts with a call (Unity's `EXPECT_ABORT_BEGIN` /
655
+ `TEST_ASSERT(0);`, Qt's `Q_OBJECT` / `Window(int w);`): a statement or
656
+ nothing once expanded, which the parser takes for the type of a
657
+ declaration the next line would be. The engine's
658
+ `parse::blank_annotation_macros` is the same rule.
659
+ """
660
+ if b"(" not in src:
661
+ return src
662
+ out: bytearray | None = None
663
+ for m in _STATEMENT_MACRO.finditer(src):
664
+ if out is None:
665
+ out = bytearray(src)
666
+ out[m.start(1):m.end(1)] = b" " * (m.end(1) - m.start(1))
667
+ for m in _ANNOTATION_MACRO.finditer(src):
668
+ before, word, args = m.group(1).rstrip(b" \t"), m.group(2), m.group(4)
669
+ close = m.start(2) # where the `)` of a parameter list is
670
+ if _PARAM_DECL.search(args):
671
+ continue
672
+ if word in _AFTER_PARAMS:
673
+ if not before.endswith(b")"):
674
+ continue
675
+ word, close = b")", m.start(1) + len(before) - 1
676
+ elif word not in (b")", b"]"):
677
+ # (`]`: an array's declarator, `int stats_[4] GUARDED_BY(mu);`)
678
+ if word in _NOT_DECLARATOR or not before or before[-1:] not in \
679
+ b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_*&>":
680
+ continue
681
+ if word == b")":
682
+ # the word before the `(` this closes, on this line or one above
683
+ # (`Status Recover(VersionEdit* edit,` / `bool* save)` / `REQUIRES(mu);`)
684
+ before = src[max(0, close - _LOOKBACK):close]
685
+ depth, i = 1, len(before) - 1
686
+ while i >= 0 and depth:
687
+ if before[i:i + 1] == b")":
688
+ depth += 1
689
+ elif before[i:i + 1] == b"(":
690
+ depth -= 1
691
+ i -= 1
692
+ if depth:
693
+ continue
694
+ head = before[:i + 1].rstrip(b" \t")
695
+ k = len(head)
696
+ while k > 0 and (head[k - 1:k].isalnum() or head[k - 1:k] in (b"_", b":", b"~")):
697
+ k -= 1
698
+ callee = head[k:].rsplit(b":", 1)[-1]
699
+ if not callee or callee in _CONTROL:
700
+ continue
701
+ if out is None:
702
+ out = bytearray(src)
703
+ out[m.start(3):m.end(3)] = b" " * (m.end(3) - m.start(3))
704
+ return bytes(out) if out is not None else src
705
+
706
+
707
+ def _blank_duplicate_branches(src: bytes) -> bytes:
708
+ """C, C++: an ``#if`` … ``#elif``/``#else`` … ``#endif`` whose every branch
709
+ leaves the same number of braces open (not none) is one piece of code
710
+ written once per configuration (``if (error_code) {`` under ``#if`` and
711
+ again under ``#else``, closed once after ``#endif``); the parser, seeing every
712
+ branch, would swallow the rest of the file into the function around. The
713
+ source with the directive lines and every branch but the first blanked
714
+ (each byte but a newline or carriage return a space), else ``src``.
715
+
716
+ The native engine's ``parse::blank_duplicate_branches`` is the same rule.
717
+ """
718
+ if b"#" not in src:
719
+ return src
720
+ lines: list[tuple[int, int]] = []
721
+ start = 0
722
+ for i, b in enumerate(src):
723
+ if b == 0x0A:
724
+ lines.append((start, i))
725
+ start = i + 1
726
+ if start < len(src):
727
+ lines.append((start, len(src)))
728
+ stack: list[tuple[list[int], list[list[int]]]] = [] # (directives, [[first, delta]])
729
+ blank: list[tuple[int, int]] = []
730
+ in_comment = False
731
+ continued = False
732
+ for li, (lo, hi) in enumerate(lines):
733
+ line = src[lo:hi]
734
+ was_continued = continued
735
+ continued = line.endswith(b"\\") or line.endswith(b"\\\r")
736
+ if was_continued:
737
+ continue
738
+ trimmed = line.lstrip(_PP_SPACE)
739
+ if not in_comment and trimmed[:1] == b"#":
740
+ rest = trimmed[1:].lstrip(_PP_SPACE)
741
+ n = 0
742
+ while n < len(rest) and (65 <= rest[n] <= 90 or 97 <= rest[n] <= 122):
743
+ n += 1
744
+ word = rest[:n]
745
+ if word in (b"if", b"ifdef", b"ifndef"):
746
+ stack.append(([li], [[li + 1, 0]]))
747
+ elif word in (b"elif", b"else", b"elifdef", b"elifndef"):
748
+ if stack:
749
+ stack[-1][0].append(li)
750
+ stack[-1][1].append([li + 1, 0])
751
+ elif word == b"endif":
752
+ if stack:
753
+ directives, branches = stack.pop()
754
+ first = branches[0][1]
755
+ if len(branches) >= 2 and first != 0 and all(b[1] == first for b in branches):
756
+ blank.extend((d, d) for d in directives)
757
+ blank.append((li, li))
758
+ for a, b in zip(directives[1:], directives[2:], strict=False):
759
+ blank.append((a + 1, b - 1))
760
+ if len(directives) >= 2:
761
+ blank.append((directives[-1] + 1, li - 1))
762
+ if stack:
763
+ stack[-1][1][-1][1] += first
764
+ continue
765
+ delta = 0
766
+ i = 0
767
+ while i < len(line):
768
+ c = line[i]
769
+ if in_comment:
770
+ if c == 0x2A and line[i + 1:i + 2] == b"/":
771
+ in_comment = False
772
+ i += 1
773
+ elif c == 0x2F and line[i + 1:i + 2] == b"/":
774
+ break
775
+ elif c == 0x2F and line[i + 1:i + 2] == b"*":
776
+ in_comment = True
777
+ i += 1
778
+ elif c in (0x22, 0x27):
779
+ i += 1
780
+ while i < len(line) and line[i] != c:
781
+ if line[i] == 0x5C:
782
+ i += 1
783
+ i += 1
784
+ elif c == 0x7B:
785
+ delta += 1
786
+ elif c == 0x7D:
787
+ delta -= 1
788
+ i += 1
789
+ if stack:
790
+ stack[-1][1][-1][1] += delta
791
+ if not blank:
792
+ return src
793
+ out = bytearray(src)
794
+ last = len(lines) - 1
795
+ for a, b in blank:
796
+ for lo, hi in lines[a:min(b, last) + 1]:
797
+ for k in range(lo, hi):
798
+ if out[k] != 0x0D:
799
+ out[k] = 0x20
800
+ return bytes(out)
801
+
802
+
803
+ def _spans_treesitter(src: bytes, rel: str) -> list[tuple[int, int, int, str]]:
804
+ """def/class/etc. spans for any tree-sitter-supported language (optional dep).
805
+
806
+ Generic: a named node whose type hints at a definition and that exposes a
807
+ ``name`` field becomes a span ``(region_start, end, def_line, qualname)``,
808
+ where ``region_start`` absorbs leading doc-comment/decorator/annotation lines
809
+ and the qualname chains enclosing named symbols. Empty when the tree-sitter
810
+ backend or the language is unavailable (caller then uses the point heuristic).
811
+ """
812
+ parser, lang = _ts_parser_for(rel, src)
813
+ if parser is None:
814
+ # No Python tree-sitter (or no grammar, offline): with the native engine
815
+ # chosen, its compiled-in grammars answer with the same rule.
816
+ if engine.requested() != "graphify":
817
+ return engine.file_spans(src, rel) or []
818
+ return []
819
+ try:
820
+ # (C, C++: an `#if` written once per configuration is parsed once)
821
+ parsed = src
822
+ if lang in ("c", "cpp"):
823
+ # (and `class EXPORT_MACRO Name {` without the macro)
824
+ # (and `int n GUARDED_BY(mu);` without the macro)
825
+ parsed = _blank_duplicate_branches(_blank_annotation_macros(_blank_class_macros(src)))
826
+ elif lang == "csharp":
827
+ # (C#: an `#if` in the middle of an expression is parsed once)
828
+ parsed = _blank_expression_branches(src)
829
+ root = parser.parse(parsed).root_node
830
+ except Exception:
831
+ return []
832
+ spans: list[tuple[int, int, int, str]] = []
833
+ fields = _ts_fields(lang or "", parser.language)
834
+ f_name, f_body, f_recv, f_type = (fields["name"], fields["body"],
835
+ fields["receiver"], fields["type"])
836
+ f_value, f_left = fields["value"], fields["left"]
837
+ symbol_cache = _TS_SYMBOL_CACHE
838
+
839
+ def add(child: Any, qual: str) -> None:
840
+ def_line = child.start_point[0] + 1
841
+ end = child.end_point[0] + 1
842
+ spans.append((_ts_region_start(child, def_line), end, def_line, qual))
843
+
844
+ # Every check below is the one the generic rules make; they are only ordered
845
+ # so that a node pays for the lookups that can still change the answer.
846
+ def walk(node: Any, prefix: str) -> None:
847
+ for child in node.named_children:
848
+ t = child.type
849
+ if not child.child_count:
850
+ # a leaf has no fields and no children: only a keyword-named
851
+ # definition can come of it
852
+ kname = _TS_KEYWORD_NAMES.get(t)
853
+ if kname is not None:
854
+ add(child, f"{prefix}{kname}")
855
+ continue
856
+ is_sym = symbol_cache.get(t)
857
+ if is_sym is None:
858
+ is_sym = _ts_is_symbol_type(t)
859
+ kname = _TS_KEYWORD_NAMES.get(t)
860
+ if kname is not None:
861
+ # a keyword-named definition (Swift `subscript`, whose `name`
862
+ # field is its result type)
863
+ qual = f"{prefix}{kname}"
864
+ add(child, qual)
865
+ walk(child, qual + ".")
866
+ continue
867
+ name_node = child.child_by_field_id(f_name) \
868
+ if is_sym and f_name is not None else None
869
+ if name_node is not None and t.endswith("_specifier") \
870
+ and (f_body is None or child.child_by_field_id(f_body) is None):
871
+ # C/C++ `struct config cfg` in a signature, or a forward
872
+ # declaration: the type is named here, not defined
873
+ walk(child, prefix)
874
+ elif name_node is not None and t == "mod_item" \
875
+ and (f_body is None or child.child_by_field_id(f_body) is None):
876
+ pass # Rust `mod foo;` names a file, it defines nothing here
877
+ elif name_node is not None:
878
+ base = name_node.text.decode("utf-8", "replace") + _TS_NAME_SUFFIX.get(t, "")
879
+ # Go method: prefix the receiver's type
880
+ recv = child.child_by_field_id(f_recv) if f_recv is not None else None
881
+ if recv is not None and (rt := _ts_receiver_type(recv)):
882
+ base = f"{rt}.{base}"
883
+ qual = f"{prefix}{base}"
884
+ add(child, qual)
885
+ if "enum" in t:
886
+ # Swift `case a, b, c`: one definition per name
887
+ for other in child.children_by_field_name("name")[1:]:
888
+ add(child, prefix + other.text.decode("utf-8", "replace"))
889
+ walk(child, qual + ".")
890
+ elif is_sym and f_type is not None and "impl" in t.lower() \
891
+ and (type_node := child.child_by_field_id(f_type)) is not None:
892
+ # Rust `impl Pool { ... }`: no `name` field, but the `type` field
893
+ # contributes to the qualname chain (so methods read `Pool.acquire`)
894
+ # without a span. Restricted to impl-like nodes so a C++
895
+ # function_definition's `type` (its return type) isn't mistaken for one.
896
+ # Strip generics: `impl ConfigBuilder<X>` -> `ConfigBuilder.`, not the
897
+ # full `ConfigBuilder<X>.`.
898
+ base = type_node.child_by_field_id(f_type) or type_node
899
+ walk(child, f"{prefix}{base.text.decode('utf-8', 'replace')}.")
900
+ elif (is_sym or (t in _TS_PROTOTYPE_TYPES
901
+ and _ts_declares_function(child)
902
+ and not _ts_macro_statement(child))) \
903
+ and (dname := (_ts_test_macro_name(child)
904
+ or _ts_declarator_name(child))) is not None:
905
+ # C/C++ function/method: the name lives in the declarator chain
906
+ qual = f"{prefix}{dname}"
907
+ add(child, qual)
908
+ walk(child, qual + ".")
909
+ elif is_sym and (kname := _ts_child_name(child)) is not None:
910
+ # no `name` field in this grammar (Kotlin), or a keyword-named
911
+ # definition (Swift `init`)
912
+ qual = f"{prefix}{kname}"
913
+ add(child, qual)
914
+ walk(child, qual + ".")
915
+ elif t in _TS_ANON_CLASS_TYPES and (anon := _ts_anonymous_class(child)) is not None:
916
+ # a class with no name of its own: named by what it implements
917
+ qual = f"{prefix}{anon}"
918
+ add(child, qual)
919
+ walk(child, qual + ".")
920
+ elif child.child_count >= 2 and (
921
+ (f_value is not None and child.child_by_field_id(f_value) is not None)
922
+ or (f_left is not None and child.child_by_field_id(f_left) is not None)) \
923
+ and (bound := _ts_bound_function(child, fields)) is not None:
924
+ # anonymous function bound to a name: `const f = () => …`. It takes
925
+ # two children, one of them a `value` or a `left`.
926
+ bname, fn = bound
927
+ qual = f"{prefix}{bname}"
928
+ def_line = fn.start_point[0] + 1
929
+ end = fn.end_point[0] + 1
930
+ spans.append((def_line, end, def_line, qual))
931
+ walk(fn, qual + ".")
932
+ else:
933
+ walk(child, prefix)
934
+
935
+ try:
936
+ walk(root, "")
937
+ except RecursionError:
938
+ pass
939
+ return spans
940
+
941
+
942
+ # --- test code that lives in a source file ------------------------------------
943
+ # Rust keeps unit tests next to the code: `#[cfg(test)] mod tests { … }` and
944
+ # `#[test] fn …`. No path rule can tell those from production code, so the span
945
+ # engine marks their line ranges. Per file, (path, mtime)-cached like the spans.
946
+ _TEST_REGION_CACHE: dict[str, tuple[float, list[tuple[int, int]]]] = {}
947
+
948
+
949
+ def _rust_attributes(node: Any) -> list[str]:
950
+ """Texts of the `#[...]` attributes stacked right above ``node``."""
951
+ out: list[str] = []
952
+ prev = node.prev_named_sibling
953
+ while prev is not None and (prev.type == "attribute_item" or "comment" in prev.type):
954
+ if prev.type == "attribute_item":
955
+ out.append(prev.text.decode("utf-8", "replace"))
956
+ prev = prev.prev_named_sibling
957
+ return out
958
+
959
+
960
+ _RUST_CFG_TEST = re.compile(r"\bcfg\s*\((?:[^()]|\([^()]*\))*\btest\b")
961
+ _RUST_CFG_NOT_TEST = re.compile(r"\bnot\s*\(\s*test\s*\)")
962
+ _RUST_TEST_ATTR = re.compile(r"^#\s*\[\s*(?:[\w:]+::)?test\s*(?:\(|\])")
963
+
964
+
965
+ def _is_cfg_test(attr: str) -> bool:
966
+ return bool(_RUST_CFG_TEST.search(attr)) and not _RUST_CFG_NOT_TEST.search(attr)
967
+
968
+
969
+ def _test_regions_rust(src: bytes, rel: str) -> list[tuple[int, int]]:
970
+ parser, _lang = _ts_parser_for(rel, src)
971
+ if parser is None:
972
+ return []
973
+ try:
974
+ root = parser.parse(src).root_node
975
+ except Exception:
976
+ return []
977
+ if any(c.type == "inner_attribute_item" and _is_cfg_test(c.text.decode("utf-8", "replace"))
978
+ for c in root.named_children):
979
+ return [(1, root.end_point[0] + 1)] # `#![cfg(test)]`: the whole file
980
+ regions: list[tuple[int, int]] = []
981
+
982
+ def walk(node: Any) -> None:
983
+ for child in node.named_children:
984
+ span = (child.start_point[0] + 1, child.end_point[0] + 1)
985
+ if child.type == "mod_item":
986
+ body = child.child_by_field_name("body")
987
+ inner = body is not None and any(
988
+ c.type == "inner_attribute_item"
989
+ and _is_cfg_test(c.text.decode("utf-8", "replace"))
990
+ for c in body.named_children)
991
+ if inner or any(_is_cfg_test(a) for a in _rust_attributes(child)):
992
+ regions.append(span)
993
+ continue
994
+ elif child.type == "function_item" and any(
995
+ # (`#[cfg(test)] fn helper()`: compiled only with the tests)
996
+ _RUST_TEST_ATTR.match(a) or _is_cfg_test(a)
997
+ for a in _rust_attributes(child)):
998
+ regions.append(span)
999
+ continue
1000
+ walk(child)
1001
+
1002
+ try:
1003
+ walk(root)
1004
+ except RecursionError:
1005
+ pass
1006
+ return regions
1007
+
1008
+
1009
+ def _test_regions(file_path: str) -> list[tuple[int, int]]:
1010
+ """Line ranges of a source file that are test code although the file is not a
1011
+ test file. Rust only: other languages keep tests in test files, which
1012
+ `_is_test_path` recognises."""
1013
+ if not str(file_path).lower().endswith(".rs"):
1014
+ return []
1015
+ return _cached_file_analysis(_TEST_REGION_CACHE, file_path, _test_regions_rust, list)
1016
+
1017
+
1018
+ def _is_test_node(n: dict) -> bool:
1019
+ """A node that is test code: in a test file, or inside a test region of a
1020
+ source file (a Rust `#[cfg(test)]` module or `#[test]` function)."""
1021
+ file = _node_file(n)
1022
+ if not file:
1023
+ return False
1024
+ if _is_test_path(file):
1025
+ return True
1026
+ regions = _test_regions(file)
1027
+ if not regions:
1028
+ return False
1029
+ try:
1030
+ line = int(_node_line(n))
1031
+ except (TypeError, ValueError):
1032
+ return False
1033
+ return any(lo <= line <= hi for lo, hi in regions)
1034
+
1035
+
1036
+ def _spans_for_file(file_path: str) -> list[tuple[int, int, int, str]]:
1037
+ """def/class/etc. spans for a source file under PROJECT_DIR, across languages.
1038
+
1039
+ Returns ``[(region_start, end_line, def_line, qualname), ...]`` sorted by
1040
+ ``region_start``. Python uses stdlib ``ast`` (decorator-aware, zero deps); any
1041
+ other language uses the optional tree-sitter backend when present. Empty for
1042
+ unsupported / missing / unparseable files (cached either way so a broken file
1043
+ isn't re-parsed). Cached by (path, mtime).
1044
+ """
1045
+ # Read bytes so a BOM / coding cookie is honored. Span extraction is
1046
+ # best-effort: any failure degrades to [] so the caller falls back to the
1047
+ # point heuristic rather than breaking the whole locate.
1048
+ def compute(src: bytes, rel: str) -> list[tuple[int, int, int, str]]:
1049
+ spans = _spans_python(src) if rel.lower().endswith(".py") else _spans_treesitter(src, rel)
1050
+ spans.sort(key=lambda s: s[0])
1051
+ return spans
1052
+
1053
+ return _cached_file_analysis(_SPAN_CACHE, file_path, compute, list)
1054
+
1055
+
1056
+ def _enclosing_spans(
1057
+ file_path: str, line: int, end_line: int
1058
+ ) -> list[tuple[int, int, int, str]]:
1059
+ """Spans enclosing a semble chunk, most-specific first.
1060
+
1061
+ If a symbol's real range contains the chunk *start*, return those
1062
+ innermost-first (decorator-aware true containment). Otherwise the chunk
1063
+ starts in module-level code spanning several defs — return the symbols whose
1064
+ definitions begin inside the chunk, earliest first (the first symbol the
1065
+ chunk introduces), never a tiny method that only the chunk's tail grazes.
1066
+ """
1067
+ spans = _spans_for_file(file_path)
1068
+ if not spans:
1069
+ return []
1070
+ containing = [s for s in spans if s[0] <= line <= s[1]]
1071
+ if containing:
1072
+ # innermost = smallest region; tie-break the later (more specific) def
1073
+ containing.sort(key=lambda s: (s[1] - s[0], -s[2]))
1074
+ return containing
1075
+ in_chunk = [s for s in spans if line < s[2] <= end_line]
1076
+ in_chunk.sort(key=lambda s: s[2]) # earliest definition first
1077
+ return in_chunk
1078
+
1079
+
1080
+ def _span_of_definition(
1081
+ file_path: str, line: int, name: str
1082
+ ) -> tuple[int, int, int, str] | None:
1083
+ """The span of the definition a graph node stands for.
1084
+
1085
+ Several spans can start on one line (``enum Color { RED, GREEN }``, a class and
1086
+ its one-line member), and the innermost is then not the node's own: the span
1087
+ that starts on the node's line under the node's name wins, else the innermost
1088
+ enclosing one.
1089
+ """
1090
+ spans = _enclosing_spans(file_path, line, line)
1091
+ if not spans:
1092
+ return None
1093
+ for s in spans:
1094
+ if s[2] == line and s[3].rsplit(".", 1)[-1] == name:
1095
+ return s
1096
+ return spans[0]
1097
+
1098
+
1099
+ def _span_qualname(file_path: str, line: int, end_line: int | None = None) -> str | None:
1100
+ """Fully-qualified name of the most specific symbol enclosing a chunk, if any."""
1101
+ hi = end_line if end_line is not None else line
1102
+ spans = _enclosing_spans(file_path, line, hi)
1103
+ return spans[0][3] if spans else None
1104
+
1105
+
1106
+ # file (normalized relpath) -> nodes index, keyed by id(nodes) with an identity
1107
+ # guard — the same scheme as graph._ADJ_CACHE. _node_for_location is called in
1108
+ # loops (per semantic hit in locate, per seed/related pair in duplication_scan,
1109
+ # per route row), so the full-node scan it replaced was O(calls x N).
1110
+ _FILE_NODES_CACHE: dict[int, tuple[list[dict], dict[str, list[dict]]]] = {}
1111
+ _FILE_NODES_CACHE_MAX = 8
1112
+
1113
+
1114
+ def _nodes_by_file(nodes: list[dict]) -> dict[str, list[dict]]:
1115
+ """Normalized-relpath -> nodes map for `nodes`, cached on list identity."""
1116
+ cached = _FILE_NODES_CACHE.get(id(nodes))
1117
+ if cached is not None and cached[0] is nodes:
1118
+ return cached[1]
1119
+ by_file: dict[str, list[dict]] = {}
1120
+ for n in nodes:
1121
+ rel = _norm_relpath(_node_file(n))
1122
+ if rel:
1123
+ by_file.setdefault(rel, []).append(n)
1124
+ if id(nodes) not in _FILE_NODES_CACHE and len(_FILE_NODES_CACHE) >= _FILE_NODES_CACHE_MAX:
1125
+ _FILE_NODES_CACHE.pop(next(iter(_FILE_NODES_CACHE)), None) # FIFO
1126
+ _FILE_NODES_CACHE[id(nodes)] = (nodes, by_file)
1127
+ return by_file
1128
+
1129
+
1130
+ def _node_for_location(
1131
+ nodes: list[dict], file_path: str, line: int, end_line: int | None = None
1132
+ ) -> dict | None:
1133
+ """Map a semble chunk ``(file_path, line[..end_line])`` to its graph node.
1134
+
1135
+ Resolution order:
1136
+ 1. **Span containment** (source available): find the most specific def/class
1137
+ whose real line range encloses the chunk, then the code node that *owns*
1138
+ that symbol; walk outward to the next enclosing symbol that has a node (so
1139
+ a chunk inside a nested closure with no node resolves to the enclosing
1140
+ function that does). A node owns the span that most tightly encloses its
1141
+ *own* line, so a node whose ``source_location`` points into a body
1142
+ (LLM-origin nodes) still binds to its real symbol. Using real end-lines,
1143
+ this never misattributes a chunk to a previous function that already
1144
+ ended — graphify nodes carry only a single ``source_location`` point.
1145
+ 2. **Point heuristic** (fallback: no source on disk / no enclosing span
1146
+ carried a node): prefer a ``file_type == "code"`` node, pick the enclosing
1147
+ definition (greatest line <= start), else a def starting inside the chunk,
1148
+ else the closest. ``None`` only if the file has no nodes.
1149
+ """
1150
+ target = _norm_relpath(file_path)
1151
+ if not target:
1152
+ return None
1153
+ same_file = _nodes_by_file(nodes).get(target, [])
1154
+ if not same_file:
1155
+ return None
1156
+ hi = end_line if end_line is not None else line
1157
+ code = [n for n in same_file if str(n.get("file_type", "")).lower() == "code"]
1158
+
1159
+ # 1. canonical span join: a node belongs to the span most tightly enclosing its
1160
+ # own line; resolve to the node owned by the most specific span enclosing the
1161
+ # chunk, walking outward to the nearest enclosing symbol that owns a node.
1162
+ spans = _spans_for_file(file_path)
1163
+ if spans and code:
1164
+ def _owning_def(ln: int) -> int | None:
1165
+ here = [s for s in spans if s[0] <= ln <= s[1]]
1166
+ return min(here, key=lambda s: (s[1] - s[0], -s[2]))[2] if here else None
1167
+
1168
+ owner: dict[int, int | None] = {}
1169
+ for n in code:
1170
+ try:
1171
+ owner[id(n)] = _owning_def(int(_node_line(n)))
1172
+ except (TypeError, ValueError):
1173
+ owner[id(n)] = None
1174
+ for _rs, _end, def_line, _qual in _enclosing_spans(file_path, line, hi):
1175
+ owned = [n for n in code if owner.get(id(n)) == def_line]
1176
+ if owned:
1177
+ return min(owned, key=lambda n: abs(int(_node_line(n)) - def_line))
1178
+ # spans exist but none own a code node -> fall through to point heuristic
1179
+
1180
+ def _pick(cands: list[dict]) -> dict | None:
1181
+ lined: list[tuple[dict, int]] = []
1182
+ for n in cands:
1183
+ try:
1184
+ lined.append((n, int(_node_line(n))))
1185
+ except (TypeError, ValueError):
1186
+ pass
1187
+ if not lined:
1188
+ return cands[0] if cands else None
1189
+ encl = [(n, ln) for n, ln in lined if ln <= line]
1190
+ if encl:
1191
+ return max(encl, key=lambda x: x[1])[0]
1192
+ in_chunk = [(n, ln) for n, ln in lined if line < ln <= hi]
1193
+ if in_chunk:
1194
+ return min(in_chunk, key=lambda x: x[1])[0]
1195
+ return min(lined, key=lambda x: abs(x[1] - line))[0]
1196
+
1197
+ return _pick(code) or _pick(same_file)
1198
+
1199
+
1200
+ def _ts_skeleton(root: Any) -> tuple | None:
1201
+ """A structural fingerprint of a tree-sitter tree that ignores comments (and,
1202
+ since whitespace isn't a token, formatting).
1203
+
1204
+ Walks ALL children — anonymous operator/keyword/punctuation tokens included —
1205
+ so that an operator flip (``+``→``-``, ``==``→``!=``, ``&&``→``||``), a
1206
+ ``sync``→``async`` or ``let``→``const`` change, and any rename/value edit are
1207
+ all structural; only comment and whitespace edits compare equal. ``None`` on
1208
+ overflow."""
1209
+ parts: list = []
1210
+
1211
+ def walk(n: Any) -> None:
1212
+ if "comment" in n.type: # comments are cosmetic in every grammar
1213
+ return
1214
+ if n.child_count == 0:
1215
+ parts.append((n.type, bytes(n.text))) # leaf (named OR anonymous token)
1216
+ else:
1217
+ parts.append((n.type,))
1218
+ for c in n.children:
1219
+ walk(c)
1220
+
1221
+ try:
1222
+ walk(root)
1223
+ except RecursionError:
1224
+ return None
1225
+ return tuple(parts)
1226
+
1227
+
1228
+ def _structurally_equal(rel: str, old_src: Any, new_src: Any) -> bool | None:
1229
+ """True if two source versions differ only cosmetically.
1230
+
1231
+ Python uses ``ast.dump`` equality; any other language uses a comment-stripped
1232
+ tree-sitter skeleton. ``None`` when it can't be determined (unparseable, or no
1233
+ backend for the language).
1234
+ """
1235
+ if rel.lower().endswith(".py"):
1236
+ try:
1237
+ return ast.dump(ast.parse(old_src)) == ast.dump(ast.parse(new_src))
1238
+ except (SyntaxError, ValueError, RecursionError):
1239
+ return None
1240
+ def _b(s: Any) -> bytes:
1241
+ return bytes(s) if isinstance(s, bytes | bytearray) else str(s).encode("utf-8", "replace")
1242
+
1243
+ parser, _lang = _ts_parser_for(rel, _b(new_src))
1244
+ if parser is None:
1245
+ return None
1246
+
1247
+ try:
1248
+ a = _ts_skeleton(parser.parse(_b(old_src)).root_node)
1249
+ b = _ts_skeleton(parser.parse(_b(new_src)).root_node)
1250
+ except Exception:
1251
+ return None
1252
+ if a is None or b is None:
1253
+ return None
1254
+ return a == b