code-graph-cli 3.0.1

Code intelligence engine for TypeScript/JavaScript/Rust/Python/Go — query the dependency graph instead of reading source files.
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
use std::sync::OnceLock;

use tree_sitter::{Language, Node, Query, QueryCursor, StreamingIterator, Tree};

use crate::graph::node::{DecoratorInfo, SymbolInfo, SymbolKind, SymbolVisibility};

// ---------------------------------------------------------------------------
// Rust query string
// ---------------------------------------------------------------------------

/// Tree-sitter S-expression query for Rust (`.rs`) top-level items.
/// impl blocks are NOT captured here — they are walked directly via `extract_impl_methods`.
const SYMBOL_QUERY_RS: &str = r#"
    (function_item name: (identifier) @name) @symbol
    (struct_item name: (type_identifier) @name) @symbol
    (enum_item name: (type_identifier) @name) @symbol
    (trait_item name: (type_identifier) @name) @symbol
    (type_item name: (type_identifier) @name) @symbol
    (const_item name: (identifier) @name) @symbol
    (static_item name: (identifier) @name) @symbol
    (macro_definition name: (identifier) @name) @symbol
"#;

// ---------------------------------------------------------------------------
// Query strings
// ---------------------------------------------------------------------------

/// Tree-sitter S-expression query for TypeScript (`.ts`) files.
const SYMBOL_QUERY_TS: &str = r#"
    ; Top-level function declarations
    (function_declaration
      name: (identifier) @name) @symbol

    ; Class declarations
    (class_declaration
      name: (type_identifier) @name) @symbol

    ; Interface declarations (TS-only)
    (interface_declaration
      name: (type_identifier) @name) @symbol

    ; Type alias declarations (TS-only)
    (type_alias_declaration
      name: (type_identifier) @name) @symbol

    ; Enum declarations
    (enum_declaration
      name: (identifier) @name) @symbol

    ; Exported arrow-function constants: export const Foo = () => {}
    (export_statement
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (arrow_function)))) @symbol

    ; Top-level non-exported arrow-function constants: const Foo = () => {}
    (program
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (arrow_function)))) @symbol

    ; Exported variables that are NOT arrow functions: export const Foo = value
    (export_statement
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (_) @val))) @symbol
"#;

/// Tree-sitter S-expression query for TSX (`.tsx`) and JSX (`.jsx`) files.
const SYMBOL_QUERY_TSX: &str = r#"
    ; Top-level function declarations
    (function_declaration
      name: (identifier) @name) @symbol

    ; Class declarations
    (class_declaration
      name: (type_identifier) @name) @symbol

    ; Interface declarations (TS-only but TSX grammar supports it)
    (interface_declaration
      name: (type_identifier) @name) @symbol

    ; Type alias declarations (TS-only but TSX grammar supports it)
    (type_alias_declaration
      name: (type_identifier) @name) @symbol

    ; Enum declarations
    (enum_declaration
      name: (identifier) @name) @symbol

    ; Exported arrow-function constants
    (export_statement
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (arrow_function)))) @symbol

    ; Top-level non-exported arrow-function constants
    (program
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (arrow_function)))) @symbol

    ; Exported variables that are NOT arrow functions
    (export_statement
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (_) @val))) @symbol
"#;

/// Tree-sitter S-expression query for JavaScript (`.js`/`.jsx`) files.
/// JavaScript does not have interface/type-alias/enum declarations.
const SYMBOL_QUERY_JS: &str = r#"
    ; Top-level function declarations
    (function_declaration
      name: (identifier) @name) @symbol

    ; Class declarations
    (class_declaration
      name: (identifier) @name) @symbol

    ; Exported arrow-function constants
    (export_statement
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (arrow_function)))) @symbol

    ; Top-level non-exported arrow-function constants
    (program
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (arrow_function)))) @symbol

    ; Exported variables that are NOT arrow functions
    (export_statement
      (lexical_declaration
        (variable_declarator
          name: (identifier) @name
          value: (_) @val))) @symbol
"#;

// ---------------------------------------------------------------------------
// Query cache (compiled once per language via OnceLock)
// ---------------------------------------------------------------------------

static TS_QUERY: OnceLock<Query> = OnceLock::new();
static TSX_QUERY: OnceLock<Query> = OnceLock::new();
static JS_QUERY: OnceLock<Query> = OnceLock::new();
static RS_SYMBOL_QUERY: OnceLock<Query> = OnceLock::new();

fn ts_query(language: &Language) -> &'static Query {
    TS_QUERY.get_or_init(|| Query::new(language, SYMBOL_QUERY_TS).expect("invalid TS symbol query"))
}

fn tsx_query(language: &Language) -> &'static Query {
    TSX_QUERY
        .get_or_init(|| Query::new(language, SYMBOL_QUERY_TSX).expect("invalid TSX symbol query"))
}

fn js_query(language: &Language) -> &'static Query {
    JS_QUERY.get_or_init(|| Query::new(language, SYMBOL_QUERY_JS).expect("invalid JS symbol query"))
}

