cverif 0.0.2

Verifies that compiled machine code faithfully matches its C source
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
//! C lexer and preprocessor.

use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc as Rc; // shared read-only between verification threads

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct Loc {
    pub file: u16,
    pub line: u32,
}

#[derive(Debug, Clone)]
pub struct CError {
    pub loc: Loc,
    pub msg: String,
}

pub type Res<T> = Result<T, CError>;

pub fn err<T>(loc: Loc, msg: impl Into<String>) -> Res<T> {
    Err(CError { loc, msg: msg.into() })
}

#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
    Ident(Rc<str>),
    /// Preprocessing number, converted by the parser.
    Num(Rc<str>),
    Str(Rc<[u8]>),
    /// Wide string literal: little-endian code units of the given size, no terminator.
    WStr(Rc<[u8]>, u8),
    Char(u32),
    Punct(&'static str),
    Eof,
}

#[derive(Clone, Debug)]
pub struct Token {
    pub tok: Tok,
    pub loc: Loc,
    /// First token on its line.
    pub bol: bool,
    /// Preceded by whitespace.
    pub space: bool,
    /// Macros that must not be expanded again in this token.
    hide: Option<Rc<Vec<Rc<str>>>>,
}

impl Token {
    fn hidden(&self, name: &str) -> bool {
        self.hide.as_ref().is_some_and(|h| h.iter().any(|n| &**n == name))
    }

    pub fn is_punct(&self, p: &str) -> bool {
        matches!(self.tok, Tok::Punct(q) if q == p)
    }

    pub fn ident(&self) -> Option<&Rc<str>> {
        match &self.tok {
            Tok::Ident(s) => Some(s),
            _ => None,
        }
    }

    pub fn text(&self) -> String {
        match &self.tok {
            Tok::Ident(s) => s.to_string(),
            Tok::Num(s) => s.to_string(),
            Tok::Str(b) => {
                let mut s = String::from("\"");
                for &c in b.iter() {
                    match c {
                        b'"' => s.push_str("\\\""),
                        b'\\' => s.push_str("\\\\"),
                        b'\n' => s.push_str("\\n"),
                        0x20..=0x7e => s.push(c as char),
                        _ => s.push_str(&format!("\\{c:03o}")),
                    }
                }
                s.push('"');
                s
            }
            Tok::WStr(..) => "L\"...\"".into(),
            Tok::Char(c) => format!("{c}"),
            Tok::Punct(p) => p.to_string(),
            Tok::Eof => String::new(),
        }
    }
}

const PUNCTS: &[&str] = &[
    "<<=", ">>=", "...", "->", "++", "--", "<<", ">>", "<=", ">=", "==", "!=", "&&", "||", "*=", "/=", "%=", "+=",
    "-=", "&=", "^=", "|=", "##", "[", "]", "(", ")", "{", "}", ".", "&", "*", "+", "-", "~", "!", "/", "%", "<", ">",
    "^", "|", "?", ":", ";", "=", ",", "#",
];

const DIGRAPHS: &[(&str, &str)] = &[
    ("%:%:", "##"),
    ("<:", "["),
    (":>", "]"),
    ("<%", "{"),
    ("%>", "}"),
    ("%:", "#"),
];

fn read_escape(b: &[u8], i: &mut usize) -> u32 {
    // b[*i] is the character after the backslash.
    let c = b[*i];
    *i += 1;
    match c {
        b'n' => 10,
        b't' => 9,
        b'r' => 13,
        b'a' => 7,
        b'b' => 8,
        b'f' => 12,
        b'v' => 11,
        b'e' => 27,
        b'x' => {
            let mut v = 0u32;
            while *i < b.len() && b[*i].is_ascii_hexdigit() {
                v = v.wrapping_mul(16) + (b[*i] as char).to_digit(16).unwrap();
                *i += 1;
            }
            v
        }
        b'0'..=b'7' => {
            let mut v = (c - b'0') as u32;
            let mut n = 1;
            while n < 3 && *i < b.len() && (b'0'..=b'7').contains(&b[*i]) {
                v = v * 8 + (b[*i] - b'0') as u32;
                *i += 1;
                n += 1;
            }
            v
        }
        _ => c as u32,
    }
}

