dayzmake-core 0.3.1

Readers and writers for DayZ file formats: PBO, rapified config, P3D, PAA, BI keys and signatures, and navmesh generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
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
//! Functions for preprocessing Arma configs and scripts

use std::cell::Cell;
use std::clone::Clone;
use std::collections::HashMap;
use std::env::current_dir;
use std::ffi::OsStr;
use std::fs::{File, read_dir};
use std::io::{Error, Read};
use std::path::{Component, Path, PathBuf};

use crate::error::{ErrorExt, PreprocessParseErrorExt, printable};
use crate::warning::{Warning, WarningSink};

peg::parser! {
    /// PEG grammar for the preprocessor: directives, macros, comments and tokens. `deep` is set when
    /// macro argument parentheses nest deeper than [`MAX_NESTING_DEPTH`]; the caller turns that into an error.
    pub(crate) grammar preprocess_grammar(deep: &Cell<bool>, file_end: bool) for str {
        rule newline() = "\r\n" / "\n"

        rule name() -> String = n:$(['a'..='z' | 'A'..='Z' | '0'..='9' | '_']+) {
            n.to_string()
        }

        rule include_path() -> String =
            "\"" path:$((!['"'] [_])*) "\"" { path.to_string() } /
            "<" path:$((!['>'] [_])*) ">"   { path.to_string() }

        rule parameters() -> Vec<String> = "(" [' ' | '\t']* p:(name() ** ([' ' | '\t']* "," [' ' | '\t']*)) [' ' | '\t']* ")" {
            p
        }

        rule definition_value() -> Vec<Token> = ([' ' | '\t']+ / &("\\" newline())) v:(token()*) {
            v
        }

        rule definition() -> Definition = n:name() p:parameters()? v:definition_value()? {
            Definition {
                name: n,
                parameters: p,
                value: v.unwrap_or_default(),
                local: false
            }
        }

        rule directive() -> Directive =
            "#" [' ' | '\t']* "include" [' ' | '\t']+ path:include_path() { Directive::IncludeDirective(path) } /
            "#" [' ' | '\t']* "define" [' ' | '\t']+ d:definition() { Directive::DefineDirective(d) } /
            "#" [' ' | '\t']* "undef" [' ' | '\t']+ n:name() { Directive::UndefDirective(n) } /
            "#" [' ' | '\t']* "ifdef" [' ' | '\t']+ n:name() { Directive::IfDefDirective(n) } /
            "#" [' ' | '\t']* "ifndef" [' ' | '\t']+ n:name() { Directive::IfNDefDirective(n) } /
            "#" [' ' | '\t']* "else" { Directive::ElseDirective } /
            "#" [' ' | '\t']* "endif" { Directive::EndIfDirective }

        rule nesting_ok(d: usize) = {?
            if deep.get() || d >= MAX_NESTING_DEPTH {
                deep.set(true);
                Err("parentheses nested within the limit")
            } else {
                Ok(())
            }
        }

        rule arg_rec(d: usize) = "(" nesting_ok(d) (arg_rec(d + 1) / "\\\\" / ("\\" newline()) / !['\r' | '\n' | '(' | ')'] [_])* ")"

        rule argument() -> String = a:$((arg_rec(0) / "\\\\" / ("\\" newline()) / !['\r' | '\n' | ',' | ')'] [_])*) {
            a.to_string()
        }

        /// Parses a macro argument list: `(a, b, c)`.
        pub rule arguments() -> Vec<String> = [' ' | '\t']* "(" [' ' | '\t']* a:(argument() ** ([' ' | '\t']* "," [' ' | '\t']*)) [' ' | '\t']* ")" {
            a
        }

        rule nonmacro_token() -> String = s:$((!macro_proper() !comment_token() !concat_token() ("\\\\" / ("\\" newline()) / !['"' | '\r' | '\n'] [_]))+) {
            s.to_string()
        }

        rule string_token() -> (String, u32) =
                s:$("\"" ("\\\\" / ("\\" newline()) / "\"\"" / !['\r' | '\n' | '"'] [_])* "\"") {
            let newlines =
                u32::try_from(s.chars().filter(|c| c == &'\n').count()).unwrap_or(u32::MAX);
            (String::from(s).replace("\r\n", "\n").replace("\\\n", ""), newlines)
        }

        /// Parses a macro invocation: an optional `#`, a name, optional arguments.
        pub rule macro_proper() -> Macro = quoted:"#"? n:name() args:arguments()? {
            Macro {
                name: n,
                arguments: args,
                original: String::new(),
                quoted: quoted.is_some()
            }
        }

        rule macro_token() -> Macro = original:$(macro_proper()) {?
            parse_macro(original).map_err(|_| "a parseable macro invocation")
        }

        rule concat_token() = "##"

        /// A `//` comment ends at a line end or at the end of the input (without one `CfgConvert` accepts it too).
        rule sl_comment() -> u32 = "//" (!newline() [_])* &(newline() / ![_]) {
            0
        }

        rule ml_comment() -> u32 = [' ' | '\t']* "/*" content:$((!"*/" (newline() / [_]))*) "*/" {
            u32::try_from(content.chars().filter(|c| c == &'\n').count()).unwrap_or(u32::MAX)
        }

        /// An unterminated `/*` runs to the end of the file, as in `CfgConvert`. Only the parse of a whole
        /// file (`file_end`) allows it, not the re-tokenised substrings of macro arguments.
        rule open_comment() -> u32 = [' ' | '\t']* "/*" content:$([_]*) ![_] {?
            if file_end {
                // The file's final line end does not start another line: a diagnostic stays inside the file.
                let content = content.strip_suffix('\n').unwrap_or(content);
                Ok(u32::try_from(content.chars().filter(|c| c == &'\n').count()).unwrap_or(u32::MAX))
            } else {
                Err("a terminated comment")
            }
        }

        rule comment_token() -> u32 = sl_comment() / ml_comment()

        rule token() -> Token =
            c:comment_token() { Token::CommentToken(c) } /
            c:open_comment() { Token::OpenCommentToken(c) } /
            sn:string_token() { Token::NewlineToken(sn.0, sn.1) } /
            concat_token() { Token::ConcatToken } /
            m:macro_token() { Token::MacroToken(m) } /
            nm:nonmacro_token() { Token::RegularToken(nm) }

        /// Parses a sequence of tokens.
        pub rule tokens() -> Vec<Token> = t:(token()*) {
            t
        }

        rule line() -> Line =
            [' ' | '\t']* d:directive() cmts:(([' ' | '\t']* c:comment_token() { c })*) open:([' ' | '\t']* c:open_comment() { c })? [' ' | '\t']* {
                Line::DirectiveLine(d, cmts.iter().sum::<u32>().saturating_add(open.unwrap_or(0)), open.is_some())
            } /
            [' ' | '\t']* t:tokens() { Line::TokenLine(t) }

        /// Parses a whole file into lines.
        pub rule file() -> Vec<Line> = lines:(line() ** (newline())) ![_] {
            lines
        }
    }
}

/// Macro definition
#[derive(Clone, Debug)]
pub(crate) struct Definition {
    name: String,
    parameters: Option<Vec<String>>,
    value: Vec<Token>,
    local: bool,
}