fn rs_symbol_query(language: &Language) -> &'static Query {
    RS_SYMBOL_QUERY
        .get_or_init(|| Query::new(language, SYMBOL_QUERY_RS).expect("invalid RS symbol query"))
}

// ---------------------------------------------------------------------------
// Helper utilities
// ---------------------------------------------------------------------------

/// Extract the UTF-8 text of a node from the original source bytes.
fn node_text<'a>(node: Node<'a>, source: &'a [u8]) -> &'a str {
    node.utf8_text(source).unwrap_or("")
}

/// Check whether `node` is — or is nested inside — an `export_statement`.
/// Returns `(is_exported, is_default)`.
fn detect_export(node: Node, source: &[u8]) -> (bool, bool) {
    // Start from `node` itself (the @symbol capture may BE the export_statement)
    let mut current = Some(node);
    while let Some(n) = current {
        if n.kind() == "export_statement" {
            // Check for `default` keyword among direct children
            let is_default = (0..n.child_count()).any(|i| {
                n.child(i as u32)
                    .map(|c| node_text(c, source) == "default")
                    .unwrap_or(false)
            });
            return (true, is_default);
        }
        current = n.parent();
    }
    (false, false)
}

/// Return true when the tree rooted at `node` contains a `jsx_element`,
/// `jsx_fragment`, or `jsx_self_closing_element` anywhere in its descendants.
fn contains_jsx(node: Node) -> bool {
    if matches!(
        node.kind(),
        "jsx_element" | "jsx_fragment" | "jsx_self_closing_element"
    ) {
        return true;
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if contains_jsx(child) {
            return true;
        }
    }
    false
}

/// Return true if `node` is an `arrow_function` or a `function` expression.
fn is_arrow_or_function_value(node: Node) -> bool {
    matches!(node.kind(), "arrow_function" | "function")
}

// ---------------------------------------------------------------------------
// Symbol classification
// ---------------------------------------------------------------------------

/// Classify the kind of a top-level match node.
///
/// `symbol_node` is the `@symbol` capture (the outer statement node).
/// `name_node` is the `@name` capture (the identifier node).
/// `val_node` is the optional `@val` capture (value in a `variable_declarator`).
/// `is_tsx` enables JSX component detection.
fn classify_symbol(
    symbol_node: Node,
    name_node: Node,
    val_node: Option<Node>,
    is_tsx: bool,
    _source: &[u8],
) -> Option<SymbolKind> {
    let kind = find_declaration_kind(symbol_node, name_node);

    match kind.as_deref() {
        Some("function_declaration") => {
            if is_tsx && function_body_contains_jsx(symbol_node) {
                Some(SymbolKind::Component)
            } else {
                Some(SymbolKind::Function)
            }
        }
        Some("class_declaration") => Some(SymbolKind::Class),
        Some("interface_declaration") => Some(SymbolKind::Interface),
        Some("type_alias_declaration") => Some(SymbolKind::TypeAlias),
        Some("enum_declaration") => Some(SymbolKind::Enum),
        Some("arrow_function_decl") => {
            if is_tsx && arrow_body_contains_jsx(symbol_node, name_node) {
                Some(SymbolKind::Component)
            } else {
                Some(SymbolKind::Function)
            }
        }
        Some("exported_variable") => {
            if let Some(val) = val_node {
                if is_arrow_or_function_value(val) {
                    // arrow function — should have been caught earlier but handle defensively
                    if is_tsx && arrow_body_contains_jsx(symbol_node, name_node) {
                        Some(SymbolKind::Component)
                    } else {
                        Some(SymbolKind::Function)
                    }
                } else {
                    Some(SymbolKind::Variable)
                }
            } else {
                Some(SymbolKind::Variable)
            }
        }
        _ => None,
    }
}

/// Classify `symbol_node` by inspecting its kind and children.
/// Returns a synthetic kind string.
fn find_declaration_kind(symbol_node: Node, _name_node: Node) -> Option<String> {
    let kind = symbol_node.kind();
    match kind {
        "function_declaration" => Some("function_declaration".into()),
        "class_declaration" => Some("class_declaration".into()),
        "interface_declaration" => Some("interface_declaration".into()),
        "type_alias_declaration" => Some("type_alias_declaration".into()),
        "enum_declaration" => Some("enum_declaration".into()),
        "export_statement" => {
            let mut cursor = symbol_node.walk();
            for child in symbol_node.children(&mut cursor) {
                match child.kind() {
                    "function_declaration" => return Some("function_declaration".into()),
                    "class_declaration" => return Some("class_declaration".into()),
                    "interface_declaration" => return Some("interface_declaration".into()),
                    "type_alias_declaration" => return Some("type_alias_declaration".into()),
                    "enum_declaration" => return Some("enum_declaration".into()),
                    "lexical_declaration" => {
                        return classify_lexical_declaration(child);
                    }
                    _ => {}
                }
            }
            None
        }
        "lexical_declaration" => classify_lexical_declaration(symbol_node),
        _ => None,
    }
}

