tldr-core 0.1.4

Core analysis engine for TLDR code analysis tool
Documentation
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
//! Lua language handler for call graph analysis.
//!
//! This module provides Lua-specific call graph support using tree-sitter-lua.
//!
//! # Import Patterns Supported
//!
//! | Pattern | ImportDef |
//! |---------|-----------|
//! | `require('module')` | `{module: "module", is_from: false}` |
//! | `require 'module'` | `{module: "module", is_from: false}` |
//! | `dofile('path.lua')` | `{module: "path.lua", is_from: false}` |
//! | `loadfile('path.lua')` | `{module: "path.lua", is_from: false}` |
//! | `local M = require('mod')` | `{module: "mod", alias: "M"}` |
//!
//! # Call Extraction
//!
//! - Direct calls: `func()` -> CallType::Direct or CallType::Intra
//! - Attribute calls: `module.func()` -> CallType::Attr (dot syntax)
//! - Method calls: `obj:method()` -> CallType::Method (colon syntax, self passed implicitly)
//!
//! # Lua-Specific Notes
//!
//! - Lua uses `require` for module imports (similar to Ruby)
//! - `dofile` and `loadfile` execute/load files by path
//! - Dot notation (`M.func`) is for table/module access
//! - Colon notation (`obj:method`) passes self implicitly as first argument
//!
//! # Spec Reference
//!
//! See `migration/spec/callgraph-spec.md` Section 9.x for Lua-specific details.

use std::collections::{HashMap, HashSet};
use std::path::Path;

use tree_sitter::{Node, Parser, Tree};

use super::base::{get_node_text, walk_tree};
use super::{CallGraphLanguageSupport, ParseError};
use crate::callgraph::cross_file_types::{CallSite, CallType, ClassDef, FuncDef, ImportDef};

// =============================================================================
// Lua Handler
// =============================================================================

/// Lua language handler using tree-sitter-lua.
///
/// Supports:
/// - Import parsing (require, dofile, loadfile)
/// - Call extraction (direct, attribute via dot, method via colon)
/// - Function definition tracking
/// - `<module>` synthetic function for module-level calls
#[derive(Debug, Default)]
pub struct LuaHandler;

impl LuaHandler {
    /// Creates a new LuaHandler.
    pub fn new() -> Self {
        Self
    }

