aurora-lint 0.5.2

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
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
//! Textual expansion of function-like C macros — Phase 2 of the macro-expansion
//! plan (`docs/design/macro-expansion.md`).
//!
//! aurora-lint has no preprocessor, so function-like macro *invocations* are opaque to
//! dataflow. This module collects function-like macro *definitions* from the
//! parsed source (the prescan pre-pass crosses headers, so vendored/project
//! macros are visible) and expands an invocation on demand via token-aware
//! parameter substitution plus recursive rescanning (C11 6.10.3). Wiring the
//! expanded text into the CFG/dataflow is increment 2b; this module is the
//! engine + the collector, independently unit-tested.
//!
//! Out of scope (intentionally left unexpanded — safe, same as today):
//!   * macros using `#` (stringize) or `##` (token paste) — need real cpp
//!     semantics and are rare (<1% in the surveyed codebases);
//!   * variadic macros (`...` / `__VA_ARGS__`);
//!   * object-like macros — handled separately by `const_eval`.
//
// Increment 2a delivered the collector + engine. Increment 2b wired
// `collect_function_macros` into the prescan pre-pass / `ProjectContext` (so
// definitions are cached and available cross-file). The expander
// (`expand_invocation`) is consumed by the dataflow rules:
//   * 2c-ii — `macro_output_param_indices` feeds EXP33-C's read-checker and the
//     init-state transfer to recognize macro output arguments (`CF_DATA_SAVE`);
//   * 2c-iii — `macro_nulls_param_indices` feeds MEM30-C to recognize "safe
//     free" macros that free AND null their argument (`Curl_safefree`).

use super::dead_regions::DeadRegions;
use std::collections::{HashMap, HashSet};
use tree_sitter::Node;

/// A collected function-like macro definition.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FunctionMacro {
    /// Parameter names in order, e.g. `["x", "y"]`.
    pub params: Vec<String>,
    /// Raw replacement-list text, e.g. `(((x) < (y)) ? (x) : (y))`.
    pub body: String,
}

impl FunctionMacro {
    /// Whether two definitions expand every invocation identically: same
    /// arity and the same body once parameter names are replaced by their
    /// positions. `#define f(a, b)` and `#define f(x, y)` with empty bodies
    /// (mosquitto's `metrics__int_inc` stubs in two files) are the same
    /// macro, not a conflict.
    pub fn same_expansion(&self, other: &FunctionMacro) -> bool {
        self.params.len() == other.params.len() && self.positional_body() == other.positional_body()
    }

    fn positional_body(&self) -> String {
        let map: HashMap<String, String> = self
            .params
            .iter()
            .enumerate()
            .map(|(i, p)| (p.clone(), format!("__param{i}__")))
            .collect();
        substitute_params(&self.body, &map)
    }
}

/// Maximum recursive-rescan depth (defense against pathological input; real
/// macro nesting is shallow).
const MAX_EXPAND_DEPTH: usize = 32;

fn is_ident_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_'
}
fn is_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

/// Collect function-like macro definitions from a parsed translation unit.
/// Skips macros that use `#`/`##` or are variadic (left unexpanded downstream).
///
/// Two passes: (1) a precise AST pass over `preproc_function_def` nodes; (2) a
/// textual error-correcting pass over the raw source that recovers definitions
/// tree-sitter buried in `ERROR` recovery regions (e.g. curl's `curl_setup.h`,
/// 1480 lines of nested `#if`, where `#define curlx_free(ptr) …` is misparsed
/// as `ERROR(#define) + call_expression` and never emitted as a
/// `preproc_function_def`). The AST pass is authoritative; the textual pass only
/// fills names the AST missed (`or_insert`), so clean files are unaffected.
///
/// Both passes skip a definition inside a branch the assumed platform never
/// compiles ([`DeadRegions`], task 1142), so first-wins arbitrates only among
/// the definitions that could actually be live: hostap's `os.h` defines
/// `os_strdup(s)` as `_strdup(s)` under `_MSC_VER` and as `strdup(s)` in the
/// `#else`, and the Windows body used to win.
pub fn collect_function_macros(root: &Node, source: &str) -> HashMap<String, FunctionMacro> {
    let dead = DeadRegions::of(source);
    let mut out = HashMap::new();
    collect_rec(root, source, &dead, &mut out);
    for (name, m) in collect_function_macros_textual_outside(source, &dead) {
        out.entry(name).or_insert(m);
    }
    out
}

/// Secondary, error-correcting collector: scans raw source line-by-line for
/// function-like `#define NAME(params) body` directives. Because the C
/// preprocessor is line-oriented, this is immune to however tree-sitter mangles
/// the surrounding C in error-recovery regions. Applies the same exclusions as
/// the AST pass (`#`/`##`, variadic) so the expander sees a consistent set.
///
/// Sees every preprocessor branch; [`collect_function_macros`] is the entry
/// point that additionally drops platform-dead definitions.
#[cfg(test)]
pub fn collect_function_macros_textual(source: &str) -> HashMap<String, FunctionMacro> {
    collect_function_macros_textual_outside(source, &DeadRegions::default())
}

fn collect_function_macros_textual_outside(
    source: &str,
    dead: &DeadRegions,
) -> HashMap<String, FunctionMacro> {
    let lines: Vec<&str> = source.lines().collect();
    let mut out = HashMap::new();
    let mut i = 0;
    while i < lines.len() {
        let (logical, next) = join_continuation(&lines, i);
        // The directive's first physical line (1-based) decides which
        // preprocessor branch it belongs to.
        let first_line = i + 1;
        i = next;
        if dead.contains_line(first_line) {
            continue;
        }
        if let Some((name, m)) = parse_define_line(&logical) {
            // First definition wins (mirrors the AST pass): redefinitions across
            // `#ifdef` branches the platform profile cannot settle are
            // ambiguous, so keep the first.
            out.entry(name).or_insert(m);
        }
    }
    out
}

/// Every function-like definition found in `source`, keyed by macro name and
/// keeping **all** definitions of a name rather than only the first.
///
/// [`collect_function_macros`] deliberately keeps one body per name: an
/// expander has to pick a branch, and picking the first is as defensible as
/// any. A caller asking the different question "could a call to this macro
/// touch a variable named `x` in my scope?" cannot pick — the alternatives
/// live in mutually exclusive `#ifdef` branches, and the one that matters is
/// not usually the first. sqlite's `complete.c` is the shape: `IdChar(C)` is
/// defined twice, `#ifdef SQLITE_ASCII` as a pure table lookup and `#ifdef
/// SQLITE_EBCDIC` as `(((c=C)>=0x42 && …))`, which assigns and reads a
/// caller-scope `c`. Only the second definition explains the `unsigned char
/// c;` sitting under the matching `#ifdef` in the caller.
///
/// Textual scan only (no AST pass): the point here is coverage of every
/// preprocessor branch, and the line-oriented scanner already sees all of
/// them.
pub fn collect_function_macro_alternatives(source: &str) -> HashMap<String, Vec<FunctionMacro>> {
    let lines: Vec<&str> = source.lines().collect();
    let mut out: HashMap<String, Vec<FunctionMacro>> = HashMap::new();
    let mut i = 0;
    while i < lines.len() {
        let (logical, next) = join_continuation(&lines, i);
        i = next;
        if let Some((name, m)) = parse_define_line(&logical) {
            let alts = out.entry(name).or_default();
            if !alts.contains(&m) {
                alts.push(m);
            }
        }
    }
    out
}

/// One occurrence of a free identifier in a macro's replacement list.
struct FreeIdentOccurrence {
    name: String,
    /// The occurrence is the left operand of a *simple* assignment (`=`,
    /// not `==`/`+=`/`<=`), so it writes the caller's variable without
    /// reading it.
    is_write: bool,
}

/// Every occurrence of a *free* identifier in `m`'s replacement list — one
/// that is not among the macro's own parameters, and so binds to whatever
/// that name means at the call site.
///
/// This is C semantics, not a heuristic: a macro is textual substitution, so
/// a free `c` in the replacement list really does read (or write) the `c` in
/// scope where the macro is invoked. Identifiers are matched whole-token, so
/// `c` does not match `cnt` or `pc`.
///
/// Two positions are excluded because the token there is not a variable
/// reference at all and so cannot bind to a same-named local at the call
/// site (task 966):
///
///   - after `.` or `->`, where it names a struct member. curl's
///     `CONN_IS_PROXIED(x)` → `(x)->bits.proxy` does not touch a caller's
///     `char *proxy`.
///   - as the type of a cast. seL4's `pptr_of_cap(cap)` →
///     `((pptr_t)cap_get_capPtr(cap))` does not touch anything named
///     `pptr_t`.
///
/// Matching either would report a read the macro never performs, which for
/// MSC13-C means silently suppressing a real finding.
fn free_identifier_occurrences(m: &FunctionMacro) -> Vec<FreeIdentOccurrence> {
    let chars: Vec<char> = m.body.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        if !is_ident_start(chars[i]) {
            i += 1;
            continue;
        }
        let start = i;
        while i < chars.len() && is_ident_char(chars[i]) {
            i += 1;
        }
        let tok: String = chars[start..i].iter().collect();
        if m.params.contains(&tok) {
            continue;
        }
        if follows_member_access(&chars, start) || is_cast_type_position(&chars, start, i) {
            continue;
        }
        out.push(FreeIdentOccurrence {
            name: tok,
            is_write: is_simple_assignment_target(&chars, i),
        });
    }
    out
}

/// Index of the last non-whitespace character before `at`, if any.
fn prev_non_space(chars: &[char], at: usize) -> Option<usize> {
    chars[..at].iter().rposition(|c| !c.is_whitespace())
}

/// Index of the first non-whitespace character at or after `from`, if any.
fn next_non_space(chars: &[char], from: usize) -> Option<usize> {
    chars[from..]
        .iter()
        .position(|c| !c.is_whitespace())
        .map(|off| from + off)
}

/// True if the token starting at `start` is preceded by `.` or `->`, i.e. it
/// names a struct member (or a designated initializer's field) rather than a
/// variable.
fn follows_member_access(chars: &[char], start: usize) -> bool {
    let Some(p) = prev_non_space(chars, start) else {
        return false;
    };
    if chars[p] == '>' {
        return p > 0 && chars[p - 1] == '-';
    }
    // A `.` here is member access, not a float: `1.foo` is not C, and a
    // float's fractional part never begins with an identifier character.
    chars[p] == '.'
}