pub fn tokenize(src: &str, file: u16) -> Res<Vec<Token>> {
    let b = src.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    let mut line = 1u32;
    let mut bol = true;
    let mut space = false;
    while i < b.len() {
        let c = b[i];
        let loc = Loc { file, line };
        if c == b'\n' {
            line += 1;
            bol = true;
            space = false;
            i += 1;
            continue;
        }
        if c == b'\\' && i + 1 < b.len() && (b[i + 1] == b'\n' || (b[i + 1] == b'\r' && b.get(i + 2) == Some(&b'\n'))) {
            i += if b[i + 1] == b'\n' { 2 } else { 3 };
            line += 1;
            space = true;
            continue;
        }
        if c == b' ' || c == b'\t' || c == b'\r' || c == 0x0c || c == 0x0b {
            space = true;
            i += 1;
            continue;
        }
        if c == b'/' && b.get(i + 1) == Some(&b'/') {
            while i < b.len() && b[i] != b'\n' {
                if b[i] == b'\\' && b.get(i + 1) == Some(&b'\n') {
                    line += 1;
                    i += 1;
                }
                i += 1;
            }
            space = true;
            continue;
        }
        if c == b'/' && b.get(i + 1) == Some(&b'*') {
            i += 2;
            loop {
                if i + 1 >= b.len() {
                    return err(loc, "unterminated comment");
                }
                if b[i] == b'*' && b[i + 1] == b'/' {
                    i += 2;
                    break;
                }
                if b[i] == b'\n' {
                    line += 1;
                }
                i += 1;
            }
            space = true;
            continue;
        }
        let start = i;
        let tok = if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(|d| d.is_ascii_digit())) {
            i += 1;
            while i < b.len() {
                let d = b[i];
                if (d == b'+' || d == b'-') && matches!(b[i - 1], b'e' | b'E' | b'p' | b'P') {
                    // exponent sign, unless this is a hex integer like 0xE+1
                    let hex = src[start..i].starts_with("0x") || src[start..i].starts_with("0X");
                    if hex && !matches!(b[i - 1], b'p' | b'P') {
                        break;
                    }
                    i += 1;
                } else if d.is_ascii_alphanumeric() || d == b'.' || d == b'_' {
                    i += 1;
                } else {
                    break;
                }
            }
            Tok::Num(src[start..i].into())
        } else if (c == b'"' || c == b'\'')
            || ((c == b'L' || c == b'u' || c == b'U') && matches!(b.get(i + 1), Some(b'"') | Some(b'\'')))
            || (c == b'u' && b.get(i + 1) == Some(&b'8') && b.get(i + 2) == Some(&b'"'))
        {
            while b[i] != b'"' && b[i] != b'\'' {
                i += 1;
            }
            // Code-unit size of a prefixed literal (u8 strings are plain byte strings).
            let unit: u8 = match c {
                b'L' | b'U' => 4,
                b'u' if b[start + 1] != b'8' => 2,
                _ => 1,
            };
            let q = b[i];
            i += 1;
            let mut bytes = Vec::new();
            let mut chars: Vec<u32> = Vec::new();
            loop {
                if i >= b.len() || b[i] == b'\n' {
                    return err(loc, "unterminated literal");
                }
                if b[i] == q {
                    i += 1;
                    break;
                }
                let v = if b[i] == b'\\' {
                    i += 1;
                    if i >= b.len() {
                        return err(loc, "unterminated literal");
                    }
                    read_escape(b, &mut i)
                } else if unit > 1 && b[i] >= 0x80 {
                    // A wide literal holds code points, not the bytes of their UTF-8 form.
                    let ch = src[i..].chars().next().unwrap_or('?');
                    i += ch.len_utf8();
                    ch as u32
                } else {
                    i += 1;
                    b[i - 1] as u32
                };
                chars.push(v);
                bytes.push(v as u8);
            }
            if q == b'"' && unit == 1 {
                Tok::Str(bytes.into())
            } else if q == b'"' {
                let enc: Vec<u8> = chars
                    .iter()
                    .flat_map(|v| v.to_le_bytes().into_iter().take(unit as usize))
                    .collect();
                Tok::WStr(enc.into(), unit)
            } else if unit > 1 {
                Tok::Char(chars.first().copied().unwrap_or(0))
            } else {
                // Plain char is unsigned on ARM; a multi-character constant packs its
                // characters big-end first, as GCC and Clang do.
                Tok::Char(chars.iter().fold(0u32, |v, c| v << 8 | (c & 0xff)))
            }
        } else if c.is_ascii_alphabetic() || c == b'_' || c == b'$' {
            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'$') {
                i += 1;
            }
            Tok::Ident(src[start..i].into())
        } else if let Some((d, p)) = DIGRAPHS.iter().find(|(d, _)| src[i..].starts_with(*d)) {
            i += d.len();
            Tok::Punct(p)
        } else if let Some(p) = PUNCTS.iter().find(|p| src[i..].starts_with(**p)) {
            i += p.len();
            Tok::Punct(p)
        } else {
            return err(loc, format!("stray character {:?}", c as char));
        };
        out.push(Token {
            tok,
            loc,
            bol,
            space,
            hide: None,
        });
        bol = false;
        space = false;
    }
    Ok(out)
}

#[derive(Clone)]
struct Macro {
    func: bool,
    params: Vec<Rc<str>>,
    variadic: bool,
    /// GNU named variable arguments (`args...`).
    va_name: Option<Rc<str>>,
    body: Vec<Token>,
}

pub struct Preprocessor {
    pub files: Vec<PathBuf>,
    macros: HashMap<Rc<str>, Macro>,
    include_dirs: Vec<PathBuf>,
    once: Vec<PathBuf>,
    depth: u32,
    counter: u32,
}

struct Cond {
    /// Some branch of this #if chain has been taken.
    taken: bool,
    /// Currently emitting tokens.
    active: bool,
    /// The enclosing region is active.
    parent: bool,
}

