cverif 0.0.0

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
//! C lexer and preprocessor.

use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::rc::Rc;

#[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]>),
    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::Char(c) => format!("{c}"),
            Tok::Punct(p) => p.to_string(),
            Tok::Eof => String::new(),
        }
    }
}

const PUNCTS: &[&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;
            }
            let q = b[i];
            i += 1;
            let mut bytes = Vec::new();
            let mut first = None;
            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 {
                    i += 1;
                    b[i - 1] as u32
                };
                first.get_or_insert(v);
                bytes.push(v as u8);
            }
            if q == b'"' {
                Tok::Str(bytes.into())
            } else {
                // Multi-character constants are not supported; plain char is unsigned on ARM.
                Tok::Char(first.unwrap_or(0) & 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(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,
    body: Vec<Token>,
}

pub struct Preprocessor {
    pub files: Vec<PathBuf>,
    macros: HashMap<Rc<str>, Macro>,
    include_dirs: Vec<PathBuf>,
    once: Vec<PathBuf>,
    depth: 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#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",
    ),
    (
        "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"),
];

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 {
    pub fn new(include_dirs: Vec<PathBuf>, defines: &[(String, String)]) -> Res<Preprocessor> {
        let mut pp = Preprocessor {
            files: Vec::new(),
            macros: HashMap::new(),
            include_dirs,
            once: Vec::new(),
            depth: 0,
        };
        pp.files.push(PathBuf::from("<predefined>"));
        let mut text = String::from(PREDEFINED);
        for (k, v) in defines {
            text.push_str(&format!("#define {k} {v}\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) -> Res<Vec<Token>> {
        let toks = self.load(path, Loc::default())?;
        let mut out = 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)
    }

    fn include(&mut self, name: &str, angled: bool, cur: Option<&Path>, loc: Loc) -> Res<Vec<Token>> {
        let mut cands = Vec::new();
        if !angled && let Some(dir) = cur.and_then(|c| c.parent()) {
            cands.push(dir.join(name));
        }
        for d in &self.include_dirs {
            cands.push(d.join(name));
        }
        for c in cands {
            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 == "__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__" {
                    return Some(m.params.len());
                }
                m.params.iter().position(|p| p == id)
            };
            body = Vec::new();
            let mut i = 0;
            while i < m.body.len() {
                let bt = &m.body[i];
                if bt.is_punct("#")
                    && let Some(pi) = m.body.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 =
                    m.body.get(i + 1).is_some_and(|n| n.is_punct("##")) || (i > 0 && m.body[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)?
                } else {
                    let Some(id) = rest.first().and_then(|t| t.ident()) else {
                        return err(loc, "macro name expected");
                    };
                    self.macros.contains_key(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)?;
                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,
                    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("...")) {
                                return err(loc, "named variadic macro parameters are not supported");
                            }
                            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" => {
                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, 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(" ")));
            }
            "warning" | "line" | "ident" => {}
            other => return err(loc, format!("unknown directive #{other}")),
        }
        Ok(())
    }

    fn eval_if(&mut self, loc: Loc, toks: &[Token]) -> 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.macros.contains_key(id), t));
                i += n;
            } else {
                pre.push(t.clone());
                i += 1;
            }
        }
        let exp = self.run(pre.into(), false, None)?;
        let mut e = IfEval {
            toks: &exp,
            pos: 0,
            loc,
        };
        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,
}

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()?;
            if !self.eat(":") {
                return err(self.loc, "expected ':' in #if");
            }
            let b = self.ternary()?;
            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()?;
        loop {
            let Some(&(op, prec)) = OPS.iter().find(|(o, p)| *p >= min && self.peek(o)) else {
                return Ok(l);
            };
            self.pos += 1;
            let r = self.binary(prec + 1)?;
            l = match op {
                "||" => (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!(),
            };
        }
    }

    fn unary(&mut self) -> Res<i64> {
        if self.eat("!") {
            return Ok((self.unary()? == 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, _, _)) => Ok(v as i64),
                None => err(self.loc, format!("bad number in #if: {s}")),
            },
            Tok::Char(c) => Ok(*c as i64),
            Tok::Ident(_) => 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))
}