/// True if the token spanning `start..end` is the type in a cast: it is the
/// entire content of a parenthesised group, and something a cast can apply
/// to follows the closing paren.
///
/// Deliberately tight. Widening it would drop genuine free identifiers,
/// which is the opposite error — an unseen read reported as a dead store.
fn is_cast_type_position(chars: &[char], start: usize, end: usize) -> bool {
    let Some(open) = prev_non_space(chars, start) else {
        return false;
    };
    if chars[open] != '(' {
        return false;
    }
    let Some(close) = next_non_space(chars, end) else {
        return false;
    };
    if chars[close] != ')' {
        return false;
    }
    let Some(after) = next_non_space(chars, close + 1) else {
        return false;
    };
    // `*` and `&` are deliberately absent: `(T)*p` and `(T)&x` are casts,
    // but `(a) * (b)` and `(a) & (b)` are multiplication and bitwise-and,
    // and in a macro body the operators are far commoner than the casts.
    // Treating those as casts would drop a genuine free identifier, so the
    // ambiguity resolves toward keeping it.
    let c = chars[after];
    is_ident_start(c) || c.is_ascii_digit() || matches!(c, '(' | '~' | '!')
}

/// True if the token ending at `end` is the left operand of a simple
/// assignment: the next non-whitespace character is `=`, and it is neither
/// half of a comparison (`==`, `<=`, `>=`, `!=`) nor a compound assignment
/// (`+=`, `&=`, …), both of which read the old value.
fn is_simple_assignment_target(chars: &[char], end: usize) -> bool {
    let Some(eq) = next_non_space(chars, end) else {
        return false;
    };
    if chars[eq] != '=' {
        return false;
    }
    if chars.get(eq + 1) == Some(&'=') {
        return false;
    }
    // A compound-assignment operator's first character sits immediately
    // before the `=`, with no space (`x += 1`, never `x + = 1`).
    !matches!(
        chars.get(eq.wrapping_sub(1)),
        Some('=')
            | Some('!')
            | Some('<')
            | Some('>')
            | Some('+')
            | Some('-')
            | Some('*')
            | Some('/')
            | Some('%')
            | Some('&')
            | Some('|')
            | Some('^')
    )
}

/// True if `m`'s replacement list mentions `var` as a *free* identifier —
/// one that is not one of the macro's own parameters, and so binds to
/// whatever `var` names at the call site. Write occurrences count: for the
/// "is this variable used at all" question a write through a macro is still
/// a use of the caller's variable.
pub fn macro_references_free_identifier(m: &FunctionMacro, var: &str) -> bool {
    if var.is_empty() || m.params.iter().any(|p| p == var) {
        return false;
    }
    free_identifier_occurrences(m)
        .iter()
        .any(|occ| occ.name == var)
}

/// The free identifiers in `m`'s replacement list that the macro actually
/// *reads*: every one except those appearing only as the left operand of a
/// simple assignment.
///
/// The distinction matters for liveness (task 965). Only a read makes a
/// previously-active definition live, so a macro that assigns to a
/// caller-scope variable and never reads it must not resurrect a genuinely
/// dead store — mosquitto's
/// `#define read_e(f, b, c) if(fread(b,1,c,f) != c){ rc = MOSQ_ERR_UNKNOWN; goto error; }`
/// only ever writes `rc`, so the caller's `int rc = MOSQ_ERR_UNKNOWN;` really
/// is dead and counting the macro's `rc` as a read would suppress a true
/// positive.
///
/// The unused-variable question is different and keeps taking the union:
/// a variable a macro only writes is still *used*.
pub fn macro_free_identifier_reads(m: &FunctionMacro) -> HashSet<String> {
    free_identifier_occurrences(m)
        .into_iter()
        .filter(|occ| !occ.is_write)
        .map(|occ| occ.name)
        .collect()
}

/// Join a backslash-continued logical line starting at `start`. Returns the
/// spliced text (continuation backslashes removed, joined with a space) and the
/// index of the next unconsumed physical line.
fn join_continuation(lines: &[&str], start: usize) -> (String, usize) {
    let mut buf = String::new();
    let mut i = start;
    while i < lines.len() {
        let line = lines[i];
        let te = line.trim_end();
        if let Some(stripped) = te.strip_suffix('\\') {
            buf.push_str(stripped);
            buf.push(' ');
            i += 1;
        } else {
            buf.push_str(line);
            i += 1;
            break;
        }
    }
    (buf, i)
}

/// Why the collector left a function-like `#define` out of the expansion
/// table. Every invocation of such a macro stays opaque to dataflow, which
/// is exactly what `--report-macro-gaps` exists to surface (task 1180); the
/// variants are the module-doc "out of scope" list, one per reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum DefineSkip {
    /// `#define M(a, ...)` — variadic; `__VA_ARGS__` needs real cpp semantics.
    Variadic,
    /// The replacement list uses `#` (stringize) or `##` (token paste).
    PasteOrStringize,
    /// The parameter list never closes on its logical line.
    Malformed,
}

impl DefineSkip {
    /// One-line explanation for a report.
    pub fn describe(self) -> &'static str {
        match self {
            DefineSkip::Variadic => "variadic macro (`...`/`__VA_ARGS__`) — not expanded",
            DefineSkip::PasteOrStringize => {
                "uses `#` (stringize) or `##` (token paste) — not expanded"
            }
            DefineSkip::Malformed => "parameter list never closes — not expanded",
        }
    }
}

/// One function-like `#define` as the line-oriented scanner saw it, before
/// any platform-dead filtering: the name, its first physical line (1-based),
/// and either the definition the expander would use or why it was skipped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScannedDefine {
    /// The macro name.
    pub name: String,
    /// First physical line of the directive, 1-based.
    pub line: usize,
    /// The definition the expander would hold, or why it holds none.
    pub outcome: Result<FunctionMacro, DefineSkip>,
}

/// Every function-like `#define` in `source`, in file order, across every
/// preprocessor branch, with the collector's own accept/skip verdict on each.
///
/// This is the same line scan [`collect_function_macros`] runs; it differs
/// only in keeping the skipped definitions and their reasons, so a report can
/// say "this macro exists but the engine will never expand it" from the same
/// decision the engine actually made, rather than from a second heuristic.
pub fn scan_function_macro_defines(source: &str) -> Vec<ScannedDefine> {
    let lines: Vec<&str> = source.lines().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        let (logical, next) = join_continuation(&lines, i);
        let line = i + 1;
        i = next;
        if let Some((name, outcome)) = classify_define_line(&logical) {
            out.push(ScannedDefine {
                name,
                line,
                outcome,
            });
        }
    }
    out
}

/// Parse one logical line as a function-like `#define`. Returns `None` for
/// non-directives, object-like macros, variadic macros, and macros using
/// `#`/`##`.
fn parse_define_line(line: &str) -> Option<(String, FunctionMacro)> {
    let (name, outcome) = classify_define_line(line)?;
    outcome.ok().map(|m| (name, m))
}

/// Recognize one logical line as a function-like `#define`, returning the
/// macro name and either its definition or the reason the collector skips
/// it. `None` means the line is not a function-like `#define` at all
/// (non-directive, or object-like — `#define NAME (x)` with a space is an
/// object-like macro whose body is `(x)`).
fn classify_define_line(line: &str) -> Option<(String, Result<FunctionMacro, DefineSkip>)> {
    let s = line.trim_start();
    let s = s.strip_prefix('#')?;
    let s = s.trim_start().strip_prefix("define")?;
    // `define` must be a whole token (followed by whitespace), not a prefix
    // like `defined` or `definex`.
    if !s.starts_with(|c: char| c.is_whitespace()) {
        return None;
    }
    let s = s.trim_start();

    // Macro name.
    let chars: Vec<char> = s.chars().collect();
    if chars.is_empty() || !is_ident_start(chars[0]) {
        return None;
    }
    let mut k = 0;
    while k < chars.len() && is_ident_char(chars[k]) {
        k += 1;
    }
    let name: String = chars[..k].iter().collect();

    // Function-like requires '(' *immediately* after the name (no whitespace);
    // `#define NAME (x)` is object-like with body `(x)`.
    if k >= chars.len() || chars[k] != '(' {
        return None;
    }

    // Parse parameter list up to the matching ')'.
    let (params, body_start) = match parse_param_list(&chars, k) {
        Ok(v) => v,
        Err(skip) => return Some((name, Err(skip))),
    };
    let body_raw: String = chars[body_start..].iter().collect();
    let body = strip_comments(&body_raw).trim().to_string();

    if body_uses_paste_or_stringize(&body) {
        return Some((name, Err(DefineSkip::PasteOrStringize)));
    }
    Some((name, Ok(FunctionMacro { params, body })))
}

/// Parse `(p1, p2, …)` starting at `open` (an index of `'('`). Returns the
/// parameter names and the index just past the closing `')'`, or the reason
/// the list cannot be used: variadic (`...`) or never closed.
fn parse_param_list(chars: &[char], open: usize) -> Result<(Vec<String>, usize), DefineSkip> {
    debug_assert_eq!(chars[open], '(');
    let mut params = Vec::new();
    let mut cur = String::new();
    let mut i = open + 1;
    let mut depth = 1i32;
    while i < chars.len() {
        match chars[i] {
            '(' => {
                depth += 1;
                cur.push('(');
            }
            ')' => {
                depth -= 1;
                if depth == 0 {
                    let t = cur.trim();
                    if !t.is_empty() {
                        params.push(t.to_string());
                    }
                    // Variadic param → unsupported.
                    if params.iter().any(|p| p.contains("...")) {
                        return Err(DefineSkip::Variadic);
                    }
                    return Ok((params, i + 1));
                }
                cur.push(')');
            }
            ',' if depth == 1 => {
                params.push(cur.trim().to_string());
                cur.clear();
            }
            c => cur.push(c),
        }
        i += 1;
    }
    Err(DefineSkip::Malformed) // unbalanced
}

/// Remove `/* … */` and `// …` comments from a macro replacement list, so the
/// textual body matches what the AST pass's `preproc_arg` yields.
fn strip_comments(s: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
            i += 2;
            while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
                i += 1;
            }
            i += 2;
            out.push(' ');
        } else if chars[i] == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
            break;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    out
}

fn collect_rec(
    node: &Node,
    source: &str,
    dead: &DeadRegions,
    out: &mut HashMap<String, FunctionMacro>,
) {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            match child.kind() {
                "preproc_function_def" => {
                    if dead.contains_node(&child) {
                        continue;
                    }
                    if let Some((name, m)) = parse_function_def(&child, source) {
                        // First definition wins; redefinitions under a
                        // build-config `#ifdef` the platform profile cannot
                        // settle are ambiguous, so keep the first.
                        out.entry(name).or_insert(m);
                    }
                }
                kind if kind.starts_with("preproc_") => collect_rec(&child, source, dead, out),
                _ => {}
            }
        }
    }
}

fn parse_function_def(node: &Node, source: &str) -> Option<(String, FunctionMacro)> {
    let name = node
        .child_by_field_name("name")?
        .utf8_text(source.as_bytes())
        .ok()?
        .to_string();

    let params_node = node.child_by_field_name("parameters")?;
    let mut params = Vec::new();
    for i in 0..params_node.child_count() {
        if let Some(p) = params_node.child(i) {
            match p.kind() {
                "identifier" => params.push(p.utf8_text(source.as_bytes()).ok()?.to_string()),
                // variadic param: bail (unsupported)
                "..." => return None,
                _ => {}
            }
        }
    }

    let body = node
        .child_by_field_name("value")
        .and_then(|v| v.utf8_text(source.as_bytes()).ok())
        .unwrap_or("")
        .trim()
        .to_string();

    // Skip stringize / token-paste — require real preprocessor semantics.
    if body_uses_paste_or_stringize(&body) {
        return None;
    }

    Some((name, FunctionMacro { params, body }))
}