/// Preprocessor directive
#[derive(Debug)]
#[expect(
    clippy::enum_variant_names,
    reason = "the variants are named after the directives they stand for"
)]
pub(crate) enum Directive {
    /// `#include` directive containing the given path
    IncludeDirective(String),
    /// `#define` directive containing the definition
    DefineDirective(Definition),
    /// `#undef` directive containing the name of the macro
    UndefDirective(String),
    /// `#ifdef` directive containing the name of the macro
    IfDefDirective(String),
    /// `#ifndef` directive containing the name of the macro
    IfNDefDirective(String),
    /// `#else` directive
    ElseDirective,
    /// `#endif` directive
    EndIfDirective,
}

/// Potential macro invocation
#[derive(Debug)]
pub(crate) struct Macro {
    name: String,
    arguments: Option<Vec<String>>,
    original: String,
    quoted: bool,
}

/// Preprocessor token
#[derive(Debug)]
#[expect(
    clippy::enum_variant_names,
    reason = "the variants are named after the tokens they stand for"
)]
pub(crate) enum Token {
    /// Non-macro token
    RegularToken(String),
    /// Non-macro token that contains a number of newlines
    NewlineToken(String, u32),
    /// Potential macro token
    MacroToken(Macro),
    /// Comment token containing a number of newlines
    CommentToken(u32),
    /// Unterminated `/*` comment (to the end of the file) containing a number of newlines
    OpenCommentToken(u32),
    /// Token for the concatenation operator (`##`)
    ConcatToken,
}

/// Preprocessor line
#[derive(Debug)]
pub(crate) enum Line {
    /// Directive line
    DirectiveLine(Directive, u32, bool),
    /// Non-directive line of tokens
    TokenLine(Vec<Token>),
}

/// The folders searched for absolute includes (`#include "\DZ\data\x.hpp"`).
///
/// A folder in `search` is searched recursively for a file whose path ends in the include path (and whose
/// `$PBOPREFIX$` matches); the walk does not follow directory symlinks that leave the folder, and enters no directory twice;
/// a search folder that reaches 1,000,000 visited entries is an error naming the
/// include, and it ends the whole lookup (the other folders are not tried). A folder in `direct` is only
/// checked for `<folder>/<include path>` (case-insensitively as a second pass), without walking it: use it for the
/// current working directory, which can be a whole disk. The `search` folders are tried first, then the `direct`
/// ones.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct IncludeFolders {
    /// Folders searched recursively.
    pub search: Vec<PathBuf>,
    /// Folders checked only for the include path directly below them.
    pub direct: Vec<PathBuf>,
    /// When set, includes come from these in-memory files only and the file system is never read (the
    /// folders above are ignored); see [`MemoryIncludes`].
    pub memory: Option<MemoryIncludes>,
}

/// The files of one archive (a PBO) as an include source, for input that must never reach the file system.
///
/// `origin` of the preprocessed input is the name of the including entry, and an include is resolved
/// relative to the folder of that entry, or, in the engine's `\prefix\path` form, when it points into
/// `prefix`. Absolute paths and drive letters are errors, as are empty components and control characters
/// (see [`crate::pbo::safe_relative_path`]). In the relative form a `..` component is resolved inside the PBO and one that would leave
/// the PBO's root is an error; in the `\prefix\path` form `..` is always an error. Names compare ignoring case. The files
/// an `#include` pulls in count against a total of 64 MiB per preprocess call.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct MemoryIncludes {
    prefix: String,
    /// lowercase `/`-separated name -> (name as given, content)
    files: std::collections::BTreeMap<String, (String, Vec<u8>)>,
    /// lowercase `/`-separated name -> why the entry is not available
    unreadable: std::collections::BTreeMap<String, String>,
}

impl MemoryIncludes {
    /// An include source over `files` (name, content) of an archive with the given `prefix` (may be empty).
    /// The first of several entries with the same name (ignoring case and separator) wins.
    #[must_use]
    pub fn new(prefix: &str, files: Vec<(String, Vec<u8>)>) -> Self {
        let mut map = std::collections::BTreeMap::new();
        for (name, content) in files {
            map.entry(name.replace('\\', "/").to_lowercase())
                .or_insert((name, content));
        }
        MemoryIncludes {
            prefix: prefix.replace('\\', "/").trim_matches('/').to_lowercase(),
            files: map,
            unreadable: std::collections::BTreeMap::new(),
        }
    }

    /// Adds entries (name, reason) that exist in the archive but could not be read. An `#include` of one of
    /// them fails with the reason instead of "not found". A name that is also a readable file stays readable.
    #[must_use]
    pub fn with_unreadable(mut self, entries: Vec<(String, String)>) -> Self {
        for (name, reason) in entries {
            self.unreadable
                .entry(name.replace('\\', "/").to_lowercase())
                .or_insert(reason);
        }
        self
    }

    /// The content of the entry `name` (ignoring case and separator), if it was read.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&[u8]> {
        self.files
            .get(&name.replace('\\', "/").to_lowercase())
            .map(|(_, content)| content.as_slice())
    }

    /// The file `include_path` names when included from the entry `origin` (an entry name, or `None` for
    /// the top level).
    fn find(
        &self,
        include_path: &str,
        origin: Option<&Path>,
        line: u32,
    ) -> Result<(&str, &[u8]), Error> {
        let bad = |why: &str| {
            error!(
                "Include \"{}\" is not allowed ({why}); only files of the same PBO can be included.",
                printable(include_path)
            )
        };
        let key = if let Some(rest) = include_path.strip_prefix('\\') {
            let rest = rest.replace('\\', "/").to_lowercase();
            let below = if self.prefix.is_empty() {
                None
            } else {
                rest.strip_prefix(&self.prefix)
                    .and_then(|r| r.strip_prefix('/'))
            };
            let Some(below) = below else {
                return Err(include_not_found(include_path, origin, line));
            };
            if crate::pbo::safe_relative_path(below).is_none() {
                return Err(bad("invalid path"));
            }
            below.to_string()
        } else {
            let folder = origin
                .map(|o| o.to_string_lossy().replace('\\', "/").to_lowercase())
                .and_then(|o| o.rsplit_once('/').map(|(f, _)| f.to_string()));
            let mut parts: Vec<String> = folder
                .iter()
                .flat_map(|f| f.split('/'))
                .map(str::to_string)
                .collect();
            if include_path.starts_with('/') {
                return Err(bad("absolute, drive or invalid path"));
            }
            for component in include_path.replace('\\', "/").to_lowercase().split('/') {
                if component == ".." {
                    if parts.pop().is_none() {
                        return Err(bad("`..` leaves the PBO"));
                    }
                } else if crate::pbo::safe_relative_path(component).is_some() {
                    parts.push(component.to_string());
                } else {
                    return Err(bad("absolute, drive or invalid path"));
                }
            }
            parts.join("/")
        };
        if let Some((name, content)) = self.files.get(&key) {
            return Ok((name.as_str(), content.as_slice()));
        }
        if let Some(reason) = self.unreadable.get(&key) {
            return Err(match origin {
                Some(o) => error!(
                    "Include \"{}\" (from \"{}:{line}\") cannot be read: {reason}",
                    printable(include_path),
                    printable(&o.display().to_string())
                ),
                None => error!(
                    "Include \"{}\" (line {line}) cannot be read: {reason}",
                    printable(include_path)
                ),
            });
        }
        Err(include_not_found(include_path, origin, line))
    }
}

impl IncludeFolders {
    /// Folders searched recursively, none checked directly.
    #[must_use]
    pub fn new(search: Vec<PathBuf>) -> Self {
        IncludeFolders {
            search,
            direct: Vec::new(),
            memory: None,
        }
    }

