tokless 0.4.1 → 0.5.1

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,851 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ preprocessBraceLines,
5
+ findMatchingForward,
6
+ findMatchingBackward,
7
+ skipWhitespaceBackward,
8
+ stripLeadingAnnotationsOnText,
9
+ sliceCleanRange,
10
+ hasTopLevelChar,
11
+ } = require('./lexer');
12
+
13
+ const DEFAULT_CONTROL_KEYWORDS = new Set([
14
+ 'if',
15
+ 'else',
16
+ 'for',
17
+ 'while',
18
+ 'do',
19
+ 'switch',
20
+ 'case',
21
+ 'catch',
22
+ 'finally',
23
+ 'try',
24
+ 'with',
25
+ 'synchronized',
26
+ 'when',
27
+ 'match',
28
+ 'loop',
29
+ 'using',
30
+ 'lock',
31
+ 'fixed',
32
+ 'checked',
33
+ 'unchecked',
34
+ 'return',
35
+ 'throw',
36
+ 'new',
37
+ 'typeof',
38
+ 'delete',
39
+ 'await',
40
+ 'yield',
41
+ 'sizeof',
42
+ 'alignof',
43
+ 'decltype',
44
+ 'static_assert',
45
+ ]);
46
+
47
+ const DEFAULT_CONTAINERS = new Set([
48
+ 'class',
49
+ 'interface',
50
+ '@interface',
51
+ 'enum',
52
+ 'record',
53
+ 'struct',
54
+ 'trait',
55
+ 'impl',
56
+ 'namespace',
57
+ 'module',
58
+ 'mod',
59
+ 'object',
60
+ ]);
61
+
62
+ const DEFAULT_TRAILING_KEYWORDS = new Set([
63
+ 'throws',
64
+ 'const',
65
+ 'noexcept',
66
+ 'override',
67
+ 'final',
68
+ 'volatile',
69
+ 'mutable',
70
+ 'ref',
71
+ 'where',
72
+ 'pure',
73
+ 'default',
74
+ 'delete',
75
+ 'requires',
76
+ ]);
77
+
78
+ function findDeclarationRange(analyzed, startIdx, options = {}) {
79
+ const lang = typeof options === 'string' ? options : options.lang || '';
80
+ const allowThrows = options.allowThrows !== false && (lang === 'c' || lang === 'java' || !lang);
81
+ const allowWhere = options.allowWhere !== false && (lang === 'rust' || lang === 'c' || lang === 'kotlin' || !lang);
82
+
83
+ let paren = 0;
84
+ let bracket = 0;
85
+ let brace = 0;
86
+ let blockStarted = false;
87
+ let headerEndIdx = startIdx;
88
+
89
+ for (let j = startIdx; j < analyzed.length; j++) {
90
+ const line = analyzed[j].clean;
91
+ for (let k = 0; k < line.length; k++) {
92
+ const ch = line[k];
93
+ if (ch === '(') paren++;
94
+ else if (ch === ')') paren = Math.max(0, paren - 1);
95
+ else if (ch === '[') bracket++;
96
+ else if (ch === ']') bracket = Math.max(0, bracket - 1);
97
+ else if (ch === '{') {
98
+ if (!blockStarted && paren === 0 && bracket === 0) {
99
+ blockStarted = true;
100
+ headerEndIdx = j;
101
+ }
102
+ brace++;
103
+ } else if (ch === '}') {
104
+ brace = Math.max(0, brace - 1);
105
+ if (blockStarted && brace === 0) {
106
+ // 陷阱: TS 函数返回对象字面量类型 `: { a: string } {` 同一行紧跟真实函数体 `{` 时不能提前截断
107
+ const rest = line.slice(k + 1).trim();
108
+ if (rest.startsWith('{') || rest.startsWith('=>')) {
109
+ blockStarted = false;
110
+ } else {
111
+ return { endIdx: j, headerEndIdx, hasBlock: true };
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ if (blockStarted && brace === 0) {
118
+ return { endIdx: j, headerEndIdx, hasBlock: true };
119
+ }
120
+
121
+ if (!blockStarted && brace === 0 && paren === 0 && bracket === 0) {
122
+ const trimmed = line.trim();
123
+ if (trimmed.endsWith(';')) {
124
+ return { endIdx: j, headerEndIdx: j, hasBlock: false };
125
+ }
126
+ if (
127
+ trimmed.endsWith('=>') ||
128
+ trimmed.endsWith('=') ||
129
+ trimmed.endsWith(':') ||
130
+ trimmed.endsWith(',') ||
131
+ trimmed.endsWith('(') ||
132
+ trimmed.endsWith('|') ||
133
+ trimmed.endsWith('&') ||
134
+ trimmed.endsWith('->') ||
135
+ trimmed.startsWith('@') ||
136
+ /\b(?:extends|implements|permits|throws|where)\s*$/.test(trimmed)
137
+ ) {
138
+ continue;
139
+ }
140
+
141
+ let nextTrimmed = '';
142
+ for (let n = j + 1; n < analyzed.length && n <= j + 4; n++) {
143
+ const t = analyzed[n].clean.trim();
144
+ if (t) {
145
+ nextTrimmed = t;
146
+ break;
147
+ }
148
+ }
149
+ if (
150
+ nextTrimmed.startsWith('{') ||
151
+ nextTrimmed.startsWith('=>') ||
152
+ nextTrimmed.startsWith('|') ||
153
+ nextTrimmed.startsWith('&') ||
154
+ nextTrimmed.startsWith('->') ||
155
+ nextTrimmed.startsWith(':') ||
156
+ (allowThrows && /^(?:throws|extends|implements|permits)\b/.test(nextTrimmed)) ||
157
+ (allowWhere && /^where\b/.test(nextTrimmed))
158
+ ) {
159
+ continue;
160
+ }
161
+
162
+ return { endIdx: j, headerEndIdx: j, hasBlock: false };
163
+ }
164
+ }
165
+
166
+ return { endIdx: analyzed.length - 1, headerEndIdx, hasBlock: blockStarted };
167
+ }
168
+
169
+ function buildCompactSignature(analyzed, startIdx, headerEndIdx, hasBlock, maxLen = 140, cutPos = null) {
170
+ let sig = '';
171
+
172
+ if (hasBlock) {
173
+ let cutLine = cutPos ? cutPos.line : -1;
174
+ let cutCol = cutPos ? cutPos.col : -1;
175
+
176
+ if (cutLine === -1) {
177
+ let p = 0;
178
+ let b = 0;
179
+ for (let i = startIdx; i <= headerEndIdx; i++) {
180
+ const cleanLine = analyzed[i].clean;
181
+ for (let k = 0; k < cleanLine.length; k++) {
182
+ const ch = cleanLine[k];
183
+ if (ch === '(') p++;
184
+ else if (ch === ')') p = Math.max(0, p - 1);
185
+ else if (ch === '[') b++;
186
+ else if (ch === ']') b = Math.max(0, b - 1);
187
+ else if (ch === '{' && p === 0 && b === 0) {
188
+ const after = cleanLine.slice(k + 1);
189
+ const closeIdx = after.indexOf('}');
190
+ if (closeIdx !== -1 && after.slice(closeIdx + 1).trim().startsWith('{')) {
191
+ continue;
192
+ }
193
+ cutLine = i;
194
+ cutCol = k;
195
+ break;
196
+ }
197
+ }
198
+ if (cutLine !== -1) break;
199
+ }
200
+ }
201
+
202
+ const effectiveEnd = cutLine !== -1 ? cutLine : headerEndIdx;
203
+ const parts = [];
204
+ for (let i = startIdx; i <= effectiveEnd; i++) {
205
+ let rawLine = analyzed[i].raw;
206
+ if (i === cutLine && cutCol !== -1) {
207
+ rawLine = rawLine.slice(0, cutCol);
208
+ }
209
+ const trimmed = rawLine.trim();
210
+ if (trimmed) parts.push(trimmed);
211
+ }
212
+ sig = parts.join(' ').replace(/\s+/g, ' ').trim();
213
+ } else {
214
+ const parts = [];
215
+ for (let i = startIdx; i <= headerEndIdx; i++) {
216
+ const trimmed = analyzed[i].raw.trim();
217
+ if (trimmed) parts.push(trimmed);
218
+ }
219
+ sig = parts.join(' ').replace(/\s+/g, ' ').replace(/;+\s*$/, '').trim();
220
+ }
221
+
222
+ if (maxLen > 0 && sig.length > maxLen) {
223
+ sig = sig.slice(0, maxLen - 3).trimEnd() + '...';
224
+ }
225
+ return sig;
226
+ }
227
+
228
+ function findStatementStart(analyzed, fromLine, fromCol, minLine, targetDepth) {
229
+ let startLine = fromLine;
230
+ let startCol = 0;
231
+
232
+ let paren = 0;
233
+ let bracket = 0;
234
+ let foundBoundary = false;
235
+
236
+ for (let line = fromLine; line >= minLine; line--) {
237
+ const info = analyzed[line];
238
+ const clean = info.clean;
239
+ const kStart = line === fromLine ? fromCol - 1 : clean.length - 1;
240
+
241
+ for (let col = kStart; col >= 0; col--) {
242
+ const ch = clean[col];
243
+ if (ch === ')') paren++;
244
+ else if (ch === '(') paren = Math.max(0, paren - 1);
245
+ else if (ch === ']') bracket++;
246
+ else if (ch === '[') bracket = Math.max(0, bracket - 1);
247
+ else if (paren === 0 && bracket === 0 && (ch === ';' || ch === '{' || ch === '}')) {
248
+ startLine = line;
249
+ startCol = col + 1;
250
+ foundBoundary = true;
251
+ break;
252
+ }
253
+ }
254
+ if (foundBoundary) break;
255
+
256
+ if (line < fromLine && paren === 0 && bracket === 0) {
257
+ const trimmed = clean.trim();
258
+ if (!trimmed || trimmed.startsWith('#')) {
259
+ startLine = line + 1;
260
+ startCol = 0;
261
+ foundBoundary = true;
262
+ break;
263
+ }
264
+ if (info.braceStart !== targetDepth && info.braceEnd !== targetDepth) {
265
+ startLine = line + 1;
266
+ startCol = 0;
267
+ foundBoundary = true;
268
+ break;
269
+ }
270
+ }
271
+ }
272
+
273
+ if (!foundBoundary) {
274
+ startLine = minLine;
275
+ startCol = 0;
276
+ }
277
+
278
+ while (startLine < fromLine || (startLine === fromLine && startCol < fromCol)) {
279
+ const rest = analyzed[startLine].clean.slice(startCol);
280
+ if (rest.trim() !== '' && !rest.trim().startsWith('#')) {
281
+ const leadWs = rest.match(/^\s*/)[0].length;
282
+ startCol += leadWs;
283
+ break;
284
+ }
285
+ startLine++;
286
+ startCol = 0;
287
+ }
288
+
289
+ // 陷阱: 注解/属性行与声明头分行书写时需向上合并,否则生成的方法签名会丢失 `@Auth(...)` / `#[derive]` 且行号偏晚
290
+ if (startCol === (analyzed[startLine].clean.match(/^\s*/)[0].length)) {
291
+ let probe = startLine - 1;
292
+ while (probe >= minLine) {
293
+ const pInfo = analyzed[probe];
294
+ const pTrim = pInfo.clean.trim();
295
+ if (!pTrim) break;
296
+ if (pInfo.braceEnd === targetDepth && pTrim.endsWith(')') && pInfo.parenStart > 0) {
297
+ const openParen = findMatchingBackward(analyzed, probe, pInfo.clean.lastIndexOf(')'), ')', '(', minLine);
298
+ if (openParen) {
299
+ const headTrim = analyzed[openParen.line].clean.slice(0, openParen.col).trim();
300
+ if (/^(?:@[A-Za-z_$][\w$.:]*|#\s*\[|[A-Za-z_][\w.]*\s*$)/.test(headTrim)) {
301
+ startLine = openParen.line;
302
+ startCol = analyzed[startLine].clean.match(/^\s*/)[0].length;
303
+ probe = openParen.line - 1;
304
+ continue;
305
+ }
306
+ }
307
+ }
308
+ if (
309
+ pInfo.braceStart === targetDepth &&
310
+ (/^@[A-Za-z_$]/.test(pTrim) || /^#!?\[/.test(pTrim) || /^\[[A-Za-z_]/.test(pTrim)) &&
311
+ !pTrim.endsWith(';') &&
312
+ !pTrim.endsWith('{') &&
313
+ !pTrim.endsWith('}')
314
+ ) {
315
+ startLine = probe;
316
+ startCol = analyzed[startLine].clean.match(/^\s*/)[0].length;
317
+ probe--;
318
+ continue;
319
+ }
320
+ break;
321
+ }
322
+ }
323
+
324
+ return { line: startLine, col: startCol };
325
+ }
326
+
327
+ function stripLeadingAttributesAndAnnotations(text) {
328
+ let s = text;
329
+ while (s.length > 0) {
330
+ s = s.trimStart();
331
+ if (s.startsWith('@') && !/^@interface\b/.test(s)) {
332
+ const stripped = stripLeadingAnnotationsOnText(s);
333
+ if (stripped.offset > 0) {
334
+ s = stripped.rest;
335
+ continue;
336
+ }
337
+ break;
338
+ }
339
+ if (s.startsWith('#[') || s.startsWith('#![') || (s.startsWith('[') && /^\[[A-Za-z_]/.test(s))) {
340
+ const openIdx = s.indexOf('[');
341
+ let depth = 0;
342
+ let endIdx = -1;
343
+ for (let i = openIdx; i < s.length; i++) {
344
+ if (s[i] === '[') depth++;
345
+ else if (s[i] === ']') {
346
+ depth--;
347
+ if (depth === 0) {
348
+ endIdx = i;
349
+ break;
350
+ }
351
+ }
352
+ }
353
+ if (endIdx !== -1) {
354
+ s = s.slice(endIdx + 1);
355
+ continue;
356
+ }
357
+ }
358
+ break;
359
+ }
360
+ return s.trimStart();
361
+ }
362
+
363
+ function matchContainerHeader(headerClean, containersSet) {
364
+ const core = stripLeadingAttributesAndAnnotations(headerClean);
365
+ if (!core) return null;
366
+ if (hasTopLevelChar(core, '=')) return null;
367
+
368
+ const annoTypeMatch = core.match(
369
+ /^(?:(?:public|private|protected|internal|abstract|final|static|strictfp)\s+)*(@interface)\s+([A-Za-z_$][\w$]*)\b/
370
+ );
371
+ if (annoTypeMatch && containersSet.has('@interface')) {
372
+ return { kind: '@interface', name: annoTypeMatch[2] };
373
+ }
374
+
375
+ if (containersSet.has('impl')) {
376
+ const implMatch = core.match(/^(?:(?:pub(?:\s*\([^)]*\))?|unsafe|default|const)\s+)*impl\b([\s\S]*)$/);
377
+ if (implMatch) {
378
+ const rawRest = implMatch[1].replace(/\bwhere\b[\s\S]*$/, '').replace(/\s+/g, ' ').trim();
379
+ return { kind: 'impl', name: rawRest || 'impl' };
380
+ }
381
+ }
382
+
383
+ if (containersSet.has('object')) {
384
+ const objMatch = core.match(
385
+ /^(?:(?:public|private|protected|internal|data|sealed|external)\s+)*(?:companion\s+)?object(?:\s+([A-Za-z_$][\w$]*))?(?:\s*:|\s*$)/
386
+ );
387
+ if (objMatch) {
388
+ return { kind: 'object', name: objMatch[1] || 'companion' };
389
+ }
390
+ }
391
+
392
+ const goTypeMatch = core.match(/^type\s+([A-Za-z_]\w*)\s+(struct|interface)\b/);
393
+ if (goTypeMatch && containersSet.has(goTypeMatch[2])) {
394
+ return { kind: goTypeMatch[2], name: goTypeMatch[1] };
395
+ }
396
+
397
+ const kwRegex =
398
+ /^(?:(?:public|private|protected|internal|export|default|declare|abstract|final|static|sealed|non-sealed|open|data|value|inline|inner|fun|partial|unsafe|extern|pub(?:\s*\([^)]*\))?|async|const|template\s*<[^>]*>)\s+)*(@interface|class|interface|enum\s+class|enum\s+struct|enum|record|struct|trait|namespace|module|mod|union)\s+([A-Za-z_$][\w$.:]*)/;
399
+ const m = core.match(kwRegex);
400
+ if (!m) return null;
401
+
402
+ let rawKind = m[1].replace(/\s+/g, ' ');
403
+ if (rawKind === 'enum class' || rawKind === 'enum struct') rawKind = 'enum';
404
+ if (!containersSet.has(rawKind)) return null;
405
+
406
+ return { kind: rawKind, name: m[2] };
407
+ }
408
+
409
+ function skipTrailingClausesBackward(analyzed, braceLine, braceCol, minLine, profile) {
410
+ const trailingKw = profile.trailingKeywords || DEFAULT_TRAILING_KEYWORDS;
411
+ let cur = skipWhitespaceBackward(analyzed, braceLine, braceCol - 1, minLine);
412
+ if (!cur) return null;
413
+
414
+ let guard = 0;
415
+ while (cur && guard++ < 40) {
416
+ if (cur.ch === ')') {
417
+ const openPos = findMatchingBackward(analyzed, cur.line, cur.col, ')', '(', minLine);
418
+ if (!openPos) return null;
419
+ const beforeOpen = skipWhitespaceBackward(analyzed, openPos.line, openPos.col - 1, minLine);
420
+ if (beforeOpen) {
421
+ const linePrefix = analyzed[beforeOpen.line].clean.slice(0, beforeOpen.col + 1);
422
+ const wordMatch = linePrefix.match(/([A-Za-z_~][\w$]*)\s*$/);
423
+ const word = wordMatch ? wordMatch[1] : '';
424
+ if (word === 'noexcept' || word === 'throw' || word === 'requires') {
425
+ const wordCol = beforeOpen.col + 1 - wordMatch[0].length;
426
+ cur = skipWhitespaceBackward(analyzed, beforeOpen.line, wordCol - 1, minLine);
427
+ continue;
428
+ }
429
+ // 陷阱: C++/Kotlin 构造器委托 `: Base(a)` 与 Go 多返回值 `(int, error)` 会紧贴 `{`,需继续向左回退定位真实形参 `(...)`
430
+ const colonCheck = sliceCleanRange(analyzed, minLine, 0, openPos.line, openPos.col - 1);
431
+ if (/\)\s*:\s*[A-Za-z_][\w:.,\s<>()]*$/.test(colonCheck)) {
432
+ const colonIdx = colonCheck.lastIndexOf(':');
433
+ const prefixBeforeColon = colonCheck.slice(0, colonIdx);
434
+ const linesBefore = prefixBeforeColon.split('\n');
435
+ const targetLine = minLine + linesBefore.length - 1;
436
+ const targetCol = linesBefore[linesBefore.length - 1].length - 1;
437
+ cur = skipWhitespaceBackward(analyzed, targetLine, targetCol, minLine);
438
+ continue;
439
+ }
440
+ if (beforeOpen.ch === ')') {
441
+ const prevOpen = findMatchingBackward(analyzed, beforeOpen.line, beforeOpen.col, ')', '(', minLine);
442
+ if (prevOpen) {
443
+ const beforePrevOpen = sliceCleanRange(analyzed, minLine, 0, prevOpen.line, prevOpen.col - 1).trim();
444
+ if (!/^func$/.test(beforePrevOpen)) {
445
+ cur = beforeOpen;
446
+ continue;
447
+ }
448
+ }
449
+ }
450
+ }
451
+ return { closeParen: cur, openParen: openPos };
452
+ }
453
+
454
+ if (cur.ch === '>') {
455
+ const lineBefore = analyzed[cur.line].clean.slice(0, cur.col + 1);
456
+ if (/->\s*$/.test(lineBefore)) {
457
+ cur = skipWhitespaceBackward(analyzed, cur.line, cur.col - 2, minLine);
458
+ continue;
459
+ }
460
+ const openAngle = findMatchingBackward(analyzed, cur.line, cur.col, '>', '<', minLine);
461
+ if (!openAngle) break;
462
+ cur = skipWhitespaceBackward(analyzed, openAngle.line, openAngle.col - 1, minLine);
463
+ continue;
464
+ }
465
+
466
+ if (cur.ch === ']') {
467
+ const openBracket = findMatchingBackward(analyzed, cur.line, cur.col, ']', '[', minLine);
468
+ if (!openBracket) break;
469
+ cur = skipWhitespaceBackward(analyzed, openBracket.line, openBracket.col - 1, minLine);
470
+ continue;
471
+ }
472
+
473
+ const lineSlice = analyzed[cur.line].clean.slice(0, cur.col + 1);
474
+ const arrowMatch = lineSlice.match(/(?:->|:|::|,|\?|&|\*|\+|\||!)\s*$/);
475
+ if (arrowMatch) {
476
+ cur = skipWhitespaceBackward(
477
+ analyzed,
478
+ cur.line,
479
+ cur.col + 1 - arrowMatch[0].length - 1,
480
+ minLine
481
+ );
482
+ continue;
483
+ }
484
+
485
+ const tokenMatch = lineSlice.match(/([A-Za-z_$][\w$.:]*)\s*$/);
486
+ if (tokenMatch) {
487
+ const word = tokenMatch[1];
488
+ const nextPos = skipWhitespaceBackward(
489
+ analyzed,
490
+ cur.line,
491
+ cur.col + 1 - tokenMatch[0].length - 1,
492
+ minLine
493
+ );
494
+ if (!nextPos) return null;
495
+ if (
496
+ trailingKw.has(word) ||
497
+ nextPos.ch === ')' ||
498
+ nextPos.ch === ',' ||
499
+ nextPos.ch === ':' ||
500
+ nextPos.ch === '>' ||
501
+ nextPos.ch === '&' ||
502
+ nextPos.ch === '*' ||
503
+ nextPos.ch === '?' ||
504
+ nextPos.ch === '.' ||
505
+ nextPos.ch === '+' ||
506
+ nextPos.ch === '|' ||
507
+ nextPos.ch === "'"
508
+ ) {
509
+ cur = nextPos;
510
+ continue;
511
+ }
512
+ const prevSlice = analyzed[nextPos.line].clean.slice(0, nextPos.col + 1);
513
+ if (/(?:->|\bthrows|\bwhere|\bimpl|\bdyn|\bfor|\bconst|\bmut|\blifetime)\s*$/.test(prevSlice) || /'[A-Za-z_]\w*\s*$/.test(prevSlice)) {
514
+ cur = nextPos;
515
+ continue;
516
+ }
517
+ return null;
518
+ }
519
+
520
+ if (cur.ch === "'") {
521
+ cur = skipWhitespaceBackward(analyzed, cur.line, cur.col - 1, minLine);
522
+ continue;
523
+ }
524
+
525
+ break;
526
+ }
527
+
528
+ return null;
529
+ }
530
+
531
+ function extractCallableFromBeforeParen(beforeParenClean, controlKeywords, inContainer) {
532
+ const core = stripLeadingAttributesAndAnnotations(beforeParenClean).trim();
533
+ if (!core) return null;
534
+
535
+ // 陷阱: 语句顶层含 `=` 属于字段匿名类初始化(如 `Runnable r = new Runnable() {}`),但须放行 C++ `operator=` / `operator==`
536
+ const withoutOperatorEq = core.replace(/\boperator\s*==?\b/g, 'operator_eq');
537
+ if (hasTopLevelChar(withoutOperatorEq, '=')) return null;
538
+ if (/\bnew\s+[A-Za-z_$][\w$.:<>?\s,]*$/.test(core)) return null;
539
+
540
+ const firstWordMatch = core.match(/^([A-Za-z_$][\w$]*)\b/);
541
+ if (firstWordMatch && controlKeywords.has(firstWordMatch[1])) {
542
+ return null;
543
+ }
544
+
545
+ const goRecvMatch = core.match(/^func\s*\([^)]*\)\s*([A-Za-z_]\w*)$/);
546
+ if (goRecvMatch) {
547
+ return { kind: 'func', name: goRecvMatch[1] };
548
+ }
549
+
550
+ const opMatch = core.match(/\b(operator\s*(?:\(\)|\[\]|[^\s(]+))\s*$/);
551
+ if (opMatch) {
552
+ return { kind: inContainer ? 'method' : 'function', name: opMatch[1].replace(/\s+/g, '') };
553
+ }
554
+
555
+ let target = core;
556
+ if (target.endsWith('>')) {
557
+ let angle = 0;
558
+ for (let i = target.length - 1; i >= 0; i--) {
559
+ if (target[i] === '>') angle++;
560
+ else if (target[i] === '<') {
561
+ angle--;
562
+ if (angle === 0) {
563
+ target = target.slice(0, i).trimEnd();
564
+ break;
565
+ }
566
+ }
567
+ }
568
+ }
569
+
570
+ const nameMatch = target.match(/([~A-Za-z_$][\w$]*)$/);
571
+ if (!nameMatch) return null;
572
+ const name = nameMatch[1];
573
+ if (controlKeywords.has(name)) return null;
574
+
575
+ const prefix = target.slice(0, target.length - name.length).trim();
576
+ if (/\bfn$/.test(prefix)) return { kind: inContainer ? 'method' : 'fn', name };
577
+ if (/\bfunc$/.test(prefix)) return { kind: inContainer ? 'method' : 'func', name };
578
+ if (/\bfun$/.test(prefix) || /\bfun\s*<[^>]*>$/.test(prefix)) {
579
+ return { kind: inContainer ? 'method' : 'fun', name };
580
+ }
581
+
582
+ return { kind: inContainer ? 'method' : 'function', name };
583
+ }
584
+
585
+ function findEnumConstantsSemicolon(analyzed, bodyStartLine, bodyStartCol, enumEndLine, enumBodyDepth) {
586
+ for (let line = bodyStartLine; line <= enumEndLine; line++) {
587
+ const clean = analyzed[line].clean;
588
+ const kStart = line === bodyStartLine ? bodyStartCol : 0;
589
+ let curDepth = line === bodyStartLine ? enumBodyDepth : analyzed[line].braceStart;
590
+ let paren = line === bodyStartLine ? 0 : analyzed[line].parenStart;
591
+
592
+ for (let col = kStart; col < clean.length; col++) {
593
+ const ch = clean[col];
594
+ if (ch === '{') curDepth++;
595
+ else if (ch === '}') {
596
+ curDepth--;
597
+ if (curDepth < enumBodyDepth) return null;
598
+ } else if (ch === '(') paren++;
599
+ else if (ch === ')') paren = Math.max(0, paren - 1);
600
+ else if (ch === ';' && curDepth === enumBodyDepth && paren === 0) {
601
+ return { line, col };
602
+ }
603
+ }
604
+ }
605
+ return null;
606
+ }
607
+
608
+ function scanBraceLanguage(lines, profile = {}) {
609
+ const analyzed = Array.isArray(lines) && lines.length > 0 && typeof lines[0] === 'object' && 'clean' in lines[0]
610
+ ? lines
611
+ : preprocessBraceLines(lines, profile.lexer || 'c');
612
+
613
+ const containersSet = profile.containers instanceof Set
614
+ ? profile.containers
615
+ : new Set(profile.containers || DEFAULT_CONTAINERS);
616
+ const controlKeywords = profile.controlKeywords instanceof Set
617
+ ? profile.controlKeywords
618
+ : new Set([...DEFAULT_CONTROL_KEYWORDS, ...(profile.controlKeywords || [])]);
619
+ const lineOffset = profile.lineOffset || 0;
620
+ const maxSigLen = profile.maxSignatureLength || 140;
621
+
622
+ const items = [];
623
+ const scopeStack = [];
624
+ let minStatementLine = 0;
625
+
626
+ for (let i = 0; i < analyzed.length; i++) {
627
+ while (scopeStack.length > 0 && i > scopeStack[scopeStack.length - 1].endIdx) {
628
+ scopeStack.pop();
629
+ }
630
+
631
+ const activeScope = scopeStack.length > 0 ? scopeStack[scopeStack.length - 1] : null;
632
+ const expectedDepth = activeScope ? activeScope.bodyDepth : 0;
633
+ const info = analyzed[i];
634
+
635
+ if (typeof profile.onStatementLine === 'function' && info.braceStart === expectedDepth) {
636
+ const hookRes = profile.onStatementLine({
637
+ analyzed,
638
+ lineIdx: i,
639
+ expectedDepth,
640
+ scopeStack,
641
+ items,
642
+ lineOffset,
643
+ findDeclarationRange,
644
+ buildCompactSignature,
645
+ });
646
+ if (hookRes && typeof hookRes.jumpToLine === 'number') {
647
+ minStatementLine = hookRes.jumpToLine + 1;
648
+ i = hookRes.jumpToLine;
649
+ continue;
650
+ }
651
+ }
652
+
653
+ let curBrace = info.braceStart;
654
+ const clean = info.clean;
655
+
656
+ for (let col = 0; col < clean.length; col++) {
657
+ const ch = clean[col];
658
+ if (ch === ';') {
659
+ if (curBrace === expectedDepth) {
660
+ minStatementLine = i;
661
+ }
662
+ continue;
663
+ }
664
+ if (ch === '}') {
665
+ curBrace = Math.max(0, curBrace - 1);
666
+ if (curBrace === expectedDepth) {
667
+ minStatementLine = i;
668
+ }
669
+ continue;
670
+ }
671
+ if (ch !== '{') continue;
672
+
673
+ const openDepth = curBrace;
674
+ curBrace++;
675
+
676
+ if (openDepth !== expectedDepth) continue;
677
+
678
+ // 陷阱: Java `enum` 首个顶层 `;` 之前的 `RED("r") { ... }` 是枚举常量实例块,必须整块跳过防内部重写方法平铺泄漏到外层
679
+ if (
680
+ activeScope &&
681
+ activeScope.kind === 'enum' &&
682
+ activeScope.enumBodyEnabledAfter &&
683
+ (i < activeScope.enumBodyEnabledAfter.line ||
684
+ (i === activeScope.enumBodyEnabledAfter.line && col < activeScope.enumBodyEnabledAfter.col))
685
+ ) {
686
+ const closeEnumConst = findMatchingForward(analyzed, i, col, '{', '}');
687
+ if (closeEnumConst) {
688
+ minStatementLine = closeEnumConst.line;
689
+ i = closeEnumConst.line;
690
+ break;
691
+ }
692
+ continue;
693
+ }
694
+ if (activeScope && activeScope.kind === 'enum' && activeScope.hasEnumMethods === false) {
695
+ continue;
696
+ }
697
+
698
+ const closeBrace = findMatchingForward(analyzed, i, col, '{', '}');
699
+ const blockEndLine = closeBrace ? closeBrace.line : analyzed.length - 1;
700
+ const floorLine = Math.max(
701
+ minStatementLine,
702
+ activeScope ? activeScope.headerEndIdx : 0
703
+ );
704
+ const stmtStart = findStatementStart(analyzed, i, col, floorLine, expectedDepth);
705
+ const headerClean = sliceCleanRange(analyzed, stmtStart.line, stmtStart.col, i, col - 1);
706
+
707
+ const containerMatch = matchContainerHeader(headerClean, containersSet);
708
+ if (containerMatch) {
709
+ const signature = buildCompactSignature(
710
+ analyzed,
711
+ stmtStart.line,
712
+ i,
713
+ true,
714
+ maxSigLen,
715
+ { line: i, col }
716
+ );
717
+ items.push({
718
+ kind: containerMatch.kind,
719
+ name: containerMatch.name,
720
+ signature,
721
+ startLine: stmtStart.line + 1 + lineOffset,
722
+ endLine: blockEndLine + 1 + lineOffset,
723
+ depth: scopeStack.length,
724
+ });
725
+
726
+ const scopeEntry = {
727
+ kind: containerMatch.kind,
728
+ name: containerMatch.name,
729
+ headerEndIdx: i,
730
+ endIdx: blockEndLine,
731
+ bodyDepth: expectedDepth + 1,
732
+ hasEnumMethods: true,
733
+ enumBodyEnabledAfter: null,
734
+ };
735
+
736
+ if (containerMatch.kind === 'enum' && profile.javaStyleEnum) {
737
+ const semiPos = findEnumConstantsSemicolon(
738
+ analyzed,
739
+ i,
740
+ col + 1,
741
+ blockEndLine,
742
+ expectedDepth + 1
743
+ );
744
+ if (semiPos) {
745
+ scopeEntry.enumBodyEnabledAfter = semiPos;
746
+ } else {
747
+ scopeEntry.hasEnumMethods = false;
748
+ }
749
+ }
750
+
751
+ scopeStack.push(scopeEntry);
752
+ minStatementLine = i;
753
+ break;
754
+ }
755
+
756
+ const parenPair = skipTrailingClausesBackward(analyzed, i, col, stmtStart.line, profile);
757
+ if (parenPair) {
758
+ const beforeParenClean = sliceCleanRange(
759
+ analyzed,
760
+ stmtStart.line,
761
+ stmtStart.col,
762
+ parenPair.openParen.line,
763
+ parenPair.openParen.col - 1
764
+ );
765
+ const callable = extractCallableFromBeforeParen(
766
+ beforeParenClean,
767
+ controlKeywords,
768
+ scopeStack.length > 0
769
+ );
770
+ if (callable) {
771
+ let finalKind = callable.kind;
772
+ if (typeof profile.mapCallableKind === 'function') {
773
+ finalKind = profile.mapCallableKind(callable, scopeStack) || finalKind;
774
+ }
775
+ const signature = buildCompactSignature(
776
+ analyzed,
777
+ stmtStart.line,
778
+ i,
779
+ true,
780
+ maxSigLen,
781
+ { line: i, col }
782
+ );
783
+ items.push({
784
+ kind: finalKind,
785
+ name: callable.name,
786
+ signature,
787
+ startLine: stmtStart.line + 1 + lineOffset,
788
+ endLine: blockEndLine + 1 + lineOffset,
789
+ depth: scopeStack.length,
790
+ });
791
+ minStatementLine = blockEndLine;
792
+ i = blockEndLine;
793
+ break;
794
+ }
795
+ } else if (
796
+ activeScope &&
797
+ activeScope.kind === 'record' &&
798
+ profile.javaCompactRecordConstructor
799
+ ) {
800
+ const compactCore = stripLeadingAttributesAndAnnotations(headerClean).trim();
801
+ const recCtor = compactCore.match(
802
+ /^(?:(?:public|private|protected)\s+)?([A-Za-z_$][\w$]*)$/
803
+ );
804
+ if (recCtor && recCtor[1] === activeScope.name) {
805
+ const signature = buildCompactSignature(
806
+ analyzed,
807
+ stmtStart.line,
808
+ i,
809
+ true,
810
+ maxSigLen,
811
+ { line: i, col }
812
+ );
813
+ items.push({
814
+ kind: 'method',
815
+ name: recCtor[1],
816
+ signature,
817
+ startLine: stmtStart.line + 1 + lineOffset,
818
+ endLine: blockEndLine + 1 + lineOffset,
819
+ depth: scopeStack.length,
820
+ });
821
+ minStatementLine = blockEndLine;
822
+ i = blockEndLine;
823
+ break;
824
+ }
825
+ }
826
+
827
+ // 陷阱: 非容器且非函数的代码块(如 `static { ... }` 或匿名内部类字段)必须整块跳过,否则其内部方法会在子级深度被误扫或打断外层
828
+ if (closeBrace && closeBrace.line > i) {
829
+ minStatementLine = closeBrace.line;
830
+ i = closeBrace.line;
831
+ break;
832
+ }
833
+ }
834
+ }
835
+
836
+ return items;
837
+ }
838
+
839
+ module.exports = {
840
+ DEFAULT_CONTROL_KEYWORDS,
841
+ DEFAULT_CONTAINERS,
842
+ DEFAULT_TRAILING_KEYWORDS,
843
+ findDeclarationRange,
844
+ buildCompactSignature,
845
+ findStatementStart,
846
+ stripLeadingAttributesAndAnnotations,
847
+ matchContainerHeader,
848
+ skipTrailingClausesBackward,
849
+ extractCallableFromBeforeParen,
850
+ scanBraceLanguage,
851
+ };