forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
1990 lines (1875 loc) · 77.9 KB
/
Copy pathmod.rs
File metadata and controls
1990 lines (1875 loc) · 77.9 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
//! C / C++ extraction — a faithful Rust port of `TreeSitterExtractor`'s c/cpp
//! paths (src/extraction/tree-sitter.ts) plus languages/c-cpp.ts, one dual-
//! language module flagged like tsjs/ (checklist:
//! docs/design/ccpp-kernel-port-checklist.md — read it before editing).
//!
//! The seven preParse blanking passes are NOT here: the TS route point
//! (src/extraction/kernel/index.ts) applies `extractor.preParse` before the
//! kernel call, so this walker receives the SAME blanked bytes the wasm
//! extractor parses (all blanks are equal-length-space replacements — every
//! offset survives). `.metal`/`.cu`/`.cuh` arrive as language 'cpp' with their
//! dialect blanks already applied.
//!
//! Quirks mirrored bug-for-bug (each pinned by the parity gates):
//! - cpp namespace prefix stack (#1291): named `namespace a::b {` pushes the
//! name AS WRITTEN onto the qualifiedName prefix; anonymous falls through.
//! No namespace NODE is minted (#1093 crowd-out).
//! - out-of-line `Cls::method` defs: name = LAST `::` segment of the
//! declarator's qualified_identifier (BFS that skips parameter_list +
//! trailing_return_type), receiver = the template-stripped qualifier,
//! qualifiedName composed against the namespace prefix with the re-spelled-
//! prefix anchor rule; owner `contains` edge to the FIRST earlier
//! struct/class/enum/trait of the receiver's bare name.
//! - macro-name salvage: recoverCppMacroDefinedName (ALL-CAPS macro def whose
//! real name is the lone first argument) at resolveName, and
//! recoverMangledCppName (glued "Ret name" → last token) as the universal
//! post-hoc net for BOTH c and cpp.
//! - `class MACRO Name` misparse residue: isMisparsedFunction drops the
//! phantom function (name starts `namespace`, C++ keywords, or the bodyless
//! class/struct `type` + non-function_declarator shape, #946/#1061) but
//! still walks the body.
//! - C file-scope variables: init/pointer/array declarators only — a BARE
//! identifier declarator is the macro-prototype misparse and is skipped
//! (loses uninit scalars by design); cpp declarations instead take the TS
//! GENERIC fallback (direct identifier children only → `int x;` extracts,
//! `int x = 5;` does not — bug-for-bug).
//! - inheritance quirk: extractInheritance recurses into
//! field_declaration_list, where a field_declaration with no DIRECT
//! field_identifier child (pointer/array/method members) but a direct
//! type_identifier emits an `extends` ref to that type (the Go-embedding
//! branch matching c/cpp shapes). Kept: the parity gate pins today's graph.
//! - static-member/value-read pass (cpp only): `field_expression` is in
//! MEMBER_ACCESS_TYPES (listed for Scala, same node kind in cpp), so
//! `Capitalized.member` / `Capitalized->member` VALUE reads emit
//! `references` refs; qualified_identifier is checked too but its scope
//! child is namespace_identifier/template_type/…, never a plain
//! identifier, so it can't emit.
//! - explicit operator calls (#1247) ride an ERROR child — but has_error()
//! defers the whole file to wasm, so the ported branch is a faithful no-op
//! here; kept so an error-free shape (if a grammar bump ever produces one)
//! stays parity-true.
//! - local fn-pointer fan-out (#932-adjacent): `auto k = &fn<…>;` records
//! per-caller targets (insertion-ordered, branch reassignments accumulate);
//! a later bare `k(args)` emits one `calls` ref PER target and suppresses
//! the local name. Template args stripped like base-class refs (#1043).
//! - stack construction (#1035): cpp `declaration` with class-like named
//! `type` and an init_declarator whose value is argument_list /
//! initializer_list → `instantiates` (most-vexing-parse excluded).
//! - value-reference edges: C only (VALUE_REF_LANGS has 'c', not 'cpp') —
//! shadow prune via init_declarator counts, MAX_VALUE_REF_NODES cap,
//! CODEGRAPH_VALUE_REFS=0 kill switch.
//! - fn-ref capture (#756): cFamilySpec for both; cpp adds addressOfOnly
//! (bare identifiers only qualify in file-scope value/list positions).
//!
//! Files with parse errors defer to wasm (`defer:`) — error recovery is
//! encoding-dependent and the wasm recovery is canonical.
use crate::buffers::{
build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
RefRow, StrRef, Tables, FLAG_IS_EXPORTED, FUNCTION_REF_CODE, NONE, NONE_STR,
};
use crate::docstring::preceding_docstring;
use crate::ids;
use crate::textutil as util;
use regex::Regex;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::OnceLock;
use tree_sitter::{Node, Parser};
const MAX_VALUE_REF_NODES: usize = 20_000;
// --- compiled regexes (JS \w/\s spelled as ASCII classes for parity) ---------
/// recoverCppMacroDefinedName: macro-shaped parsed name.
fn macro_shaped_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$").unwrap())
}
fn has_lower_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"[a-z]").unwrap())
}
/// normalizeCppReturnType: smart-pointer/optional unwrap.
fn ret_wrapper_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"\b(?:std\s*::\s*)?(?:unique_ptr|shared_ptr|weak_ptr|optional)\s*<\s*([^,>]+?)\s*>")
.unwrap()
})
}
fn ret_keyword_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"\b(?:const|volatile|typename|struct|class|enum)\b").unwrap())
}
fn angle_group_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
}
fn ptr_ref_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"[*&]+").unwrap())
}
fn ws_run_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"\s+").unwrap())
}
fn simple_ident_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*$").unwrap())
}
/// recoverMangledCppName's `Ret (name)` idiom guard.
fn ret_paren_name_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^\S+\s+\([A-Za-z_][A-Za-z0-9_]*\)").unwrap())
}
/// Operator-call receiver: simple identifier / dotted member chain.
fn operator_receiver_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_.]*$").unwrap())
}
/// Symbolic operator tail (`/^[^\w\s]/` in JS).
fn symbolic_op_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[^A-Za-z0-9_\s]").unwrap())
}
/// extractStaticMemberRef's capitalized-receiver test.
fn capitalized_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
}
/// normalizeValue's qualified `&Cls::m` member-pointer test (`/^[A-Za-z_][\w:]*$/`).
fn qualified_ref_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_:]*$").unwrap())
}
/// CPP_NON_CLASS_RETURN (languages/c-cpp.ts).
fn is_non_class_return(name: &str) -> bool {
matches!(
name,
"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"
)
}
/// CPP_PRIMITIVE_NAMES (languages/c-cpp.ts) — recoverMangledCppName's guard.
fn is_cpp_primitive_name(name: &str) -> bool {
matches!(
name,
"bool" | "void" | "int" | "char" | "short" | "long" | "float" | "double" | "unsigned"
| "signed" | "wchar_t" | "char8_t" | "char16_t" | "char32_t" | "char_t" | "size_t"
| "auto" | "const" | "struct" | "class" | "enum" | "union" | "typename"
)
}
/// NAME_STOPLIST (function-ref.ts).
fn is_stoplisted(name: &str) -> bool {
matches!(
name,
"this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
| "NULL" | "nullptr" | "None"
)
}
/// LITERAL_RECEIVER_TYPES (tree-sitter.ts) — full set; membership is what the
/// TS code tests even though only a few kinds occur in the c/cpp grammars.
fn is_literal_receiver(kind: &str) -> bool {
matches!(
kind,
"string" | "string_literal" | "interpreted_string_literal" | "raw_string_literal"
| "template_string" | "concatenated_string" | "formatted_string" | "f_string"
| "line_string_literal" | "string_content" | "heredoc_body"
| "number" | "number_literal" | "integer" | "integer_literal" | "float"
| "float_literal" | "int_literal" | "decimal_integer_literal" | "real_literal"
| "char_literal" | "character_literal" | "rune_literal" | "regex" | "regex_literal"
| "true" | "false" | "boolean_literal" | "bool_literal" | "none" | "null" | "nil"
| "null_literal" | "undefined"
| "list" | "list_literal" | "array" | "array_literal" | "array_creation_expression"
| "dictionary" | "dict_literal" | "object" | "tuple" | "set"
)
}
/// stripCppTemplateArgs (languages/c-cpp.ts): depth-counted removal of every
/// balanced `<…>` group; `<` and `>` never reach the output.
fn strip_cpp_template_args(name: &str) -> String {
if !name.contains('<') {
return name.to_string();
}
let mut out = String::with_capacity(name.len());
let mut depth = 0u32;
for ch in name.chars() {
if ch == '<' {
depth += 1;
} else if ch == '>' {
depth = depth.saturating_sub(1);
} else if depth == 0 {
out.push(ch);
}
}
out.trim().to_string()
}
/// recoverMangledCppName (languages/c-cpp.ts) — universal post-hoc salvage for
/// a name still mangled by an unblanked macro ("Ret name" → "name").
fn recover_mangled_cpp_name(name: String) -> String {
if !name.chars().any(|c| c.is_whitespace())
|| name.starts_with("operator")
|| name.starts_with('~')
{
return name;
}
if ret_paren_name_re().is_match(&name) {
return name; // `Ret (name)` idiom — leave alone
}
let before_params = match name.find('(') {
Some(i) => &name[..i],
None => &name[..],
};
// (JS: `beforeParams.trim().split(/\s+/)` — split_whitespace already
// ignores leading/trailing whitespace, so no explicit trim.)
let candidate = before_params.split_whitespace().last().unwrap_or("");
if candidate.is_empty()
|| !simple_ident_re().is_match(candidate)
|| is_cpp_primitive_name(candidate)
{
return name;
}
candidate.to_string()
}
/// normalizeCppReturnType (languages/c-cpp.ts).
fn normalize_cpp_return_type(raw: &str) -> Option<String> {
let mut t = raw.trim().to_string();
if t.is_empty() {
return None;
}
if let Some(c) = ret_wrapper_re().captures(&t) {
if let Some(inner) = c.get(1) {
t = inner.as_str().to_string();
}
}
let t = ret_keyword_re().replace_all(&t, " ");
let t = angle_group_re().replace_all(&t, " ");
let t = ptr_ref_re().replace_all(&t, " ");
let t = ws_run_re().replace_all(&t, " ");
let t = t.trim();
if t.is_empty() {
return None;
}
let parts: Vec<&str> = t.split("::").filter(|p| !p.is_empty()).collect();
let last = *parts.last()?;
if is_non_class_return(last) || !simple_ident_re().is_match(last) {
return None;
}
Some(last.to_string())
}
/// JS `String.replace(/->/g,'.').replace(/\s+/g,'')` used on receivers.
fn arrow_dot_no_ws(s: &str) -> String {
s.replace("->", ".").chars().filter(|c| !c.is_whitespace()).collect()
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Variant {
C,
Cpp,
}
struct Scope {
row: u32,
kind: &'static str,
name: String,
}
#[derive(Default)]
struct Extra {
docstring: Option<String>,
signature: Option<String>,
visibility: Option<u8>,
is_exported: Option<bool>,
return_type: Option<String>,
qualified_name: Option<String>,
}
struct ValueScope<'t> {
row: u32,
node: Node<'t>,
name: String,
}
/// Capture mode for a fn-ref candidate (gate policy keys on it).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
Args,
Rhs,
Value,
List,
Varinit,
}
struct Cand {
from: u32,
name: String,
mode: Mode,
explicit_ref: bool,
line: u32,
column_byte: usize,
row: usize,
}
/// Per-node metadata for the receiver-method owner lookup (mirrors the TS
/// side's scan over `this.nodes` — FIRST match wins, earlier-in-file only).
struct NodeMeta {
kind: &'static str,
name: String,
}
pub struct Walker<'t> {
src: &'t str,
file_path: &'t str,
variant: Variant,
line_starts: Vec<usize>,
arena: Arena,
tables: Tables,
stack: Vec<Scope>,
nodes_meta: Vec<NodeMeta>,
node_ids: Vec<String>,
/// C/C++ enclosing `namespace ns { … }` names (cpp only ever non-empty).
namespace_prefix: Vec<String>,
/// cppLocalFnPtrs: caller row → local name → insertion-ordered targets.
local_fn_ptrs: HashMap<u32, HashMap<String, Vec<String>>>,
defined_fn_names: HashSet<String>,
imported_names: HashSet<String>,
fn_ref_cands: Vec<Cand>,
fs_values: HashMap<String, u32>,
fs_value_counts: HashMap<String, u32>,
value_scopes: Vec<ValueScope<'t>>,
}
pub fn extract(file_path: &str, source: &str, language: &str) -> Result<EmitOut, String> {
let variant = match language {
"c" => Variant::C,
"cpp" => Variant::Cpp,
other => return Err(format!("ccpp walker got language '{other}'")),
};
let grammar = crate::langs::grammar_for(language).ok_or("no c/cpp grammar")?;
let t0 = std::time::Instant::now();
let mut parser = Parser::new();
parser
.set_language(&grammar)
.map_err(|e| format!("set_language({language}) failed: {e}"))?;
let tree = parser
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
// Measurement hatch (parity sweeps only — never set in production): skip
// the defer so the sweep can QUANTIFY how often UTF-8 vs UTF-16 error
// recovery actually diverges on this language's erroring files.
let no_defer = std::env::var("CODEGRAPH_KERNEL_CCPP_ERROR_EXTRACT").as_deref() == Ok("1");
if tree.root_node().has_error() && !no_defer {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
}
let mut w = Walker {
src: source,
file_path,
variant,
line_starts: util::line_starts(source),
arena: Arena::default(),
tables: Tables::default(),
stack: Vec::new(),
nodes_meta: Vec::new(),
node_ids: Vec::new(),
namespace_prefix: Vec::new(),
local_fn_ptrs: HashMap::new(),
defined_fn_names: HashSet::new(),
imported_names: HashSet::new(),
fn_ref_cands: Vec::new(),
fs_values: HashMap::new(),
fs_value_counts: HashMap::new(),
value_scopes: Vec::new(),
};
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
let mut flags = BoolFlags::default();
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
visibility: 0,
flags,
start_line: 1,
end_line: line_count,
start_column: 0,
end_column: 0,
name: name_ref,
qualified_name: qn_ref,
id: file_id,
docstring: NONE_STR,
signature: NONE_STR,
decorators: NONE_STR,
type_parameters: NONE_STR,
return_type: NONE_STR,
extra_json: NONE_STR,
});
w.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
w.visit_node(tree.root_node());
w.flush_fn_ref_candidates();
w.flush_value_refs(tree.root_node());
w.stack.pop();
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
meta,
nodes: w.tables.nodes,
edges: w.tables.edges,
refs: w.tables.refs,
arena: w.arena.into_vec(),
})
}
impl<'t> Walker<'t> {
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
}
fn line_of(&self, node: Node) -> u32 {
node.start_position().row as u32 + 1
}
fn col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
}
fn end_col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
}
fn top_row(&self) -> u32 {
self.stack.last().map(|s| s.row).unwrap_or(0)
}
fn inside_class_like(&self) -> bool {
self.stack
.last()
.map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
.unwrap_or(false)
}
fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
let name_ref = self.arena.put(name);
self.tables.push_ref(&RefRow {
from_idx: from_row,
kind: kind_code,
line: self.line_of(node),
column: self.col_of(node),
reference_name: name_ref,
candidates: NONE_STR,
from_id_str: NONE_STR,
});
if kind_code == edge_kind_index("imports").unwrap() {
if util::simple_name().is_match(name) {
self.imported_names.insert(name.to_string());
} else if let Some(c) = util::qualified_import().captures(name) {
self.imported_names.insert(c[1].to_string());
}
}
}
fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
if name.is_empty() {
return None;
}
let start_line = self.line_of(node);
let id = ids::node_id(self.file_path, kind, name, start_line);
// (c/cpp define no resolveBody hook, so createNode's endLine extension
// for sibling-body grammars never fires — endLine is the node's own.)
let end_line = node.end_position().row as u32 + 1;
let qualified = extra.qualified_name.unwrap_or_else(|| {
let mut parts: Vec<&str> = self.namespace_prefix.iter().map(|s| s.as_str()).collect();
for s in &self.stack {
if s.kind != "file" {
parts.push(&s.name);
}
}
let mut qn = parts.join("::");
if !qn.is_empty() {
qn.push_str("::");
}
qn.push_str(name);
qn
});
let mut flags = BoolFlags::default();
if let Some(v) = extra.is_exported {
flags.set(FLAG_IS_EXPORTED, v);
}
let name_ref = self.arena.put(name);
let qn_ref = self.arena.put(&qualified);
let id_ref = self.arena.put(&id);
let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
let row = self.tables.push_node(&NodeRow {
kind: node_kind_index(kind).unwrap(),
visibility: extra.visibility.unwrap_or(0),
flags,
start_line,
end_line,
start_column: self.col_of(node),
end_column: self.end_col_of(node),
name: name_ref,
qualified_name: qn_ref,
id: id_ref,
docstring: doc_ref,
signature: sig_ref,
decorators: NONE_STR,
type_parameters: NONE_STR,
return_type: ret_ref,
extra_json: NONE_STR,
});
self.nodes_meta.push(NodeMeta { kind, name: name.to_string() });
self.node_ids.push(id);
let parent_row = self.top_row();
self.tables.push_edge(&EdgeRow {
source_idx: parent_row,
target_idx: row,
kind: edge_kind_index("contains").unwrap(),
provenance: 0,
line: NONE,
column: NONE,
metadata_json: NONE_STR,
source_id_str: NONE_STR,
target_id_str: NONE_STR,
});
if kind == "function" || kind == "method" {
self.defined_fn_names.insert(name.to_string());
}
// captureValueRefScope (capture is variant-agnostic like the TS side;
// flushValueRefs gates on the language — C only).
let target_kind_ok = kind == "constant" || kind == "variable";
if target_kind_ok
&& util::utf16_len(name) >= 3
&& util::has_upper_or_underscore().is_match(name)
{
let parent_ok = self
.stack
.last()
.map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
.unwrap_or(false);
if parent_ok {
self.fs_values.insert(name.to_string(), row);
*self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
}
}
if matches!(kind, "function" | "method" | "constant" | "variable") {
self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
}
Some(row)
}
// --- name extraction -----------------------------------------------------
/// extractName: extractNameRaw + the universal recoverMangledName net
/// (wired for BOTH c and cpp in languages/c-cpp.ts).
fn extract_name(&self, node: Node) -> String {
recover_mangled_cpp_name(self.extract_name_raw(node))
}
/// extractNameRaw for the c/cpp extractor configs (nameField 'declarator';
/// cpp resolveName = extractCppQualifiedMethodName).
fn extract_name_raw(&self, node: Node) -> String {
if self.variant == Variant::Cpp {
if let Some(hook) = self.extract_cpp_qualified_method_name(node) {
return hook;
}
}
if let Some(name_node) = node.child_by_field_name("declarator") {
let mut resolved = name_node;
// Unwrap pointer/reference declarators (`int* f()`, `T& f()`).
while matches!(resolved.kind(), "pointer_declarator" | "reference_declarator") {
let inner = resolved
.child_by_field_name("declarator")
.or_else(|| resolved.named_child(0));
match inner {
Some(i) => resolved = i,
None => break,
}
}
// C++ conversion operator: `operator <type>`.
if resolved.kind() == "operator_cast" {
return match resolved.named_child(0) {
Some(t) => format!("operator {}", self.text(t).trim()),
None => self.text(resolved).to_string(),
};
}
if resolved.kind() == "function_declarator" || resolved.kind() == "declarator" {
let inner = resolved
.child_by_field_name("declarator")
.or_else(|| resolved.named_child(0));
return match inner {
Some(i) => self.text(i).to_string(),
None => self.text(resolved).to_string(),
};
}
return self.text(resolved).to_string();
}
for i in 0..node.named_child_count() {
if let Some(c) = node.named_child(i) {
if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
return self.text(c).to_string();
}
}
}
"<anonymous>".to_string()
}
/// extractCppQualifiedMethodName (languages/c-cpp.ts:75).
fn extract_cpp_qualified_method_name(&self, node: Node) -> Option<String> {
if let Some(n) = self.recover_cpp_macro_defined_name(node) {
return Some(n);
}
let declarator = node.child_by_field_name("declarator")?;
let qid = find_declarator_qualified_id(declarator)?;
let text = self.text(qid).trim();
let parts: Vec<&str> = text.split("::").filter(|p| !p.is_empty()).collect();
parts.last().map(|s| s.to_string())
}
/// recoverCppMacroDefinedName (languages/c-cpp.ts:49).
fn recover_cpp_macro_defined_name(&self, node: Node) -> Option<String> {
if node.kind() != "function_definition" {
return None;
}
let declarator = node.child_by_field_name("declarator")?;
if declarator.kind() != "function_declarator" {
return None;
}
let inner = declarator.child_by_field_name("declarator")?;
if inner.kind() != "identifier" {
return None;
}
let macro_name = self.text(inner);
if !macro_shaped_re().is_match(macro_name) {
return None;
}
let params = declarator.child_by_field_name("parameters")?;
if params.named_child_count() < 2 {
return None;
}
let lone_ident_text = |p: Node| -> Option<&'t str> {
if p.kind() == "parameter_declaration"
&& p.named_child_count() == 1
&& p.named_child(0).map(|c| c.kind() == "type_identifier").unwrap_or(false)
{
Some(self.text(p.named_child(0).unwrap()))
} else {
None
}
};
let name = params.named_child(0).and_then(lone_ident_text)?;
if !has_lower_re().is_match(name) {
return None;
}
for i in 1..params.named_child_count() {
if let Some(p) = params.named_child(i) {
if lone_ident_text(p).is_some() {
return None;
}
}
}
Some(name.to_string())
}
/// extractCppReceiverType (languages/c-cpp.ts:86).
fn receiver_type_of(&self, node: Node) -> Option<String> {
let declarator = node.child_by_field_name("declarator")?;
let qid = find_declarator_qualified_id(declarator)?;
let text = self.text(qid).trim();
let parts: Vec<&str> = text.split("::").filter(|p| !p.is_empty()).collect();
if parts.len() <= 1 {
return None;
}
let receiver = strip_cpp_template_args(&parts[..parts.len() - 1].join("::"));
if receiver.is_empty() {
None
} else {
Some(receiver)
}
}
/// extractCppReturnType: the `type` field, normalized.
fn return_type_of(&self, node: Node) -> Option<String> {
let type_node = node.child_by_field_name("type")?;
normalize_cpp_return_type(self.text(type_node))
}
/// cppExtractor.getVisibility: the FIRST access_specifier among the
/// parent's children decides (document order, not nearest-preceding —
/// bug-for-bug with the TS loop).
fn visibility_of(&self, node: Node) -> Option<u8> {
let parent = node.parent()?;
for i in 0..parent.child_count() {
let Some(child) = parent.child(i) else { continue };
if child.kind() == "access_specifier" {
let text = self.text(child);
if text.contains("public") {
return Some(1);
}
if text.contains("private") {
return Some(2);
}
if text.contains("protected") {
return Some(3);
}
}
}
None
}
/// cExtractor.isConst: any named `type_qualifier` child reading "const".
fn is_const_declaration(&self, node: Node) -> bool {
(0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.any(|c| c.kind() == "type_qualifier" && self.text(c) == "const")
}
/// cppExtractor.isMisparsedFunction (languages/c-cpp.ts:811). cpp only.
fn is_misparsed_function(&self, name: &str, node: Node) -> bool {
if self.variant != Variant::Cpp {
return false;
}
if name.starts_with("namespace") {
return true;
}
if matches!(name, "switch" | "if" | "for" | "while" | "do" | "case" | "return") {
return true;
}
is_macro_misparsed_type_decl(node)
}
/// composeReceiverQualifiedName (tree-sitter.ts:1424).
fn compose_receiver_qualified_name(&self, receiver_type: &str, name: &str) -> String {
let base = format!("{receiver_type}::{name}");
if self.namespace_prefix.is_empty() {
return base;
}
let receiver_head = receiver_type.split("::").next().unwrap_or("");
let anchor = self.namespace_prefix.iter().position(|p| p == receiver_head);
let prefix: &[String] = match anchor {
Some(i) => &self.namespace_prefix[..i],
None => &self.namespace_prefix[..],
};
if prefix.is_empty() {
base
} else {
format!("{}::{}", prefix.join("::"), base)
}
}
// --- visitNode -----------------------------------------------------------
fn visit_node(&mut self, node: Node<'t>) {
let kind = node.kind();
let mut skip_children = false;
// C++ namespace blocks: prefix-only, no node (#1291/#1093). Anonymous
// namespaces fall through to the generic walk.
if self.variant == Variant::Cpp && kind == "namespace_definition" {
let ns_name = node
.child_by_field_name("name")
.map(|n| self.text(n).to_string())
.unwrap_or_default();
if !ns_name.is_empty() {
self.namespace_prefix.push(ns_name);
for i in 0..node.named_child_count() {
if let Some(c) = node.named_child(i) {
self.visit_node(c);
}
}
self.namespace_prefix.pop();
return;
}
}
self.maybe_capture_fn_refs(node);
if kind == "function_definition" {
// functionTypes for both; cpp's methodTypes also lists it, so
// inside a class-like scope it extracts as a method.
if self.inside_class_like() && self.variant == Variant::Cpp {
self.extract_method(node);
} else {
self.extract_function(node);
}
skip_children = true;
} else if self.variant == Variant::Cpp && kind == "class_specifier" {
self.extract_class(node);
skip_children = true;
} else if kind == "struct_specifier" {
self.extract_struct(node);
skip_children = true;
} else if kind == "enum_specifier" {
self.extract_enum(node);
skip_children = true;
} else if kind == "type_definition"
|| (self.variant == Variant::Cpp && kind == "alias_declaration")
{
skip_children = self.extract_type_alias(node);
} else if kind == "declaration" && !self.inside_class_like() {
self.extract_variable(node);
self.scan_fn_ref_subtree(node, 0);
skip_children = true;
} else if kind == "preproc_include" {
self.extract_import(node);
} else if kind == "call_expression" {
self.extract_call(node);
} else if kind == "new_expression" {
// INSTANTIATION_KINDS: cpp `new Foo(...)`. (No anonymous-class
// body exists under new_expression in this grammar; children are
// still walked for nested calls.)
self.extract_instantiation(node);
}
if !skip_children {
for i in 0..node.named_child_count() {
if let Some(c) = node.named_child(i) {
self.visit_node(c);
}
}
}
}
// --- extractors ----------------------------------------------------------
fn extract_function(&mut self, node: Node<'t>) {
// Receiver present (out-of-line `Cls::method` def) → method instead.
if self.variant == Variant::Cpp && self.receiver_type_of(node).is_some() {
self.extract_method(node);
return;
}
let name = self.extract_name(node);
if name == "<anonymous>" {
if let Some(body) = node.child_by_field_name("body") {
self.visit_function_body(body);
}
return;
}
// Misparse artifacts: drop the node, still walk the body (#946/#1061).
if self.is_misparsed_function(&name, node) {
if let Some(body) = node.child_by_field_name("body") {
self.visit_function_body(body);
}
return;
}
let extra = Extra {
docstring: preceding_docstring(node, self.src),
visibility: if self.variant == Variant::Cpp { self.visibility_of(node) } else { None },
return_type: self.return_type_of(node),
..Extra::default()
};
let Some(row) = self.create_node("function", &name, node, extra) else { return };
// (extractTypeAnnotations + extractDecoratorsFor are structural no-ops
// for c/cpp: not in TYPE_ANNOTATION_LANGUAGES, and the decorator node
// kinds never appear as direct children/preceding siblings in these
// grammars — `attribute` only occurs under attribute_declaration.)
self.stack.push(Scope { row, kind: "function", name });
if let Some(body) = node.child_by_field_name("body") {
self.visit_function_body(body);
}
self.stack.pop();
}
fn extract_method(&mut self, node: Node<'t>) {
let receiver_type = if self.variant == Variant::Cpp { self.receiver_type_of(node) } else { None };
if !self.inside_class_like() && receiver_type.is_none() {
// (object-literal parents don't occur in c/cpp) — treat as function.
self.extract_function(node);
return;
}
let name = self.extract_name(node);
if self.is_misparsed_function(&name, node) {
if let Some(body) = node.child_by_field_name("body") {
self.visit_function_body(body);
}
return;
}
let extra = Extra {
docstring: preceding_docstring(node, self.src),
visibility: if self.variant == Variant::Cpp { self.visibility_of(node) } else { None },
return_type: self.return_type_of(node),
qualified_name: receiver_type
.as_ref()
.map(|r| self.compose_receiver_qualified_name(r, &name)),
..Extra::default() // extractMethod passes no isExported
};
let Some(row) = self.create_node("method", &name, node, extra) else { return };
// Out-of-line def: contains edge from the FIRST earlier-in-file
// struct/class/enum/trait node of the receiver's name.
if let Some(receiver_type) = &receiver_type {
if !self.inside_class_like() {
let owner_row = self
.nodes_meta
.iter()
.position(|m| {
m.name == *receiver_type
&& matches!(m.kind, "struct" | "class" | "enum" | "trait")
})
.map(|i| i as u32);
if let Some(owner_row) = owner_row {
self.tables.push_edge(&EdgeRow {
source_idx: owner_row,
target_idx: row,
kind: edge_kind_index("contains").unwrap(),
provenance: 0,
line: NONE,
column: NONE,
metadata_json: NONE_STR,
source_id_str: NONE_STR,
target_id_str: NONE_STR,
});
}
}
}
self.stack.push(Scope { row, kind: "method", name });
if let Some(body) = node.child_by_field_name("body") {
self.visit_function_body(body);
}
self.stack.pop();
}
/// extractClass for cpp class_specifier (skipBodilessClass, #1093).
fn extract_class(&mut self, node: Node<'t>) {
let Some(body) = node.child_by_field_name("body") else { return };
let name = self.extract_name(node);
let extra = Extra {
docstring: preceding_docstring(node, self.src),
visibility: self.visibility_of(node),
..Extra::default()
};
let Some(row) = self.create_node("class", &name, node, extra) else { return };
self.extract_inheritance(node, row);
self.stack.push(Scope { row, kind: "class", name });
for i in 0..body.named_child_count() {
if let Some(c) = body.named_child(i) {
self.visit_node(c);
}
}
self.stack.pop();
}
/// extractStruct: bodiless specifiers (fwd decls / elaborated refs) skip.
fn extract_struct(&mut self, node: Node<'t>) {
let Some(body) = node.child_by_field_name("body") else { return };
let name = self.extract_name(node);
let extra = Extra {
docstring: preceding_docstring(node, self.src),
visibility: if self.variant == Variant::Cpp { self.visibility_of(node) } else { None },
..Extra::default()
};
let Some(row) = self.create_node("struct", &name, node, extra) else { return };
self.extract_inheritance(node, row);
self.stack.push(Scope { row, kind: "struct", name });
for i in 0..body.named_child_count() {
if let Some(c) = body.named_child(i) {
self.visit_node(c);
}
}
self.stack.pop();
}
fn extract_enum(&mut self, node: Node<'t>) {
let Some(body) = node.child_by_field_name("body") else { return };
let name = self.extract_name(node);
let extra = Extra {
docstring: preceding_docstring(node, self.src),
visibility: if self.variant == Variant::Cpp { self.visibility_of(node) } else { None },
..Extra::default()