/// Inspect a `lexical_declaration` to determine if its declarator value is an
/// arrow function or plain expression.
fn classify_lexical_declaration(lex_decl: Node) -> Option<String> {
    let mut cursor = lex_decl.walk();
    for child in lex_decl.children(&mut cursor) {
        if child.kind() == "variable_declarator"
            && let Some(value_node) = child.child_by_field_name("value")
        {
            if is_arrow_or_function_value(value_node) {
                return Some("arrow_function_decl".into());
            } else {
                return Some("exported_variable".into());
            }
        }
    }
    None
}

/// True if a `function_declaration` node's body contains JSX.
fn function_body_contains_jsx(func_node: Node) -> bool {
    if let Some(body) = func_node.child_by_field_name("body") {
        return contains_jsx(body);
    }
    false
}

/// True if the arrow function value for the variable named by `name_node`
/// has a body containing JSX.
fn arrow_body_contains_jsx(symbol_node: Node, name_node: Node) -> bool {
    find_arrow_body(symbol_node, name_node)
        .map(contains_jsx)
        .unwrap_or(false)
}

/// Locate the `body` of the arrow function whose declarator matches `name_node`.
fn find_arrow_body<'a>(node: Node<'a>, name_node: Node<'a>) -> Option<Node<'a>> {
    if node.kind() == "variable_declarator"
        && let Some(decl_name) = node.child_by_field_name("name")
        && decl_name.id() == name_node.id()
        && let Some(value) = node.child_by_field_name("value")
        && is_arrow_or_function_value(value)
    {
        return value.child_by_field_name("body");
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(found) = find_arrow_body(child, name_node) {
            return Some(found);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Child-symbol extraction
// ---------------------------------------------------------------------------

/// Extract `property_signature` and `method_signature` children from an
/// `interface_body` as `SymbolKind::Property` child symbols.
fn extract_interface_children(iface_node: Node, source: &[u8]) -> Vec<SymbolInfo> {
    let mut children = Vec::new();
    // Find the interface_body child
    let body = {
        let mut found = None;
        let mut cursor = iface_node.walk();
        for child in iface_node.children(&mut cursor) {
            if child.kind() == "interface_body" {
                found = Some(child);
                break;
            }
        }
        match found {
            Some(b) => b,
            None => return children,
        }
    };

    let mut cursor = body.walk();
    for child in body.children(&mut cursor) {
        match child.kind() {
            "property_signature" | "method_signature" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = node_text(name_node, source).to_owned();
                    let pos = name_node.start_position();
                    children.push(SymbolInfo {
                        name,
                        kind: SymbolKind::Property,
                        line: pos.row + 1,
                        col: pos.column,
                        line_end: child.end_position().row + 1,
                        ..Default::default()
                    });
                }
            }
            _ => {}
        }
    }
    children
}

/// Extract `method_definition` children from a `class_body` as
/// `SymbolKind::Method` child symbols.
fn extract_class_children(class_node: Node, source: &[u8]) -> Vec<SymbolInfo> {
    let mut children = Vec::new();
    let body = {
        let mut found = None;
        let mut cursor = class_node.walk();
        for child in class_node.children(&mut cursor) {
            if child.kind() == "class_body" {
                found = Some(child);
                break;
            }
        }
        match found {
            Some(b) => b,
            None => return children,
        }
    };

    let mut cursor = body.walk();
    for child in body.children(&mut cursor) {
        if child.kind() == "method_definition"
            && let Some(name_node) = child.child_by_field_name("name")
        {
            let name = node_text(name_node, source).to_owned();
            let pos = name_node.start_position();
            let decorators = extract_ts_decorators(child, source);
            children.push(SymbolInfo {
                name,
                kind: SymbolKind::Method,
                line: pos.row + 1,
                col: pos.column,
                line_end: child.end_position().row + 1,
                decorators,
                ..Default::default()
            });
        }
    }
    children
}

// ---------------------------------------------------------------------------
// Decorator / attribute extraction helpers
// ---------------------------------------------------------------------------

/// Extract decorators from a TS/JS node.
///
/// In tree-sitter-typescript 0.23+, decorators are children with field name "decorator"
/// within the decorated declaration node (class_declaration, function_declaration, etc.).
/// We also check previous siblings in the parent for decorator nodes (older grammar or
/// cases where the decorated node is inside an export_statement).
fn extract_ts_decorators(node: tree_sitter::Node, source: &[u8]) -> Vec<DecoratorInfo> {
    let mut decorators = Vec::new();

    // Strategy 1: look for decorator-typed children of node itself (e.g. class_declaration).
    for i in 0..node.child_count() {
        let child = node.child(i as u32).unwrap();
        if child.kind() == "decorator" {
            decorators.push(parse_decorator_node(child, source));
        }
    }
    if !decorators.is_empty() {
        return decorators;
    }

    // Strategy 2: check children of the inner declaration (for export_statement wrapping).
    // Find the actual declaration child and look at ITS decorator children.
    for i in 0..node.child_count() {
        let child = node.child(i as u32).unwrap();
        match child.kind() {
            "class_declaration"
            | "function_declaration"
            | "interface_declaration"
            | "type_alias_declaration"
            | "enum_declaration" => {
                for j in 0..child.child_count() {
                    let grandchild = child.child(j as u32).unwrap();
                    if grandchild.kind() == "decorator" {
                        decorators.push(parse_decorator_node(grandchild, source));
                    }
                }
                if !decorators.is_empty() {
                    return decorators;
                }
            }
            _ => {}
        }
    }

    // Strategy 3: walk previous siblings in the parent (fallback for older grammars).
    let parent = match node.parent() {
        Some(p) => p,
        None => return decorators,
    };
    for i in 0..parent.child_count() {
        let child = parent.child(i as u32).unwrap();
        if child.id() == node.id() {
            break; // stop at current node
        }
        if child.kind() == "decorator" {
            decorators.push(parse_decorator_node(child, source));
        }
    }
    decorators
}

/// Parse a single `decorator` node into a `DecoratorInfo`.
/// Shared between TS/JS (and later Python).
fn parse_decorator_node(decorator_node: tree_sitter::Node, source: &[u8]) -> DecoratorInfo {
    let inner = decorator_node.named_child(0);
    match inner.map(|n| n.kind()) {
        Some("identifier") => {
            let name = node_text(inner.unwrap(), source).to_owned();
            DecoratorInfo {
                name,
                object: None,
                attribute: None,
                args_raw: None,
                framework: None,
            }
        }
        Some("member_expression") | Some("attribute") => {
            let attr_node = inner.unwrap();
            let obj = attr_node
                .child_by_field_name("object")
                .map(|n| node_text(n, source).to_owned());
            let attr = attr_node
                .child_by_field_name("property")
                .or_else(|| attr_node.child_by_field_name("attribute"))
                .map(|n| node_text(n, source).to_owned());
            let name = format!(
                "{}.{}",
                obj.as_deref().unwrap_or(""),
                attr.as_deref().unwrap_or("")
            );
            DecoratorInfo {
                name,
                object: obj,
                attribute: attr,
                args_raw: None,
                framework: None,
            }
        }
        Some("call_expression") => {
            let call = inner.unwrap();
            let func = call.child_by_field_name("function");
            let args = call
                .child_by_field_name("arguments")
                .map(|n| node_text(n, source).to_owned());
            let (name, obj, attr) = match func.map(|f| f.kind()) {
                Some("identifier") => {
                    let n = node_text(func.unwrap(), source).to_owned();
                    (n, None, None)
                }
                Some("member_expression") => {
                    let f = func.unwrap();
                    let o = f
                        .child_by_field_name("object")
                        .map(|n| node_text(n, source).to_owned());
                    let a = f
                        .child_by_field_name("property")
                        .map(|n| node_text(n, source).to_owned());
                    let n = format!(
                        "{}.{}",
                        o.as_deref().unwrap_or(""),
                        a.as_deref().unwrap_or("")
                    );
                    (n, o, a)
                }
                _ => (node_text(call, source).to_owned(), None, None),
            };
            DecoratorInfo {
                name,
                object: obj,
                attribute: attr,
                args_raw: args,
                framework: None,
            }
        }
        _ => DecoratorInfo {
            name: node_text(decorator_node, source).to_owned(),
            object: None,
            attribute: None,
            args_raw: None,
            framework: None,
        },
    }
}

/// Walk previous siblings of `item_node` in its parent to find `attribute_item` nodes (Rust).
fn extract_rust_attributes(item_node: tree_sitter::Node, source: &[u8]) -> Vec<DecoratorInfo> {
    let mut attrs = Vec::new();
    let parent = match item_node.parent() {
        Some(p) => p,
        None => return attrs,
    };
    for i in 0..parent.child_count() {
        let child = parent.child(i as u32).unwrap();
        if child.id() == item_node.id() {
            break;
        }
        if child.kind() == "attribute_item" {
            attrs.push(parse_rust_attribute(child, source));
        }
    }
    attrs
}

/// Parse a Rust `attribute_item` node (e.g. `#[derive(Clone, Debug)]`) into a `DecoratorInfo`.
fn parse_rust_attribute(attr_item: tree_sitter::Node, source: &[u8]) -> DecoratorInfo {
    let full_text = node_text(attr_item, source);
    // Strip outer #[ and ]
    let inner = full_text
        .trim_start_matches("#[")
        .trim_start_matches("#![")
        .trim_end_matches(']');
    // Split name from args at first '('
    let (name, args) = match inner.find('(') {
        Some(idx) => (
            inner[..idx].trim().to_owned(),
            Some(inner[idx..].to_owned()),
        ),
        None => (inner.trim().to_owned(), None),
    };
    DecoratorInfo {
        name,
        object: None,
        attribute: None,
        args_raw: args,
        framework: None,
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Which language group a file falls into (used for query selection).
enum LangKind {
    TypeScript,
    Tsx,
    JavaScript,
}

fn lang_kind(language: &Language, is_tsx: bool) -> LangKind {
    // Use the language name to distinguish TS / TSX / JS.
    match language.name().unwrap_or("") {
        "javascript" => LangKind::JavaScript,
        _ => {
            if is_tsx {
                LangKind::Tsx
            } else {
                LangKind::TypeScript
            }
        }
    }
}

/// Extract all symbols from a parsed syntax tree.
///
/// Returns a `Vec` of `(parent_symbol, child_symbols)` tuples.
///
/// # Parameters
/// - `tree`: the tree-sitter syntax tree
/// - `source`: the raw UTF-8 source bytes
/// - `language`: the grammar used to parse `source`
/// - `is_tsx`: `true` for `.tsx`/`.jsx` files — enables JSX component detection
pub fn extract_symbols(
    tree: &Tree,
    source: &[u8],
    language: &Language,
    is_tsx: bool,
) -> Vec<(SymbolInfo, Vec<SymbolInfo>)> {
    let query = match lang_kind(language, is_tsx) {
        LangKind::JavaScript => js_query(language),
        LangKind::Tsx => tsx_query(language),
        LangKind::TypeScript => ts_query(language),
    };

    let name_idx = query
        .capture_index_for_name("name")
        .expect("query must have @name capture");
    let symbol_idx = query
        .capture_index_for_name("symbol")
        .expect("query must have @symbol capture");
    let val_idx = query.capture_index_for_name("val");

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, tree.root_node(), source);

    // De-duplicate by (name, line) to avoid double-matches from overlapping patterns.
    let mut seen: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new();
    let mut results: Vec<(SymbolInfo, Vec<SymbolInfo>)> = Vec::new();

    while let Some(m) = matches.next() {
        let mut symbol_node: Option<Node> = None;
        let mut name_node: Option<Node> = None;
        let mut val_node: Option<Node> = None;

        for capture in m.captures {
            if capture.index == symbol_idx {
                symbol_node = Some(capture.node);
            } else if capture.index == name_idx {
                name_node = Some(capture.node);
            } else if val_idx == Some(capture.index) {
                val_node = Some(capture.node);
            }
        }

        let (sym_node, name_node) = match (symbol_node, name_node) {
            (Some(s), Some(n)) => (s, n),
            _ => continue,
        };

        let name = node_text(name_node, source).to_owned();
        let pos = name_node.start_position();
        let key = (name.clone(), pos.row);

        // Skip duplicate matches (overlapping patterns)
        if !seen.insert(key) {
            continue;
        }

        // Classify the symbol kind
        let kind = match classify_symbol(sym_node, name_node, val_node, is_tsx, source) {
            Some(k) => k,
            None => continue,
        };

        // For exported-variable matches that are actually arrow functions — skip.
        if kind == SymbolKind::Variable
            && let Some(val) = val_node
            && is_arrow_or_function_value(val)
        {
            continue;
        }

        let (is_exported, is_default) = detect_export(sym_node, source);
        let decorators = extract_ts_decorators(sym_node, source);

        let info = SymbolInfo {
            name,
            kind: kind.clone(),
            line: pos.row + 1,
            col: pos.column,
            line_end: sym_node.end_position().row + 1,
            is_exported,
            is_default,
            decorators,
            ..Default::default()
        };

        // Extract child symbols
        let children = match kind {
            SymbolKind::Interface => {
                let iface_node = find_declaration_node(sym_node, "interface_declaration");
                iface_node
                    .map(|n| extract_interface_children(n, source))
                    .unwrap_or_default()
            }
            SymbolKind::Class => {
                let class_node = find_declaration_node(sym_node, "class_declaration");
                class_node
                    .map(|n| extract_class_children(n, source))
                    .unwrap_or_default()
            }
            _ => vec![],
        };

        results.push((info, children));
    }

    results
}

/// Walk down from `node` to find a child (or the node itself) of kind `target_kind`.
fn find_declaration_node<'a>(node: Node<'a>, target_kind: &str) -> Option<Node<'a>> {
    if node.kind() == target_kind {
        return Some(node);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(found) = find_declaration_node(child, target_kind) {
            return Some(found);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Rust-specific helpers
// ---------------------------------------------------------------------------

/// Extract visibility from a Rust item node.
///
/// Looks for a `visibility_modifier` child:
/// - `"pub"` alone → `Pub`
/// - `"pub(..."` (any variant incl. pub(crate), pub(super), pub(in ...)) → `PubCrate`
/// - No modifier → `Private`
fn extract_visibility(node: Node, source: &[u8]) -> SymbolVisibility {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "visibility_modifier" {
            let text = node_text(child, source);
            if text == "pub" {
                return SymbolVisibility::Pub;
            } else if text.starts_with("pub(") {
                return SymbolVisibility::PubCrate;
            }
            // Any other visibility_modifier falls through to Private
        }
    }
    SymbolVisibility::Private
}

/// Extract a simple type name from an impl block's "type" field node.
///
/// Handles:
/// - `type_identifier` | `scoped_type_identifier` → text as-is
/// - `generic_type` → read the "type" field child's text (strips generics)
/// - Fallback → text as-is
fn extract_simple_type_name<'a>(type_node: Node<'a>, source: &'a [u8]) -> &'a str {
    match type_node.kind() {
        "type_identifier" | "scoped_type_identifier" => node_text(type_node, source),
        "generic_type" => {
            // `HashMap<K, V>` → get the "type" field which is `HashMap`
            if let Some(name_node) = type_node.child_by_field_name("type") {
                node_text(name_node, source)
            } else {
                node_text(type_node, source)
            }
        }
        _ => node_text(type_node, source),
    }
}

/// Extract trait methods from a `trait_item` node as child `SymbolInfo` entries.
///
/// Handles both:
/// - `function_signature_item`: required methods (no body)
/// - `function_item`: default methods (has body)
fn extract_trait_methods(trait_node: Node, trait_name: &str, source: &[u8]) -> Vec<SymbolInfo> {
    let mut methods = Vec::new();

    // Find the declaration_list child
    let decl_list = {
        let mut found = None;
        let mut cursor = trait_node.walk();
        for child in trait_node.children(&mut cursor) {
            if child.kind() == "declaration_list" {
                found = Some(child);
                break;
            }
        }
        match found {
            Some(n) => n,
            None => return methods,
        }
    };

    let mut cursor = decl_list.walk();
    for child in decl_list.children(&mut cursor) {
        match child.kind() {
            "function_signature_item" | "function_item" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let method_name = node_text(name_node, source);
                    let qualified_name = format!("{}::{}", trait_name, method_name);
                    let pos = name_node.start_position();
                    let visibility = extract_visibility(child, source);
                    let decorators = extract_rust_attributes(child, source);
                    methods.push(SymbolInfo {
                        name: qualified_name,
                        kind: SymbolKind::ImplMethod,
                        line: pos.row + 1,
                        col: pos.column,
                        line_end: child.end_position().row + 1,
                        visibility,
                        decorators,
                        ..Default::default()
                    });
                }
            }
            _ => {}
        }
    }

    methods
}