    /// Takes the includes from `memory` only; the file system is not read.
    #[must_use]
    pub fn with_memory(mut self, memory: MemoryIncludes) -> Self {
        self.memory = Some(memory);
        self
    }

    /// Adds folders that are only checked directly.
    #[must_use]
    pub fn with_direct(mut self, direct: Vec<PathBuf>) -> Self {
        self.direct = direct;
        self
    }
}

/// Struct for additional information about preprocessor output. Contains import stack used for
/// loop detection and the origins of all the lines in the output.
#[derive(Debug)]
pub struct PreprocessInfo {
    /// For every line in the output, `line_origins` contains a line number (starting at 1) and a
    /// `PathBuf` to the file where the line was found. The path may be `None` if the line was in the
    /// original input to `preprocess` and `origin` was not given.
    pub(crate) line_origins: Vec<(u32, Option<PathBuf>)>,
    import_stack: Vec<PathBuf>,
    /// Number of `#include`s currently being processed (the root file does not count).
    include_depth: usize,
    /// Tokens produced by macro expansion so far, over the file and its includes.
    expanded: usize,
    /// Bytes of token text copied by macro expansion so far.
    expanded_bytes: usize,
    /// Macro resolution steps taken so far, over the file and its includes.
    steps: usize,
    /// `#include`s processed so far, over the file and its includes.
    includes: usize,
    /// Bytes of the in-memory includes read so far.
    include_bytes: usize,
    /// Whether the last source line of the file is an entry line (not empty, a directive, a comment or
    /// inside an unterminated comment), so that the line end the preprocessor adds is not one of the source.
    pub(crate) ends_in_entry: bool,
}

impl PreprocessInfo {
    /// For every line in the output, a line number (starting at 1) and the file where the line was
    /// found. The path is `None` if the line was in the original input to `preprocess` and no
    /// path was given.
    #[must_use]
    pub fn line_origins(&self) -> &[(u32, Option<PathBuf>)] {
        &self.line_origins
    }
}

/// Maximum nesting of brackets in the grammars: macro argument parentheses, config classes, config
/// arrays and `__EVAL` parentheses and operator chains. Deeper input is a parse error, not a stack
/// overflow. The generated parsers use up to about 5 KiB of stack per level in a debug build, so this
/// fits the 1 MiB main-thread stack of Windows (`tests/nesting.rs` runs on such a stack); it equals the
/// limit of the rapified reader (`MAX_RAPIFIED_DEPTH`), and real configs nest fewer than 20 levels.
pub(crate) const MAX_NESTING_DEPTH: usize = 128;

/// The error for input nested deeper than [`MAX_NESTING_DEPTH`].
pub(crate) fn nesting_error() -> Error {
    error!("Nesting is deeper than {MAX_NESTING_DEPTH} levels")
}

/// Runs a grammar entry point with a fresh nesting flag; a parse that hit the limit is the nesting
/// error, whatever the parser reported.
fn parse_checked<T, E>(
    parse: impl FnOnce(&Cell<bool>) -> Result<T, E>,
    on_error: impl FnOnce(E) -> Error,
) -> Result<T, Error> {
    let deep = Cell::new(false);
    let result = parse(&deep);
    if deep.get() {
        return Err(nesting_error());
    }
    result.map_err(on_error)
}

/// Maximum nesting of macro expansions; deeper input is an error, not a stack overflow.
const MAX_EXPANSION_DEPTH: usize = 64;

/// Maximum tokens one source line may produce while its macros expand (every token copied at any level
/// counts). Real configs stay far below it (see the #57 measurements in the README); an exponential
/// definition chain hits it after a few milliseconds instead of exhausting memory.
const MAX_LINE_EXPANSION: usize = 500_000;

/// Maximum tokens all lines of one `preprocess` call (the includes count too) may produce.
const MAX_FILE_EXPANSION: usize = 16_000_000;

/// Maximum bytes of token text one source line may copy while its macros expand. Stringification
/// collapses many tokens into one long string, so the token count alone does not bound memory.
const MAX_LINE_BYTES: usize = 64 << 20;

/// Maximum bytes copied by the lines of one `preprocess` call (the includes count too).
const MAX_FILE_BYTES: usize = 512 << 20;

// Both step caps are 100,000: real configs need at most 34 calls on a line and far fewer than 100,000 over a
// file, so one number is easy to remember. The line cap still has a use: it stops a single line early (and names
// it) instead of letting that line run up to the file cap.
/// Maximum macro resolution steps (every call of a defined macro, argument pre-expansion included) of one source line. A step
/// that produces nothing still costs, so expansion that drops its output cannot run exponentially (#59).
const MAX_LINE_STEPS: usize = 100_000;

/// Maximum macro resolution steps of all lines of one `preprocess` call (the includes count too). The line cap alone lets
/// thousands of cheap-looking lines add up to tens of seconds (#64).
const MAX_FILE_STEPS: usize = 100_000;

/// Counts the tokens and bytes macro expansion produces, so that exponential expansion stops early.
struct Budget {
    tokens: usize,
    bytes: usize,
    steps: usize,
    /// Steps the earlier lines of the `preprocess` call took.
    file_steps: usize,
}

impl Budget {
    /// A budget for one line; `file_steps` are the steps the earlier lines of the call already took.
    fn new(file_steps: usize) -> Budget {
        Budget {
            tokens: 0,
            bytes: 0,
            steps: 0,
            file_steps,
        }
    }

    /// Charges one resolution step of the macro `name`.
    fn step(&mut self, name: &str) -> Result<(), Error> {
        self.steps = self.steps.saturating_add(1);
        if self.steps > MAX_LINE_STEPS {
            return Err(error!(
                "Macro \"{}\" expands to more than {MAX_LINE_STEPS} macro calls in one line",
                printable(name)
            ));
        }
        if self.file_steps.saturating_add(self.steps) > MAX_FILE_STEPS {
            return Err(error!(
                "The file and its includes reach more than {MAX_FILE_STEPS} macro calls (at macro \"{}\")",
                printable(name)
            ));
        }
        self.spend(1, name.len().max(1), name)
    }

    /// Charges `tokens` tokens and `bytes` bytes of text, produced by the expansion of `name`.
    fn spend(&mut self, tokens: usize, bytes: usize, name: &str) -> Result<(), Error> {
        self.tokens = self.tokens.saturating_add(tokens);
        self.bytes = self.bytes.saturating_add(bytes);
        if self.tokens > MAX_LINE_EXPANSION || self.bytes > MAX_LINE_BYTES {
            return Err(error!(
                "Macro \"{}\" expands to more than {MAX_LINE_EXPANSION} tokens or {MAX_LINE_BYTES} bytes in one line",
                printable(name)
            ));
        }
        Ok(())
    }
}

/// The bytes a token costs: its text, at least 1.
fn token_bytes(token: &Token) -> usize {
    match token {
        Token::RegularToken(s) | Token::NewlineToken(s, _) => s.len().max(1),
        Token::MacroToken(m) => m.original.len().max(1),
        Token::CommentToken(_) | Token::OpenCommentToken(_) | Token::ConcatToken => 1,
    }
}

/// Maximum nesting of `#include`s; deeper input is an error, not a stack overflow.
const MAX_INCLUDE_DEPTH: usize = 32;

/// Maximum `#include`s processed by one `preprocess` call, nested includes counted (every inclusion of
/// the same file counts). Bounds exponential include fan-out (#60), which no token budget sees.
const MAX_INCLUDES: usize = 10_000;

/// Maximum bytes of in-memory includes ([`MemoryIncludes`]) one `preprocess` call reads, every inclusion counted.
const MAX_INCLUDE_BYTES: usize = 64 << 20;

/// The file as the cycle check compares it: canonical when the file system can say, else as given.
fn identity(path: &Path, memory: bool) -> PathBuf {
    if memory {
        // an archive entry name is not a file system path
        return PathBuf::from(path.to_string_lossy().replace('\\', "/").to_lowercase());
    }
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

fn parse_macro(input: &str) -> Result<Macro, Error> {
    let without_original = parse_checked(
        |deep| preprocess_grammar::macro_proper(input, deep, false),
        |e| error!("Failed to parse macro invocation \"{input}\": {e}"),
    )?;

    Ok(Macro {
        original: String::from(input),
        ..without_original
    })
}

impl Clone for Macro {
    fn clone(&self) -> Macro {
        Macro {
            name: self.name.clone(),
            arguments: self.arguments.clone(),
            original: self.original.clone(),
            quoted: self.quoted,
        }
    }
}

impl Clone for Token {
    fn clone(&self) -> Token {
        match self {
            Token::RegularToken(s) => Token::RegularToken(s.clone()),
            Token::NewlineToken(s, n) => Token::NewlineToken(s.clone(), *n),
            Token::MacroToken(m) => Token::MacroToken(m.clone()),
            Token::CommentToken(n) => Token::CommentToken(*n),
            Token::OpenCommentToken(n) => Token::OpenCommentToken(*n),
            Token::ConcatToken => Token::ConcatToken,
        }
    }
}

impl Definition {
    fn value(
        &self,
        arguments: Option<&[String]>,
        def_map: &HashMap<String, Definition>,
        stack: &[Definition],
        depth: usize,
        mismatches: &mut Vec<String>,
        budget: &mut Budget,
    ) -> Result<Option<Vec<Token>>, Error> {
        let params = self.parameters.clone().unwrap_or_default();
        let args = arguments.unwrap_or(&[]);

        let empty_call = params.is_empty()
            && args.len() == 1
            && args.first().is_some_and(|a| a.trim().is_empty());
        if params.len() != args.len() && !empty_call {
            return Ok(None);
        }

        let mut tokens = self.value.clone();

        if stack.iter().any(|d| d.name == self.name) {
            return Ok(Some(tokens));
        }

        let mut stack_new: Vec<Definition> = stack.to_vec();
        stack_new.push(self.clone());

        if params.is_empty() {
            tokens = Macro::resolve_all(&tokens, def_map, &stack_new, depth, mismatches, budget)?;
        } else {
            let mut local_map: HashMap<String, Definition> = HashMap::new();

            for (key, value) in def_map {
                local_map.insert(key.clone(), value.clone());
            }

            // @todo: handle these errors properly
            for (param, arg) in params.iter().zip(args.iter()) {
                let mut tokens = parse_checked(
                    |deep| preprocess_grammar::tokens(arg, deep, false),
                    |e| error!("Failed to parse macro argument: {e}"),
                )?;
                let stack: Vec<Definition> = Vec::new();
                tokens = Macro::resolve_all(&tokens, def_map, &stack, depth, mismatches, budget)?;

                local_map.insert(
                    param.clone(),
                    Definition {
                        name: param.clone(),
                        parameters: None,
                        value: tokens,
                        local: true,
                    },
                );
            }

            tokens =
                Macro::resolve_all(&tokens, &local_map, &stack_new, depth, mismatches, budget)?;
        }

        Ok(Some(tokens))
    }
}

impl Macro {
    fn resolve_pseudoargs(
        &self,
        def_map: &HashMap<String, Definition>,
        stack: &[Definition],
        depth: usize,
        mismatches: &mut Vec<String>,
        budget: &mut Budget,
    ) -> Result<Vec<Token>, Error> {
        let mut tokens: Vec<Token> = Vec::new();
        tokens.push(Token::RegularToken(self.name.clone()));

        if self.arguments.is_none() {
            return Ok(tokens);
        }

        let (_, without_name) = self.original.split_at(self.name.len());
        let mut arg_tokens = parse_checked(
            |deep| preprocess_grammar::tokens(without_name, deep, false),
            |e| error!("Failed to parse macro arguments: {e}"),
        )?;

        arg_tokens = Macro::resolve_all(&arg_tokens, def_map, stack, depth, mismatches, budget)?;
        for t in arg_tokens {
            tokens.push(t);
        }

        Ok(tokens)
    }

    fn resolve(
        &self,
        def_map: &HashMap<String, Definition>,
        stack: &[Definition],
        depth: usize,
        mismatches: &mut Vec<String>,
        budget: &mut Budget,
    ) -> Result<Vec<Token>, Error> {
        // Every recursive path (body, argument pre-expansion, pseudo-arguments, local parameters) goes through
        // here, so this one counter bounds them all; the `stack` check alone is reset by argument pre-expansion.
        if depth >= MAX_EXPANSION_DEPTH {
            return Err(error!(
                "Macro \"{}\" expands too deep (limit {MAX_EXPANSION_DEPTH})",
                printable(&self.name)
            ));
        }
        let depth = depth + 1;
        match def_map.get(&self.name) {
            Some(def) => {
                budget.step(&self.name)?;
                if let Some(args) = &self.arguments {
                    if def.parameters.is_none() {
                        // Object-like macro followed by parentheses: expand it, keep the parentheses.
                        let mut tokens = def
                            .value(None, def_map, stack, depth, mismatches, budget)?
                            .unwrap_or_default();
                        let (_, rest) = self.original.split_at(self.name.len());
                        let mut rest_tokens = parse_checked(
                            |deep| preprocess_grammar::tokens(rest, deep, false),
                            |e| error!("Failed to parse macro arguments: {e}"),
                        )?;
                        rest_tokens = Macro::resolve_all(
                            &rest_tokens,
                            def_map,
                            stack,
                            depth,
                            mismatches,
                            budget,
                        )?;
                        tokens.extend(rest_tokens);
                        return Ok(tokens);
                    }

                    let expected = def.parameters.as_ref().map_or(0, std::vec::Vec::len);
                    let got = if expected == 0
                        && args.len() == 1
                        && args.first().is_some_and(|a| a.trim().is_empty())
                    {
                        0
                    } else {
                        args.len()
                    };
                    if got != expected {
                        let msg = format!(
                            "Macro \"{}\" expects {} argument(s), got {}",
                            printable(&self.name),
                            expected,
                            got
                        );
                        mismatches.push(msg);
                        return Ok(if self.quoted {
                            vec![Token::NewlineToken("\"\"".to_string(), 0)]
                        } else {
                            Vec::new()
                        });
                    }
                }

                let value = def.value(
                    self.arguments.as_deref(),
                    def_map,
                    stack,
                    depth,
                    mismatches,
                    budget,
                )?;

                if !def.local && self.quoted {
                    // @todo: complain
                }

                if let Some(tokens) = value {
                    if self.quoted {
                        // charge before `concat` allocates the collapsed string
                        budget.spend(
                            tokens.len(),
                            tokens.iter().map(token_bytes).sum(),
                            &self.name,
                        )?;
                        let (concatted, newlines) = Token::concat(&tokens);
                        let mut tokens: Vec<Token> = Vec::new();
                        tokens.push(Token::NewlineToken(
                            format!("\"{}\"", concatted.trim()),
                            newlines,
                        ));
                        Ok(tokens)
                    } else {
                        Ok(tokens)
                    }
                } else {
                    self.resolve_pseudoargs(def_map, stack, depth, mismatches, budget)
                }
            }
            None => self.resolve_pseudoargs(def_map, stack, depth, mismatches, budget),
        }
    }

    fn resolve_all(
        tokens: &[Token],
        def_map: &HashMap<String, Definition>,
        stack: &[Definition],
        depth: usize,
        mismatches: &mut Vec<String>,
        budget: &mut Budget,
    ) -> Result<Vec<Token>, Error> {
        let mut result: Vec<Token> = Vec::new();

        for token in tokens {
            if let Token::MacroToken(m) = token {
                let resolved = m.resolve(def_map, stack, depth, mismatches, budget)?;
                budget.spend(
                    resolved.len(),
                    resolved.iter().map(token_bytes).sum(),
                    &m.name,
                )?;
                result.extend(resolved);
            } else {
                budget.spend(
                    1,
                    token_bytes(token),
                    stack.last().map_or("", |d| d.name.as_str()),
                )?;
                result.push(token.clone());
            }
        }

        Ok(result)
    }
}

impl Token {
    fn concat(tokens: &[Token]) -> (String, u32) {
        let mut output = String::new();
        let mut newlines = 0;

        for token in tokens {
            match token {
                Token::RegularToken(s) => {
                    output += s;
                }
                Token::NewlineToken(s, n) => {
                    output += s;
                    newlines += n;
                }
                Token::MacroToken(m) => {
                    output += &m.original;
                }
                Token::CommentToken(n) | Token::OpenCommentToken(n) => {
                    newlines += n;
                }
                Token::ConcatToken => {}
            }
        }

        (output, newlines)
    }
}

/// The source newlines of tokens, counted from the source and never from an expansion: `(inline,
/// continuations)`. `inline` are those of strings and comments (a string inside a macro call is counted
/// once), `continuations` the `\`-newlines outside strings, wherever they sit.
fn source_newlines(tokens: &[Token]) -> (u32, u32) {
    let (mut inline, mut continuations) = (0u32, 0u32);
    for token in tokens {
        match token {
            Token::NewlineToken(_, n) | Token::CommentToken(n) | Token::OpenCommentToken(n) => {
                inline = inline.saturating_add(*n);
            }
            Token::MacroToken(m) => {
                let mut in_string = false;
                let mut prev = ' ';
                for c in m.original.chars() {
                    match c {
                        '"' => in_string = !in_string,
                        '\n' if in_string => inline = inline.saturating_add(1),
                        '\n' if prev == '\\' => continuations = continuations.saturating_add(1),
                        _ => {}
                    }
                    prev = c;
                }
            }
            Token::RegularToken(s) => {
                let n = u32::try_from(s.matches("\\\n").count()).unwrap_or(u32::MAX);
                continuations = continuations.saturating_add(n);
            }
            Token::ConcatToken => {}
        }
    }
    (inline, continuations)
}

/// All source newlines of tokens that are not expanded.
fn skipped_newlines(tokens: &[Token]) -> u32 {
    let (inline, continuations) = source_newlines(tokens);
    inline.saturating_add(continuations)
}

/// Reads the first line of a `$PBOPREFIX$` file.
///
/// # Errors
///
/// Returns an error if the file cannot be opened or read.
fn read_prefix(prefix_path: &Path) -> Result<String, Error> {
    let mut content = String::new();
    File::open(prefix_path)?.read_to_string(&mut content)?;

    Ok(content.lines().next().unwrap_or_default().to_string())
}

/// Returns the path seperator used on the current operating system
#[must_use]
pub(crate) fn pathsep() -> &'static str {
    if cfg!(windows) { "\\" } else { "/" }
}