/// Detect `#`/`##` operators in a replacement list, ignoring occurrences inside
/// string/char literals.
fn body_uses_paste_or_stringize(body: &str) -> bool {
    let bytes: Vec<char> = body.chars().collect();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            '"' | '\'' => {
                let quote = bytes[i];
                i += 1;
                while i < bytes.len() && bytes[i] != quote {
                    if bytes[i] == '\\' {
                        i += 1;
                    }
                    i += 1;
                }
                i += 1;
            }
            '#' => return true,
            _ => i += 1,
        }
    }
    false
}

/// Expand a single function-like macro invocation `name(args...)` using `table`,
/// recursively rescanning the result. Returns `None` if `name` is not a known
/// function-like macro or the argument count does not match the parameters.
pub fn expand_invocation(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
    args: &[String],
) -> Option<String> {
    let mut active = HashSet::new();
    expand_named(table, name, args, &mut active, 0)
}

fn expand_named(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
    args: &[String],
    active: &mut HashSet<String>,
    depth: usize,
) -> Option<String> {
    if depth >= MAX_EXPAND_DEPTH || active.contains(name) {
        return None;
    }
    let m = table.get(name)?;
    if m.params.len() != args.len() {
        return None; // arity mismatch — do not expand
    }
    let mut map = HashMap::new();
    for (p, a) in m.params.iter().zip(args.iter()) {
        map.insert(p.clone(), a.clone());
    }
    let substituted = substitute_params(&m.body, &map);
    active.insert(name.to_string());
    let rescanned = rescan(table, &substituted, active, depth + 1);
    active.remove(name);
    Some(rescanned)
}

/// Replace whole-identifier occurrences of parameter names in `body` with their
/// argument text. Skips identifiers inside string/char literals.
fn substitute_params(body: &str, map: &HashMap<String, String>) -> String {
    let chars: Vec<char> = body.chars().collect();
    let mut out = String::with_capacity(body.len());
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '"' || c == '\'' {
            let quote = c;
            out.push(c);
            i += 1;
            while i < chars.len() {
                out.push(chars[i]);
                if chars[i] == '\\' && i + 1 < chars.len() {
                    out.push(chars[i + 1]);
                    i += 2;
                    continue;
                }
                if chars[i] == quote {
                    i += 1;
                    break;
                }
                i += 1;
            }
        } else if is_ident_start(c) {
            let start = i;
            while i < chars.len() && is_ident_char(chars[i]) {
                i += 1;
            }
            let ident: String = chars[start..i].iter().collect();
            if let Some(repl) = map.get(&ident) {
                out.push_str(repl);
            } else {
                out.push_str(&ident);
            }
        } else {
            out.push(c);
            i += 1;
        }
    }
    out
}

/// Rescan expanded text, expanding any further function-like macro invocations.
fn rescan(
    table: &HashMap<String, FunctionMacro>,
    text: &str,
    active: &mut HashSet<String>,
    depth: usize,
) -> String {
    if depth >= MAX_EXPAND_DEPTH {
        return text.to_string();
    }
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '"' || c == '\'' {
            let quote = c;
            out.push(c);
            i += 1;
            while i < chars.len() {
                out.push(chars[i]);
                if chars[i] == '\\' && i + 1 < chars.len() {
                    out.push(chars[i + 1]);
                    i += 2;
                    continue;
                }
                if chars[i] == quote {
                    i += 1;
                    break;
                }
                i += 1;
            }
        } else if is_ident_start(c) {
            let start = i;
            while i < chars.len() && is_ident_char(chars[i]) {
                i += 1;
            }
            let ident: String = chars[start..i].iter().collect();
            // Is this a function-like macro invocation? Look for a '(' after
            // optional whitespace.
            let mut j = i;
            while j < chars.len() && chars[j].is_whitespace() {
                j += 1;
            }
            if table.contains_key(&ident)
                && !active.contains(&ident)
                && j < chars.len()
                && chars[j] == '('
            {
                if let Some((args, end)) = parse_call_args(&chars, j) {
                    if let Some(expanded) = expand_named(table, &ident, &args, active, depth) {
                        out.push_str(&expanded);
                        i = end;
                        continue;
                    }
                }
            }
            out.push_str(&ident);
        } else {
            out.push(c);
            i += 1;
        }
    }
    out
}

/// Parse a parenthesized, comma-separated argument list starting at `open`
/// (which must index a `'('`). Returns the argument texts (trimmed) and the
/// index just past the closing `')'`. Respects nested parens/brackets/braces
/// and string/char literals.
pub(crate) fn parse_call_args(chars: &[char], open: usize) -> Option<(Vec<String>, usize)> {
    debug_assert_eq!(chars[open], '(');
    let mut args = Vec::new();
    let mut cur = String::new();
    let mut depth = 0i32;
    let mut i = open;
    while i < chars.len() {
        let c = chars[i];
        match c {
            '"' | '\'' => {
                let quote = c;
                cur.push(c);
                i += 1;
                while i < chars.len() {
                    cur.push(chars[i]);
                    if chars[i] == '\\' && i + 1 < chars.len() {
                        cur.push(chars[i + 1]);
                        i += 2;
                        continue;
                    }
                    if chars[i] == quote {
                        i += 1;
                        break;
                    }
                    i += 1;
                }
            }
            '(' | '[' | '{' => {
                depth += 1;
                if depth > 1 {
                    cur.push(c);
                }
                i += 1;
            }
            ')' | ']' | '}' => {
                depth -= 1;
                if depth == 0 {
                    // end of arg list
                    let trimmed = cur.trim();
                    // An empty `()` call has zero args, not one empty arg.
                    if !(args.is_empty() && trimmed.is_empty()) {
                        args.push(trimmed.to_string());
                    }
                    return Some((args, i + 1));
                }
                cur.push(c);
                i += 1;
            }
            ',' if depth == 1 => {
                args.push(cur.trim().to_string());
                cur.clear();
                i += 1;
            }
            _ => {
                cur.push(c);
                i += 1;
            }
        }
    }
    None // unbalanced
}

/// Parameter indices that a function-like macro *writes* — i.e. the macro body
/// assigns to the (whole) parameter, directly or after expanding nested macros
/// drawn from `table`. Such positions are macro **output arguments**: a
/// bare-identifier argument there is being written by the macro, not read, so it
/// is not a use of uninitialized memory and is initialized afterwards.
///
/// Example: curl's `CF_DATA_SAVE(save, cf, data)` expands to
/// `do { (save) = …; … } while(0)`, so index 0 (`save`) is an output. The other
/// args (`cf`, `data`) only appear as reads, so they are not outputs.
///
/// Detection is deliberately conservative — only *whole-object* assignment
/// (`(param) = …`) counts. Field/element/deref writes (`param->f = …`,
/// `param[i] = …`, `*param = …`) read `param` first and so are NOT outputs.
pub fn macro_output_param_indices(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
) -> Vec<usize> {
    let m = match table.get(name) {
        Some(m) => m,
        None => return Vec::new(),
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    // Substitute each parameter with a unique sentinel, then fully expand (so
    // nested macros from the same body — `CF_CTX_CALL_DATA`, `CURL_UNCONST` —
    // resolve and we see the real lvalue context of each parameter).
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MOUT_{i}__"))
        .collect();
    let expanded = match expand_invocation(table, name, &sentinels) {
        Some(e) => e,
        None => return Vec::new(),
    };
    let mut out = Vec::new();
    for (i, sent) in sentinels.iter().enumerate() {
        if is_whole_assignment_target(&expanded, sent) {
            out.push(i);
        }
    }
    out
}

/// True if a function-like macro's replacement list begins with a `case`
/// label — e.g. sqlite's `#define CASE(i,str) case i: assert(...);`, invoked
/// as `CASE(0, "xColumnCount") { ... }`. Tree-sitter parses the invocation as
/// an ordinary `call_expression` (the real `case` label is hidden inside the
/// macro body it can't see), so a switch-statement structural check walking
/// the AST directly would misread the invocation as a plain statement
/// preceding the first visible label. Callers use this to recognize such an
/// invocation as itself being the case label.
///
/// No parameter substitution is needed: the leading `case` token is a literal
/// keyword in the replacement list, never a parameter, so it is visible
/// before expansion.
pub fn macro_expands_to_case_label(table: &HashMap<String, FunctionMacro>, name: &str) -> bool {
    let m = match table.get(name) {
        Some(m) => m,
        None => return false,
    };
    let body = m.body.trim_start();
    match body.strip_prefix("case") {
        Some(rest) => !rest.starts_with(|c: char| is_ident_char(c)),
        None => false,
    }
}

/// Parameter indices that a function-like macro frees-and-nulls: the body
/// assigns the (whole) parameter the null pointer constant (`(param) = NULL`),
/// directly or after expanding nested macros from `table`. This is the
/// "safe free" idiom — curl `Curl_safefree(ptr)` expands to
/// `do { curlx_free(ptr); (ptr) = NULL; } while(0)`, so index 0 is reported.
///
/// MEM30-C already treats such macros as a free (the name contains `FREE`), but
/// cannot see the `= NULL`; consuming this list lets it clear the argument's
/// freed state — exactly as if the caller had written `free(p); p = NULL;` —
/// removing use-after-free / double-free false positives on safe-free wrappers.
/// (mosquitto `mosquitto_FREE`, `SAFE_FREE` share the idiom — engine, not
/// allowlist.)
pub fn macro_nulls_param_indices(table: &HashMap<String, FunctionMacro>, name: &str) -> Vec<usize> {
    let m = match table.get(name) {
        Some(m) => m,
        None => return Vec::new(),
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MNULL_{i}__"))
        .collect();
    let expanded = match expand_invocation(table, name, &sentinels) {
        Some(e) => e,
        None => return Vec::new(),
    };
    let mut out = Vec::new();
    for (i, sent) in sentinels.iter().enumerate() {
        if is_null_assignment_target(&expanded, sent) {
            out.push(i);
        }
    }
    out
}

/// Parameter indices that a function-like macro **writes through**: either a
/// whole-object assignment (`(param) = …`, same as
/// [`macro_output_param_indices`]), a whole-object read-modify-write
/// (`param += …`, `param ^= …`, `param++` — [`is_compound_assignment_target`];
/// pure-ftpd's `CHACHA20_QUARTERROUND(A,B,C,D)` touches `A` and `C` only this
/// way, task 1254), or a write through the pointer/array itself
/// — `param->field = …`, `param[i] = …`, `*param = …`. The latter forms are
/// deliberately *excluded* from `macro_output_param_indices` because they
/// presuppose `param` already holds a valid address (relevant to EXP33-C's
/// uninitialized-*scalar* question), but they are exactly what EXP34-C
/// (null-pointer) and ARR00-C (array-bounds) care about: successfully writing
/// through `param` proves it was non-null / in-bounds, the same idiom
/// `function_summary.rs::modifies_params` tracks for real (non-macro)
/// functions via `line_has_arrow_or_subscript_write`.
///
/// Example: sqlite's `fts3GetVarint32(p, piVal)` expands with a deref write
/// `*piVal = *(u8*)(p)`, so index 1 (`piVal`) is reported.
pub fn macro_writes_param_indices(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
) -> Vec<usize> {
    let m = match table.get(name) {
        Some(m) => m,
        None => return Vec::new(),
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MWR_{i}__"))
        .collect();
    let expanded = match expand_invocation(table, name, &sentinels) {
        Some(e) => e,
        None => return Vec::new(),
    };
    let mut out = Vec::new();
    for (i, sent) in sentinels.iter().enumerate() {
        if is_whole_assignment_target(&expanded, sent)
            || is_compound_assignment_target(&expanded, sent)
            || writes_through_pointer(&expanded, sent)
        {
            out.push(i);
        }
    }
    out
}

/// True if `ident` is written through a pointer/array access in `text`:
/// `ident->field = …`, `ident[i] = …`, or a dereference write `*ident = …` /
/// `*(ident) = …`. Mirrors `function_summary.rs::line_has_arrow_or_subscript_write`
/// (arrow/subscript half) plus a deref-write check for the `*ident =` form,
/// which real-function analysis doesn't need separately (a function body's
/// `*param = x` is textually indistinguishable from other dereferences there,
/// but here we search the fully-expanded, sentinel-substituted macro body so
/// a direct char scan is precise). See [`macro_writes_param_indices`].
fn writes_through_pointer(text: &str, ident: &str) -> bool {
    let chars: Vec<char> = text.chars().collect();
    let id: Vec<char> = ident.chars().collect();
    let (n, m) = (chars.len(), id.len());
    if m == 0 {
        return false;
    }
    let mut i = 0;
    while i + m <= n {
        if chars[i..i + m] == id[..] {
            let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
            let next_ok = i + m >= n || !is_ident_char(chars[i + m]);
            if prev_ok && next_ok {
                // Arrow/subscript write: skip wrapping `)`/whitespace after the
                // identifier (handles `(ident)->f` / `(ident)[0]`), then check
                // for `->`/`[` followed eventually by a genuine `=`.
                let mut j = i + m;
                while j < n && (chars[j].is_whitespace() || chars[j] == ')') {
                    j += 1;
                }
                let is_arrow = j + 1 < n && chars[j] == '-' && chars[j + 1] == '>';
                let is_subscript = j < n && chars[j] == '[';
                if is_arrow || is_subscript {
                    if let Some(eq_pos) = find_genuine_eq_after(&chars, j) {
                        let _ = eq_pos;
                        return true;
                    }
                }
                // Deref write: `*ident =` or `*(ident) =` (wrapping parens
                // between the `*` and the identifier).
                let mut b = i;
                while b > 0 && (chars[b - 1].is_whitespace() || chars[b - 1] == '(') {
                    b -= 1;
                }
                if b > 0 && chars[b - 1] == '*' {
                    let mut k = i + m;
                    while k < n && (chars[k].is_whitespace() || chars[k] == ')') {
                        k += 1;
                    }
                    if k < n && chars[k] == '=' && (k + 1 >= n || chars[k + 1] != '=') {
                        return true;
                    }
                }
            }
        }
        i += 1;
    }
    false
}

/// Starting from `from` (index of `-`/`[`), find the next genuine assignment
/// `=` (excluding `==`/`!=`/`<=`/`>=`) at or after this access, returning its
/// index. Bounded to the same textual "access chain" by simply scanning
/// forward — good enough for the short, sentinel-substituted macro bodies
/// this operates on.
fn find_genuine_eq_after(chars: &[char], from: usize) -> Option<usize> {
    let n = chars.len();
    let mut search_from = from;
    while search_from < n {
        if chars[search_from] == '=' {
            let before = if search_from > 0 {
                chars[search_from - 1]
            } else {
                ' '
            };
            let after = if search_from + 1 < n {
                chars[search_from + 1]
            } else {
                ' '
            };
            let is_comparison =
                before == '!' || before == '<' || before == '>' || before == '=' || after == '=';
            if !is_comparison {
                return Some(search_from);
            }
        }
        search_from += 1;
    }
    None
}

/// A "pure forwarding" macro: one whose entire body is a single call to
/// another (real, non-macro) function, passing each of its own parameters
/// through -- verbatim or wrapped in casts/parens -- as call arguments,
/// possibly interleaved with extra literal arguments the macro adds itself.
/// curl's `#define Curl_rand(a, b, c) Curl_rand_bytes(a, TRUE, b, c)` is the
/// motivating case (task 589): the macro's own body has no assignment for
/// [`macro_output_param_indices`] to see, but the forwarded function
/// (`Curl_rand_bytes`) genuinely writes through one of those args, per its
/// `FunctionSummary::modifies_params`. Callers resolve output-param indices
/// for a forwarding macro by mapping the forwarded function's
/// `modifies_params` (callee-argument-position-indexed) back through
/// `param_map` to the macro's own parameter indices.
///
/// Returns `(forwarded_function_name, param_map)` where `param_map[i]` is
/// `Some(j)` when the callee's `i`-th argument is (after stripping
/// casts/grouping parens) exactly the macro's `j`-th own parameter,
/// unmodified -- and `None` when that argument position is something else
/// (a literal, an expression combining/transforming params, etc). This is
/// deliberately conservative: a macro that recombines or drops a parameter
/// before forwarding does not get positional credit for that argument, so a
/// caller can never misattribute a write to the wrong macro parameter.
pub fn macro_forwarding_target(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
) -> Option<(String, Vec<Option<usize>>)> {
    let m = table.get(name)?;
    if m.params.is_empty() {
        return None;
    }
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MFWD_{i}__"))
        .collect();
    let expanded = expand_invocation(table, name, &sentinels)?;
    let body = expanded.trim().trim_end_matches(';').trim();

    // Must be exactly one call expression: NAME(args), nothing else around it.
    let open = body.find('(')?;
    if !body.ends_with(')') {
        return None;
    }
    let callee = body[..open].trim();
    if callee.is_empty()
        || !callee.starts_with(is_ident_start)
        || !callee.chars().all(is_ident_char)
    {
        return None;
    }
    // Refuse chains into another macro -- callers resolve one hop via a real
    // FunctionSummary, not another expansion.
    if table.contains_key(callee) {
        return None;
    }

    let args_text = &body[open + 1..body.len() - 1];
    let args = split_top_level_commas(args_text);
    let param_map = args
        .iter()
        .map(|arg| {
            let unwrapped = unwrap_cast_and_parens(arg.trim());
            sentinels.iter().position(|s| s == unwrapped)
        })
        .collect();
    Some((callee.to_string(), param_map))
}

/// Split `text` on top-level commas (depth 0 parens), trimming nothing --
/// callers trim each piece themselves. Empty input yields an empty `Vec`
/// (zero arguments), matching a niladic call `f()`.
fn split_top_level_commas(text: &str) -> Vec<&str> {
    if text.trim().is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    let bytes = text.as_bytes();
    let mut depth = 0i32;
    let mut start = 0usize;
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'(' | b'[' => depth += 1,
            b')' | b']' => depth -= 1,
            b',' if depth == 0 => {
                out.push(&text[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    out.push(&text[start..]);
    out
}

/// Strip outer grouping parens and cast expressions from `s`, repeatedly:
/// `(rnd)` -> `rnd`, `(unsigned char *)rnd` -> `rnd`,
/// `((unsigned char *)(rnd))` -> `rnd`. Anything else (an operator, a
/// function call, more than one token left after stripping a leading
/// parenthesized group) is left as-is, since it can no longer be a bare
/// parameter reference.
fn unwrap_cast_and_parens(s: &str) -> &str {
    let mut s = s.trim();
    if !s.is_ascii() {
        // Byte offsets below are computed over `chars()`; only valid to
        // slice `s` with them when every char is one byte. Non-ASCII text
        // in this position is not a bare parameter reference anyway.
        return s;
    }
    loop {
        if !s.starts_with('(') {
            return s;
        }
        let chars: Vec<char> = s.chars().collect();
        let mut depth = 0i32;
        let mut close = None;
        for (i, &c) in chars.iter().enumerate() {
            match c {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        close = Some(i);
                        break;
                    }
                }
                _ => {}
            }
        }
        let Some(close) = close else { return s };
        if close == chars.len() - 1 {
            // The whole string is one parenthesized group: `(rnd)`.
            s = s[1..s.len() - 1].trim();
        } else {
            // A leading group followed by more text: a cast, `(T)rest`.
            let rest = s[close + 1..].trim();
            if rest.is_empty() {
                return s;
            }
            s = rest;
        }
    }
}

/// Deallocation functions recognized by [`macro_frees_param_indices`].
const DEALLOC_FUNCTIONS: &[&str] = &["free", "fclose", "close"];

/// Parameter indices that a function-like macro releases: the body calls one
/// of `free`/`fclose`/`close` with the (possibly wrapped) parameter as an
/// argument, directly or after expanding nested macros from `table`. Unlike
/// [`macro_nulls_param_indices`] this does not require the macro to also null
/// the pointer — callers that only need to know the resource was released
/// (e.g. MEM12-C's early-return leak check) don't need the null-clearing
/// signal.
pub fn macro_frees_param_indices(table: &HashMap<String, FunctionMacro>, name: &str) -> Vec<usize> {
    let m = match table.get(name) {
        Some(m) => m,
        None => return Vec::new(),
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MFREE_{i}__"))
        .collect();
    let expanded = match expand_invocation(table, name, &sentinels) {
        Some(e) => e,
        None => return Vec::new(),
    };
    let mut out = Vec::new();
    for (i, sent) in sentinels.iter().enumerate() {
        if calls_dealloc_fn_with_arg(&expanded, sent) {
            out.push(i);
        }
    }
    out
}

/// Parameter indices a function-like macro clears: after expansion the body
/// calls one of `call_roles::MEMORY_CLEARING_FUNCS` with the (possibly
/// wrapped) parameter as the FIRST argument -- the destination. hostap's
/// `#define os_memset(s, c, n) memset(s, c, n)` is this shape; MEM03-C
/// credits its callers with the clear the same way it credits a wrapper
/// function's (task 1127).
pub fn macro_clears_param_indices(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
) -> Vec<usize> {
    let m = match table.get(name) {
        Some(m) => m,
        None => return Vec::new(),
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MCLEAR_{i}__"))
        .collect();
    let expanded = match expand_invocation(table, name, &sentinels) {
        Some(e) => e,
        None => return Vec::new(),
    };
    let mut out = Vec::new();
    for (i, sent) in sentinels.iter().enumerate() {
        if calls_fn_with_arg(
            &expanded,
            crate::utility::cert_c::call_roles::MEMORY_CLEARING_FUNCS,
            sent,
            true,
        ) {
            out.push(i);
        }
    }
    out
}

/// Parameter indices a function-like macro hands to a callee `releases`
/// accepts, as an argument at any position. The fixed-list form
/// ([`macro_frees_param_indices`]) knows `free`/`fclose`/`close` by
/// spelling, which misses a project's own: curl's `Curl_safefree(ptr)`
/// frees through `curlx_free`, and `mosquitto_FREE(A)` through
/// `mosquitto_free`, each a free by name shape or by alias. A rule that
/// already classifies a direct call by such a predicate passes the same
/// one here, so a macro invocation and the call it expands to are read
/// alike.
///
/// Expansion is one level at a time, asking `releases` about each callee
/// BEFORE rescanning it, because the spelling that identifies a free can
/// be an intermediate macro's name: curl's `curlx_free(ptr)` is itself a
/// macro for `curl_dbg_free(ptr, __LINE__, __FILE__)`, whose body frees
/// through a function pointer no summary can read, so a fully rescanned
/// text would show only a callee the predicate cannot accept. A callee the
/// predicate rejects that is a macro is recursed into and its released
/// parameters mapped back onto the arguments it was given.
pub fn macro_param_indices_released_by(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
    releases: impl Fn(&str) -> bool,
) -> Vec<usize> {
    let mut active = HashSet::new();
    released_param_indices(table, name, &releases, &mut active, 0)
}

fn released_param_indices(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
    releases: &impl Fn(&str) -> bool,
    active: &mut HashSet<String>,
    depth: usize,
) -> Vec<usize> {
    if depth >= MAX_EXPAND_DEPTH || active.contains(name) {
        return Vec::new();
    }
    let Some(m) = table.get(name) else {
        return Vec::new();
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MREL_{i}__"))
        .collect();
    let map: HashMap<String, String> = m
        .params
        .iter()
        .cloned()
        .zip(sentinels.iter().cloned())
        .collect();
    let body = substitute_params(&m.body, &map);
    // The argument must BE the parameter, not merely mention it: uthash's
    // HASH_ADD frees `(add)->hh.tbl` on its out-of-memory path, which
    // releases a table the element owns and not the element itself.
    let sentinel_indices_in = |arg: &str| -> Vec<usize> {
        let bare = strip_parens_and_casts(arg);
        sentinels
            .iter()
            .enumerate()
            .filter(|(_, s)| bare == s.as_str())
            .map(|(i, _)| i)
            .collect()
    };

    active.insert(name.to_string());
    let mut out = Vec::new();
    for (callee, args) in calls_in(&body) {
        if releases(&callee) {
            for arg in &args {
                out.extend(sentinel_indices_in(arg));
            }
        } else if table.contains_key(&callee) {
            for j in released_param_indices(table, &callee, releases, active, depth + 1) {
                if let Some(arg) = args.get(j) {
                    out.extend(sentinel_indices_in(arg));
                }
            }
        }
    }
    active.remove(name);
    out.sort_unstable();
    out.dedup();
    out
}

/// Every `IDENT(args...)` in `text`, with the argument list split at
/// top-level commas. Calls nested inside another call's arguments are
/// listed too, in textual order.
fn calls_in(text: &str) -> Vec<(String, Vec<String>)> {
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    let mut out = Vec::new();
    let mut i = 0;
    while i < n {
        if !is_ident_start(chars[i]) || (i > 0 && is_ident_char(chars[i - 1])) {
            i += 1;
            continue;
        }
        let start = i;
        while i < n && is_ident_char(chars[i]) {
            i += 1;
        }
        let callee: String = chars[start..i].iter().collect();
        let mut j = i;
        while j < n && chars[j].is_whitespace() {
            j += 1;
        }
        if j >= n || chars[j] != '(' {
            continue;
        }
        let mut depth = 0i32;
        let mut k = j;
        while k < n {
            match chars[k] {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                _ => {}
            }
            k += 1;
        }
        if k < n {
            let arg_text: String = chars[j + 1..k].iter().collect();
            out.push((callee, split_top_level_args(&arg_text)));
        }
    }
    out
}

/// `expr` without surrounding whitespace, enclosing parentheses and
/// leading casts: `(void *)(p)` and `((p))` both yield `p`. A cast is a
/// parenthesized group that is followed by more expression; enclosing
/// parentheses are a group that is the whole expression.
fn strip_parens_and_casts(expr: &str) -> &str {
    let mut e = expr.trim();
    loop {
        if !e.starts_with('(') {
            return e;
        }
        let Some(close) = matching_close_paren(e) else {
            return e;
        };
        let rest = e[close + 1..].trim();
        e = if rest.is_empty() {
            e[1..close].trim()
        } else {
            rest
        };
    }
}

/// Index of the `)` matching the `(` at the start of `s`, if any.
fn matching_close_paren(s: &str) -> Option<usize> {
    let mut depth = 0i32;
    for (i, c) in s.char_indices() {
        match c {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// `args` split at commas outside any bracket, each piece trimmed.
fn split_top_level_args(args: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut depth = 0i32;
    let mut last = 0;
    for (i, c) in args.char_indices() {
        match c {
            '(' | '[' | '{' => depth += 1,
            ')' | ']' | '}' => depth -= 1,
            ',' if depth == 0 => {
                out.push(args[last..i].trim().to_string());
                last = i + 1;
            }
            _ => {}
        }
    }
    out.push(args[last..].trim().to_string());
    out
}

/// True if `text` contains a call to one of [`DEALLOC_FUNCTIONS`] with `ident`
/// appearing as one of its arguments.
fn calls_dealloc_fn_with_arg(text: &str, ident: &str) -> bool {
    calls_fn_with_arg(text, DEALLOC_FUNCTIONS, ident, false)
}

/// True if `text` contains a call to one of `fns` with `ident` appearing as
/// a whole token among its arguments -- in the first argument only when
/// `first_arg_only`, anywhere in the argument list otherwise.
fn calls_fn_with_arg(text: &str, fns: &[&str], ident: &str, first_arg_only: bool) -> bool {
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    for &fn_name in fns {
        let fname: Vec<char> = fn_name.chars().collect();
        let flen = fname.len();
        let mut i = 0;
        while i + flen <= n {
            if chars[i..i + flen] == fname[..] {
                let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
                let mut j = i + flen;
                while j < n && chars[j].is_whitespace() {
                    j += 1;
                }
                if prev_ok && j < n && chars[j] == '(' {
                    // Find the matching close paren, then check whether
                    // `ident` occurs (as a whole token) inside the argument
                    // list.
                    let mut depth = 0i32;
                    let mut k = j;
                    let mut close = None;
                    while k < n {
                        match chars[k] {
                            '(' => depth += 1,
                            ')' => {
                                depth -= 1;
                                if depth == 0 {
                                    close = Some(k);
                                    break;
                                }
                            }
                            _ => {}
                        }
                        k += 1;
                    }
                    if let Some(close) = close {
                        let arg_text: String = chars[j + 1..close].iter().collect();
                        let scope = if first_arg_only {
                            first_top_level_argument(&arg_text)
                        } else {
                            arg_text.as_str()
                        };
                        if contains_whole_ident(scope, ident) {
                            return true;
                        }
                    }
                }
            }
            i += 1;
        }
    }
    false
}

/// The text of the first comma-separated argument in `args`, respecting
/// nested parentheses so `f((a, b), c)` yields `(a, b)`.
fn first_top_level_argument(args: &str) -> &str {
    let mut depth = 0i32;
    for (i, c) in args.char_indices() {
        match c {
            '(' | '[' | '{' => depth += 1,
            ')' | ']' | '}' => depth -= 1,
            ',' if depth == 0 => return &args[..i],
            _ => {}
        }
    }
    args
}

/// True if `ident` appears anywhere in `text` as a whole token (not a
/// substring of a longer identifier).
fn contains_whole_ident(text: &str, ident: &str) -> bool {
    let chars: Vec<char> = text.chars().collect();
    let id: Vec<char> = ident.chars().collect();
    let (n, m) = (chars.len(), id.len());
    if m == 0 {
        return false;
    }
    let mut i = 0;
    while i + m <= n {
        if chars[i..i + m] == id[..] {
            let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
            let next_ok = i + m >= n || !is_ident_char(chars[i + m]);
            if prev_ok && next_ok {
                return true;
            }
        }
        i += 1;
    }
    false
}

/// True if the token starting at `start` (after skipping whitespace and an
/// optional opening paren of a cast we don't model) is the null pointer
/// constant `NULL` or `0`, terminated by a non-identifier/non-digit char.
fn rhs_is_null_constant(chars: &[char], start: usize) -> bool {
    let n = chars.len();
    let mut j = start;
    while j < n && chars[j].is_whitespace() {
        j += 1;
    }
    // `NULL`
    let null_kw = ['N', 'U', 'L', 'L'];
    if j + 4 <= n && chars[j..j + 4] == null_kw && (j + 4 >= n || !is_ident_char(chars[j + 4])) {
        return true;
    }
    // `0` (or `0L`, `0u`… ) — a bare zero literal, not `0x..`/`0.5`/`01`.
    if j < n && chars[j] == '0' {
        let after = if j + 1 < n { chars[j + 1] } else { ' ' };
        if !after.is_ascii_digit() && after != '.' && after != 'x' && after != 'X' {
            return true;
        }
    }
    false
}

/// True if identifier `ident` appears in `text` as the target of a whole-object
/// assignment: `ident =` or `(ident) =` (any number of wrapping parens),
/// excluding compound assignment (`+=`/`==`/…), field/element/deref writes, and
/// member/arrow access. See [`macro_output_param_indices`].
fn is_whole_assignment_target(text: &str, ident: &str) -> bool {
    find_assignment_targets(text, ident, |_| true)
}

/// True if `ident` appears in `text` as the whole-object target of a compound
/// assignment or an increment/decrement: `ident += …`, `(ident) <<= …`,
/// `ident++`, `--ident`. Deliberately a separate predicate from
/// [`is_whole_assignment_target`] rather than a widening of it:
/// [`macro_output_param_indices`] uses that one to prove an argument is *only
/// written* (so an uninitialized scalar may be passed there), and a
/// read-modify-write reads the object first. Deref/field/subscript forms
/// (`*ident += …`, `ident->f++`, `ident[i] |= …`) are excluded by the same
/// look-back as the plain-assignment scan; [`writes_through_pointer`] owns
/// those.
fn is_compound_assignment_target(text: &str, ident: &str) -> bool {
    const COMPOUND_OPS: [&str; 10] = ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="];
    let chars: Vec<char> = text.chars().collect();
    let id: Vec<char> = ident.chars().collect();
    let (n, m) = (chars.len(), id.len());
    if m == 0 {
        return false;
    }
    let mut i = 0;
    while i + m <= n {
        if chars[i..i + m] == id[..] {
            let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
            let next_ok = i + m >= n || !is_ident_char(chars[i + m]);
            // Same look-back as `find_assignment_targets`: a `*`, `.` or `->`
            // just before the (possibly parenthesized) identifier makes this a
            // deref/field access, which reads `ident` rather than assigning it.
            let mut b = i;
            while b > 0 && (chars[b - 1].is_whitespace() || chars[b - 1] == '(') {
                b -= 1;
            }
            let prev_c = if b > 0 { chars[b - 1] } else { ' ' };
            let arrow = b >= 2 && chars[b - 1] == '>' && chars[b - 2] == '-';
            if prev_ok && next_ok && prev_c != '.' && prev_c != '*' && !arrow {
                // Prefix increment/decrement: `++ident` / `--(ident)`.
                if b >= 2
                    && ((chars[b - 1] == '+' && chars[b - 2] == '+')
                        || (chars[b - 1] == '-' && chars[b - 2] == '-'))
                {
                    return true;
                }
                let mut j = i + m;
                while j < n && (chars[j].is_whitespace() || chars[j] == ')') {
                    j += 1;
                }
                let rest: String = chars[j..(j + 3).min(n)].iter().collect();
                if rest.starts_with("++") || rest.starts_with("--") {
                    return true;
                }
                if COMPOUND_OPS.iter().any(|op| rest.starts_with(op)) {
                    return true;
                }
            }
        }
        i += 1;
    }
    false
}

/// True if `ident` appears in `text` as a whole-object assignment whose
/// right-hand side is the null pointer constant (`NULL` or `0`) — i.e.
/// `ident = NULL` / `(ident) = 0`. See [`macro_nulls_param_indices`].
fn is_null_assignment_target(text: &str, ident: &str) -> bool {
    let chars: Vec<char> = text.chars().collect();
    find_assignment_targets(text, ident, |rhs_start| {
        rhs_is_null_constant(&chars, rhs_start)
    })
}

/// Scan `text` for whole-object assignment targets named `ident` (handling
/// wrapping parens and excluding deref/field/compound/comparison forms — see
/// [`is_whole_assignment_target`]). For each candidate, call `rhs_ok` with the
/// char index just past the `=`; return true on the first that passes.
fn find_assignment_targets(text: &str, ident: &str, rhs_ok: impl Fn(usize) -> bool) -> bool {
    let chars: Vec<char> = text.chars().collect();
    let id: Vec<char> = ident.chars().collect();
    let (n, m) = (chars.len(), id.len());
    if m == 0 {
        return false;
    }
    let mut i = 0;
    while i + m <= n {
        if chars[i..i + m] == id[..] {
            // Whole-token match: boundaries must not be identifier chars.
            let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
            let next_ok = i + m >= n || !is_ident_char(chars[i + m]);
            // Look back past wrapping `(` and whitespace for the first
            // significant char. `*`/`.`/`->` there means a deref/field write
            // (`*(p) =`, `(*p) =`, `obj.ident`) which READS the identifier.
            let mut b = i;
            while b > 0 && (chars[b - 1].is_whitespace() || chars[b - 1] == '(') {
                b -= 1;
            }
            let prev_c = if b > 0 { chars[b - 1] } else { ' ' };
            let arrow = b >= 2 && chars[b - 1] == '>' && chars[b - 2] == '-';
            if prev_ok && next_ok && prev_c != '.' && prev_c != '*' && !arrow {
                // Skip whitespace and closing parens after the identifier.
                let mut j = i + m;
                while j < n && (chars[j].is_whitespace() || chars[j] == ')') {
                    j += 1;
                }
                // A single `=` (not `==`) immediately follows → assignment target.
                if j < n && chars[j] == '=' && (j + 1 >= n || chars[j + 1] != '=') && rhs_ok(j + 1)
                {
                    return true;
                }
            }
        }
        i += 1;
    }
    false
}

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

    fn table(src: &str) -> HashMap<String, FunctionMacro> {
        let mut p = CParser::new().unwrap();
        let (tree, src) = p.parse_source(src).unwrap();
        collect_function_macros(&tree.root_node(), &src)
    }

    #[test]
    fn writes_param_indices_sees_compound_assignment_and_increment() {
        // pure-ftpd alt_arc4random.c (task 1254): A and C are only ever
        // read-modify-written; B and D get a plain assignment as well.
        let t = table(concat!(
            "#define ROTL32(x, b) (uint32_t)(((x) << (b)) | ((x) >> (32 - (b))))\n",
            "#define CHACHA20_QUARTERROUND(A, B, C, D) \\\n",
            "    A += B;                               \\\n",
            "    D = ROTL32(D ^ A, 16);                \\\n",
            "    C += D;                               \\\n",
            "    B = ROTL32(B ^ C, 12)\n",
            "#define BUMP(n) ((n)++)\n",
            "#define PRE(n) (--n)\n",
            "#define READS(n) ((n) + 1)\n",
        ));
        assert_eq!(
            macro_writes_param_indices(&t, "CHACHA20_QUARTERROUND"),
            vec![0, 1, 2, 3]
        );
        assert_eq!(macro_writes_param_indices(&t, "BUMP"), vec![0]);
        assert_eq!(macro_writes_param_indices(&t, "PRE"), vec![0]);
        assert!(macro_writes_param_indices(&t, "READS").is_empty());
        // `*(p) += 1` writes THROUGH p (writes_through_pointer's business), and
        // must not be reported as a whole-object compound write of p itself.
        assert!(!is_compound_assignment_target("(*(p) += 1)", "p"));
        // The output-argument predicate must stay strict: a compound
        // assignment reads its target first.
        assert_eq!(
            macro_output_param_indices(&t, "CHACHA20_QUARTERROUND"),
            vec![1, 3]
        );
    }

    #[test]
    fn collects_simple_function_macro() {
        let t = table("#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n");
        let m = t.get("MIN").expect("MIN collected");
        assert_eq!(m.params, vec!["x", "y"]);
        assert!(m.body.contains("(x) < (y)"));
    }

    #[test]
    fn skips_stringize_and_paste() {
        let t = table("#define STR(x) #x\n#define CAT(a,b) a##b\n#define OK(a) ((a)+1)\n");
        assert!(!t.contains_key("STR"));
        assert!(!t.contains_key("CAT"));
        assert!(t.contains_key("OK"));
    }

    #[test]
    fn skips_variadic() {
        let t = table("#define LOG(fmt, ...) printf(fmt, __VA_ARGS__)\n");
        assert!(!t.contains_key("LOG"));
    }

    #[test]
    fn expands_simple() {
        let t = table("#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n");
        let out = expand_invocation(&t, "MIN", &["a".into(), "b+1".into()]).unwrap();
        assert_eq!(out, "(((a) < (b+1)) ? (a) : (b+1))");
    }

    #[test]
    fn expands_deref_macro() {
        let t = table("#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))\n");
        let out = expand_invocation(&t, "ORIGVFS", &["pFile".into()]).unwrap();
        assert_eq!(out, "((sqlite3_vfs*)((pFile)->pAppData))");
    }

    #[test]
    fn arity_mismatch_returns_none() {
        let t = table("#define MIN(x,y) ((x)<(y)?(x):(y))\n");
        assert!(expand_invocation(&t, "MIN", &["a".into()]).is_none());
    }

    #[test]
    fn does_not_substitute_inside_string() {
        let t = table("#define TAG(x) \"x is here\" x\n");
        // The "x" inside the string literal must not be replaced.
        let out = expand_invocation(&t, "TAG", &["v".into()]).unwrap();
        assert_eq!(out, "\"x is here\" v");
    }

    #[test]
    fn recursive_rescan_nested_macro() {
        let t = table("#define SQUARE(z) ((z)*(z))\n#define DIST(a) SQUARE(a)\n");
        let out = expand_invocation(&t, "DIST", &["n+1".into()]).unwrap();
        assert_eq!(out, "((n+1)*(n+1))");
    }

    #[test]
    fn self_reference_does_not_loop() {
        // `#define A(x) A(x)` must not infinitely recurse; the inner A is left
        // unexpanded once A is active.
        let t = table("#define A(x) A((x)+1)\n");
        let out = expand_invocation(&t, "A", &["v".into()]).unwrap();
        assert_eq!(out, "A((v)+1)");
    }

    #[test]
    fn nested_call_args_with_commas() {
        let t = table("#define ADD(a,b) ((a)+(b))\n#define ID(x) (x)\n");
        // ID(ADD(1,2)) — the comma is inside a nested call, one arg to ID.
        let out = expand_invocation(&t, "ID", &["ADD(1,2)".into()]).unwrap();
        assert_eq!(out, "(((1)+(2)))");
    }

    // ── Textual error-correcting collector ──────────────────────────────────

    #[test]
    fn textual_collects_function_like() {
        let t = collect_function_macros_textual(
            "#define curlx_free(ptr) curl_dbg_free(ptr, __LINE__, __FILE__)\n",
        );
        let m = t.get("curlx_free").expect("curlx_free collected");
        assert_eq!(m.params, vec!["ptr"]);
        assert_eq!(m.body, "curl_dbg_free(ptr, __LINE__, __FILE__)");
    }

    #[test]
    fn textual_skips_object_like() {
        // Space before '(' → object-like alias, not a function-like macro.
        let t = collect_function_macros_textual("#define curlx_free Curl_cfree\n");
        assert!(!t.contains_key("curlx_free"));
        let t2 = collect_function_macros_textual("#define PAREN (1 + 2)\n");
        assert!(!t2.contains_key("PAREN"));
    }

    #[test]
    fn textual_skips_variadic_and_paste() {
        let t = collect_function_macros_textual(
            "#define LOG(fmt, ...) printf(fmt, __VA_ARGS__)\n#define CAT(a,b) a##b\n",
        );
        assert!(!t.contains_key("LOG"));
        assert!(!t.contains_key("CAT"));
    }

    #[test]
    fn textual_joins_continuation() {
        let t = collect_function_macros_textual(
            "#define curlx_calloc(nbelem, size) \\\n  curl_dbg_calloc(nbelem, size, __LINE__, __FILE__)\n",
        );
        let m = t
            .get("curlx_calloc")
            .expect("collected across continuation");
        assert_eq!(m.params, vec!["nbelem", "size"]);
        assert!(m.body.contains("curl_dbg_calloc(nbelem, size"));
    }

    #[test]
    fn textual_strips_comments() {
        let t = collect_function_macros_textual("#define WRAP(x) real(x) /* trailing */\n");
        assert_eq!(t.get("WRAP").unwrap().body, "real(x)");
    }

    #[test]
    fn textual_indented_define_with_space_after_hash() {
        let t = collect_function_macros_textual("  #  define INDENT(x) ((x)+1)\n");
        assert!(t.contains_key("INDENT"));
    }

    #[test]
    fn does_not_match_defined_operator() {
        let t = collect_function_macros_textual("#if defined(FOO)\n#endif\n");
        assert!(t.is_empty());
    }

    // ── Macro output-parameter detection ────────────────────────────────────

    #[test]
    fn output_param_simple_assignment() {
        // The first parameter is assigned; the others are only read.
        let t = table("#define SAVE(out, a, b) do { (out) = (a) + (b); } while(0)\n");
        assert_eq!(macro_output_param_indices(&t, "SAVE"), vec![0]);
    }

    #[test]
    fn output_param_cf_data_save_shape() {
        // curl's CF_DATA_SAVE pattern (with the nested CF_CTX_CALL_DATA macro
        // resolving through the table). save (arg 0) is assigned; cf/data are read.
        let t = table(
            "#define CF_CTX_CALL_DATA(cf) ((cf)->ctx->call_data)\n\
             #define CF_DATA_SAVE(save, cf, data) do { (save) = CF_CTX_CALL_DATA(cf); CF_CTX_CALL_DATA(cf).data = (data); } while(0)\n",
        );
        assert_eq!(macro_output_param_indices(&t, "CF_DATA_SAVE"), vec![0]);
    }

    #[test]
    fn output_param_excludes_field_and_deref_writes() {
        // Field write (p->f =), element write (p[i] =), and deref write (*p =)
        // all READ the pointer first — they are not whole-object outputs.
        let t = table(
            "#define FW(p) do { (p)->f = 1; } while(0)\n\
             #define EW(p) do { (p)[0] = 1; } while(0)\n\
             #define DW(p) do { *(p) = 1; } while(0)\n",
        );
        assert!(macro_output_param_indices(&t, "FW").is_empty());
        assert!(macro_output_param_indices(&t, "EW").is_empty());
        assert!(macro_output_param_indices(&t, "DW").is_empty());
    }

    #[test]
    fn output_param_excludes_compound_and_comparison() {
        // `+=` reads first; `==` is a comparison, not an assignment.
        let t = table(
            "#define ADDEQ(x, y) do { (x) += (y); } while(0)\n\
             #define CMP(x, y) ((x) == (y))\n",
        );
        assert!(macro_output_param_indices(&t, "ADDEQ").is_empty());
        assert!(macro_output_param_indices(&t, "CMP").is_empty());
    }

    #[test]
    fn output_param_multiple_outputs() {
        let t = table("#define BOTH(a, b, c) do { a = 1; b = 2; (void)c; } while(0)\n");
        assert_eq!(macro_output_param_indices(&t, "BOTH"), vec![0, 1]);
    }

    #[test]
    fn output_param_unknown_macro_is_empty() {
        let t = table("#define X(a) (a)\n");
        assert!(macro_output_param_indices(&t, "NOPE").is_empty());
    }

    // ── Macro write-through-pointer detection (EXP34-C/ARR00-C) ────────────

    #[test]
    fn writes_param_includes_field_and_deref_and_subscript() {
        // Unlike macro_output_param_indices, these ARE reported: writing
        // through the pointer proves it's non-null / in-bounds.
        let t = table(
            "#define FW(p) do { (p)->f = 1; } while(0)\n\
             #define EW(p) do { (p)[0] = 1; } while(0)\n\
             #define DW(p) do { *(p) = 1; } while(0)\n",
        );
        assert_eq!(macro_writes_param_indices(&t, "FW"), vec![0]);
        assert_eq!(macro_writes_param_indices(&t, "EW"), vec![0]);
        assert_eq!(macro_writes_param_indices(&t, "DW"), vec![0]);
    }

    #[test]
    fn writes_param_still_includes_whole_object_assignment() {
        let t = table("#define SAVE(out, a, b) do { (out) = (a) + (b); } while(0)\n");
        assert_eq!(macro_writes_param_indices(&t, "SAVE"), vec![0]);
    }

    #[test]
    fn writes_param_fts3_getvarint32_shape() {
        // sqlite's fts3GetVarint32(p, piVal): *piVal = *(u8*)(p) -- a deref
        // write to the second (output) parameter.
        let t = table("#define fts3GetVarint32(p, piVal) (*(piVal) = *(unsigned char*)(p))\n");
        assert_eq!(macro_writes_param_indices(&t, "fts3GetVarint32"), vec![1]);
    }

    #[test]
    fn writes_param_excludes_read_only_and_comparison() {
        let t = table(
            "#define READ(p) ((p)->f)\n\
             #define CMP(p) ((p)->f == 1)\n",
        );
        assert!(macro_writes_param_indices(&t, "READ").is_empty());
        assert!(macro_writes_param_indices(&t, "CMP").is_empty());
    }

    #[test]
    fn writes_param_unknown_macro_is_empty() {
        let t = table("#define X(a) (a)\n");
        assert!(macro_writes_param_indices(&t, "NOPE").is_empty());
    }

    // ── Free-and-null (safe-free) macro detection ───────────────────────────

    #[test]
    fn nulls_param_curl_safefree_shape() {
        // curl Curl_safefree expands free(ptr) then (ptr)=NULL through the
        // nested curlx_free wrapper.
        let t = table(
            "#define curlx_free(p) free(p)\n\
             #define Curl_safefree(ptr) do { curlx_free(ptr); (ptr) = NULL; } while(0)\n",
        );
        assert_eq!(macro_nulls_param_indices(&t, "Curl_safefree"), vec![0]);
    }

    #[test]
    fn nulls_param_zero_literal() {
        let t = table("#define SAFE_FREE(x) do { free(x); (x) = 0; } while(0)\n");
        assert_eq!(macro_nulls_param_indices(&t, "SAFE_FREE"), vec![0]);
    }

    #[test]
    fn nulls_param_excludes_plain_free_no_null() {
        // A free wrapper that does NOT null its arg must not be reported.
        let t = table("#define just_free(p) free(p)\n");
        assert!(macro_nulls_param_indices(&t, "just_free").is_empty());
    }

    #[test]
    fn nulls_param_excludes_nonzero_and_field_assign() {
        // RHS is not the null constant; and a field write is not whole-object.
        let t = table(
            "#define SETONE(x) do { (x) = 1; } while(0)\n\
             #define CLEARF(p) do { (p)->next = NULL; } while(0)\n",
        );
        assert!(macro_nulls_param_indices(&t, "SETONE").is_empty());
        assert!(macro_nulls_param_indices(&t, "CLEARF").is_empty());
    }

    #[test]
    fn nulls_param_only_nulled_arg() {
        // Frees a, nulls b — only b is the nulled param.
        let t = table("#define FN(a, b) do { free(a); (b) = NULL; } while(0)\n");
        assert_eq!(macro_nulls_param_indices(&t, "FN"), vec![1]);
    }

    // ── Case-label macro detection ──────────────────────────────────────────

    #[test]
    fn expands_to_case_label_sqlite_shape() {
        let t = table("#define CASE(i,str) case i: assert( strcmp(aSub[i].zName, str)==0 );\n");
        assert!(macro_expands_to_case_label(&t, "CASE"));
    }

    #[test]
    fn expands_to_case_label_rejects_non_case_body() {
        let t = table("#define FOO(i) do_something(i);\n");
        assert!(!macro_expands_to_case_label(&t, "FOO"));
    }

    #[test]
    fn expands_to_case_label_rejects_prefix_match() {
        // "casement(i)" must not be mistaken for the "case" keyword.
        let t = table("#define WEIRD(i) casement(i);\n");
        assert!(!macro_expands_to_case_label(&t, "WEIRD"));
    }

    #[test]
    fn expands_to_case_label_unknown_macro_is_false() {
        let t = table("#define X(a) (a)\n");
        assert!(!macro_expands_to_case_label(&t, "NOPE"));
    }

    // ── Deallocation (frees) macro detection ────────────────────────────────

    #[test]
    fn frees_param_simple_fclose_wrapper() {
        let t = table("#define SAFE_FCLOSE(f) fclose(f)\n");
        assert_eq!(macro_frees_param_indices(&t, "SAFE_FCLOSE"), vec![0]);
    }

    #[test]
    fn frees_param_safe_free_shape() {
        let t = table("#define SAFE_FREE(x) do { free(x); (x) = NULL; } while(0)\n");
        assert_eq!(macro_frees_param_indices(&t, "SAFE_FREE"), vec![0]);
    }

    #[test]
    fn frees_param_unrelated_macro_is_empty() {
        let t = table("#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n");
        assert!(macro_frees_param_indices(&t, "MIN").is_empty());
    }

    /// curl's `Curl_safefree` frees through `curlx_free`, a name the fixed
    /// list cannot know and itself a macro for a `curl_dbg_free` call whose
    /// body no predicate would accept. The caller's predicate is asked
    /// about `curlx_free` before it is rescanned away. Only the parameter
    /// handed to the accepted callee is reported, through a macro that
    /// merely forwards it too.
    #[test]
    fn released_by_predicate_sees_project_spelling() {
        let t = table(
            "#define curlx_free(ptr) curl_dbg_free(ptr, __LINE__, __FILE__)\n\
             #define Curl_safefree(ptr) do { curlx_free(ptr); (ptr) = NULL; } while(0)\n\
             #define PAIR_FREE(a, b) do { keep(a); Curl_safefree(b); } while(0)\n\
             #define SWAP_FREE(a, b) PAIR_FREE(b, a)\n\
             #define CAST_FREE(p) free((void *)(p))\n\
             #define TABLE_FREE(e) do { free((e)->tbl); (e)->tbl = NULL; } while(0)\n",
        );
        let is_free = |name: &str| name == "curlx_free" || name == "free";
        assert_eq!(
            macro_param_indices_released_by(&t, "CAST_FREE", is_free),
            vec![0]
        );
        assert!(macro_param_indices_released_by(&t, "TABLE_FREE", is_free).is_empty());
        assert!(macro_frees_param_indices(&t, "Curl_safefree").is_empty());
        assert_eq!(
            macro_param_indices_released_by(&t, "Curl_safefree", is_free),
            vec![0]
        );
        assert_eq!(
            macro_param_indices_released_by(&t, "PAIR_FREE", is_free),
            vec![1]
        );
        assert_eq!(
            macro_param_indices_released_by(&t, "SWAP_FREE", is_free),
            vec![0]
        );
        assert!(macro_param_indices_released_by(&t, "Curl_safefree", |_| false).is_empty());
        assert!(macro_param_indices_released_by(&t, "NOPE", is_free).is_empty());
    }

    /// hostap's `os_memset` shape: the destination parameter, and only it,
    /// is cleared. A parameter that is the fill value or the length, or one
    /// handed to memset as anything but its first argument, is not
    /// (task 1127).
    #[test]
    fn clears_param_only_the_destination() {
        let t = table("#define os_memset(s, c, n) memset(s, c, n)\n");
        assert_eq!(macro_clears_param_indices(&t, "os_memset"), vec![0]);
        let t = table("#define ZERO_INTO(dst, src, n) memset((void *)(dst), 0, (n))\n");
        assert_eq!(macro_clears_param_indices(&t, "ZERO_INTO"), vec![0]);
        let t = table("#define COPY(dst, src, n) memcpy(dst, src, n)\n");
        assert!(macro_clears_param_indices(&t, "COPY").is_empty());
        let t = table("#define ZERO_LEN(buf, n) memset(scratch, 0, n)\n");
        assert!(macro_clears_param_indices(&t, "ZERO_LEN").is_empty());
    }

    #[test]
    fn forwarding_target_curl_rand_shape() {
        // curl's real (non-DEBUGBUILD) shape:
        // #define Curl_rand(a, b, c) Curl_rand_bytes(a, b, c)
        let t = table("#define Curl_rand(a, b, c) Curl_rand_bytes(a, b, c)\n");
        let (callee, map) = macro_forwarding_target(&t, "Curl_rand").expect("forwarding");
        assert_eq!(callee, "Curl_rand_bytes");
        assert_eq!(map, vec![Some(0), Some(1), Some(2)]);
    }

    #[test]
    fn forwarding_target_curl_rand_debug_shape_with_literal_and_cast() {
        // curl's DEBUGBUILD shape adds a literal arg and the real call site
        // wraps the buffer arg in a cast: Curl_rand(data, (unsigned char *)rnd, rnd_size)
        let t = table("#define Curl_rand(a, b, c) Curl_rand_bytes(a, TRUE, b, c)\n");
        let (callee, map) = macro_forwarding_target(&t, "Curl_rand").expect("forwarding");
        assert_eq!(callee, "Curl_rand_bytes");
        // arg0 -> macro param 0 (a), arg1 is the literal TRUE (no mapping),
        // arg2 -> macro param 1 (b), arg3 -> macro param 2 (c).
        assert_eq!(map, vec![Some(0), None, Some(1), Some(2)]);
    }

    #[test]
    fn forwarding_target_rejects_transformed_param() {
        // Not a pure passthrough: the callee sees `a+1`, not the bare param.
        let t = table("#define BUMP_CALL(a) real_fn(a+1)\n");
        let (callee, map) = macro_forwarding_target(&t, "BUMP_CALL").expect("forwarding");
        assert_eq!(callee, "real_fn");
        assert_eq!(map, vec![None]);
    }

    #[test]
    fn forwarding_target_none_for_non_call_body() {
        let t = table("#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n");
        assert!(macro_forwarding_target(&t, "MIN").is_none());
    }

    #[test]
    fn forwarding_target_none_when_callee_is_itself_a_macro() {
        let t = table("#define INNER(a) real_fn(a)\n#define OUTER(a) INNER(a)\n");
        // OUTER expands (via rescan) all the way through INNER to real_fn, so
        // this should resolve straight to the real function, not stop at the
        // intermediate macro name.
        let (callee, map) = macro_forwarding_target(&t, "OUTER").expect("forwarding");
        assert_eq!(callee, "real_fn");
        assert_eq!(map, vec![Some(0)]);
    }

    #[test]
    fn merge_recovers_macro_in_error_region() {
        // A torture-header shape: a malformed construct forces tree-sitter into
        // ERROR recovery, so the following `#define` is NOT emitted as a
        // preproc_function_def — only the textual pass recovers it.
        let src = "#define BROKEN(a) a +++ ++ +\n\
                   int f(void) { return 1 } }\n\
                   #define recovered_free(ptr) free(ptr)\n";
        let mut p = CParser::new().unwrap();
        let (tree, src) = p.parse_source(src).unwrap();
        let ast_only = {
            let mut out = HashMap::new();
            collect_rec(&tree.root_node(), &src, &DeadRegions::default(), &mut out);
            out
        };
        let merged = collect_function_macros(&tree.root_node(), &src);
        // Whatever the AST pass managed, the merged set must contain the wrapper.
        assert!(
            merged.contains_key("recovered_free"),
            "textual pass should recover recovered_free; ast_only={:?}",
            ast_only.keys().collect::<Vec<_>>()
        );
        assert_eq!(merged["recovered_free"].body, "free(ptr)");
    }

    #[test]
    fn platform_dead_definition_does_not_win_first() {
        // hostap os.h's shape: the `_MSC_VER` body comes first, so
        // first-wins used to hand every consumer `_strdup`, a name no POSIX
        // build ever has. The AST pass and the textual pass must agree.
        let src = "#ifndef os_strdup
                   #ifdef _MSC_VER
                   #define os_strdup(s) _strdup(s)
                   #else
                   #define os_strdup(s) strdup(s)
                   #endif
                   #endif
";
        let mut p = CParser::new().unwrap();
        let (tree, src) = p.parse_source(src).unwrap();
        let macros = collect_function_macros(&tree.root_node(), &src);
        assert_eq!(macros["os_strdup"].body, "strdup(s)");

        // A build-config guard the platform profile has no opinion about
        // still resolves first-wins, exactly as before.
        let src = "#ifdef WPA_TRACE
                   #define os_strdup(s) trace_strdup(s)
                   #else
                   #define os_strdup(s) strdup(s)
                   #endif
";
        let (tree, src) = p.parse_source(src).unwrap();
        let macros = collect_function_macros(&tree.root_node(), &src);
        assert_eq!(macros["os_strdup"].body, "trace_strdup(s)");

        // A definition only the dead platform has is dropped, not kept.
        let src = "#ifdef _WIN32
#define ONLY_WIN(x) win(x)
#endif
#define BOTH(x) x
";
        let (tree, src) = p.parse_source(src).unwrap();
        let macros = collect_function_macros(&tree.root_node(), &src);
        assert!(!macros.contains_key("ONLY_WIN"), "{:?}", macros.keys());
        assert!(macros.contains_key("BOTH"));
    }

    #[test]
    fn alternatives_keep_every_preprocessor_branch_of_one_name() {
        // sqlite complete.c's shape, reduced: two mutually exclusive
        // definitions of one name, only the second of which touches a
        // caller-scope `c`.
        let src = "#ifdef SQLITE_ASCII\n                   #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)\n                   #endif\n                   #ifdef SQLITE_EBCDIC\n                   #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))\n                   #endif\n";
        let alts = collect_function_macro_alternatives(src);
        let idchar = alts.get("IdChar").expect("IdChar collected");
        assert_eq!(idchar.len(), 2, "both branches kept: {:?}", idchar);

        // collect_function_macros keeps only the first, which is exactly why
        // the alternatives collector exists.
        assert!(!idchar
            .iter()
            .all(|m| macro_references_free_identifier(m, "c")));
        assert!(idchar
            .iter()
            .any(|m| macro_references_free_identifier(m, "c")));
    }

    #[test]
    fn free_identifier_check_ignores_parameters_and_substrings() {
        let alts = collect_function_macro_alternatives(
            "#define SQUARE(x) ((x) * (x))\n#define BUMP(n) (cnt += (n))\n",
        );
        let square = &alts["SQUARE"][0];
        let bump = &alts["BUMP"][0];

        // A macro's own parameter is bound by the macro, not by the caller.
        assert!(!macro_references_free_identifier(square, "x"));
        // Whole-token matching: `cnt` is free, but `c` and `nt` are not in it.
        assert!(macro_references_free_identifier(bump, "cnt"));
        assert!(!macro_references_free_identifier(bump, "c"));
        assert!(!macro_references_free_identifier(bump, "nt"));
        assert!(!macro_references_free_identifier(bump, ""));
    }

    fn one(src: &str, name: &str) -> FunctionMacro {
        collect_function_macro_alternatives(src)
            .remove(name)
            .and_then(|mut v| {
                if v.is_empty() {
                    None
                } else {
                    Some(v.remove(0))
                }
            })
            .unwrap_or_else(|| panic!("{name} collected"))
    }

    #[test]
    fn free_identifier_scan_skips_struct_members() {
        // curl lib/urldata.h: `proxy` here is a member of `bits`, not the
        // caller's `char *proxy = NULL;` in lib/url.c.
        let m = one(
            "#define CONN_IS_PROXIED(x) ((x)->bits.proxy)\n",
            "CONN_IS_PROXIED",
        );
        assert!(!macro_references_free_identifier(&m, "proxy"));
        assert!(!macro_references_free_identifier(&m, "bits"));

        // sqlite src/sqliteInt.h: `eDest` is a member of the parameter.
        let m = one(
            "#define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)\n",
            "IgnorableOrderby",
        );
        assert!(!macro_references_free_identifier(&m, "eDest"));
        assert!(macro_references_free_identifier(&m, "SRT_Fifo"));
    }

    #[test]
    fn free_identifier_scan_skips_cast_type_names() {
        // seL4 include/kernel/boot.h: `pptr_t` is the cast's type.
        let m = one(
            "#define pptr_of_cap(cap) ((pptr_t)cap_get_capPtr(cap))\n",
            "pptr_of_cap",
        );
        assert!(!macro_references_free_identifier(&m, "pptr_t"));
        assert!(macro_references_free_identifier(&m, "cap_get_capPtr"));

        // A parenthesised identifier followed by a binary operator stays a
        // reference -- `(flags) & (f)` is bitwise-and, not a cast to
        // `flags` of `&(f)`.
        let m = one("#define IS_SET(f) ((flags) & (f))\n", "IS_SET");
        assert!(macro_references_free_identifier(&m, "flags"));
    }

    #[test]
    fn free_identifier_reads_exclude_write_only_targets() {
        // mosquitto src/persist.h: read_e only ever WRITES rc, so the
        // caller's `int rc = MOSQ_ERR_UNKNOWN;` stays dead.
        let m = one(
            "#define read_e(f, b, c) if(fread(b,1,c,f) != c){ rc = MOSQ_ERR_UNKNOWN; goto error; }\n",
            "read_e",
        );
        let reads = macro_free_identifier_reads(&m);
        assert!(
            !reads.contains("rc"),
            "write-only target is not a read: {reads:?}"
        );
        assert!(reads.contains("fread"));
        assert!(reads.contains("MOSQ_ERR_UNKNOWN"));

        // But the unused-variable question still counts it: a write through
        // a macro is a use of the caller's variable.
        assert!(macro_references_free_identifier(&m, "rc"));
    }

    #[test]
    fn free_identifier_reads_keep_compound_and_comparison_operands() {
        // `+=` and `==` both read the old value; only a bare `=` does not.
        let m = one("#define BUMP(n) (cnt += (n))\n", "BUMP");
        assert!(macro_free_identifier_reads(&m).contains("cnt"));

        let m = one("#define AT_END(n) (pos == (n))\n", "AT_END");
        assert!(macro_free_identifier_reads(&m).contains("pos"));

        // A variable both written once and read once elsewhere is a read.
        let m = one(
            "#define SWAP_IN(v) do { tmp = (v); use(tmp); } while (0)\n",
            "SWAP_IN",
        );
        assert!(macro_free_identifier_reads(&m).contains("tmp"));
    }
}