// ---------------------------------------------------------------------------
// Rust public API
// ---------------------------------------------------------------------------

/// Extract top-level Rust symbols from a parsed syntax tree.
///
/// Returns a `Vec` of `(parent_symbol, child_symbols)` tuples.
/// For trait items, child_symbols contains the trait's methods.
/// For all other items, child_symbols is empty.
pub fn extract_rust_symbols(
    tree: &Tree,
    source: &[u8],
    language: &Language,
) -> Vec<(SymbolInfo, Vec<SymbolInfo>)> {
    let query = rs_symbol_query(language);

    let name_idx = query
        .capture_index_for_name("name")
        .expect("RS query must have @name capture");
    let symbol_idx = query
        .capture_index_for_name("symbol")
        .expect("RS query must have @symbol capture");

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, tree.root_node(), source);

    // De-duplicate by (name, row) — same pattern as TS/JS
    let mut seen: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new();
    let mut results: Vec<(SymbolInfo, Vec<SymbolInfo>)> = Vec::new();

    while let Some(m) = matches.next() {
        let mut symbol_node: Option<Node> = None;
        let mut name_node: Option<Node> = None;

        for capture in m.captures {
            if capture.index == symbol_idx {
                symbol_node = Some(capture.node);
            } else if capture.index == name_idx {
                name_node = Some(capture.node);
            }
        }

        let (sym_node, name_node) = match (symbol_node, name_node) {
            (Some(s), Some(n)) => (s, n),
            _ => continue,
        };

        let name = node_text(name_node, source).to_owned();
        let pos = name_node.start_position();
        let key = (name.clone(), pos.row);

        if !seen.insert(key) {
            continue;
        }

        let kind = match sym_node.kind() {
            "function_item" => SymbolKind::Function,
            "struct_item" => SymbolKind::Struct,
            "enum_item" => SymbolKind::Enum,
            "trait_item" => SymbolKind::Trait,
            "type_item" => SymbolKind::TypeAlias,
            "const_item" => SymbolKind::Const,
            "static_item" => SymbolKind::Static,
            "macro_definition" => SymbolKind::Macro,
            _ => continue,
        };

        let visibility = extract_visibility(sym_node, source);
        let decorators = extract_rust_attributes(sym_node, source);

        let info = SymbolInfo {
            name: name.clone(),
            kind: kind.clone(),
            line: pos.row + 1,
            col: pos.column,
            line_end: sym_node.end_position().row + 1,
            visibility,
            decorators,
            ..Default::default()
        };

        // For trait items: extract child methods from the declaration_list.
        let children = if kind == SymbolKind::Trait {
            extract_trait_methods(sym_node, &name, source)
        } else {
            vec![]
        };

        results.push((info, children));
    }

    results
}

