tokensafe 2.6.0 → 2.7.0

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,538 @@
1
+ """
2
+ Optional Tree-sitter Backend for TokenSafe GraphEngine and Skeletonizer.
3
+
4
+ Strictly optional: all imports of `tree_sitter` and `tree_sitter_*` grammars are
5
+ lazy and fail-safe. When unavailable (or disabled via TOKENSAFE_TREESITTER=0),
6
+ callers fall back seamlessly to TokenSafe's zero-dependency stdlib AST/BraceLexer
7
+ engines.
8
+ """
9
+
10
+ import importlib
11
+ import os
12
+ import re
13
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
14
+
15
+ # Extension -> (module_name, loader_attr)
16
+ _LANGUAGE_SPECS: Dict[str, Tuple[str, str]] = {
17
+ ".py": ("tree_sitter_python", "language"),
18
+ ".js": ("tree_sitter_javascript", "language"),
19
+ ".jsx": ("tree_sitter_javascript", "language"),
20
+ ".mjs": ("tree_sitter_javascript", "language"),
21
+ ".cjs": ("tree_sitter_javascript", "language"),
22
+ ".ts": ("tree_sitter_typescript", "language_typescript"),
23
+ ".tsx": ("tree_sitter_typescript", "language_tsx"),
24
+ ".go": ("tree_sitter_go", "language"),
25
+ ".rs": ("tree_sitter_rust", "language"),
26
+ ".java": ("tree_sitter_java", "language"),
27
+ ".cs": ("tree_sitter_c_sharp", "language"),
28
+ ".c": ("tree_sitter_c", "language"),
29
+ ".h": ("tree_sitter_c", "language"),
30
+ ".cpp": ("tree_sitter_cpp", "language"),
31
+ ".cc": ("tree_sitter_cpp", "language"),
32
+ ".cxx": ("tree_sitter_cpp", "language"),
33
+ ".hpp": ("tree_sitter_cpp", "language"),
34
+ ".php": ("tree_sitter_php", "language_php"),
35
+ ".kt": ("tree_sitter_kotlin", "language"),
36
+ ".kts": ("tree_sitter_kotlin", "language"),
37
+ ".swift": ("tree_sitter_swift", "language"),
38
+ }
39
+
40
+ _CONTAINER_NODE_TYPES = {
41
+ "class_definition",
42
+ "class_declaration",
43
+ "class_specifier",
44
+ "struct_item",
45
+ "struct_specifier",
46
+ "struct_declaration",
47
+ "impl_item",
48
+ "trait_item",
49
+ "trait_declaration",
50
+ "interface_declaration",
51
+ "record_declaration",
52
+ "enum_declaration",
53
+ "enum_item",
54
+ "protocol_declaration",
55
+ "extension_declaration",
56
+ "namespace_definition",
57
+ "namespace_declaration",
58
+ }
59
+
60
+ _FUNC_NODE_TYPES = {
61
+ "function_definition",
62
+ "function_declaration",
63
+ "function_item",
64
+ "method_definition",
65
+ "method_declaration",
66
+ "constructor_declaration",
67
+ "destructor_declaration",
68
+ "arrow_function",
69
+ "function_expression",
70
+ "function",
71
+ "operator_declaration",
72
+ "init_declaration",
73
+ "deinit_declaration",
74
+ "secondary_constructor",
75
+ "anonymous_function",
76
+ }
77
+
78
+ _IMPORT_NODE_TYPES = {
79
+ "import_statement",
80
+ "import_from_statement",
81
+ "import_declaration",
82
+ "use_declaration",
83
+ "using_directive",
84
+ "preproc_include",
85
+ "namespace_use_declaration",
86
+ "import",
87
+ }
88
+
89
+ _CALL_NODE_TYPES = {
90
+ "call",
91
+ "call_expression",
92
+ "method_invocation",
93
+ "invocation_expression",
94
+ "function_call_expression",
95
+ "member_call_expression",
96
+ "scoped_call_expression",
97
+ "macro_invocation",
98
+ "object_creation_expression",
99
+ "new_expression",
100
+ }
101
+
102
+ _SKIP_CALL_NAMES = {
103
+ "if", "for", "while", "switch", "catch", "return", "throw", "sizeof",
104
+ "typeof", "instanceof", "new", "delete", "await", "yield", "import",
105
+ "require", "print", "len", "str", "int", "float", "bool", "list",
106
+ "dict", "set", "tuple", "div", "span", "button", "input", "label",
107
+ "form", "svg", "path", "true", "false", "null", "undefined", "None",
108
+ "True", "False",
109
+ }
110
+
111
+
112
+ class TreeSitterBackend:
113
+ """Lazy, cached wrapper around optional `tree_sitter` language parsers."""
114
+
115
+ _ts_mod: Any = None
116
+ _ts_checked: bool = False
117
+ _parsers: Dict[str, Any] = {}
118
+ _unavailable_exts: Set[str] = set()
119
+
120
+ @classmethod
121
+ def is_enabled(cls) -> bool:
122
+ flag = os.environ.get("TOKENSAFE_TREESITTER", "auto").strip().lower()
123
+ return flag not in ("0", "false", "off", "no", "disabled")
124
+
125
+ @classmethod
126
+ def is_available(cls) -> bool:
127
+ if not cls.is_enabled():
128
+ return False
129
+ if not cls._ts_checked:
130
+ cls._ts_checked = True
131
+ try:
132
+ cls._ts_mod = importlib.import_module("tree_sitter")
133
+ except Exception:
134
+ cls._ts_mod = None
135
+ return cls._ts_mod is not None
136
+
137
+ @classmethod
138
+ def get_parser(cls, ext: str) -> Optional[Any]:
139
+ ext = ext.lower()
140
+ if not ext.startswith("."):
141
+ ext = f".{ext}" if ext else ""
142
+ if not cls.is_available() or ext not in _LANGUAGE_SPECS or ext in cls._unavailable_exts:
143
+ return None
144
+ if ext in cls._parsers:
145
+ return cls._parsers[ext]
146
+
147
+ mod_name, fn_name = _LANGUAGE_SPECS[ext]
148
+ try:
149
+ lang_mod = importlib.import_module(mod_name)
150
+ lang_ptr = getattr(lang_mod, fn_name)()
151
+ lang_obj = cls._ts_mod.Language(lang_ptr)
152
+ parser = cls._ts_mod.Parser(lang_obj)
153
+ cls._parsers[ext] = parser
154
+ return parser
155
+ except Exception:
156
+ cls._unavailable_exts.add(ext)
157
+ return None
158
+
159
+ @classmethod
160
+ def supports_ext(cls, ext: str) -> bool:
161
+ return cls.get_parser(ext) is not None
162
+
163
+ @classmethod
164
+ def supported_languages(cls) -> Set[str]:
165
+ if not cls.is_available():
166
+ return set()
167
+ return {ext for ext in _LANGUAGE_SPECS if cls.get_parser(ext) is not None}
168
+
169
+ @staticmethod
170
+ def _node_text(node: Any, code_bytes: bytes) -> str:
171
+ return code_bytes[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
172
+
173
+ @classmethod
174
+ def _find_identifier_in_declarator(cls, node: Any, code_bytes: bytes) -> Optional[str]:
175
+ if node is None:
176
+ return None
177
+ if node.type in (
178
+ "identifier", "type_identifier", "field_identifier",
179
+ "property_identifier", "simple_identifier", "name",
180
+ ):
181
+ return cls._node_text(node, code_bytes)
182
+ if node.type == "qualified_identifier":
183
+ # e.g. C++ ClassName::method -> take last identifier or full
184
+ parts = [cls._find_identifier_in_declarator(c, code_bytes) for c in node.children]
185
+ parts = [p for p in parts if p]
186
+ return parts[-1] if parts else None
187
+ if node.type in ("function_declarator", "pointer_declarator", "reference_declarator"):
188
+ decl = node.child_by_field_name("declarator")
189
+ if decl is not None:
190
+ res = cls._find_identifier_in_declarator(decl, code_bytes)
191
+ if res:
192
+ return res
193
+ for child in node.children:
194
+ if child.type in (
195
+ "identifier", "type_identifier", "field_identifier",
196
+ "property_identifier", "simple_identifier", "name",
197
+ "function_declarator", "qualified_identifier",
198
+ ):
199
+ res = cls._find_identifier_in_declarator(child, code_bytes)
200
+ if res:
201
+ return res
202
+ return None
203
+
204
+ @classmethod
205
+ def _extract_symbol_name(cls, node: Any, code_bytes: bytes) -> Optional[str]:
206
+ # Rust impl Foo / impl Trait for Foo
207
+ if node.type == "impl_item":
208
+ type_node = node.child_by_field_name("type")
209
+ if type_node is not None:
210
+ return cls._find_identifier_in_declarator(type_node, code_bytes)
211
+ for c in node.children:
212
+ if c.type in ("type_identifier", "generic_type"):
213
+ return cls._find_identifier_in_declarator(c, code_bytes)
214
+
215
+ # Go type_declaration -> type_spec
216
+ if node.type == "type_declaration":
217
+ for c in node.children:
218
+ if c.type == "type_spec":
219
+ name_n = c.child_by_field_name("name")
220
+ if name_n is not None:
221
+ return cls._node_text(name_n, code_bytes)
222
+
223
+ # Arrow/function assigned to variable_declarator: const Foo = (...) => {}
224
+ if node.type in ("arrow_function", "function_expression", "function"):
225
+ parent = node.parent
226
+ while parent is not None and parent.type in ("call_expression", "arguments", "parenthesized_expression"):
227
+ # Handle React.memo((...) => ...) or useCallback((...) => ...)
228
+ parent = parent.parent
229
+ if parent is not None and parent.type == "variable_declarator":
230
+ name_n = parent.child_by_field_name("name")
231
+ if name_n is not None:
232
+ return cls._node_text(name_n, code_bytes)
233
+ if parent is not None and parent.type == "pair":
234
+ key_n = parent.child_by_field_name("key")
235
+ if key_n is not None:
236
+ return cls._node_text(key_n, code_bytes).strip("\"'")
237
+
238
+ # Standard named field (`name`)
239
+ name_node = node.child_by_field_name("name")
240
+ if name_node is not None:
241
+ return cls._find_identifier_in_declarator(name_node, code_bytes)
242
+
243
+ # C/C++ declarator
244
+ decl_node = node.child_by_field_name("declarator")
245
+ if decl_node is not None:
246
+ return cls._find_identifier_in_declarator(decl_node, code_bytes)
247
+
248
+ # Fallback: first direct identifier/name child
249
+ for child in node.children:
250
+ if child.type in (
251
+ "identifier", "type_identifier", "field_identifier",
252
+ "property_identifier", "simple_identifier", "name",
253
+ ):
254
+ return cls._node_text(child, code_bytes)
255
+ return None
256
+
257
+ @classmethod
258
+ def _find_body_node(cls, node: Any) -> Optional[Any]:
259
+ body = node.child_by_field_name("body")
260
+ if body is not None:
261
+ return body
262
+ for child in node.children:
263
+ if child.type in (
264
+ "block", "statement_block", "compound_statement",
265
+ "function_body", "declaration_list",
266
+ ):
267
+ return child
268
+ return None
269
+
270
+ @classmethod
271
+ def _extract_call_name(cls, node: Any, code_bytes: bytes) -> Optional[str]:
272
+ if node.type == "method_invocation":
273
+ name_n = node.child_by_field_name("name")
274
+ if name_n is not None:
275
+ return cls._node_text(name_n, code_bytes)
276
+ if node.type == "member_call_expression":
277
+ name_n = node.child_by_field_name("name")
278
+ if name_n is not None:
279
+ return cls._node_text(name_n, code_bytes)
280
+
281
+ fn_node = node.child_by_field_name("function") or node.child_by_field_name("name")
282
+ if fn_node is None and node.children:
283
+ fn_node = node.children[0]
284
+ if fn_node is None:
285
+ return None
286
+
287
+ text = cls._node_text(fn_node, code_bytes).strip()
288
+ # Strip trailing generics/arguments and take leaf identifier after ., ::, ->
289
+ text = re.sub(r"<[^>]*>$", "", text)
290
+ leaf = re.split(r"(?:\.|::|->|\?\.)", text)[-1].strip()
291
+ if re.match(r"^[A-Za-z_$][A-Za-z0-9_$]*$", leaf) and leaf not in _SKIP_CALL_NAMES:
292
+ return leaf
293
+ return None
294
+
295
+ @classmethod
296
+ def _extract_imports_from_node(cls, node: Any, code_bytes: bytes, ext: str) -> Tuple[List[str], List[str]]:
297
+ mods: List[str] = []
298
+ syms: List[str] = []
299
+ raw = cls._node_text(node, code_bytes).strip()
300
+
301
+ if ext == ".py":
302
+ if node.type == "import_statement":
303
+ for c in node.children:
304
+ if c.type in ("dotted_name", "aliased_import"):
305
+ t = cls._node_text(c, code_bytes).split(" as ")[0].strip()
306
+ if t:
307
+ mods.append(t)
308
+ elif node.type == "import_from_statement":
309
+ m = re.match(r"^from\s+([A-Za-z0-9_.]+)\s+import\s+(.+)$", raw, re.DOTALL)
310
+ if m:
311
+ mods.append(m.group(1).strip())
312
+ for item in m.group(2).replace("(", "").replace(")", "").split(","):
313
+ sym = item.strip().split(" as ")[0].strip()
314
+ if sym and sym != "*":
315
+ syms.append(sym)
316
+ elif ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
317
+ for m in re.finditer(r"""['"]([^'"]+)['"]""", raw):
318
+ mods.append(m.group(1))
319
+ m_named = re.search(r"\{([^}]+)\}", raw)
320
+ if m_named:
321
+ for item in m_named.group(1).split(","):
322
+ s = item.strip().split(" as ")[0].strip()
323
+ if s:
324
+ syms.append(s)
325
+ elif ext == ".go":
326
+ for m in re.finditer(r'"([^"]+)"', raw):
327
+ mods.append(m.group(1))
328
+ elif ext in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp"):
329
+ m = re.search(r'[<"]([^>"]+)[>"]', raw)
330
+ if m:
331
+ mods.append(m.group(1))
332
+ else:
333
+ # Rust use, Java/Kotlin import, C# using, PHP use, Swift import
334
+ cleaned = re.sub(r"^(?:pub\s+)?(?:use|import|using|namespace)\s+", "", raw)
335
+ cleaned = cleaned.rstrip(";").strip()
336
+ if cleaned:
337
+ mods.append(cleaned)
338
+ return mods, syms
339
+
340
+ @classmethod
341
+ def extract_graph_data(cls, code: str, ext: str, rel_path: str) -> Optional[Dict[str, Any]]:
342
+ parser = cls.get_parser(ext)
343
+ if parser is None:
344
+ return None
345
+
346
+ code_bytes = code.encode("utf-8", errors="replace")
347
+ try:
348
+ tree = parser.parse(code_bytes)
349
+ except Exception:
350
+ return None
351
+
352
+ lines = code.splitlines()
353
+ imports: List[str] = []
354
+ imported_symbols: List[str] = []
355
+ symbols: List[Dict[str, Any]] = []
356
+ seen_keys: Set[str] = set()
357
+ calls: List[Tuple[str, str]] = []
358
+
359
+ def walk(node: Any, container_stack: List[str], current_fn_key: Optional[str]):
360
+ ntype = node.type
361
+
362
+ if ntype in _IMPORT_NODE_TYPES:
363
+ mods, syms = cls._extract_imports_from_node(node, code_bytes, ext)
364
+ imports.extend(mods)
365
+ imported_symbols.extend(syms)
366
+ return
367
+
368
+ # Go `type Foo struct { ... }` / `type Foo interface { ... }`
369
+ is_go_type = (
370
+ ext == ".go"
371
+ and ntype == "type_declaration"
372
+ and any(c.type == "type_spec" for c in node.children)
373
+ )
374
+
375
+ if ntype in _CONTAINER_NODE_TYPES or is_go_type:
376
+ name = cls._extract_symbol_name(node, code_bytes)
377
+ if name:
378
+ qual = "::".join(container_stack + [name]) if container_stack else name
379
+ sym_key = f"{rel_path}::{qual}"
380
+ if sym_key not in seen_keys:
381
+ seen_keys.add(sym_key)
382
+ l_start = node.start_point[0] + 1
383
+ l_end = max(l_start, node.end_point[0] + 1)
384
+ sig = lines[l_start - 1].strip() if 0 < l_start <= len(lines) else name
385
+ symbols.append({
386
+ "sym_key": sym_key,
387
+ "name": name,
388
+ "qualified_name": qual,
389
+ "kind": "class",
390
+ "line_start": l_start,
391
+ "line_end": l_end,
392
+ "signature": sig,
393
+ })
394
+ next_stack = container_stack + [name]
395
+ else:
396
+ next_stack = container_stack
397
+
398
+ for child in node.children:
399
+ walk(child, next_stack, current_fn_key)
400
+ return
401
+
402
+ if ntype in _FUNC_NODE_TYPES:
403
+ name = cls._extract_symbol_name(node, code_bytes)
404
+ next_fn_key = current_fn_key
405
+ if name:
406
+ qual = "::".join(container_stack + [name]) if container_stack else name
407
+ sym_key = f"{rel_path}::{qual}"
408
+ if sym_key not in seen_keys:
409
+ seen_keys.add(sym_key)
410
+ l_start = node.start_point[0] + 1
411
+ l_end = max(l_start, node.end_point[0] + 1)
412
+ # Use the variable declaration line for arrow functions if applicable
413
+ sig_line = l_start
414
+ if ntype in ("arrow_function", "function_expression") and node.parent is not None:
415
+ sig_line = min(l_start, node.parent.start_point[0] + 1)
416
+ sig = lines[sig_line - 1].strip() if 0 < sig_line <= len(lines) else name
417
+ symbols.append({
418
+ "sym_key": sym_key,
419
+ "name": name,
420
+ "qualified_name": qual,
421
+ "kind": "function",
422
+ "line_start": l_start,
423
+ "line_end": l_end,
424
+ "signature": sig,
425
+ })
426
+ next_fn_key = sym_key
427
+
428
+ for child in node.children:
429
+ walk(child, container_stack, next_fn_key)
430
+ return
431
+
432
+ if ntype in _CALL_NODE_TYPES and current_fn_key:
433
+ callee = cls._extract_call_name(node, code_bytes)
434
+ if callee:
435
+ calls.append((current_fn_key, callee))
436
+
437
+ for child in node.children:
438
+ walk(child, container_stack, current_fn_key)
439
+
440
+ walk(tree.root_node, [], None)
441
+ return {
442
+ "imports": imports,
443
+ "imported_symbols": imported_symbols,
444
+ "symbols": symbols,
445
+ "calls": calls,
446
+ }
447
+
448
+ @classmethod
449
+ def skeletonize_braces(
450
+ cls,
451
+ code: str,
452
+ ext: str,
453
+ keep_symbols: Optional[Set[str]] = None,
454
+ ) -> Optional[str]:
455
+ """
456
+ Tree-sitter brace-language skeletonizer: replaces non-kept function/method
457
+ bodies with `{ /* ... */ }` while preserving multi-line signatures,
458
+ Allman-style braces, classes/structs/impls, and control-flow blocks.
459
+ """
460
+ ext = ext.lower()
461
+ if not ext.startswith("."):
462
+ ext = f".{ext}" if ext else ""
463
+ if ext == ".py":
464
+ return None
465
+ parser = cls.get_parser(ext)
466
+ if parser is None:
467
+ return None
468
+
469
+ code_bytes = code.encode("utf-8", errors="replace")
470
+ try:
471
+ tree = parser.parse(code_bytes)
472
+ except Exception:
473
+ return None
474
+
475
+ replacements: List[Tuple[int, int, bytes]] = []
476
+ comment_token = "# ..." if ext == ".py" else "/* ... */"
477
+ folded_body = f"{{ {comment_token} }}".encode("utf-8")
478
+
479
+ def walk(node: Any, container_stack: List[str], in_kept_scope: bool = False):
480
+ ntype = node.type
481
+
482
+ if ntype in _CONTAINER_NODE_TYPES:
483
+ cname = cls._extract_symbol_name(node, code_bytes)
484
+ next_stack = container_stack + [cname] if cname else container_stack
485
+ for child in node.children:
486
+ walk(child, next_stack, in_kept_scope)
487
+ return
488
+
489
+ if ntype in _FUNC_NODE_TYPES:
490
+ name = cls._extract_symbol_name(node, code_bytes)
491
+ qual_dot = ".".join(container_stack + [name]) if (container_stack and name) else name
492
+ qual_col = "::".join(container_stack + [name]) if (container_stack and name) else name
493
+ body = cls._find_body_node(node)
494
+ is_target_kept = (
495
+ keep_symbols is not None
496
+ and (
497
+ (name and name in keep_symbols)
498
+ or (qual_dot and qual_dot in keep_symbols)
499
+ or (qual_col and qual_col in keep_symbols)
500
+ )
501
+ )
502
+ if body is not None:
503
+ body_bytes = code_bytes[body.start_byte:body.end_byte]
504
+ if body_bytes.startswith(b"{") and body_bytes.endswith(b"}"):
505
+ if is_target_kept:
506
+ for child in node.children:
507
+ walk(child, container_stack, True)
508
+ return
509
+ # Inside a kept function, leave unnamed inline callbacks intact
510
+ if in_kept_scope and not name:
511
+ for child in node.children:
512
+ walk(child, container_stack, True)
513
+ return
514
+ replacements.append((body.start_byte, body.end_byte, folded_body))
515
+ return
516
+ for child in node.children:
517
+ walk(child, container_stack, in_kept_scope or is_target_kept)
518
+ return
519
+
520
+ for child in node.children:
521
+ walk(child, container_stack, in_kept_scope)
522
+
523
+ walk(tree.root_node, [], False)
524
+ if not replacements:
525
+ return code
526
+
527
+ # Sort and deduplicate non-overlapping spans
528
+ replacements.sort(key=lambda r: (r[0], -r[1]))
529
+ out_parts: List[bytes] = []
530
+ cursor = 0
531
+ for start, end, rep in replacements:
532
+ if start < cursor:
533
+ continue
534
+ out_parts.append(code_bytes[cursor:start])
535
+ out_parts.append(rep)
536
+ cursor = end
537
+ out_parts.append(code_bytes[cursor:])
538
+ return b"".join(out_parts).decode("utf-8", errors="replace")
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.6.0"
19
+ CURRENT_VERSION = "2.7.0"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage