aurora-lint 0.4.336

aurora-lint - a fast CERT C static analyzer
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
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
//! EXP33-C: Do not read uninitialized memory
//!
//! Detects reads of local variables that may not have been initialized.
//! Uses CFG-based forward dataflow analysis to track initialization state
//! across branches, loops, and early returns.

use super::super::{CertRule, RuleViolation};
use crate::analyze::cfg::{self as cfg_mod, FunctionCfg};
use crate::analyze::context::ProjectContext;
use crate::analyze::function_summary::FunctionSummary;
use crate::analyze::init_state::{self, InitAnalysisResult, InitState, InitStateMap};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::{get_identifier_from_declarator, get_node_text};
use lang_parsing_substrate::query;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use tree_sitter::Node;

pub struct Exp33C {
    function_cfgs: RefCell<HashMap<usize, FunctionCfg>>,
    /// File-scope static variable init states (collected at translation_unit level).
    file_scope_statics: RefCell<InitStateMap>,
    /// Functions that return realloc results (interprocedural pre-scan).
    realloc_wrapper_fns: RefCell<HashSet<String>>,
    /// Functions with pointer params that are only conditionally initialized.
    /// Maps function name → set of pointer parameter indices that are conditional.
    conditionally_init_fns: RefCell<HashMap<String, HashSet<usize>>>,
    /// Cross-file function summaries from prescan (for inter-procedural init tracking).
    cross_file_summaries: RefCell<HashMap<String, FunctionSummary>>,
    /// File-scope constants for dead-branch elimination in init-state analysis.
    file_scope_constants: RefCell<HashMap<String, i64>>,
    /// Cross-file function-like macro definitions (from the prescan / macro
    /// engine). Used to recognize macro output arguments (e.g. `CF_DATA_SAVE`).
    function_macros: RefCell<HashMap<String, crate::analyze::macro_expand::FunctionMacro>>,
    /// Output-parameter indices for macros actually invoked in the current file
    /// (computed once per file from `function_macros`). Feeds the init-state
    /// transfer and the read-checker so macro-written args are not flagged.
    macro_output_params: RefCell<HashMap<String, Vec<usize>>>,
}

impl Exp33C {
    pub fn new() -> Self {
        Self {
            function_cfgs: RefCell::new(HashMap::new()),
            file_scope_statics: RefCell::new(InitStateMap::new()),
            realloc_wrapper_fns: RefCell::new(HashSet::new()),
            conditionally_init_fns: RefCell::new(HashMap::new()),
            cross_file_summaries: RefCell::new(HashMap::new()),
            file_scope_constants: RefCell::new(HashMap::new()),
            function_macros: RefCell::new(HashMap::new()),
            macro_output_params: RefCell::new(HashMap::new()),
        }
    }

    /// Build the read-only dereference map from cross-file summaries.
    /// Returns functions that dereference a pointer param without modifying it.
    fn build_read_only_deref_fns(&self) -> HashMap<String, HashSet<usize>> {
        let summaries = self.cross_file_summaries.borrow();
        let mut result = HashMap::new();
        for (name, summary) in summaries.iter() {
            let read_only: HashSet<usize> = summary
                .dereferences_params
                .difference(&summary.modifies_params)
                .copied()
                .collect();
            if !read_only.is_empty() {
                result.insert(name.clone(), read_only);
            }
        }
        result
    }

    /// Build the cross-file output-param map from prescan summaries: functions
    /// that write through a pointer param, per `FunctionSummary::modifies_params`.
    /// Complements `build_read_only_deref_fns` — where that returns the read-only
    /// complement, this returns the write set directly (task 195/319 follow-on).
    fn build_cross_file_output_params(&self) -> HashMap<String, HashSet<usize>> {
        let summaries = self.cross_file_summaries.borrow();
        let mut result = HashMap::new();
        for (name, summary) in summaries.iter() {
            if !summary.modifies_params.is_empty() {
                result.insert(name.clone(), summary.modifies_params.clone());
            }
        }
        result
    }
}

impl CertRule for Exp33C {
    fn rule_id(&self) -> &'static str {
        "EXP33-C"
    }

    fn description(&self) -> &'static str {
        "Do not read uninitialized memory"
    }

    fn severity(&self) -> Severity {
        Severity::High
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Rule
    }

    fn cert_id(&self) -> &'static str {
        "EXP33-C"
    }

    fn set_project_context(&self, context: &ProjectContext) {
        *self.cross_file_summaries.borrow_mut() = context.function_summaries.clone();
        // Merge prescan global constants into file-scope constants.
        // File-scope constants (set later during check()) take precedence.
        let mut constants = self.file_scope_constants.borrow_mut();
        for (k, v) in &context.global_constants {
            constants.entry(k.clone()).or_insert(*v);
        }
        // Also include prescan macro constants (from #define directives)
        for (k, v) in &context.macro_constants {
            constants.entry(k.clone()).or_insert(*v);
        }
        drop(constants);
        // Function-like macro definitions (for macro output-arg recognition).
        *self.function_macros.borrow_mut() = context.function_macros.clone();
    }

    fn set_function_cfgs(&self, cfgs: &HashMap<usize, FunctionCfg>) {
        *self.function_cfgs.borrow_mut() = cfgs.clone();
    }

    fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
        let mut violations = Vec::new();
        let cfgs = self.function_cfgs.borrow();

        for n in
            query::find_descendants_of_kinds(*node, &["translation_unit", "function_definition"])
        {
            let node = &n;
            // At translation_unit level: collect file-scope statics and pre-scan functions
            if node.kind() == "translation_unit" {
                let statics = init_state::collect_file_scope_statics(node, source);
                *self.file_scope_statics.borrow_mut() = statics;

                // Collect file-scope constants for dead-branch elimination.
                // Merge with prescan global constants (file-scope wins on conflict).
                let file_constants = init_state::collect_file_scope_constants(node, source);
                // Also collect zero-arg constant-return functions (e.g., staticReturnsTrue()).
                let fn_constants = init_state::collect_constant_functions(node, source);
                {
                    let mut constants = self.file_scope_constants.borrow_mut();
                    // File-scope constants and constant functions override prescan globals
                    constants.extend(file_constants);
                    constants.extend(fn_constants);
                }

                // Pre-scan for realloc wrapper functions
                let mut wrappers = HashSet::new();
                scan_realloc_wrappers(node, source, &mut wrappers);
                *self.realloc_wrapper_fns.borrow_mut() = wrappers;

                // Pre-scan for functions that conditionally initialize pointer params
                let mut cond_init = HashMap::new();
                scan_conditionally_init_functions(node, source, &mut cond_init);
                *self.conditionally_init_fns.borrow_mut() = cond_init;

                // Precompute output-parameter indices for the function-like macros
                // actually invoked in this file (cheap: only invoked names, once per
                // file). Macros whose body assigns a parameter (e.g. CF_DATA_SAVE)
                // write that argument — feeds the init-state transfer + read-checker.
                let macros = self.function_macros.borrow();
                if !macros.is_empty() {
                    let mut invoked = HashSet::new();
                    collect_invoked_macro_names(node, source, &macros, &mut invoked);
                    let mut out_params = HashMap::new();
                    let cross_file_summaries = self.cross_file_summaries.borrow();
                    for name in invoked {
                        let mut idx = crate::analyze::macro_expand::macro_output_param_indices(
                            &macros, &name,
                        );
                        // No output arg from the macro's own body text? It may
                        // still be a "pure forwarding" macro (curl's
                        // `Curl_rand(a,b,c)` -> `Curl_rand_bytes(a,b,c)`) whose
                        // forwarded function genuinely writes through one of
                        // those args, per its own (already-computed)
                        // FunctionSummary -- task 589.
                        if idx.is_empty() {
                            if let Some((callee, param_map)) =
                                crate::analyze::macro_expand::macro_forwarding_target(
                                    &macros, &name,
                                )
                            {
                                if let Some(summary) = cross_file_summaries.get(&callee) {
                                    let mut mapped: Vec<usize> = summary
                                        .modifies_params
                                        .iter()
                                        .filter_map(|&callee_idx| {
                                            param_map.get(callee_idx).copied().flatten()
                                        })
                                        .collect();
                                    mapped.sort_unstable();
                                    idx = mapped;
                                }
                            }
                        }
                        if !idx.is_empty() {
                            out_params.insert(name, idx);
                        }
                    }
                    drop(cross_file_summaries);
                    *self.macro_output_params.borrow_mut() = out_params;
                }
            }

            if node.kind() == "function_definition" {
                if let Some(body) = node.child_by_field_name("body") {
                    // Get pre-built CFG or build one on the fly
                    let inline_cfg;
                    let cfg = if let Some(c) = cfgs.get(&node.start_byte()) {
                        c
                    } else if let Some(c) = cfg_mod::build_function_cfg(node, source) {
                        inline_cfg = c;
                        &inline_cfg
                    } else {
                        continue;
                    };

                    // Run CFG-based init-state dataflow
                    let statics = self.file_scope_statics.borrow();
                    let cond_fns = self.conditionally_init_fns.borrow();
                    let realloc_fns = self.realloc_wrapper_fns.borrow();
                    let read_only_fns = self.build_read_only_deref_fns();
                    let cross_file_output_params = self.build_cross_file_output_params();
                    let file_constants = self.file_scope_constants.borrow();
                    let macro_out = self.macro_output_params.borrow();
                    let config = init_state::InitAnalysisConfig {
                        conditionally_init_fns: cond_fns.clone(),
                        realloc_wrapper_fns: realloc_fns.clone(),
                        read_only_deref_fns: read_only_fns.clone(),
                        file_scope_constants: file_constants.clone(),
                        macro_output_params: macro_out.clone(),
                        cross_file_output_params,
                    };
                    let analysis = init_state::analyze_init_states_with_statics(
                        cfg, node, source, &statics, &config,
                    );

                    // Walk AST for read sites and check each against dataflow result
                    let mut reported: HashSet<String> = HashSet::new();
                    check_reads(
                        &body,
                        source,
                        &analysis,
                        cfg,
                        &body,
                        &mut violations,
                        &mut reported,
                        &config,
                    );

                    check_append_call_reads(
                        &body,
                        source,
                        &analysis,
                        cfg,
                        &body,
                        &mut violations,
                        &mut reported,
                        &config,
                    );

                    // Check for cross-file calls passing &uninit_var to functions
                    // that read through the pointer (variant 63/64 pattern).
                    if !read_only_fns.is_empty() {
                        check_cross_file_uninit_calls(
                            &body,
                            source,
                            &analysis,
                            cfg,
                            &body,
                            &read_only_fns,
                            &mut violations,
                            &mut reported,
                        );
                    }
                }
            }
        }

        violations
    }
}

// ---------------------------------------------------------------------------
// AST walk for read sites
// ---------------------------------------------------------------------------

/// Walk the AST looking for reads of tracked variables.
fn check_reads(
    node: &Node,
    source: &str,
    analysis: &InitAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    violations: &mut Vec<RuleViolation>,
    reported: &mut HashSet<String>,
    config: &init_state::InitAnalysisConfig,
) {
    let asm_ranges = asm_call_ranges(body, source);

    for n in query::find_descendants_of_kinds(
        *node,
        &["identifier", "pointer_expression", "subscript_expression"],
    ) {
        match n.kind() {
            "identifier" => {
                check_identifier_read(
                    &n,
                    source,
                    analysis,
                    cfg,
                    body,
                    violations,
                    reported,
                    config,
                    &asm_ranges,
                );
            }
            "pointer_expression" => {
                // *ptr — check if ptr content is uninitialized
                let text = get_node_text(&n, source);
                if text.starts_with('*') {
                    check_deref_read(
                        &n, source, analysis, cfg, body, violations, reported, config,
                    );
                }
            }
            "subscript_expression" => {
                check_subscript_read(
                    &n, source, analysis, cfg, body, violations, reported, config,
                );
            }
            _ => {}
        }
    }
}

/// Collect the names of function-like macros (present in `macros`) that are
/// invoked as `call_expression`s anywhere under `node`. Used to limit the
/// (slightly costly) output-param computation to macros actually used in the
/// file, rather than the whole cross-file macro table.
fn collect_invoked_macro_names(
    node: &Node,
    source: &str,
    macros: &HashMap<String, crate::analyze::macro_expand::FunctionMacro>,
    out: &mut HashSet<String>,
) {
    for call in query::find_descendants_of_kind(*node, "call_expression") {
        if let Some(func) = call.child_by_field_name("function") {
            if func.kind() == "identifier" {
                let name = get_node_text(&func, source);
                if macros.contains_key(name) {
                    out.insert(name.to_string());
                }
            }
        }
    }
}

/// True if `node` is a bare-identifier argument occupying an *output* position
/// (per `macro_output_params`) of a function-like macro invocation — i.e. the
/// macro writes this argument, so reading it there is not a use of an
/// uninitialized value. Mirrors `macro_semantics::is_macro_output_arg` for
/// expansion-derived (rather than registry) macros.
fn is_function_macro_output_arg(
    node: &Node,
    source: &str,
    macro_output_params: &HashMap<String, Vec<usize>>,
) -> bool {
    if node.kind() != "identifier" {
        return false;
    }
    // identifier -> argument_list -> call_expression
    let arg_list = match node.parent() {
        Some(p) if p.kind() == "argument_list" => p,
        _ => return false,
    };
    let call = match arg_list.parent() {
        Some(c) if c.kind() == "call_expression" => c,
        _ => return false,
    };
    let func_name = match call.child_by_field_name("function") {
        Some(f) => get_node_text(&f, source),
        None => return false,
    };
    let out_indices = match macro_output_params.get(func_name) {
        Some(v) => v,
        None => return false,
    };
    let args = crate::analyze::macro_semantics::positional_args(&call);
    let target = node.id();
    for (pos, arg) in args.into_iter().enumerate() {
        if arg.id() == target {
            return out_indices.contains(&pos);
        }
    }
    false
}

/// The nearest enclosing `#ifdef`/`#ifndef` guard around `node`, as a key
/// combining the directive spelling and the guarded macro name (e.g.
/// `"#ifdef:CONFIG_ELOOP_SELECT"`) so `#ifdef X` and `#ifndef X` -- opposite
/// conditions -- never compare equal. `tree-sitter-c` parses both directives
/// as the same `preproc_ifdef` node kind (field `name` for the macro,
/// `alternative` for a trailing `#else`/`#elif`), distinguished only by the
/// literal leading token. Returns `None` when `node` is in the `#else`/`#elif`
/// alternative of the nearest conditional (a different, unrelated branch) or
/// there is no enclosing conditional before `boundary` (the function body).
/// See [`all_write_sites_ifdef_correlated`] for why this matters (task 590).
fn enclosing_ifdef_guard_key(node: &Node, boundary: &Node, source: &str) -> Option<String> {
    let mut current = *node;
    while current.id() != boundary.id() {
        let Some(parent) = current.parent() else {
            // No `preproc_ifdef` ancestor found before running out of tree
            // -- same "give up" case as reaching `boundary` below.
            return blanked_label_guard_key(node, boundary, source);
        };
        if parent.kind() == "preproc_ifdef" {
            let is_alt = parent
                .child_by_field_name("alternative")
                .is_some_and(|alt| alt.id() == current.id());
            if is_alt {
                return None;
            }
            let directive = parent.child(0).map(|c| get_node_text(&c, source))?;
            let name = parent.child_by_field_name("name")?;
            return Some(format!("{directive}:{}", get_node_text(&name, source)));
        }
        if parent.id() == boundary.id() {
            // No real `preproc_ifdef` ancestor -- fall back to the
            // text-level marker `label_preproc_guard::blank_label_guarded_preproc`
            // leaves behind when it removes a label-adjacent
            // `#ifdef`/`#ifndef` guard's AST node entirely (task 663).
            // Without this, a read site inside such a guard reports `None`
            // even though a real, unblanked occurrence of the identical
            // macro elsewhere in the function correctly resolves via the
            // path above -- defeating `all_write_sites_ifdef_correlated`
            // purely because of *how* the read's guard happened to parse.
            return blanked_label_guard_key(node, boundary, source);
        }
        current = parent;
    }
    None
}

