Repository navigation
Expand file tree
/
Copy pathkotlin.rs
More file actions
1792 lines (1705 loc) · 71.1 KB
/
Copy pathkotlin.rs
File metadata and controls
1792 lines (1705 loc) · 71.1 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
//! Kotlin extraction — a faithful Rust port of `TreeSitterExtractor`'s Kotlin
//! paths (src/extraction/tree-sitter.ts) plus languages/kotlin.ts.
//!
//! Same porting contract as the other walkers: behavior parity, bug-for-bug.
//! The authoritative quirk list is docs/design/kotlin-kernel-port-checklist.md.
//! Two surfaces are FIRSTS for the kernel: extension-function receivers
//! (getReceiverType → `Type::method` qualified-name OVERRIDE with no package
//! prefix + the owner-contains fallback that excludes `interface` kinds and
//! is source-order dependent) and extractModifiers (expect/actual platform
//! modifiers → the node DECORATORS wire field, on every created node — the
//! KMP synthesizer's input). Preserved on purpose: the FIELD_COUNT-0 dead
//! cluster (no signatures, ZERO type-annotation refs), the bodiless-class
//! header re-walk asymmetry, enum-entry bodies being invisible, KDoc
//! (`multiline_comment`) never being a docstring AND chain-breaking,
//! comment-gluing into import/package extents,
//! `@Anno(args)` emitting nothing while `@Anno` emits decorates, zero
//! instantiates refs (constructors are capitalized `calls`), the qualified-
//! receiver `com::qext` bug, the paren-then-lambda `trailing()` garbage
//! callee, and the packaged-file value-ref target drop (namespace parents are
//! not accepted). The fun-interface misparse-recovery hook branches are
//! DEFER-SHIELDED (every such file has_error → wasm) and are not ported.
//! Positions in UTF-16 code units. Expected deferral 4.7–8.5% (both-arm,
//! grammar-inherent — incl. phantom errors: trust the has_error 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) — full shared set.
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"
)
}
/// `/^[A-Za-z_]\w*$/` with JS's ASCII `\w` (getReturnType's ident test).
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` for the #750 inner-callee strip.
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()
}
/// A property's CODE children: the named child right after the `=` token, a
/// `property_delegate` (`by lazy { … }`), and an accessor the grammar nested
/// under the declaration (`val x: Int get() = compute()` — written on ONE line;
/// an accessor on its own line parses as a SIBLING of the property and is not
/// reachable from here). What stays unwalked is the declaration itself —
/// modifiers, the `val`/`var` keyword, the name+type, and an extension
/// receiver's type and type parameters. (Go's #693 fix walks the `value` field
/// for the same reason; this grammar exposes no fields at all, hence the `=`
/// anchor.)
fn property_initializers<'t>(node: Node<'t>) -> Vec<Node<'t>> {
let mut out: Vec<Node<'t>> = Vec::new();
let mut after_eq = false;
for i in 0..node.child_count() {
let Some(c) = node.child(i) else { continue };
if !c.is_named() {
if c.kind() == "=" {
after_eq = true;
}
continue;
}
if after_eq {
out.push(c);
after_eq = false;
} else if matches!(c.kind(), "property_delegate" | "getter" | "setter") {
out.push(c);
}
}
out
}
/// Accessors written on their OWN line parse as SIBLINGS of the property, not
/// as children of it (same-line ones nest — see property_initializers). Walking
/// back over any accessors between us and the declaration finds the property an
/// accessor belongs to; None when this accessor stands alone.
fn accessor_owner<'t>(node: Node<'t>) -> Option<Node<'t>> {
let mut p = node.prev_named_sibling();
while let Some(n) = p {
if matches!(n.kind(), "getter" | "setter") {
p = n.prev_named_sibling();
continue;
}
return if n.kind() == "property_declaration" { Some(n) } else { None };
}
None
}
/// The sibling accessors that follow a property declaration, in source order.
fn following_accessors<'t>(node: Node<'t>) -> Vec<Node<'t>> {
let mut out = Vec::new();
let mut n = node.next_named_sibling();
while let Some(c) = n {
if !matches!(c.kind(), "getter" | "setter") {
break;
}
out.push(c);
n = c.next_named_sibling();
}
out
}
struct Scope {
row: u32,
kind: &'static str,
name: String,
}
/// Per-node metadata for the extension-fn owner-contains lookup.
struct NodeMeta {
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>,
/// composeReceiverQualifiedName override (extension methods) — the id
/// still hashes the bare NAME; only the qualifiedName column changes.
qualified_override: 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,
node_id_allocator: ids::NodeIdAllocator,
tables: Tables,
stack: Vec<Scope>,
node_ids: Vec<String>,
nodes_meta: Vec<NodeMeta>,
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("kotlin").ok_or("no kotlin grammar")?;
let t0 = std::time::Instant::now();
let mut parser = Parser::new();
parser
.set_language(&grammar)
.map_err(|e| format!("set_language(kotlin) failed: {e}"))?;
let tree = parser
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
// Includes the PHANTOM errors (complete CSTs with hasError set) and
// every fun-interface misparse — trust the flag, wasm is canonical.
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(),
node_id_allocator: ids::NodeIdAllocator::default(),
tables: Tables::default(),
stack: Vec::new(),
node_ids: Vec::new(),
nodes_meta: 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(),
};
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.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
// extractFilePackage: the FIRST package_header among root's direct named
// children → namespace node (comment-glued extents included), pushed for
// the whole walk.
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() != "package_header" {
continue;
}
let id_node = (0..child.named_child_count())
.filter_map(|j| child.named_child(j))
.find(|c| c.kind() == "identifier");
if let Some(id_node) = id_node {
let pkg = w.text(id_node).trim().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(),
})
}
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" | "enum_member"))
.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));
}
/// resolveBody (kotlin.ts:219): first ERROR child whose child(0) is `{`
/// (fun-interface parent body — unreachable post-defer, kept for
/// contract), else first function_body | class_body | enum_class_body.
fn resolve_body(&self, node: Node<'t>) -> Option<Node<'t>> {
for i in 0..node.named_child_count() {
let Some(child) = node.named_child(i) else { continue };
if child.kind() == "ERROR" {
if let Some(first) = child.child(0) {
if first.kind() == "{" {
return Some(child);
}
}
}
if matches!(child.kind(), "function_body" | "class_body" | "enum_class_body") {
return Some(child);
}
}
None
}
// --- 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 column = self.col_of(node);
let id = self.node_id_allocator.generate(self.file_path, kind, name, start_line, column);
// endLine extension via resolveBody — LIVE for kotlin function/method
// kinds (in-range for this grammar, so practically a no-op — but the
// hook is part of the contract).
let mut end_line = node.end_position().row as u32 + 1;
if kind == "function" || kind == "method" {
if let Some(body) = self.resolve_body(node) {
let be = body.end_position().row as u32 + 1;
if be > end_line {
end_line = be;
}
}
}
let qualified = match &extra.qualified_override {
Some(qn) => qn.clone(),
None => {
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_async {
flags.set(FLAG_IS_ASYNC, v);
}
if let Some(v) = extra.is_static {
flags.set(FLAG_IS_STATIC, v);
}
// extractModifiers merge (tree-sitter.ts:1355) — runs for EVERY
// created node: expect/actual platform modifiers → decorators.
let mods = self.extract_modifiers(node);
let dec_ref: StrRef = match &mods {
Some(list) if !list.is_empty() => self.arena.put_list(list),
_ => NONE_STR,
};
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: dec_ref,
type_parameters: NONE_STR,
return_type: ret_ref,
extra_json: NONE_STR,
});
self.node_ids.push(id);
self.nodes_meta.push(NodeMeta { kind, name: 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,
});
if kind == "function" || kind == "method" {
self.defined_fn_names.insert(name.to_string());
}
// captureValueRefScope — namespace parents are NOT accepted, so
// packaged files' top-level constants are never targets (quirk).
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)
}
// --- hooks (languages/kotlin.ts) ----------------------------------------------
/// extractName — the zero-field grammar means the nameField lookup always
/// misses; names come from the shared fallback scan (first direct
/// identifier-family child; backtick names keep their backticks).
fn extract_name(&self, node: Node) -> String {
if let Some(name_node) = node.child_by_field_name("simple_identifier") {
// nameField is a TYPE name used as a FIELD name — never resolves
// (mirrored for shape; the grammar has zero fields).
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()
}
/// getVisibility: modifiers text includes public/private/protected/
/// internal in that order; default PUBLIC. Text-includes semantics —
/// annotation text inside modifiers can flip it (bug-for-bug).
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() == "modifiers" {
let text = self.text(child);
if text.contains("public") {
return 1;
}
if text.contains("private") {
return 2;
}
if text.contains("protected") {
return 3;
}
if text.contains("internal") {
return 4;
}
}
}
1 // Kotlin defaults to public
}
/// isAsync: modifiers text includes 'suspend' (text-includes false
/// positive on `@suspendMarker` annotations — preserve).
fn is_async(&self, node: Node) -> bool {
(0..node.child_count())
.filter_map(|i| node.child(i))
.any(|c| c.kind() == "modifiers" && self.text(c).contains("suspend"))
}
/// `(params): ReturnType` — the positional read TreeSitterExtractor's
/// kotlin getSignature does (#1495): the `function_value_parameters` child,
/// then the type node that follows it before the body. Verbatim source text,
/// so it round-trips through parity byte-for-byte.
fn signature_of(&self, node: Node) -> Option<String> {
let mut params: Option<Node> = None;
let mut return_type: Option<Node> = None;
for i in 0..node.named_child_count() {
let Some(child) = node.named_child(i) else { continue };
if child.kind() == "function_value_parameters" {
params = Some(child);
continue;
}
if params.is_none() {
continue;
}
if matches!(child.kind(), "function_body" | "type_constraints") {
break;
}
if matches!(child.kind(), "user_type" | "nullable_type" | "function_type") {
return_type = Some(child);
break;
}
}
let params = params?;
let mut sig = self.text(params).to_string();
if let Some(rt) = return_type {
sig.push_str(": ");
sig.push_str(self.text(rt));
}
Some(sig)
}
/// extractKotlinReturnType — positional: the first user_type/nullable_type
/// AFTER function_value_parameters; function_body/type_constraints first →
/// None; Unit/Nothing → None; `: T` generic params leak (preserve).
fn return_type_of(&self, node: Node) -> Option<String> {
let mut seen_params = false;
for i in 0..node.named_child_count() {
let Some(child) = node.named_child(i) else { continue };
if child.kind() == "function_value_parameters" {
seen_params = true;
continue;
}
if !seen_params {
continue;
}
if matches!(child.kind(), "function_body" | "type_constraints") {
return None;
}
if matches!(child.kind(), "user_type" | "nullable_type") {
let ut = if child.kind() == "nullable_type" {
(0..child.named_child_count())
.filter_map(|j| child.named_child(j))
.find(|c| c.kind() == "user_type")
.unwrap_or(child)
} else {
child
};
let type_id = (0..ut.named_child_count())
.filter_map(|j| ut.named_child(j))
.find(|c| c.kind() == "type_identifier");
let name = self.text(type_id.unwrap_or(ut)).trim();
if name.is_empty() || !ascii_ident_re().is_match(name) {
return None;
}
if matches!(name, "Unit" | "Nothing") {
return None;
}
return Some(name.to_string());
}
}
None
}
/// getReceiverType — extension functions: the last user_type BEFORE a `.`
/// child; its FIRST type_identifier's text (qualified receivers take the
/// FIRST segment — the `com::qext` bug, preserve).
fn receiver_type_of(&self, node: Node<'t>) -> Option<String> {
let mut found_user_type: Option<Node> = None;
for i in 0..node.child_count() {
let Some(child) = node.child(i) else { continue };
match child.kind() {
"user_type" => found_user_type = Some(child),
"." => {
if let Some(ut) = found_user_type {
let type_id = (0..ut.named_child_count())
.filter_map(|j| ut.named_child(j))
.find(|c| c.kind() == "type_identifier");
return Some(self.text(type_id.unwrap_or(ut)).to_string());
}
}
"simple_identifier" | "function_value_parameters" => break,
_ => {}
}
}
None
}
/// extractModifiers — expect/actual platform modifiers, matched by NODE
/// TYPE (never text), in order. Runs inside create_node for every node.
fn extract_modifiers(&self, node: Node) -> Option<Vec<String>> {
let mut mods: Vec<String> = Vec::new();
for i in 0..node.child_count() {
let Some(child) = node.child(i) else { continue };
if child.kind() != "modifiers" {
continue;
}
for j in 0..child.child_count() {
let Some(pm) = child.child(j) else { continue };
if pm.kind() != "platform_modifier" {
continue;
}
for k in 0..pm.child_count() {
let Some(kw) = pm.child(k) else { continue };
if matches!(kw.kind(), "expect" | "actual") {
mods.push(kw.kind().to_string());
}
}
}
}
if mods.is_empty() { None } else { Some(mods) }
}
// --- the visitNode hook (property branch ONLY — fun-interface recovery is
// defer-shielded and not ported) ------------------------------------------------
/// A property's node kind, or None when the declaration mints no node at
/// all: destructuring, an unreadable name, or a local (inside a function
/// body / `init` block / lambda / accessor). Kind by enclosing scope — a
/// singleton `object` / `companion object` (and a top-level property) holds
/// SHARED values (`val`→constant, `var`→variable, the Scala-object rule; a
/// `const val` is just a val); a class/interface/enum instance `val`/`var`
/// is per-instance state → `field`.
fn property_kind(&self, node: Node<'t>) -> Option<&'static str> {
let var_decl = (0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "variable_declaration")?;
let name_node = (0..var_decl.named_child_count())
.filter_map(|i| var_decl.named_child(i))
.find(|c| c.kind() == "simple_identifier")?;
if self.text(name_node).is_empty() {
return None;
}
let mut scope: &str = "const";
let mut p = node.parent();
while let Some(pn) = p {
match pn.kind() {
"function_body" | "function_declaration" | "lambda_literal"
| "anonymous_initializer" | "control_structure_body" | "getter" | "setter" => {
scope = "local";
break;
}
"companion_object" | "object_declaration" => {
scope = "const";
break;
}
"class_declaration" => {
scope = "instance";
break;
}
_ => {}
}
p = pn.parent();
}
if scope == "local" {
return None;
}
let binding = (0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "binding_pattern_kind");
let is_val = binding.map(|b| self.text(b) == "val").unwrap_or(false);
Some(if scope == "instance" {
"field"
} else if is_val {
"constant"
} else {
"variable"
})
}
fn try_visit_hook(&mut self, node: Node<'t>) -> bool {
// An own-line accessor already walked by its owning property below. The
// ownership test re-derives the property's kind rather than remembering
// it: a destructured or local declaration mints no node, so its
// accessors were NOT consumed and must keep falling through.
if matches!(node.kind(), "getter" | "setter") {
return accessor_owner(node)
.and_then(|owner| self.property_kind(owner))
.is_some();
}
if node.kind() != "property_declaration" {
return false;
}
let var_decl = (0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "variable_declaration");
let name_node = var_decl.and_then(|vd| {
(0..vd.named_child_count())
.filter_map(|i| vd.named_child(i))
.find(|c| c.kind() == "simple_identifier")
});
// Destructuring (`val (a, b) = makePair()`): NEITHER arm mints a symbol
// for the destructured names — declining just routes the node to
// extractField/extractVariable, which both find nothing for kotlin and
// end in the same fn-ref scan. But the RHS is CODE, and it was vanishing
// whole. Consume the node here and walk it at the ENCLOSING scope (no
// symbol of its own to attribute to).
let Some(name_node) = name_node else {
for init in property_initializers(node) {
self.visit_function_body(init);
}
return true;
};
let name = self.text(name_node).to_string();
if name.is_empty() {
return false;
}
let Some(kind) = self.property_kind(node) else {
// A local — no node is minted, but the initializer is still code.
// Walk it at the ENCLOSING scope: an `init { }` block's
// `val q = load()` is the CLASS calling load, and it used to
// disappear entirely (only the block's bare statements survived).
for init in property_initializers(node) {
self.visit_function_body(init);
}
return true;
};
// The `type`-field signature read is dead (zero fields) → signature
// undefined; NO docstring/visibility/isStatic — the modifiers merge in
// create_node still decorates expect/actual properties.
let row = self.create_node(kind, &name, node, Extra::default());
// Walk the initializer ATTRIBUTED to the declared symbol (#693, the Go
// fix, ported): without this the subtree is only fn-ref-scanned, so a
// lambda / SAM / object initializer (`val cb = Runnable { target() }` —
// the idiomatic Android callback field) contributed NO call edge at all.
// The property also OWNS any accessor written on its own line, which the
// grammar makes a following SIBLING rather than a child; those bodies
// used to attribute to the enclosing class.
if let Some(row) = row {
self.stack.push(Scope { row, kind, name: name.clone() });
for init in property_initializers(node) {
self.visit_function_body(init);
}
for acc in following_accessors(node) {
self.visit_function_body(acc);
}
self.stack.pop();
}
true
}
// --- the dispatcher (visitNode, Kotlin-relevant branches) -----------------------
fn visit_node(&mut self, node: Node<'t>) {
stack_guard!();
if self.try_visit_hook(node) {
self.scan_fn_ref_subtree(node, 0);
return;
}
let kind = node.kind();
let mut skip_children = false;
self.maybe_capture_fn_refs(node);
if kind == "function_declaration" {
if self.inside_class_like() {
self.extract_method(node);
} else {
self.extract_function(node);
}
skip_children = true;
} else if kind == "class_declaration" {
// classifyClassNode: `interface`/`enum` keyword children.
let mut classified = "class";
for i in 0..node.child_count() {
if let Some(c) = node.child(i) {
if c.kind() == "interface" {
classified = "interface";
break;
}
if c.kind() == "enum" {
classified = "enum";
break;
}
}
}
match classified {
"interface" => self.extract_interface(node),
"enum" => self.extract_enum(node),
_ => self.extract_class(node),
}
skip_children = true;
} else if kind == "object_declaration" {
// extraClassNodeTypes → extractClass → kind `class`.
self.extract_class(node);
skip_children = true;
} else if kind == "type_alias" {
skip_children = self.extract_type_alias(node);
} else if kind == "property_declaration" {
// Hook-declined destructuring: extractField/extractVariable both
// find no matching children for kotlin — NOTHING minted, RHS
// invisible; candidates-only scan.
self.scan_fn_ref_subtree(node, 0);
skip_children = true;
} else if kind == "import_header" {
self.extract_import(node);
} else if kind == "call_expression" {
self.extract_call(node);
} else if kind == "infix_expression" {
self.extract_infix_call(node);
}
// companion_object, anonymous_initializer, secondary_constructor,
// getter/setter siblings, file_annotation, object_literal, if/when at
// top level: no branch — recursed (calls attribute to the stack top).
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>) {
stack_guard!();
self.visit_for_calls_and_structure(body);
}
fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
stack_guard!();
let kind = node.kind();
self.maybe_capture_fn_refs(node);
if kind == "call_expression" {
self.extract_call(node);
} else if kind == "infix_expression" {
self.extract_infix_call(node);
}
// (INSTANTIATION_KINDS has no kotlin members; extractBareCall absent.)
self.extract_static_member_ref(node);
if kind == "function_declaration" {
let name = self.extract_name(node);
if name != "<anonymous>" {
// extractFunction diverts receiver-bearing nested fns to
// extractMethod itself.
self.extract_function(node);
return;
}
}
if kind == "class_declaration" {
let mut classified = "class";
for i in 0..node.child_count() {
if let Some(c) = node.child(i) {
if c.kind() == "interface" {
classified = "interface";
break;
}
if c.kind() == "enum" {
classified = "enum";
break;
}
}
}
match classified {
"interface" => self.extract_interface(node),
"enum" => self.extract_enum(node),
_ => self.extract_class(node),
}
return;
}
// object_declaration is NOT dispatched here — a body-local object's
// `fun`s hit the function branch above and leak out as FUNCTIONS
// under the enclosing fn; its properties mint nothing (quirk).
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_function(&mut self, node: Node<'t>) {
stack_guard!();
// getReceiverType short-circuit (1522) — extension fns at any scope.
if 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) = self.resolve_body(node) {
self.visit_function_body(body);
}
return;
}
let extra = Extra {
docstring: preceding_docstring(node, self.src),
signature: self.signature_of(node),
visibility: Some(self.visibility_of(node)),
is_async: Some(self.is_async(node)),
is_static: Some(false), // kotlin isStatic is always false
return_type: self.return_type_of(node),
..Extra::default()
};
let Some(row) = self.create_node("function", &name, node, extra) else { return };
// extractTypeAnnotations: the generic path's field lookups all miss
// (zero fields) — kotlin emits ZERO type-annotation refs.
self.extract_decorators_for(node, row);
self.stack.push(Scope { row, kind: "function", name });
if let Some(body) = self.resolve_body(node) {
self.visit_function_body(body);
}
self.stack.pop();
}
fn extract_method(&mut self, node: Node<'t>) {
stack_guard!();
let receiver = self.receiver_type_of(node);
let name = self.extract_name(node);
let qualified_override = receiver.as_ref().map(|r| format!("{r}::{name}"));
let extra = Extra {
docstring: preceding_docstring(node, self.src),
signature: self.signature_of(node),
visibility: Some(self.visibility_of(node)),
is_async: Some(self.is_async(node)),
is_static: Some(false),
return_type: self.return_type_of(node),
qualified_override,
};
let Some(row) = self.create_node("method", &name, node, extra) else { return };
// Owner-contains fallback (1799): receiver present, not class-like →
// the FIRST same-file node named like the receiver with kind ∈
// {struct, class, enum, trait} (interface EXCLUDED; source-order
// dependent — both quirks preserved). Additive to the normal edge.
if let Some(recv) = &receiver {
if !self.inside_class_like() {
let owner = self