forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsharp.rs
More file actions
1610 lines (1514 loc) · 64.6 KB
/
Copy pathcsharp.rs
File metadata and controls
1610 lines (1514 loc) · 64.6 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# extraction — a faithful Rust port of `TreeSitterExtractor`'s C# paths
//! (src/extraction/tree-sitter.ts) plus languages/csharp.ts.
//!
//! Same porting contract as the other walkers: behavior parity with the wasm
//! path, bug-for-bug, verified by scripts/kernel-parity.mjs and the full-index
//! dump-diff gate. The authoritative quirk list is
//! docs/design/csharp-kernel-port-checklist.md — including every deliberate
//! emission hole (property/accessor bodies, constructor initializers,
//! delegates/events/operators/indexers, top-level locals) and garbage ref
//! (`(repo)` primary-ctor extends, `: byte` enum extends, `nameof` calls)
//! this file preserves on purpose. Positions in UTF-16 code units. Files whose
//! parse tree contains ERRORS defer to the wasm extractor.
//!
//! preParse (#237 `#if` blanking) stays TS-side: the route point hoists it, so
//! the kernel receives pre-blanked bytes — port NOTHING of it here (its regex
//! carries JS `(?m)`/CRLF semantics that must not be re-implemented).
use crate::buffers::{
build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
RefRow, StrRef, Tables, FLAG_IS_ASYNC, FLAG_IS_EXPORTED, FLAG_IS_STATIC, 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};
use std::sync::OnceLock;
use tree_sitter::{Node, Parser};
const MAX_VALUE_REF_NODES: usize = 20_000;
/// BUILTIN_TYPES (tree-sitter.ts) — the full shared table; membership is what
/// the TS code tests, so every row is ported even where only the Java/C# row
/// can fire (a C# type named `String`/`error` IS suppressed via other rows).
fn is_builtin_type(name: &str) -> bool {
matches!(
name,
"string" | "number" | "boolean" | "void" | "null" | "undefined" | "never" | "any"
| "unknown" | "object" | "symbol" | "bigint" | "true" | "false"
| "str" | "bool" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
| "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "f32" | "f64" | "char"
| "int" | "long" | "short" | "byte" | "float" | "double"
| "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"
| "float32" | "float64" | "complex64" | "complex128" | "rune" | "error"
| "Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char"
| "Unit" | "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
)
}
/// 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"
)
}
/// extractCsharpReturnType's trailing-nullable strip (`/\?+$/`).
fn trailing_nullable_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"\?+$").unwrap())
}
/// extractCsharpReturnType's generics strip (`/<[^>]*>/g`) — deliberately
/// non-nesting: `Task<List<Foo>>` → `Task>` → the ident test fails →
/// returnType undefined (same class of quirk as rust; PRESERVE).
fn generic_args_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
}
/// `/^[A-Za-z_]\w*$/` with JS's ASCII `\w` (Rust's default `\w` is Unicode).
fn ascii_ident_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").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())
}
/// JS `\s` (WhiteSpace ∪ LineTerminator) — differs from Rust's `\p{White_Space}`
/// on U+FEFF (JS: yes) and U+0085 (JS: no). The chained-call inner-callee strip
/// (`.replace(/\s+/g, '')`) runs on arbitrary source slices, so match JS exactly.
fn is_js_space(c: char) -> bool {
matches!(
c,
'\t' | '\n' | '\x0B' | '\x0C' | '\r' | ' ' | '\u{00A0}' | '\u{1680}'
| '\u{2000}'..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}'
| '\u{3000}' | '\u{FEFF}'
)
}
fn strip_js_ws(s: &str) -> String {
s.chars().filter(|c| !is_js_space(*c)).collect()
}
struct Scope {
row: u32,
kind: &'static str,
name: String,
}
#[derive(Default)]
struct Extra {
docstring: Option<String>,
signature: Option<String>,
visibility: Option<u8>,
is_static: Option<bool>,
is_async: Option<bool>,
return_type: Option<String>,
}
struct ValueScope<'t> {
row: u32,
node: Node<'t>,
name: String,
}
struct Cand {
from: u32,
name: String,
line: u32,
column_byte: usize,
row: usize,
}
pub struct Walker<'t> {
src: &'t str,
file_path: &'t str,
line_starts: Vec<usize>,
arena: Arena,
tables: Tables,
stack: Vec<Scope>,
/// Node id string per row — ids COLLIDE for same-(kind, name, line) nodes
/// and the TS side's fn-ref dedupe / value-ref self-checks key on the id.
node_ids: 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) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("csharp").ok_or("no csharp grammar")?;
let t0 = std::time::Instant::now();
let mut parser = Parser::new();
parser
.set_language(&grammar)
.map_err(|e| format!("set_language(csharp) failed: {e}"))?;
let tree = parser
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
}
let mut w = Walker {
src: source,
file_path,
line_starts: util::line_starts(source),
arena: Arena::default(),
tables: Tables::default(),
stack: Vec::new(),
node_ids: Vec::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(),
};
// File node (TreeSitterExtractor.extract). Source here is the pre-blanked
// text (the route point hoists preParse), identical bytes on both arms.
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.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
// extractFilePackage: the FIRST top-level namespace declaration mints ONE
// `namespace` node that stays pushed for the ENTIRE file — a second
// top-level namespace's types nest under the first's node/QN, nested
// namespaces leave no trace, and every import ref in a namespaced file
// hangs off this node (checklist §namespace).
let root = tree.root_node();
let mut pkg_pushed = false;
for i in 0..root.named_child_count() {
let Some(child) = root.named_child(i) else { continue };
if child.kind() != "namespace_declaration"
&& child.kind() != "file_scoped_namespace_declaration"
{
continue;
}
// csharpExtractor.extractPackage: `name` field ?? first
// qualified_name/identifier named child. No trim.
let name_node = child.child_by_field_name("name").or_else(|| {
(0..child.named_child_count())
.filter_map(|j| child.named_child(j))
.find(|c| matches!(c.kind(), "qualified_name" | "identifier"))
});
if let Some(name_node) = name_node {
let pkg = w.text(name_node).to_string();
if !pkg.is_empty() {
if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
w.stack.push(Scope { row, kind: "namespace", name: pkg });
pkg_pushed = true;
}
}
}
break;
}
w.visit_node(root);
w.flush_fn_ref_candidates();
w.flush_value_refs(root);
if pkg_pushed {
w.stack.pop();
}
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(),
})
}
/// classifyClassNode (languages/csharp.ts): a record_declaration with an
/// anonymous `struct` keyword child is a record struct.
fn record_is_struct(node: Node) -> bool {
(0..node.child_count())
.filter_map(|i| node.child(i))
.any(|c| c.kind() == "struct")
}
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(&mut self, from_row: u32, name: &str, kind_code: u8, line: u32, column: u32) {
let name_ref = self.arena.put(name);
self.tables.push_ref(&RefRow {
from_idx: from_row,
kind: kind_code,
line,
column,
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 push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
self.push_ref(from_row, name, kind_code, self.line_of(node), self.col_of(node));
}
// --- createNode ------------------------------------------------------------
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);
let end_line = node.end_position().row as u32 + 1; // no resolveBody for csharp
let qualified = {
let mut parts: Vec<&str> = Vec::new();
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_static {
flags.set(FLAG_IS_STATIC, v);
}
if let Some(v) = extra.is_async {
flags.set(FLAG_IS_ASYNC, 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, // C# extraction emits no decorators (checklist §decorators)
type_parameters: NONE_STR,
return_type: ret_ref,
extra_json: NONE_STR,
});
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());
}
self.capture_value_ref_scope(kind, name, row, node);
Some(row)
}
fn capture_value_ref_scope(&mut self, kind: &'static str, name: &str, row: u32, node: Node<'t>) {
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() });
}
}
// --- hooks (languages/csharp.ts) --------------------------------------------
//
// C# modifiers are individual named `modifier` children — there is NO
// Java-style `modifiers` wrapper (probed).
/// getVisibility: FIRST `modifier` child whose text is one of the four
/// levels wins; none → private (the C# default).
fn visibility_of(&self, node: Node) -> u8 {
for i in 0..node.child_count() {
let Some(child) = node.child(i) else { continue };
if child.kind() == "modifier" {
match self.text(child) {
"public" => return 1,
"private" => return 2,
"protected" => return 3,
"internal" => return 4,
_ => {}
}
}
}
2 // C# defaults to private
}
fn is_static(&self, node: Node) -> bool {
(0..node.child_count())
.filter_map(|i| node.child(i))
.any(|c| c.kind() == "modifier" && self.text(c) == "static")
}
fn is_async(&self, node: Node) -> bool {
(0..node.child_count())
.filter_map(|i| node.child(i))
.any(|c| c.kind() == "modifier" && self.text(c) == "async")
}
/// isConst: `const` → true; else `static` AND `readonly` both present.
fn is_const(&self, node: Node) -> bool {
let mut has_static = false;
let mut has_readonly = false;
for i in 0..node.child_count() {
let Some(child) = node.child(i) else { continue };
if child.kind() != "modifier" {
continue;
}
match self.text(child) {
"const" => return true,
"static" => has_static = true,
"readonly" => has_readonly = true,
_ => {}
}
}
has_static && has_readonly
}
/// extractCsharpReturnType — reads the `returns` field; feeds the
/// #645/#608 chained-call resolution. Constructors have no `returns`.
fn return_type_of(&self, node: Node) -> Option<String> {
let t = node.child_by_field_name("returns")?;
if matches!(t.kind(), "predefined_type" | "array_type") {
return None;
}
let mut s = self.text(t).trim().to_string();
s = trailing_nullable_re().replace(&s, "").into_owned();
s = generic_args_re().replace_all(&s, "").into_owned();
let last = s.rsplit('.').next().unwrap_or("").trim().to_string();
if last.is_empty() || !ascii_ident_re().is_match(&last) {
return None;
}
Some(last)
}
/// extractName (tree-sitter.ts:90) — the C#-reachable paths: the `name`
/// field (always present on named declarations), else the shared
/// identifier scan, else `<anonymous>`.
fn extract_name(&self, node: Node) -> String {
if let Some(name_node) = node.child_by_field_name("name") {
return self.text(name_node).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()
}
// --- the dispatcher (visitNode, C#-relevant branches) -----------------------
fn visit_node(&mut self, node: Node<'t>) {
let kind = node.kind();
let mut skip_children = false;
self.maybe_capture_fn_refs(node);
if kind == "class_declaration" || kind == "record_declaration" {
// classifyClassNode: `record struct` → extractStruct, else class.
if kind == "record_declaration" && record_is_struct(node) {
self.extract_struct(node);
} else {
self.extract_class(node);
}
skip_children = true;
} else if kind == "method_declaration" || kind == "constructor_declaration" {
self.extract_method(node);
skip_children = true;
} else if kind == "interface_declaration" {
self.extract_interface(node);
skip_children = true;
} else if kind == "struct_declaration" || kind == "record_struct_declaration" {
self.extract_struct(node);
skip_children = true;
} else if kind == "enum_declaration" {
self.extract_enum(node);
skip_children = true;
} else if kind == "property_declaration" && self.inside_class_like() {
// Property accessor/expression bodies are NEVER walked (calls
// inside are lost by design) — candidates-only scan.
self.extract_property(node);
self.scan_fn_ref_subtree(node, 0);
skip_children = true;
} else if kind == "field_declaration" && self.inside_class_like() {
self.extract_field(node);
self.scan_fn_ref_subtree(node, 0);
skip_children = true;
} else if kind == "local_declaration_statement" && !self.inside_class_like() {
// Top-level statements: extractVariable's generic fallback finds no
// direct identifier/variable_declarator children (C# nests them in
// variable_declaration) → ZERO nodes, zero refs. Candidates only.
self.extract_variable(node);
self.scan_fn_ref_subtree(node, 0);
skip_children = true;
} else if kind == "using_directive" {
self.extract_import(node);
// no skipChildren (TS importTypes branch) — children visited below
} else if kind == "invocation_expression" {
self.extract_call(node);
} else if kind == "object_creation_expression" {
self.extract_instantiation(node);
if let Some(anon_body) = find_anonymous_class_body(node) {
self.extract_anonymous_class(node, anon_body);
skip_children = true;
}
}
// Everything else (namespace_declaration, global_statement, delegates,
// events, operators, indexers, destructors, local functions, preproc_*)
// falls through: no node minted, children visited — their bodies' calls
// attribute to the enclosing scope (checklist §dispatch).
if !skip_children {
for i in 0..node.named_child_count() {
if let Some(c) = node.named_child(i) {
self.visit_node(c);
}
}
}
}
// --- visitFunctionBody ------------------------------------------------------
fn visit_function_body(&mut self, body: Node<'t>) {
self.visit_for_calls_and_structure(body);
}
fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
let kind = node.kind();
self.maybe_capture_fn_refs(node);
if kind == "invocation_expression" {
self.extract_call(node);
} else if kind == "object_creation_expression" {
self.extract_instantiation(node);
if let Some(anon_body) = find_anonymous_class_body(node) {
self.extract_anonymous_class(node, anon_body);
return;
}
}
// Static value reads (`ReadType.ReadAsDouble`) — body walker only.
self.extract_static_member_ref(node);
// (variable_declarator type-annotation branch: C# has no
// `type_annotation` child node — structurally inert, not ported.
// functionTypes is empty — no nested-function branch.)
if kind == "class_declaration" || kind == "record_declaration" {
if kind == "record_declaration" && record_is_struct(node) {
self.extract_struct(node);
} else {
self.extract_class(node);
}
return;
}
if kind == "struct_declaration" || kind == "record_struct_declaration" {
self.extract_struct(node);
return;
}
if kind == "enum_declaration" {
self.extract_enum(node);
return;
}
if kind == "interface_declaration" {
self.extract_interface(node);
return;
}
for i in 0..node.named_child_count() {
if let Some(c) = node.named_child(i) {
self.visit_for_calls_and_structure(c);
}
}
}
// --- extractors --------------------------------------------------------------
fn extract_class(&mut self, node: Node<'t>) {
// skipBodilessClass unset: a bodiless `record Empty;` still mints a node.
let name = self.extract_name(node);
let extra = Extra {
docstring: preceding_docstring(node, self.src),
visibility: Some(self.visibility_of(node)),
..Extra::default() // isExported hook absent → flag not present
};
let Some(row) = self.create_node("class", &name, node, extra) else { return };
self.extract_inheritance(node, row);
self.extract_primary_ctor_param_refs(node, row);
// extractDecoratorsFor: C# attributes never match its accepted node
// types (attribute_list is skipped, its children never reached) —
// zero `decorates` refs; the call slot emits nothing.
self.stack.push(Scope { row, kind: "class", name });
// body ?? node: a bodiless record's own children are iterated
// "harmlessly" — visit_node on identifier/parameter_list/base_list
// children falls through (base-arg identifiers still feed fn-ref
// capture, mirroring the TS walk).
let body = node.child_by_field_name("body").unwrap_or(node);
for i in 0..body.named_child_count() {
if let Some(c) = body.named_child(i) {
self.visit_node(c);
}
}
// no synthesizeMembers for C#
self.stack.pop();
}
fn extract_struct(&mut self, node: Node<'t>) {
// Body gate — EXCEPT C# positional records (`record struct M(…);`,
// node type record_declaration), complete definitions with no body.
// A bodiless `struct Fwd;` mints NO node. (#831)
let body = node.child_by_field_name("body");
if body.is_none() && node.kind() != "record_declaration" {
return;
}
let name = self.extract_name(node);
let extra = Extra {
docstring: preceding_docstring(node, self.src),
visibility: Some(self.visibility_of(node)),
..Extra::default()
};
let Some(row) = self.create_node("struct", &name, node, extra) else { return };
self.extract_inheritance(node, row);
self.extract_primary_ctor_param_refs(node, row);
// NOTE: extractStruct does NOT call extractDecoratorsFor (TS parity).
if let Some(body) = body {
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_interface(&mut self, node: Node<'t>) {
let name = self.extract_name(node);
let extra = Extra {
docstring: preceding_docstring(node, self.src),
..Extra::default() // NO visibility — extractInterface never asks
};
let Some(row) = self.create_node("interface", &name, node, extra) else { return };
self.extract_inheritance(node, row);
self.stack.push(Scope { row, kind: "interface", name });
let body = node.child_by_field_name("body").unwrap_or(node);
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: Some(self.visibility_of(node)),
..Extra::default()
};
let Some(row) = self.create_node("enum", &name, node, extra) else { return };
// The underlying type (`enum ReadType : byte`) sits in base_list →
// an `extends` ref named `byte` (garbage, PRESERVE).
self.extract_inheritance(node, row);
self.stack.push(Scope { row, kind: "enum", name });
for i in 0..body.named_child_count() {
let Some(child) = body.named_child(i) else { continue };
if child.kind() == "enum_member_declaration" {
self.extract_enum_members(child);
} else {
self.visit_node(child);
}
}
self.stack.pop();
}
fn extract_enum_members(&mut self, node: Node<'t>) {
// name-field path: one enum_member node positioned at the MEMBER node
// (attributes included in its span); values/attributes ignored.
if let Some(name_node) = node.child_by_field_name("name") {
let name = self.text(name_node).to_string();
self.create_node("enum_member", &name, node, Extra::default());
}
// (identifier-children / leaf fallbacks are other grammars' shapes)
}
/// extractProperty (1986) — property_declaration only (dispatch-gated to
/// class-like scopes). Accessor bodies and `=>` value clauses are never
/// walked; type refs DO come from the `type` field.
fn extract_property(&mut self, node: Node<'t>) {
let docstring = preceding_docstring(node, self.src);
let visibility = Some(self.visibility_of(node));
let is_static = Some(self.is_static(node)); // ?? false — always concrete
let name_node = node
.child_by_field_name("name")
.or_else(|| node.child_by_field_name("property"))
.or_else(|| {
(0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "identifier")
});
let Some(name_node) = name_node else { return };
let name = self.text(name_node).to_string();
if name.is_empty() {
return;
}
// Generic scan (isTsJsField=false): FIRST namedChild that isn't a
// modifier/name/accessor/initializer. A BARE-identifier declared type
// (`public Widget Parent {get;}`) is excluded by the `identifier`
// filter → the signature loses its type (QUIRK, preserve); the type
// ref below still fires via the `type` FIELD.
let type_node = (0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| {
!matches!(
c.kind(),
"modifier" | "modifiers" | "identifier" | "accessor_list" | "accessors"
| "equals_value_clause"
)
});
let type_text = type_node.map(|t| {
let raw = self.text(t);
// TS `.replace(/^:\s*/, '')` — inert for C# type text; mirrored.
match raw.strip_prefix(':') {
Some(rest) => rest.trim_start_matches(is_js_space).to_string(),
None => raw.to_string(),
}
});
let signature = match &type_text {
Some(t) => format!("{t} {name}"),
None => name.clone(),
};
let row = self.create_node(
"property",
&name,
node,
Extra { docstring, signature: Some(signature), visibility, is_static, ..Extra::default() },
);
if let Some(row) = row {
// decorators: none for C#; then the csharp type-ref path.
self.extract_csharp_type_refs(node, row);
}
}
/// extractField (2046) — field_declaration; each declarator becomes a
/// field/constant node anchored at the DECLARATOR.
fn extract_field(&mut self, node: Node<'t>) {
let docstring = preceding_docstring(node, self.src);
let visibility = Some(self.visibility_of(node));
let is_static = Some(self.is_static(node));
// `const` / `static readonly` → constant (value-ref targets).
let field_kind: &'static str = if self.is_const(node) { "constant" } else { "field" };
// Direct declarators (Java shape) — none for C#; the wrapper path:
let mut declarators: Vec<Node> = (0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.filter(|c| c.kind() == "variable_declarator")
.collect();
let var_decl = (0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "variable_declaration");
if declarators.is_empty() {
if let Some(vd) = var_decl {
declarators = (0..vd.named_child_count())
.filter_map(|i| vd.named_child(i))
.filter(|c| c.kind() == "variable_declarator")
.collect();
}
}
// (PHP property_element branch: unreachable for C#.)
if !declarators.is_empty() {
let type_search = var_decl.unwrap_or(node);
let type_node = (0..type_search.named_child_count())
.filter_map(|i| type_search.named_child(i))
.find(|c| {
!matches!(
c.kind(),
"modifiers" | "modifier" | "variable_declarator" | "variable_declaration"
| "marker_annotation" | "annotation"
)
});
let type_text = type_node.map(|t| self.text(t).to_string());
for decl in declarators {
let name_node = decl.child_by_field_name("name").or_else(|| {
(0..decl.named_child_count())
.filter_map(|i| decl.named_child(i))
.find(|c| c.kind() == "identifier")
});
let Some(name_node) = name_node else { continue };
let name = self.text(name_node).to_string();
let signature = match &type_text {
Some(t) => format!("{t} {name}"),
None => name.clone(),
};
let row = self.create_node(
field_kind,
&name,
decl,
Extra {
docstring: docstring.clone(),
signature: Some(signature),
visibility,
is_static,
..Extra::default()
},
);
if let Some(row) = row {
// decorators: none; type refs from the OUTER declaration —
// multi-declarator fields emit the type refs once PER
// declarator, each from its own field node.
self.extract_csharp_type_refs(node, row);
}
}
} else {
// Bare fallback (unreachable on non-erroring C#; ported for shape).
let name_node = node.child_by_field_name("name").or_else(|| {
(0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "identifier")
});
if let Some(name_node) = name_node {
let name = self.text(name_node).to_string();
self.create_node(
field_kind,
&name,
node,
Extra { docstring, visibility, is_static, ..Extra::default() },
);
}
}
}
/// extractMethod (1737) — method_declaration + constructor_declaration.
/// Signature is ALWAYS undefined (no getSignature hook); isAsync is real.
fn extract_method(&mut self, node: Node<'t>) {
if !self.inside_class_like() {
// Unreachable on non-erroring C# (top-level `void M(){}` parses as
// local_function_statement; erroring files defer) — mirror the TS
// treat-as-function tail for shape.
self.extract_function(node);
return;
}
let name = self.extract_name(node);
let extra = Extra {
docstring: preceding_docstring(node, self.src),
signature: None,
visibility: Some(self.visibility_of(node)),
is_async: Some(self.is_async(node)),
is_static: Some(self.is_static(node)),
return_type: self.return_type_of(node),
};
let Some(row) = self.create_node("method", &name, node, extra) else { return };
// extractTypeAnnotations short-circuits into the csharp path:
// `returns`-field refs FIRST, then per-parameter type refs.
self.extract_csharp_type_refs(node, row);
// decorators: none.
self.stack.push(Scope { row, kind: "method", name });
// The `body` FIELD only (block or arrow_expression_clause). A
// constructor_initializer (`: base(args)`) is NOT the body → its
// argument calls are LOST (quirk, preserve).
if let Some(body) = node.child_by_field_name("body") {
self.visit_function_body(body);
}
self.stack.pop();
}
/// extractFunction — only reachable for a method outside any class
/// (unreachable on non-erroring C#; kept faithful to the generic tail).
fn extract_function(&mut self, node: Node<'t>) {
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;
}
let extra = Extra {
docstring: preceding_docstring(node, self.src),
signature: None,
visibility: Some(self.visibility_of(node)),
is_async: Some(self.is_async(node)),
is_static: Some(self.is_static(node)),
return_type: self.return_type_of(node),
};
let Some(row) = self.create_node("function", &name, node, extra) else { return };
self.extract_csharp_type_refs(node, row);
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_variable(&mut self, node: Node<'t>) {
// extractVariable's generic fallback: direct identifier /
// variable_declarator children only — C# nests declarators inside
// variable_declaration, so this NEVER fires (`var x = F();` at top
// level produces no node, no calls ref, no instantiates — preserve).
let kind: &'static str = if self.is_const(node) { "constant" } else { "variable" };
let docstring = preceding_docstring(node, self.src);
for i in 0..node.named_child_count() {
let Some(child) = node.named_child(i) else { continue };
let name = match child.kind() {
"identifier" => self.text(child).to_string(),
"variable_declarator" => self.extract_name(child),
_ => continue,
};
if name.is_empty() || name == "<anonymous>" {
continue;
}
self.create_node(
kind,
&name,
child,
Extra { docstring: docstring.clone(), ..Extra::default() },
);
}
}
/// extractImport via csharpExtractor.extractImport: moduleName = first
/// qualified_name child's text, else first identifier's — with the alias
/// quirks (alias-to-qualified keeps generic args on the TARGET text;
/// alias-to-identifier captures the ALIAS name) preserved verbatim.
fn extract_import(&mut self, node: Node<'t>) {
let import_text = self.text(node).trim().to_string();
let target = (0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "qualified_name")
.or_else(|| {
(0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "identifier")
});
let Some(target) = target else { return }; // hook declined → no node, no ref
let module_name = self.text(target).to_string();
if module_name.is_empty() {
return;
}
self.create_node(
"import",
&module_name,
node,
Extra { signature: Some(import_text), ..Extra::default() },