/// Extract all impl block methods from a Rust syntax tree.
///
/// impl blocks are NOT added as graph nodes (per CONTEXT.md: impl blocks are containers only).
/// Each method is returned as a standalone `(SymbolInfo, vec![])` with qualified name
/// `TypeName::method_name`.
pub fn extract_impl_methods(tree: &Tree, source: &[u8]) -> Vec<(SymbolInfo, Vec<SymbolInfo>)> {
    let mut results = Vec::new();
    let root = tree.root_node();

    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if child.kind() != "impl_item" {
            continue;
        }

        // Extract the type name from the "type" field
        let type_name = match child.child_by_field_name("type") {
            Some(type_node) => extract_simple_type_name(type_node, source).to_owned(),
            None => continue,
        };

        // Check if this is a trait impl: look for "trait" field
        let trait_name: Option<String> = child
            .child_by_field_name("trait")
            .map(|trait_node| extract_simple_type_name(trait_node, source).to_owned());

        // Find the declaration_list body
        let decl_list = {
            let mut found = None;
            let mut c = child.walk();
            for grandchild in child.children(&mut c) {
                if grandchild.kind() == "declaration_list" {
                    found = Some(grandchild);
                    break;
                }
            }
            match found {
                Some(n) => n,
                None => continue,
            }
        };

        // Walk declaration_list for function_item nodes
        let mut decl_cursor = decl_list.walk();
        for method_node in decl_list.children(&mut decl_cursor) {
            if method_node.kind() != "function_item" {
                continue;
            }

            let method_name = match method_node.child_by_field_name("name") {
                Some(n) => node_text(n, source).to_owned(),
                None => continue,
            };

            let name_node = method_node.child_by_field_name("name").unwrap();
            let pos = name_node.start_position();
            let qualified_name = format!("{}::{}", type_name, method_name);
            let visibility = extract_visibility(method_node, source);
            let decorators = extract_rust_attributes(method_node, source);

            results.push((
                SymbolInfo {
                    name: qualified_name,
                    kind: SymbolKind::ImplMethod,
                    line: pos.row + 1,
                    col: pos.column,
                    line_end: method_node.end_position().row + 1,
                    visibility,
                    trait_impl: trait_name.clone(),
                    decorators,
                    ..Default::default()
                },
                vec![],
            ));
        }
    }

    results
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::languages::language_for_extension;

    fn parse_ts(source: &str) -> (tree_sitter::Tree, Language) {
        let lang = language_for_extension("ts").unwrap();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(source.as_bytes(), None).unwrap();
        (tree, lang)
    }

    fn parse_tsx(source: &str) -> (tree_sitter::Tree, Language) {
        let lang = language_for_extension("tsx").unwrap();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(source.as_bytes(), None).unwrap();
        (tree, lang)
    }

    fn first_symbol(results: &[(SymbolInfo, Vec<SymbolInfo>)]) -> &SymbolInfo {
        &results
            .first()
            .unwrap_or_else(|| panic!("expected at least one symbol, got none"))
            .0
    }

    // Test 1: Function declaration
    #[test]
    fn test_export_function_declaration() {
        let src = "export function hello() {}";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "hello");
        assert_eq!(sym.kind, SymbolKind::Function);
        assert!(sym.is_exported, "should be exported");
    }

    // Test 2: Exported const arrow function
    #[test]
    fn test_export_const_arrow_function() {
        let src = "export const greet = () => {};";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "greet");
        assert_eq!(sym.kind, SymbolKind::Function);
        assert!(sym.is_exported, "should be exported");
    }

    // Test 3: Class declaration (non-exported)
    #[test]
    fn test_class_declaration() {
        let src = "class MyClass {}";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "MyClass");
        assert_eq!(sym.kind, SymbolKind::Class);
        assert!(!sym.is_exported);
    }

    // Test 4: Interface with child symbols
    #[test]
    fn test_interface_with_children() {
        let src = "interface IUser { name: string; getId(): number; }";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let (sym, children) = results.first().expect("expected interface symbol");
        assert_eq!(sym.name, "IUser");
        assert_eq!(sym.kind, SymbolKind::Interface);
        assert_eq!(children.len(), 2, "expected 2 child symbols (name, getId)");
        let child_names: Vec<_> = children.iter().map(|c| c.name.as_str()).collect();
        assert!(child_names.contains(&"name"), "missing 'name' child");
        assert!(child_names.contains(&"getId"), "missing 'getId' child");
        assert!(
            children.iter().all(|c| c.kind == SymbolKind::Property),
            "all children should be Property kind"
        );
    }

    // Test 5: Type alias
    #[test]
    fn test_type_alias() {
        let src = "type ID = string;";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "ID");
        assert_eq!(sym.kind, SymbolKind::TypeAlias);
    }

    // Test 6: Enum declaration
    #[test]
    fn test_enum_declaration() {
        let src = "enum Color { Red, Blue }";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "Color");
        assert_eq!(sym.kind, SymbolKind::Enum);
    }

    // Test 7: React component in TSX
    #[test]
    fn test_tsx_component_detection() {
        let src = "export const App = () => <div/>;";
        let (tree, lang) = parse_tsx(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, true);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "App");
        assert_eq!(sym.kind, SymbolKind::Component);
        assert!(sym.is_exported);
    }

    // Bonus: Non-JSX arrow function in TSX should stay as Function
    #[test]
    fn test_tsx_non_component_arrow_fn() {
        let src = "export const add = (a: number, b: number) => a + b;";
        let (tree, lang) = parse_tsx(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, true);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "add");
        assert_eq!(sym.kind, SymbolKind::Function);
    }

    // Bonus: class with methods
    #[test]
    fn test_class_with_methods() {
        let src = "class Dog { bark() {} sit() {} }";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let (sym, children) = results.first().expect("expected class");
        assert_eq!(sym.kind, SymbolKind::Class);
        assert_eq!(children.len(), 2, "expected 2 methods");
        assert!(children.iter().all(|c| c.kind == SymbolKind::Method));
    }

    fn parse_rs(source: &str) -> (tree_sitter::Tree, Language) {
        let lang = language_for_extension("rs").unwrap();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&lang).unwrap();
        let tree = parser.parse(source.as_bytes(), None).unwrap();
        (tree, lang)
    }

    // Test: TS decorator extraction
    #[test]
    fn test_ts_decorator_extraction() {
        // @Controller applied to a class
        let src = "@Controller\nclass AppController {}";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "AppController");
        assert_eq!(
            sym.decorators.len(),
            1,
            "expected 1 decorator, got {:?}",
            sym.decorators
        );
        let dec = &sym.decorators[0];
        assert_eq!(dec.name, "Controller");
        assert!(dec.object.is_none());
        assert!(dec.attribute.is_none());
        assert!(dec.args_raw.is_none());
    }

    // Test: TS attribute-style decorator with arguments (@Injectable())
    #[test]
    fn test_ts_attribute_decorator() {
        // Decorator with call arguments on a class
        let src = "@Injectable()\nclass MyService {}";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "MyService");
        assert_eq!(
            sym.decorators.len(),
            1,
            "expected 1 decorator, got {:?}",
            sym.decorators
        );
        let dec = &sym.decorators[0];
        assert_eq!(dec.name, "Injectable");
        // args_raw should contain the argument string "()"
        assert!(
            dec.args_raw.is_some(),
            "expected args_raw to be Some for call decorator"
        );
    }

    // Test: Rust #[derive(Clone, Debug)] attribute extraction
    #[test]
    fn test_rust_derive_decorator() {
        let src = "#[derive(Clone, Debug)]\npub struct MyStruct {}";
        let (tree, lang) = parse_rs(src);
        let results = extract_rust_symbols(&tree, src.as_bytes(), &lang);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "MyStruct");
        assert_eq!(
            sym.decorators.len(),
            1,
            "expected 1 attribute, got {:?}",
            sym.decorators
        );
        let attr = &sym.decorators[0];
        assert_eq!(attr.name, "derive");
        assert!(
            attr.args_raw.is_some(),
            "expected args_raw for derive attribute"
        );
        let args = attr.args_raw.as_deref().unwrap();
        assert!(
            args.contains("Clone"),
            "args_raw should contain 'Clone', got '{}'",
            args
        );
        assert!(
            args.contains("Debug"),
            "args_raw should contain 'Debug', got '{}'",
            args
        );
    }

    // Test: Rust #[get("/path")] attribute extraction
    #[test]
    fn test_rust_route_decorator() {
        let src = "#[get(\"/path\")]\npub fn get_path() {}";
        let (tree, lang) = parse_rs(src);
        let results = extract_rust_symbols(&tree, src.as_bytes(), &lang);
        let sym = first_symbol(&results);
        assert_eq!(
            sym.decorators.len(),
            1,
            "expected 1 attribute, got {:?}",
            sym.decorators
        );
        let attr = &sym.decorators[0];
        assert_eq!(attr.name, "get");
        assert!(
            attr.args_raw.is_some(),
            "expected args_raw for get attribute"
        );
    }

    // Test: line_end > line for multi-line TS function
    #[test]
    fn test_line_end_ts() {
        let src = "export function hello() {\n  return 42;\n}";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "hello");
        assert!(
            sym.line_end > sym.line,
            "line_end ({}) should be > line ({}) for multi-line function",
            sym.line_end,
            sym.line
        );
    }

    // Test: line_end > line for multi-line Rust function
    #[test]
    fn test_line_end_rust() {
        let src = "pub fn hello() {\n    let x = 1;\n    x\n}";
        let (tree, lang) = parse_rs(src);
        let results = extract_rust_symbols(&tree, src.as_bytes(), &lang);
        let sym = first_symbol(&results);
        assert_eq!(sym.name, "hello");
        assert!(
            sym.line_end > sym.line,
            "line_end ({}) should be > line ({}) for multi-line function",
            sym.line_end,
            sym.line
        );
    }

    // Test: stacked decorators preserved in source order
    #[test]
    fn test_stacked_decorators() {
        let src = "@Controller\n@Injectable\nclass AppService {}";
        let (tree, lang) = parse_ts(src);
        let results = extract_symbols(&tree, src.as_bytes(), &lang, false);
        let sym = first_symbol(&results);
        assert_eq!(
            sym.decorators.len(),
            2,
            "expected 2 decorators, got {:?}",
            sym.decorators
        );
        // Source order: @Controller first, @Injectable second
        assert_eq!(sym.decorators[0].name, "Controller");
        assert_eq!(sym.decorators[1].name, "Injectable");
    }
}