ethicaldilkhush-code-context-mcp 0.1.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.
@@ -0,0 +1,993 @@
1
+ """Structure-aware chunking of source files.
2
+
3
+ ``parse_source`` turns one file into ``Chunk`` objects aligned with language
4
+ constructs:
5
+
6
+ * tree-sitter languages: one chunk per function, method, class, interface,
7
+ struct, enum, ... plus "module" chunks for top-level code between them;
8
+ * Markdown: one chunk per heading section;
9
+ * anything else: line windows split on blank lines.
10
+
11
+ Alongside the chunks it extracts the metadata the rest of the system relies
12
+ on: signatures, doc comments, enclosing type, base types, called names and
13
+ imports.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import inspect
19
+ import re
20
+ from dataclasses import dataclass, field
21
+ from typing import Iterator
22
+
23
+ from tree_sitter import Node
24
+
25
+ from .languages import LanguageSpec, new_parser
26
+ from .models import CONTAINER_KINDS, Chunk, ImportRef, ParsedFile
27
+ from .textutil import collapse_whitespace, truncate
28
+
29
+ MAX_SIGNATURE_CHARS = 300
30
+ MAX_DOCSTRING_CHARS = 800
31
+ MAX_CALLS_PER_CHUNK = 80
32
+ WINDOW_TARGET_LINES = 60
33
+ WINDOW_MAX_LINES = 100
34
+
35
+ _IDENT_RE = re.compile(r"[A-Za-z_$][A-Za-z0-9_$]*[?!]?")
36
+ _IDENT_TYPES = frozenset({"constant", "name", "word"})
37
+ # Fields that hold "the name" of a qualified expression, most specific first.
38
+ _NAME_FIELDS = ("name", "property", "attribute", "field", "method", "function", "value")
39
+ _CALLEE_FIELDS = ("function", "name", "method", "constructor", "type")
40
+ _JS_FUNCTION_VALUES = frozenset(
41
+ {"arrow_function", "function_expression", "function", "generator_function", "class"}
42
+ )
43
+ _JS_NON_OWNERS = frozenset({"module", "exports", "this", "window", "self", "globalThis"})
44
+ _BODY_TYPES = frozenset(
45
+ {
46
+ "function_body",
47
+ "class_body",
48
+ "enum_class_body",
49
+ "protocol_body",
50
+ "block",
51
+ "declaration_list",
52
+ "field_declaration_list",
53
+ "compound_statement",
54
+ "statement_block",
55
+ "body_statement",
56
+ "enum_body",
57
+ "interface_body",
58
+ }
59
+ )
60
+ _HERITAGE_LISTS = frozenset(
61
+ {
62
+ "class_heritage",
63
+ "superclass",
64
+ "super_interfaces",
65
+ "extends_interfaces",
66
+ "argument_list",
67
+ "trait_bounds",
68
+ "delegation_specifiers",
69
+ }
70
+ )
71
+ # Lines that carry no content of their own: closing brackets (optionally with a
72
+ # trailing comment) and bare block openers such as `type (` or `namespace ui {`.
73
+ _NOISE_LINE_RE = re.compile(
74
+ r"^[\s)\]};,]*$" # only closers / punctuation
75
+ r"|^\s*[)\]}][\s)\]};,]*(//|#|--).*$" # closer followed by a comment
76
+ r"|^(\w+[ \t]*){1,4}[{(]$" # bare block opener
77
+ )
78
+ _NOISE_LINES = frozenset({"end", "<?php", "?>", "#pragma once"})
79
+ _MD_HEADING_RE = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$")
80
+ _COMMENT_MARKER_RE = re.compile(r"^(///?!?|//!|/\*\*?|\*/|\*|#!?|--)\s?")
81
+ _XML_TAG_RE = re.compile(r"</?[A-Za-z][\w:.-]*[^<>]*>")
82
+
83
+
84
+ @dataclass
85
+ class _Def:
86
+ """A syntax node recognised as a definition."""
87
+
88
+ kind: str
89
+ name: str
90
+ owner: str | None = None
91
+ body: Node | None = None
92
+
93
+
94
+ @dataclass
95
+ class _Raw:
96
+ """A chunk under construction, addressed by 0-based rows."""
97
+
98
+ kind: str
99
+ name: str
100
+ qualified_name: str
101
+ start_row: int
102
+ end_row: int
103
+ def_row: int
104
+ signature: str = ""
105
+ docstring: str = ""
106
+ parent: int | None = None
107
+ owner: str | None = None
108
+ bases: list[str] = field(default_factory=list)
109
+ calls: list[str] = field(default_factory=list)
110
+
111
+
112
+ # --------------------------------------------------------------------------- helpers
113
+
114
+
115
+ def _node_text(node: Node) -> str:
116
+ return (node.text or b"").decode("utf-8", "replace")
117
+
118
+
119
+ def _iter_tree(root: Node) -> Iterator[Node]:
120
+ """Every node under ``root`` in document order, without recursion."""
121
+ cursor = root.walk()
122
+ descend = True
123
+ while True:
124
+ if descend:
125
+ yield cursor.node
126
+ if cursor.goto_first_child():
127
+ continue
128
+ if cursor.goto_next_sibling():
129
+ descend = True
130
+ elif cursor.goto_parent():
131
+ descend = False
132
+ else:
133
+ return
134
+
135
+
136
+ def _rightmost_name(node: Node | None, depth: int = 0) -> str | None:
137
+ """The identifier a (possibly qualified or generic) expression refers to.
138
+
139
+ ``a.b.c`` -> ``c``, ``ns::Type<T>`` -> ``Type``, ``foo`` -> ``foo``.
140
+ """
141
+ if node is None or depth > 8:
142
+ return None
143
+ if node.named_child_count == 0:
144
+ if node.type.endswith("identifier") or node.type in _IDENT_TYPES:
145
+ text = _node_text(node)
146
+ return text if _IDENT_RE.fullmatch(text) else None
147
+ return None
148
+ for name in _NAME_FIELDS:
149
+ child = node.child_by_field_name(name)
150
+ if child is not None:
151
+ found = _rightmost_name(child, depth + 1)
152
+ if found:
153
+ return found
154
+ for child in reversed(node.named_children):
155
+ if "argument" in child.type or "parameter" in child.type:
156
+ continue
157
+ found = _rightmost_name(child, depth + 1)
158
+ if found:
159
+ return found
160
+ return None
161
+
162
+
163
+ def _scope_name(text: str) -> str:
164
+ """`a::b` / `App\\Mail` / `Shop.Services` as a dotted path."""
165
+ return ".".join(p for p in re.split(r"::|\\|\.|\s+", text) if p)
166
+
167
+
168
+ def _call_name(node: Node) -> str | None:
169
+ for name in _CALLEE_FIELDS:
170
+ child = node.child_by_field_name(name)
171
+ if child is not None:
172
+ return _rightmost_name(child)
173
+ if node.named_child_count:
174
+ return _rightmost_name(node.named_children[0])
175
+ return None
176
+
177
+
178
+ def _c_declarator_name(node: Node | None) -> tuple[str | None, str | None]:
179
+ """(name, owning scope) of a C/C++ declarator such as ``*A::m(int)``."""
180
+ owner: str | None = None
181
+ for _ in range(12):
182
+ if node is None:
183
+ return None, owner
184
+ kind = node.type
185
+ if kind in ("identifier", "field_identifier", "type_identifier", "destructor_name", "operator_name"):
186
+ return collapse_whitespace(_node_text(node)), owner
187
+ if kind in ("qualified_identifier", "scoped_identifier"):
188
+ scope = node.child_by_field_name("scope")
189
+ if scope is not None:
190
+ owner = _rightmost_name(scope) or collapse_whitespace(_node_text(scope))
191
+ node = node.child_by_field_name("name")
192
+ continue
193
+ if kind == "template_function":
194
+ node = node.child_by_field_name("name")
195
+ continue
196
+ nxt = node.child_by_field_name("declarator")
197
+ if nxt is None:
198
+ nxt = next(
199
+ (c for c in node.named_children if "declarator" in c.type or "identifier" in c.type),
200
+ None,
201
+ )
202
+ node = nxt
203
+ return None, owner
204
+
205
+
206
+ def _clean_comment(lines: list[str]) -> str:
207
+ out: list[str] = []
208
+ for line in lines:
209
+ text = line.strip()
210
+ if text.startswith(("#[", "#![", "@")): # attributes / annotations, not prose
211
+ continue
212
+ text = _COMMENT_MARKER_RE.sub("", text)
213
+ if text.endswith("*/"):
214
+ text = text[:-2].rstrip()
215
+ out.append(_XML_TAG_RE.sub("", text).strip())
216
+ return truncate("\n".join(out).strip(), MAX_DOCSTRING_CHARS)
217
+
218
+
219
+ def _is_meaningful(lines: list[str]) -> bool:
220
+ for line in lines:
221
+ text = line.strip()
222
+ if text and not _NOISE_LINE_RE.match(text) and text not in _NOISE_LINES:
223
+ return True
224
+ return False
225
+
226
+
227
+ def _windows(lines: list[str], start: int, end: int) -> list[tuple[int, int]]:
228
+ """Split rows ``start..end`` into windows, preferring blank-line boundaries."""
229
+ out: list[tuple[int, int]] = []
230
+ row = start
231
+ while end - row + 1 > WINDOW_MAX_LINES:
232
+ blank = next(
233
+ (r for r in range(row + WINDOW_TARGET_LINES, row + WINDOW_MAX_LINES) if not lines[r].strip()),
234
+ None,
235
+ )
236
+ if blank is None: # no paragraph break in range: cut at the hard limit
237
+ out.append((row, row + WINDOW_MAX_LINES - 1))
238
+ row += WINDOW_MAX_LINES
239
+ else:
240
+ out.append((row, blank - 1))
241
+ row = blank + 1
242
+ if row <= end:
243
+ out.append((row, end))
244
+ return out
245
+
246
+
247
+ def _trim_blank(lines: list[str], start: int, end: int) -> tuple[int, int]:
248
+ while start <= end and not lines[start].strip():
249
+ start += 1
250
+ while end >= start and not lines[end].strip():
251
+ end -= 1
252
+ return start, end
253
+
254
+
255
+ # --------------------------------------------------------------------------- tree-sitter
256
+
257
+
258
+ class _TreeChunker:
259
+ def __init__(self, spec: LanguageSpec, text: str) -> None:
260
+ self.spec = spec
261
+ self.source = text.encode("utf-8", "replace")
262
+ self.lines = text.split("\n")
263
+ self.raw: list[_Raw] = []
264
+ self.imports: list[ImportRef] = []
265
+ self._calls: list[tuple[int, str]] = []
266
+
267
+ # -- entry point
268
+
269
+ def run(self, root: Node) -> tuple[list[Chunk], list[ImportRef]]:
270
+ stack: list[tuple[Node, int | None, tuple[str, ...]]] = [(root, None, ())]
271
+ while stack:
272
+ node, parent, scope = stack.pop()
273
+ descend = self._visit(node, parent, scope)
274
+ if descend is not None:
275
+ inner, inner_parent, inner_scope = descend
276
+ for child in reversed(inner.named_children):
277
+ stack.append((child, inner_parent, inner_scope))
278
+ self._link_owners()
279
+ self._collect_references(root)
280
+ self._add_module_chunks()
281
+ self._assign_calls()
282
+ return self._finish(), self.imports
283
+
284
+ # -- structure walk
285
+
286
+ def _visit(
287
+ self, node: Node, parent: int | None, scope: tuple[str, ...]
288
+ ) -> tuple[Node, int | None, tuple[str, ...]] | None:
289
+ spec = self.spec
290
+ target = node
291
+ wrapped = False
292
+ if node.type in spec.wrappers:
293
+ inner = self._unwrap(node)
294
+ if inner is None:
295
+ return node, parent, scope
296
+ target, wrapped = inner, True
297
+
298
+ found = self._classify(target, wrapped)
299
+ if found is None:
300
+ if target.type in spec.scopes:
301
+ name_node = target.child_by_field_name("name")
302
+ name = _scope_name(_node_text(name_node)) if name_node is not None else ""
303
+ return target, parent, (scope + (name,) if name else scope)
304
+ return node, parent, scope
305
+
306
+ kind = found.kind
307
+ if kind == "function" and parent is not None:
308
+ kind = "method"
309
+ index = self._emit(node, target, found, kind, parent, scope)
310
+ if kind in CONTAINER_KINDS:
311
+ return target, index, scope + (found.name,)
312
+ return None # function bodies are not searched for nested definitions
313
+
314
+ def _unwrap(self, node: Node) -> Node | None:
315
+ spec = self.spec
316
+ for _ in range(4):
317
+ inner = None
318
+ for name in ("declaration", "definition", "value"):
319
+ inner = node.child_by_field_name(name)
320
+ if inner is not None:
321
+ break
322
+ if inner is None:
323
+ candidates = [
324
+ c for c in node.named_children if c.type in spec.definitions or c.type in spec.wrappers
325
+ ]
326
+ if len(candidates) != 1:
327
+ return None
328
+ inner = candidates[0]
329
+ if inner.type not in spec.wrappers:
330
+ return inner
331
+ node = inner
332
+ return None
333
+
334
+ def _body_of(self, node: Node) -> Node | None:
335
+ body = node.child_by_field_name("body")
336
+ if body is not None:
337
+ return body
338
+ for name in ("value", "right"):
339
+ value = node.child_by_field_name(name)
340
+ if value is not None:
341
+ body = value.child_by_field_name("body")
342
+ if body is not None:
343
+ return body
344
+ for child in node.named_children:
345
+ if child.type in _BODY_TYPES:
346
+ return child
347
+ if child.type in ("variable_declarator", "assignment_expression"):
348
+ found = self._body_of(child)
349
+ if found is not None:
350
+ return found
351
+ return None
352
+
353
+ def _classify(self, node: Node, wrapped: bool) -> _Def | None:
354
+ spec = self.spec
355
+ kind = spec.definitions.get(node.type)
356
+ if kind is None:
357
+ if spec.family == "js" and wrapped and node.type in _JS_FUNCTION_VALUES:
358
+ # `export default function () {}` / `export default class {}`
359
+ return _Def("class" if node.type == "class" else "function", "default", body=self._body_of(node))
360
+ return None
361
+
362
+ hook = getattr(self, f"_classify_{spec.family}", None)
363
+ found = hook(node, kind) if hook is not None else NotImplemented
364
+ if found is NotImplemented:
365
+ name = _rightmost_name(node.child_by_field_name("name"))
366
+ if not name:
367
+ return None
368
+ found = _Def(kind, name)
369
+ if found is None:
370
+ return None
371
+ if found.body is None:
372
+ found.body = self._body_of(node)
373
+ if spec.require_body and found.kind in ("function", "method", "constructor") and found.body is None:
374
+ return None
375
+ return found
376
+
377
+ # -- language hooks: return a _Def, None (not a definition) or NotImplemented (default rule)
378
+
379
+ def _classify_js(self, node: Node, kind: str):
380
+ t = node.type
381
+ if t in ("lexical_declaration", "variable_declaration"):
382
+ declarators = [c for c in node.named_children if c.type == "variable_declarator"]
383
+ if len(declarators) != 1:
384
+ return None
385
+ name_node = declarators[0].child_by_field_name("name")
386
+ value = declarators[0].child_by_field_name("value")
387
+ if name_node is None or value is None or name_node.type != "identifier":
388
+ return None
389
+ if value.type not in _JS_FUNCTION_VALUES:
390
+ return None
391
+ return _Def("class" if value.type == "class" else "function", _node_text(name_node))
392
+ if t == "expression_statement":
393
+ expr = node.named_children[0] if node.named_child_count else None
394
+ if expr is None or expr.type != "assignment_expression":
395
+ return None
396
+ left = expr.child_by_field_name("left")
397
+ right = expr.child_by_field_name("right")
398
+ if left is None or right is None or right.type not in _JS_FUNCTION_VALUES:
399
+ return None
400
+ parts = [p for p in _node_text(left).replace(" ", "").split(".") if p != "prototype"]
401
+ if not parts or not all(_IDENT_RE.fullmatch(p) for p in parts):
402
+ return None
403
+ owner = parts[-2] if len(parts) > 1 and parts[-2] not in _JS_NON_OWNERS else None
404
+ return _Def("class" if right.type == "class" else "function", parts[-1], owner)
405
+ if t == "pair":
406
+ key = node.child_by_field_name("key")
407
+ value = node.child_by_field_name("value")
408
+ if key is None or value is None or value.type not in _JS_FUNCTION_VALUES:
409
+ return None
410
+ if node.end_point.row - node.start_point.row < 2:
411
+ return None # one-line callbacks in object literals are noise
412
+ return _Def("function", _node_text(key).strip("'\"`"))
413
+ if t in ("field_definition", "public_field_definition"):
414
+ name_node = node.child_by_field_name("property") or node.child_by_field_name("name")
415
+ value = node.child_by_field_name("value")
416
+ if name_node is None or value is None or value.type not in _JS_FUNCTION_VALUES:
417
+ return None
418
+ return _Def("method", _node_text(name_node))
419
+ if t == "method_definition":
420
+ name_node = node.child_by_field_name("name")
421
+ return _Def("method", collapse_whitespace(_node_text(name_node))) if name_node is not None else None
422
+ return NotImplemented
423
+
424
+ def _classify_go(self, node: Node, kind: str):
425
+ t = node.type
426
+ if t == "method_declaration":
427
+ name = _rightmost_name(node.child_by_field_name("name"))
428
+ if not name:
429
+ return None
430
+ owner = None
431
+ receiver = node.child_by_field_name("receiver")
432
+ if receiver is not None:
433
+ for sub in _iter_tree(receiver):
434
+ if sub.type == "type_identifier":
435
+ owner = _node_text(sub)
436
+ break
437
+ return _Def("method", name, owner)
438
+ if t in ("type_spec", "type_alias"):
439
+ name = _rightmost_name(node.child_by_field_name("name"))
440
+ if not name:
441
+ return None
442
+ type_node = node.child_by_field_name("type")
443
+ type_kind = type_node.type if type_node is not None else ""
444
+ mapped = {"struct_type": "struct", "interface_type": "interface"}.get(type_kind, "type")
445
+ return _Def(mapped, name)
446
+ return NotImplemented
447
+
448
+ def _classify_rust(self, node: Node, kind: str):
449
+ if node.type == "impl_item":
450
+ name = _rightmost_name(node.child_by_field_name("type"))
451
+ return _Def("impl", name, owner=name) if name else None
452
+ return NotImplemented
453
+
454
+ def _classify_c(self, node: Node, kind: str):
455
+ t = node.type
456
+ if t == "function_definition":
457
+ name, owner = _c_declarator_name(node.child_by_field_name("declarator"))
458
+ return _Def("function", name, owner) if name else None
459
+ if t in ("struct_specifier", "union_specifier", "enum_specifier", "class_specifier"):
460
+ if node.child_by_field_name("body") is None:
461
+ return None # a use of the type, not its definition
462
+ name = _rightmost_name(node.child_by_field_name("name"))
463
+ return _Def(kind, name) if name else None
464
+ if t == "type_definition":
465
+ declarators = node.children_by_field_name("declarator")
466
+ name, _ = _c_declarator_name(declarators[-1] if declarators else None)
467
+ if not name:
468
+ return None
469
+ inner = node.child_by_field_name("type")
470
+ inner_kind = "type"
471
+ if inner is not None and inner.child_by_field_name("body") is not None:
472
+ inner_kind = {"enum_specifier": "enum"}.get(inner.type, "struct")
473
+ return _Def(inner_kind, name)
474
+ return NotImplemented
475
+
476
+ def _classify_swift(self, node: Node, kind: str):
477
+ t = node.type
478
+ if t == "class_declaration":
479
+ keyword = next(
480
+ (c.type for c in node.children if c.type in ("class", "struct", "enum", "extension", "actor")),
481
+ "class",
482
+ )
483
+ name = _rightmost_name(node.child_by_field_name("name"))
484
+ if not name:
485
+ return None
486
+ mapped = {"actor": "class"}.get(keyword, keyword)
487
+ return _Def(mapped, name, owner=name if mapped == "extension" else None)
488
+ if t == "init_declaration":
489
+ return _Def("constructor", "init")
490
+ return NotImplemented
491
+
492
+ def _classify_kotlin(self, node: Node, kind: str):
493
+ t = node.type
494
+ if t == "class_declaration":
495
+ name_node = node.child_by_field_name("name") or next(
496
+ (c for c in node.named_children if c.type in ("identifier", "type_identifier", "simple_identifier")),
497
+ None,
498
+ )
499
+ name = _rightmost_name(name_node)
500
+ if not name or name_node is None:
501
+ return None
502
+ header = self.source[node.start_byte : name_node.start_byte].decode("utf-8", "replace").split()
503
+ mapped = "interface" if "interface" in header else "enum" if "enum" in header else "class"
504
+ return _Def(mapped, name)
505
+ if t == "companion_object":
506
+ name = _rightmost_name(node.child_by_field_name("name")) or "Companion"
507
+ return _Def("object", name)
508
+ if t in ("object_declaration", "function_declaration"):
509
+ name_node = node.child_by_field_name("name") or next(
510
+ (c for c in node.named_children if c.type in ("identifier", "type_identifier", "simple_identifier")),
511
+ None,
512
+ )
513
+ name = _rightmost_name(name_node)
514
+ return _Def(kind, name) if name else None
515
+ return NotImplemented
516
+
517
+ # -- chunk construction
518
+
519
+ def _emit(
520
+ self, outer: Node, target: Node, found: _Def, kind: str, parent: int | None, scope: tuple[str, ...]
521
+ ) -> int:
522
+ start_row = outer.start_point.row
523
+ end_row = outer.end_point.row
524
+ if outer.end_point.column == 0 and end_row > start_row:
525
+ end_row -= 1
526
+ lead_row = self._leading_comment_row(start_row)
527
+
528
+ docstring = self._python_docstring(found.body) if self.spec.family == "python" else ""
529
+ if not docstring and lead_row < start_row:
530
+ docstring = _clean_comment(self.lines[lead_row:start_row])
531
+
532
+ names = list(scope)
533
+ if found.owner and kind not in ("impl", "extension") and (not names or names[-1] != found.owner):
534
+ names.append(found.owner)
535
+ names.append(found.name)
536
+
537
+ self.raw.append(
538
+ _Raw(
539
+ kind=kind,
540
+ name=found.name,
541
+ qualified_name=".".join(names),
542
+ start_row=lead_row,
543
+ end_row=end_row,
544
+ def_row=target.start_point.row,
545
+ signature=self._signature(target if outer.type == "decorated_definition" else outer, found.body),
546
+ docstring=docstring,
547
+ parent=parent,
548
+ owner=found.owner,
549
+ bases=self._bases(target) if kind in CONTAINER_KINDS else [],
550
+ )
551
+ )
552
+ return len(self.raw) - 1
553
+
554
+ def _leading_comment_row(self, row: int) -> int:
555
+ """First row of the comment block (and Rust attributes) directly above ``row``."""
556
+ spec = self.spec
557
+ lines = self.lines
558
+ start = row
559
+ index = row - 1
560
+ while index >= 0:
561
+ text = lines[index].strip()
562
+ if not text:
563
+ break
564
+ if spec.block_comments and text.endswith("*/"):
565
+ opener = index
566
+ while opener >= 0 and "/*" not in lines[opener]:
567
+ opener -= 1
568
+ if opener < 0 or not lines[opener].strip().startswith("/*"):
569
+ break
570
+ start = opener
571
+ index = opener - 1
572
+ continue
573
+ if text.startswith(spec.line_comments):
574
+ start = index
575
+ index -= 1
576
+ continue
577
+ break
578
+ return start
579
+
580
+ def _signature(self, target: Node, body: Node | None) -> str:
581
+ if body is not None and body.start_byte > target.start_byte:
582
+ raw = self.source[target.start_byte : body.start_byte].decode("utf-8", "replace")
583
+ else:
584
+ raw = _node_text(target).split("\n", 1)[0]
585
+ # Ruby and friends allow a comment between the header and the body.
586
+ kept: list[str] = []
587
+ for position, line in enumerate(raw.split("\n")):
588
+ if position and line.strip().startswith(self.spec.line_comments):
589
+ break
590
+ kept.append(line)
591
+ signature = collapse_whitespace(" ".join(kept)).rstrip("{:").rstrip()
592
+ return truncate(signature, MAX_SIGNATURE_CHARS)
593
+
594
+ def _python_docstring(self, body: Node | None) -> str:
595
+ if body is None or body.named_child_count == 0:
596
+ return ""
597
+ first = body.named_children[0]
598
+ if first.type != "expression_statement" or first.named_child_count == 0:
599
+ return ""
600
+ string = first.named_children[0]
601
+ if string.type != "string":
602
+ return ""
603
+ parts = [_node_text(c) for c in string.named_children if c.type == "string_content"]
604
+ text = "".join(parts) if parts else _node_text(string).strip("rRbBuUfF").strip("\"'")
605
+ return truncate(inspect.cleandoc(text), MAX_DOCSTRING_CHARS)
606
+
607
+ def _bases(self, node: Node) -> list[str]:
608
+ out: list[str] = []
609
+ for key in self.spec.heritage:
610
+ roots: list[Node] = []
611
+ by_field = node.child_by_field_name(key)
612
+ if by_field is not None:
613
+ roots.append(by_field)
614
+ roots.extend(c for c in node.named_children if c.type == key and c != by_field)
615
+ for root in roots:
616
+ self._collect_heritage(root, out, 0)
617
+ seen: set[str] = set()
618
+ return [b for b in out if not (b in seen or seen.add(b))]
619
+
620
+ def _collect_heritage(self, node: Node, out: list[str], depth: int) -> None:
621
+ kind = node.type
622
+ is_list = kind in _HERITAGE_LISTS or kind.endswith(("_clause", "_list", "_specifier", "_specifiers"))
623
+ if is_list and depth < 5 and node.named_child_count:
624
+ for child in node.named_children:
625
+ if "argument" in child.type and child.type not in _HERITAGE_LISTS:
626
+ continue
627
+ self._collect_heritage(child, out, depth + 1)
628
+ return
629
+ name = _rightmost_name(node)
630
+ if name:
631
+ out.append(name)
632
+
633
+ def _link_owners(self) -> None:
634
+ """Attach Go methods / out-of-line C++ members to their type when it is in this file."""
635
+ containers: dict[str, int] = {}
636
+ for index, raw in enumerate(self.raw):
637
+ if raw.kind in CONTAINER_KINDS and raw.kind not in ("impl", "extension"):
638
+ containers.setdefault(raw.name, index)
639
+ for index, raw in enumerate(self.raw):
640
+ if raw.parent is None and raw.owner and raw.owner in containers and containers[raw.owner] != index:
641
+ raw.parent = containers[raw.owner]
642
+ if raw.kind == "function":
643
+ raw.kind = "method"
644
+
645
+ # -- imports and calls
646
+
647
+ def _collect_references(self, root: Node) -> None:
648
+ spec = self.spec
649
+ handler = getattr(self, f"_import_{spec.family}", None)
650
+ for node in _iter_tree(root):
651
+ if not node.is_named:
652
+ continue # keyword tokens such as `import` share their type name with nodes
653
+ kind = node.type
654
+ if handler is not None and kind in spec.imports and handler(node):
655
+ continue
656
+ if kind in spec.calls:
657
+ name = _call_name(node)
658
+ if name and len(name) > 1:
659
+ self._calls.append((node.start_point.row, name))
660
+
661
+ def _add_import(self, node: Node, module: str, names: tuple[str, ...] = ()) -> bool:
662
+ module = module.strip()
663
+ if not module:
664
+ return False
665
+ self.imports.append(ImportRef(module=module, names=names, line=node.start_point.row + 1))
666
+ return True
667
+
668
+ def _import_python(self, node: Node) -> bool:
669
+ if node.type == "import_statement":
670
+ added = False
671
+ for child in node.children_by_field_name("name"):
672
+ target = child.child_by_field_name("name") if child.type == "aliased_import" else child
673
+ if target is not None:
674
+ added |= self._add_import(node, _node_text(target))
675
+ return added
676
+ module = node.child_by_field_name("module_name")
677
+ if module is None:
678
+ return False
679
+ names: list[str] = []
680
+ for child in node.children_by_field_name("name"):
681
+ target = child.child_by_field_name("name") if child.type == "aliased_import" else child
682
+ if target is not None:
683
+ names.append(_node_text(target))
684
+ return self._add_import(node, _node_text(module), tuple(names))
685
+
686
+ def _import_js(self, node: Node) -> bool:
687
+ if node.type == "call_expression":
688
+ function = node.child_by_field_name("function")
689
+ if function is None or _node_text(function) not in ("require", "import"):
690
+ return False
691
+ arguments = node.child_by_field_name("arguments")
692
+ first = arguments.named_children[0] if arguments is not None and arguments.named_child_count else None
693
+ if first is None or first.type != "string":
694
+ return False
695
+ return self._add_import(node, _node_text(first).strip("'\"`"))
696
+ source = node.child_by_field_name("source")
697
+ if source is None:
698
+ return False
699
+ self._add_import(node, _node_text(source).strip("'\"`"))
700
+ # An `export ... from` still needs its children walked; an import does not.
701
+ return node.type == "import_statement"
702
+
703
+ def _import_go(self, node: Node) -> bool:
704
+ path = node.child_by_field_name("path")
705
+ return self._add_import(node, _node_text(path).strip('"`')) if path is not None else False
706
+
707
+ def _import_rust(self, node: Node) -> bool:
708
+ if node.type == "mod_item":
709
+ if node.child_by_field_name("body") is not None:
710
+ return False
711
+ name = node.child_by_field_name("name")
712
+ return self._add_import(node, f"mod {_node_text(name)}") if name is not None else False
713
+ argument = node.child_by_field_name("argument")
714
+ if argument is None:
715
+ return False
716
+ text = collapse_whitespace(_node_text(argument)).replace(" ", "")
717
+ head, brace, rest = text.partition("{")
718
+ names: tuple[str, ...] = ()
719
+ if brace:
720
+ names = tuple(p.split("::")[0] for p in rest.rstrip("}").split(",") if p and p != "self")
721
+ return self._add_import(node, head.rstrip(":"), names)
722
+
723
+ def _import_java(self, node: Node) -> bool:
724
+ text = collapse_whitespace(_node_text(node)).rstrip(";")
725
+ text = re.sub(r"^import\s+(static\s+)?", "", text)
726
+ return self._add_import(node, text)
727
+
728
+ def _import_kotlin(self, node: Node) -> bool:
729
+ text = collapse_whitespace(_node_text(node))
730
+ text = re.sub(r"^import\s+", "", text)
731
+ text = re.sub(r"\s+as\s+\w+$", "", text)
732
+ return self._add_import(node, text)
733
+
734
+ def _import_c(self, node: Node) -> bool:
735
+ path = node.child_by_field_name("path")
736
+ return self._add_import(node, _node_text(path).strip('"<>')) if path is not None else False
737
+
738
+ def _import_csharp(self, node: Node) -> bool:
739
+ text = collapse_whitespace(_node_text(node)).rstrip(";")
740
+ text = re.sub(r"^(global\s+)?using\s+(static\s+)?", "", text)
741
+ text = text.split("=")[-1].strip()
742
+ return self._add_import(node, text)
743
+
744
+ def _import_ruby(self, node: Node) -> bool:
745
+ method = node.child_by_field_name("method")
746
+ if method is None or node.child_by_field_name("receiver") is not None:
747
+ return False
748
+ name = _node_text(method)
749
+ if name not in ("require", "require_relative", "load"):
750
+ return False
751
+ arguments = node.child_by_field_name("arguments")
752
+ first = arguments.named_children[0] if arguments is not None and arguments.named_child_count else None
753
+ if first is None or first.type != "string":
754
+ return False
755
+ target = _node_text(first).strip("'\"")
756
+ if name == "require_relative" and not target.startswith("."):
757
+ target = "./" + target
758
+ return self._add_import(node, target)
759
+
760
+ def _import_php(self, node: Node) -> bool:
761
+ if node.type == "namespace_use_declaration":
762
+ added = False
763
+ for clause in node.named_children:
764
+ if clause.type == "namespace_use_clause":
765
+ text = re.sub(r"\s+as\s+\w+$", "", collapse_whitespace(_node_text(clause)))
766
+ added |= self._add_import(node, text.lstrip("\\"))
767
+ return added
768
+ first = node.named_children[0] if node.named_child_count else None
769
+ if first is None or first.type not in ("string", "encapsed_string"):
770
+ return False
771
+ return self._add_import(node, _node_text(first).strip("'\""))
772
+
773
+ def _import_swift(self, node: Node) -> bool:
774
+ parts = collapse_whitespace(_node_text(node)).split()
775
+ return self._add_import(node, parts[-1]) if len(parts) > 1 else False
776
+
777
+ def _import_bash(self, node: Node) -> bool:
778
+ name = node.child_by_field_name("name")
779
+ if name is None or _node_text(name) not in ("source", "."):
780
+ return False
781
+ argument = node.child_by_field_name("argument")
782
+ return self._add_import(node, _node_text(argument).strip("'\"")) if argument is not None else False
783
+
784
+ # -- top-level code and finishing
785
+
786
+ def _add_module_chunks(self) -> None:
787
+ lines = self.lines
788
+ covered = bytearray(len(lines))
789
+ for raw in self.raw:
790
+ for row in range(raw.start_row, min(raw.end_row, len(lines) - 1) + 1):
791
+ covered[row] = 1
792
+ row = 0
793
+ total = len(lines)
794
+ while row < total:
795
+ if covered[row]:
796
+ row += 1
797
+ continue
798
+ end = row
799
+ while end + 1 < total and not covered[end + 1]:
800
+ end += 1
801
+ start, stop = _trim_blank(lines, row, end)
802
+ if start <= stop and _is_meaningful(lines[start : stop + 1]):
803
+ for win_start, win_end in _windows(lines, start, stop):
804
+ win_start, win_end = _trim_blank(lines, win_start, win_end)
805
+ if win_start <= win_end and _is_meaningful(lines[win_start : win_end + 1]):
806
+ self.raw.append(
807
+ _Raw(
808
+ kind="module",
809
+ name="<module>",
810
+ qualified_name="<module>",
811
+ start_row=win_start,
812
+ end_row=win_end,
813
+ def_row=win_start,
814
+ signature=truncate(collapse_whitespace(lines[win_start]), MAX_SIGNATURE_CHARS),
815
+ )
816
+ )
817
+ row = end + 1
818
+
819
+ def _assign_calls(self) -> None:
820
+ if not self._calls or not self.raw:
821
+ return
822
+ order = sorted(range(len(self.raw)), key=lambda i: (self.raw[i].start_row, -self.raw[i].end_row))
823
+ for row, name in self._calls:
824
+ best: int | None = None
825
+ for index in order:
826
+ raw = self.raw[index]
827
+ if raw.start_row > row:
828
+ break
829
+ if raw.end_row >= row:
830
+ best = index # later in `order` means more deeply nested
831
+ if best is None:
832
+ continue
833
+ target = self.raw[best]
834
+ if name != target.name and name not in target.calls and len(target.calls) < MAX_CALLS_PER_CHUNK:
835
+ target.calls.append(name)
836
+
837
+ def _skeleton(self, index: int, children: list[int]) -> str:
838
+ """A container's source with each member reduced to its signature."""
839
+ lines = self.lines
840
+ raw = self.raw[index]
841
+ out: list[str] = []
842
+ row = raw.start_row
843
+ for child_index in sorted(children, key=lambda i: self.raw[i].start_row):
844
+ child = self.raw[child_index]
845
+ if child.start_row < row or child.end_row > raw.end_row:
846
+ continue
847
+ out.extend(lines[row : child.start_row])
848
+ def_line = lines[child.def_row] if child.def_row < len(lines) else ""
849
+ indent = def_line[: len(def_line) - len(def_line.lstrip())]
850
+ out.append(f"{indent}{child.signature} ...")
851
+ row = child.end_row + 1
852
+ out.extend(lines[row : raw.end_row + 1])
853
+ return "\n".join(out)
854
+
855
+ def _finish(self) -> list[Chunk]:
856
+ lines = self.lines
857
+ order = sorted(range(len(self.raw)), key=lambda i: (self.raw[i].start_row, -self.raw[i].end_row))
858
+ remap = {old: new for new, old in enumerate(order)}
859
+ children: dict[int, list[int]] = {}
860
+ for index, raw in enumerate(self.raw):
861
+ if raw.parent is not None:
862
+ children.setdefault(raw.parent, []).append(index)
863
+
864
+ chunks: list[Chunk] = []
865
+ for old in order:
866
+ raw = self.raw[old]
867
+ content = "\n".join(lines[raw.start_row : raw.end_row + 1])
868
+ index_text = self._skeleton(old, children[old]) if old in children else content
869
+ chunks.append(
870
+ Chunk(
871
+ kind=raw.kind,
872
+ name=raw.name,
873
+ qualified_name=raw.qualified_name,
874
+ start_line=raw.start_row + 1,
875
+ end_line=raw.end_row + 1,
876
+ content=content,
877
+ signature=raw.signature,
878
+ docstring=raw.docstring,
879
+ index_text=index_text,
880
+ parent=remap[raw.parent] if raw.parent is not None else None,
881
+ owner=raw.owner,
882
+ calls=raw.calls,
883
+ bases=raw.bases,
884
+ )
885
+ )
886
+ return chunks
887
+
888
+
889
+ # --------------------------------------------------------------------------- fallbacks
890
+
891
+
892
+ def _chunk_markdown(text: str) -> list[Chunk]:
893
+ lines = text.split("\n")
894
+ headings: list[tuple[int, int, str]] = []
895
+ in_fence = False
896
+ for row, line in enumerate(lines):
897
+ stripped = line.lstrip()
898
+ if stripped.startswith(("```", "~~~")):
899
+ in_fence = not in_fence
900
+ continue
901
+ if in_fence:
902
+ continue
903
+ match = _MD_HEADING_RE.match(line)
904
+ if match:
905
+ headings.append((row, len(match.group(1)), match.group(2).strip()))
906
+
907
+ chunks: list[Chunk] = []
908
+
909
+ def add(start: int, end: int, title: str, breadcrumb: str, heading: str) -> None:
910
+ start, end = _trim_blank(lines, start, end)
911
+ if start > end:
912
+ return
913
+ content = "\n".join(lines[start : end + 1])
914
+ chunks.append(
915
+ Chunk(
916
+ kind="section",
917
+ name=title,
918
+ qualified_name=breadcrumb,
919
+ start_line=start + 1,
920
+ end_line=end + 1,
921
+ content=content,
922
+ signature=heading,
923
+ index_text=content,
924
+ )
925
+ )
926
+
927
+ first = headings[0][0] if headings else len(lines)
928
+ if first > 0 and any(line.strip() for line in lines[:first]):
929
+ add(0, first - 1, "(preamble)", "(preamble)", "")
930
+
931
+ trail: list[tuple[int, str]] = []
932
+ for position, (row, level, title) in enumerate(headings):
933
+ end = headings[position + 1][0] - 1 if position + 1 < len(headings) else len(lines) - 1
934
+ while trail and trail[-1][0] >= level:
935
+ trail.pop()
936
+ trail.append((level, title))
937
+ if not any(line.strip() for line in lines[row + 1 : end + 1]):
938
+ continue # heading with no body of its own; its title lives on in the breadcrumb
939
+ add(row, end, title, " > ".join(t for _, t in trail), lines[row].strip())
940
+ return chunks
941
+
942
+
943
+ def _chunk_lines(text: str) -> list[Chunk]:
944
+ lines = text.split("\n")
945
+ start, end = _trim_blank(lines, 0, len(lines) - 1)
946
+ chunks: list[Chunk] = []
947
+ if start > end:
948
+ return chunks
949
+ for win_start, win_end in _windows(lines, start, end):
950
+ win_start, win_end = _trim_blank(lines, win_start, win_end)
951
+ if win_start > win_end:
952
+ continue
953
+ content = "\n".join(lines[win_start : win_end + 1])
954
+ label = f"lines {win_start + 1}-{win_end + 1}"
955
+ chunks.append(
956
+ Chunk(
957
+ kind="block",
958
+ name=label,
959
+ qualified_name=label,
960
+ start_line=win_start + 1,
961
+ end_line=win_end + 1,
962
+ content=content,
963
+ signature=truncate(collapse_whitespace(lines[win_start]), MAX_SIGNATURE_CHARS),
964
+ index_text=content,
965
+ )
966
+ )
967
+ return chunks
968
+
969
+
970
+ # --------------------------------------------------------------------------- public API
971
+
972
+
973
+ def parse_source(text: str, spec: LanguageSpec) -> ParsedFile:
974
+ """Chunk ``text`` according to ``spec``. Never raises on malformed source:
975
+ tree-sitter recovers from syntax errors and the result is flagged instead.
976
+ """
977
+ if spec.family == "markdown":
978
+ return ParsedFile(language=spec.name, chunks=_chunk_markdown(text), strategy="markdown")
979
+
980
+ parser = new_parser(spec)
981
+ if parser is None:
982
+ return ParsedFile(language=spec.name, chunks=_chunk_lines(text), strategy="lines")
983
+
984
+ chunker = _TreeChunker(spec, text)
985
+ tree = parser.parse(chunker.source)
986
+ chunks, imports = chunker.run(tree.root_node)
987
+ return ParsedFile(
988
+ language=spec.name,
989
+ chunks=chunks,
990
+ imports=imports,
991
+ has_syntax_errors=tree.root_node.has_error,
992
+ strategy="tree-sitter",
993
+ )