    /// Parse the source code into a tree-sitter Tree.
    fn parse_source(&self, source: &str) -> Result<Tree, ParseError> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_lua::LANGUAGE.into())
            .map_err(|e| ParseError::ParseFailed {
                file: std::path::PathBuf::new(),
                message: format!("Failed to set Lua language: {}", e),
            })?;

        parser
            .parse(source, None)
            .ok_or_else(|| ParseError::ParseFailed {
                file: std::path::PathBuf::new(),
                message: "Parser returned None".to_string(),
            })
    }

    /// Extract string content from a Lua string node.
    ///
    /// Handles:
    /// - Double quoted: `"string"`
    /// - Single quoted: `'string'`
    /// - Long brackets: `[[string]]`
    fn extract_lua_string(&self, node: &Node, source: &[u8]) -> Option<String> {
        let text = get_node_text(node, source);

        // Strip quotes based on format
        if (text.starts_with('"') && text.ends_with('"') && text.len() >= 2)
            || (text.starts_with('\'') && text.ends_with('\'') && text.len() >= 2)
        {
            Some(text[1..text.len() - 1].to_string())
        } else if text.starts_with("[[") && text.ends_with("]]") && text.len() >= 4 {
            Some(text[2..text.len() - 2].to_string())
        } else {
            // Return as-is if no recognized quote format
            Some(text.to_string())
        }
    }

    /// Parse a require/dofile/loadfile call node.
    ///
    /// Returns (import_type, module_path) if this is an import call.
    fn parse_require_node(&self, node: &Node, source: &[u8]) -> Option<(String, String)> {
        // Lua import calls are function_call nodes
        // Structure varies by call style:
        // - require("module") -> function_call with identifier + arguments
        // - require "module"  -> function_call with identifier + string (no parens)

        let mut func_name: Option<String> = None;
        let mut module_path: Option<String> = None;

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "identifier" => {
                        func_name = Some(get_node_text(&child, source).to_string());
                    }
                    "arguments" => {
                        // Find the first string argument
                        for j in 0..child.child_count() {
                            if let Some(arg) = child.child(j) {
                                if arg.kind() == "string" {
                                    module_path = self.extract_lua_string(&arg, source);
                                    break;
                                }
                            }
                        }
                    }
                    "string" => {
                        // Direct string argument (require "module" syntax)
                        module_path = self.extract_lua_string(&child, source);
                    }
                    _ => {}
                }
            }
        }

        let func = func_name?;
        let module = module_path?;

        // Only handle require, dofile, loadfile
        match func.as_str() {
            "require" | "dofile" | "loadfile" => Some((func, module)),
            _ => None,
        }
    }

    /// Collect all function definitions in the file.
    ///
    /// Tracks:
    /// - `function foo()` declarations
    /// - `function M.foo()` module function declarations
    /// - `function M:foo()` method declarations
    /// - `local foo = function()` variable declarations with function values
    fn collect_definitions(&self, tree: &Tree, source: &[u8]) -> HashSet<String> {
        let mut funcs = HashSet::new();

        for node in walk_tree(tree.root_node()) {
            match node.kind() {
                "function_declaration" => {
                    // Get function name from different patterns
                    for i in 0..node.child_count() {
                        if let Some(child) = node.child(i) {
                            match child.kind() {
                                "identifier" => {
                                    // Simple: function foo()
                                    funcs.insert(get_node_text(&child, source).to_string());
                                    break;
                                }
                                "dot_index_expression" => {
                                    // Module function: function M.foo()
                                    // Extract the last identifier (function name)
                                    if let Some(name) = self.extract_last_identifier(&child, source)
                                    {
                                        funcs.insert(name);
                                    }
                                    break;
                                }
                                "method_index_expression" => {
                                    // Method: function M:foo()
                                    // Extract the last identifier (method name)
                                    if let Some(name) = self.extract_last_identifier(&child, source)
                                    {
                                        funcs.insert(name);
                                    }
                                    break;
                                }
                                _ => {}
                            }
                        }
                    }
                }
                "variable_declaration" => {
                    // Handle: local foo = function() ... end
                    self.collect_function_from_variable_decl(&node, source, &mut funcs);
                }
                "assignment_statement" => {
                    // Handle: handler = function() ... end
                    //         MyModule.func = function() ... end
                    if let Some((name, _qualified, _body)) =
                        self.get_func_from_assignment(&node, source)
                    {
                        funcs.insert(name);
                    }
                }
                _ => {}
            }
        }

        funcs
    }

    /// Extract the last identifier from a dot or method index expression.
    fn extract_last_identifier(&self, node: &Node, source: &[u8]) -> Option<String> {
        let mut last_ident: Option<String> = None;

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "identifier" {
                    last_ident = Some(get_node_text(&child, source).to_string());
                }
            }
        }

        last_ident
    }

    /// Collect function name from variable declaration with function value.
    fn collect_function_from_variable_decl(
        &self,
        node: &Node,
        source: &[u8],
        funcs: &mut HashSet<String>,
    ) {
        // Structure: variable_declaration -> assignment_statement -> variable_list + expression_list
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "assignment_statement" {
                    let mut var_name: Option<String> = None;
                    let mut has_function = false;

                    for j in 0..child.child_count() {
                        if let Some(subchild) = child.child(j) {
                            match subchild.kind() {
                                "variable_list" => {
                                    // Get first identifier
                                    for k in 0..subchild.child_count() {
                                        if let Some(var) = subchild.child(k) {
                                            if var.kind() == "identifier" {
                                                var_name =
                                                    Some(get_node_text(&var, source).to_string());
                                                break;
                                            }
                                        }
                                    }
                                }
                                "expression_list" => {
                                    // Check if any expression is a function_definition
                                    for k in 0..subchild.child_count() {
                                        if let Some(expr) = subchild.child(k) {
                                            if expr.kind() == "function_definition" {
                                                has_function = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }

                    if let (Some(name), true) = (var_name, has_function) {
                        funcs.insert(name);
                    }
                }
            }
        }
    }

    /// Extract calls from a node, recursively.
    ///
    /// Also detects function references: identifiers that match defined functions
    /// and are used as arguments (callbacks), e.g. `table.sort(list, compare)`.
    fn extract_calls_from_node(
        &self,
        node: &Node,
        source: &[u8],
        defined_funcs: &HashSet<String>,
        caller: &str,
    ) -> Vec<CallSite> {
        let mut calls = Vec::new();
        let mut refs = HashSet::new();

        for child in walk_tree(*node) {
            match child.kind() {
                "function_call" => {
                    if let Some(call_site) =
                        self.parse_function_call(&child, source, defined_funcs, caller)
                    {
                        calls.push(call_site);
                    }
                }
                "identifier" => {
                    // Check for function references (identifiers passed as arguments)
                    let name = get_node_text(&child, source);
                    if defined_funcs.contains(name) {
                        // Only count as Ref if the identifier is inside an arguments node
                        // and is NOT the function being called
                        if let Some(parent) = child.parent() {
                            if parent.kind() == "arguments" {
                                refs.insert(name.to_string());
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        // Add function references as Ref call sites
        for ref_name in refs {
            let line = node.start_position().row as u32 + 1;
            calls.push(CallSite::new(
                caller.to_string(),
                ref_name,
                CallType::Ref,
                Some(line),
                None,
                None,
                None,
            ));
        }

        calls
    }

    /// Parse a function_call node and create a CallSite.
    fn parse_function_call(
        &self,
        node: &Node,
        source: &[u8],
        defined_funcs: &HashSet<String>,
        caller: &str,
    ) -> Option<CallSite> {
        let line = node.start_position().row as u32 + 1;

        // Check each child to determine call type
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "identifier" => {
                        // Simple call: foo()
                        let target = get_node_text(&child, source).to_string();

                        // Skip import-related calls
                        if target == "require" || target == "dofile" || target == "loadfile" {
                            return None;
                        }

                        let call_type = if defined_funcs.contains(&target) {
                            CallType::Intra
                        } else {
                            CallType::Direct
                        };

                        return Some(CallSite::new(
                            caller.to_string(),
                            target,
                            call_type,
                            Some(line),
                            None,
                            None,
                            None,
                        ));
                    }
                    "dot_index_expression" => {
                        // Attribute call: module.func() or obj.method()
                        return self.parse_dot_call(&child, source, caller, line);
                    }
                    "method_index_expression" => {
                        // Method call: obj:method()
                        return self.parse_colon_call(&child, source, caller, line);
                    }
                    _ => {}
                }
            }
        }

        None
    }

    /// Parse a dot-syntax call (module.func or obj.method).
    ///
    /// Handles both simple calls (`module.func()`) and chained calls
    /// (`a.b().c()`) where the receiver is a function_call node.
    fn parse_dot_call(
        &self,
        node: &Node,
        source: &[u8],
        caller: &str,
        line: u32,
    ) -> Option<CallSite> {
        let mut identifiers = Vec::new();
        let mut has_non_ident_receiver = false;
        let mut non_ident_receiver_text: Option<String> = None;

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "identifier" => {
                        identifiers.push(get_node_text(&child, source).to_string());
                    }
                    "function_call" | "method_index_expression" | "dot_index_expression" => {
                        // Chained call: receiver is a call expression
                        has_non_ident_receiver = true;
                        non_ident_receiver_text = Some(get_node_text(&child, source).to_string());
                    }
                    _ => {}
                }
            }
        }

        if identifiers.len() >= 2 {
            let receiver = identifiers[0].clone();
            let method = identifiers.last().unwrap().clone();
            let target = format!("{}.{}", receiver, method);

            Some(CallSite::new(
                caller.to_string(),
                target,
                CallType::Attr,
                Some(line),
                None,
                Some(receiver),
                None,
            ))
        } else if has_non_ident_receiver && identifiers.len() == 1 {
            // Chained call: something().method
            let method = identifiers[0].clone();
            let receiver_text = non_ident_receiver_text.unwrap_or_default();
            let target = format!("{}.{}", receiver_text, method);

            Some(CallSite::new(
                caller.to_string(),
                target,
                CallType::Attr,
                Some(line),
                None,
                Some(receiver_text),
                None,
            ))
        } else if identifiers.len() == 1 {
            // Single identifier - treat as the full expression
            let target = get_node_text(node, source).to_string();
            let receiver = identifiers[0].clone();

            Some(CallSite::new(
                caller.to_string(),
                target,
                CallType::Attr,
                Some(line),
                None,
                Some(receiver),
                None,
            ))
        } else {
            None
        }
    }

    /// Parse a colon-syntax call (obj:method).
    ///
    /// Handles both simple calls (`obj:method()`) and chained calls
    /// (`obj:method1():method2()`) where the receiver is a function_call node.
    fn parse_colon_call(
        &self,
        node: &Node,
        source: &[u8],
        caller: &str,
        line: u32,
    ) -> Option<CallSite> {
        let mut identifiers = Vec::new();
        let mut has_non_ident_receiver = false;
        let mut non_ident_receiver_text: Option<String> = None;

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "identifier" => {
                        identifiers.push(get_node_text(&child, source).to_string());
                    }
                    "function_call" | "method_index_expression" | "dot_index_expression" => {
                        // Chained call: receiver is a call expression, not a simple identifier
                        has_non_ident_receiver = true;
                        non_ident_receiver_text = Some(get_node_text(&child, source).to_string());
                    }
                    _ => {}
                }
            }
        }

        if identifiers.len() >= 2 {
            // Simple case: obj:method
            let receiver = identifiers[0].clone();
            let method = identifiers.last().unwrap().clone();
            let target = format!("{}:{}", receiver, method);

            Some(CallSite::new(
                caller.to_string(),
                target,
                CallType::Method,
                Some(line),
                None,
                Some(receiver),
                None,
            ))
        } else if has_non_ident_receiver && identifiers.len() == 1 {
            // Chained call: something():method
            // The method name is the single identifier we found
            let method = identifiers[0].clone();
            let receiver_text = non_ident_receiver_text.unwrap_or_default();
            let target = format!("{}:{}", receiver_text, method);

            Some(CallSite::new(
                caller.to_string(),
                target,
                CallType::Method,
                Some(line),
                None,
                Some(receiver_text),
                None,
            ))
        } else {
            None
        }
    }
}