const BUILTIN_HEADERS: &[(&str, &str)] = &[
    (
        "stdint.h",
        "typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t;\n\
         typedef int int32_t; typedef unsigned int uint32_t; typedef long long int64_t; typedef unsigned long long uint64_t;\n\
         typedef int intptr_t; typedef unsigned int uintptr_t; typedef long long intmax_t; typedef unsigned long long uintmax_t;\n\
         typedef signed char int_least8_t; typedef unsigned char uint_least8_t; typedef short int_least16_t; typedef unsigned short uint_least16_t;\n\
         typedef int int_least32_t; typedef unsigned int uint_least32_t; typedef long long int_least64_t; typedef unsigned long long uint_least64_t;\n\
         typedef int int_fast8_t; typedef unsigned int uint_fast8_t; typedef int int_fast16_t; typedef unsigned int uint_fast16_t;\n\
         typedef int int_fast32_t; typedef unsigned int uint_fast32_t; typedef long long int_fast64_t; typedef unsigned long long uint_fast64_t;\n\
         #define INT8_MIN (-128)\n#define INT8_MAX 127\n#define UINT8_MAX 255\n#define INT16_MIN (-32768)\n#define INT16_MAX 32767\n#define UINT16_MAX 65535\n\
         #define INT32_MIN (-2147483647-1)\n#define INT32_MAX 2147483647\n#define UINT32_MAX 4294967295U\n\
         #define INT64_MIN (-9223372036854775807LL-1)\n#define INT64_MAX 9223372036854775807LL\n#define UINT64_MAX 18446744073709551615ULL\n\
         #define INTPTR_MIN INT32_MIN\n#define INTPTR_MAX INT32_MAX\n#define UINTPTR_MAX UINT32_MAX\n#define SIZE_MAX UINT32_MAX\n\
         #define INTMAX_MAX INT64_MAX\n#define INTMAX_MIN INT64_MIN\n#define UINTMAX_MAX UINT64_MAX\n\
         #define INT8_C(x) x\n#define UINT8_C(x) x\n#define INT16_C(x) x\n#define UINT16_C(x) x\n#define INT32_C(x) x\n#define UINT32_C(x) x##U\n\
         #define INT64_C(x) x##LL\n#define UINT64_C(x) x##ULL\n",
    ),
    (
        "stddef.h",
        "typedef unsigned int size_t; typedef int ptrdiff_t; typedef unsigned int wchar_t;\n\
         typedef struct { long long __max_align_ll; long double __max_align_ld; } max_align_t;\n#define NULL ((void*)0)\n\
         #define offsetof(t, m) __builtin_offsetof(t, m)\n",
    ),
    ("stdbool.h", "#define bool _Bool\n#define true 1\n#define false 0\n"),
    (
        "limits.h",
        "#define CHAR_BIT 8\n#define SCHAR_MIN (-128)\n#define SCHAR_MAX 127\n#define UCHAR_MAX 255\n#define CHAR_MIN 0\n#define CHAR_MAX 255\n\
         #define SHRT_MIN (-32768)\n#define SHRT_MAX 32767\n#define USHRT_MAX 65535\n#define INT_MIN (-2147483647-1)\n#define INT_MAX 2147483647\n\
         #define UINT_MAX 4294967295U\n#define LONG_MIN (-2147483647L-1)\n#define LONG_MAX 2147483647L\n#define ULONG_MAX 4294967295UL\n\
         #define LLONG_MIN (-9223372036854775807LL-1)\n#define LLONG_MAX 9223372036854775807LL\n#define ULLONG_MAX 18446744073709551615ULL\n",
    ),
    (
        "string.h",
        "#include <stddef.h>\nvoid *memcpy(void *, const void *, size_t); void *memmove(void *, const void *, size_t);\n\
         void *memset(void *, int, size_t); int memcmp(const void *, const void *, size_t); size_t strlen(const char *);\n\
         int strcmp(const char *, const char *); int strncmp(const char *, const char *, size_t); char *strcpy(char *, const char *);\n\
         char *strncpy(char *, const char *, size_t); char *strchr(const char *, int); char *strrchr(const char *, int);\n\
         char *strcat(char *, const char *); void *memchr(const void *, int, size_t);\n",
    ),
    (
        "math.h",
        "float fabsf(float); double fabs(double); float sqrtf(float); double sqrt(double); float floorf(float); double floor(double);\n\
         float ceilf(float); double ceil(double); float fmodf(float, float); double fmod(double, double); float roundf(float);\n\
         double round(double); float powf(float, float); double pow(double, double); float expf(float); double exp(double);\n\
         float logf(float); double log(double); float sinf(float); double sin(double); float cosf(float); double cos(double);\n\
         float tanf(float); double tan(double); float atan2f(float, float); double atan2(double, double);\n\
         float fminf(float, float); double fmin(double, double); float fmaxf(float, float); double fmax(double, double);\n\
         #define M_PI 3.14159265358979323846\n",
    ),
    (
        "float.h",
        "#define FLT_RADIX 2\n#define FLT_MANT_DIG 24\n#define DBL_MANT_DIG 53\n#define LDBL_MANT_DIG 53\n#define FLT_DIG 6\n#define DBL_DIG 15\n\
         #define FLT_EPSILON 1.1920928955078125e-7F\n#define DBL_EPSILON 2.220446049250313080847263336181640625e-16\n\
         #define FLT_MAX 3.40282346638528859811704183484516925e+38F\n#define DBL_MAX 1.79769313486231570814527423731704357e+308\n\
         #define FLT_MIN 1.17549435082228750796873653722224568e-38F\n#define DBL_MIN 2.22507385850720138309023271733240406e-308\n\
         #define FLT_MAX_EXP 128\n#define DBL_MAX_EXP 1024\n#define FLT_MIN_EXP (-125)\n#define DBL_MIN_EXP (-1021)\n\
         #define LDBL_EPSILON DBL_EPSILON\n#define LDBL_MAX DBL_MAX\n#define LDBL_MIN DBL_MIN\n",
    ),
    (
        "stdlib.h",
        "#include <stddef.h>\nvoid *malloc(size_t); void *calloc(size_t, size_t); void *realloc(void *, size_t); void free(void *);\n\
         void abort(void); void exit(int); int abs(int); long labs(long); int atoi(const char *);\n",
    ),
    (
        "stdio.h",
        "#include <stddef.h>\ntypedef struct __cverif_FILE FILE;\nint printf(const char *, ...); int puts(const char *); int putchar(int);\n\
         int sprintf(char *, const char *, ...); int snprintf(char *, size_t, const char *, ...);\n",
    ),
    (
        "assert.h",
        "void __assert_fail(const char *, const char *, int);\n#define assert(x) ((x) ? (void)0 : __assert_fail(#x, __FILE__, __LINE__))\n",
    ),
    ("inttypes.h", "#include <stdint.h>\n"),
    (
        "stdarg.h",
        "typedef __builtin_va_list va_list; typedef __builtin_va_list __gnuc_va_list;\n\
         #define va_start(ap, last) __builtin_va_start(ap, last)\n#define va_end(ap) __builtin_va_end(ap)\n\
         #define va_arg(ap, type) __builtin_va_arg(ap, type)\n#define va_copy(d, s) __builtin_va_copy(d, s)\n",
    ),
    ("stdalign.h", "#define alignas _Alignas\n#define alignof _Alignof\n"),
    ("stdnoreturn.h", "#define noreturn _Noreturn\n"),
    (
        "iso646.h",
        "#define and &&\n#define or ||\n#define not !\n#define xor ^\n#define bitand &\n#define bitor |\n#define compl ~\n#define not_eq !=\n#define and_eq &=\n#define or_eq |=\n#define xor_eq ^=\n",
    ),
];

const PREDEFINED: &str = "\
#define __STDC__ 1\n#define __STDC_VERSION__ 201710L\n#define __STDC_HOSTED__ 0\n#define __arm__ 1\n#define __thumb__ 1\n\
#define __thumb2__ 1\n#define __ARM_EABI__ 1\n#define __ARMEL__ 1\n#define __CHAR_UNSIGNED__ 1\n#define __ORDER_LITTLE_ENDIAN__ 1234\n\
#define __ORDER_BIG_ENDIAN__ 4321\n#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__\n#define __SIZEOF_INT__ 4\n#define __SIZEOF_LONG__ 4\n\
#define __SIZEOF_LONG_LONG__ 8\n#define __SIZEOF_SHORT__ 2\n#define __SIZEOF_POINTER__ 4\n#define __SIZEOF_SIZE_T__ 4\n#define __CHAR_BIT__ 8\n\
#define __INT_MAX__ 2147483647\n#define __LONG_MAX__ 2147483647L\n#define __LONG_LONG_MAX__ 9223372036854775807LL\n\
#define __SIZE_TYPE__ unsigned int\n#define __PTRDIFF_TYPE__ int\n#define __INTPTR_TYPE__ int\n#define __UINTPTR_TYPE__ unsigned int\n\
#define __INT32_TYPE__ int\n#define __UINT32_TYPE__ unsigned int\n#define __cverif__ 1\n\
#define __inline inline\n#define __inline__ inline\n#define __signed__ signed\n#define __const const\n#define __const__ const\n\
#define __volatile__ volatile\n#define __restrict restrict\n#define __restrict__ restrict\n#define __extension__\n\
#define __alignof__ _Alignof\n#define __typeof__ typeof\n#define __asm__ asm\n#define __attribute __attribute__\n";

impl Preprocessor {
    /// `defines` holds `-D` and `-U` options in command-line order; a `None` value undefines.
    pub fn new(include_dirs: Vec<PathBuf>, defines: &[(String, Option<String>)]) -> Res<Preprocessor> {
        let mut pp = Preprocessor {
            files: Vec::new(),
            macros: HashMap::new(),
            include_dirs,
            once: Vec::new(),
            depth: 0,
            counter: 0,
        };
        pp.files.push(PathBuf::from("<predefined>"));
        let mut text = String::from(PREDEFINED);
        for (k, v) in defines {
            match v {
                Some(v) => text.push_str(&format!("#define {k} {v}\n")),
                None => text.push_str(&format!("#undef {k}\n")),
            }
        }
        let toks = tokenize(&text, 0)?;
        pp.run(toks.into(), true, None)?;
        Ok(pp)
    }

    pub fn file_name(&self, loc: Loc) -> String {
        self.files
            .get(loc.file as usize)
            .map(|p| p.display().to_string())
            .unwrap_or_default()
    }

    /// Preprocess a source file into a token list terminated by `Tok::Eof`.
    pub fn preprocess_file(&mut self, path: &Path, forced: &[PathBuf]) -> Res<Vec<Token>> {
        let mut out = Vec::new();
        for f in forced {
            let toks = self.load(f, Loc::default())?;
            out.extend(self.sub_run(toks, Some(f.clone()), Loc::default())?);
        }
        let toks = self.load(path, Loc::default())?;
        out.extend(self.run(toks.into(), true, Some(path.to_path_buf()))?);
        let loc = out.last().map(|t| t.loc).unwrap_or_default();
        out.push(Token {
            tok: Tok::Eof,
            loc,
            bol: true,
            space: false,
            hide: None,
        });
        Ok(out)
    }

    fn load(&mut self, path: &Path, loc: Loc) -> Res<Vec<Token>> {
        let src = match std::fs::read(path) {
            Ok(b) => String::from_utf8_lossy(&b).into_owned(),
            Err(e) => return err(loc, format!("cannot read {}: {e}", path.display())),
        };
        self.load_text(path.to_path_buf(), &src)
    }

    fn load_text(&mut self, path: PathBuf, src: &str) -> Res<Vec<Token>> {
        let id = self.files.len() as u16;
        self.files.push(path);
        tokenize(src, id)
    }

    /// Files an `#include` of `name` may designate, in search order.  With `next`
    /// (`#include_next`), only directories after the one holding the current file.
    fn include_candidates(&self, name: &str, angled: bool, next: bool, cur: Option<&Path>) -> Vec<PathBuf> {
        let mut cands = Vec::new();
        let dir = cur.and_then(|c| c.parent());
        if !angled
            && !next
            && let Some(dir) = dir
        {
            cands.push(dir.join(name));
        }
        let skip = match (next, dir) {
            (true, Some(dir)) => self.include_dirs.iter().position(|d| d == dir).map_or(0, |i| i + 1),
            _ => 0,
        };
        for d in self.include_dirs.iter().skip(skip) {
            cands.push(d.join(name));
        }
        cands
    }

    fn has_include(&self, name: &str, angled: bool, next: bool, cur: Option<&Path>) -> bool {
        self.include_candidates(name, angled, next, cur)
            .iter()
            .any(|c| c.is_file())
            || BUILTIN_HEADERS.iter().any(|(n, _)| *n == name)
    }

    fn include(&mut self, name: &str, angled: bool, next: bool, cur: Option<&Path>, loc: Loc) -> Res<Vec<Token>> {
        for c in self.include_candidates(name, angled, next, cur) {
            if c.is_file() {
                if self.once.contains(&c) {
                    return Ok(Vec::new());
                }
                let toks = self.load(&c, loc)?;
                return self.sub_run(toks, Some(c), loc);
            }
        }
        if let Some((_, text)) = BUILTIN_HEADERS.iter().find(|(n, _)| *n == name) {
            let p = PathBuf::from(format!("<builtin>/{name}"));
            if self.once.contains(&p) {
                return Ok(Vec::new());
            }
            self.once.push(p.clone());
            let toks = self.load_text(p.clone(), text)?;
            return self.sub_run(toks, Some(p), loc);
        }
        err(loc, format!("include file not found: {name}"))
    }

    fn sub_run(&mut self, toks: Vec<Token>, path: Option<PathBuf>, loc: Loc) -> Res<Vec<Token>> {
        if self.depth > 100 {
            return err(loc, "#include nested too deeply");
        }
        self.depth += 1;
        let r = self.run(toks.into(), true, path);
        self.depth -= 1;
        r
    }

    /// Expand macros in `input`; with `directives`, also process preprocessor directives.
    fn run(&mut self, mut input: VecDeque<Token>, directives: bool, cur: Option<PathBuf>) -> Res<Vec<Token>> {
        let mut out = Vec::new();
        let mut conds: Vec<Cond> = Vec::new();
        while let Some(t) = input.pop_front() {
            let active = conds.last().is_none_or(|c| c.active);
            if directives && t.bol && t.is_punct("#") && t.hide.is_none() {
                let mut line = Vec::new();
                while input.front().is_some_and(|n| !n.bol) {
                    line.push(input.pop_front().unwrap());
                }
                self.directive(t.loc, line, &mut conds, &mut input, &mut out, cur.as_deref())?;
                continue;
            }
            if !active {
                continue;
            }
            if let Tok::Ident(name) = &t.tok {
                if &**name == "__LINE__" {
                    out.push(Token {
                        tok: Tok::Num(t.loc.line.to_string().into()),
                        ..t
                    });
                    continue;
                }
                if &**name == "__COUNTER__" {
                    self.counter += 1;
                    out.push(Token {
                        tok: Tok::Num((self.counter - 1).to_string().into()),
                        ..t
                    });
                    continue;
                }
                if &**name == "_Pragma" && input.front().is_some_and(|n| n.is_punct("(")) {
                    // `_Pragma("...")`: like the directive, nothing here depends on it.
                    while let Some(n) = input.pop_front() {
                        if n.is_punct(")") {
                            break;
                        }
                    }
                    continue;
                }
                if &**name == "__FILE__" {
                    let f = self.file_name(t.loc);
                    out.push(Token {
                        tok: Tok::Str(f.as_bytes().into()),
                        ..t
                    });
                    continue;
                }
                if !t.hidden(name)
                    && let Some(m) = self.macros.get(name).cloned()
                    && self.expand_macro(&t, name.clone(), &m, &mut input)?
                {
                    continue;
                }
            }
            out.push(t);
        }
        if !conds.is_empty() {
            return err(out.last().map(|t| t.loc).unwrap_or_default(), "unterminated #if");
        }
        Ok(out)
    }

    /// Returns false if `t` names a function-like macro not followed by `(`.
    fn expand_macro(&mut self, t: &Token, name: Rc<str>, m: &Macro, input: &mut VecDeque<Token>) -> Res<bool> {
        let mut hide: Vec<Rc<str>> = t.hide.as_ref().map(|h| (**h).clone()).unwrap_or_default();
        hide.push(name.clone());
        let mut body: Vec<Token>;
        if !m.func {
            body = m.body.clone();
        } else {
            if !input.front().is_some_and(|n| n.is_punct("(")) {
                return Ok(false);
            }
            input.pop_front();
            let mut args: Vec<Vec<Token>> = vec![Vec::new()];
            let mut depth = 0;
            loop {
                let Some(a) = input.pop_front() else {
                    return err(t.loc, format!("unterminated call to macro {name}"));
                };
                if a.is_punct("(") {
                    depth += 1;
                } else if a.is_punct(")") {
                    if depth == 0 {
                        break;
                    }
                    depth -= 1;
                } else if a.is_punct(",") && depth == 0 && (args.len() <= m.params.len() || !m.variadic) {
                    args.push(Vec::new());
                    continue;
                }
                args.last_mut().unwrap().push(a);
            }
            if m.params.is_empty() && !m.variadic && args.len() == 1 && args[0].is_empty() {
                args.clear();
            }
            let nparams = m.params.len() + m.variadic as usize;
            if args.len() < nparams {
                args.resize(nparams, Vec::new());
            }
            if args.len() != nparams {
                return err(
                    t.loc,
                    format!("macro {name} expects {nparams} arguments, got {}", args.len()),
                );
            }
            let param_index = |tk: &Token| -> Option<usize> {
                let id = tk.ident()?;
                if m.variadic && (&**id == "__VA_ARGS__" || m.va_name.as_ref() == Some(id)) {
                    return Some(m.params.len());
                }
                m.params.iter().position(|p| p == id)
            };
            // `__VA_OPT__(tokens)` stands for its tokens when variable arguments are present.
            let mut mb = std::borrow::Cow::Borrowed(&m.body);
            if m.variadic && m.body.iter().any(|b| b.ident().is_some_and(|i| &**i == "__VA_OPT__")) {
                let present = !args[m.params.len()].is_empty();
                let mut nb = Vec::new();
                let mut k = 0;
                while k < m.body.len() {
                    let b = &m.body[k];
                    if b.ident().is_some_and(|i| &**i == "__VA_OPT__")
                        && m.body.get(k + 1).is_some_and(|n| n.is_punct("("))
                    {
                        let mut depth = 0;
                        let mut j = k + 2;
                        let n0 = nb.len();
                        while j < m.body.len() {
                            let c = &m.body[j];
                            if c.is_punct("(") {
                                depth += 1;
                            } else if c.is_punct(")") {
                                if depth == 0 {
                                    break;
                                }
                                depth -= 1;
                            }
                            if present {
                                nb.push(c.clone());
                            }
                            j += 1;
                        }
                        if nb.len() == n0 {
                            nb.push(Token {
                                tok: Tok::Ident("".into()),
                                loc: t.loc,
                                bol: false,
                                space: false,
                                hide: None,
                            });
                        }
                        k = j + 1;
                    } else {
                        nb.push(b.clone());
                        k += 1;
                    }
                }
                mb = std::borrow::Cow::Owned(nb);
            }
            let mbody: &[Token] = &mb;
            body = Vec::new();
            let mut i = 0;
            while i < mbody.len() {
                let bt = &mbody[i];
                // GNU `, ## __VA_ARGS__`: the comma disappears along with empty variable arguments.
                if m.variadic
                    && bt.is_punct(",")
                    && mbody.get(i + 1).is_some_and(|n| n.is_punct("##"))
                    && mbody.get(i + 2).and_then(&param_index) == Some(m.params.len())
                {
                    if !args[m.params.len()].is_empty() {
                        body.push(bt.clone());
                        body.extend(self.run(args[m.params.len()].clone().into(), false, None)?);
                    }
                    i += 3;
                    continue;
                }
                if bt.is_punct("#")
                    && let Some(pi) = mbody.get(i + 1).and_then(&param_index)
                {
                    let mut s = String::new();
                    for (k, a) in args[pi].iter().enumerate() {
                        if k > 0 && a.space {
                            s.push(' ');
                        }
                        s.push_str(&a.text());
                    }
                    body.push(Token {
                        tok: Tok::Str(s.as_bytes().into()),
                        loc: t.loc,
                        bol: false,
                        space: bt.space,
                        hide: None,
                    });
                    i += 2;
                    continue;
                }
                let pasting =
                    mbody.get(i + 1).is_some_and(|n| n.is_punct("##")) || (i > 0 && mbody[i - 1].is_punct("##"));
                if let Some(pi) = param_index(bt) {
                    let mut arg = if pasting {
                        args[pi].clone()
                    } else {
                        self.run(args[pi].clone().into(), false, None)?
                    };
                    if let Some(f) = arg.first_mut() {
                        f.space = bt.space;
                        f.bol = false;
                    } else if pasting {
                        // Empty argument next to ##: use a placemarker (empty identifier).
                        arg.push(Token {
                            tok: Tok::Ident("".into()),
                            loc: t.loc,
                            bol: false,
                            space: false,
                            hide: None,
                        });
                    }
                    body.extend(arg);
                } else {
                    body.push(bt.clone());
                }
                i += 1;
            }
        }
        // Token pasting.
        if body.iter().any(|b| b.is_punct("##")) {
            let mut pasted: Vec<Token> = Vec::new();
            let mut i = 0;
            while i < body.len() {
                if body[i].is_punct("##") && !pasted.is_empty() && i + 1 < body.len() {
                    let l = pasted.pop().unwrap();
                    let r = &body[i + 1];
                    let text = format!("{}{}", l.text(), r.text());
                    if text.is_empty() {
                        pasted.push(l);
                    } else {
                        let mut toks = tokenize(&text, t.loc.file)?;
                        for (k, tk) in toks.iter_mut().enumerate() {
                            tk.loc = t.loc;
                            tk.bol = false;
                            tk.space = k == 0 && l.space;
                        }
                        pasted.extend(toks);
                    }
                    i += 2;
                } else {
                    pasted.push(body[i].clone());
                    i += 1;
                }
            }
            body = pasted;
        }
        body.retain(|b| !matches!(&b.tok, Tok::Ident(s) if s.is_empty()));
        let hide = Rc::new(hide);
        for (k, b) in body.iter_mut().enumerate().rev() {
            let mut h = (*hide).clone();
            if let Some(old) = &b.hide {
                for o in old.iter() {
                    if !h.contains(o) {
                        h.push(o.clone());
                    }
                }
            }
            b.hide = Some(Rc::new(h));
            b.loc = t.loc;
            b.bol = false;
            if k == 0 {
                b.space = t.space;
            }
        }
        for b in body.into_iter().rev() {
            input.push_front(b);
        }
        Ok(true)
    }

    fn directive(
        &mut self,
        loc: Loc,
        line: Vec<Token>,
        conds: &mut Vec<Cond>,
        input: &mut VecDeque<Token>,
        out: &mut Vec<Token>,
        cur: Option<&Path>,
    ) -> Res<()> {
        let active = conds.last().is_none_or(|c| c.active);
        let Some(name) = line.first().and_then(|t| t.ident()).cloned() else {
            return Ok(()); // null directive or line marker
        };
        let rest = &line[1..];
        match &*name {
            "if" | "ifdef" | "ifndef" => {
                let v = if !active {
                    false
                } else if &*name == "if" {
                    self.eval_if(loc, rest, cur)?
                } else {
                    let Some(id) = rest.first().and_then(|t| t.ident()) else {
                        return err(loc, "macro name expected");
                    };
                    self.is_defined(id) == (&*name == "ifdef")
                };
                conds.push(Cond {
                    taken: v,
                    active: v,
                    parent: active,
                });
            }
            "elif" => {
                let Some(c) = conds.last() else {
                    return err(loc, "#elif without #if");
                };
                let (taken, parent) = (c.taken, c.parent);
                let v = parent && !taken && self.eval_if(loc, rest, cur)?;
                let c = conds.last_mut().unwrap();
                c.active = v;
                c.taken |= v;
            }
            "else" => {
                let Some(c) = conds.last_mut() else {
                    return err(loc, "#else without #if");
                };
                c.active = c.parent && !c.taken;
                c.taken = true;
            }
            "endif" => {
                if conds.pop().is_none() {
                    return err(loc, "#endif without #if");
                }
            }
            _ if !active => {}
            "define" => {
                let Some(id) = rest.first().and_then(|t| t.ident()).cloned() else {
                    return err(loc, "macro name expected");
                };
                let mut m = Macro {
                    func: false,
                    params: Vec::new(),
                    variadic: false,
                    va_name: None,
                    body: Vec::new(),
                };
                let mut i = 1;
                if rest.get(1).is_some_and(|t| t.is_punct("(") && !t.space) {
                    m.func = true;
                    i = 2;
                    loop {
                        let Some(t) = rest.get(i) else {
                            return err(loc, "unterminated macro parameter list");
                        };
                        i += 1;
                        if t.is_punct(")") {
                            break;
                        } else if t.is_punct("...") {
                            m.variadic = true;
                        } else if let Some(p) = t.ident() {
                            if rest.get(i).is_some_and(|n| n.is_punct("...")) {
                                m.variadic = true;
                                m.va_name = Some(p.clone());
                                i += 1;
                                continue;
                            }
                            m.params.push(p.clone());
                        } else if !t.is_punct(",") {
                            return err(loc, "bad macro parameter list");
                        }
                    }
                }
                m.body = rest[i..].to_vec();
                self.macros.insert(id, m);
            }
            "undef" => {
                if let Some(id) = rest.first().and_then(|t| t.ident()) {
                    self.macros.remove(id);
                }
            }
            "include" | "include_next" | "import" => {
                let mut toks = rest.to_vec();
                if !matches!(toks.first().map(|t| &t.tok), Some(Tok::Str(_)))
                    && !toks.first().is_some_and(|t| t.is_punct("<"))
                {
                    toks = self.run(toks.into(), false, None)?;
                }
                let (fname, angled) = match toks.first().map(|t| &t.tok) {
                    Some(Tok::Str(s)) => (String::from_utf8_lossy(s).into_owned(), false),
                    Some(Tok::Punct("<")) => {
                        let mut s = String::new();
                        for t in &toks[1..] {
                            if t.is_punct(">") {
                                break;
                            }
                            if t.space && !s.is_empty() {
                                s.push(' ');
                            }
                            s.push_str(&t.text());
                        }
                        (s, true)
                    }
                    _ => return err(loc, "bad #include"),
                };
                let toks = self.include(&fname, angled, &*name == "include_next", cur, loc)?;
                out.extend(toks);
                let _ = input;
            }
            "pragma" => {
                if rest.first().and_then(|t| t.ident()).is_some_and(|i| &**i == "once")
                    && let Some(c) = cur
                {
                    self.once.push(c.to_path_buf());
                }
            }
            "error" => {
                let msg: Vec<String> = rest.iter().map(|t| t.text()).collect();
                return err(loc, format!("#error {}", msg.join(" ")));
            }
            "line" => {
                // Renumber the rest of the file (and rename it), as __LINE__ and __FILE__ see it.
                let toks = self.run(rest.to_vec().into(), false, None)?;
                let Some(n) = toks.first().and_then(|t| match &t.tok {
                    Tok::Num(s) => s.parse::<u32>().ok(),
                    _ => None,
                }) else {
                    return err(loc, "#line needs a line number");
                };
                let file = match toks.get(1).map(|t| &t.tok) {
                    Some(Tok::Str(s)) => {
                        self.files.push(PathBuf::from(String::from_utf8_lossy(s).into_owned()));
                        Some(self.files.len() as u16 - 1)
                    }
                    _ => None,
                };
                let delta = n.wrapping_sub(loc.line + 1);
                for t in input.iter_mut().filter(|t| t.loc.file == loc.file) {
                    t.loc.line = t.loc.line.wrapping_add(delta);
                    if let Some(f) = file {
                        t.loc.file = f;
                    }
                }
            }
            "warning" | "ident" | "sccs" | "assert" | "unassert" => {}
            other => return err(loc, format!("unknown directive #{other}")),
        }
        Ok(())
    }