/// Text-level fallback for [`enclosing_ifdef_guard_key`]: scan `source`
/// backward, line by line, from `node`'s own line up to (not past)
/// `boundary`'s start line, looking for a marker left by
/// `label_preproc_guard::blank_label_guarded_preproc` (task 663 -- kept
/// manually in sync with that module's `open_marker`/`CLOSE_MARKER`
/// formats: `"/*G{d|n}:{NAME}*/"` opening, `"/*E*/"` closing).
///
/// The first marker encountered going backward decides the answer: an open
/// marker means `node` is still inside that guard (return its key, in the
/// same `"{directive}:{name}"` format the AST-based path above produces, so
/// it compares equal to a real, unblanked occurrence of the same macro); a
/// close marker means `node` is past an unrelated, already-closed guard
/// (return `None` rather than incorrectly matching something earlier).
/// Reaching `boundary` without finding either also returns `None`.
fn blanked_label_guard_key(node: &Node, boundary: &Node, source: &str) -> Option<String> {
    let node_line = node.start_position().row;
    let boundary_line = boundary.start_position().row;
    if node_line <= boundary_line {
        return None;
    }
    let lines: Vec<&str> = source.lines().collect();
    for line in lines.get(boundary_line..node_line)?.iter().rev() {
        let trimmed = line.trim();
        if trimmed == "/*E*/" {
            return None;
        }
        if let Some(rest) = trimmed.strip_prefix("/*G") {
            let Some(rest) = rest.strip_suffix("*/") else {
                continue;
            };
            let mut parts = rest.splitn(2, ':');
            let (Some(sigil), Some(name)) = (parts.next(), parts.next()) else {
                continue;
            };
            let directive = match sigil {
                "d" => "#ifdef",
                "n" => "#ifndef",
                _ => continue,
            };
            return Some(format!("{directive}:{name}"));
        }
    }
    None
}

/// True if `var_name` has at least one write site in `body` (a plain
/// `var = …` assignment, or `var = …` as part of its own declaration) and
/// EVERY such write site sits under the identical `#ifdef`/`#ifndef` guard
/// as `read_guard_key` (from [`enclosing_ifdef_guard_key`] at the read site).
///
/// Motivation (task 590): aurora-lint has no preprocessor, so
/// `cfg::process_preproc_conditional` models each `#ifdef GUARD ... #endif`
/// occurrence as an independent "maybe compiled, maybe not" branch+join.
/// When a variable's only writes AND the read in question are all under the
/// textually identical guard, that independence assumption is wrong -- one
/// macro's defined-ness is a single fixed fact for the whole translation
/// unit, so every occurrence of `GUARD` resolves the same way, and the
/// dataflow's MaybeUninitialized is a modeling artifact, not a real risk.
/// Conservative by construction: any write with no guard at all, a
/// DIFFERENT guard, or zero writes found at all, returns `false` (keep
/// flagging as before) -- this only suppresses the exact correlated shape.
fn all_write_sites_ifdef_correlated(
    body: &Node,
    var_name: &str,
    read_guard_key: &str,
    source: &str,
) -> bool {
    let mut found_any = false;
    for assign in query::find_descendants_of_kind(*body, "assignment_expression") {
        let Some(left) = assign.child_by_field_name("left") else {
            continue;
        };
        if left.kind() != "identifier" || get_node_text(&left, source) != var_name {
            continue;
        }
        found_any = true;
        match enclosing_ifdef_guard_key(&assign, body, source) {
            Some(key) if key == read_guard_key => {}
            _ => return false,
        }
    }
    for init_decl in query::find_descendants_of_kind(*body, "init_declarator") {
        let Some(declarator) = init_decl.child_by_field_name("declarator") else {
            continue;
        };
        if get_identifier_from_declarator(&declarator, source) != var_name {
            continue;
        }
        found_any = true;
        match enclosing_ifdef_guard_key(&init_decl, body, source) {
            Some(key) if key == read_guard_key => {}
            _ => return false,
        }
    }
    found_any
}

/// True if `body` contains an object-like `#define var_name ...`
/// (`preproc_def` whose `name` field spells `var_name`) anywhere. This is
/// almost always the alternative branch of an `#ifdef`/`#ifndef` whose
/// other branch assigns a same-named real variable, e.g. sqlite's
/// `#ifndef SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(...); #else
/// # define pTrigger 0 #endif`. aurora-lint has no preprocessor, so a later,
/// unconditional read of `var_name` after the `#endif` looks like a join of
/// "assigned in one branch, untouched in the other" -- MaybeUninitialized.
/// But that's not a real risk in any actually-compiled configuration:
/// whichever branch's guard condition holds, either the variable is
/// assigned directly, or it is `#define`d to a constant that the
/// preprocessor substitutes at every later use (including this read) for
/// the rest of the translation unit -- so in that configuration this
/// "read" is never actually of the declared variable at all (task 461
/// category 5; sqlite's insert.c/delete.c/update.c pTrigger/tmask/isView).
fn has_macro_shadow_definition(body: &Node, var_name: &str, source: &str) -> bool {
    query::find_descendants_of_kind(*body, "preproc_def")
        .iter()
        .any(|def| {
            def.child_by_field_name("name")
                .is_some_and(|n| get_node_text(&n, source) == var_name)
        })
}

/// Append-style functions that both read (find the existing null terminator)
/// and write their first argument. `get_output_arg_indices` models arg 0 as
/// pure output so ordinary reads of it don't false-positive elsewhere; this
/// check restores the read half specifically for the case that matters:
/// content that is still unsafe (e.g. `dst = uninit_array;` decay, or
/// `malloc` without a subsequent write) at the point it's appended to.
const APPEND_FUNCTIONS: &[&str] = &["strcat", "strncat", "wcscat", "wcsncat"];

/// Check calls to append-style functions (`strcat(dst, src)`) whose
/// destination argument is still content-unsafe — the append needs an
/// existing null terminator that was never written.
fn check_append_call_reads(
    node: &Node,
    source: &str,
    analysis: &InitAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    violations: &mut Vec<RuleViolation>,
    reported: &mut HashSet<String>,
    config: &init_state::InitAnalysisConfig,
) {
    for call in query::find_descendants_of_kind(*node, "call_expression") {
        let Some(func) = call.child_by_field_name("function") else {
            continue;
        };
        if func.kind() != "identifier" {
            continue;
        }
        let func_name = get_node_text(&func, source);
        if !APPEND_FUNCTIONS.contains(&func_name) {
            continue;
        }
        let Some(args) = call.child_by_field_name("arguments") else {
            continue;
        };
        let Some(first_arg) = (0..args.child_count())
            .filter_map(|i| args.child(i))
            .find(|c| !matches!(c.kind(), "," | "(" | ")"))
        else {
            continue;
        };
        if first_arg.kind() != "identifier" {
            continue;
        }
        let var_name = get_node_text(&first_arg, source).to_string();
        if !analysis.tracked_vars.contains(&var_name) || reported.contains(&var_name) {
            continue;
        }
        let Some(info) = init_state::get_var_info_at_with_config(
            analysis,
            cfg,
            body,
            source,
            &var_name,
            call.start_byte(),
            config,
        ) else {
            continue;
        };
        if matches!(info.state, InitState::MallocUninitialized) && !info.is_unsigned_char {
            reported.insert(var_name.clone());
            violations.push(RuleViolation {
                rule_id: "EXP33-C".to_string(),
                severity: Severity::High,
                message: format!(
                    "'{}' passed to '{}' without prior initialization (append requires an existing null terminator)",
                    var_name, func_name
                ),
                file_path: String::new(),
                line: call.start_position().row + 1,
                column: call.start_position().column + 1,
                suggestion: Some(format!(
                    "Initialize '{}' (e.g., null-terminate it) before appending to it",
                    var_name
                )),
                ..Default::default()
            });
        }
    }
}

/// Check for calls that pass `&uninit_var` to cross-file functions that read
/// through the pointer without writing first (variant 63/64 pattern).
fn check_cross_file_uninit_calls(
    node: &Node,
    source: &str,
    analysis: &InitAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    read_only_fns: &HashMap<String, HashSet<usize>>,
    violations: &mut Vec<RuleViolation>,
    reported: &mut HashSet<String>,
) {
    for call in query::find_descendants_of_kind(*node, "call_expression") {
        if let Some(func) = call.child_by_field_name("function") {
            let func_name = get_node_text(&func, source).to_string();
            if let Some(read_only_params) = read_only_fns.get(&func_name) {
                if let Some(args) = call.child_by_field_name("arguments") {
                    let mut arg_idx: usize = 0;
                    for i in 0..args.child_count() {
                        if let Some(arg) = args.child(i) {
                            if arg.kind() == "," || arg.kind() == "(" || arg.kind() == ")" {
                                continue;
                            }
                            if read_only_params.contains(&arg_idx) {
                                // Check if arg is &var where var is uninitialized
                                let var_name = extract_addr_of_var(&arg, source);
                                if !var_name.is_empty()
                                    && analysis.tracked_vars.contains(&var_name)
                                    && !reported.contains(&var_name)
                                {
                                    if let Some(info) = init_state::get_var_info_at_with_config(
                                        analysis,
                                        cfg,
                                        body,
                                        source,
                                        &var_name,
                                        call.start_byte(),
                                        &init_state::InitAnalysisConfig::default(),
                                    ) {
                                        if info.state.is_unsafe() && !info.is_unsigned_char {
                                            reported.insert(var_name.clone());
                                            violations.push(RuleViolation {
                                                rule_id: "EXP33-C".to_string(),
                                                severity: Severity::High,
                                                message: format!(
                                                    "Passing pointer to uninitialized variable '{}' to '{}' which reads the value",
                                                    var_name, func_name
                                                ),
                                                file_path: String::new(),
                                                line: call.start_position().row + 1,
                                                column: call.start_position().column + 1,
                                                suggestion: Some(format!(
                                                    "Initialize '{}' before passing its address to '{}'",
                                                    var_name, func_name
                                                )),
                                                ..Default::default()
                                            });
                                        }
                                    }
                                }
                            }
                            arg_idx += 1;
                        }
                    }
                }
            }
        }
    }
}

/// Extract the variable name from an `&var` expression. Returns empty string if not `&var`.
fn extract_addr_of_var(node: &Node, source: &str) -> String {
    // Direct &var: pointer_expression with & operator
    if node.kind() == "pointer_expression" {
        let text = get_node_text(node, source);
        if text.starts_with('&') {
            if let Some(arg) = node.child_by_field_name("argument") {
                if arg.kind() == "identifier" {
                    return get_node_text(&arg, source).to_string();
                }
            }
        }
    }
    // Parenthesized: (&var)
    if node.kind() == "parenthesized_expression" {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                let result = extract_addr_of_var(&child, source);
                if !result.is_empty() {
                    return result;
                }
            }
        }
    }
    String::new()
}

/// Check if an identifier read is of an uninitialized variable.
fn check_identifier_read(
    node: &Node,
    source: &str,
    analysis: &InitAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    violations: &mut Vec<RuleViolation>,
    reported: &mut HashSet<String>,
    config: &init_state::InitAnalysisConfig,
    asm_ranges: &[(usize, usize)],
) {
    let var_name = get_node_text(node, source).to_string();

    // Skip if not tracked
    if !analysis.tracked_vars.contains(&var_name) {
        return;
    }

    // Skip if already reported
    if reported.contains(&var_name) {
        return;
    }

    // Skip if this is NOT a read context
    if !is_read_context(node, source, &config.cross_file_output_params, asm_ranges) {
        return;
    }

    // Skip identifiers that are the iterator/temp/out argument of a known
    // iterator/find macro (utlist/uthash/BSD-queue). The macro *writes* these
    // args, so their appearance in the invocation is not a use of an
    // uninitialized value. See crate::analyze::macro_semantics (Phase 1 of
    // docs/design/macro-expansion.md).
    if crate::analyze::macro_semantics::is_macro_output_arg(node, source) {
        return;
    }

    // Skip identifiers that are the *output* argument of a function-like macro
    // whose body assigns them (e.g. curl's `CF_DATA_SAVE(save, …)`). The macro
    // writes this arg, so its appearance in the invocation is not a read of an
    // uninitialized value. Phase 2c-ii of docs/design/macro-expansion.md.
    if is_function_macro_output_arg(node, source, &config.macro_output_params) {
        return;
    }

    // Query init state at this point

    let info = match init_state::get_var_info_at_with_config(
        analysis,
        cfg,
        body,
        source,
        &var_name,
        node.start_byte(),
        config,
    ) {
        Some(i) => i,
        None => return,
    };

    // EXP33-C exception: reading uninitialized unsigned char is permitted
    if info.is_unsigned_char {
        return;
    }

    // Only flag truly uninitialized or maybe-uninitialized reads
    if !info.state.is_unsafe() {
        return;
    }

    // Arrays passed by name to unknown function calls decay to pointers.
    // The init-state transfer function treats such arrays as initialized
    // (assumes the function writes to them). Skip the read-check here
    // for consistency, but only for truly unknown functions — not for
    // known read-only or known initializing functions (handled separately).
    if info.is_array {
        if let Some(parent) = node.parent() {
            // Array-to-pointer decay: `ptr = arr` where arr is on the RHS.
            // Taking the address of an array (char or not) is not itself a
            // content read — suppress here and detect later at the actual
            // use site (subscript access, dereference, or an append-style
            // call like strcat/wcscat via check_append_call_reads).
            if parent.kind() == "assignment_expression" {
                if let Some(right) = parent.child_by_field_name("right") {
                    if right.id() == node.id() {
                        return;
                    }
                }
            }
            if parent.kind() == "argument_list" {
                if let Some(call_expr) = parent.parent() {
                    if call_expr.kind() == "call_expression" {
                        if let Some(func) = call_expr.child_by_field_name("function") {
                            let fname = get_node_text(&func, source).to_string();
                            // Known functions are already handled by is_read_in_argument_list.
                            // Only suppress for truly unknown functions (not non-initializing).
                            if init_state::match_initializing_function(&fname).is_none()
                                && !init_state::is_non_initializing_function(&fname)
                            {
                                return;
                            }
                        }
                    }
                }
            }
        }
    }

    // aurora-lint has no preprocessor, so an `#ifdef GUARD ... #endif` block is
    // modeled as possibly-compiled-or-possibly-skipped, independently at
    // each occurrence (see `cfg::process_preproc_conditional`). When a
    // variable is written ONLY inside one or more `#ifdef`/`#ifndef` blocks
    // and this read sits inside a block with the textually IDENTICAL guard
    // (same directive, same macro name), the two are not actually
    // independent: `GUARD`'s defined-ness is one fixed fact for the whole
    // translation unit, so in every real compiled configuration the write
    // and this read either both happen or both don't. Flagging
    // MaybeUninitialized here is an artifact of modeling each occurrence as
    // an independent coin flip, not a real risk (task 590; hostap's
    // eloop_run: `rfds` is declared+malloc'd only under
    // `#ifdef CONFIG_ELOOP_SELECT` and read here under the identical
    // guard). Scoped to MaybeUninitialized only -- a bare Uninitialized
    // read (no write anywhere) is unaffected by this and still flagged.
    if matches!(info.state, InitState::MaybeUninitialized) {
        if let Some(read_guard) = enclosing_ifdef_guard_key(node, body, source) {
            if all_write_sites_ifdef_correlated(body, &var_name, &read_guard, source) {
                return;
            }
        }
        if has_macro_shadow_definition(body, &var_name, source) {
            return;
        }
    }

    reported.insert(var_name.clone());

    let message = if info.is_static {
        format!(
            "Static variable '{}' used without explicit initialization",
            var_name
        )
    } else if matches!(info.state, InitState::MaybeUninitialized) {
        format!(
            "Variable '{}' may be used uninitialized (not assigned on all paths)",
            var_name
        )
    } else {
        format!("Variable '{}' is used uninitialized", var_name)
    };

    violations.push(RuleViolation {
        rule_id: "EXP33-C".to_string(),
        severity: Severity::High,
        message,
        file_path: String::new(),
        line: node.start_position().row + 1,
        column: node.start_position().column + 1,
        suggestion: Some(format!(
            "Initialize '{}' before use, e.g., at its declaration",
            var_name
        )),
        ..Default::default()
    });
}

/// Check if a dereference (*ptr) reads uninitialized content.
fn check_deref_read(
    node: &Node,
    source: &str,
    analysis: &InitAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    violations: &mut Vec<RuleViolation>,
    reported: &mut HashSet<String>,
    config: &init_state::InitAnalysisConfig,
) {
    // Extract the pointer variable being dereferenced
    let var_name = if let Some(arg) = node.child_by_field_name("argument") {
        if arg.kind() == "identifier" {
            get_node_text(&arg, source).to_string()
        } else {
            return;
        }
    } else {
        return;
    };

    if !analysis.tracked_vars.contains(&var_name) || reported.contains(&var_name) {
        return;
    }

    // Skip non-read contexts (e.g., *ptr = value is a write)
    if !is_deref_read_context(node) {
        return;
    }

    // `sizeof(*ptr)` — the operand of sizeof is unevaluated per C11 6.5.3.4,
    // so this is not a dereference of ptr's (possibly not-yet-set) value,
    // just a compile-time size computation from ptr's static pointee type.
    // check_identifier_read/is_read_context already exempts sizeof via
    // has_sizeof_or_alignof_ancestor, but that path is never reached here:
    // check_reads visits `*ptr` itself as its own pointer_expression node
    // (real-world FPs: sqlite's `pRhs = sqlite3_malloc64(sizeof(*pRhs))`,
    // hostap's `vhdr` in `while (left >= sizeof(*vhdr))`, task 391).
    if let Some(parent) = node.parent() {
        if has_sizeof_or_alignof_ancestor(parent) {
            return;
        }
    }

    let info = match init_state::get_var_info_at_with_config(
        analysis,
        cfg,
        body,
        source,
        &var_name,
        node.start_byte(),
        config,
    ) {
        Some(i) => i,
        None => return,
    };

    // A static/thread-local pointer with no explicit initializer is
    // zero-initialized (NULL) per C11 6.7.9p10 -- its value is determinate,
    // just not what the programmer probably intended (the identifier-level
    // check above already surfaces that as a softer "used without explicit
    // initialization" note). Dereferencing it is a null-pointer-deref
    // concern, not "uninitialized/indeterminate content" -- EXP33-C's own
    // domain (task 459).
    if info.is_static {
        return;
    }

    // Check both pointer and content state
    if info.state.is_unsafe() {
        // Pointer itself is uninitialized
        reported.insert(var_name.clone());
        violations.push(RuleViolation {
            rule_id: "EXP33-C".to_string(),
            severity: Severity::High,
            message: format!("Dereference of uninitialized pointer '{}'", var_name),
            file_path: String::new(),
            line: node.start_position().row + 1,
            column: node.start_position().column + 1,
            suggestion: Some(format!(
                "Initialize pointer '{}' before dereferencing",
                var_name
            )),
            ..Default::default()
        });
    } else if info.state.is_content_unsafe() {
        // Pointer is set but content is uninitialized (malloc without memset)
        reported.insert(var_name.clone());
        violations.push(RuleViolation {
            rule_id: "EXP33-C".to_string(),
            severity: Severity::High,
            message: format!(
                "Reading from '{}' which points to uninitialized memory (allocated without initialization)",
                var_name
            ),
            file_path: String::new(),
            line: node.start_position().row + 1,
            column: node.start_position().column + 1,
            suggestion: Some(
                "Use calloc() instead of malloc(), or memset() after allocation".to_string(),
            ),
            ..Default::default()
        });
    }
}

/// Check if a subscript access (arr[i]) reads uninitialized content.
fn check_subscript_read(
    node: &Node,
    source: &str,
    analysis: &InitAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    violations: &mut Vec<RuleViolation>,
    reported: &mut HashSet<String>,
    config: &init_state::InitAnalysisConfig,
) {
    // Extract base variable (handles arr[i], arr->field[i], etc.)
    let var_name = {
        let mut name = String::new();
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "identifier" {
                    name = get_node_text(&child, source).to_string();
                    break;
                }
                // Handle arr->data[i] — subscript base is a field_expression
                if child.kind() == "field_expression" {
                    name = extract_root_identifier(&child, source);
                    break;
                }
            }
        }
        name
    };

    if var_name.is_empty()
        || !analysis.tracked_vars.contains(&var_name)
        || reported.contains(&var_name)
    {
        return;
    }

    // Skip non-read contexts
    if !is_subscript_read_context(node, source) {
        return;
    }

    // `sizeof(arr[i])` — the operand of sizeof is unevaluated per C11
    // 6.5.3.4; the subscript access itself is not actually performed.
    if let Some(parent) = node.parent() {
        if has_sizeof_or_alignof_ancestor(parent) {
            return;
        }
    }

    let info = match init_state::get_var_info_at_with_config(
        analysis,
        cfg,
        body,
        source,
        &var_name,
        node.start_byte(),
        config,
    ) {
        Some(i) => i,
        None => return,
    };

    // EXP33-C exception: unsigned char content reads are permitted
    if info.is_unsigned_char {
        return;
    }

    // A static/thread-local array with no explicit initializer is
    // zero-initialized per C11 6.7.9p10 -- its elements are determinate
    // (just possibly not what the programmer intended), not indeterminate
    // content the way an uninitialized auto array's would be (task 459).
    if info.is_static {
        return;
    }

    // For subscript reads, only flag definitely-uninitialized content.
    // MaybeUninitialized often results from loop-based array initialization
    // where the loop join produces a conservative MaybeUninitialized.
    let content_unsafe = matches!(
        info.state,
        InitState::Uninitialized | InitState::MallocUninitialized
    );

    if content_unsafe {
        reported.insert(var_name.clone());
        violations.push(RuleViolation {
            rule_id: "EXP33-C".to_string(),
            severity: Severity::High,
            message: format!(
                "Reading from '{}' which may contain uninitialized data",
                var_name
            ),
            file_path: String::new(),
            line: node.start_position().row + 1,
            column: node.start_position().column + 1,
            suggestion: Some(format!(
                "Initialize the contents of '{}' before reading",
                var_name
            )),
            ..Default::default()
        });
    }
}

// ---------------------------------------------------------------------------
// Read-context detection
// ---------------------------------------------------------------------------

/// Check if an identifier node is in a read context (not a write target).
/// True if `node` lies inside the argument subtree of a `call_expression` whose
/// callee is a GNU asm keyword (`asm`, `__asm`, `__asm__`, any case).
///
/// tree-sitter-c misparses the `__asm("..." : "=r"(v) ...)` call forms, and the
/// *shape* of that misparse differs across grammar versions (e.g. 0.21 nested
/// the output operand as `call_expression("=r", [v])`, while 0.24 collapses the
/// operands into an `ERROR`/`concatenated_string` that can even swallow the
/// following statement). Rather than match one specific broken shape, treat
/// every identifier inside such an asm-keyword call as asm-opaque — never a
/// genuine uninitialized read. Properly-parsed `__asm__` uses `gnu_asm_*` nodes
/// and is handled by the match in `is_read_context`.
/// Byte ranges of the `asm(...)` / `__asm(...)` / `__asm__(...)` calls in
/// `body`, collected once per function.
///
/// The containment test this feeds replaces an ancestor walk per identifier.
/// `Node::parent()` is not a pointer hop -- tree-sitter recovers a parent by
/// descending from the tree root, so it costs O(depth) -- and walking from
/// every identifier up to its function therefore cost O(depth^2) each,
/// O(depth^3) over a file whose node count grows with its nesting depth. 800
/// nested `if`s took this rule 12 s before the change (task 952, this repo).
/// Nearly all C has no inline asm at all, so the usual result is an empty
/// slice and no test at all.
fn asm_call_ranges(body: &Node, source: &str) -> Vec<(usize, usize)> {
    let mut ranges = Vec::new();
    for call in query::find_descendants_of_kind(*body, "call_expression") {
        let Some(func) = call.child_by_field_name("function") else {
            continue;
        };
        if func.kind() != "identifier" {
            continue;
        }
        let name = get_node_text(&func, source).to_ascii_lowercase();
        if name == "asm" || name == "__asm" || name == "__asm__" {
            ranges.push((call.start_byte(), call.end_byte()));
        }
    }
    ranges
}