impl CallGraphLanguageSupport for LuaHandler {
    fn name(&self) -> &str {
        "lua"
    }

    fn extensions(&self) -> &[&str] {
        &[".lua"]
    }

    fn parse_imports(&self, source: &str, _path: &Path) -> Result<Vec<ImportDef>, ParseError> {
        let tree = self.parse_source(source)?;
        let source_bytes = source.as_bytes();
        let mut imports = Vec::new();

        // Track which function_call nodes are inside variable_declarations
        // so we don't process them twice
        let mut processed_calls = HashSet::new();

        // First pass: process variable_declarations with aliased requires
        for node in walk_tree(tree.root_node()) {
            if node.kind() == "variable_declaration" {
                // Check if this declares an alias for a require
                if let Some((alias, import_info, call_id)) =
                    self.extract_aliased_require(&node, source_bytes)
                {
                    let mut import_def = ImportDef::simple_import(import_info.1);
                    import_def.alias = Some(alias);
                    imports.push(import_def);
                    processed_calls.insert(call_id);
                }
            }
        }

        // Second pass: process standalone require calls (not in variable_declarations)
        for node in walk_tree(tree.root_node()) {
            if node.kind() == "function_call" {
                let call_id = node.id();
                if !processed_calls.contains(&call_id) {
                    if let Some((_, module_path)) = self.parse_require_node(&node, source_bytes) {
                        let import_def = ImportDef::simple_import(module_path);
                        imports.push(import_def);
                    }
                }
            }
        }

        Ok(imports)
    }