    fn is_defined(&self, id: &str) -> bool {
        self.macros.contains_key(id)
            || matches!(
                id,
                "__has_include" | "__has_include_next" | "__COUNTER__" | "__FILE__" | "__LINE__"
            )
    }

    fn eval_if(&mut self, loc: Loc, toks: &[Token], cur: Option<&Path>) -> Res<bool> {
        // Replace defined(X) before expansion.
        let mut pre = Vec::new();
        let mut i = 0;
        let num = |v: bool, t: &Token| Token {
            tok: Tok::Num(if v { "1" } else { "0" }.into()),
            ..t.clone()
        };
        while i < toks.len() {
            let t = &toks[i];
            if t.ident().is_some_and(|s| &**s == "defined") {
                let (id, n) = if toks.get(i + 1).is_some_and(|p| p.is_punct("(")) {
                    (toks.get(i + 2).and_then(|t| t.ident()), 4)
                } else {
                    (toks.get(i + 1).and_then(|t| t.ident()), 2)
                };
                let Some(id) = id else {
                    return err(loc, "bad defined()");
                };
                pre.push(num(self.is_defined(id), t));
                i += n;
            } else if let Some(which) = t
                .ident()
                .filter(|s| matches!(&***s, "__has_include" | "__has_include_next"))
                && toks.get(i + 1).is_some_and(|p| p.is_punct("("))
            {
                let end = toks[i..]
                    .iter()
                    .position(|p| p.is_punct(")"))
                    .map_or(toks.len(), |e| i + e);
                let inner = &toks[i + 2..end];
                let (fname, angled) = match inner.first().map(|t| &t.tok) {
                    Some(Tok::Str(s)) => (String::from_utf8_lossy(s).into_owned(), false),
                    Some(Tok::Punct("<")) => (
                        inner[1..]
                            .iter()
                            .take_while(|t| !t.is_punct(">"))
                            .map(|t| t.text())
                            .collect::<String>(),
                        true,
                    ),
                    _ => return err(loc, "bad __has_include"),
                };
                pre.push(num(
                    self.has_include(&fname, angled, &**which == "__has_include_next", cur),
                    t,
                ));
                i = (end + 1).min(toks.len());
            } else if t
                .ident()
                .is_some_and(|s| s.starts_with("__has_") && !self.macros.contains_key(s))
                && toks.get(i + 1).is_some_and(|p| p.is_punct("("))
            {
                // __has_attribute, __has_builtin, ...: nothing is promised.
                let end = toks[i..]
                    .iter()
                    .position(|p| p.is_punct(")"))
                    .map_or(toks.len(), |e| i + e);
                pre.push(num(false, t));
                i = (end + 1).min(toks.len());
            } else {
                pre.push(t.clone());
                i += 1;
            }
        }
        let exp = self.run(pre.into(), false, None)?;
        let mut e = IfEval {
            toks: &exp,
            pos: 0,
            loc,
            uns: false,
        };
        let v = e.ternary()?;
        if e.pos != exp.len() {
            return err(loc, "junk at end of #if expression");
        }
        Ok(v != 0)
    }
}