fn names_equal(a: &OsStr, b: &OsStr, ci: bool) -> bool {
    if ci {
        a.to_string_lossy()
            .eq_ignore_ascii_case(&b.to_string_lossy())
    } else {
        a == b
    }
}

/// Whether two paths to the same file differ in the case of any component.
/// A case-insensitive filesystem (Windows) can open a path whose case does not
/// match the file on disk; comparing the components byte-wise detects that.
fn differs_in_case(a: &Path, b: &Path) -> bool {
    let (mut a, mut b) = (a.components(), b.components());
    loop {
        match (a.next(), b.next()) {
            (None, None) => return false,
            (Some(x), Some(y)) if x.as_os_str() == y.as_os_str() => {}
            _ => return true,
        }
    }
}

/// Resolves `relative` below `base`, comparing each component ASCII-case-insensitively.
/// An exact match is preferred over a case-insensitive one at every level.
///
/// The names always come from the directory entries, never from `exists()`
/// probes: on a case-insensitive filesystem (Windows) those succeed for any
/// casing and would hide the name the file has on disk.
fn resolve_case_insensitive(base: &Path, relative: &Path) -> Option<PathBuf> {
    let mut current = base.to_path_buf();
    for component in relative.components() {
        let Component::Normal(name) = component else {
            continue;
        };
        let mut exact = None;
        let mut ignoring_case = None;
        for entry in read_dir(&current).ok()?.filter_map(std::result::Result::ok) {
            if exact.is_none() && names_equal(&entry.file_name(), name, false) {
                exact = Some(entry);
            } else if ignoring_case.is_none() && names_equal(&entry.file_name(), name, true) {
                ignoring_case = Some(entry);
            }
        }
        current = exact.or(ignoring_case)?.path();
    }
    Some(current)
}

fn matches_include_path(path: &Path, include_path: &str, ci: bool) -> bool {
    let include_pathbuf = PathBuf::from(&include_path.replace('\\', pathsep()));

    match (path.file_name(), include_pathbuf.file_name()) {
        (Some(a), Some(b)) if names_equal(a, b, ci) => {}
        _ => return false,
    }

    for parent in path.ancestors() {
        if parent.is_file() {
            continue;
        }

        let prefixpath = parent.join("$PBOPREFIX$");
        if !prefixpath.is_file() {
            continue;
        }

        // an unreadable prefix file cannot match the include; skip it instead of failing
        let Ok(mut prefix) = read_prefix(&prefixpath) else {
            continue;
        };

        prefix = if !prefix.is_empty() && !prefix.starts_with('\\') {
            format!("\\{prefix}")
        } else {
            prefix
        };

        let prefix_pathbuf = PathBuf::from(prefix.replace('\\', pathsep()));

        let Ok(relative) = path.strip_prefix(parent) else {
            continue;
        };
        let test_path = prefix_pathbuf.join(relative);

        let (mut a, mut b) = (test_path.components(), include_pathbuf.components());
        loop {
            match (a.next(), b.next()) {
                (None, None) => return true,
                (Some(x), Some(y)) if names_equal(x.as_os_str(), y.as_os_str(), ci) => {}
                _ => break,
            }
        }
    }

    false
}

/// Maximum directory entries one recursive include search visits below one folder before it gives up with an error
/// (#66). Real trees are far below it (a 109,000 entry `P:` drive copy); it stops a search that wandered into a
/// whole disk.
const MAX_SEARCH_ENTRIES: usize = 1_000_000;

/// State of one recursive include search below `root`.
struct Walk<'a> {
    include_path: &'a str,
    root: &'a Path,
    ci: bool,
    visited: usize,
    limit: usize,
    /// Canonical paths of the directories entered so far: none is entered twice, so symlink loops and several
    /// links to one directory cost nothing.
    seen: std::collections::BTreeSet<PathBuf>,
}

