tokless 0.5.1 → 0.5.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.
@@ -0,0 +1,1133 @@
1
+ 'use strict';
2
+
3
+ const C_HEADER_EXTS = new Set(['.h', '.hpp', '.hh', '.hxx', '.h++', '.inl', '.inc']);
4
+
5
+ const C_CONTROL_KEYWORDS = new Set([
6
+ 'if',
7
+ 'else',
8
+ 'for',
9
+ 'while',
10
+ 'do',
11
+ 'switch',
12
+ 'case',
13
+ 'catch',
14
+ 'finally',
15
+ 'try',
16
+ 'with',
17
+ 'return',
18
+ 'throw',
19
+ 'new',
20
+ 'typeof',
21
+ 'delete',
22
+ 'await',
23
+ 'yield',
24
+ 'sizeof',
25
+ 'alignof',
26
+ 'decltype',
27
+ 'static_assert',
28
+ '_Static_assert',
29
+ ]);
30
+
31
+ /**
32
+ * 判断 raw 字符串索引 pos 处的单引号 `'` 是否为 C++14/C23 数字分隔符(例如 1'000'000、0xFF'FF)
33
+ * 注意排除 u8'a'、u'a'、U'a'、L'a' 等字符字面量前缀
34
+ */
35
+ function isDigitSeparatorQuote(raw, pos) {
36
+ if (pos <= 0 || pos + 1 >= raw.length) return false;
37
+ if (!/[0-9a-fA-F]/.test(raw[pos + 1])) return false;
38
+ const prefixSlice = raw.slice(0, pos);
39
+ return /(?:^|[^A-Za-z0-9_])(?:0[xX][0-9a-fA-F]+(?:'[0-9a-fA-F]+)*|0[bB][01]+(?:'[01]+)*|[0-9]+(?:'[0-9]+)*)$/.test(
40
+ prefixSlice
41
+ );
42
+ }
43
+
44
+ /**
45
+ * 判断 raw 字符串索引 pos 处是否为 C++11 Raw String 开头(如 R"delim(...)delim" / u8R"...")
46
+ */
47
+ function matchCppRawStringStart(raw, pos) {
48
+ if (raw[pos] === 'R' && pos + 1 < raw.length && raw[pos + 1] === '"') {
49
+ const prev = pos > 0 ? raw[pos - 1] : '';
50
+ const before2 = pos >= 2 ? raw.slice(pos - 2, pos) : '';
51
+ const before1 = pos >= 1 ? raw[pos - 1] : '';
52
+ const prevPrev = pos >= 3 ? raw[pos - 3] : '';
53
+ const prev1Char = pos >= 2 ? raw[pos - 2] : '';
54
+
55
+ let validPrefix = pos === 0 || !/[A-Za-z0-9_]/.test(prev);
56
+ if (!validPrefix && before2 === 'u8' && (pos === 2 || !/[A-Za-z0-9_]/.test(prevPrev))) {
57
+ validPrefix = true;
58
+ } else if (
59
+ !validPrefix &&
60
+ (before1 === 'u' || before1 === 'U' || before1 === 'L') &&
61
+ (pos === 1 || !/[A-Za-z0-9_]/.test(prev1Char))
62
+ ) {
63
+ validPrefix = true;
64
+ }
65
+ if (!validPrefix) return null;
66
+
67
+ const openParenIdx = raw.indexOf('(', pos + 2);
68
+ if (openParenIdx === -1) return null;
69
+ const delim = raw.slice(pos + 2, openParenIdx);
70
+ if (delim.length > 16 || /[\s()\\]/.test(delim)) return null;
71
+ return { endMarker: `)${delim}"`, openEndIdx: openParenIdx };
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * C / C++ 专用词法与预处理器扫描器:
78
+ * - 剥离注释、字符串/字符字面量、C++11 Raw String,识别 C++14/C23 数字分隔符
79
+ * - 隔离预处理器指令行(含 `\` 续行),防止宏内花括号污染常规代码 braceDepth
80
+ * - 维护条件编译栈,隔离 #if 0 死代码并平衡 #if/#elif/#else/#endif 多分支括号深度
81
+ */
82
+ function preprocessCCppLines(lines) {
83
+ const analyzed = new Array(lines.length);
84
+ const directives = [];
85
+
86
+ let braceDepth = 0;
87
+ let parenDepth = 0;
88
+ let inBlockComment = false;
89
+ let inRawString = false;
90
+ let rawEndMarker = '';
91
+ let inStringQuote = null;
92
+ let inPreprocessor = false;
93
+ let currentDirective = null;
94
+ const condStack = [];
95
+
96
+ const isDisabled = () => condStack.some((c) => c.inDisabledBranch);
97
+
98
+ function finalizeDirective() {
99
+ if (!currentDirective) return;
100
+ const joinedClean = currentDirective.cleanLines
101
+ .map((s) => s.replace(/\\\s*$/, ' '))
102
+ .join(' ')
103
+ .replace(/\s+/g, ' ')
104
+ .trim();
105
+ const m = joinedClean.match(/^#\s*([A-Za-z_]\w*)(?:\s+(.*))?$/);
106
+ const dirName = m ? m[1] : '';
107
+ const argClean = m && m[2] ? m[2].trim() : '';
108
+
109
+ if (dirName === 'if' || dirName === 'ifdef' || dirName === 'ifndef') {
110
+ const parentDisabled = isDisabled();
111
+ const isZeroCond = dirName === 'if' && /^\(?\s*0\s*\)?$/.test(argClean);
112
+ const inDisabledBranch = parentDisabled || isZeroCond;
113
+ condStack.push({
114
+ entryBraceDepth: braceDepth,
115
+ entryParenDepth: parenDepth,
116
+ branchExitBraceDepth: null,
117
+ branchExitParenDepth: null,
118
+ parentDisabled,
119
+ inDisabledBranch,
120
+ });
121
+ } else if (dirName === 'elif') {
122
+ if (condStack.length > 0) {
123
+ const top = condStack[condStack.length - 1];
124
+ if (!top.inDisabledBranch && top.branchExitBraceDepth === null) {
125
+ top.branchExitBraceDepth = braceDepth;
126
+ top.branchExitParenDepth = parenDepth;
127
+ }
128
+ braceDepth = top.entryBraceDepth;
129
+ parenDepth = top.entryParenDepth;
130
+ const isZeroCond = /^\(?\s*0\s*\)?$/.test(argClean);
131
+ top.inDisabledBranch = top.parentDisabled || isZeroCond;
132
+ }
133
+ } else if (dirName === 'else') {
134
+ if (condStack.length > 0) {
135
+ const top = condStack[condStack.length - 1];
136
+ if (!top.inDisabledBranch && top.branchExitBraceDepth === null) {
137
+ top.branchExitBraceDepth = braceDepth;
138
+ top.branchExitParenDepth = parenDepth;
139
+ }
140
+ braceDepth = top.entryBraceDepth;
141
+ parenDepth = top.entryParenDepth;
142
+ top.inDisabledBranch = top.parentDisabled;
143
+ }
144
+ } else if (dirName === 'endif') {
145
+ if (condStack.length > 0) {
146
+ const top = condStack.pop();
147
+ if (!top.inDisabledBranch && top.branchExitBraceDepth === null) {
148
+ top.branchExitBraceDepth = braceDepth;
149
+ top.branchExitParenDepth = parenDepth;
150
+ }
151
+ if (top.branchExitBraceDepth !== null) {
152
+ braceDepth = top.branchExitBraceDepth;
153
+ parenDepth = top.branchExitParenDepth;
154
+ } else {
155
+ braceDepth = top.entryBraceDepth;
156
+ parenDepth = top.entryParenDepth;
157
+ }
158
+ }
159
+ }
160
+
161
+ currentDirective.name = dirName;
162
+ currentDirective.argClean = argClean;
163
+ currentDirective.joinedClean = joinedClean;
164
+ currentDirective.disabled =
165
+ dirName === 'if' ||
166
+ dirName === 'ifdef' ||
167
+ dirName === 'ifndef' ||
168
+ dirName === 'elif' ||
169
+ dirName === 'else' ||
170
+ dirName === 'endif'
171
+ ? condStack.some((c) => c.parentDisabled)
172
+ : isDisabled();
173
+ directives.push(currentDirective);
174
+ currentDirective = null;
175
+ }
176
+
177
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
178
+ const raw = lines[lineIdx];
179
+ const len = raw.length;
180
+ const out = [];
181
+ const braceStart = braceDepth;
182
+ const parenStart = parenDepth;
183
+ const lineDisabled = isDisabled();
184
+
185
+ let inLineComment = false;
186
+ let seenCodeTokenOnLine = false;
187
+ let isDirectiveLine = inPreprocessor;
188
+
189
+ for (let i = 0; i < len; i++) {
190
+ const ch = raw[i];
191
+ const next = i + 1 < len ? raw[i + 1] : '';
192
+
193
+ if (inLineComment) {
194
+ out.push(' ');
195
+ continue;
196
+ }
197
+
198
+ if (inBlockComment) {
199
+ if (ch === '*' && next === '/') {
200
+ out.push(' ');
201
+ i++;
202
+ inBlockComment = false;
203
+ continue;
204
+ }
205
+ out.push(' ');
206
+ continue;
207
+ }
208
+
209
+ if (inRawString) {
210
+ if (raw.startsWith(rawEndMarker, i)) {
211
+ out.push(rawEndMarker);
212
+ i += rawEndMarker.length - 1;
213
+ inRawString = false;
214
+ rawEndMarker = '';
215
+ continue;
216
+ }
217
+ out.push(' ');
218
+ continue;
219
+ }
220
+
221
+ if (inStringQuote) {
222
+ if (ch === '\\') {
223
+ out.push(' ');
224
+ i++;
225
+ continue;
226
+ }
227
+ if (ch === inStringQuote) {
228
+ out.push(ch);
229
+ inStringQuote = null;
230
+ continue;
231
+ }
232
+ out.push(' ');
233
+ continue;
234
+ }
235
+
236
+ if (ch === '/' && next === '/') {
237
+ inLineComment = true;
238
+ out.push(' ');
239
+ i++;
240
+ continue;
241
+ }
242
+
243
+ if (ch === '/' && next === '*') {
244
+ inBlockComment = true;
245
+ out.push(' ');
246
+ i++;
247
+ continue;
248
+ }
249
+
250
+ if (!isDirectiveLine && !seenCodeTokenOnLine && ch === '#') {
251
+ isDirectiveLine = true;
252
+ inPreprocessor = true;
253
+ currentDirective = {
254
+ startIdx: lineIdx,
255
+ endIdx: lineIdx,
256
+ rawLines: [],
257
+ cleanLines: [],
258
+ name: '',
259
+ argClean: '',
260
+ joinedClean: '',
261
+ disabled: lineDisabled,
262
+ };
263
+ out.push(ch);
264
+ seenCodeTokenOnLine = true;
265
+ continue;
266
+ }
267
+
268
+ const rawStart = matchCppRawStringStart(raw, i);
269
+ if (rawStart) {
270
+ seenCodeTokenOnLine = true;
271
+ inRawString = true;
272
+ rawEndMarker = rawStart.endMarker;
273
+ out.push(raw.slice(i, rawStart.openEndIdx + 1));
274
+ i = rawStart.openEndIdx;
275
+ continue;
276
+ }
277
+
278
+ if (ch === '"') {
279
+ seenCodeTokenOnLine = true;
280
+ inStringQuote = '"';
281
+ out.push('"');
282
+ continue;
283
+ }
284
+
285
+ if (ch === "'") {
286
+ seenCodeTokenOnLine = true;
287
+ if (isDigitSeparatorQuote(raw, i)) {
288
+ out.push("'");
289
+ continue;
290
+ }
291
+ inStringQuote = "'";
292
+ out.push("'");
293
+ continue;
294
+ }
295
+
296
+ if (!/\s/.test(ch)) {
297
+ seenCodeTokenOnLine = true;
298
+ }
299
+
300
+ if (!isDirectiveLine && !lineDisabled) {
301
+ if (ch === '{') braceDepth++;
302
+ else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1);
303
+ else if (ch === '(') parenDepth++;
304
+ else if (ch === ')') parenDepth = Math.max(0, parenDepth - 1);
305
+ }
306
+
307
+ out.push(ch);
308
+ }
309
+
310
+ const hasLineContinuation = /\\\s*$/.test(raw);
311
+ if (!hasLineContinuation && inStringQuote) {
312
+ inStringQuote = null;
313
+ }
314
+
315
+ const clean = out.join('');
316
+
317
+ if (isDirectiveLine && currentDirective) {
318
+ currentDirective.endIdx = lineIdx;
319
+ currentDirective.rawLines.push(raw);
320
+ currentDirective.cleanLines.push(clean);
321
+ if (!hasLineContinuation && !inBlockComment) {
322
+ inPreprocessor = false;
323
+ finalizeDirective();
324
+ }
325
+ }
326
+
327
+ analyzed[lineIdx] = {
328
+ raw,
329
+ clean,
330
+ braceStart,
331
+ braceEnd: braceDepth,
332
+ parenStart,
333
+ parenEnd: parenDepth,
334
+ isDirective: isDirectiveLine,
335
+ disabled: lineDisabled,
336
+ };
337
+ }
338
+
339
+ if (currentDirective) {
340
+ inPreprocessor = false;
341
+ finalizeDirective();
342
+ }
343
+
344
+ return { analyzed, directives };
345
+ }
346
+
347
+ function formatMacroSignature(rawLines, maxLen = 140) {
348
+ const parts = [];
349
+ for (let i = 0; i < rawLines.length; i++) {
350
+ const line = rawLines[i].replace(/\/\/.*$/, '').replace(/\\\s*$/, '').trim();
351
+ if (line) parts.push(line);
352
+ }
353
+ let sig = parts.join(' ').replace(/\s+/g, ' ').trim();
354
+ if (sig.length > maxLen) {
355
+ sig = sig.slice(0, maxLen - 3).trimEnd() + '...';
356
+ }
357
+ return sig;
358
+ }
359
+
360
+ /**
361
+ * 提取 C/C++ #define 宏(跳过 Include Guard,保留函数式宏与多行宏,智能折叠连续常量宏)
362
+ */
363
+ function extractCCppMacros(directives, analyzed, lineOffset = 0) {
364
+ const items = [];
365
+ const activeDirectives = directives.filter((d) => !d.disabled);
366
+ const singleConstMacros = [];
367
+
368
+ for (let i = 0; i < activeDirectives.length; i++) {
369
+ const dir = activeDirectives[i];
370
+ if (dir.name !== 'define') continue;
371
+
372
+ const cleanJoined = dir.joinedClean;
373
+ const m = cleanJoined.match(/^#\s*define\s+([A-Za-z_]\w*)(?:\(([^)]*)\))?(.*)$/);
374
+ if (!m) continue;
375
+
376
+ const macroName = m[1];
377
+ const hasParenArgs = m[2] !== undefined;
378
+ const bodyClean = (m[3] || '').trim();
379
+
380
+ if (!hasParenArgs && !bodyClean && i > 0) {
381
+ const prev = activeDirectives[i - 1];
382
+ if (
383
+ (prev.name === 'ifndef' && prev.argClean === macroName) ||
384
+ (prev.name === 'if' && new RegExp(`^!\\s*defined\\s*\\(?\\s*${macroName}\\s*\\)?$`).test(prev.argClean))
385
+ ) {
386
+ continue;
387
+ }
388
+ }
389
+
390
+ const isMultiLine = dir.endIdx > dir.startIdx;
391
+ if (hasParenArgs || isMultiLine) {
392
+ items.push({
393
+ kind: 'macro',
394
+ name: macroName,
395
+ signature: formatMacroSignature(dir.rawLines),
396
+ startLine: dir.startIdx + 1 + lineOffset,
397
+ endLine: dir.endIdx + 1 + lineOffset,
398
+ depth: 0,
399
+ });
400
+ } else {
401
+ singleConstMacros.push({
402
+ name: macroName,
403
+ startIdx: dir.startIdx,
404
+ endIdx: dir.endIdx,
405
+ signature: formatMacroSignature(dir.rawLines),
406
+ });
407
+ }
408
+ }
409
+
410
+ const groups = [];
411
+ for (const mac of singleConstMacros) {
412
+ if (groups.length === 0) {
413
+ groups.push([mac]);
414
+ continue;
415
+ }
416
+ const prevGroup = groups[groups.length - 1];
417
+ const prev = prevGroup[prevGroup.length - 1];
418
+ let contiguous = mac.startIdx - prev.endIdx <= 4;
419
+ if (contiguous) {
420
+ for (let lineIdx = prev.endIdx + 1; lineIdx < mac.startIdx; lineIdx++) {
421
+ const info = analyzed[lineIdx];
422
+ if (!info) continue;
423
+ if (!info.isDirective && info.clean.trim() !== '') {
424
+ contiguous = false;
425
+ break;
426
+ }
427
+ if (info.isDirective && !/^#\s*define\b/.test(info.clean.trim())) {
428
+ contiguous = false;
429
+ break;
430
+ }
431
+ }
432
+ }
433
+ if (contiguous) {
434
+ prevGroup.push(mac);
435
+ } else {
436
+ groups.push([mac]);
437
+ }
438
+ }
439
+
440
+ const totalSingle = singleConstMacros.length;
441
+ for (const group of groups) {
442
+ if ((totalSingle <= 15 && group.length <= 3) || group.length === 1) {
443
+ for (const mac of group) {
444
+ items.push({
445
+ kind: 'macro',
446
+ name: mac.name,
447
+ signature: mac.signature,
448
+ startLine: mac.startIdx + 1 + lineOffset,
449
+ endLine: mac.endIdx + 1 + lineOffset,
450
+ depth: 0,
451
+ });
452
+ }
453
+ } else {
454
+ const anchors =
455
+ group.length <= 4
456
+ ? group.map((g) => g.name).join(', ')
457
+ : `${group[0].name}, ${group[1].name}, ..., ${group[group.length - 1].name}`;
458
+ items.push({
459
+ kind: 'macro',
460
+ name: group[0].name,
461
+ signature: `#define (${group.length} macros: ${anchors})`,
462
+ startLine: group[0].startIdx + 1 + lineOffset,
463
+ endLine: group[group.length - 1].endIdx + 1 + lineOffset,
464
+ depth: 0,
465
+ });
466
+ }
467
+ }
468
+
469
+ return items;
470
+ }
471
+
472
+ function findMatchingDelim(text, openIdx, openCh, closeCh) {
473
+ let depth = 0;
474
+ for (let i = openIdx; i < text.length; i++) {
475
+ if (text[i] === openCh) depth++;
476
+ else if (text[i] === closeCh) {
477
+ depth--;
478
+ if (depth === 0) return i;
479
+ }
480
+ }
481
+ return -1;
482
+ }
483
+
484
+ function stripCCppAttributes(text) {
485
+ let s = text;
486
+ const attrPatterns = [/\b__attribute(?:__)?\s*\(/g, /\b__declspec\s*\(/g, /\balignas\s*\(/g, /\bnoexcept\s*\(/g];
487
+ for (const re of attrPatterns) {
488
+ let match;
489
+ while ((match = re.exec(s)) !== null) {
490
+ const openIdx = s.indexOf('(', match.index);
491
+ const closeIdx = openIdx !== -1 ? findMatchingDelim(s, openIdx, '(', ')') : -1;
492
+ if (closeIdx !== -1) {
493
+ s = s.slice(0, match.index) + ' ' + s.slice(closeIdx + 1);
494
+ re.lastIndex = match.index;
495
+ } else {
496
+ break;
497
+ }
498
+ }
499
+ }
500
+ let changed = true;
501
+ while (changed) {
502
+ changed = false;
503
+ const idx = s.indexOf('[[');
504
+ if (idx !== -1) {
505
+ const closeIdx = s.indexOf(']]', idx + 2);
506
+ if (closeIdx !== -1) {
507
+ s = s.slice(0, idx) + ' ' + s.slice(closeIdx + 2);
508
+ changed = true;
509
+ }
510
+ }
511
+ }
512
+ return s;
513
+ }
514
+
515
+ function stripLeadingTemplate(text) {
516
+ const trimmed = text.trimStart();
517
+ if (!/^template\s*</.test(trimmed)) return trimmed;
518
+ const ltIdx = trimmed.indexOf('<');
519
+ let depth = 0;
520
+ for (let i = ltIdx; i < trimmed.length; i++) {
521
+ if (trimmed[i] === '<') depth++;
522
+ else if (trimmed[i] === '>') {
523
+ depth--;
524
+ if (depth === 0) {
525
+ return trimmed.slice(i + 1).trimStart();
526
+ }
527
+ }
528
+ }
529
+ return trimmed;
530
+ }
531
+
532
+ function findCCppDeclarationRange(analyzed, startIdx) {
533
+ let paren = 0;
534
+ let bracket = 0;
535
+ let brace = 0;
536
+ let seenBlock = false;
537
+ let firstBlockHeaderEndIdx = startIdx;
538
+ let requiresSemiAfterBlock = null;
539
+ let headerBeforeFirstBrace = '';
540
+ let braceOpenLineIdx = -1;
541
+ let braceOpenCol = -1;
542
+ let braceCloseLineIdx = -1;
543
+ let braceCloseCol = -1;
544
+
545
+ function peekNextNonSpaceChar(lineIdx, colIdx) {
546
+ for (let j = lineIdx; j < analyzed.length; j++) {
547
+ if (analyzed[j].isDirective || analyzed[j].disabled) continue;
548
+ const line = analyzed[j].clean;
549
+ const startK = j === lineIdx ? colIdx + 1 : 0;
550
+ for (let k = startK; k < line.length; k++) {
551
+ if (!/\s/.test(line[k])) return line[k];
552
+ }
553
+ }
554
+ return '';
555
+ }
556
+
557
+ function isMemberInitBrace(prefixClean) {
558
+ const noAttr = stripLeadingTemplate(stripCCppAttributes(prefixClean)).trim();
559
+ if (/^(?:class|struct|union|enum|namespace|extern)\b/.test(noAttr)) return false;
560
+ if (/=\s*$/.test(noAttr)) return false;
561
+
562
+ let p = 0;
563
+ let sawParamClose = false;
564
+ let initColonIdx = -1;
565
+ for (let k = 0; k < noAttr.length; k++) {
566
+ const c = noAttr[k];
567
+ if (c === '(') p++;
568
+ else if (c === ')') {
569
+ p = Math.max(0, p - 1);
570
+ if (p === 0) sawParamClose = true;
571
+ } else if (c === ':' && p === 0 && sawParamClose) {
572
+ const prevC = k > 0 ? noAttr[k - 1] : '';
573
+ const nextC = k + 1 < noAttr.length ? noAttr[k + 1] : '';
574
+ if (prevC !== ':' && nextC !== ':') {
575
+ initColonIdx = k;
576
+ break;
577
+ }
578
+ }
579
+ }
580
+ if (initColonIdx === -1) return false;
581
+
582
+ const afterColon = noAttr.slice(initColonIdx + 1);
583
+ let cp = 0;
584
+ let cb = 0;
585
+ let ca = 0;
586
+ let lastComma = -1;
587
+ for (let k = 0; k < afterColon.length; k++) {
588
+ const c = afterColon[k];
589
+ if (c === '(') cp++;
590
+ else if (c === ')') cp = Math.max(0, cp - 1);
591
+ else if (c === '{') cb++;
592
+ else if (c === '}') cb = Math.max(0, cb - 1);
593
+ else if (c === '<' && cp === 0 && cb === 0) ca++;
594
+ else if (c === '>' && cp === 0 && cb === 0) ca = Math.max(0, ca - 1);
595
+ else if (c === ',' && cp === 0 && cb === 0 && ca === 0) lastComma = k;
596
+ }
597
+ const lastInitItem = afterColon.slice(lastComma + 1).trim();
598
+ if (!lastInitItem) return false;
599
+ if (lastInitItem.endsWith(')') || lastInitItem.endsWith('}')) return false;
600
+ return true;
601
+ }
602
+
603
+ let sawDirectiveSincePrevCode = false;
604
+
605
+ for (let j = startIdx; j < analyzed.length; j++) {
606
+ const info = analyzed[j];
607
+ if (info.isDirective || info.disabled) {
608
+ sawDirectiveSincePrevCode = true;
609
+ continue;
610
+ }
611
+ if (j > startIdx && sawDirectiveSincePrevCode) {
612
+ const startBraceDepth = analyzed[startIdx].braceStart;
613
+ brace = Math.max(0, info.braceStart - startBraceDepth);
614
+ sawDirectiveSincePrevCode = false;
615
+ }
616
+ const line = info.clean;
617
+
618
+ for (let k = 0; k < line.length; k++) {
619
+ const ch = line[k];
620
+ if (!seenBlock) headerBeforeFirstBrace += ch;
621
+
622
+ if (ch === '(') paren++;
623
+ else if (ch === ')') paren = Math.max(0, paren - 1);
624
+ else if (ch === '[') bracket++;
625
+ else if (ch === ']') bracket = Math.max(0, bracket - 1);
626
+ else if (ch === '{') {
627
+ if (paren === 0 && bracket === 0) {
628
+ if (!seenBlock && brace === 0) {
629
+ const prefix = headerBeforeFirstBrace.slice(0, -1);
630
+ if (!isMemberInitBrace(prefix)) {
631
+ seenBlock = true;
632
+ firstBlockHeaderEndIdx = j;
633
+ braceOpenLineIdx = j;
634
+ braceOpenCol = k;
635
+ const noAttr = stripLeadingTemplate(stripCCppAttributes(prefix)).trim();
636
+ const isPureTypeHeader =
637
+ /^(?:typedef\b|class\b|struct\b|union\b|enum\b)/.test(noAttr) &&
638
+ !/\(/.test(noAttr.split(':')[0]);
639
+ requiresSemiAfterBlock = isPureTypeHeader || /=\s*$/.test(noAttr);
640
+ }
641
+ }
642
+ brace++;
643
+ }
644
+ } else if (ch === '}') {
645
+ if (paren === 0 && bracket === 0 && brace > 0) {
646
+ brace--;
647
+ if (brace === 0 && seenBlock) {
648
+ braceCloseLineIdx = j;
649
+ braceCloseCol = k;
650
+ if (!requiresSemiAfterBlock) {
651
+ const nextCh = peekNextNonSpaceChar(j, k);
652
+ if (nextCh === ';') {
653
+ continue;
654
+ }
655
+ return {
656
+ endIdx: j,
657
+ headerEndIdx: firstBlockHeaderEndIdx,
658
+ hasBlock: true,
659
+ braceOpenLineIdx,
660
+ braceOpenCol,
661
+ braceCloseLineIdx,
662
+ braceCloseCol,
663
+ };
664
+ }
665
+ } else if (brace === 0 && !seenBlock) {
666
+ headerBeforeFirstBrace += ' ';
667
+ }
668
+ }
669
+ } else if (ch === ';') {
670
+ if (paren === 0 && bracket === 0 && brace === 0) {
671
+ return {
672
+ endIdx: j,
673
+ headerEndIdx: seenBlock ? firstBlockHeaderEndIdx : j,
674
+ hasBlock: seenBlock,
675
+ braceOpenLineIdx,
676
+ braceOpenCol,
677
+ braceCloseLineIdx: seenBlock ? braceCloseLineIdx : -1,
678
+ braceCloseCol: seenBlock ? braceCloseCol : -1,
679
+ };
680
+ }
681
+ }
682
+ }
683
+
684
+ if (!seenBlock) headerBeforeFirstBrace += ' ';
685
+ }
686
+
687
+ return {
688
+ endIdx: analyzed.length - 1,
689
+ headerEndIdx: seenBlock ? firstBlockHeaderEndIdx : analyzed.length - 1,
690
+ hasBlock: seenBlock,
691
+ braceOpenLineIdx,
692
+ braceOpenCol,
693
+ braceCloseLineIdx: seenBlock ? analyzed.length - 1 : -1,
694
+ braceCloseCol: -1,
695
+ };
696
+ }
697
+
698
+ function hasTopLevelAssignmentBeforeBrace(text) {
699
+ let p = 0;
700
+ let b = 0;
701
+ let a = 0;
702
+ for (let i = 0; i < text.length; i++) {
703
+ const ch = text[i];
704
+ if (ch === '(') p++;
705
+ else if (ch === ')') p = Math.max(0, p - 1);
706
+ else if (ch === '[') b++;
707
+ else if (ch === ']') b = Math.max(0, b - 1);
708
+ else if (ch === '<' && p === 0 && b === 0) a++;
709
+ else if (ch === '>' && p === 0 && b === 0) a = Math.max(0, a - 1);
710
+ else if (ch === '=' && p === 0 && b === 0 && a === 0) {
711
+ const next = text[i + 1] || '';
712
+ if (next !== '=') return true;
713
+ }
714
+ }
715
+ return false;
716
+ }
717
+
718
+ function stripTrailingMemberInitList(text) {
719
+ let p = 0;
720
+ let b = 0;
721
+ let sawParam = false;
722
+ for (let i = 0; i < text.length; i++) {
723
+ const ch = text[i];
724
+ if (ch === '(') p++;
725
+ else if (ch === ')') {
726
+ p = Math.max(0, p - 1);
727
+ if (p === 0) sawParam = true;
728
+ } else if (ch === '[') b++;
729
+ else if (ch === ']') b = Math.max(0, b - 1);
730
+ else if (ch === ':' && p === 0 && b === 0 && sawParam) {
731
+ const prev = i > 0 ? text[i - 1] : '';
732
+ const next = i + 1 < text.length ? text[i + 1] : '';
733
+ if (prev !== ':' && next !== ':') {
734
+ return text.slice(0, i);
735
+ }
736
+ }
737
+ }
738
+ return text;
739
+ }
740
+
741
+ function extractCFunctionName(headerClean, options = {}) {
742
+ const { hasBlock = false, inClass = false, isHeader = false, classNames = [] } = options;
743
+
744
+ let s = stripLeadingTemplate(stripCCppAttributes(headerClean));
745
+ s = stripTrailingMemberInitList(s).trim();
746
+ if (!s) return null;
747
+
748
+ const topParens = [];
749
+ let p = 0;
750
+ let b = 0;
751
+ for (let i = 0; i < s.length; i++) {
752
+ const ch = s[i];
753
+ if (ch === '(' && b === 0) {
754
+ if (p === 0) topParens.push({ start: i, end: -1 });
755
+ p++;
756
+ } else if (ch === ')' && b === 0) {
757
+ p = Math.max(0, p - 1);
758
+ if (p === 0 && topParens.length > 0 && topParens[topParens.length - 1].end === -1) {
759
+ topParens[topParens.length - 1].end = i;
760
+ }
761
+ } else if (ch === '[') {
762
+ b++;
763
+ } else if (ch === ']') {
764
+ b = Math.max(0, b - 1);
765
+ }
766
+ }
767
+
768
+ if (topParens.length === 0) return null;
769
+
770
+ const paramParen = topParens[topParens.length - 1];
771
+ if (paramParen.end === -1) return null;
772
+
773
+ const afterLastParen = s.slice(paramParen.end + 1).trim();
774
+ const prefixBeforeParen = s.slice(0, paramParen.start).trimEnd();
775
+
776
+ // 优先检查 C++ operator 重载(如 `operator()(int x)`、`operator==`、`operator<<`)
777
+ const opMatch = prefixBeforeParen.match(
778
+ /\b((?:[A-Za-z_]\w*::)*operator\s*(?:\(\)|\[\]|new\s*\[\]|delete\s*\[\]|->\*|->|<=>|<<=|>>=|<<|>>|<=|>=|==|!=|&&|\|\||\+\+|--|[+\-*/%^&|~!<>=,]))\s*$/
779
+ );
780
+ if (opMatch) {
781
+ return opMatch[1].replace(/\s+/g, '');
782
+ }
783
+
784
+ // 返回函数指针的函数声明:`ret (*fn(args))(ret_args)`
785
+ if (prefixBeforeParen.endsWith(')') && topParens.length >= 2) {
786
+ const innerParen = topParens[topParens.length - 2];
787
+ const innerContent = s.slice(innerParen.start + 1, innerParen.end);
788
+ const fnPtrDeclMatch = innerContent.match(
789
+ /^\s*\*\s*((?:[A-Za-z_]\w*::)*[A-Za-z_]\w*)\s*\(/
790
+ );
791
+ if (fnPtrDeclMatch) {
792
+ const name = fnPtrDeclMatch[1];
793
+ const baseName = name.split('::').pop();
794
+ if (C_CONTROL_KEYWORDS.has(baseName)) return null;
795
+ return name;
796
+ }
797
+ return null;
798
+ }
799
+
800
+ const nameMatch = prefixBeforeParen.match(/((?:~?[A-Za-z_]\w*::)*~?[A-Za-z_]\w*)\s*$/);
801
+ if (!nameMatch) return null;
802
+
803
+ const fullName = nameMatch[1];
804
+ const shortName = fullName.split('::').pop();
805
+ if (C_CONTROL_KEYWORDS.has(shortName)) {
806
+ return null;
807
+ }
808
+
809
+ const retPrefix = prefixBeforeParen.slice(0, prefixBeforeParen.length - fullName.length).trim();
810
+ if (/=/.test(retPrefix) && !/\boperator\b/.test(retPrefix)) {
811
+ return null;
812
+ }
813
+
814
+ if (
815
+ afterLastParen &&
816
+ !/^(?:const|volatile|override|final|noexcept|throw\b|->|=\s*(?:0|default|delete)|&|&&|;|\s)*$/.test(
817
+ afterLastParen
818
+ )
819
+ ) {
820
+ if (/[=+]/.test(afterLastParen) && !/^=\s*(?:0|default|delete)\s*;?\s*$/.test(afterLastParen)) {
821
+ return null;
822
+ }
823
+ }
824
+
825
+ if (!hasBlock) {
826
+ if (!inClass) {
827
+ if (!retPrefix) return null;
828
+ if (!isHeader && !/\bextern\b/.test(retPrefix)) {
829
+ return null;
830
+ }
831
+ } else {
832
+ const isCtorOrDtor = shortName.startsWith('~') || classNames.includes(shortName);
833
+ if (!retPrefix && !isCtorOrDtor) {
834
+ return null;
835
+ }
836
+ }
837
+ }
838
+
839
+ return fullName;
840
+ }
841
+
842
+ function buildCCppSignature(analyzed, startIdx, range, suffixOverride = '', maxLen = 140) {
843
+ const limitEnd = range.hasBlock
844
+ ? Math.min(range.headerEndIdx, startIdx + 20)
845
+ : Math.min(range.endIdx, startIdx + 20);
846
+ const parts = [];
847
+
848
+ for (let i = startIdx; i <= limitEnd; i++) {
849
+ const info = analyzed[i];
850
+ if (!info || info.isDirective || info.disabled) continue;
851
+ let slice = info.clean;
852
+ if (range.hasBlock && i === range.braceOpenLineIdx && range.braceOpenCol !== -1) {
853
+ slice = slice.slice(0, range.braceOpenCol);
854
+ }
855
+ const trimmed = slice.trim();
856
+ if (trimmed) parts.push(trimmed);
857
+ }
858
+
859
+ let sig = parts.join(' ').replace(/\s+/g, ' ').replace(/;+\s*$/, '').trim();
860
+ if (suffixOverride) {
861
+ sig = `${sig} ${suffixOverride}`.replace(/\s+/g, ' ').trim();
862
+ }
863
+ if (sig.length > maxLen) {
864
+ sig = sig.slice(0, maxLen - 3).trimEnd() + '...';
865
+ }
866
+ return sig;
867
+ }
868
+
869
+ /**
870
+ * 解析 C / C++ 源码与头文件(.c, .cpp, .cc, .cxx, .c++, .h, .hpp, .hh, .hxx, .h++, .inl, .inc)
871
+ */
872
+ function parseCCpp(lines, ext = '.c', options = {}) {
873
+ const lineOffset = options.lineOffset || 0;
874
+ const isHeader = C_HEADER_EXTS.has(ext);
875
+ const isPlainC = ext === '.c';
876
+ const { analyzed, directives } = preprocessCCppLines(lines);
877
+
878
+ const macroItems = extractCCppMacros(directives, analyzed, lineOffset);
879
+ const declItems = [];
880
+ const containerStack = [];
881
+
882
+ for (let i = 0; i < analyzed.length; i++) {
883
+ while (containerStack.length > 0 && i > containerStack[containerStack.length - 1].endIdx) {
884
+ containerStack.pop();
885
+ }
886
+
887
+ const info = analyzed[i];
888
+ if (info.isDirective || info.disabled) continue;
889
+
890
+ let trimmed = info.clean.trim();
891
+ if (!trimmed) continue;
892
+
893
+ trimmed = trimmed.replace(/^(?:\}\s*;?\s*)+/, '').trim();
894
+ trimmed = trimmed.replace(/^(?:public|protected|private)(?:\s+slots)?\s*:/, '').trim();
895
+ trimmed = trimmed.replace(/^(?:signals|Q_SIGNALS|slots|Q_SLOTS)\s*:/, '').trim();
896
+ if (!trimmed || trimmed === ';') continue;
897
+
898
+ const topContainer = containerStack.length > 0 ? containerStack[containerStack.length - 1] : null;
899
+ const activeBodyDepth = topContainer ? topContainer.bodyDepth : 0;
900
+ const currentDepth = containerStack.filter((c) => !c.transparent).length;
901
+
902
+ if (info.braceStart !== activeBodyDepth) continue;
903
+
904
+ const range = findCCppDeclarationRange(analyzed, i);
905
+
906
+ const headerParts = [];
907
+ const headerScanEnd = range.hasBlock ? range.braceOpenLineIdx : range.endIdx;
908
+ for (let k = i; k <= headerScanEnd; k++) {
909
+ const kInfo = analyzed[k];
910
+ if (!kInfo || kInfo.isDirective || kInfo.disabled) continue;
911
+ let seg = kInfo.clean;
912
+ if (k === i) {
913
+ seg = seg.trimStart().replace(/^(?:\}\s*;?\s*)+/, '').trimStart();
914
+ seg = seg.replace(/^(?:public|protected|private)(?:\s+slots)?\s*:/, '').trimStart();
915
+ seg = seg.replace(/^(?:signals|Q_SIGNALS|slots|Q_SLOTS)\s*:/, '').trimStart();
916
+ }
917
+ if (range.hasBlock && k === range.braceOpenLineIdx && range.braceOpenCol !== -1) {
918
+ seg = seg.slice(0, range.braceOpenCol);
919
+ }
920
+ const t = seg.trim();
921
+ if (t) headerParts.push(t);
922
+ }
923
+ let headerClean = headerParts.join(' ').replace(/\s+/g, ' ').replace(/;+\s*$/, '').trim();
924
+ if (!headerClean) {
925
+ i = range.endIdx;
926
+ continue;
927
+ }
928
+
929
+ if (/^(?:using\b|static_assert\b|_Static_assert\b|friend\b)/.test(headerClean)) {
930
+ i = range.endIdx;
931
+ continue;
932
+ }
933
+
934
+ // 1. extern "C" / extern "C++" 透明容器或单行声明前缀
935
+ const externBlockMatch = headerClean.match(/^extern\s+"[^"]*"\s*$/);
936
+ if (externBlockMatch && range.hasBlock) {
937
+ if (range.endIdx > range.headerEndIdx) {
938
+ containerStack.push({
939
+ type: 'extern_c',
940
+ bodyDepth: activeBodyDepth + 1,
941
+ endIdx: range.endIdx,
942
+ transparent: true,
943
+ name: '',
944
+ });
945
+ i = range.headerEndIdx;
946
+ } else {
947
+ i = range.endIdx;
948
+ }
949
+ continue;
950
+ }
951
+ if (/^extern\s+"[^"]*"\s+/.test(headerClean)) {
952
+ headerClean = headerClean.replace(/^extern\s+"[^"]*"\s+/, '').trim();
953
+ }
954
+
955
+ let tailClean = '';
956
+ if (range.hasBlock && range.braceCloseLineIdx !== -1) {
957
+ const tailParts = [];
958
+ for (let k = range.braceCloseLineIdx; k <= range.endIdx; k++) {
959
+ const kInfo = analyzed[k];
960
+ if (!kInfo || kInfo.isDirective || kInfo.disabled) continue;
961
+ let seg = kInfo.clean;
962
+ if (k === range.braceCloseLineIdx && range.braceCloseCol !== -1) {
963
+ seg = seg.slice(range.braceCloseCol + 1);
964
+ }
965
+ const t = seg.replace(/;+\s*$/, '').trim();
966
+ if (t) tailParts.push(t);
967
+ }
968
+ tailClean = tailParts.join(' ').replace(/\s+/g, ' ').trim();
969
+ }
970
+
971
+ const headerNoAttr = stripLeadingTemplate(stripCCppAttributes(headerClean)).trim();
972
+
973
+ // 2. C++ namespace
974
+ const nsMatch = headerNoAttr.match(
975
+ /^(?:inline\s+)?namespace(?:\s+([A-Za-z_]\w*(?:::[A-Za-z_]\w*)*))?\s*$/
976
+ );
977
+ if (nsMatch && range.hasBlock) {
978
+ const nsName = nsMatch[1] || '(anonymous)';
979
+ declItems.push({
980
+ kind: 'namespace',
981
+ name: nsName,
982
+ signature: buildCCppSignature(analyzed, i, range),
983
+ startLine: i + 1 + lineOffset,
984
+ endLine: range.endIdx + 1 + lineOffset,
985
+ depth: currentDepth,
986
+ });
987
+ if (range.endIdx > range.headerEndIdx) {
988
+ containerStack.push({
989
+ type: 'namespace',
990
+ bodyDepth: activeBodyDepth + 1,
991
+ endIdx: range.endIdx,
992
+ transparent: false,
993
+ name: nsName,
994
+ });
995
+ i = range.headerEndIdx;
996
+ } else {
997
+ i = range.endIdx;
998
+ }
999
+ continue;
1000
+ }
1001
+
1002
+ // 3. typedef(struct/union/enum 块别名与函数指针/常规别名)
1003
+ if (/^typedef\b/.test(headerNoAttr)) {
1004
+ let aliasName = 'typedef';
1005
+ let sig = '';
1006
+ if (range.hasBlock) {
1007
+ const aliasMatch = tailClean.match(/\**\s*([A-Za-z_]\w*)(?:\s*\[[^\]]*\])?(?:\s*,|$)/);
1008
+ if (aliasMatch) aliasName = aliasMatch[1];
1009
+ const suffix = tailClean ? `{ ... } ${tailClean}` : '{ ... }';
1010
+ sig = buildCCppSignature(analyzed, i, range, suffix);
1011
+ } else {
1012
+ const fnPtrMatch = headerClean.match(/\(\s*\*\s*([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*\)/);
1013
+ if (fnPtrMatch) {
1014
+ aliasName = fnPtrMatch[1];
1015
+ } else {
1016
+ const simpleMatch = headerClean
1017
+ .replace(/(?:\s*\[[^\]]*\])+\s*$/, '')
1018
+ .match(/([A-Za-z_]\w*)\s*$/);
1019
+ if (simpleMatch) aliasName = simpleMatch[1];
1020
+ }
1021
+ sig = buildCCppSignature(analyzed, i, range);
1022
+ }
1023
+
1024
+ declItems.push({
1025
+ kind: 'typedef',
1026
+ name: aliasName,
1027
+ signature: sig,
1028
+ startLine: i + 1 + lineOffset,
1029
+ endLine: range.endIdx + 1 + lineOffset,
1030
+ depth: currentDepth,
1031
+ });
1032
+ i = range.endIdx;
1033
+ continue;
1034
+ }
1035
+
1036
+ // 4. class / struct / union / enum 定义
1037
+ const typeMatch = headerNoAttr.match(
1038
+ /^(class|struct|union|enum(?:\s+class|\s+struct)?)(?:\s+(?:[A-Za-z_]\w*::)*([A-Za-z_]\w*))?(?:\s*:\s*.*)?$/
1039
+ );
1040
+ const hasParenInTypeHeader = /\(/.test(headerNoAttr.split(':')[0]);
1041
+ if (typeMatch && range.hasBlock && !hasParenInTypeHeader) {
1042
+ const rawKind = typeMatch[1].split(/\s+/)[0];
1043
+ const typeName =
1044
+ typeMatch[2] ||
1045
+ (tailClean ? tailClean.replace(/^[*&\s]+/, '').split(/[\s,;=\[]/)[0] : '(anonymous)');
1046
+ const suffix = tailClean && !tailClean.startsWith('=') ? `{ ... } ${tailClean}` : '';
1047
+ declItems.push({
1048
+ kind: rawKind,
1049
+ name: typeName,
1050
+ signature: buildCCppSignature(analyzed, i, range, suffix),
1051
+ startLine: i + 1 + lineOffset,
1052
+ endLine: range.endIdx + 1 + lineOffset,
1053
+ depth: currentDepth,
1054
+ });
1055
+
1056
+ const shouldEnterScope =
1057
+ range.endIdx > range.headerEndIdx &&
1058
+ (rawKind === 'class' || (rawKind === 'struct' && !isPlainC));
1059
+
1060
+ if (shouldEnterScope) {
1061
+ containerStack.push({
1062
+ type: rawKind,
1063
+ bodyDepth: activeBodyDepth + 1,
1064
+ endIdx: range.endIdx,
1065
+ transparent: false,
1066
+ name: typeName,
1067
+ });
1068
+ i = range.headerEndIdx;
1069
+ } else {
1070
+ i = range.endIdx;
1071
+ }
1072
+ continue;
1073
+ }
1074
+
1075
+ // 5. 大型顶层静态初始化表 / 驱动 ops 表(带 = { ... } 且跨行 >= 4 行)
1076
+ const inClassContainer =
1077
+ topContainer && (topContainer.type === 'class' || topContainer.type === 'struct');
1078
+ if (range.hasBlock && !inClassContainer && hasTopLevelAssignmentBeforeBrace(headerClean)) {
1079
+ const spanLines = range.endIdx - i + 1;
1080
+ if (spanLines >= 4) {
1081
+ const lhs = headerClean.split('=')[0].replace(/(?:\s*\[[^\]]*\])+\s*$/, '').trim();
1082
+ const varMatch = lhs.match(/([A-Za-z_]\w*)\s*$/);
1083
+ const varName = varMatch ? varMatch[1] : 'var';
1084
+ declItems.push({
1085
+ kind: 'var',
1086
+ name: varName,
1087
+ signature: buildCCppSignature(analyzed, i, range, '= { ... }').replace(
1088
+ /=\s*=\s*\{\s*\.\.\.\s*\}/,
1089
+ '= { ... }'
1090
+ ),
1091
+ startLine: i + 1 + lineOffset,
1092
+ endLine: range.endIdx + 1 + lineOffset,
1093
+ depth: currentDepth,
1094
+ });
1095
+ }
1096
+ i = range.endIdx;
1097
+ continue;
1098
+ }
1099
+
1100
+ // 6. 函数定义与头文件/类内函数原型(与上游契约对齐:顶层使用 'function',类内使用 'method')
1101
+ const classNames = containerStack
1102
+ .filter((c) => c.type === 'class' || c.type === 'struct')
1103
+ .map((c) => c.name);
1104
+ const fnName = extractCFunctionName(headerClean, {
1105
+ hasBlock: range.hasBlock,
1106
+ inClass: Boolean(inClassContainer),
1107
+ isHeader,
1108
+ classNames,
1109
+ });
1110
+
1111
+ if (fnName) {
1112
+ declItems.push({
1113
+ kind: inClassContainer ? 'method' : 'function',
1114
+ name: fnName,
1115
+ signature: buildCCppSignature(analyzed, i, range),
1116
+ startLine: i + 1 + lineOffset,
1117
+ endLine: range.endIdx + 1 + lineOffset,
1118
+ depth: currentDepth,
1119
+ });
1120
+ }
1121
+
1122
+ i = range.endIdx;
1123
+ }
1124
+
1125
+ return [...macroItems, ...declItems].sort(
1126
+ (a, b) => a.startLine - b.startLine || a.depth - b.depth
1127
+ );
1128
+ }
1129
+
1130
+ module.exports = {
1131
+ C_HEADER_EXTS,
1132
+ parseCCpp,
1133
+ };