fn is_in_asm_call(node: &Node, asm_ranges: &[(usize, usize)]) -> bool {
    let start = node.start_byte();
    asm_ranges
        .iter()
        .any(|&(from, to)| start >= from && start < to)
}

fn is_read_context(
    node: &Node,
    source: &str,
    cross_file_output_params: &HashMap<String, HashSet<usize>>,
    asm_ranges: &[(usize, usize)],
) -> bool {
    // GNU asm is opaque to uninitialized analysis, and tree-sitter-c misparses
    // the __asm(...) / __ASM(...) call forms differently across grammar
    // versions. Any identifier inside such an asm-keyword call is asm-related,
    // not a real read — short-circuit before the shape-specific logic below.
    if is_in_asm_call(node, asm_ranges) {
        return false;
    }

    // Preprocessor-directive name identifiers are not C-expression reads at
    // all: `# define pTrigger 0` inside a conditionally-compiled `#else`
    // branch parses to a `preproc_def` whose `name` field is an `identifier`
    // node holding the same text as an unrelated tracked variable declared
    // in the surrounding function. aurora-lint has no preprocessor, so this
    // directive's tokens land as ordinary descendants of the function body
    // and fell through to the catch-all `_ => true` below, misflagging the
    // `#define` line itself as a read of that variable (task 461 category
    // 5 -- real-world sqlite insert.c/delete.c/update.c: `#ifndef
    // SQLITE_OMIT_TRIGGER ... #else # define pTrigger 0 ... #endif`).
    // Function-like macros (`preproc_function_def`) and their parameter
    // list (`preproc_params`), and `#undef NAME`, have the same shape.
    if let Some(parent) = node.parent() {
        if matches!(
            parent.kind(),
            "preproc_def" | "preproc_function_def" | "preproc_params" | "preproc_undef"
        ) {
            return false;
        }
    }

    // The declared name of a declaration is never itself a read, whether or
    // not it has an initializer — `Foo *pCaller;` and `Mem *pMem = expr;`
    // both just bring storage into existence at that point. The direct
    // "declaration" | "init_declarator" arm below only catches unwrapped
    // scalars (`int x;`); a pointer or array declarator wraps the identifier
    // one or more levels deeper (`pointer_declarator`/`array_declarator`),
    // which fell through to the catch-all `_ => true` and misflagged the
    // declaration line itself as a read (task 391's "plain declaration
    // statements misflagged as reads" category — real-world sqlite examples:
    // vdbe.c `VdbeOp *pCaller;` and `Mem *pMem = p->pResultRow;`).
    if is_declarator_name_of_declaration(node) {
        return false;
    }

    let parent = match node.parent() {
        Some(p) => p,
        None => return true,
    };

    // Walk up ancestors to check context
    // Some non-read contexts are nested: sizeof(x) → sizeof_expression > parenthesized_expression > identifier
    if has_sizeof_or_alignof_ancestor(parent) {
        return false;
    }

    match parent.kind() {
        // LHS of assignment
        "assignment_expression" => is_read_in_assignment(&parent, node, source),
        // Compound assignment (+=, -=, etc.) — both read and write
        "augmented_assignment_expression" => true,
        // Declaration — not a read
        "declaration" | "init_declarator" => false,
        // sizeof(x) — not a read
        "sizeof_expression" => false,
        // &x — address-of. Generally not a read, BUT if &x is passed to a
        // non-initializing function (one that reads from the pointer), it IS a read.
        "pointer_expression" => is_read_in_pointer_expression(&parent, source),
        // Update expression (i++, ++i) — both read and write, but we don't flag these
        "update_expression" => false,
        // Field expression LHS — writing to a field is NOT reading the base
        "field_expression" => is_read_in_field_expression(&parent),
        // Subscript base (arr[i]) — the base identifier provides the address,
        // not a value read. Content reads are handled by check_subscript_read.
        "subscript_expression" => false,
        // Parameter declaration — not a read
        "parameter_declaration" => false,
        // Cast expression — reading the value, EXCEPT the `(void)x;`
        // discard idiom (a bare identifier cast straight to `void`): the
        // standard "suppress unused-variable warning" convention, which
        // GCC/Clang special-case to never actually load the operand's
        // value when it's a plain identifier -- so this is not a real
        // content read regardless of what follows (task 461 category 10;
        // curl's ldap.c/mbedtls.c `(void)ldap_option;` / `(void)ldap_ca;`
        // on an `#else` branch that never assigned them, immediately
        // before an error-return path).
        "cast_expression" => !is_void_discard_cast(&parent, node, source),
        // Condition expressions — reading
        "binary_expression" | "unary_expression" | "conditional_expression" => true,
        // Function call argument — usually a read, but check for output args
        // of known initializing functions (e.g., fgets(input, ...) is a write to input)
        "argument_list" => {
            if is_misparsed_asm_output_operand(&parent, source) {
                return false;
            }
            is_read_in_argument_list(node, &parent, source, cross_file_output_params)
        }
        // Return statement — reading
        "return_statement" => true,
        // Comma expression
        "comma_expression" => true,
        // GNU asm output operands are writes ("=r"(var)) — not reads
        "gnu_asm_output_operand" => false,
        _ => true,
    }
}

/// True if `node` is the declared identifier of a declaration statement —
/// reached from the identifier by walking up through zero or more
/// `pointer_declarator`/`array_declarator` wrapping layers (each followed
/// only via its own `declarator` field, so an array's `size` expression is
/// never mistaken for the declared name) to a `declaration` (no initializer)
/// or `init_declarator` (has one) node. Either way, the identifier there
/// names storage coming into existence, not a value being read.
fn is_declarator_name_of_declaration(node: &Node) -> bool {
    let mut cur = *node;
    loop {
        let Some(parent) = cur.parent() else {
            return false;
        };
        match parent.kind() {
            "pointer_declarator" | "array_declarator" => {
                if parent.child_by_field_name("declarator").map(|d| d.id()) != Some(cur.id()) {
                    return false; // e.g. an array_declarator's `size` field
                }
                cur = parent;
            }
            "declaration" | "init_declarator" => return true,
            _ => return false,
        }
    }
}

/// Walk up through wrapping-expression ancestors (max 5 hops) to check
/// whether the nearest "real" ancestor is a `sizeof`/`_Alignof` context:
/// `sizeof(x)` → `sizeof_expression` > `parenthesized_expression` > `identifier`.
/// Also passes through `pointer_expression`/`subscript_expression`/
/// `field_expression` wrapping, so `sizeof(*p)`, `sizeof(arr[i])`, and
/// `sizeof(p->field)` are recognized too — the identifier read one of these
/// composes (`p`, `i`, `p`) is just as unevaluated as a bare `sizeof(x)`,
/// since sizeof's whole operand is unevaluated per C11 6.5.3.4.
fn has_sizeof_or_alignof_ancestor(parent: Node) -> bool {
    let mut ancestor = Some(parent);
    let mut depth = 0;
    while let Some(anc) = ancestor {
        depth += 1;
        if depth > 5 {
            return false;
        }
        match anc.kind() {
            "sizeof_expression" | "_Alignof" => return true,
            "parenthesized_expression"
            | "pointer_expression"
            | "subscript_expression"
            | "field_expression" => {
                ancestor = anc.parent();
                continue;
            }
            _ => return false,
        }
    }
    false
}

