Repository navigation
Expand file tree
/
Copy pathc-cpp.ts
More file actions
3093 lines (2989 loc) · 151 KB
/
Copy pathc-cpp.ts
File metadata and controls
3093 lines (2989 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getChildByField, getNodeText } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
/**
* Resolve the declared identifier inside a C declarator. A `declaration`'s
* `declarator` field nests the name through `init_declarator` (with value),
* `pointer_declarator`/`array_declarator`/`parenthesized_declarator`
* wrappers (each via their own `declarator` field) down to an `identifier`.
* A `function_declarator` means the declaration is a function prototype (or a
* function-pointer var) — return null so it isn't extracted as a variable.
*/
export function cDeclaratorIdentifier(node: SyntaxNode | null): SyntaxNode | null {
let cur: SyntaxNode | null = node;
let guard = 0;
while (cur && guard++ < 12) {
switch (cur.type) {
case 'identifier':
return cur;
case 'function_declarator':
return null;
case 'init_declarator':
case 'pointer_declarator':
case 'array_declarator':
case 'parenthesized_declarator':
cur = getChildByField(cur, 'declarator');
break;
default:
return null;
}
}
return null;
}
/**
* Whether a C or Objective-C declaration is a constant: a `const` or
* `static const` file-scope declaration carries a `type_qualifier` child
* reading "const". Extracted as `constant`, plain globals as `variable`. A
* `const` inside a pointer declarator (`char *const p`) qualifies the
* pointer, and the declaration stays a variable.
*/
export function isConstDeclaration(node: SyntaxNode): boolean {
return node.namedChildren.some((c: SyntaxNode) => c.type === 'type_qualifier' && c.text === 'const');
}
/** C and C++ specifiers that define a class-like type, or an enum, when they carry a body (C has no `class_specifier`). */
const CLASS_LIKE_SPECIFIERS = new Set(['class_specifier', 'struct_specifier', 'union_specifier', 'enum_specifier']);
/** Conditional compilation a class body can hold members in. */
const MEMBER_CONDITIONALS = new Set(['preproc_if', 'preproc_ifdef', 'preproc_else', 'preproc_elif', 'preproc_elifdef']);
/** A type the program computes (`decltype(x)`, `auto`), which names no declaration. */
const COMPUTED_TYPE_SPECIFIERS = new Set(['decltype', 'placeholder_type_specifier']);
/**
* A name of the C++ standard library, or a type C itself gives a name the
* grammars read like any other. A project's copy of one is a compiler shim
* (jemalloc's msvc_compat/C99/stdbool.h), which code elsewhere never means.
*/
const C_STANDARD_TYPE_NAME = /^(?:(?:::\s*)?std\s*::|(?:_Bool|_Complex|wchar_t|char(?:8|16|32)_t|u?intmax_t|u?int_(?:least|fast)\d+_t|max_align_t|nullptr_t)$)/;
/** What a declarator's next part is: a field where the grammar gives one, the first named child where it doesn't. */
function innerDeclarator(declarator: SyntaxNode): SyntaxNode | null {
return getChildByField(declarator, 'declarator') ?? declarator.namedChild(0);
}
/**
* Whether a member declarator declares a member function (`Status Get(int);`,
* `Foo* Make();`, `Slice operator[](int);`), rather than data, which may be a
* pointer to a function (`void (*cb)(int);`), whose function declarator wraps
* a parenthesized one.
*/
function declaresMemberFunction(declarator: SyntaxNode): boolean {
let d: SyntaxNode | null = declarator;
while (d && (d.type === 'pointer_declarator' || d.type === 'reference_declarator')) d = innerDeclarator(d);
return d?.type === 'function_declarator' && getChildByField(d, 'declarator')?.type !== 'parenthesized_declarator';
}
/** Is this class-like specifier an unnamed member of another (`struct S { union { … } u; };`)? */
export function isUnnamedMemberType(specifier: SyntaxNode): boolean {
return !getChildByField(specifier, 'name') && specifier.parent?.type === 'field_declaration';
}
/** A type name a declaration writes: the name as references carry it, and the node it is read at. */
export interface CTypeName {
name: string;
node: SyntaxNode;
}
/**
* The type names a C or C++ class, struct or union's members are declared
* with, in source order: `pause_event` in `pause_event by_value;`, `*p`, `a[3]`
* or `(*cb)(pause_event *)`, the `struct` or `enum` a member names by its tag
* (`struct client *c`), and whatever a template's arguments name, in
* `std::vector<Foo>` too. `specifier` is the class's own, carrying the body;
* `ownName` is what the index calls it, which a typedef may decide.
*
* A name inside an unnamed member (`union { Foo a; }`, `struct { Foo a; } s;`)
* is the holder's: its members are members of the holder, and nothing can name
* the unnamed type (isUnnamedMemberType). A member function's return type
* counts, since a member a macro trails reads the same (`Version* v GUARDED_BY(mu);`),
* but not its parameters. Not read: builtins; a type of `std`, though its
* template arguments are; the class's own name, which a list's `next` writes;
* a type the program computes; a nested definition that declares no member
* (`class Rep;`, `struct Node { … };`).
*
* Mirrored in the kernel (ccpp/mod.rs).
*/
export function cMemberTypeNames(specifier: SyntaxNode, ownName: string, source: string): CTypeName[] {
const names: CTypeName[] = [];
const own = new Set([ownName]);
const tag = getChildByField(specifier, 'name');
if (tag) own.add(stripCppTemplateArgs(getNodeText(tag, source)));
const body = getChildByField(specifier, 'body');
if (body) collectMemberTypeNames(body, own, source, names);
return names;
}
/**
* The type names a C or C++ alias is declared with: `redisObject` in `typedef
* struct redisObject robj;`, `Foo` in `using Foos = std::vector<Foo>;`. Code
* names the alias, so this is how a change to the type reaches what holds one.
* Skipped as in cMemberTypeNames: `typedef struct dict dict;` names no other type.
*/
export function cAliasTypeNames(alias: SyntaxNode, ownName: string, source: string): CTypeName[] {
const names: CTypeName[] = [];
const own = new Set([ownName]);
const type = getChildByField(alias, 'type');
if (type) collectCTypeNames(type, own, source, names);
for (const declarator of alias.childrenForFieldName('declarator')) {
if (declarator) collectDeclaratorTypeNames(declarator, own, source, names);
}
return names;
}
function collectMemberTypeNames(list: SyntaxNode, own: ReadonlySet<string>, source: string, names: CTypeName[]): void {
for (const child of list.namedChildren) {
if (MEMBER_CONDITIONALS.has(child.type)) {
collectMemberTypeNames(child, own, source, names);
continue;
}
if (child.type !== 'field_declaration') continue;
const type = getChildByField(child, 'type');
if (!type) continue;
const declarators = child.childrenForFieldName('declarator').filter((d: SyntaxNode | null): d is SyntaxNode => !!d);
const unnamedBody = CLASS_LIKE_SPECIFIERS.has(type.type) && !getChildByField(type, 'name')
? getChildByField(type, 'body')
: null;
if (unnamedBody) collectMemberTypeNames(unnamedBody, own, source, names);
else if (declarators.length > 0) collectCTypeNames(type, own, source, names);
for (const declarator of declarators) {
if (!declaresMemberFunction(declarator)) collectDeclaratorTypeNames(declarator, own, source, names);
}
}
}
/** The types a declarator names, past the type written before it: a function pointer's parameters. */
function collectDeclaratorTypeNames(declarator: SyntaxNode, own: ReadonlySet<string>, source: string, names: CTypeName[]): void {
if (declarator.type === 'function_declarator') {
const parameters = getChildByField(declarator, 'parameters');
if (parameters) collectCTypeNames(parameters, own, source, names);
}
if (!declarator.type.endsWith('declarator')) return;
const inner = innerDeclarator(declarator);
if (inner) collectDeclaratorTypeNames(inner, own, source, names);
}
/** Collects the type names under `node` onto `names`, in source order. */
function collectCTypeNames(node: SyntaxNode, own: ReadonlySet<string>, source: string, names: CTypeName[]): void {
if (COMPUTED_TYPE_SPECIFIERS.has(node.type)) return;
if (node.type === 'type_identifier' || node.type === 'qualified_identifier' || node.type === 'template_type') {
const name = stripCppTemplateArgs(getNodeText(node, source)).trim();
if (name && !own.has(name) && !C_STANDARD_TYPE_NAME.test(name)) names.push({ name, node });
collectTemplateArguments(node, own, source, names);
return;
}
const tag = CLASS_LIKE_SPECIFIERS.has(node.type) ? getChildByField(node, 'name') : null;
for (const c of tag ? [tag] : node.namedChildren) collectCTypeNames(c, own, source, names);
}
/** The types the template arguments of a written name name, wherever in the name they are. */
function collectTemplateArguments(node: SyntaxNode, own: ReadonlySet<string>, source: string, names: CTypeName[]): void {
for (const c of node.namedChildren) {
if (c.type === 'template_argument_list') collectCTypeNames(c, own, source, names);
else if (c.type === 'qualified_identifier' || c.type === 'template_type') collectTemplateArguments(c, own, source, names);
}
}
/**
* Whether a C/C++ type specifier defines a class, struct, union or enum, as
* opposed to naming one (`struct Foo *p`, the forward declaration `class Foo;`).
*/
export function isClassLikeDefinition(node: SyntaxNode): boolean {
return CLASS_LIKE_SPECIFIERS.has(node.type) && getChildByField(node, 'body') !== null;
}
/**
* The `declaration` a class, struct, union or enum is defined in the type of —
* `struct Foo { … } foo;` — or null for one written on its own, in a typedef or
* in a member's type. Objective-C shares it (objc.ts).
*/
export function definingDeclaration(node: SyntaxNode): SyntaxNode | null {
if (!isClassLikeDefinition(node)) return null;
const parent = node.parent;
return parent?.type === 'declaration' && getChildByField(parent, 'type')?.id === node.id ? parent : null;
}
/**
* The name of an unnamed class, struct, union or enum that a declaration
* defines: the first variable the declaration declares. No code can name the
* type of `static struct { … } SPT;` (only `SPT`), so the struct is indexed as
* `SPT`, the way `typedef struct { … } Name;` is indexed as `Name`. Undefined
* for a named type, and when the declaration declares no variable (a
* function's return type). Mirrored in the kernel (ccpp/mod.rs). Objective-C
* shares it (objc.ts), and has no kernel walker.
*/
export function unnamedTypeVariableName(node: SyntaxNode, source: string): string | undefined {
if (getChildByField(node, 'name')) return undefined;
const declaration = definingDeclaration(node);
if (!declaration) return undefined;
for (const declarator of declaration.childrenForFieldName('declarator')) {
const identifier = cDeclaratorIdentifier(declarator);
if (identifier) return getNodeText(identifier, source);
}
return undefined;
}
/**
* Find the function NAME's `qualified_identifier` (`Foo::bar`) inside a
* declarator, skipping the `parameter_list` — a parameter with a qualified type
* (`const std::string& x`) must NOT be mistaken for the method name. Without the
* skip, a plain free function `std::string TableFileName(const std::string&...)`
* was named `string` (from the parameter type), so calls to it never resolved
* and its file looked like nothing depended on it.
*/
function findDeclaratorQualifiedId(declarator: SyntaxNode): SyntaxNode | undefined {
const queue: SyntaxNode[] = [declarator];
while (queue.length > 0) {
const current = queue.shift()!;
if (current.type === 'qualified_identifier') return current;
for (let i = 0; i < current.namedChildCount; i++) {
const child = current.namedChild(i);
// Don't descend into parameters, the trailing return type or the
// clauses after them — `const std::string&`, `-> std::string`,
// nlohmann/json's `noexcept(noexcept(JSONSerializer<U>::to_json(…)))`,
// `throw(std::bad_alloc)`, `requires std::integral<T>` name no function.
if (child && !DECLARATOR_NON_NAME_PARTS.has(child.type)) {
queue.push(child);
}
}
}
return undefined;
}
/** The parts of a function declarator that hold types or expressions, never its name. */
const DECLARATOR_NON_NAME_PARTS: ReadonlySet<string> = new Set([
'parameter_list', 'trailing_return_type', 'noexcept', 'throw_specifier', 'requires_clause',
]);
/**
* Single-argument macros are ambiguous without their definition (#1373).
* Require a preceding local #define whose replacement uses its sole parameter
* as the function declarator; registration, token-pasting, and K&R forms stay
* untouched. Walk enclosing scopes, but never guess across conditional macros.
*/
function recoverSingleArgMacroDefinedName(node: SyntaxNode, source: string): string | undefined {
if (node.type !== 'function_definition') return undefined;
const declarator = getChildByField(node, 'declarator');
let macro: SyntaxNode | null = null;
let argument: SyntaxNode | null = null;
if (declarator?.type === 'parenthesized_declarator' && declarator.namedChildCount === 1) {
// C: NATIVE_FN is parsed as the return type, (name) as the declarator.
macro = getChildByField(node, 'type');
argument = declarator.namedChild(0);
if (macro?.type !== 'type_identifier' || argument?.type !== 'identifier') return undefined;
} else if (declarator?.type === 'function_declarator' && !getChildByField(node, 'type')) {
// C++: NATIVE_FN(name) is parsed as an implicit-return-type function.
macro = getChildByField(declarator, 'declarator');
const params = getChildByField(declarator, 'parameters');
const param = params?.namedChild(0);
if (macro?.type !== 'identifier' || params?.namedChildCount !== 1 ||
param?.type !== 'parameter_declaration' || param.namedChildCount !== 1) return undefined;
argument = param.namedChild(0);
if (argument?.type !== 'type_identifier') return undefined;
}
if (!macro || !argument) return undefined;
const macroName = getNodeText(macro, source);
for (let scope: SyntaxNode | null = node; scope; scope = scope.parent) {
if (scope.type === 'preproc_else' || scope.type.startsWith('preproc_elif')) return undefined;
for (let prev = scope.previousNamedSibling; prev; prev = prev.previousNamedSibling) {
if (prev.type.startsWith('preproc_if')) return undefined;
if (prev.type === 'preproc_call' && getChildByField(prev, 'directive')?.text === '#undef' &&
getChildByField(prev, 'argument')?.text.trim() === macroName) return undefined;
if (prev.type !== 'preproc_function_def' && prev.type !== 'preproc_def') continue;
if (getChildByField(prev, 'name')?.text !== macroName) continue;
const params = getChildByField(prev, 'parameters');
const param = params?.namedChild(0);
const value = getChildByField(prev, 'value');
if (params?.namedChildCount !== 1 || param?.type !== 'identifier' || !value) return undefined;
const replacement = getNodeText(value, source).replace(/\\\r?\n/g, ' ').trim();
const match = replacement.match(/^(?:[A-Za-z_][A-Za-z0-9_:]*\s+)+[*&\s]*([A-Za-z_]\w*)\s*\([^(){};#]*\)\s*$/);
if (!match || /\btypedef\b/.test(replacement) || match[1] !== param.text) return undefined;
return getNodeText(argument, source);
}
}
return undefined;
}
/**
* Recover the real function name from the macro-definition idiom
* `MACRO_NAME(real_name, typed args…) { body }` — flash-attention's
* `DEFINE_FLASH_FORWARD_KERNEL(flash_fwd_kernel, bool Is_dropout, …) { … }`
* being the motivating case: tree-sitter parses the invocation as a
* function_definition NAMED after the macro, so every such kernel shared one
* name (`DEFINE_FLASH_FORWARD_KERNEL`) and the launch sites' calls to the real
* names (`flash_fwd_kernel<…><<<…>>>`) could never resolve.
*
* Deliberately narrow so name-in-first-arg is unambiguous — ALL of:
* - the parsed name is macro-shaped: ALL-CAPS with at least one underscore
* (`TEST` never matches; K&R C definitions have lowercase names);
* - the first "parameter" is a LONE identifier (no type, no declarator)
* containing a lowercase letter — the name being defined;
* - at least one more parameter follows and NONE of them is another lone
* identifier — a second bare arg means the first isn't the name (gtest's
* `TEST_F(Fixture, Name)`, `PYBIND11_MODULE(ext, m)`,
* google-benchmark's `BENCHMARK_DEFINE_F(Fix, name)` all bail here).
*/
function recoverCppMacroDefinedName(node: SyntaxNode, source: string): string | undefined {
if (node.type !== 'function_definition') return undefined;
const declarator = getChildByField(node, 'declarator');
if (declarator?.type !== 'function_declarator') return undefined;
const inner = getChildByField(declarator, 'declarator');
if (inner?.type !== 'identifier') return undefined;
const macroName = getNodeText(inner, source);
if (!/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(macroName)) return undefined;
const params = getChildByField(declarator, 'parameters');
if (!params || params.namedChildCount < 2) return undefined;
const loneIdentText = (p: SyntaxNode): string | null =>
p.type === 'parameter_declaration' &&
p.namedChildCount === 1 &&
p.namedChild(0)?.type === 'type_identifier'
? getNodeText(p.namedChild(0)!, source)
: null;
const first = params.namedChild(0);
const name = first ? loneIdentText(first) : null;
if (!name || !/[a-z]/.test(name)) return undefined;
for (let i = 1; i < params.namedChildCount; i++) {
const p = params.namedChild(i);
if (p && loneIdentText(p) !== null) return undefined;
}
return name;
}
const CPP_CLASS_SPECIFIERS: ReadonlySet<string> = new Set(['class_specifier', 'struct_specifier', 'union_specifier']);
/**
* The `::` segments of a C++ class, struct or union name written with a
* scope, the scope's template arguments dropped: `['SkipList', 'Node']` for
* an out-of-line nested class `struct SkipList<Key, Comparator>::Node`. Such
* a class was indexed `<anonymous>`, so its members were no class's.
* Undefined for a plain name, and for a specialization (`class
* FunctionMocker<R(Args...)>`, `struct fmt::formatter<Foo>`): named after its
* template, it would stand in for the template and every other
* specialization of it (fmt's `formatter<weekday, Char> : formatter<std::tm,
* Char>` extended `formatter<day, Char>`). Mirrored in the kernel
* (ccpp/mod.rs).
*/
function cppWrittenClassParts(node: SyntaxNode, source: string): string[] | undefined {
if (!CPP_CLASS_SPECIFIERS.has(node.type)) return undefined;
const written = getChildByField(node, 'name');
if (written?.type !== 'qualified_identifier') return undefined;
let innermost: SyntaxNode | null = written;
while (innermost?.type === 'qualified_identifier') innermost = getChildByField(innermost, 'name');
if (innermost?.type !== 'type_identifier') return undefined;
const parts = stripCppTemplateArgs(getNodeText(written, source)).split('::').map((p) => p.trim()).filter(Boolean);
return parts.length > 0 && parts.every((p) => /^[A-Za-z_]\w*$/.test(p)) ? parts : undefined;
}
/**
* The name a C++ `qualified_identifier` ends in, past its scopes: the
* `template_function` `ReadPrimitive<int32_t, WireFormatLite::TYPE_INT32>` for
* `WireFormatLite::ReadPrimitive<int32_t, WireFormatLite::TYPE_INT32>`. Null
* when the tree lacks one.
*/
function cppQualifiedIdName(qid: SyntaxNode): SyntaxNode | null {
let name: SyntaxNode | null = qid;
while (name?.type === 'qualified_identifier') name = getChildByField(name, 'name');
return name;
}
/**
* A C++ definition's name node, as named: an explicit specialization's
* (`template_function`) without its template arguments, so
* `ReadPrimitive<int32_t, WireFormatLite::TYPE_INT32>` is `ReadPrimitive`,
* the name every call to it writes. Mirrored in the kernel (ccpp/mod.rs).
*/
function cppDefinedName(name: SyntaxNode, source: string): string {
const own = name.type === 'template_function' ? getChildByField(name, 'name') : null;
return getNodeText(own ?? name, source).trim();
}
function extractCppQualifiedMethodName(node: SyntaxNode, source: string): string | undefined {
const macroDefined = recoverSingleArgMacroDefinedName(node, source) ?? recoverCppMacroDefinedName(node, source);
if (macroDefined) return macroDefined;
const declarator = getChildByField(node, 'declarator');
if (!declarator) return undefined;
const qid = findDeclaratorQualifiedId(declarator);
if (!qid) return undefined;
const name = cppQualifiedIdName(qid);
if (name) return cppDefinedName(name, source);
const parts = getNodeText(qid, source).trim().split('::').filter(Boolean);
return parts[parts.length - 1];
}
/**
* The name of a C++ function an explicit specialization defines, without its
* template arguments: `Swap` for `template <> void Swap<Foo>(Foo& a, Foo& b)`.
* Undefined for any other definition. Mirrored in the kernel (ccpp/mod.rs).
*/
function cppSpecializedFunctionName(node: SyntaxNode, source: string): string | undefined {
if (node.type !== 'function_definition') return undefined;
let declarator = getChildByField(node, 'declarator');
while (declarator && (declarator.type === 'pointer_declarator' || declarator.type === 'reference_declarator')) {
declarator = getChildByField(declarator, 'declarator') || declarator.namedChild(0);
}
if (declarator?.type !== 'function_declarator') return undefined;
const inner = getChildByField(declarator, 'declarator');
return inner?.type === 'template_function' ? cppDefinedName(inner, source) : undefined;
}
function extractCppReceiverType(node: SyntaxNode, source: string): string | undefined {
const declarator = getChildByField(node, 'declarator');
if (!declarator) return undefined;
const qid = findDeclaratorQualifiedId(declarator);
if (!qid) return undefined;
// The scopes are what the qualified id writes before its name: a
// specialization's arguments (`ReadPrimitive<int32_t,
// WireFormatLite::TYPE_INT32>`) are no scope, though they may write `::`.
const name = cppQualifiedIdName(qid);
let scopes = getNodeText(qid, source).trim().split('::').filter(Boolean).slice(0, -1).join('::');
if (name) {
scopes = source.slice(qid.startIndex, name.startIndex).trimEnd();
// A `::` the parser supplied in recovery writes nothing: Metal's `vertex
// VertexOut vertexShader(…)` reads as `VertexOut::vertexShader`.
if (!scopes.endsWith('::')) return undefined;
}
const parts = scopes.split('::').filter(Boolean);
if (parts.length === 0) return undefined;
// An out-of-line template method definition carries the class's template
// parameter list in the qualifier (`template<typename T> T Box<T>::get()`),
// but the class node is indexed as bare `Box` — strip `<…>` so the receiver
// matches it, the same normalization #1043 applies to base-class refs.
// Multi-line parameter lists otherwise leak whole `<…>` blocks (newlines
// included) into qualified_name, which can exceed NAME_MAX (#1286).
const receiver = stripCppTemplateArgs(parts.join('::'));
return receiver || undefined;
}
/**
* Built-in / non-class return types that can never be a method receiver. We
* store no `returnType` for these so resolution never tries to resolve a method
* on `void` / `int` / etc.
*/
const CPP_NON_CLASS_RETURN = new Set([
'void', 'bool', 'char', 'short', 'int', 'long', 'float', 'double', 'unsigned',
'signed', 'size_t', 'ssize_t', 'auto', 'wchar_t', 'char8_t', 'char16_t',
'char32_t', 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t',
'uint32_t', 'uint64_t', 'intptr_t', 'uintptr_t', 'nullptr_t',
]);
/**
* Normalize a C++ return type to the bare class name a method could be called
* on. Unwraps smart-pointer / optional wrappers to their element type
* (`std::unique_ptr<Widget>` → `Widget`) so a factory's `->method()` resolves on
* the pointee. Strips cv-qualifiers, `&`/`*`, namespace qualifiers, and other
* template args. Returns undefined for primitives / void / `auto` / empty.
*/
export function normalizeCppReturnType(raw: string): string | undefined {
let t = raw.trim();
if (!t) return undefined;
// Unwrap smart pointers / optional to their pointee (the thing you call `->` on).
const wrapper = t.match(/\b(?:std\s*::\s*)?(?:unique_ptr|shared_ptr|weak_ptr|optional)\s*<\s*([^,>]+?)\s*>/);
if (wrapper && wrapper[1]) t = wrapper[1];
t = t
.replace(/\b(?:const|volatile|typename|struct|class|enum)\b/g, ' ')
.replace(/<[^>]*>/g, ' ')
.replace(/[*&]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!t) return undefined;
const last = t.split('::').filter(Boolean).pop();
if (!last) return undefined;
if (CPP_NON_CLASS_RETURN.has(last)) return undefined;
if (!/^[A-Za-z_]\w*$/.test(last)) return undefined;
return last;
}
/**
* Strip C++ template arguments from a base-type reference name so it matches the
* bare class/struct the template was DEFINED as. `template<typename T> class
* Base { … }` is indexed as a node named `Base`, but a derived class
* `class D : public Base<int>` records its base as the full `Base<int>` (and
* `class Q : public ns::Tpl<int>` as `ns::Tpl<int>`) — neither name-matches
* `Base` / `ns::Tpl`, so the `extends` edge never resolves and the derived class
* looks like it inherits from nothing (#1043).
*
* Removes every balanced `<…>` group regardless of nesting or position, so
* `Base<int>` → `Base`, `ns::Tpl<Foo<int>>` → `ns::Tpl`, and the rare
* `Outer<int>::Inner` → `Outer::Inner`. The remaining qualified head is exactly
* what the non-templated base case already produces, so resolution treats them
* identically. A name with no template args passes through unchanged.
*/
export function stripCppTemplateArgs(name: string): string {
if (!name.includes('<')) return name;
let out = '';
let depth = 0;
for (const ch of name) {
if (ch === '<') depth++;
else if (ch === '>') { if (depth > 0) depth--; }
else if (depth === 0) out += ch;
}
return out.trim();
}
/**
* Is this C++ `field_declaration` a pure-virtual method (`virtual int read(int key) = 0;`)?
* tree-sitter-cpp shapes those as a field_declaration whose declarator unwraps to a
* `function_declarator`, with the pure-virtual `= 0` as a DIRECT `number_literal` "0"
* child of the field_declaration (default-arg `= 0` lives inside parameter_declaration
* and must not match). Bodiless method prototypes (`int foo();`) and data members
* (`int x = 0;`) are excluded — prototypes usually have an out-of-line definition that
* already mints the method node; pure virtuals never do (#1727).
*/
export function isCppPureVirtualMethodDecl(node: SyntaxNode): boolean {
if (node.type !== 'field_declaration') return false;
let declarator: SyntaxNode | null = getChildByField(node, 'declarator');
if (!declarator) return false;
while (
declarator.type === 'pointer_declarator' ||
declarator.type === 'reference_declarator'
) {
const inner: SyntaxNode | null =
getChildByField(declarator, 'declarator') || declarator.namedChild(0);
if (!inner) return false;
declarator = inner;
}
if (declarator.type !== 'function_declarator') return false;
return node.namedChildren.some(
(c: SyntaxNode) => c.type === 'number_literal' && c.text === '0'
);
}
/**
* A function/method's return type lives in the `function_definition`'s `type`
* field (`Metrics& Metrics::instance()` → `Metrics`). Constructors, destructors,
* and conversion operators have no `type` field → undefined.
*/
function extractCppReturnType(node: SyntaxNode, source: string): string | undefined {
const typeNode = getChildByField(node, 'type');
if (!typeNode) return undefined;
return normalizeCppReturnType(getNodeText(typeNode, source));
}
export const cExtractor: LanguageExtractor = {
resolveName: (node, source) =>
recoverSingleArgMacroDefinedName(node, source) ?? unnamedTypeVariableName(node, source),
// A struct, union or enum defined in a declaration's type is documented by
// the comment above the declaration.
getDeclarationWrapper: (node) => definingDeclaration(node) ?? undefined,
// CUDA in C-detected headers (content-gated blank; see preParseCSource).
preParse: preParseCSource,
// Universal net: recover a real name from any macro-mangled function name.
recoverMangledName: recoverMangledCppName,
functionTypes: ['function_definition'],
classTypes: [],
methodTypes: [],
interfaceTypes: [],
structTypes: ['struct_specifier'],
// A bodiless `union U;` is a forward declaration; the aggregate extractor
// applies the same body requirement it uses for C structs.
unionTypes: ['union_specifier'],
enumTypes: ['enum_specifier'],
enumMemberTypes: ['enumerator'],
typeAliasTypes: ['type_definition'], // typedef
importTypes: ['preproc_include'],
callTypes: ['call_expression'],
variableTypes: ['declaration'],
nameField: 'declarator',
bodyField: 'body',
paramsField: 'parameters',
isConst: isConstDeclaration,
getReturnType: extractCppReturnType,
resolveTypeAliasKind: (node, _source) => {
// C typedef: `typedef enum { ... } name;` or `typedef struct { ... } name;`
// The inner enum_specifier/struct_specifier is anonymous, but we want the typedef name
// to become the enum/struct node name. `typedef union { ... } name;` takes the
// same route — otherwise the union body would mint a second, `<anonymous>` node
// beside the alias.
for (let i = 0; i < node.namedChildCount; i++) {
const child = node.namedChild(i);
if (!child) continue;
if (child.type === 'enum_specifier' && getChildByField(child, 'body')) return 'enum';
if (
child.type === 'struct_specifier' &&
getChildByField(child, 'body')
)
return 'struct';
if (child.type === 'union_specifier' && getChildByField(child, 'body')) return 'union';
}
return undefined;
},
extractImport: (node, source) => {
const importText = source.substring(node.startIndex, node.endIndex).trim();
// C includes: #include <stdio.h>, #include "myheader.h"
const systemLib = node.namedChildren.find((c: SyntaxNode) => c.type === 'system_lib_string');
if (systemLib) {
return { moduleName: getNodeText(systemLib, source).replace(/^<|>$/g, ''), signature: importText };
}
const stringLiteral = node.namedChildren.find((c: SyntaxNode) => c.type === 'string_literal');
if (stringLiteral) {
const stringContent = stringLiteral.namedChildren.find((c: SyntaxNode) => c.type === 'string_content');
if (stringContent) {
return { moduleName: getNodeText(stringContent, source), signature: importText };
}
}
return null;
},
};
/**
* Detect tree-sitter's misparse of a macro-annotated class/struct, e.g.
* `class MACRO Name { … }` or `class MACRO Name : public Base { … }` (#946).
* Not knowing `MACRO` is a macro, tree-sitter reads `class MACRO` as an
* *elaborated type specifier* (a bodyless `class_specifier`/`struct_specifier`
* whose "type name" is the macro) and the rest as a function: `Name` becomes the
* declarator and the `{ … }` a function body — so the whole declaration surfaces
* as a `function_definition` named after the class, with a line range spanning
* the entire class body. (A base clause, when present, additionally lands in an
* `ERROR` node, but it isn't required — the leading macro alone triggers this.)
*
* Two structural signals pin it down with no risk to genuine code:
* - the `type` field is a *bodyless* class/struct specifier — an elaborated
* type, not a real inline-defined return type like
* `struct P { int x; } makeP() { … }` (which carries a field list); and
* - the declarator is not a `function_declarator` — a real function definition
* always has one, which also leaves the legal-but-rare `class Foo f() { … }`
* (an elaborated return type on a genuine function) alone.
*
* The class body is mangled by the same misparse and is unrecoverable, so —
* matching how macro-prefixed C prototypes are handled — we drop the spurious
* node rather than mint a misleading whole-body `function` that pollutes
* callers/impact and skews kind statistics.
*/
function isMacroMisparsedTypeDecl(node: SyntaxNode): boolean {
const typeNode = getChildByField(node, 'type');
if (!typeNode) return false;
if (typeNode.type !== 'class_specifier' && typeNode.type !== 'struct_specifier') return false;
if (typeNode.namedChildren.some((c: SyntaxNode) => c.type === 'field_declaration_list')) return false;
const declarator = getChildByField(node, 'declarator');
if (declarator && declarator.type === 'function_declarator') return false;
return true;
}
/**
* Blank an export/visibility macro in a `class/struct EXPORT_MACRO Name …`
* *definition* header before parsing. Not knowing the macro, tree-sitter reads
* `class EXPORT_MACRO` as an elaborated type specifier and the rest as a
* function, so the whole class — its name, base clause, and members — drops out
* of the index (#946 catches the resulting phantom function but can't recover
* the class), which silently breaks type-hierarchy / inheritance-impact queries
* for effectively every Unreal-Engine (`*_API`), Qt/Boost (`*_EXPORT`), LLVM
* (`*_ABI`), … class. Replacing the macro with equal-length spaces preserves
* every byte offset (and thus line/column), so the declaration then parses as a
* normal class_specifier and the existing extraction emits the node, members,
* and `extends` edge. (#1061, follow-up to #946.)
*
* Matched tightly so it can't touch the same macro used as an ordinary value
* elsewhere (`int x = SOME_API;`): the macro is the ALL-CAPS token sitting
* *between* `class`/`struct` and the type name, and the trailing `[:{]`
* definition-guard fires only when a base clause or body follows — the only
* shape that misparses. That guard also leaves elaborated-type variable
* declarations (`struct FOO var;`, `class FOO obj = …`) untouched, since those
* end in `;` / `=` / `[`, never `:` / `{`. C++-only (wired into cppExtractor),
* so C's heavier use of `struct TAG var;` never reaches it.
*
* The head may carry several macros, and a macro may take arguments: protobuf's
* generated `class PROTOBUF_EXPORT PROTOBUF_FUTURE_ADD_EARLY_WARN_UNUSED Any
* final : public Message`, `class ABSL_ATTRIBUTE_WARN_UNUSED
* PROTOBUF_DECLSPEC_EMPTY_BASES RepeatedField final`, rocksdb's `struct
* ALIGN_AS(64U) HandleImpl : public ClockHandle`. The whole run is blanked; the
* last name before the guard is the class. The name may be followed by template
* arguments, for a specialization (`class PROTOBUF_DECLSPEC_EMPTY_BASES
* RepeatedFieldProxyWithSet<ElementType, …> {`). Matched on the code alone, so
* a comment or string never takes part.
*/
const CPP_CLASS_HEAD_MACROS_RE =
/\b(?:class|struct)\s+((?:[A-Z][A-Z0-9_]+(?:\s*\((?:[^()]|\([^()]*\))*\))?\s+)+)(?!final\b)[A-Za-z_]\w*(?:\s*::\s*[A-Za-z_]\w*)*/g;
export function blankCppExportMacros(source: string): string {
if (source.indexOf('class') === -1 && source.indexOf('struct') === -1) return source;
if (!/\b(?:class|struct)\s+[A-Z][A-Z0-9_]/.test(source)) return source;
const code = maskCppCode(source);
const spans: Array<[number, number]> = [];
const re = new RegExp(CPP_CLASS_HEAD_MACROS_RE.source, 'g');
let m: RegExpExecArray | null;
while ((m = re.exec(code)) !== null) {
let i = skipCppSpace(code, m.index + m[0].length);
if (code[i] === '<') {
i = skipCppAngleArgs(code, i);
if (i < 0) continue;
i = skipCppSpace(code, i);
}
if (/^final\b/.test(code.slice(i, i + 6))) i = skipCppSpace(code, i + 5);
if (code[i] !== '{' && !(code[i] === ':' && code[i + 1] !== ':')) continue;
const run = m[1] as string;
const start = m.index + m[0].indexOf(run);
pushCppRunTokens(spans, run, start);
}
return blankCppSpans(source, spans, code);
}
// Comments and string/char literals (raw strings are masked beforehand by
// maskCppRawStrings). The char-literal boundary leaves digit separators alone.
const CPP_COMMENT_OR_LITERAL_RE =
/\/\/(?:\\\r?\n|[^\r\n])*|\/\*[\s\S]*?(?:\*\/|$)|"(?:\\[\s\S]|[^"\\])*(?:"|$)|(?<!\w)(?:u8|[LuU])?'(?:\\[\s\S]|[^'\\])*(?:'|$)/g;
/**
* The source with comments and string/char literals turned to spaces, line
* endings kept. The macro scans below match on this, so a word in a comment or
* a literal (`* NOTE: …` in a doc comment) is never blanked, and every offset
* still lines up with the source.
*/
function maskCppCommentsAndLiterals(source: string): string {
return source.replace(CPP_COMMENT_OR_LITERAL_RE, (m) => (m.includes('\n') || m.includes('\r') ? m.replace(/[^\r\n]/g, ' ') : ' '.repeat(m.length)));
}
/**
* The code the macro scans below match on, at the source's offsets: comments
* are spaces, a string or char literal keeps its place as `\x01`s (it is a
* token, not space: in `"… using " GTEST_NAME_` the macro does not start a
* line, and a run of macros never reaches across a literal), and
* preprocessor directives with their `\` continuation lines are spaces — the
* `)` ending `#if !defined(__MINGW32__)` closes no parameter list, so the
* `TEST(file_test, open_windows_file) {` under it is not a trailing macro.
*/
function maskCppCode(source: string): string {
if (cppMaskMemo !== null && cppMaskMemo.source === source) return cppMaskMemo.code;
const code = source
.replace(CPP_COMMENT_OR_LITERAL_RE, (m) => m.replace(/[^\r\n]/g, m.startsWith('/') ? ' ' : '\x01'))
.replace(/^[ \t]*#(?:\\\r?\n|[^\r\n])*/gm, (m) => m.replace(/[^\r\n]/g, ' '));
cppMaskMemo = { source, code };
return code;
}
// The last source maskCppCode masked. The passes run one after another on
// the same text: one that blanks nothing hands the next the same string, and
// one that blanks hands it a mask blanked the same way (blankCppSpans), so a
// file is masked once rather than once per pass.
let cppMaskMemo: { source: string; code: string } | null = null;
// One macro, with its arguments, inside a run matched on the masked code.
const CPP_RUN_TOKEN_RE = /[A-Z][A-Z0-9_]*(?:\s*\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\))?/g;
/** Add a span for each macro of `run` (found at `start`), leaving what lies between them. */
function pushCppRunTokens(spans: Array<[number, number]>, run: string, start: number): void {
for (const t of run.matchAll(CPP_RUN_TOKEN_RE)) spans.push([start + t.index, start + t.index + t[0].length]);
}
/**
* Replace each [start, end) span of `source` with spaces, keeping line
* endings. Given the mask the spans were found on, blank it the same way and
* keep it for the next pass: a span holds whole macros (with their arguments),
* so the result is what masking the new source would give.
*/
function blankCppSpans(source: string, spans: ReadonlyArray<readonly [number, number]>, code?: string): string {
if (spans.length === 0) return source;
const ordered = [...spans].sort((a, b) => a[0] - b[0]);
const blank = (text: string): string => {
let out = '';
let at = 0;
for (const [start, end] of ordered) {
const from = Math.max(start, at);
if (from >= end) continue;
const span = text.slice(from, end);
out += text.slice(at, from) + (span.includes('\n') || span.includes('\r') ? span.replace(/[^\r\n]/g, ' ') : ' '.repeat(span.length));
at = end;
}
return out + text.slice(at);
};
const out = blank(source);
if (code !== undefined) cppMaskMemo = { source: out, code: blank(code) };
return out;
}
function skipCppSpace(code: string, i: number): number {
while (i < code.length && /\s/.test(code[i] as string)) i++;
return i;
}
/**
* The index just past the template argument list opening at `code[open]`
* (`<`), or -1 when it doesn't close before a `;`, `{` or `}` — then it was a
* comparison, not template arguments. Angle brackets inside parentheses don't
* count (`Foo<sizeof(a) < 4>`).
*/
function skipCppAngleArgs(code: string, open: number): number {
let angles = 0;
let parens = 0;
const limit = Math.min(code.length, open + 4000);
for (let i = open; i < limit; i++) {
const c = code[i];
if (c === '(') parens++;
else if (c === ')') {
if (--parens < 0) return -1;
} else if (c === ';' || c === '{' || c === '}') return -1;
else if (parens === 0 && c === '<') angles++;
else if (parens === 0 && c === '>' && code[i - 1] !== '-') {
if (--angles === 0) return i + 1;
}
}
return -1;
}
/**
* Blank attribute macros between a pointer or reference and the name it
* declares: protobuf's nullability annotations (`const Descriptor*
* PROTOBUF_NONNULL descriptor()`, `Any* PROTOBUF_RESTRICT PROTOBUF_NONNULL
* other`, `const FieldDescriptor* PROTOBUF_NULLABLE* PROTOBUF_NONNULL field`).
* tree-sitter takes the macro for the declared name and the real name for an
* error: a member keeps a broken declarator, an out-of-line definition gets the
* macro glued into its qualified name (`PROTOBUF_NONNULL Any::mutable_type_url`),
* and a definition whose parameter carries one (`void Any::Swap(Any*
* PROTOBUF_NONNULL other) { … }`) parses as a variable and drops out of the
* index. Generated `.pb.h`/`.pb.cc` files carry thousands of them.
*
* Matched on the code alone: the macro is ALL-CAPS with an underscore, right
* after `*` or `&`, and followed by the name (or, after `*`, by another `*`).
* C++ never puts two names in a row there, and a product (`a * MAX_LEN + 1`)
* or a bit test (`flags & FOO_BIT)`) is followed by an operator or a closer
* instead; a `*` after `)`, `]` or a number is a product too (`sizeof(int) *
* CHAR_BIT * 3`). A trailing macro with nothing after it (`Foo*
* PROTOBUF_NONNULL)`) parses as the parameter name and is left alone.
* C++-only.
*/
const CPP_POINTER_ANNOTATION_RE =
/([*&])\s*((?:[A-Z][A-Z0-9]*_[A-Z0-9_]*(?:\s+|(?=\*)))+)(?=\*|::|(?!(?:and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|xor|xor_eq)\b)[A-Za-z_~])/g;
export function blankCppPointerAnnotationMacros(source: string): string {
if (!/[*&]\s*[A-Z][A-Z0-9]*_/.test(source)) return source;
const code = maskCppCode(source);
const spans: Array<[number, number]> = [];
const re = new RegExp(CPP_POINTER_ANNOTATION_RE.source, 'g');
let m: RegExpExecArray | null;
while ((m = re.exec(code)) !== null) {
const run = m[2] as string;
const start = m.index + m[0].length - run.length;
// After `&`, only a name: `flags & FOO_BIT\n && ok` is an expression.
if (m[1] === '&' && code[start + run.length] === '*') continue;
// A `*` after a closing bracket or a number multiplies: `sizeof(int) * CHAR_BIT * 3`.
if (/(?:[)\]]|\b\d[\w.]*)\s*$/.test(code.slice(Math.max(0, m.index - 40), m.index))) continue;
pushCppRunTokens(spans, run, start);
}
return blankCppSpans(source, spans, code);
}
// Keywords that take a parenthesized operand: a `)` closing one of these is
// not a parameter list, so a token after it is not a trailing attribute.
// `constexpr` / `consteval` stand before the condition of `if constexpr (…)`.
const CPP_PAREN_KEYWORDS = new Set([
'if', 'while', 'for', 'switch', 'catch', 'return', 'sizeof', 'alignof', 'alignas', 'decltype',
'typeid', 'noexcept', 'throw', 'static_assert', 'new', 'delete', 'case', 'requires', 'co_await',
'co_yield', 'co_return', 'asm', '__asm__', '__attribute__', '__attribute', '__declspec', '_Pragma',
'else', 'do', 'constexpr', 'consteval', 'explicit', 'typeof', '__typeof__', '__typeof', '_Alignof',
'__alignof__', 'volatile', '__volatile__',
]);
/**
* Blank attribute macros after a function's parameter list: protobuf's
* `unknown_fields() const\n ABSL_ATTRIBUTE_LIFETIME_BOUND {` and `~Any()
* PROTOBUF_FINAL;`, and the thread-safety annotations of leveldb, rocksdb and
* abseil (`void Wait() LOCKS_EXCLUDED(mu_) {`, `void Lock()
* EXCLUSIVE_LOCK_FUNCTION();`). tree-sitter reads the macro as the start of a
* new declaration, so the method loses its `;` or its body: an inline body
* becomes a stray block, and in a long run of members the class can end early.
*
* Matched on the code alone, so it can't touch an expression:
* - the `)` closes a parameter list: the `(` it matches follows a function
* name (`name(`, `~Name(`, `operator==(`, `operator()(`), not a keyword
* (`if (x) FOO;`), a cast (`= (int) MAX_VALUE;`) or a macro call
* (`FMT_PRAGMA_CLANG(…)` above `TEST(std_test, bitint) {`);
* - between `)` and the macro only `const`, `volatile`, `&`, `&&`,
* `noexcept`, `override` or `final` may stand, and no blank line;
* - the macro (ALL-CAPS, optionally with balanced arguments; several may
* stack) is followed by what may end a declarator: `{`, `;`, `=`, a
* constructor's `:`, `->`, or `override`/`final`/`const`/`noexcept`.
* C++-only.
*/
const CPP_TRAILING_ATTR_CANDIDATE_RE =
/\)((?:\s*(?:const|volatile|noexcept|override|final|&&|&)(?![\w]))*)\s*(?=[A-Z][A-Z0-9_]{2,}\b)/g;
const CPP_TRAILING_ATTR_RUN_RE =
/(?:[A-Z][A-Z0-9_]{2,}\b(?:\s*\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\))?\s*)+/y;
const CPP_TRAILING_ATTR_FOLLOW_RE = /(?:\{|;|=(?!=)|:(?!:)|->|(?:override|final|const|noexcept)\b)/y;
export function blankCppTrailingAttributeMacros(source: string): string {
if (!/\)[\s\w&]*?\b[A-Z][A-Z0-9_]{2,}\b/.test(source)) return source;
const code = maskCppCode(source);
const spans: Array<[number, number]> = [];
const re = new RegExp(CPP_TRAILING_ATTR_CANDIDATE_RE.source, 'g');
const run = new RegExp(CPP_TRAILING_ATTR_RUN_RE.source, 'y');
const follow = new RegExp(CPP_TRAILING_ATTR_FOLLOW_RE.source, 'y');
let m: RegExpExecArray | null;
while ((m = re.exec(code)) !== null) {
const macroStart = m.index + m[0].length;
if (/\n[ \t]*\r?\n/.test(m[0])) continue;
run.lastIndex = macroStart;
const r = run.exec(code);
if (!r) continue;
follow.lastIndex = macroStart + r[0].length;
if (!follow.test(code)) continue;
if (!closesParameterList(code, m.index)) continue;
pushCppRunTokens(spans, r[0], macroStart);
re.lastIndex = macroStart + r[0].length;
}
return blankCppSpans(source, spans, code);
}
// Type keywords that may stand right before a declared name (`int count_ …`).
const CPP_TYPE_KEYWORDS = new Set([
'void', 'bool', 'char', 'char8_t', 'char16_t', 'char32_t', 'wchar_t', 'short', 'int', 'long', 'float',
'double', 'signed', 'unsigned', 'auto',
]);
const CPP_KEYWORDS = new Set([
...CPP_TYPE_KEYWORDS, ...CPP_PAREN_KEYWORDS, 'const', 'volatile', 'static', 'extern', 'inline', 'virtual',
'explicit', 'constexpr', 'consteval', 'constinit', 'friend', 'mutable', 'thread_local', 'register',
'typedef', 'using', 'template', 'typename', 'class', 'struct', 'union', 'enum', 'namespace', 'operator',
'goto', 'break', 'continue', 'default', 'public', 'private', 'protected', 'this', 'true', 'false',
'nullptr', 'and', 'or', 'not', 'xor', 'bitand', 'bitor', 'compl', 'and_eq', 'or_eq', 'xor_eq', 'not_eq',
]);
/**
* Blank attribute macros after the name a declaration declares, or after its
* array brackets: thread-safety annotations on fields (leveldb's `port::CondVar
* cv GUARDED_BY(mu);`, abseil's `ABSL_GUARDED_BY`), annotated parameters
* (`const absl::Cord* cord ABSL_ATTRIBUTE_LIFETIME_BOUND)`), and the section
* attributes of protobuf's generated globals (`Any_globals_
* PROTOBUF_MESSAGE_GLOBALS_SECTION(.data.rel.ro);`, `offsets[]
* ABSL_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {`). tree-sitter reads
* the macro as a second declarator and errors.
*
* Matched on the code alone, so it can't touch a variable named in capitals:
* - the macro is ALL-CAPS with an underscore, optionally with balanced
* arguments, and is followed by `;`, `=`, `,` or `)`;
* - before it stands `]`, or a name with a lowercase letter that itself
* follows a type: a type name, a type keyword, `*`, `&`, `>`, or `const`
* after a pointer. `Foo DEFAULT_OPTIONS;` and `const Foo kMAX_SIZE;`
* declare those capitals (nothing names a type before `Foo`), `typedef Foo
* BAR_T;` names a type, and `return x FOO;` or `f(a, b FOO)` have no type
* before the name.
* C++-only.
*/
const CPP_DECLARATOR_ATTR_CANDIDATE_RE = /(?<![\w$])[A-Z][A-Z0-9]*_[A-Z0-9_]*\b/g;
const CPP_DECLARATOR_ATTR_RUN_RE =
/(?:[A-Z][A-Z0-9]*_[A-Z0-9_]*\b(?:\s*\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\))?\s*)+/y;
export function blankCppDeclaratorAttributeMacros(source: string): string {
if (!/[\w\]]\s+[A-Z][A-Z0-9]*_[A-Z0-9_]*\s*[(;=,)]/.test(source)) return source;
const code = maskCppCode(source);
const spans: Array<[number, number]> = [];
const re = new RegExp(CPP_DECLARATOR_ATTR_CANDIDATE_RE.source, 'g');
const run = new RegExp(CPP_DECLARATOR_ATTR_RUN_RE.source, 'y');
let m: RegExpExecArray | null;
while ((m = re.exec(code)) !== null) {
const macroStart = m.index;
// Whitespace before the macro, and before that a name or `]`.
let last = macroStart - 1;
while (last >= 0 && /\s/.test(code[last] as string)) last--;
if (last === macroStart - 1 || last < 0 || !/[\w\]]/.test(code[last] as string)) continue;
run.lastIndex = macroStart;
const r = run.exec(code);
if (!r || !/^[;,)]|^=(?!=)/.test(code.slice(macroStart + r[0].length, macroStart + r[0].length + 2))) continue;
if (code[last] !== ']' && !followsDeclaredName(code, last)) continue;
pushCppRunTokens(spans, r[0], macroStart);
re.lastIndex = macroStart + r[0].length;
}
return blankCppSpans(source, spans, code);
}
/** True when the identifier ending at `code[last]` is a name a declaration declares. */
function followsDeclaredName(code: string, last: number): boolean {
let start = last;
while (start > 0 && /\w/.test(code[start - 1] as string)) start--;
const name = code.slice(start, last + 1);
if (!/^[A-Za-z_]\w*$/.test(name) || !/[a-z]/.test(name) || CPP_KEYWORDS.has(name)) return false;
let i = start - 1;
while (i >= 0 && /\s/.test(code[i] as string)) i--;
const c = code[i];
if (c === '*' || c === '&') return true;
if (c === '>') return code[i - 1] !== '-';
if (!c || !/\w/.test(c)) return false;
let j = i;
while (j > 0 && /\w/.test(code[j - 1] as string)) j--;
const before = code.slice(j, i + 1);
if (before === 'const' || before === 'volatile') {