forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscala.rs
More file actions
1459 lines (1374 loc) · 56.8 KB
/
Copy pathscala.rs
File metadata and controls
1459 lines (1374 loc) · 56.8 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
//! Scala extraction — a faithful Rust port of the scala paths of
//! `TreeSitterExtractor` (src/extraction/tree-sitter.ts) plus
//! languages/scala.ts.
//!
//! Same porting contract as the other walkers: behavior parity, bug-for-bug.
//! The authoritative quirk list is docs/design/scala-kernel-port-checklist.md —
//! including the load-bearing oddities this file preserves on purpose:
//! functionTypes is EMPTY so every def routes through extractMethod (top level
//! falls back to a `function` node); NO namespace node ever (package headers
//! ignored, QNs bare); imports are named the FIRST path segment (`import
//! com.example.C` → `com`); the val/var hook keys on the enclosing-definition
//! NODE TYPE (object vals → constants, class/trait/enum/given vals → fields)
//! and consumes the initializer (no calls/instantiates from hook-consumed
//! initializers); extension methods mint NO nodes (the first def's body calls
//! leak to the enclosing scope, every later def is invisible, and the braced
//! form resolves its `body` field to the `{` TOKEN — whole extension
//! invisible); anonymous `new T { … }` bodies leak their defs to the
//! enclosing scope (findAnonymousClassBody misses template_body); nested
//! defs in bodies mint NOTHING (inverse of kotlin); the bodied-vs-bodiless
//! class asymmetry (bodiless headers walk class_parameters → default-value
//! calls emit from the class; bodied ones never see them); curried signatures
//! keep only the FIRST parameter list and type params win the `parameters`
//! field; static-member WRITES emit (unlike kotlin); infix calls are
//! invisible; `derives` emits nothing; value-ref same-name targets take the
//! LAST registration. Positions in UTF-16 code units. Files with parse errors
//! defer to wasm — including scala-3 PHANTOM hasError files (flag-true, zero
//! ERROR nodes): trust the flag.
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;
/// 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:373-388).
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"
)
}
/// BUILTIN_TYPES (tree-sitter.ts:5768-5782) — the shared cross-language table.
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"
)
}
/// SCALA_BUILTIN_TYPES (languages/scala.ts:14-17) — the hook's OWN smaller set.
fn is_scala_builtin(name: &str) -> bool {
matches!(
name,
"Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char" | "Unit"
| "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
)
}
/// extractScalaReturnType's simple-name gate (`/^[A-Za-z_]\w*$/`).
fn simple_type_name_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
}
/// extractScalaReturnType's generic-args strip (`/\[[^\]]*\]/g`).
fn bracket_args_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"\[[^\]]*\]").unwrap())
}
/// Static-member receiver gate (`/^[A-Z][A-Za-z0-9_]*$/`).
fn cap_ident_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
}
/// The #750 re-encode gate (`/^[A-Z]/`).
fn starts_upper_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[A-Z]").unwrap())
}
/// JS `\s+` for the re-encode/return-type strips (Unicode whitespace).
fn ws_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"\s+").unwrap())
}
struct Scope {
row: u32,
kind: &'static str,
name: String,
}
struct Cand {
from: u32,
name: String,
line: u32,
column_byte: usize,
row: usize,
}
struct ValueScope<'t> {
row: u32,
node: Node<'t>,
name: String,
}
#[derive(Default)]
struct Extra {
docstring: Option<String>,
signature: Option<String>,
/// 0 = absent; 1 public, 2 private, 3 protected.
visibility: u8,
/// (present, value) — isAsync/isStatic are literal-false hooks for scala.
is_async: Option<bool>,
is_static: Option<bool>,
return_type: Option<String>,
}
pub struct Walker<'t> {
src: &'t str,
file_path: &'t str,
line_starts: Vec<usize>,
arena: Arena,
tables: Tables,
stack: Vec<Scope>,
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("scala").ok_or("no scala grammar")?;
let t0 = std::time::Instant::now();
let mut parser = Parser::new();
parser
.set_language(&grammar)
.map_err(|e| format!("set_language(scala) failed: {e}"))?;
let tree = parser
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
// Includes scala-3 PHANTOMS (flag-true, zero ERROR nodes) — the flag
// is the policy, never node-scanning.
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 (tree-sitter.ts:508-521).
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() });
// No packageTypes → no namespace node, ever.
w.visit(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)
}
/// isInsideClassLikeNode (:1486) — stack-top kind only.
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: &str, node: Node) {
let name_ref = self.arena.put(name);
self.tables.push_ref(&RefRow {
from_idx: from_row,
kind: edge_kind_index(kind).unwrap(),
line: self.line_of(node),
column: self.col_of(node),
reference_name: name_ref,
candidates: NONE_STR,
from_id_str: NONE_STR,
});
// flushFnRefCandidates' importedNames (tree-sitter.ts:661-675). Scala
// import refs are named the FIRST path segment — always SIMPLE_NAME.
if kind == "imports" {
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());
}
}
}
// --- createNode (tree-sitter.ts:1308) ---------------------------------
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);
// buildQualifiedName (:1447-1460) — non-file stack names, `::`-joined;
// namespacePrefix always empty (no C++ namespaces, no scala namespace).
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 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 mut flags = BoolFlags::default();
if let Some(v) = extra.is_async {
flags.set(FLAG_IS_ASYNC, v);
}
if let Some(v) = extra.is_static {
flags.set(FLAG_IS_STATIC, v);
}
let row = self.tables.push_node(&NodeRow {
kind: node_kind_index(kind).unwrap(),
visibility: extra.visibility,
flags,
start_line,
end_line: node.end_position().row as u32 + 1, // no resolveBody hook
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.node_ids.push(id.clone());
if kind == "function" || kind == "method" {
self.defined_fn_names.insert(name.to_string());
}
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,
});
// captureValueRefScope (:735-767).
if (kind == "constant" || kind == "variable")
&& 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); // LAST wins
*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)
}
// --- languages/scala.ts helper transcriptions -------------------------
/// getValVarName (scala.ts:5-11).
fn val_var_name(&self, node: Node<'t>) -> Option<&'t str> {
let pattern = node.child_by_field_name("pattern")?;
if pattern.kind() == "identifier" {
return Some(self.text(pattern));
}
let mut cursor = pattern.walk();
for c in pattern.named_children(&mut cursor) {
if c.kind() == "identifier" {
return Some(self.text(c));
}
}
None
}
/// extractVisibility (scala.ts:69-80) → wire byte (1 public default).
fn visibility_of(&self, node: Node<'t>) -> u8 {
let mut cursor = node.walk();
for c in node.named_children(&mut cursor) {
if c.kind() == "modifiers" || c.kind() == "access_modifier" {
let t = self.text(c);
if t.contains("private") {
return 2;
}
if t.contains("protected") {
return 3;
}
}
}
1
}
/// isStatic (scala.ts:123-129) — text scan, effectively always false.
fn is_static_of(&self, node: Node<'t>) -> bool {
let mut cursor = node.walk();
for c in node.named_children(&mut cursor) {
if c.kind() == "modifiers" && self.text(c).contains("static") {
return true;
}
}
false
}
/// getSignature (scala.ts:110-117) — first-match-wins fields: curried
/// defs keep only the first list; a type_parameters node carrying field
/// `parameters` wins over the value list.
fn signature_of(&self, node: Node<'t>) -> Option<String> {
let params = node.child_by_field_name("parameters");
let ret = node.child_by_field_name("return_type");
if params.is_none() && ret.is_none() {
return None;
}
let mut sig = params.map(|p| self.text(p).to_string()).unwrap_or_default();
if let Some(r) = ret {
sig.push_str(": ");
sig.push_str(self.text(r));
}
if sig.is_empty() {
None
} else {
Some(sig)
}
}
/// extractScalaReturnType (scala.ts:56-67).
fn return_type_of(&self, node: Node<'t>) -> Option<String> {
let rt = node.child_by_field_name("return_type")?;
let raw = self.text(rt).trim();
if raw.starts_with("this.") {
return None;
}
let base = bracket_args_re().replace_all(raw, "");
let base = ws_re().replace_all(&base, "");
let last = base.split('.').next_back()?;
if last.is_empty() || !simple_type_name_re().is_match(last) {
return None;
}
Some(last.to_string())
}
/// scalaBaseTypeName (tree-sitter.ts:201-224).
fn scala_base_type_name(&self, node: Option<Node<'t>>) -> Option<String> {
let node = node?;
match node.kind() {
"type_identifier" | "identifier" => Some(self.text(node).to_string()),
"generic_type" => self.scala_base_type_name(node.named_child(0)),
"stable_type_identifier" | "stable_identifier" => {
let mut cursor = node.walk();
let last = node
.named_children(&mut cursor)
.filter(|c| c.kind() == "type_identifier" || c.kind() == "identifier")
.last();
last.map(|n| self.text(n).to_string())
}
_ => {
let mut cursor = node.walk();
let id = node
.named_children(&mut cursor)
.find(|c| c.kind() == "type_identifier");
id.map(|n| self.text(n).to_string())
}
}
}
/// emitScalaTypeRefs (scala.ts:27-45) — the hook's own builtin set.
fn emit_scala_type_refs(&mut self, type_node: Node<'t>, from_row: u32) {
if type_node.kind() == "type_identifier" {
let name = self.text(type_node);
if !name.is_empty() && !is_scala_builtin(name) {
let name = name.to_string();
self.push_ref_at(from_row, &name, "references", type_node);
}
return;
}
let mut cursor = type_node.walk();
let kids: Vec<Node<'t>> = type_node.named_children(&mut cursor).collect();
for c in kids {
self.emit_scala_type_refs(c, from_row);
}
}
/// extractName (tree-sitter.ts:98-192) — scala-reachable branches: the
/// `name` field's raw text (operator glyphs and backticks kept), else the
/// first identifier-ish child, else `<anonymous>`.
fn extract_name(&self, node: Node<'t>) -> String {
if let Some(name_node) = node.child_by_field_name("name") {
return self.text(name_node).to_string();
}
let mut cursor = node.walk();
for c in node.named_children(&mut cursor) {
if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
return self.text(c).to_string();
}
}
"<anonymous>".to_string()
}
// --- the main walk (visitNode, tree-sitter.ts:936-1303) ---------------
fn visit(&mut self, node: Node<'t>) {
// The visitNode hook (scala.ts:131-198) runs FIRST.
if self.hook(node) {
self.scan_fn_ref_subtree(node, 0);
return;
}
// maybeCaptureFnRefs (:990).
self.maybe_capture_fn_refs(node);
let kind = node.kind();
match kind {
// methodTypes (functionTypes is EMPTY — :994 never fires).
"function_definition" | "function_declaration" => {
self.extract_method_or_function(node);
return; // skipChildren
}
"class_definition" | "object_definition" => {
self.extract_class(node, "class");
return;
}
"trait_definition" => {
self.extract_class(node, "trait");
return;
}
"enum_definition" => {
self.extract_enum(node);
return;
}
"type_definition" => {
let skip = self.extract_type_alias(node);
if skip {
return;
}
// plain path → false → children re-visited (nothing matches).
}
"import_declaration" => {
self.extract_import(node);
return; // skipChildren
}
"call_expression" => {
self.extract_call(node);
// no skipChildren — chains/args re-visited
}
"instance_expression" => {
// INSTANTIATION_KINDS (:1255). findAnonymousClassBody looks
// for class_body/declaration_list — scala's template_body is
// neither → extractAnonymousClass never runs → children
// recursed: anon-body defs LEAK to the enclosing scope.
self.extract_instantiation(node);
}
_ => {}
}
let mut cursor = node.walk();
let children: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
for child in children {
self.visit(child);
}
}
/// The visitNode hook (scala.ts:131-198). Returns true when consumed.
fn hook(&mut self, node: Node<'t>) -> bool {
match node.kind() {
"val_definition" | "var_definition" => {
let is_val = node.kind() == "val_definition";
let name = match self.val_var_name(node) {
Some(n) => n.to_string(),
None => return false,
};
// Enclosing-definition NODE-TYPE walk (scala.ts:146-156).
let mut enclosing: Option<&'static str> = None;
let mut p = node.parent();
while let Some(parent) = p {
match parent.kind() {
"class_definition" => {
enclosing = Some("class_definition");
break;
}
"trait_definition" => {
enclosing = Some("trait_definition");
break;
}
"enum_definition" => {
enclosing = Some("enum_definition");
break;
}
"given_definition" => {
enclosing = Some("given_definition");
break;
}
"object_definition" => {
enclosing = Some("object_definition");
break;
}
_ => p = parent.parent(),
}
}
let is_instance_field = matches!(
enclosing,
Some("class_definition") | Some("trait_definition") | Some("enum_definition")
| Some("given_definition")
);
let kind: &'static str = if is_instance_field {
"field"
} else if is_val {
"constant"
} else {
"variable"
};
let type_node = node.child_by_field_name("type");
let signature = type_node.map(|t| {
format!("{} {}: {}", if is_val { "val" } else { "var" }, name, self.text(t))
});
let visibility = self.visibility_of(node);
let created = self.create_node(
kind,
&name,
node,
Extra { signature, visibility, ..Default::default() },
);
if let (Some(row), Some(t)) = (created, type_node) {
self.emit_scala_type_refs(t, row);
}
true
}
"enum_case_definitions" => {
let mut cursor = node.walk();
let cases: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
for case in cases {
if case.kind() == "simple_enum_case" || case.kind() == "full_enum_case" {
if let Some(name_node) = case.child_by_field_name("name") {
let name = self.text(name_node).to_string();
// ctx.createNode('enum_member', name, child) — no
// extras: no docstring/visibility/flags.
self.create_node("enum_member", &name, case, Extra::default());
}
}
}
true
}
"extension_definition" => {
// childForFieldName('body') is FIRST-MATCH-WINS over the full
// (named + anonymous) child list: paren/indent form → the
// first function_definition (its children visited — no node
// minted, later defs invisible); braced form → the `{` TOKEN
// (namedChildCount 0 — whole extension invisible).
if let Some(body) = node.child_by_field_name("body") {
let mut cursor = body.walk();
let kids: Vec<Node<'t>> = body.named_children(&mut cursor).collect();
for child in kids {
self.visit(child);
}
}
true
}
_ => false,
}
}
// --- extractMethod → extractFunction routing (:1737 / :1517) ----------
fn extract_method_or_function(&mut self, node: Node<'t>) {
// No receiver hook, no methodsAreTopLevel: inside class-like → method,
// else → function (the object/object_expression parent check never
// matches scala node kinds).
let is_method = self.inside_class_like();
let name = self.extract_name(node);
if name == "<anonymous>" {
// Unreachable for scala defs (name field required) — preserved:
// walk the body with nothing pushed.
if let Some(body) = node.child_by_field_name("body") {
self.visit_body(body);
}
return;
}
let docstring = preceding_docstring(node, self.src);
let signature = self.signature_of(node);
let visibility = self.visibility_of(node);
let is_static = self.is_static_of(node);
let return_type = self.return_type_of(node);
let row = self.create_node(
if is_method { "method" } else { "function" },
&name,
node,
Extra {
docstring,
signature,
visibility,
is_async: Some(false),
is_static: Some(is_static),
return_type,
},
);
let Some(row) = row else { return };
self.extract_type_annotations(node, row);
self.extract_decorators_for(node, row);
self.stack.push(Scope { row, kind: if is_method { "method" } else { "function" }, name });
if let Some(body) = node.child_by_field_name("body") {
self.visit_body(body);
}
self.stack.pop();
}
// --- extractClass (:1679) — classes, objects, traits ------------------
fn extract_class(&mut self, node: Node<'t>, kind: &'static str) {
let resolved_body = node.child_by_field_name("body"); // template_body
// No skipBodilessClass — bodiless mints (scala-complete).
let name = self.extract_name(node);
let docstring = preceding_docstring(node, self.src);
let visibility = self.visibility_of(node);
let row = self.create_node(
kind,
&name,
node,
Extra { docstring, visibility, ..Default::default() },
);
let Some(row) = row else { return };
self.extract_inheritance(node, row);
self.extract_decorators_for(node, row);
self.stack.push(Scope { row, kind, name });
// THE ASYMMETRY: bodiless classes walk the node ITSELF — header
// children (class_parameters defaults, extends args) reach the
// ladder; bodied classes walk only template_body children.
let body = resolved_body.unwrap_or(node);
let mut cursor = body.walk();
let children: Vec<Node<'t>> = body.named_children(&mut cursor).collect();
for child in children {
self.visit(child);
}
self.stack.pop();
}
// --- extractEnum (:1914) ----------------------------------------------
fn extract_enum(&mut self, node: Node<'t>) {
let body = match node.child_by_field_name("body") {
Some(b) => b,
None => return, // bodiless enum mints nothing
};
let name = self.extract_name(node);
let docstring = preceding_docstring(node, self.src);
let visibility = self.visibility_of(node);
let row = self.create_node(
"enum",
&name,
node,
Extra { docstring, visibility, ..Default::default() },
);
let Some(row) = row else { return };
self.extract_inheritance(node, row);
// No extractDecoratorsFor on the enum path (annotated enums emit no
// decorates — shared-pipeline behavior).
self.stack.push(Scope { row, kind: "enum", name });
// enumMemberTypes is EMPTY → every body child goes through visitNode
// (enum_case_definitions hits the hook; defs become methods).
let mut cursor = body.walk();
let children: Vec<Node<'t>> = body.named_children(&mut cursor).collect();
for child in children {
self.visit(child);
}
self.stack.pop();
}
// --- extractTypeAlias (:2890, plain path :2967-2991) ------------------
/// Returns skipChildren — always false on the scala plain path.
fn extract_type_alias(&mut self, node: Node<'t>) -> bool {
let name = self.extract_name(node);
if name == "<anonymous>" {
return false;
}
let docstring = preceding_docstring(node, self.src);
// isExported hook absent; visibility not read on this path. The
// alias-value ref walk reads field 'value' — scala's field is 'type'
// → no reference to the aliased type, ever.
self.create_node("type_alias", &name, node, Extra { docstring, ..Default::default() });
false
}
// --- extractImport (:3170-3236) ---------------------------------------
fn extract_import(&mut self, node: Node<'t>) {
let import_text = self.text(node).trim();
// extractImport hook (scala.ts:200-211): `path` field is FIRST-MATCH-
// WINS → the FIRST dotted segment names the import.
let module = if let Some(path) = node.child_by_field_name("path") {
Some(self.text(path))
} else {
let mut cursor = node.walk();
let mut found = None;
for c in node.named_children(&mut cursor) {
if c.kind() == "identifier" || c.kind() == "stable_identifier" {
found = Some(self.text(c));
break;
}
}
found
};
let Some(module) = module else { return };
let module = module.to_string();
let signature = import_text.to_string();
let created = self.create_node(
"import",
&module,
node,
Extra { signature: Some(signature), ..Default::default() },
);
// Generic imports ref (:3183-3194) — hook sets no handledRefs.
if created.is_some() && !module.is_empty() && !self.stack.is_empty() {
let parent_row = self.top_row();
self.push_ref_at(parent_row, &module, "imports", node);
}
}
// --- extractCall (:3684) ----------------------------------------------
fn extract_call(&mut self, node: Node<'t>) {
if self.stack.is_empty() {
return;
}
let caller_row = self.top_row();
let func = node
.child_by_field_name("function")
.or_else(|| node.named_child(0));
let Some(func) = func else { return };
let mut callee: Option<String> = None;
if func.kind() == "field_expression" {
// Member branch (:4364): property = `field` field for scala.
let property = func
.child_by_field_name("property")
.or_else(|| func.child_by_field_name("field"))
.or_else(|| func.named_child(1));
if let Some(property) = property {
let method_name = self.text(property);
let receiver = func
.child_by_field_name("object")
.or_else(|| func.child_by_field_name("operand"))
.or_else(|| func.child_by_field_name("argument"))
.or_else(|| func.named_child(0));
if let Some(receiver) = receiver {
if is_literal_receiver(receiver.kind()) {
return; // literal receivers emit NOTHING (#1230)
}
if matches!(receiver.kind(), "identifier" | "simple_identifier" | "field_identifier") {
let recv_name = self.text(receiver);
if matches!(recv_name, "self" | "this" | "cls" | "super") {
callee = Some(method_name.to_string());
} else {
callee = Some(format!("{recv_name}.{method_name}"));
}
} else if receiver.kind() == "call_expression" {
// The #750 re-encode, scala arm (:4443-4464): inner
// callee via the REAL `function` field; re-encode only
// capitalized (companion-factory / apply) chains.
let inner_fn = receiver.child_by_field_name("function");
let inner_callee = inner_fn
.map(|f| {
let t = self.text(f).replace("->", ".");
ws_re().replace_all(&t, "").into_owned()
})
.unwrap_or_default();
let reencode = starts_upper_re().is_match(&inner_callee);
callee = Some(if reencode {
format!("{inner_callee}().{method_name}")
} else {
method_name.to_string()
});
} else {
callee = Some(method_name.to_string());
}
} else {
callee = Some(method_name.to_string());
}
}
} else {
// Else branch (:4518-4520): RAW func text (apply-sugar `WidgetS`,
// `genericCall[Int]` type args kept, curried `curried(1)` inners).
callee = Some(self.text(func).to_string());
}
let Some(mut callee) = callee else { return };
// Parenthesized-conversion (:4529-4532).
if let Some(caps) = util::paren_conversion().captures(&callee) {
if let Some(inner) = caps.get(1) {
callee = inner.as_str().to_string();
}
}
if callee.is_empty() {
return;
}
self.push_ref_at(caller_row, &callee, "calls", node);
}
// --- extractInstantiation (:4610, scala arm :4647-4662) ---------------
fn extract_instantiation(&mut self, node: Node<'t>) {
if self.stack.is_empty() {
return;
}
let from_row = self.top_row();
let ctor = node
.child_by_field_name("constructor")
.or_else(|| node.child_by_field_name("type"))
.or_else(|| node.child_by_field_name("name"))
.or_else(|| node.named_child(0));
let Some(ctor) = ctor else { return };
if let Some(name) = self.scala_base_type_name(Some(ctor)) {
self.push_ref_at(from_row, &name, "instantiates", node);
}
}
// --- extractStaticMemberRef (:4750-4808) ------------------------------
fn extract_static_member_ref(&mut self, node: Node<'t>) {
if self.stack.is_empty() {
return;
}
let owner_row = self.top_row();
// MEMBER_ACCESS_TYPES — only field_expression occurs in scala trees.
if !matches!(
node.kind(),
"field_access" | "member_access_expression" | "navigation_expression"
| "field_expression" | "class_constant_access_expression"
| "scoped_property_access_expression" | "qualified_identifier"
) {
return;
}
// Callee-of-call skip: `Type.method()`'s callee access is already a
// calls ref.
if let Some(parent) = node.parent() {
if parent.kind() == "call_expression" {
let callee = parent
.child_by_field_name("function")
.or_else(|| parent.child_by_field_name("method"))
.or_else(|| parent.named_child(0));
if let Some(callee) = callee {
if callee.start_byte() == node.start_byte() {
return;
}
}
}
}
let recv = node
.child_by_field_name("object")
.or_else(|| node.child_by_field_name("expression"))
.or_else(|| node.child_by_field_name("scope"))
.or_else(|| node.named_child(0));
let Some(recv) = recv else { return };
if matches!(
recv.kind(),
"identifier" | "type_identifier" | "simple_identifier" | "name" | "scoped_type_identifier"
) {
let text = self.text(recv);
if cap_ident_re().is_match(text) {
let text = text.to_string();
self.push_ref_at(owner_row, &text, "references", recv);
}
}
}
// --- extractDecoratorsFor (:4897-5024) --------------------------------
fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) {
// consider(): scala annotations are `annotation` nodes; the name is
// the first identifier-ish child (type_identifier for scala), with
// call_expression unwrap for invoked decorators.
// Scan 1: direct children (+ modifiers descent — inert for scala,