struct IfEval<'a> {
    toks: &'a [Token],
    pos: usize,
    loc: Loc,
    /// The value last computed has an unsigned type (`#if` arithmetic is in intmax_t or
    /// uintmax_t, by the usual conversions).
    uns: bool,
}

impl IfEval<'_> {
    fn peek(&self, p: &str) -> bool {
        self.toks.get(self.pos).is_some_and(|t| t.is_punct(p))
    }

    fn eat(&mut self, p: &str) -> bool {
        if self.peek(p) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    fn ternary(&mut self) -> Res<i64> {
        let c = self.binary(0)?;
        if self.eat("?") {
            let a = self.ternary()?;
            let au = self.uns;
            if !self.eat(":") {
                return err(self.loc, "expected ':' in #if");
            }
            let b = self.ternary()?;
            self.uns |= au;
            return Ok(if c != 0 { a } else { b });
        }
        Ok(c)
    }

    fn binary(&mut self, min: u8) -> Res<i64> {
        const OPS: &[(&str, u8)] = &[
            ("||", 1),
            ("&&", 2),
            ("|", 3),
            ("^", 4),
            ("&", 5),
            ("==", 6),
            ("!=", 6),
            ("<=", 7),
            (">=", 7),
            ("<", 7),
            (">", 7),
            ("<<", 8),
            (">>", 8),
            ("+", 9),
            ("-", 9),
            ("*", 10),
            ("/", 10),
            ("%", 10),
        ];
        let mut l = self.unary()?;
        let mut lu = self.uns;
        loop {
            let Some(&(op, prec)) = OPS.iter().find(|(o, p)| *p >= min && self.peek(o)) else {
                self.uns = lu;
                return Ok(l);
            };
            self.pos += 1;
            let r = self.binary(prec + 1)?;
            let u = lu || self.uns;
            let (ul, ur) = (l as u64, r as u64);
            let res_u = match op {
                "||" | "&&" | "==" | "!=" | "<=" | ">=" | "<" | ">" => false,
                "<<" | ">>" => lu,
                _ => u,
            };
            l = match op {
                "<=" if u => (ul <= ur) as i64,
                ">=" if u => (ul >= ur) as i64,
                "<" if u => (ul < ur) as i64,
                ">" if u => (ul > ur) as i64,
                ">>" if lu => ul.wrapping_shr(r as u32) as i64,
                "/" if u && r != 0 => (ul / ur) as i64,
                "%" if u && r != 0 => (ul % ur) as i64,
                "||" => (l != 0 || r != 0) as i64,
                "&&" => (l != 0 && r != 0) as i64,
                "|" => l | r,
                "^" => l ^ r,
                "&" => l & r,
                "==" => (l == r) as i64,
                "!=" => (l != r) as i64,
                "<=" => (l <= r) as i64,
                ">=" => (l >= r) as i64,
                "<" => (l < r) as i64,
                ">" => (l > r) as i64,
                "<<" => l.wrapping_shl(r as u32),
                ">>" => l.wrapping_shr(r as u32),
                "+" => l.wrapping_add(r),
                "-" => l.wrapping_sub(r),
                "*" => l.wrapping_mul(r),
                "/" | "%" => {
                    if r == 0 {
                        return err(self.loc, "division by zero in #if");
                    }
                    if op == "/" {
                        l.wrapping_div(r)
                    } else {
                        l.wrapping_rem(r)
                    }
                }
                _ => unreachable!(),
            };
            lu = res_u;
        }
    }

    fn unary(&mut self) -> Res<i64> {
        if self.eat("!") {
            let v = self.unary()?;
            self.uns = false;
            return Ok((v == 0) as i64);
        }
        if self.eat("-") {
            return Ok(self.unary()?.wrapping_neg());
        }
        if self.eat("+") {
            return self.unary();
        }
        if self.eat("~") {
            return Ok(!self.unary()?);
        }
        if self.eat("(") {
            let v = self.ternary()?;
            if !self.eat(")") {
                return err(self.loc, "expected ')' in #if");
            }
            return Ok(v);
        }
        let Some(t) = self.toks.get(self.pos) else {
            return err(self.loc, "expression expected in #if");
        };
        self.pos += 1;
        match &t.tok {
            Tok::Num(s) => match parse_int(s) {
                Some((v, u, _)) => {
                    self.uns = u || v > i64::MAX as u64;
                    Ok(v as i64)
                }
                None => err(self.loc, format!("bad number in #if: {s}")),
            },
            Tok::Char(c) => {
                self.uns = false;
                Ok(*c as i64)
            }
            Tok::Ident(_) => {
                self.uns = false;
                Ok(0)
            }
            _ => err(self.loc, "bad token in #if"),
        }
    }
}

/// Parse an integer literal: (value, has unsigned suffix or needs unsigned, number of `l` suffixes).
/// Returns None for floating-point literals and malformed numbers.
pub fn parse_int(s: &str) -> Option<(u64, bool, u8)> {
    let lower = s.to_ascii_lowercase();
    let (digits, radix) = if let Some(r) = lower.strip_prefix("0x") {
        (r, 16)
    } else if let Some(r) = lower.strip_prefix("0b") {
        (r, 2)
    } else if lower.len() > 1 && lower.starts_with('0') {
        (&lower[1..], 8)
    } else {
        (&lower[..], 10)
    };
    let end = digits.find(|c: char| !c.is_digit(radix)).unwrap_or(digits.len());
    let (num, suffix) = digits.split_at(end);
    let (unsigned, longs) = match suffix {
        "" => (false, 0),
        "u" => (true, 0),
        "l" => (false, 1),
        "ul" | "lu" => (true, 1),
        "ll" => (false, 2),
        "ull" | "llu" => (true, 2),
        _ => return None,
    };
    let v = if num.is_empty() {
        if radix == 8 { 0 } else { return None }
    } else {
        u64::from_str_radix(num, radix).ok()?
    };
    Some((v, unsigned, longs))
}