    fn extract_calls(
        &self,
        _path: &Path,
        source: &str,
        tree: &Tree,
    ) -> Result<HashMap<String, Vec<CallSite>>, ParseError> {
        let source_bytes = source.as_bytes();
        let defined_funcs = self.collect_definitions(tree, source_bytes);
        let mut calls_by_func: HashMap<String, Vec<CallSite>> = HashMap::new();

        // Process function declarations
        for node in walk_tree(tree.root_node()) {
            if node.kind() == "function_declaration" {
                if let Some((simple_name, qualified_name, body)) =
                    self.get_function_name_and_body(&node, source_bytes)
                {
                    let calls = self.extract_calls_from_node(
                        &body,
                        source_bytes,
                        &defined_funcs,
                        &qualified_name,
                    );
                    if !calls.is_empty() {
                        // Store with qualified name for cross-scope tracking
                        calls_by_func.insert(qualified_name.clone(), calls.clone());
                        // Also store with simple name for backward compatibility
                        if simple_name != qualified_name {
                            calls_by_func.insert(simple_name, calls);
                        }
                    }
                }
            }
        }

        // Process variable declarations with function values
        for node in walk_tree(tree.root_node()) {
            if node.kind() == "variable_declaration" {
                if let Some((simple_name, qualified_name, body)) =
                    self.get_func_from_var_decl(&node, source_bytes)
                {
                    let calls = self.extract_calls_from_node(
                        &body,
                        source_bytes,
                        &defined_funcs,
                        &qualified_name,
                    );
                    if !calls.is_empty() {
                        // Store with qualified name for cross-scope tracking
                        calls_by_func.insert(qualified_name.clone(), calls.clone());
                        // Also store with simple name for backward compatibility
                        if simple_name != qualified_name {
                            calls_by_func.insert(simple_name, calls);
                        }
                    }
                }
            }
        }

        // Process top-level assignment_statements with function values
        // e.g., MyModule.func = function() ... end
        //        handler = function() ... end
        for node in tree.root_node().children(&mut tree.root_node().walk()) {
            if node.kind() == "assignment_statement" {
                if let Some((simple_name, qualified_name, body)) =
                    self.get_func_from_assignment(&node, source_bytes)
                {
                    let calls = self.extract_calls_from_node(
                        &body,
                        source_bytes,
                        &defined_funcs,
                        &qualified_name,
                    );
                    if !calls.is_empty() {
                        // Store with qualified name for cross-scope tracking
                        calls_by_func.insert(qualified_name.clone(), calls.clone());
                        // Also store with simple name for backward compatibility
                        if simple_name != qualified_name {
                            calls_by_func.insert(simple_name, calls);
                        }
                    }
                }
            }
        }

        // Extract module-level calls into synthetic <module> function
        let mut module_calls = Vec::new();
        for node in tree.root_node().children(&mut tree.root_node().walk()) {
            // Skip function declarations and variable declarations with functions
            if node.kind() == "function_declaration" {
                continue;
            }
            if node.kind() == "variable_declaration" {
                // Check if this is a function definition
                if self.get_func_from_var_decl(&node, source_bytes).is_some() {
                    continue;
                }
            }
            // Skip assignment_statements with function values
            if node.kind() == "assignment_statement"
                && self.get_func_from_assignment(&node, source_bytes).is_some()
            {
                continue;
            }

            let calls =
                self.extract_calls_from_node(&node, source_bytes, &defined_funcs, "<module>");
            module_calls.extend(calls);
        }

        if !module_calls.is_empty() {
            calls_by_func.insert("<module>".to_string(), module_calls);
        }

        Ok(calls_by_func)
    }