impl Walk<'_> {
    /// Whether the directory symlink `path` must not be followed: its target is outside the search root or cannot
    /// be resolved. (Loops are caught by the set of directories already entered.)
    fn skips_link(&self, path: &Path) -> bool {
        path.canonicalize()
            .map_or(true, |target| !target.starts_with(self.root))
    }

    fn search(&mut self, directory: &Path) -> Result<Option<PathBuf>, Error> {
        // an unresolvable directory is skipped like an unreadable one
        let Ok(canonical) = directory.canonicalize() else {
            return Ok(None);
        };
        if !self.seen.insert(canonical) {
            return Ok(None);
        }
        // unreadable directories are skipped
        if let Ok(entries) = read_dir(directory) {
            for entry in entries.filter_map(std::result::Result::ok) {
                self.visited += 1;
                if self.visited > self.limit {
                    return Err(error!(
                        "Include \"{}\" not found: the search below \"{}\" stopped after {} entries",
                        printable(self.include_path),
                        printable(&self.root.display().to_string()),
                        self.limit
                    ));
                }
                let path = entry.path();
                let is_link = entry.file_type().is_ok_and(|t| t.is_symlink());
                if path.is_dir() {
                    if path.file_name() == Some(OsStr::new(".git")) {
                        continue;
                    }
                    if is_link && self.skips_link(&path) {
                        continue;
                    }

                    if let Some(path) = self.search(&path)? {
                        return Ok(Some(path));
                    }
                } else if matches_include_path(&path, self.include_path, self.ci) {
                    return Ok(Some(path));
                }
            }
        }

        Ok(lookup_directly(self.include_path, directory, self.ci))
    }
}

/// The include `include_path` at exactly `directory/<include path>`, without looking at any other folder.
fn lookup_directly(include_path: &str, directory: &Path, ci: bool) -> Option<PathBuf> {
    let relative = PathBuf::from(
        include_path
            .trim_start_matches('\\')
            .replace('\\', pathsep()),
    );
    let direct_pathbuf = if ci {
        resolve_case_insensitive(directory, &relative)?
    } else {
        // A case-insensitive filesystem (Windows) opens the joined path even
        // when the case does not match; leave such matches to the ci pass,
        // which reports them, instead of returning them silently.
        let joined = directory.join(&relative);
        if !joined.is_file() {
            return None;
        }
        match resolve_case_insensitive(directory, &relative) {
            Some(found) if differs_in_case(&joined, &found) => return None,
            // the directories cannot be read, so the case cannot be checked
            _ => return Some(joined),
        }
    };

    if direct_pathbuf.is_file() {
        return Some(direct_pathbuf);
    }

    None
}

fn canonicalize(path: &Path) -> PathBuf {
    let mut result = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                result.pop();
            }
            _ => {
                result.push(component);
            }
        }
    }
    result
}

fn include_not_found(include_path: &str, origin: Option<&Path>, line: u32) -> Error {
    match origin {
        Some(origin_path) => error!(
            "File \"{}\" included from \"{}:{}\" not found.",
            printable(include_path),
            printable(&origin_path.display().to_string()),
            line
        ),
        None => error!(
            "Included file \"{}\" (line {}) not found.",
            printable(include_path),
            line
        ),
    }
}

fn warn_include_case(include_path: &str, found: &Path, warnings: &mut dyn WarningSink) {
    warnings.warn(Warning::new(
        Some("include-case"),
        format!(
            "Include \"{}\" only matched \"{}\" ignoring case.",
            printable(include_path),
            printable(&found.display().to_string())
        ),
    ));
}

fn find_include_file(
    include_path: &str,
    origin: Option<&Path>,
    folders: &IncludeFolders,
    line: u32,
    warnings: &mut dyn WarningSink,
) -> Result<PathBuf, Error> {
    if include_path.starts_with('\\') {
        let canonical = |search_path: &PathBuf| {
            search_path.canonicalize().map_err(|e| {
                error!(
                    "Include folder \"{}\" is not usable: {}",
                    search_path.display(),
                    e
                )
            })
        };
        let roots = folders
            .search
            .iter()
            .map(canonical)
            .collect::<Result<Vec<PathBuf>, Error>>()?;
        let direct = folders
            .direct
            .iter()
            .map(canonical)
            .collect::<Result<Vec<PathBuf>, Error>>()?;

        for ci in [false, true] {
            let mut found = None;
            for root in &roots {
                let mut walk = Walk {
                    include_path,
                    root,
                    ci,
                    visited: 0,
                    limit: MAX_SEARCH_ENTRIES,
                    seen: std::collections::BTreeSet::new(),
                };
                found = walk.search(root)?;
                if found.is_some() {
                    break;
                }
            }
            if found.is_none() {
                found = direct
                    .iter()
                    .find_map(|root| lookup_directly(include_path, root, ci));
            }
            if let Some(file_path) = found {
                if ci {
                    warn_include_case(include_path, &file_path, warnings);
                }
                return Ok(file_path);
            }
        }

        Err(include_not_found(include_path, origin, line))
    } else {
        let mut path = PathBuf::from(include_path.replace('\\', pathsep()));

        if let Some(origin_path) = origin {
            let absolute = PathBuf::from(origin_path).canonicalize()?;
            let Some(origin_dir) = absolute.parent() else {
                return Err(error!(
                    "Include origin \"{}\" has no parent directory.",
                    printable(&origin_path.display().to_string())
                ));
            };
            path = origin_dir.join(path);
        } else {
            path = current_dir()?.join(path);
        }

        let absolute = canonicalize(&path);
        let root: PathBuf = absolute
            .components()
            .take_while(|c| !matches!(c, Component::Normal(_)))
            .collect();
        let relative: PathBuf = absolute
            .components()
            .skip_while(|c| !matches!(c, Component::Normal(_)))
            .collect();

        if absolute.is_file() {
            // A case-insensitive filesystem (Windows) opens the probe even when
            // the case does not match the file on disk; check the components
            // against the directory entries so the warning fires there too.
            if let Some(found) = resolve_case_insensitive(&root, &relative)
                && differs_in_case(&absolute, &found)
            {
                warn_include_case(include_path, &found, warnings);
            }
            return Ok(absolute);
        }

        // case-insensitive fallback for case-sensitive filesystems
        match resolve_case_insensitive(&root, &relative) {
            Some(found) if found.is_file() => {
                warn_include_case(include_path, &found, warnings);
                Ok(found)
            }
            _ => Err(include_not_found(include_path, origin, line)),
        }
    }
}

/// The warning for a `/*` that is never closed (`line` is where the comment starts).
fn warn_unterminated(origin: Option<&Path>, line: u32, warnings: &mut dyn WarningSink) {
    let mut warning = Warning::new(
        Some("unterminated-comment"),
        "A /* comment is never closed; the rest of the file is ignored.",
    )
    .at_line(line);
    if let Some(origin) = origin {
        warning = warning.in_file(origin.display().to_string());
    }
    warnings.warn(warning);
}

