use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc as 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>),
Num(Rc<str>),
Str(Rc<[u8]>),
WStr(Rc<[u8]>, u8),
Char(u32),
Punct(&'static str),
Eof,
}
#[derive(Clone, Debug)]
pub struct Token {
pub tok: Tok,
pub loc: Loc,
pub bol: bool,
pub space: bool,
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 {
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') {
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 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 {
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 {
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,
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 {
taken: bool,
active: bool,
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 __INT32_TYPE__ int32_t; typedef __UINT32_TYPE__ 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_LEAST32_TYPE__ int_least32_t; typedef __UINT_LEAST32_TYPE__ 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\
#define __builtin_add_overflow(a, b, r) __cverif_overflow(+, long long, a, b, r)\n\
#define __builtin_sub_overflow(a, b, r) __cverif_overflow(-, long long, a, b, r)\n\
#define __builtin_mul_overflow(a, b, r) __cverif_overflow(*, unsigned long long, a, b, r)\n\
#define __cverif_overflow(op, wide, a, b, r) ({ typeof(a) __cv_a = (a); typeof(b) __cv_b = (b); typeof(r) __cv_r = (r); \
_Static_assert(sizeof(__cv_a) <= 4 && sizeof(__cv_b) <= 4 && sizeof(*__cv_r) <= 4, \"64-bit overflow built-ins are not modelled\"); \
wide __cv_t = (wide)(long long)__cv_a op (wide)(long long)__cv_b; *__cv_r = (typeof(*__cv_r))__cv_t; \
(wide)(long long)*__cv_r != __cv_t; })\n";
impl Preprocessor {
pub fn new(include_dirs: Vec<PathBuf>, target: &str, 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);
text.push_str(target);
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()
}
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)
}
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
}
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("(")) {
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)
}
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;
let mut conds: Vec<Cond> = Vec::new();
let mut sink = Vec::new();
loop {
let Some(a) = input.pop_front() else {
return err(t.loc, format!("unterminated call to macro {name}"));
};
if a.bol && a.is_punct("#") && a.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(a.loc, line, &mut conds, input, &mut sink, None)?;
continue;
}
if conds.last().is_some_and(|c| !c.active) {
continue;
}
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)
};
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];
if m.variadic
&& bt.is_punct(",")
&& mbody.get(i + 1).is_some_and(|n| n.is_punct("##"))
&& mbody.get(i + 2).and_then(¶m_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(¶m_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 {
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;
}
}
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(()); };
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" => {
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> {
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("("))
{
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,
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"),
}
}
}
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))
}