/// LHS of a plain assignment is a write only; LHS of a compound assignment
/// (`+=`, `-=`, ...) both reads and writes. The RHS is always a read.
fn is_read_in_assignment(parent: &Node, node: &Node, source: &str) -> bool {
    let Some(left) = parent.child_by_field_name("left") else {
        return true; // RHS is a read
    };
    if left.id() != node.id() {
        return true; // RHS is a read
    }
    for i in 0..parent.child_count() {
        if let Some(op) = parent.child(i) {
            let op_text = get_node_text(&op, source);
            if matches!(
                op_text,
                "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | "&=" | "|=" | "^="
            ) {
                return true; // Compound assignment reads the LHS
            }
        }
    }
    false // Simple assignment (=) — write only
}

/// True if `cast` is exactly `(void)node` -- `node` is the cast's bare
/// `value` operand and the cast's type is plain `void` (no pointer/array
/// wrapping, e.g. NOT `(void *)x`). This is the standard idiom for
/// silencing an "unused variable" warning without reading it: GCC/Clang
/// special-case a plain-identifier operand here to skip emitting a load,
/// so per real compiler behavior (not just intent) this never actually
/// reads the variable's content.
fn is_void_discard_cast(cast: &Node, node: &Node, source: &str) -> bool {
    let Some(value) = cast.child_by_field_name("value") else {
        return false;
    };
    if value.id() != node.id() {
        return false;
    }
    let Some(type_node) = cast.child_by_field_name("type") else {
        return false;
    };
    get_node_text(&type_node, source).trim() == "void"
}

/// `*x` is always a dereference read. `&var` is a read only when passed to a
/// non-initializing function (one that reads from the pointer).
fn is_read_in_pointer_expression(parent: &Node, source: &str) -> bool {
    let text = get_node_text(parent, source);
    if !text.starts_with('&') {
        return true; // *x — dereference read
    }
    // Check if &var is inside an argument_list of a non-initializing function
    let Some(arg_list) = parent.parent() else {
        return false;
    };
    if arg_list.kind() != "argument_list" {
        return false;
    }
    let Some(call) = arg_list.parent() else {
        return false;
    };
    if call.kind() != "call_expression" {
        return false;
    }
    let Some(func) = call.child_by_field_name("function") else {
        return false;
    };
    let func_name = get_node_text(&func, source);
    init_state::is_non_initializing_function(&func_name) // &var read by callee
}

/// `obj.field` is not a read of `obj` when it is the LHS of an assignment.
/// Walks up through chained field expressions (`a.b.c = val` — `a`'s
/// immediate parent is `a.b`, not `a.b.c`) to find the outermost field
/// access, since only that one can be the assignment's actual LHS.
fn is_read_in_field_expression(parent: &Node) -> bool {
    let mut outer = *parent;
    while let Some(next) = outer.parent() {
        // `obj.field[i] = val` / `obj.field[i].g[j] = val` — the assignment's
        // LHS is the subscript_expression wrapping the field access, not the
        // field access itself. Keep rebasing `outer` through subscript and
        // field wrapping (mirrors is_subscript_read_context's walk in the
        // other direction) so the assignment-LHS check below compares
        // against the actual outermost lvalue node, not just the last
        // field_expression seen.
        if next.kind() != "field_expression" && next.kind() != "subscript_expression" {
            break;
        }
        outer = next;
    }
    let Some(grandparent) = outer.parent() else {
        return true;
    };
    if grandparent.kind() != "assignment_expression" {
        return true;
    }
    let Some(left) = grandparent.child_by_field_name("left") else {
        return true;
    };
    left.id() != outer.id() // obj.field = val / obj.field[i] = val — obj is not "read"
}

/// `__asm("..." : "=r"(var) ...)` is misparsed by tree-sitter as
/// `call_expression("__asm", [ERROR, "=r"(var), ...])`. The output operand
/// `"=r"(var)` becomes `call_expression("=r", [var])`. Detect this: an
/// identifier inside an `argument_list` of a call whose function is a
/// string_literal with "=" (output constraint).
fn is_misparsed_asm_output_operand(arg_list: &Node, source: &str) -> bool {
    let Some(call_gp) = arg_list.parent() else {
        return false;
    };
    if call_gp.kind() != "call_expression" {
        return false;
    }
    let Some(func) = call_gp.child_by_field_name("function") else {
        return false;
    };
    if func.kind() != "string_literal" {
        return false;
    }
    get_node_text(&func, source).contains('=')
}

/// Check if an identifier in an argument_list is being read (vs. being an output arg).
fn is_read_in_argument_list(
    node: &Node,
    arg_list: &Node,
    source: &str,
    cross_file_output_params: &HashMap<String, HashSet<usize>>,
) -> bool {
    // Find the parent call_expression
    let call_expr = match arg_list.parent() {
        Some(c) if c.kind() == "call_expression" => c,
        _ => return true,
    };

    // Get function name
    let func_name = match call_expr.child_by_field_name("function") {
        Some(f) => get_node_text(&f, source).to_string(),
        None => return true,
    };

    // va_start/va_copy: first arg is output (initializes the va_list)
    if func_name == "va_start" || func_name == "va_copy" {
        // First non-punctuation arg is the output va_list
        if let Some(first_arg) = call_expr.child_by_field_name("arguments").and_then(|args| {
            for i in 0..args.child_count() {
                if let Some(c) = args.child(i) {
                    if c.kind() != "(" && c.kind() != ")" && c.kind() != "," {
                        return Some(c);
                    }
                }
            }
            None
        }) {
            if contains_node(&first_arg, node) {
                return false; // Output arg — not a read
            }
        }
        return true;
    }

    // Check if this is a known initializing function (exact or suffix match)
    let output_indices: HashSet<usize> = match init_state::match_initializing_function(&func_name) {
        Some(base_name) => init_state::get_output_arg_indices(base_name)
            .into_iter()
            .collect(),
        None => {
            // Not a built-in-registry initializer. Fall back to whether a
            // (same-file or cross-file) FunctionSummary found this function
            // writes through one of its pointer params (task 456) —
            // e.g. eloop_sock_table_set_fds(table, fd_set *fds) writing
            // `fds` via FD_ZERO/FD_SET. Without this, a bare pointer
            // variable passed by value (not `&var`, not an array) to such a
            // function was always treated as a read here, regardless of
            // what process_unknown_function_call's state transfer decided
            // afterward — the finding fires at the call site itself, before
            // any post-call state update is even consulted.
            match cross_file_output_params.get(&func_name) {
                Some(indices) if !indices.is_empty() => indices.clone(),
                _ => return true,
            }
        }
    };

    if output_indices.is_empty() {
        return true; // No output args — this is a read
    }

    let mut arg_idx = 0;
    for i in 0..arg_list.child_count() {
        if let Some(child) = arg_list.child(i) {
            if child.kind() == "," || child.kind() == "(" || child.kind() == ")" {
                continue;
            }
            // Check if this argument contains our identifier node
            if contains_node(&child, node) {
                return !output_indices.contains(&arg_idx);
            }
            arg_idx += 1;
        }
    }
    true // Couldn't determine position — assume read
}

/// Check if a node contains a specific descendant (by ID).
fn contains_node(haystack: &Node, needle: &Node) -> bool {
    let needle_id = needle.id();
    query::find_first_descendant(*haystack, |n| n.id() == needle_id).is_some()
}

/// Check if a dereference (*ptr) is in a read context.
fn is_deref_read_context(node: &Node) -> bool {
    let parent = match node.parent() {
        Some(p) => p,
        None => return true,
    };
    match parent.kind() {
        // *ptr = value is a write
        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                left.id() != node.id()
            } else {
                true
            }
        }
        _ => true,
    }
}