#[expect(
    clippy::too_many_lines,
    reason = "one branch per directive keeps the preprocessor loop readable"
)]
fn preprocess_rec(
    input: &str,
    origin: Option<&Path>,
    definition_map: &mut HashMap<String, Definition>,
    info: &mut PreprocessInfo,
    includefolders: &IncludeFolders,
    warnings: &mut dyn WarningSink,
) -> Result<String, Error> {
    // CRLF and classic Mac (lone CR) newlines
    let input = input.replace("\r\n", "\n").replace('\r', "\n");
    let deep = Cell::new(false);
    let parsed = preprocess_grammar::file(&input, &deep, true);
    if deep.get() {
        return Err(nesting_error());
    }
    let lines = PreprocessParseErrorExt::format_error(parsed, origin, &input)?;
    let mut output = String::new();
    let mut original_lineno = 1;
    let mut level = 0;
    let mut level_true = 0;
    let mut last_is_entry = false;

    for line in lines {
        last_is_entry = false;
        // Every path leaves this block (never `continue`), so the line counter below always runs (#63).
        'line: {
            match line {
                Line::DirectiveLine(dir, newlines, open) => {
                    if open {
                        warn_unterminated(origin, original_lineno, warnings);
                    }
                    original_lineno += newlines;

                    match dir {
                        Directive::IncludeDirective(path) => {
                            if level > level_true {
                                break 'line;
                            }

                            let memory = includefolders.memory.as_ref();
                            let (file_path, in_memory) = if let Some(m) = memory {
                                let (name, content) = m.find(&path, origin, original_lineno)?;
                                (PathBuf::from(name), Some(content))
                            } else {
                                (
                                    find_include_file(
                                        &path,
                                        origin,
                                        includefolders,
                                        original_lineno,
                                        warnings,
                                    )?,
                                    None,
                                )
                            };

                            let is_mem = memory.is_some();
                            let wanted = identity(&file_path, is_mem);
                            if info
                                .import_stack
                                .iter()
                                .any(|p| identity(p, is_mem) == wanted)
                            {
                                let chain: Vec<String> = info
                                    .import_stack
                                    .iter()
                                    .chain(std::iter::once(&file_path))
                                    .map(|p| printable(&p.display().to_string()))
                                    .collect();
                                return Err(error!("Include cycle: {}", chain.join(" -> ")));
                            }
                            if info.include_depth >= MAX_INCLUDE_DEPTH {
                                return Err(error!(
                                    "Include \"{}\" nests too deep (limit {MAX_INCLUDE_DEPTH})",
                                    printable(&path)
                                ));
                            }

                            info.includes += 1;
                            if info.includes > MAX_INCLUDES {
                                return Err(error!(
                                    "Include \"{}\" is the {}th include; the limit is {MAX_INCLUDES} per preprocess call",
                                    printable(&path),
                                    info.includes
                                ));
                            }

                            let content = if let Some(bytes) = in_memory {
                                info.include_bytes = info.include_bytes.saturating_add(bytes.len());
                                if info.include_bytes > MAX_INCLUDE_BYTES {
                                    return Err(error!(
                                        "Include \"{}\" brings the included files past {MAX_INCLUDE_BYTES} bytes",
                                        printable(&path)
                                    ));
                                }
                                String::from_utf8(bytes.to_vec()).map_err(|e| {
                                    error!(
                                        "Include \"{}\" is not valid UTF-8: {e}",
                                        printable(&path)
                                    )
                                })?
                            } else {
                                let mut content = String::new();
                                File::open(&file_path)?.read_to_string(&mut content)?;
                                content
                            };
                            info.import_stack.push(file_path.clone());
                            info.include_depth += 1;
                            let result = preprocess_rec(
                                &content,
                                Some(&file_path),
                                definition_map,
                                info,
                                includefolders,
                                warnings,
                            )
                            .prepend_error(format!(
                                "Failed to preprocess include \"{}\":",
                                printable(&path)
                            ))?;

                            info.import_stack.pop();
                            info.include_depth -= 1;

                            output += &result;
                        }
                        Directive::DefineDirective(def) => {
                            if let Some(at) = def
                                .value
                                .iter()
                                .position(|t| matches!(t, Token::OpenCommentToken(_)))
                            {
                                let before = def.value.get(..at).unwrap_or_default();
                                warn_unterminated(
                                    origin,
                                    original_lineno.saturating_add(skipped_newlines(before)),
                                    warnings,
                                );
                            }
                            original_lineno += skipped_newlines(&def.value);

                            if level > level_true {
                                break 'line;
                            }

                            if definition_map.remove(&def.name).is_some() {
                                // @todo: warn about redefine
                            }

                            definition_map.insert(def.name.clone(), def);
                        }
                        Directive::UndefDirective(name) => {
                            if level > level_true {
                                break 'line;
                            }

                            definition_map.remove(&name);
                        }
                        Directive::IfDefDirective(name) => {
                            level_true += i32::from(
                                level_true == level && definition_map.contains_key(&name),
                            );
                            level += 1;
                        }
                        Directive::IfNDefDirective(name) => {
                            level_true += i32::from(
                                level_true == level && !definition_map.contains_key(&name),
                            );
                            level += 1;
                        }
                        Directive::ElseDirective => {
                            if level_true + 1 == level {
                                level_true = level;
                            } else if level_true == level {
                                level_true -= 1;
                            }
                        }
                        Directive::EndIfDirective => {
                            if level == 0 {
                                return Err(error!("#endif without matching #ifdef/#ifndef"));
                            }
                            level -= 1;
                            if level_true > level {
                                level_true -= 1;
                            }
                        }
                    }
                }
                Line::TokenLine(tokens) => {
                    // Found after the parse, so a backtracked path never warns; also in a disabled branch,
                    // because the comment swallows the rest of the file there too.
                    if let Some(at) = tokens
                        .iter()
                        .position(|t| matches!(t, Token::OpenCommentToken(_)))
                    {
                        let before = tokens.get(..at).unwrap_or_default();
                        warn_unterminated(
                            origin,
                            original_lineno.saturating_add(skipped_newlines(before)),
                            warnings,
                        );
                    }
                    if level > level_true {
                        // A disabled line is never expanded (#61): it can neither error nor cost time.
                        original_lineno += skipped_newlines(&tokens);
                        break 'line;
                    }
                    last_is_entry = !tokens
                        .iter()
                        .any(|t| matches!(t, Token::OpenCommentToken(_)))
                        && tokens.iter().any(|t| match t {
                            Token::RegularToken(s) => !s.trim().is_empty(),
                            Token::NewlineToken(..) | Token::MacroToken(_) => true,
                            _ => false,
                        });
                    let stack: Vec<Definition> = Vec::new();
                    let mut mismatches: Vec<String> = Vec::new();
                    let mut budget = Budget::new(info.steps);
                    let resolved = Macro::resolve_all(
                        &tokens,
                        definition_map,
                        &stack,
                        0,
                        &mut mismatches,
                        &mut budget,
                    )
                    .prepend_error("Failed to resolve macros:");
                    let resolved = resolved?;
                    info.steps = info.steps.saturating_add(budget.steps);
                    info.expanded = info.expanded.saturating_add(budget.tokens);
                    info.expanded_bytes = info.expanded_bytes.saturating_add(budget.bytes);
                    if info.expanded > MAX_FILE_EXPANSION || info.expanded_bytes > MAX_FILE_BYTES {
                        return Err(error!(
                            "Macro expansion produced more than {MAX_FILE_EXPANSION} tokens or {MAX_FILE_BYTES} bytes in one file and its includes"
                        ));
                    }

                    // Line numbers follow the source tokens, so a macro use never shifts them.
                    let (inline, continuations) = source_newlines(&tokens);
                    let (mut result, _) = Token::concat(&resolved);
                    result = result.replace("\r\n", "\n");
                    original_lineno += inline;

                    result = result.replace("\\\n", "");

                    let file = origin.map(|p| p.display().to_string());
                    for msg in mismatches {
                        let mut warning =
                            Warning::new(Some("macro-arg-count"), msg).at_line(original_lineno);
                        if let Some(file) = &file {
                            warning = warning.in_file(file.clone());
                        }
                        warnings.warn(warning);
                    }

                    output += &result;
                    output += "\n";

                    info.line_origins
                        .push((original_lineno, origin.map(Path::to_path_buf)));
                    original_lineno += continuations;
                }
            }
        }
        original_lineno += 1;

        if level > 0 {
            // @todo: complain
        }
    }

    info.ends_in_entry = last_is_entry;
    Ok(output)
}