    fn extract_definitions(
        &self,
        source: &str,
        _path: &Path,
        tree: &Tree,
    ) -> Result<(Vec<FuncDef>, Vec<ClassDef>), super::ParseError> {
        let source_bytes = source.as_bytes();
        let mut funcs = Vec::new();
        // Lua has no classes, only return funcs

        for node in walk_tree(tree.root_node()) {
            match node.kind() {
                "function_declaration" => {
                    let line = node.start_position().row as u32 + 1;
                    let end_line = node.end_position().row as u32 + 1;

                    for i in 0..node.child_count() {
                        if let Some(child) = node.child(i) {
                            match child.kind() {
                                "identifier" => {
                                    let name = get_node_text(&child, source_bytes).to_string();
                                    funcs.push(FuncDef::function(name, line, end_line));
                                    break;
                                }
                                "dot_index_expression" => {
                                    if let Some(name) =
                                        self.extract_last_identifier(&child, source_bytes)
                                    {
                                        funcs.push(FuncDef::function(name, line, end_line));
                                    }
                                    break;
                                }
                                "method_index_expression" => {
                                    if let Some(name) =
                                        self.extract_last_identifier(&child, source_bytes)
                                    {
                                        funcs.push(FuncDef::function(name, line, end_line));
                                    }
                                    break;
                                }
                                _ => {}
                            }
                        }
                    }
                }
                "variable_declaration" => {
                    // Handle: local foo = function() ... end
                    let mut var_names: Vec<String> = Vec::new();
                    let mut has_function = false;
                    let line = node.start_position().row as u32 + 1;
                    let end_line = node.end_position().row as u32 + 1;

                    for i in 0..node.child_count() {
                        if let Some(child) = node.child(i) {
                            if child.kind() == "assignment_statement" {
                                for j in 0..child.child_count() {
                                    if let Some(subchild) = child.child(j) {
                                        if subchild.kind() == "variable_list" {
                                            for k in 0..subchild.child_count() {
                                                if let Some(var) = subchild.child(k) {
                                                    if var.kind() == "identifier" {
                                                        var_names.push(
                                                            get_node_text(&var, source_bytes)
                                                                .to_string(),
                                                        );
                                                    }
                                                }
                                            }
                                        }
                                        if subchild.kind() == "expression_list" {
                                            for k in 0..subchild.child_count() {
                                                if let Some(expr) = subchild.child(k) {
                                                    if expr.kind() == "function_definition" {
                                                        has_function = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if has_function {
                        for name in var_names {
                            funcs.push(FuncDef::function(name, line, end_line));
                        }
                    }
                }
                "assignment_statement" => {
                    // Handle: handler = function() ... end
                    //         MyModule.func = function() ... end
                    if let Some((name, _qualified, _body)) =
                        self.get_func_from_assignment(&node, source_bytes)
                    {
                        let line = node.start_position().row as u32 + 1;
                        let end_line = node.end_position().row as u32 + 1;
                        funcs.push(FuncDef::function(name, line, end_line));
                    }
                }
                _ => {}
            }
        }

        Ok((funcs, Vec::new()))
    }
}

impl LuaHandler {
    /// Extract an aliased require from a variable declaration.
    ///
    /// Returns (alias, (import_type, module_path), call_node_id) if found.
    fn extract_aliased_require(
        &self,
        node: &Node,
        source: &[u8],
    ) -> Option<(String, (String, String), usize)> {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "assignment_statement" {
                    let mut var_name: Option<String> = None;
                    let mut require_info: Option<((String, String), usize)> = None;

                    for j in 0..child.child_count() {
                        if let Some(subchild) = child.child(j) {
                            match subchild.kind() {
                                "variable_list" => {
                                    // Get first identifier as variable name
                                    for k in 0..subchild.child_count() {
                                        if let Some(var) = subchild.child(k) {
                                            if var.kind() == "identifier" {
                                                var_name =
                                                    Some(get_node_text(&var, source).to_string());
                                                break;
                                            }
                                        }
                                    }
                                }
                                "expression_list" => {
                                    // Look for require call in expression directly
                                    for inner in walk_tree(subchild) {
                                        if inner.kind() == "function_call" {
                                            if let Some((import_type, module_path)) =
                                                self.parse_require_node(&inner, source)
                                            {
                                                require_info =
                                                    Some(((import_type, module_path), inner.id()));
                                                break;
                                            }
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }

                    // If we found both a variable name and a require, return them
                    if let (Some(alias), Some((import_info, call_id))) = (var_name, require_info) {
                        return Some((alias, import_info, call_id));
                    }
                }
            }
        }
        None
    }

    /// Get function name and body from a function declaration.
    /// Returns (simple_name, qualified_name, body) where qualified_name includes table prefix.
    fn get_function_name_and_body<'a>(
        &self,
        node: &'a Node,
        source: &[u8],
    ) -> Option<(String, String, Node<'a>)> {
        let mut simple_name: Option<String> = None;
        let mut qualified_name: Option<String> = None;
        let mut body: Option<Node<'a>> = None;

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "identifier" => {
                        let name = get_node_text(&child, source).to_string();
                        simple_name = Some(name.clone());
                        qualified_name = Some(name);
                    }
                    "dot_index_expression" => {
                        // Table function: M.func or MyModule.sub.func
                        // Extract both simple name and qualified name
                        if let Some(name) = self.extract_last_identifier(&child, source) {
                            simple_name = Some(name);
                        }
                        // Get full qualified name like "M.func"
                        let full_text = get_node_text(&child, source).to_string();
                        qualified_name = Some(full_text);
                    }
                    "method_index_expression" => {
                        // Method: M:method
                        if let Some(name) = self.extract_last_identifier(&child, source) {
                            simple_name = Some(name);
                        }
                        // Get full qualified name like "M:method"
                        let full_text = get_node_text(&child, source).to_string();
                        qualified_name = Some(full_text);
                    }
                    "block" => {
                        body = Some(child);
                    }
                    _ => {}
                }
            }
        }

        if let (Some(simple), Some(qualified), Some(b)) = (simple_name, qualified_name, body) {
            Some((simple, qualified, b))
        } else {
            None
        }
    }

    /// Check if a function name represents a table method (contains . or :).
    /// Returns the table name if it's a table method, None otherwise.
    fn _get_table_prefix(&self, func_name: &str) -> Option<String> {
        if func_name.contains('.') {
            func_name.split('.').next().map(|s| s.to_string())
        } else if func_name.contains(':') {
            func_name.split(':').next().map(|s| s.to_string())
        } else {
            None
        }
    }

    /// Get function name and body from a variable declaration with function value.
    /// Returns (simple_name, qualified_name, body) where qualified_name includes table prefix.
    fn get_func_from_var_decl<'a>(
        &self,
        node: &'a Node,
        source: &[u8],
    ) -> Option<(String, String, Node<'a>)> {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "assignment_statement" {
                    let mut simple_name: Option<String> = None;
                    let mut qualified_name: Option<String> = None;
                    let mut func_body: Option<Node<'a>> = None;

                    for j in 0..child.child_count() {
                        if let Some(subchild) = child.child(j) {
                            match subchild.kind() {
                                "variable_list" => {
                                    for k in 0..subchild.child_count() {
                                        if let Some(var) = subchild.child(k) {
                                            match var.kind() {
                                                "identifier" => {
                                                    let name =
                                                        get_node_text(&var, source).to_string();
                                                    simple_name = Some(name.clone());
                                                    qualified_name = Some(name);
                                                    break;
                                                }
                                                "dot_index_expression" => {
                                                    // M.func = function() ... end
                                                    if let Some(name) =
                                                        self.extract_last_identifier(&var, source)
                                                    {
                                                        simple_name = Some(name);
                                                    }
                                                    qualified_name = Some(
                                                        get_node_text(&var, source).to_string(),
                                                    );
                                                    break;
                                                }
                                                "method_index_expression" => {
                                                    // M:method = function() ... end
                                                    if let Some(name) =
                                                        self.extract_last_identifier(&var, source)
                                                    {
                                                        simple_name = Some(name);
                                                    }
                                                    qualified_name = Some(
                                                        get_node_text(&var, source).to_string(),
                                                    );
                                                    break;
                                                }
                                                _ => {}
                                            }
                                        }
                                    }
                                }
                                "expression_list" => {
                                    for k in 0..subchild.child_count() {
                                        if let Some(expr) = subchild.child(k) {
                                            if expr.kind() == "function_definition" {
                                                // Get the body (block) from function_definition
                                                for l in 0..expr.child_count() {
                                                    if let Some(part) = expr.child(l) {
                                                        if part.kind() == "block" {
                                                            func_body = Some(part);
                                                            break;
                                                        }
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }

                    if let (Some(simple), Some(qualified), Some(body)) =
                        (simple_name, qualified_name, func_body)
                    {
                        return Some((simple, qualified, body));
                    }
                }
            }
        }
        None
    }

    /// Get function name and body from a top-level assignment_statement with function value.
    ///
    /// Handles patterns like:
    /// - `handler = function() ... end`
    /// - `MyModule.func = function() ... end`
    ///
    /// These are NOT wrapped in `variable_declaration` (no `local` keyword).
    /// Returns (simple_name, qualified_name, body) where qualified_name includes table prefix.
    fn get_func_from_assignment<'a>(
        &self,
        node: &'a Node,
        source: &[u8],
    ) -> Option<(String, String, Node<'a>)> {
        if node.kind() != "assignment_statement" {
            return None;
        }

        let mut simple_name: Option<String> = None;
        let mut qualified_name: Option<String> = None;
        let mut func_body: Option<Node<'a>> = None;

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "variable_list" => {
                        // Try to extract name from first variable
                        for k in 0..child.child_count() {
                            if let Some(var) = child.child(k) {
                                match var.kind() {
                                    "identifier" => {
                                        // Simple: handler = function() end
                                        let name = get_node_text(&var, source).to_string();
                                        simple_name = Some(name.clone());
                                        qualified_name = Some(name);
                                        break;
                                    }
                                    "dot_index_expression" => {
                                        // Dotted: MyModule.func = function() end
                                        // Use the last identifier as the simple function name
                                        if let Some(name) =
                                            self.extract_last_identifier(&var, source)
                                        {
                                            simple_name = Some(name);
                                        }
                                        // Get full qualified name
                                        qualified_name =
                                            Some(get_node_text(&var, source).to_string());
                                        break;
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                    "expression_list" => {
                        for k in 0..child.child_count() {
                            if let Some(expr) = child.child(k) {
                                if expr.kind() == "function_definition" {
                                    // Get the body (block) from function_definition
                                    for l in 0..expr.child_count() {
                                        if let Some(part) = expr.child(l) {
                                            if part.kind() == "block" {
                                                func_body = Some(part);
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
        }

        if let (Some(simple), Some(qualified), Some(body)) =
            (simple_name, qualified_name, func_body)
        {
            Some((simple, qualified, body))
        } else {
            None
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_imports(source: &str) -> Vec<ImportDef> {
        let handler = LuaHandler::new();
        handler
            .parse_imports(source, Path::new("test.lua"))
            .unwrap()
    }

    fn extract_calls(source: &str) -> HashMap<String, Vec<CallSite>> {
        let handler = LuaHandler::new();
        let tree = handler.parse_source(source).unwrap();
        handler
            .extract_calls(Path::new("test.lua"), source, &tree)
            .unwrap()
    }

    // -------------------------------------------------------------------------
    // Import Parsing Tests
    // -------------------------------------------------------------------------

    mod import_tests {
        use super::*;

        #[test]
        fn test_parse_require() {
            let imports = parse_imports("require('json')");
            assert_eq!(imports.len(), 1);
            assert_eq!(imports[0].module, "json");
            assert!(!imports[0].is_from);
        }

        #[test]
        fn test_parse_require_double_quotes() {
            let imports = parse_imports("require(\"json\")");
            assert_eq!(imports.len(), 1);
            assert_eq!(imports[0].module, "json");
        }

        #[test]
        fn test_parse_require_no_parens() {
            let imports = parse_imports("require 'json'");
            assert_eq!(imports.len(), 1);
            assert_eq!(imports[0].module, "json");
        }

        #[test]
        fn test_parse_require_with_alias() {
            let imports = parse_imports("local M = require('module')");
            assert_eq!(imports.len(), 1);
            assert_eq!(imports[0].module, "module");
            assert_eq!(imports[0].alias, Some("M".to_string()));
        }

        #[test]
        fn test_parse_dofile() {
            let imports = parse_imports("dofile('config.lua')");
            assert_eq!(imports.len(), 1);
            assert_eq!(imports[0].module, "config.lua");
        }

        #[test]
        fn test_parse_loadfile() {
            let imports = parse_imports("loadfile('utils.lua')");
            assert_eq!(imports.len(), 1);
            assert_eq!(imports[0].module, "utils.lua");
        }

        #[test]
        fn test_parse_require_dot_path() {
            let imports = parse_imports("require('lib.json')");
            assert_eq!(imports.len(), 1);
            assert_eq!(imports[0].module, "lib.json");
        }

        #[test]
        fn test_parse_multiple_imports() {
            let source = r#"
require('json')
local utils = require('utils')
dofile('config.lua')
"#;
            let imports = parse_imports(source);
            assert_eq!(imports.len(), 3);
        }
    }

    // -------------------------------------------------------------------------
    // Call Extraction Tests
    // -------------------------------------------------------------------------

    mod call_tests {
        use super::*;

        #[test]
        fn test_extract_calls_direct() {
            let source = r#"
function main()
    print("hello")
    helper()
end
"#;
            let calls = extract_calls(source);
            let main_calls = calls.get("main").unwrap();
            assert!(main_calls.iter().any(|c| c.target == "print"));
            assert!(main_calls.iter().any(|c| c.target == "helper"));
        }

        #[test]
        fn test_extract_calls_intra_file() {
            let source = r#"
function helper()
    return "help"
end

function main()
    helper()
end
"#;
            let calls = extract_calls(source);
            let main_calls = calls.get("main").unwrap();
            let helper_call = main_calls.iter().find(|c| c.target == "helper").unwrap();
            assert_eq!(helper_call.call_type, CallType::Intra);
        }

        #[test]
        fn test_extract_calls_attr() {
            let source = r#"
function process()
    json.encode(data)
    os.exit(0)
end
"#;
            let calls = extract_calls(source);
            let process_calls = calls.get("process").unwrap();

            let json_call = process_calls
                .iter()
                .find(|c| c.target.contains("encode"))
                .unwrap();
            assert_eq!(json_call.call_type, CallType::Attr);
            assert_eq!(json_call.receiver, Some("json".to_string()));
        }

        #[test]
        fn test_extract_calls_method() {
            let source = r#"
function process()
    obj:start()
    service:stop()
end
"#;
            let calls = extract_calls(source);
            let process_calls = calls.get("process").unwrap();

            let start_call = process_calls
                .iter()
                .find(|c| c.target.contains("start"))
                .unwrap();
            assert_eq!(start_call.call_type, CallType::Method);
            assert_eq!(start_call.receiver, Some("obj".to_string()));
            assert!(start_call.target.contains(":"));
        }

        #[test]
        fn test_extract_calls_module_function() {
            let source = r#"
function M.helper()
    print("in module helper")
end

function main()
    M.helper()
end
"#;
            let calls = extract_calls(source);
            // The function M.helper should be tracked by its simple name "helper"
            assert!(calls.contains_key("main"));
        }

        #[test]
        fn test_extract_calls_method_function() {
            let source = r#"
function Obj:init()
    self.value = 0
end

function Obj:increment()
    self.value = self.value + 1
end
"#;
            let calls = extract_calls(source);
            // Method functions should be tracked by their simple name
            // This test ensures we can parse method declarations
            // (even if they don't contain calls)
            assert!(calls.is_empty() || !calls.is_empty()); // Valid either way
        }

        #[test]
        fn test_extract_calls_local_function() {
            let source = r#"
local function helper()
    return "help"
end

local processor = function()
    helper()
    print("done")
end
"#;
            let calls = extract_calls(source);
            let processor_calls = calls.get("processor").unwrap();
            assert!(processor_calls.iter().any(|c| c.target == "helper"));
            assert!(processor_calls.iter().any(|c| c.target == "print"));
        }

        #[test]
        fn test_extract_calls_module_level() {
            let source = r#"
function helper()
    return "help"
end

-- Module-level call
result = helper()
print("Starting")
"#;
            let calls = extract_calls(source);
            assert!(calls.contains_key("<module>"));
            let module_calls = calls.get("<module>").unwrap();
            assert!(module_calls.iter().any(|c| c.target == "helper"));
            assert!(module_calls.iter().any(|c| c.target == "print"));
        }
    }

    // -------------------------------------------------------------------------
    // Handler Trait Tests
    // -------------------------------------------------------------------------

    mod trait_tests {
        use super::*;

        #[test]
        fn test_handler_name() {
            let handler = LuaHandler::new();
            assert_eq!(handler.name(), "lua");
        }

        #[test]
        fn test_handler_extensions() {
            let handler = LuaHandler::new();
            let exts = handler.extensions();
            assert!(exts.contains(&".lua"));
        }

        #[test]
        fn test_handler_supports() {
            let handler = LuaHandler::new();
            assert!(handler.supports("lua"));
            assert!(handler.supports("Lua"));
            assert!(handler.supports("LUA"));
            assert!(!handler.supports("python"));
        }

        #[test]
        fn test_handler_supports_extension() {
            let handler = LuaHandler::new();
            assert!(handler.supports_extension(".lua"));
            assert!(handler.supports_extension(".LUA"));
            assert!(!handler.supports_extension(".py"));
        }
    }

    // -------------------------------------------------------------------------
    // Pattern Completeness Tests (new)
    // -------------------------------------------------------------------------

    mod pattern_tests {
        use super::*;

        // ----- Table constructor calls -----
        #[test]
        fn test_table_constructor_calls() {
            let source = r#"
function build()
    local t = { field = func(), other = compute() }
end
"#;
            let calls = extract_calls(source);
            let p = calls.get("build").unwrap();
            assert!(
                p.iter().any(|c| c.target == "func"),
                "Should find func() inside table constructor"
            );
            assert!(
                p.iter().any(|c| c.target == "compute"),
                "Should find compute() inside table constructor"
            );
        }

        // ----- Self-method calls -----
        #[test]
        fn test_self_colon_call() {
            let source = r#"
function Foo:bar()
    self:method()
end
"#;
            let calls = extract_calls(source);
            let bar_calls = calls.get("bar").unwrap();
            let call = bar_calls
                .iter()
                .find(|c| c.target == "self:method")
                .unwrap();
            assert_eq!(call.call_type, CallType::Method);
            assert_eq!(call.receiver, Some("self".to_string()));
        }

        #[test]
        fn test_self_dot_call() {
            let source = r#"
function Foo:bar()
    self.other()
end
"#;
            let calls = extract_calls(source);
            let bar_calls = calls.get("bar").unwrap();
            let call = bar_calls.iter().find(|c| c.target == "self.other").unwrap();
            assert_eq!(call.call_type, CallType::Attr);
            assert_eq!(call.receiver, Some("self".to_string()));
        }

        // ----- Chained calls -----
        #[test]
        fn test_chained_method_calls() {
            let source = r#"
function process()
    obj:method1():method2()
end
"#;
            let calls = extract_calls(source);
            let p = calls.get("process").unwrap();
            // Both method1 and method2 should be found
            assert!(
                p.iter().any(|c| c.target == "obj:method1"),
                "Should find inner call obj:method1()"
            );
            assert!(
                p.iter().any(|c| c.target.contains("method2")),
                "Should find outer chained call method2()"
            );
        }

        #[test]
        fn test_chained_dot_calls() {
            let source = r#"
function process()
    a.b().c()
end
"#;
            let calls = extract_calls(source);
            let p = calls.get("process").unwrap();
            // Should find both a.b() and the chained .c() call
            assert!(
                p.iter().any(|c| c.target == "a.b"),
                "Should find inner call a.b()"
            );
            assert!(
                p.iter().any(|c| c.target.contains("c")),
                "Should find outer chained call c()"
            );
        }

        // ----- Nested function calls -----
        #[test]
        fn test_nested_calls() {
            let source = r#"
function process()
    foo(bar(baz()))
end
"#;
            let calls = extract_calls(source);
            let p = calls.get("process").unwrap();
            assert_eq!(p.len(), 3, "Should find all three nested calls");
            assert!(p.iter().any(|c| c.target == "foo"));
            assert!(p.iter().any(|c| c.target == "bar"));
            assert!(p.iter().any(|c| c.target == "baz"));
        }

        // ----- Callback / function reference -----
        #[test]
        fn test_callback_ref() {
            let source = r#"
function compare(a, b)
    return a < b
end

function process()
    table.sort(list, compare)
end
"#;
            let calls = extract_calls(source);
            let p = calls.get("process").unwrap();
            assert!(
                p.iter().any(|c| c.target == "table.sort"),
                "Should find table.sort call"
            );
            assert!(
                p.iter()
                    .any(|c| c.target == "compare" && c.call_type == CallType::Ref),
                "Should find compare as Ref (callback)"
            );
        }

        // ----- Global function assignment -----
        #[test]
        fn test_global_func_assignment() {
            let source = r#"
MyModule.func = function()
    helper()
end
"#;
            let calls = extract_calls(source);
            assert!(
                calls.contains_key("func"),
                "Should attribute calls to 'func', not '<module>'"
            );
            let func_calls = calls.get("func").unwrap();
            assert!(func_calls.iter().any(|c| c.target == "helper"));
        }

        #[test]
        fn test_global_func_assignment_simple() {
            // Non-dotted global: plain assignment with function value
            let source = r#"
handler = function()
    process()
end
"#;
            let calls = extract_calls(source);
            assert!(
                calls.contains_key("handler"),
                "Should attribute calls to 'handler'"
            );
            let h_calls = calls.get("handler").unwrap();
            assert!(h_calls.iter().any(|c| c.target == "process"));
        }

        // ----- Module-level calls with non-local assignment -----
        #[test]
        fn test_module_level_non_local_assignment_call() {
            let source = r#"
function helper()
    return 42
end

result = helper()
"#;
            let calls = extract_calls(source);
            assert!(calls.contains_key("<module>"));
            let m = calls.get("<module>").unwrap();
            assert!(m.iter().any(|c| c.target == "helper"));
        }

        // ----- Or-default pattern -----
        #[test]
        fn test_or_default_call() {
            let source = r#"
function init()
    local x = x or default()
end
"#;
            let calls = extract_calls(source);
            let p = calls.get("init").unwrap();
            assert!(
                p.iter().any(|c| c.target == "default"),
                "Should find default() in or-default pattern"
            );
        }

        // ----- Method definition tracking -----
        #[test]
        fn test_method_definition_name() {
            let source = r#"
function Foo:bar()
    print("hello")
end
"#;
            let handler = LuaHandler::new();
            let tree = handler.parse_source(source).unwrap();
            let (funcs, _) = handler
                .extract_definitions(source, Path::new("test.lua"), &tree)
                .unwrap();
            // Method should be tracked (by its short name "bar")
            assert!(funcs.iter().any(|f| f.name == "bar"), "Should define 'bar'");
        }

        // ----- String method calls -----
        #[test]
        fn test_string_method_calls() {
            let source = r#"
function format_name()
    local s = string.format("hello %s", name)
    string.len(s)
end
"#;
            let calls = extract_calls(source);
            let p = calls.get("format_name").unwrap();
            assert!(p.iter().any(|c| c.target == "string.format"));
            assert!(p.iter().any(|c| c.target == "string.len"));
        }

        // ----- Global func assignment definition tracking -----
        #[test]
        fn test_global_func_assignment_definition() {
            let source = r#"
MyModule.func = function()
    return 1
end
"#;
            let handler = LuaHandler::new();
            let tree = handler.parse_source(source).unwrap();
            let (funcs, _) = handler
                .extract_definitions(source, Path::new("test.lua"), &tree)
                .unwrap();
            assert!(
                funcs.iter().any(|f| f.name == "func"),
                "Should define 'func' from MyModule.func = function() end"
            );
        }

        /// Test cross-scope intra-file call extraction: method in table calls top-level function.
        /// The caller name should be qualified with the table name.
        #[test]
        fn test_extract_calls_method_to_toplevel() {
            let source = r#"
function helper_func()
    return 42
end

local M = {}

function M.method()
    helper_func()
end

return M
"#;
            let calls = extract_calls(source);

            // The method should have a call to helper_func marked as Intra
            // The caller name should be qualified as "M.method"
            let method_calls = calls.get("M.method").or(calls.get("method"));
            assert!(
                method_calls.is_some(),
                "Should find calls for M.method. Got: {:?}",
                calls.keys().collect::<Vec<_>>()
            );

            let method_calls = method_calls.unwrap();
            let helper_call = method_calls.iter().find(|c| c.target == "helper_func");

            assert!(
                helper_call.is_some(),
                "Should find call from method to top-level helper_func. Got: {:?}",
                method_calls
            );

            let call = helper_call.unwrap();
            assert_eq!(
                call.call_type,
                CallType::Intra,
                "Call to same-file top-level function should be Intra"
            );

            // Verify the caller is qualified with table name
            assert_eq!(
                call.caller, "M.method",
                "Caller should be qualified with table name"
            );
        }
    }
}