/// Check if a subscript access (arr[i]) is in a read context.
fn is_subscript_read_context(node: &Node, source: &str) -> bool {
    // Walk up ancestors to find if this subscript is ultimately on the LHS of an assignment
    let mut current = *node;
    for _ in 0..5 {
        let parent = match current.parent() {
            Some(p) => p,
            None => return true,
        };
        match parent.kind() {
            "assignment_expression" => {
                if let Some(left) = parent.child_by_field_name("left") {
                    // If the subscript (or its field_expression ancestor) is on the LHS → write
                    return left.id() != current.id();
                }
                return true;
            }
            // arr[0].field — subscript is inside field_expression, keep walking up
            "field_expression" => {
                current = parent;
                continue;
            }
            // &arr[i] — address-of a subscript element (e.g. an output-param
            // pointer into an array, curl's `&mime->boundary[N]` passed to
            // Curl_rand_alnum) is not itself a content read, same as
            // is_read_in_pointer_expression's identical exception for &var
            // (task 457) -- unless that address is then handed to a function
            // known to only read through it.
            "pointer_expression" => {
                let text = get_node_text(&parent, source);
                if !text.starts_with('&') {
                    return true;
                }
                let Some(arg_list) = parent.parent() else {
                    return false;
                };
                if arg_list.kind() != "argument_list" {
                    return false;
                }
                let Some(call) = arg_list.parent() else {
                    return false;
                };
                if call.kind() != "call_expression" {
                    return false;
                }
                let Some(func) = call.child_by_field_name("function") else {
                    return false;
                };
                let func_name = get_node_text(&func, source);
                return init_state::is_non_initializing_function(&func_name);
            }
            _ => return true,
        }
    }
    true
}

// ---------------------------------------------------------------------------
// Interprocedural pre-scan
// ---------------------------------------------------------------------------

/// Whether `body` contains a call to a function named `name`, matched
/// against the callee identifier node rather than the body's raw text — a
/// comment or string literal mentioning the name can't fake a call.
fn body_calls_function(body: &Node, source: &str, name: &str) -> bool {
    query::find_descendants_of_kind(*body, "call_expression")
        .iter()
        .any(|c| {
            c.child_by_field_name("function")
                .is_some_and(|f| get_node_text(&f, source) == name)
        })
}

/// Scan translation unit for functions that wrap realloc.
fn scan_realloc_wrappers(node: &Node, source: &str, wrappers: &mut HashSet<String>) {
    for func_def in query::find_descendants_of_kind(*node, "function_definition") {
        if let Some(body) = func_def.child_by_field_name("body") {
            if body_calls_function(&body, source, "realloc")
                && !body_calls_function(&body, source, "memset")
            {
                if let Some(declarator) = func_def.child_by_field_name("declarator") {
                    let name = get_func_name(&declarator, source);
                    if !name.is_empty() {
                        wrappers.insert(name);
                    }
                }
            }
        }
    }
}

/// Scan for functions that only conditionally initialize pointer params.
/// e.g., void set_flag(int n, int *flag) { if (n > 0) *flag = 1; }
/// — doesn't init *flag on all paths.
fn scan_conditionally_init_functions(
    node: &Node,
    source: &str,
    result: &mut HashMap<String, HashSet<usize>>,
) {
    for func_def in query::find_descendants_of_kind(*node, "function_definition") {
        let cond_indices = get_conditional_init_param_indices(&func_def, source);
        if !cond_indices.is_empty() {
            if let Some(declarator) = func_def.child_by_field_name("declarator") {
                let name = get_func_name(&declarator, source);
                if !name.is_empty() {
                    result.insert(name, cond_indices);
                }
            }
        }
    }
}

/// Get the set of pointer parameter indices that are only conditionally initialized.
/// Returns indices into the full parameter list (including non-pointer params).
fn get_conditional_init_param_indices(func_node: &Node, source: &str) -> HashSet<usize> {
    let mut result = HashSet::new();
    let body = match func_node.child_by_field_name("body") {
        Some(b) => b,
        None => return result,
    };

    // Collect all parameter names with their indices in the parameter list
    let mut all_params: Vec<(usize, String, bool)> = Vec::new(); // (index, name, is_pointer)
    collect_param_list_with_indices(func_node, source, &mut all_params);

    // Whether `node` is `*param_name` — a genuine pointer dereference of the
    // given parameter, matched against the pointer_expression's own operand
    // nodes rather than raw text, so a comment or string literal mentioning
    // "*param_name" can't fake a dereference that isn't actually there.
    let is_param_deref = |node: &Node, param_name: &str| {
        node.kind() == "pointer_expression"
            && node
                .child_by_field_name("operator")
                .is_some_and(|o| get_node_text(&o, source) == "*")
            && node.child_by_field_name("argument").is_some_and(|a| {
                a.kind() == "identifier" && get_node_text(&a, source) == param_name
            })
    };

    for (idx, param_name, is_pointer) in &all_params {
        if !is_pointer {
            continue;
        }

        // Cheap pre-filter: is the param dereferenced anywhere in the body at all?
        let derefs_param = query::find_descendants_of_kind(body, "pointer_expression")
            .iter()
            .any(|p| is_param_deref(p, param_name));
        if !derefs_param {
            continue; // Param not written through at all
        }

        // Precise check: does `*param = ...` appear as an assignment at
        // compound_statement top level (i.e. unconditionally, not nested
        // inside an `if`)?
        let has_unconditional_write =
            (0..body.child_count())
                .filter_map(|i| body.child(i))
                .any(|child| {
                    if child.kind() != "expression_statement" {
                        return false;
                    }
                    let Some(expr) = child.named_child(0) else {
                        return false;
                    };
                    expr.kind() == "assignment_expression"
                        && expr
                            .child_by_field_name("left")
                            .is_some_and(|left| is_param_deref(&left, param_name))
                });

        if !has_unconditional_write {
            result.insert(*idx);
        }
    }

    result
}

/// Collect all parameters with their indices, names, and whether they're pointers.
fn collect_param_list_with_indices(
    func_node: &Node,
    source: &str,
    params: &mut Vec<(usize, String, bool)>,
) {
    let declarator = match func_node.child_by_field_name("declarator") {
        Some(d) => d,
        None => return,
    };
    let func_decl = match find_function_declarator_node(&declarator) {
        Some(d) => d,
        None => return,
    };

    for i in 0..func_decl.child_count() {
        if let Some(child) = func_decl.child(i) {
            if child.kind() == "parameter_list" {
                let mut param_idx = 0;
                for j in 0..child.child_count() {
                    if let Some(param) = child.child(j) {
                        if param.kind() == "parameter_declaration" {
                            let param_text = get_node_text(&param, source);
                            let is_pointer = param_text.contains('*');
                            let name = get_declarator_name_from(&param, source);
                            if !name.is_empty() {
                                params.push((param_idx, name, is_pointer));
                            }
                            param_idx += 1;
                        }
                    }
                }
            }
        }
    }
}

fn find_function_declarator_node<'a>(node: &Node<'a>) -> Option<Node<'a>> {
    query::find_first_descendant(*node, |n| n.kind() == "function_declarator")
}

fn get_declarator_name_from(node: &Node, source: &str) -> String {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            if child.kind() == "identifier" {
                return get_node_text(&child, source).to_string();
            }
            if child.kind() == "pointer_declarator" {
                return get_declarator_name_from(&child, source);
            }
        }
    }
    String::new()
}

/// Walk down a field_expression / subscript_expression chain to find the root identifier.
/// e.g., arr->data → "arr", ptr->field[i] → "ptr"
fn extract_root_identifier(node: &Node, source: &str) -> String {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            if child.kind() == "identifier" {
                return get_node_text(&child, source).to_string();
            }
            if child.kind() == "field_expression" || child.kind() == "subscript_expression" {
                return extract_root_identifier(&child, source);
            }
        }
    }
    String::new()
}

fn get_func_name(declarator: &Node, source: &str) -> String {
    match declarator.kind() {
        "identifier" => get_node_text(declarator, source).to_string(),
        "function_declarator" | "pointer_declarator" => {
            if let Some(inner) = declarator.child_by_field_name("declarator") {
                get_func_name(&inner, source)
            } else {
                for i in 0..declarator.child_count() {
                    if let Some(child) = declarator.child(i) {
                        if child.kind() == "identifier" {
                            return get_node_text(&child, source).to_string();
                        }
                    }
                }
                String::new()
            }
        }
        _ => String::new(),
    }
}