tokensafe 1.4.1 → 1.4.2
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.
- package/README.md +23 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/src/graph_engine.py +22 -33
- package/src/mcp_server.py +1 -1
- package/src/skeletonizer.py +253 -27
package/README.md
CHANGED
|
@@ -118,6 +118,29 @@ Turns out, there's a simple reason for this:
|
|
|
118
118
|
|
|
119
119
|
---
|
|
120
120
|
|
|
121
|
+
## 🌐 Polyglot Zero-Loss AST Engine (10+ Languages)
|
|
122
|
+
|
|
123
|
+
TokenSafe is built from the ground up to support modern polyglot monorepos. Its zero-LLM deterministic AST state machine folds non-target function bodies in **< 30ms** with zero external dependencies, while preserving active symbols and 1-hop dependencies with full executable bodies.
|
|
124
|
+
|
|
125
|
+
### Supported Language Matrix
|
|
126
|
+
|
|
127
|
+
| Language / Framework | File Extensions | Preserved Structures | Folding Mechanism |
|
|
128
|
+
|---|---|---|---|
|
|
129
|
+
| **TypeScript / React** | `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs` | React components (`React.FC`, `memo`, `forwardRef`, multi-line destructuring), arrow functions, hooks, classes, interfaces | Target & 1-hop bodies kept full; non-target bodies folded into `{ /* ... */ };` |
|
|
130
|
+
| **Python** | `.py` | Classes, typed signatures, docstrings, decorators, `async def` | Native `ast.parse` tree pruning with `...` body replacement |
|
|
131
|
+
| **Go** | `.go` | Struct declarations, interfaces, methods `func (r *Recv) Method(...)`, generics `func Map[T any]` | Non-target functions folded; struct layouts and `select` blocks preserved |
|
|
132
|
+
| **Rust** | `.rs` | `struct`, `enum`, `impl` blocks, `trait` blocks, `pub(crate) async fn`, `const fn` | `impl` containers stay open; method bodies folded into `{ /* ... */ }` |
|
|
133
|
+
| **Java & C#** | `.java`, `.cs` | Classes, records, methods with access modifiers (`public`, `protected`, `static`, `async`, `override`), generic return types (`Task<T>`, `List<E>`), `throws` | Method bodies folded; classes and interfaces remain structural |
|
|
134
|
+
| **C & C++** | `.c`, `.cpp`, `.cc`, `.cxx`, `.h`, `.hpp` | Classes, structs, namespaces, scoped methods `ClassName::method`, `const`, `noexcept`, `override`, destructors | Functions folded; namespace and class hierarchies preserved |
|
|
135
|
+
| **PHP, Kotlin, Swift** | `.php`, `.kt`, `.kts`, `.swift` | Classes, `function`, `fun`, `func` declarations with visibility modifiers | Function bodies folded into `{ /* ... */ }` |
|
|
136
|
+
|
|
137
|
+
### Key Engine Guarantees:
|
|
138
|
+
- **Graph-Guided Neighborhood Slicing**: When your AI agent inspects a function or component (via `tokensafe:smart_read_file(path, symbol="Target")`), TokenSafe automatically keeps the full implementation of the target **and its 1-hop callees/callers**, while collapsing all unrelated code.
|
|
139
|
+
- **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked in a dedicated token lexer (`BraceLexer`), guaranteeing zero bracket desynchronization.
|
|
140
|
+
- **Control-Flow Statement Immunity**: Statements like `if (...)`, `catch (err) {`, `for (...)`, and `while (...)` are strictly protected and never corrupted into placeholders.
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
121
144
|
## 🛡️ The Hidden Context Killer: MCP Tool Schema Bloat
|
|
122
145
|
|
|
123
146
|
Why do AI coding agent quotas (like Antigravity's **5-Hour Limit** or Claude/OpenAI monthly token budgets) evaporate after just a few prompts?
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.2",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/src/graph_engine.py
CHANGED
|
@@ -222,13 +222,18 @@ class CodeGraph:
|
|
|
222
222
|
self.add_edge(file_node, f"mod:{target_mod}")
|
|
223
223
|
|
|
224
224
|
# Functions & Methods
|
|
225
|
-
fn_pattern = re.compile(
|
|
225
|
+
fn_pattern = re.compile(
|
|
226
|
+
r"""(?:export\s+(?:default\s+)?)?(?:async\s+)?(?:function\s*\*?\s*([a-zA-Z0-9_$]+)|(?:class|interface|struct|impl|trait)\s+([a-zA-Z0-9_$]+)|func\s+(?:\(.*?\)\s+)?([a-zA-Z0-9_]+)|(?:const|let|var)\s+([a-zA-Z0-9_$]+)(?:\s*:\s*[^=]+)?\s*=\s*(?:async\s*)?(?:React\.(?:memo|forwardRef)\s*\()?(?:useCallback\s*\()?\s*\(?)"""
|
|
227
|
+
)
|
|
228
|
+
call_pattern = re.compile(r"""(?:<|\b)([a-zA-Z0-9_$]{3,})\s*(?:\(|>|(?:\s+[a-zA-Z0-9_$-]+))""")
|
|
229
|
+
current_sym = None
|
|
230
|
+
|
|
226
231
|
for idx, line in enumerate(lines, 1):
|
|
227
232
|
match = fn_pattern.search(line)
|
|
228
233
|
if match:
|
|
229
234
|
name = match.group(1) or match.group(2) or match.group(3) or match.group(4)
|
|
230
|
-
if name:
|
|
231
|
-
kind = "class" if
|
|
235
|
+
if name and name not in {"if", "for", "while", "switch", "catch", "return", "import", "export"}:
|
|
236
|
+
kind = "class" if any(w in line for w in ("class", "interface", "struct", "impl")) else "function"
|
|
232
237
|
sym_key = f"{rel_path}::{name}"
|
|
233
238
|
symbol = CodeSymbol(
|
|
234
239
|
name=name,
|
|
@@ -241,6 +246,12 @@ class CodeGraph:
|
|
|
241
246
|
self.symbols[sym_key] = symbol
|
|
242
247
|
self.file_symbols[rel_path].append(sym_key)
|
|
243
248
|
self.add_edge(file_node, sym_key)
|
|
249
|
+
current_sym = sym_key
|
|
250
|
+
elif current_sym:
|
|
251
|
+
for cm in call_pattern.finditer(line):
|
|
252
|
+
callee = cm.group(1)
|
|
253
|
+
if callee not in {"div", "span", "button", "input", "label", "form", "svg", "path", "true", "false", "null", "undefined"}:
|
|
254
|
+
self.add_edge(current_sym, f"call:{callee}")
|
|
244
255
|
|
|
245
256
|
# -------------------------------------------------------------
|
|
246
257
|
# 1. God Nodes Analysis (Degree Centrality)
|
|
@@ -321,41 +332,19 @@ class CodeGraph:
|
|
|
321
332
|
except OSError:
|
|
322
333
|
return ""
|
|
323
334
|
|
|
324
|
-
|
|
325
|
-
# Fall back to standard skeletonization
|
|
326
|
-
from src.skeletonizer import Skeletonizer
|
|
327
|
-
_, ext = os.path.splitext(full_path)
|
|
328
|
-
return Skeletonizer.skeletonize_code(code, ext)
|
|
329
|
-
|
|
335
|
+
from src.skeletonizer import Skeletonizer
|
|
330
336
|
_, ext = os.path.splitext(full_path)
|
|
331
337
|
ext = ext.lower()
|
|
332
338
|
|
|
333
|
-
if
|
|
334
|
-
# For brace-based languages, fallback to standard skeleton
|
|
335
|
-
from src.skeletonizer import Skeletonizer
|
|
339
|
+
if not target_symbol:
|
|
336
340
|
return Skeletonizer.skeletonize_code(code, ext)
|
|
337
341
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
keep_full_names.add(k.split("::")[-1])
|
|
345
|
-
|
|
346
|
-
for node in ast.walk(tree):
|
|
347
|
-
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
348
|
-
if node.name not in keep_full_names:
|
|
349
|
-
doc = ast.get_docstring(node)
|
|
350
|
-
new_body = []
|
|
351
|
-
if doc:
|
|
352
|
-
new_body.append(ast.Expr(value=ast.Constant(value=doc)))
|
|
353
|
-
new_body.append(ast.Expr(value=ast.Constant(value=Ellipsis)))
|
|
354
|
-
node.body = new_body
|
|
355
|
-
|
|
356
|
-
return ast.unparse(tree)
|
|
357
|
-
except Exception:
|
|
358
|
-
return code
|
|
342
|
+
neighborhood = self.get_neighborhood(target_symbol)
|
|
343
|
+
keep_full_names = {target_symbol}
|
|
344
|
+
for k in neighborhood.get("one_hop", set()):
|
|
345
|
+
keep_full_names.add(k.split("::")[-1])
|
|
346
|
+
|
|
347
|
+
return Skeletonizer.skeletonize_code(code, ext, keep_symbols=keep_full_names)
|
|
359
348
|
|
|
360
349
|
# -------------------------------------------------------------
|
|
361
350
|
# 3. API Surface Generator (tokensafe-out/API_SURFACE.md)
|
package/src/mcp_server.py
CHANGED
package/src/skeletonizer.py
CHANGED
|
@@ -9,31 +9,113 @@ import re
|
|
|
9
9
|
import ast
|
|
10
10
|
import hashlib
|
|
11
11
|
import json
|
|
12
|
-
from typing import Optional, Tuple
|
|
12
|
+
from typing import Optional, Tuple, Set
|
|
13
13
|
from src.tokenizer import count_tokens
|
|
14
14
|
|
|
15
|
+
CONTROL_KEYWORDS = {
|
|
16
|
+
'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'default',
|
|
17
|
+
'try', 'catch', 'finally', 'with', 'select', 'lock', 'using',
|
|
18
|
+
'fixed', 'unsafe', 'synchronized', 'struct', 'enum', 'interface',
|
|
19
|
+
'type', 'namespace', 'class', 'trait', 'impl', 'package', 'module',
|
|
20
|
+
'return', 'throw', 'yield', 'await', 'import', 'export', 'record'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
# 1. Standard function declarations (JS/TS/PHP/Swift/Kotlin)
|
|
24
|
+
FN_DECL_REGEX = re.compile(
|
|
25
|
+
r'^(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\s*\*?|fun)\s+([a-zA-Z0-9_$]+)?\s*(?:<[^>]+>)?\s*\('
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# 2. Go func: func Foo(...) or func (r *Recv) Foo(...)
|
|
29
|
+
GO_FN_REGEX = re.compile(
|
|
30
|
+
r'^func\s+(?:\([^)]+\)\s+)?([a-zA-Z0-9_]+)\s*(?:\[[^\]]+\])?\s*\('
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# 3. Rust fn: fn foo(...) or pub async fn foo(...)
|
|
34
|
+
RUST_FN_REGEX = re.compile(
|
|
35
|
+
r'^(?:pub(?:\([^)]+\))?\s+)?(?:async\s+)?(?:const\s+)?(?:unsafe\s+)?fn\s+([a-zA-Z0-9_]+)\s*(?:<[^>]+>)?\s*\('
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
# 4. Arrow function / React component: const Foo = (...) => { or export const Foo: React.FC<Props> = (...) => {
|
|
39
|
+
ARROW_FN_REGEX = re.compile(
|
|
40
|
+
r'^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)(?:\s*:\s*[^=]+)?\s*=\s*(?:async\s*)?(?:React\.(?:memo|forwardRef)\s*\()?(?:useCallback\s*\()?(?:(?:\([^)]*\)|[a-zA-Z0-9_$]+)\s*=>|function\b)'
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# 4b. Multi-line arrow function start: const Foo: React.FC<Props> = (
|
|
44
|
+
ARROW_MULTILINE_START = re.compile(
|
|
45
|
+
r'^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)(?:\s*:\s*[^=]+)?\s*=\s*(?:async\s*)?(?:React\.(?:memo|forwardRef)\s*\()?(?:useCallback\s*\()?\s*\('
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# 5. Method definition (Java, C#, C++, TS, PHP)
|
|
49
|
+
METHOD_REGEX = re.compile(
|
|
50
|
+
r'^(?:(?:public|private|protected|static|final|native|synchronized|abstract|async|override|virtual|inline|explicit|const|get|set)\s+)*'
|
|
51
|
+
r'(?:[a-zA-Z0-9_<>\[\],.?*&:]+\s+)*'
|
|
52
|
+
r'([a-zA-Z0-9_$:~]+)\s*(?:<[^>]+>)?\s*\([^)]*\)\s*'
|
|
53
|
+
r'(?:const\s+|override\s+|final\s+|noexcept\s+|throws\s+[^{]+|->\s*[^{]+|:\s*[^{]+)*\{'
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
class BraceLexer:
|
|
57
|
+
"""Accurate tokenizer tracking multi-line comments and string literals for brace counting."""
|
|
58
|
+
def __init__(self):
|
|
59
|
+
self.in_block_comment = False
|
|
60
|
+
|
|
61
|
+
def clean_line(self, line: str) -> str:
|
|
62
|
+
l = line
|
|
63
|
+
if self.in_block_comment:
|
|
64
|
+
if "*/" in l:
|
|
65
|
+
self.in_block_comment = False
|
|
66
|
+
l = l[l.find("*/") + 2:]
|
|
67
|
+
else:
|
|
68
|
+
return ""
|
|
69
|
+
|
|
70
|
+
while "/*" in l:
|
|
71
|
+
start = l.find("/*")
|
|
72
|
+
end = l.find("*/", start + 2)
|
|
73
|
+
if end != -1:
|
|
74
|
+
l = l[:start] + " " + l[end + 2:]
|
|
75
|
+
else:
|
|
76
|
+
l = l[:start]
|
|
77
|
+
self.in_block_comment = True
|
|
78
|
+
break
|
|
79
|
+
|
|
80
|
+
# Strip single-line comments
|
|
81
|
+
l = re.sub(r"//.*$", "", l)
|
|
82
|
+
# Strip string literals and template strings
|
|
83
|
+
l = re.sub(r'"(?:\\.|[^"\\])*"', '""', l)
|
|
84
|
+
l = re.sub(r"'(?:\\.|[^'\\])*'", "''", l)
|
|
85
|
+
l = re.sub(r"`(?:\\.|[^`\\])*`", "``", l)
|
|
86
|
+
return l
|
|
87
|
+
|
|
88
|
+
def count_braces(self, line: str) -> Tuple[int, int]:
|
|
89
|
+
clean = self.clean_line(line)
|
|
90
|
+
return clean.count("{"), clean.count("}")
|
|
91
|
+
|
|
15
92
|
class Skeletonizer:
|
|
16
93
|
"""Generates structural AST skeletons without LLMs with incremental mtime caching."""
|
|
17
94
|
|
|
18
95
|
CACHE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "skeletons")
|
|
19
96
|
|
|
20
97
|
@classmethod
|
|
21
|
-
def skeletonize_code(cls, code: str, file_ext: str) -> str:
|
|
22
|
-
"""Skeletons source code based on file extension."""
|
|
98
|
+
def skeletonize_code(cls, code: str, file_ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
|
99
|
+
"""Skeletons source code based on file extension, optionally preserving keep_symbols."""
|
|
23
100
|
ext = file_ext.lower()
|
|
24
101
|
if ext == ".py":
|
|
25
|
-
return cls._skeletonize_python(code)
|
|
26
|
-
elif ext in (
|
|
27
|
-
|
|
102
|
+
return cls._skeletonize_python(code, keep_symbols=keep_symbols)
|
|
103
|
+
elif ext in (
|
|
104
|
+
".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
|
|
105
|
+
".go", ".java", ".rs", ".cpp", ".cc", ".cxx", ".c", ".h", ".hpp", ".cs", ".php", ".kt", ".swift"
|
|
106
|
+
):
|
|
107
|
+
return cls._skeletonize_braces(code, ext, keep_symbols=keep_symbols)
|
|
28
108
|
return code
|
|
29
109
|
|
|
30
110
|
@classmethod
|
|
31
|
-
def _skeletonize_python(cls, code: str) -> str:
|
|
111
|
+
def _skeletonize_python(cls, code: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
|
32
112
|
"""Uses Python standard library `ast` to fold function bodies."""
|
|
33
113
|
try:
|
|
34
114
|
tree = ast.parse(code)
|
|
35
115
|
for node in ast.walk(tree):
|
|
36
116
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
117
|
+
if keep_symbols is not None and node.name in keep_symbols:
|
|
118
|
+
continue
|
|
37
119
|
doc = ast.get_docstring(node)
|
|
38
120
|
new_body = []
|
|
39
121
|
if doc:
|
|
@@ -45,34 +127,178 @@ class Skeletonizer:
|
|
|
45
127
|
return code
|
|
46
128
|
|
|
47
129
|
@classmethod
|
|
48
|
-
def
|
|
49
|
-
|
|
130
|
+
def _extract_fn(cls, line: str) -> Optional[Tuple[str, str]]:
|
|
131
|
+
line_clean = line.strip()
|
|
132
|
+
if not line_clean or line_clean.startswith("//") or line_clean.startswith("/*") or line_clean.startswith("*"):
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
if line_clean.startswith("}"):
|
|
136
|
+
line_clean = line_clean[1:].strip()
|
|
137
|
+
|
|
138
|
+
# Strip export prefix so exported declarations can be inspected
|
|
139
|
+
if line_clean.startswith("export default "):
|
|
140
|
+
check_line = line_clean[15:].strip()
|
|
141
|
+
elif line_clean.startswith("export "):
|
|
142
|
+
check_line = line_clean[7:].strip()
|
|
143
|
+
else:
|
|
144
|
+
check_line = line_clean
|
|
145
|
+
|
|
146
|
+
first_word = re.split(r"[\s(]", check_line)[0]
|
|
147
|
+
if first_word in CONTROL_KEYWORDS:
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
m = FN_DECL_REGEX.match(line_clean)
|
|
151
|
+
if m:
|
|
152
|
+
return (m.group(1) or "anonymous", "fn_decl")
|
|
153
|
+
|
|
154
|
+
m = GO_FN_REGEX.match(line_clean)
|
|
155
|
+
if m:
|
|
156
|
+
return (m.group(1), "go_func")
|
|
157
|
+
|
|
158
|
+
m = RUST_FN_REGEX.match(line_clean)
|
|
159
|
+
if m:
|
|
160
|
+
return (m.group(1), "rust_fn")
|
|
161
|
+
|
|
162
|
+
m = ARROW_FN_REGEX.match(line_clean)
|
|
163
|
+
if m:
|
|
164
|
+
return (m.group(1), "arrow_fn")
|
|
165
|
+
|
|
166
|
+
m = ARROW_MULTILINE_START.match(line_clean)
|
|
167
|
+
if m and not line_clean.endswith(";"):
|
|
168
|
+
return (m.group(1), "arrow_multiline")
|
|
169
|
+
|
|
170
|
+
m = METHOD_REGEX.match(line_clean)
|
|
171
|
+
if m:
|
|
172
|
+
name = m.group(1)
|
|
173
|
+
clean_name = name.split("::")[-1]
|
|
174
|
+
if clean_name not in CONTROL_KEYWORDS:
|
|
175
|
+
return (clean_name, "method")
|
|
176
|
+
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
@classmethod
|
|
180
|
+
def _skeletonize_braces(cls, code: str, ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
|
181
|
+
"""
|
|
182
|
+
Universal brace-depth state machine for TS/JS/Go/Java/Rust/C++/C#/PHP.
|
|
183
|
+
Folds function bodies into '{ /* ... */ }' while strictly preserving:
|
|
184
|
+
1. Target symbols and 1-hop dependencies in full (via keep_symbols).
|
|
185
|
+
2. Container blocks (classes, interfaces, structs, namespaces, impls).
|
|
186
|
+
3. Control flow statements (if, catch, for, while, switch, try).
|
|
187
|
+
4. Arrow functions, React components, and multi-line signatures.
|
|
188
|
+
5. Multi-line comment & string immunity for brace depth tracking.
|
|
189
|
+
"""
|
|
50
190
|
lines = code.splitlines()
|
|
51
191
|
out = []
|
|
52
|
-
in_function = False
|
|
53
|
-
brace_depth = 0
|
|
54
192
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
193
|
+
lexer = BraceLexer()
|
|
194
|
+
in_folding = False
|
|
195
|
+
fold_depth = 0
|
|
196
|
+
current_depth = 0
|
|
197
|
+
|
|
198
|
+
pending_header_lines = []
|
|
199
|
+
pending_name = None
|
|
200
|
+
pending_kind = None
|
|
60
201
|
|
|
61
202
|
comment_token = "/* ... */" if ext != ".py" else "..."
|
|
62
203
|
|
|
63
204
|
for line in lines:
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
205
|
+
raw_line = line
|
|
206
|
+
line_clean = line.strip()
|
|
207
|
+
|
|
208
|
+
# 1. If currently skipping a folded function body
|
|
209
|
+
if in_folding:
|
|
210
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
211
|
+
current_depth += open_b - close_b
|
|
212
|
+
if current_depth <= fold_depth:
|
|
213
|
+
in_folding = False
|
|
214
|
+
trailing = ""
|
|
215
|
+
idx = raw_line.rfind("}")
|
|
216
|
+
if idx != -1 and idx < len(raw_line) - 1:
|
|
217
|
+
suffix = raw_line[idx + 1:].strip()
|
|
218
|
+
if suffix.startswith(";") or suffix.startswith(","):
|
|
219
|
+
trailing = suffix
|
|
220
|
+
if trailing and out:
|
|
221
|
+
out[-1] = out[-1] + trailing
|
|
222
|
+
continue
|
|
223
|
+
|
|
224
|
+
# 2. If accumulating a multi-line header
|
|
225
|
+
if pending_header_lines:
|
|
226
|
+
pending_header_lines.append(raw_line)
|
|
227
|
+
if "=>" in line_clean or "{" in line_clean:
|
|
228
|
+
fn_name = pending_name
|
|
229
|
+
should_keep = keep_symbols is not None and fn_name in keep_symbols
|
|
230
|
+
|
|
231
|
+
last_brace_idx = raw_line.rfind("{")
|
|
232
|
+
if last_brace_idx != -1:
|
|
233
|
+
sig_lines = pending_header_lines[:-1] + [raw_line[:last_brace_idx]]
|
|
234
|
+
temp_lexer = BraceLexer()
|
|
235
|
+
sig_open = sum(temp_lexer.count_braces(sl)[0] for sl in sig_lines)
|
|
236
|
+
sig_close = sum(temp_lexer.count_braces(sl)[1] for sl in sig_lines)
|
|
237
|
+
base_depth = current_depth + (sig_open - sig_close)
|
|
238
|
+
else:
|
|
239
|
+
base_depth = current_depth
|
|
240
|
+
|
|
241
|
+
if should_keep:
|
|
242
|
+
out.extend(pending_header_lines)
|
|
243
|
+
for phl in pending_header_lines:
|
|
244
|
+
op, cl = lexer.count_braces(phl)
|
|
245
|
+
current_depth += op - cl
|
|
246
|
+
else:
|
|
247
|
+
folded_last_line = re.sub(r'\{.*$', f'{{ {comment_token} }}', raw_line)
|
|
248
|
+
pending_header_lines[-1] = folded_last_line
|
|
249
|
+
out.extend(pending_header_lines)
|
|
250
|
+
fold_depth = base_depth
|
|
251
|
+
current_depth = base_depth + 1
|
|
252
|
+
in_folding = True
|
|
253
|
+
|
|
254
|
+
pending_header_lines = []
|
|
255
|
+
pending_name = None
|
|
256
|
+
pending_kind = None
|
|
257
|
+
continue
|
|
258
|
+
elif ";" in line_clean and not ("{" in line_clean or "=>" in line_clean):
|
|
259
|
+
out.extend(pending_header_lines)
|
|
260
|
+
for phl in pending_header_lines:
|
|
261
|
+
op, cl = lexer.count_braces(phl)
|
|
262
|
+
current_depth += op - cl
|
|
263
|
+
pending_header_lines = []
|
|
264
|
+
pending_name = None
|
|
265
|
+
pending_kind = None
|
|
266
|
+
continue
|
|
70
267
|
else:
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
268
|
+
continue
|
|
269
|
+
|
|
270
|
+
# 3. Check for function start
|
|
271
|
+
fn_info = cls._extract_fn(raw_line)
|
|
272
|
+
if fn_info:
|
|
273
|
+
name, kind = fn_info
|
|
274
|
+
|
|
275
|
+
if (kind in ('arrow_multiline', 'arrow_fn')) and "=>" not in raw_line:
|
|
276
|
+
pending_header_lines = [raw_line]
|
|
277
|
+
pending_name = name
|
|
278
|
+
pending_kind = 'arrow_multiline'
|
|
279
|
+
continue
|
|
280
|
+
|
|
281
|
+
if "{" in raw_line:
|
|
282
|
+
should_keep = keep_symbols is not None and name in keep_symbols
|
|
283
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
284
|
+
|
|
285
|
+
if should_keep:
|
|
286
|
+
out.append(raw_line)
|
|
287
|
+
current_depth += open_b - close_b
|
|
288
|
+
else:
|
|
289
|
+
folded_line = re.sub(r'\{.*$', f'{{ {comment_token} }}', raw_line)
|
|
290
|
+
out.append(folded_line)
|
|
291
|
+
open_b_head, _ = lexer.count_braces(raw_line[:raw_line.find("{") + 1])
|
|
292
|
+
fold_depth = current_depth + open_b_head - 1
|
|
293
|
+
current_depth += open_b - close_b
|
|
294
|
+
if current_depth > fold_depth:
|
|
295
|
+
in_folding = True
|
|
296
|
+
continue
|
|
297
|
+
|
|
298
|
+
# 4. Normal line
|
|
299
|
+
out.append(raw_line)
|
|
300
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
301
|
+
current_depth += open_b - close_b
|
|
76
302
|
|
|
77
303
|
return "\n".join(out)
|
|
78
304
|
|