/// Reads input string and returns preprocessed string with an info struct containing the origins
/// of the lines in the output.
///
/// `path` is the path to the input if it is known and is used for relative includes and error
/// messages. `includefolders` are the folders searched recursively for absolute includes (see
/// [`IncludeFolders`] for folders that are only checked directly).
///
/// # Errors
///
/// Returns an error on parse failures, unreadable includes or invalid include folders.
///
/// # Examples
///
/// ```
/// # use dayzmake_core::preprocess::preprocess;
/// # use dayzmake_core::warning::Warnings;
/// let input = String::from("
/// #define QUOTE(x) #x
/// #define DOUBLES(x,y) x##_##y
///
/// foo = QUOTE(DOUBLES(abc, xyz));
/// ");
///
/// let (output, _) = preprocess(input, None, &Vec::new(), &mut Warnings::new()).expect("Failed to preprocess");
///
/// assert_eq!("foo = \"abc_xyz\";", output.trim());
/// ```
pub fn preprocess(
    input: String,
    origin: Option<PathBuf>,
    includefolders: &[PathBuf],
    warnings: &mut dyn WarningSink,
) -> Result<(String, PreprocessInfo), Error> {
    preprocess_in(
        input,
        origin,
        &IncludeFolders::new(includefolders.to_vec()),
        warnings,
    )
}

/// Like [`preprocess`], with the include folders given as an [`IncludeFolders`], so that some of them can be
/// checked directly instead of searched recursively.
///
/// # Errors
///
/// Returns an error on parse failures, unreadable includes or invalid include folders.
#[expect(
    clippy::needless_pass_by_value,
    reason = "public API takes ownership of the input; callers pass owned strings"
)]
pub fn preprocess_in(
    mut input: String,
    origin: Option<PathBuf>,
    includefolders: &IncludeFolders,
    warnings: &mut dyn WarningSink,
) -> Result<(String, PreprocessInfo), Error> {
    if input.as_bytes().starts_with(&[0xef, 0xbb, 0xbf]) {
        input = input[3..].to_string();
    }

    for folder in includefolders
        .search
        .iter()
        .chain(&includefolders.direct)
        .filter(|_| includefolders.memory.is_none())
    {
        if !folder.is_dir() {
            return Err(error!(
                "Include folder \"{}\" does not exist or is not a directory.",
                folder.display()
            ));
        }
    }

    let mut info = PreprocessInfo {
        line_origins: Vec::new(),
        import_stack: Vec::new(),
        include_depth: 0,
        expanded: 0,
        expanded_bytes: 0,
        steps: 0,
        includes: 0,
        include_bytes: 0,
        ends_in_entry: false,
    };

    if let Some(ref path) = origin {
        info.import_stack.push(path.clone());
    }

    let mut def_map: HashMap<String, Definition> = HashMap::new();

    match preprocess_rec(
        &input,
        origin.as_deref(),
        &mut def_map,
        &mut info,
        includefolders,
        warnings,
    ) {
        Ok(result) => Ok((result, info)),
        Err(e) => Err(e),
    }
}

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

    /// Several links to one directory are entered once: the entries are counted once.
    #[cfg(unix)]
    #[test]
    fn sibling_links_are_not_visited_twice() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        std::fs::create_dir(root.join("real")).unwrap();
        std::fs::write(root.join("real/f.txt"), "x").unwrap();
        std::os::unix::fs::symlink("real", root.join("l1")).unwrap();
        std::os::unix::fs::symlink("real", root.join("l2")).unwrap();
        let mut walk = Walk {
            include_path: "\\DZ\\gone.hpp",
            root: &root,
            ci: false,
            visited: 0,
            limit: 1000,
            seen: std::collections::BTreeSet::new(),
        };
        assert!(walk.search(&root).unwrap().is_none());
        // root: real, l1, l2 (3 entries) plus real's one file; the links add nothing
        assert_eq!(walk.visited, 4);
    }

    /// The walk stops with an error naming the include once it visited more entries than its limit (#66).
    #[test]
    fn search_stops_after_the_entry_limit() {
        let dir = tempfile::tempdir().unwrap();
        for i in 0..10 {
            std::fs::write(dir.path().join(format!("f{i}.txt")), "x").unwrap();
        }
        let root = dir.path().canonicalize().unwrap();
        let mut walk = Walk {
            include_path: "\\DZ\\gone.hpp",
            root: &root,
            ci: false,
            visited: 0,
            limit: 5,
            seen: std::collections::BTreeSet::new(),
        };
        let err = walk.search(&root).unwrap_err().to_string();
        assert!(
            err.contains("DZ") && err.contains("stopped after 5 entries"),
            "{err}"
        );
    }

    use std::ffi::OsStr;

    /// Argument-count mismatches go into the buffer of the call, not into state shared by the
    /// thread: a second resolve with a fresh buffer sees nothing of the first.
    #[test]
    fn arg_count_mismatches_belong_to_their_call() {
        let mut defs: HashMap<String, Definition> = HashMap::new();
        let def = Definition {
            name: "F".to_string(),
            parameters: Some(vec!["a".to_string()]),
            value: Vec::new(),
            local: false,
        };
        defs.insert("F".to_string(), def);
        let tokens = vec![Token::MacroToken(parse_macro("F(1,2)").unwrap())];

        let mut first = Vec::new();
        Macro::resolve_all(&tokens, &defs, &[], 0, &mut first, &mut Budget::new(0)).unwrap();
        assert_eq!(first.len(), 1);

        let plain = vec![Token::RegularToken("x".to_string())];
        let mut second = Vec::new();
        Macro::resolve_all(&plain, &defs, &[], 0, &mut second, &mut Budget::new(0)).unwrap();
        assert_eq!(second.len(), 0);
    }

    /// The resolver reports the name the file has on disk, never the requested
    /// one: on Windows an `exists()` probe succeeds for any casing, so only the
    /// directory entries carry the truth.
    #[test]
    fn resolve_reports_the_on_disk_casing() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("inc.hpp"), b"x").unwrap();
        let found = resolve_case_insensitive(dir.path(), Path::new("INC.hpp")).unwrap();
        assert_eq!(found.file_name(), Some(OsStr::new("inc.hpp")));
    }

    /// An exact match is preferred over a case-insensitive one. The fixture
    /// needs two files that differ only in case, which a case-insensitive
    /// filesystem (Windows) cannot hold.
    #[test]
    #[cfg(not(windows))]
    fn resolve_prefers_the_exact_match() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("Inc.hpp"), b"a").unwrap();
        std::fs::write(dir.path().join("inc.hpp"), b"b").unwrap();
        let found = resolve_case_insensitive(dir.path(), Path::new("inc.hpp")).unwrap();
        assert_eq!(found.file_name(), Some(OsStr::new("inc.hpp")));
    }

    #[test]
    fn case_difference_is_detected_component_wise() {
        assert!(differs_in_case(
            Path::new("/a/B.hpp"),
            Path::new("/a/b.hpp")
        ));
        assert!(!differs_in_case(
            Path::new("/a/b.hpp"),
            Path::new("/a/b.hpp")
        ));
    }
}