Skip to main content

rucc_pp/
predef.rs

1//! The predefined macro set, generated from the target description.
2//!
3//! Design: `spec/04-driver-and-cli.md` section 4.5.
4//!
5//! The set is built as text and then read by the directive engine, which is what GCC does and
6//! is not laziness. Constructing a few hundred `MacroDef` values by hand would need its own
7//! parser for macro bodies, would not exercise the one that already exists, and could not be
8//! read by a person checking a limit against the psABI. A file of `#define` lines can be
9//! printed by `-dM`, diffed against GCC's output, and understood at a glance.
10//!
11//! Two synthetic files come out of this, and they are the two GCC names in a diagnostic:
12//! `<built-in>` for the generated set and `<command-line>` for `-D` and `-U`. Keeping them
13//! apart is what lets "`FOO` redefined" point at the command line rather than at a line
14//! nobody wrote.
15//!
16//! The decision that everything else follows from is in section 4.5: we define `__GNUC__`,
17//! which means glibc's headers, the kernel's headers and every autoconf probe take the GNU
18//! path. The version claimed is deliberately conservative and is a knob, because claiming too
19//! high a version means headers use extensions we do not have, and the matrix in `rucc-gnu`
20//! is the list of promises the claim makes.
21
22use rucc_base::float::Format;
23use rucc_session::{GnucVersion, OptLevel, Options, Std};
24use rucc_target::{Arch, Env, Os, TargetInfo};
25
26/// The name a diagnostic about the generated set points at.
27pub const BUILT_IN: &str = "<built-in>";
28
29/// The name a diagnostic about `-D` or `-U` points at.
30pub const COMMAND_LINE: &str = "<command-line>";
31
32/// The translation date, as `__DATE__` and `__TIME__` spell it.
33///
34/// Fixed for the whole translation unit, which is what the standard requires and what makes
35/// the two macros ordinary object-like macros rather than something the expander has to know
36/// about.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Timestamp {
39    /// `Mmm dd yyyy`, with the day space padded, which is the format the standard fixes.
40    pub date: String,
41    /// `hh:mm:ss`.
42    pub time: String,
43}
44
45impl Timestamp {
46    /// The current time, or `SOURCE_DATE_EPOCH` when the build asked for a reproducible one.
47    ///
48    /// Reading the environment here rather than in the driver is what GCC does, and it keeps
49    /// the variable working for an embedder who never goes through a command line.
50    pub fn now() -> Timestamp {
51        let seconds = match std::env::var("SOURCE_DATE_EPOCH").ok().and_then(|v| v.parse().ok()) {
52            Some(fixed) => fixed,
53            None => std::time::SystemTime::now()
54                .duration_since(std::time::UNIX_EPOCH)
55                .map_or(0, |d| d.as_secs() as i64),
56        };
57        Timestamp::from_unix(seconds)
58    }
59
60    /// The time `seconds` after the epoch, in UTC.
61    ///
62    /// UTC rather than local time, because a compiler whose output depends on the machine's
63    /// time zone is a compiler whose output is not reproducible.
64    pub fn from_unix(seconds: i64) -> Timestamp {
65        let days = seconds.div_euclid(86_400);
66        let rest = seconds.rem_euclid(86_400);
67        let (year, month, day) = civil_from_days(days);
68        const MONTHS: [&str; 12] =
69            ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
70        let name = MONTHS[(month - 1) as usize];
71        Timestamp {
72            date: format!("{name} {day:2} {year}"),
73            time: format!("{:02}:{:02}:{:02}", rest / 3600, (rest / 60) % 60, rest % 60),
74        }
75    }
76}
77
78/// The year, month and day `days` after 1970-01-01.
79///
80/// Howard Hinnant's civil calendar algorithm, which is a handful of divisions and no table.
81/// It is here rather than in a dependency because the whole workspace has no dependencies,
82/// and a date conversion is not a good reason to acquire the first one.
83fn civil_from_days(days: i64) -> (i64, u32, u32) {
84    // Shift the epoch to 0000-03-01, so that a leap day is the last day of the year and the
85    // month lengths become a repeating pattern that one division can invert.
86    let shifted = days + 719_468;
87    let era = shifted.div_euclid(146_097);
88    let day_of_era = shifted.rem_euclid(146_097);
89    let year_of_era =
90        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
91    let year = year_of_era + era * 400;
92    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
93    let marched = (5 * day_of_year + 2) / 153;
94    let day = (day_of_year - (153 * marched + 2) / 5 + 1) as u32;
95    let month = if marched < 10 { marched + 3 } else { marched - 9 } as u32;
96    (year + i64::from(month <= 2), month, day)
97}
98
99/// Everything the predefined set is built from that is not the target.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Predef {
102    /// The dialect, which decides `__STDC_VERSION__`.
103    pub std: Std,
104    /// Whether the GNU extensions are on, which is `-std=gnu23` rather than `-std=c23`. It
105    /// decides `__STRICT_ANSI__` and the unarmoured `linux` and `unix` macros.
106    pub gnu_extensions: bool,
107    /// Whether the unit is under GNU's reading of `inline`, which is `-fgnu89-inline`. It decides
108    /// which of `__GNUC_GNU_INLINE__` and `__GNUC_STDC_INLINE__` is defined, and the C89 dialects
109    /// are under that reading whatever it says.
110    pub gnu89_inline: bool,
111    /// The GCC release claimed.
112    pub gnuc: GnucVersion,
113    /// Decides `__OPTIMIZE__`, `__OPTIMIZE_SIZE__` and `__NO_INLINE__`.
114    pub opt_level: OptLevel,
115    /// Whether there is a standard library, which is `-ffreestanding` turned around.
116    pub hosted: bool,
117    /// `__DATE__` and `__TIME__`.
118    pub timestamp: Timestamp,
119    /// `-D` in command line order. `FOO` means `FOO=1`, as GCC has it.
120    pub defines: Vec<String>,
121    /// `-U` in command line order, applied after the defines.
122    pub undefines: Vec<String>,
123}
124
125impl Predef {
126    /// The default dialect, `gnu23`, at `-O0`.
127    pub fn new() -> Predef {
128        Predef {
129            std: Std::default(),
130            gnu_extensions: true,
131            gnu89_inline: false,
132            gnuc: GnucVersion::default(),
133            opt_level: OptLevel::O0,
134            hosted: true,
135            timestamp: Timestamp::now(),
136            defines: Vec::new(),
137            undefines: Vec::new(),
138        }
139    }
140}
141
142impl Predef {
143    /// The set the command line asked for.
144    ///
145    /// The mapping lives here rather than in the driver because it is the definition of what
146    /// each flag means to the macro set, and the driver's job is to parse a command line, not
147    /// to know that `-ffreestanding` is `__STDC_HOSTED__` being zero.
148    pub fn for_options(opts: &Options) -> Predef {
149        Predef {
150            std: opts.std,
151            gnu_extensions: opts.gnu_extensions,
152            gnu89_inline: opts.gnu89_inline,
153            gnuc: opts.gnuc,
154            opt_level: opts.opt_level,
155            hosted: opts.hosted,
156            timestamp: Timestamp::now(),
157            defines: opts.defines.clone(),
158            undefines: opts.undefines.clone(),
159        }
160    }
161}
162
163impl Default for Predef {
164    fn default() -> Predef {
165        Predef::new()
166    }
167}
168
169/// A file of `#define` lines being built up.
170struct Defs {
171    text: String,
172}
173
174impl Defs {
175    fn new() -> Defs {
176        Defs { text: String::new() }
177    }
178
179    /// `#define name value`.
180    fn set(&mut self, name: &str, value: &str) {
181        self.text.push_str("#define ");
182        self.text.push_str(name);
183        self.text.push(' ');
184        self.text.push_str(value);
185        self.text.push('\n');
186    }
187
188    /// `#define name 1`, which is what a macro that is only ever tested for needs.
189    fn flag(&mut self, name: &str) {
190        self.set(name, "1");
191    }
192
193    fn set_if(&mut self, when: bool, name: &str, value: &str) {
194        if when {
195            self.set(name, value);
196        }
197    }
198
199    fn flag_if(&mut self, when: bool, name: &str) {
200        if when {
201            self.flag(name);
202        }
203    }
204}
205
206/// The whole predefined set for a target, as the text of a file.
207pub(crate) fn built_in(target: &TargetInfo, opts: &Predef) -> String {
208    let mut d = Defs::new();
209    identity(&mut d, target, opts);
210    // `__DATE__` and `__TIME__` are fixed for the whole translation unit, which is what the
211    // standard asks for, so they are ordinary object-like macros and the expander needs to
212    // know nothing about them.
213    d.set("__DATE__", &format!("\"{}\"", opts.timestamp.date));
214    d.set("__TIME__", &format!("\"{}\"", opts.timestamp.time));
215    dialect(&mut d, opts);
216    optimization(&mut d, opts);
217    platform(&mut d, target, opts);
218    sizes(&mut d, target);
219    integers(&mut d, target);
220    floats(&mut d, target);
221    atomics(&mut d, target);
222    d.text
223}
224
225/// `-D` and `-U`, as the text of a file.
226///
227/// Empty when there are none, so that the caller can skip adding a file that would say
228/// nothing. The undefines come last whatever order they were written in, because `-U` beats
229/// `-D` in GCC no matter which side of it the `-D` was on.
230pub(crate) fn command_line(opts: &Predef) -> String {
231    let mut d = Defs::new();
232    for define in &opts.defines {
233        match define.split_once('=') {
234            Some((name, value)) => d.set(name, value),
235            // `-DFOO` is `-DFOO=1`. A macro nobody gave a value to is one that is only ever
236            // tested for, and giving it an empty body would break `#if FOO`.
237            None => d.flag(define),
238        }
239    }
240    for name in &opts.undefines {
241        d.text.push_str("#undef ");
242        d.text.push_str(name);
243        d.text.push('\n');
244    }
245    d.text
246}
247
248/// Who the compiler says it is.
249fn identity(d: &mut Defs, target: &TargetInfo, opts: &Predef) {
250    d.flag("__rucc__");
251    d.set("__rucc_version__", "\"0.1.0\"");
252    d.set("__rucc_major__", "0");
253    d.set("__rucc_minor__", "1");
254    d.set("__rucc_patchlevel__", "0");
255    // The promise from section 4.5. Everything in the matrix hangs off this line.
256    d.set("__GNUC__", &opts.gnuc.major.to_string());
257    d.set("__GNUC_MINOR__", &opts.gnuc.minor.to_string());
258    d.set("__GNUC_PATCHLEVEL__", &opts.gnuc.patch.to_string());
259    d.set("__VERSION__", "\"rucc 0.1.0\"");
260    // Not `__clang__`, deliberately. Section 4.5 says so, and a header that takes the Clang
261    // path expects Clang's extension surface rather than GCC's.
262    //
263    // Which of the two readings of `inline` is in force, which a header reads to decide how to
264    // write its own inline definitions: glibc's `__extern_inline` is `extern __inline` under the
265    // one and adds `__attribute__ ((__gnu_inline__))` under the other. C99 changed the meaning of
266    // the keyword and gcc follows the dialect, so the C89 ones keep GNU's reading and every
267    // dialect after them takes C's until `-fgnu89-inline` says otherwise.
268    let gnu_inline = opts.gnu89_inline || opts.std == Std::C89;
269    d.flag_if(gnu_inline, "__GNUC_GNU_INLINE__");
270    d.flag_if(!gnu_inline, "__GNUC_STDC_INLINE__");
271    // The charsets a literal is converted to. Both are fixed here rather than settable, since
272    // there is no `-fexec-charset` to set them with, and both are what gcc answers with none.
273    // The wide one follows `wchar_t`, which is sixteen bits on Windows and thirty two
274    // everywhere else, so it is the one target fact in this function.
275    d.set("__GNUC_EXECUTION_CHARSET_NAME", "\"UTF-8\"");
276    let wide = if target.wchar_width == 16 { "\"UTF-16LE\"" } else { "\"UTF-32LE\"" };
277    d.set("__GNUC_WIDE_EXECUTION_CHARSET_NAME", wide);
278    // The C++ ABI this would be if it compiled C++, which gcc defines in C as well. It is not
279    // a claim about this compiler so much as a number headers read: libstdc++ is not the only
280    // thing that tests it, and a C header shared with a C++ one reaches it through `extern
281    // "C"` guards. The value is gcc 16's.
282    d.set("__GXX_ABI_VERSION", "1021");
283}
284
285/// What the dialect flags say.
286fn dialect(d: &mut Defs, opts: &Predef) {
287    d.flag("__STDC__");
288    d.set_if(opts.hosted, "__STDC_HOSTED__", "1");
289    d.set_if(!opts.hosted, "__STDC_HOSTED__", "0");
290    if let Some(version) = opts.std.stdc_version() {
291        d.set("__STDC_VERSION__", version);
292    }
293    // Defined exactly when the extensions are off, which is the whole difference between
294    // `-std=c23` and `-std=gnu23` as far as the preprocessor is concerned.
295    d.flag_if(!opts.gnu_extensions, "__STRICT_ANSI__");
296    d.flag("__STDC_UTF_16__");
297    d.flag("__STDC_UTF_32__");
298    d.flag("__STDC_IEC_559__");
299    d.flag("__STDC_IEC_559_COMPLEX__");
300    d.set_if(opts.std == Std::C23, "__STDC_IEC_60559_BFP__", "202311L");
301    d.set("__STDC_ISO_10646__", "201706L");
302    // The type behind `char8_t`, which C23 added and no dialect before it has. It sits here
303    // rather than next to `__CHAR16_TYPE__` and `__CHAR32_TYPE__` because those two are the
304    // same in every dialect and this one is not, which is the whole reason a header can test
305    // for it: gcc's own `stdatomic.h` writes `atomic_char8_t` under `#ifdef __CHAR8_TYPE__`
306    // and gets it in C23 and not in C17.
307    d.set_if(opts.std == Std::C23, "__CHAR8_TYPE__", "unsigned char");
308    // C11 made these conditional features, and a header that sees `__STDC_VERSION__` at
309    // 201112 with no `__STDC_NO_ATOMICS__` next to it will use `_Atomic`. Each one here is a
310    // claim not to have something, so each one is only correct while it stays true: atomics
311    // because there is no `stdatomic.h` to include, threads because there is no `threads.h`,
312    // and complex because the arithmetic is not lowered.
313    //
314    // Variable length arrays are not on this list, because they work. Claiming otherwise is
315    // not a harmless overstatement of caution: glibc's `regex.h` writes the bound of
316    // `regexec`'s match array as `_REGEX_NELTS (__nmatch)`, which is the parameter when the
317    // dialect has them and nothing at all when a compiler says it does not, so the claim
318    // silently changes a declaration in a header rather than turning something off.
319    if opts.std.has_c11() {
320        d.flag("__STDC_NO_ATOMICS__");
321        d.flag("__STDC_NO_THREADS__");
322        d.flag("__STDC_NO_COMPLEX__");
323    }
324    // What `__has_embed` answers with. They are defined in every dialect and not only in C23,
325    // because the operator is answerable in every dialect and a header that writes
326    // `#if __has_embed(...) == __STDC_EMBED_FOUND__` under `-std=gnu17` would otherwise be
327    // comparing against zero and taking the not found branch on a resource that is there.
328    d.set("__STDC_EMBED_NOT_FOUND__", "0");
329    d.set("__STDC_EMBED_FOUND__", "1");
330    d.set("__STDC_EMBED_EMPTY__", "2");
331}
332
333/// The memory orders and the lock free answers.
334///
335/// These are here whether or not `_Atomic` is, and `__STDC_NO_ATOMICS__` does not turn them
336/// off, because they are the numbering the `__atomic` builtins take rather than a promise
337/// about the language. musl's `stdatomic.h` writes `memory_order_relaxed = __ATOMIC_RELAXED`
338/// with no test around it at all, so a compiler without them prints an enumerator whose value
339/// is an identifier.
340///
341/// Two means always lock free, and every integer type gets a two on all three targets, which
342/// are all sixty four bit machines. `long long` is the one that would change on a thirty two
343/// bit target, where a double word load is an instruction the machine may or may not have.
344fn atomics(d: &mut Defs, target: &TargetInfo) {
345    d.set("__ATOMIC_RELAXED", "0");
346    d.set("__ATOMIC_CONSUME", "1");
347    d.set("__ATOMIC_ACQUIRE", "2");
348    d.set("__ATOMIC_RELEASE", "3");
349    d.set("__ATOMIC_ACQ_REL", "4");
350    d.set("__ATOMIC_SEQ_CST", "5");
351    // The gate is the machine word rather than `long`, because Windows has a thirty two bit
352    // `long` on a sixty four bit machine and its `long long` is still one instruction.
353    let llong = if target.pointer_width == 64 { "2" } else { "1" };
354    for name in [
355        "BOOL", "CHAR", "CHAR8_T", "CHAR16_T", "CHAR32_T", "WCHAR_T", "SHORT", "INT", "LONG",
356        "POINTER",
357    ] {
358        d.set(&format!("__GCC_ATOMIC_{name}_LOCK_FREE"), "2");
359    }
360    // The one that is not always two: a target whose word is thirty two bits wide can only
361    // promise `long long` is lock free if it has a double word instruction, and the honest
362    // answer there is sometimes rather than always.
363    d.set("__GCC_ATOMIC_LLONG_LOCK_FREE", llong);
364    d.set("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
365    // What `__sync_bool_compare_and_swap` works on, one macro per width in bytes. Every target
366    // here has the instruction at all four, and glibc reads these rather than the `__atomic_*`
367    // set because they are the older question and the answer is the same one.
368    for width in [1, 2, 4, 8] {
369        d.flag(&format!("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_{width}"));
370    }
371    // The two flag bits an x86 memory order can carry, for the hardware lock elision prefixes.
372    // They are numbers a program passes back to a builtin rather than a claim that the prefix
373    // is emitted, and a program that computes one on a machine where the macro is missing gets
374    // a preprocessor error rather than a slower atomic.
375    if target.triple.arch == Arch::X86_64 {
376        d.set("__ATOMIC_HLE_ACQUIRE", "65536");
377        d.set("__ATOMIC_HLE_RELEASE", "131072");
378    }
379}
380
381/// What the optimizer level says.
382fn optimization(d: &mut Defs, opts: &Predef) {
383    d.flag_if(opts.opt_level.runs_optimizer(), "__OPTIMIZE__");
384    d.flag_if(opts.opt_level.is_size(), "__OPTIMIZE_SIZE__");
385    // glibc's headers test this before deciding whether to define a function as an inline
386    // wrapper, so getting it wrong changes what a program links against.
387    d.flag_if(!opts.opt_level.runs_optimizer(), "__NO_INLINE__");
388    // Zero, and zero until there is a `-ffast-math` to make it one. glibc's `math.h` reads it
389    // to decide whether to declare the `__*_finite` aliases, so it has to be defined rather
390    // than merely not claimed: a header testing `#if __FINITE_MATH_ONLY__ > 0` on a compiler
391    // that leaves it undefined takes the same branch, but one writing `#if
392    // !__FINITE_MATH_ONLY__` is a different question and gcc gives it an answer.
393    d.set("__FINITE_MATH_ONLY__", "0");
394}
395
396/// The architecture, the operating system and the object format.
397fn platform(d: &mut Defs, target: &TargetInfo, opts: &Predef) {
398    let triple = target.triple;
399    match triple.arch {
400        Arch::X86_64 => {
401            d.flag("__x86_64__");
402            d.flag("__x86_64");
403            d.flag("__amd64__");
404            d.flag("__amd64");
405            d.flag("__SSE__");
406            d.flag("__SSE2__");
407            d.flag("__MMX__");
408            d.flag("__SSE_MATH__");
409            d.flag("__SSE2_MATH__");
410            d.flag("__k8");
411            d.flag("__k8__");
412            // FXSAVE and FXRSTOR, which every x86-64 has, and the small code model, which is
413            // the default and the only one a program gets without being told otherwise.
414            d.flag("__FXSR__");
415            d.flag("__code_model_small__");
416            // The MMX registers are not used on x86-64: the sixty four bit operations go
417            // through SSE instead. gcc's own `xmmintrin.h` reads this to decide how to write
418            // `_mm_maskmove_si64`, so a compiler that leaves it undefined is handed a
419            // different function body than gcc is, which is what the header sweep found.
420            d.flag("__MMX_WITH_SSE__");
421        }
422        Arch::Aarch64 => {
423            d.flag("__aarch64__");
424            d.flag("__AARCH64EL__");
425            d.set("__ARM_ARCH", "8");
426            d.set("__ARM_ARCH_PROFILE", "'A'");
427            d.set("__ARM_64BIT_STATE", "1");
428            d.set("__ARM_ALIGN_MAX_PWR", "28");
429            d.set("__ARM_FP", "0xe");
430            d.set("__ARM_NEON", "1");
431            d.set("__ARM_FEATURE_UNALIGNED", "1");
432            d.set("__ARM_PCS_AAPCS64", "1");
433        }
434        Arch::Riscv64 => {
435            d.flag("__riscv");
436            d.set("__riscv_xlen", "64");
437            d.set("__riscv_flen", "64");
438            d.flag("__riscv_float_abi_double");
439            d.flag("__riscv_muldiv");
440            d.flag("__riscv_atomic");
441            d.flag("__riscv_compressed");
442            d.set("__riscv_cmodel_medlow", "1");
443        }
444    }
445    match triple.os {
446        Os::Linux => {
447            d.flag("__linux__");
448            d.flag("__linux");
449            d.flag("__unix__");
450            d.flag("__unix");
451            d.flag("__gnu_linux__");
452            d.flag("__ELF__");
453            // The unarmoured spellings are not reserved identifiers, so a strict mode may not
454            // define them. Autoconf still tests for `linux`, which is why they exist at all.
455            if opts.gnu_extensions {
456                d.flag("linux");
457                d.flag("unix");
458            }
459        }
460        Os::Darwin => {
461            d.flag("__APPLE__");
462            d.flag("__MACH__");
463            d.flag("__unix__");
464            d.flag("__unix");
465            d.set("__APPLE_CC__", "6000");
466            d.set("__DYNAMIC__", "1");
467            if triple.arch == Arch::Aarch64 {
468                // Apple's own spelling of the architecture, which its headers use rather than
469                // __aarch64__. sys/cdefs.h tests for it by name and reaches an #error called
470                // "Unsupported architecture" without it, so every system header on this
471                // platform fails on the first include until these two are here.
472                d.flag("__arm64__");
473                d.flag("__arm64");
474            }
475            if opts.gnu_extensions {
476                d.flag("unix");
477            }
478        }
479        Os::Windows => {
480            d.flag("_WIN32");
481            d.flag("__WIN32__");
482            d.flag("_WIN64");
483            d.flag("__WIN64__");
484            d.flag("__MINGW32__");
485        }
486        Os::None => {
487            // Freestanding. `__ELF__` still holds, because the object format is a property of
488            // the target rather than of having an operating system under it.
489            d.flag("__ELF__");
490        }
491    }
492    match triple.env {
493        Env::Musl => d.flag("__musl__"),
494        Env::Gnu | Env::None | Env::Msvc => {}
495    }
496    // LP64 is the model everywhere except Windows, and a great deal of code tests for it
497    // rather than testing pointer and long widths separately.
498    if target.long_width == 64 && target.pointer_width == 64 {
499        d.flag("__LP64__");
500        d.flag("_LP64");
501    }
502    // What the assembler prepends to a C name to get the symbol. Mach-O keeps the leading
503    // underscore that every a.out toolchain had and ELF dropped it. It has to be defined even
504    // where it is empty, because of how it is used: glibc writes `__asm__ (__ASMNAME (name))`
505    // and that stringifies `__USER_LABEL_PREFIX__`, so a compiler that leaves it undefined
506    // does not get an error, it gets the name of the macro as the string and renames the
507    // function.
508    d.set("__USER_LABEL_PREFIX__", if triple.os == Os::Darwin { "_" } else { "" });
509    // Its counterpart, what the assembler puts in front of a register name. Empty on every
510    // target here, since all three assemble in a syntax that does not mark registers, and
511    // defined anyway for the same reason as the line above: it is used inside a stringize.
512    d.set("__REGISTER_PREFIX__", "");
513
514    // Position independent code is the default on the ELF targets and on Apple's, which is
515    // what a distribution build expects. The value 2 is GCC's for `-fPIC` rather than `-fpic`.
516    if !matches!(triple.os, Os::Windows) {
517        d.set("__PIC__", "2");
518        d.set("__pic__", "2");
519    }
520}
521
522/// `__CHAR_BIT__`, the `__SIZEOF_*__` family and the alignment macros.
523fn sizes(d: &mut Defs, target: &TargetInfo) {
524    let pointer = target.pointer_width / 8;
525    // The two hardware interference sizes, which say how far apart two objects have to be for
526    // a write to one not to invalidate the other's cache line, and how close together two have
527    // to be to share one. A cache line is sixty four bytes on every target here, so the two
528    // answers are the same number and gcc gives the same number as well.
529    d.set("__GCC_CONSTRUCTIVE_SIZE", "64");
530    d.set("__GCC_DESTRUCTIVE_SIZE", "64");
531    let long = target.long_width / 8;
532    let long_double = target.long_double_width / 8;
533    d.set("__CHAR_BIT__", "8");
534    d.set("__SIZEOF_SHORT__", "2");
535    d.set("__SIZEOF_INT__", "4");
536    d.set("__SIZEOF_LONG__", &long.to_string());
537    d.set("__SIZEOF_LONG_LONG__", "8");
538    d.set("__SIZEOF_INT128__", "16");
539    d.set("__SIZEOF_FLOAT__", "4");
540    d.set("__SIZEOF_DOUBLE__", "8");
541    d.set("__SIZEOF_LONG_DOUBLE__", &long_double.to_string());
542    d.set("__SIZEOF_POINTER__", &pointer.to_string());
543    d.set("__SIZEOF_SIZE_T__", &pointer.to_string());
544    d.set("__SIZEOF_PTRDIFF_T__", &pointer.to_string());
545    d.set("__SIZEOF_WCHAR_T__", &wchar(target).size.to_string());
546    d.set("__SIZEOF_WINT_T__", "4");
547    d.set("__BIGGEST_ALIGNMENT__", "16");
548    // The `__BYTE_ORDER__` family, which the kernel and every serialisation library read.
549    // The names of the orders are defined whichever one is in force, because code compares
550    // against both.
551    d.set("__ORDER_LITTLE_ENDIAN__", "1234");
552    d.set("__ORDER_BIG_ENDIAN__", "4321");
553    d.set("__ORDER_PDP_ENDIAN__", "3412");
554    let order =
555        if target.little_endian { "__ORDER_LITTLE_ENDIAN__" } else { "__ORDER_BIG_ENDIAN__" };
556    d.set("__BYTE_ORDER__", order);
557    d.set("__FLOAT_WORD_ORDER__", order);
558    d.flag_if(!target.char_is_signed, "__CHAR_UNSIGNED__");
559}
560
561/// How `wchar_t` is spelled on a target, and what it holds.
562struct Wchar {
563    /// The C type it is a name for.
564    spelling: &'static str,
565    /// Its width in bytes.
566    size: u32,
567    /// `__WCHAR_MAX__`.
568    max: &'static str,
569    /// `__WCHAR_MIN__`.
570    min: &'static str,
571}
572
573/// `wchar_t` is the type that divides the targets most and is written down least.
574///
575/// Windows makes it 16 bits so that a wide string is UTF-16. AArch64 Linux makes it unsigned,
576/// following the psABI's rule for plain `char`, while x86-64 Linux makes it signed. Code that
577/// compares a `wchar_t` against a negative value is correct on one and not on the other.
578///
579/// The width and the signedness come from the target description rather than from another match
580/// on the triple, because the lexer needs the same two facts to convert a wide literal and the
581/// two answers have to be the same one.
582fn wchar(target: &TargetInfo) -> Wchar {
583    match (target.wchar_width, target.wchar_is_signed) {
584        (16, false) => Wchar { spelling: "short unsigned int", size: 2, max: "0xffff", min: "0" },
585        (16, true) => Wchar { spelling: "short int", size: 2, max: "0x7fff", min: "(-32767 - 1)" },
586        (_, false) => Wchar { spelling: "unsigned int", size: 4, max: "0xffffffffU", min: "0U" },
587        (_, true) => {
588            Wchar { spelling: "int", size: 4, max: "0x7fffffff", min: "(-__WCHAR_MAX__ - 1)" }
589        }
590    }
591}
592
593/// How `wint_t` is spelled on a target, and what it holds.
594struct Wint {
595    /// The C type it is a name for.
596    spelling: &'static str,
597    /// `__WINT_MAX__`.
598    max: &'static str,
599    /// `__WINT_MIN__`.
600    min: &'static str,
601    /// `__WINT_WIDTH__`, which follows the spelling rather than `__SIZEOF_WINT_T__`.
602    width: u32,
603}
604
605/// `wint_t` does not follow `wchar_t`, and Darwin is where that shows.
606///
607/// Apple makes it a signed `int`, so that `WEOF` is negative the way `EOF` is, while Linux
608/// makes it `unsigned int` and gives `WEOF` the value `0xffffffff`. The SDK's `arm/_types.h`
609/// spells `__darwin_wint_t` as `__WINT_TYPE__` and nothing else, so getting this wrong changes
610/// the signedness of every wide character function's argument on that platform.
611fn wint(target: &TargetInfo) -> Wint {
612    match target.triple.os {
613        Os::Windows => Wint { spelling: "short unsigned int", max: "0xffff", min: "0", width: 16 },
614        Os::Darwin => {
615            Wint { spelling: "int", max: "0x7fffffff", min: "(-__WINT_MAX__ - 1)", width: 32 }
616        }
617        _ => Wint { spelling: "unsigned int", max: "0xffffffffU", min: "0U", width: 32 },
618    }
619}
620
621/// The integer type names, their limits, and the exact width family.
622fn integers(d: &mut Defs, target: &TargetInfo) {
623    // The one fact everything below turns on: which type is 64 bits wide. On LP64 it is
624    // `long`, and on Windows LLP64 it is `long long`, and every `size_t`, `intmax_t` and
625    // `int64_t` spelling follows from that.
626    let lp64 = target.long_width == 64;
627    let wide = if lp64 { "long int" } else { "long long int" };
628    let wide_unsigned = if lp64 { "long unsigned int" } else { "long long unsigned int" };
629    let wide_suffix = if lp64 { "L" } else { "LL" };
630    let wide_max = format!("0x7fffffffffffffff{wide_suffix}");
631    let wide_umax = format!("0xffffffffffffffffU{wide_suffix}");
632
633    d.set("__SCHAR_MAX__", "0x7f");
634    d.set("__SHRT_MAX__", "0x7fff");
635    d.set("__INT_MAX__", "0x7fffffff");
636    d.set("__LONG_MAX__", if lp64 { "0x7fffffffffffffffL" } else { "0x7fffffffL" });
637    d.set("__LONG_LONG_MAX__", "0x7fffffffffffffffLL");
638    d.set("__INTMAX_MAX__", &wide_max);
639    d.set("__UINTMAX_MAX__", &wide_umax);
640    d.set("__SIZE_MAX__", &wide_umax);
641    d.set("__PTRDIFF_MAX__", &wide_max);
642    d.set("__INTPTR_MAX__", &wide_max);
643    d.set("__UINTPTR_MAX__", &wide_umax);
644    d.set("__SIG_ATOMIC_MAX__", "0x7fffffff");
645    d.set("__SIG_ATOMIC_MIN__", "(-__SIG_ATOMIC_MAX__ - 1)");
646    // The widest `_BitInt` this compiler builds, which is narrower than gcc 16's sixty five
647    // thousand five hundred and thirty five because a folded constant here is a hundred and
648    // twenty eight bits wide. A program that reads this macro to decide what to write gets an
649    // answer it can rely on, which is the point of saying a number smaller than gcc's rather
650    // than saying gcc's and refusing what it asked for. `MAX_BIT_INT_WIDTH` in `rucc-sema` is
651    // the same number and has to be changed with it.
652    d.set("__BITINT_MAXWIDTH__", "128");
653
654    let wchar = wchar(target);
655    d.set("__WCHAR_TYPE__", wchar.spelling);
656    d.set("__WCHAR_MAX__", wchar.max);
657    d.set("__WCHAR_MIN__", wchar.min);
658    let wint = wint(target);
659    d.set("__WINT_TYPE__", wint.spelling);
660    d.set("__WINT_MAX__", wint.max);
661    d.set("__WINT_MIN__", wint.min);
662    d.set("__SIZE_TYPE__", wide_unsigned);
663    d.set("__PTRDIFF_TYPE__", wide);
664    d.set("__INTMAX_TYPE__", wide);
665    d.set("__UINTMAX_TYPE__", wide_unsigned);
666    d.set("__INTPTR_TYPE__", wide);
667    d.set("__UINTPTR_TYPE__", wide_unsigned);
668    d.set("__SIG_ATOMIC_TYPE__", "int");
669    d.set("__CHAR16_TYPE__", "short unsigned int");
670    d.set("__CHAR32_TYPE__", "unsigned int");
671    d.set("__INTMAX_C(c)", &format!("c ## {wide_suffix}"));
672    d.set("__UINTMAX_C(c)", &format!("c ## U{wide_suffix}"));
673
674    // The exact width family, which is what a freestanding `stdint.h` is written out of.
675    exact(d, 8, "signed char", "unsigned char", "0x7f", "0xff", "");
676    exact(d, 16, "short int", "short unsigned int", "0x7fff", "0xffff", "");
677    // No suffix. An `int` needs none, and the `U` on the unsigned side is added by `exact`
678    // rather than being part of the width.
679    exact(d, 32, "int", "unsigned int", "0x7fffffff", "0xffffffffU", "");
680    exact(d, 64, wide, wide_unsigned, &wide_max, &wide_umax, wide_suffix);
681
682    // The fast types. GCC makes the 16 and 32 bit ones `long` on x86-64 glibc and `int`
683    // everywhere else, and a header that computes a printf format from the type name notices
684    // the difference.
685    //
686    // musl is the reason this is not simply a question of the architecture. musl defines
687    // `int_fast16_t` and `int_fast32_t` as `int32_t` on every target it supports, GCC built
688    // for a musl target agrees with it, and GCC built for glibc on the same processor does
689    // not. The place it shows is `stdatomic.h`, which GCC ships and writes directly out of
690    // these macros: `typedef _Atomic __INT_FAST16_TYPE__ atomic_int_fast16_t;`. Get this wrong
691    // and every atomic fast type in the program is the wrong width.
692    let fast_is_wide = target.triple.arch == Arch::X86_64 && lp64 && target.triple.env != Env::Musl;
693    let fast_middle = if fast_is_wide { wide } else { "int" };
694    d.set("__INT_FAST8_TYPE__", "signed char");
695    d.set("__UINT_FAST8_TYPE__", "unsigned char");
696    d.set("__INT_FAST8_MAX__", "0x7f");
697    d.set("__UINT_FAST8_MAX__", "0xff");
698    for width in [16, 32] {
699        let unsigned = if fast_middle == "int" { "unsigned int" } else { wide_unsigned };
700        let max = if fast_middle == "int" { "0x7fffffff" } else { wide_max.as_str() };
701        let umax = if fast_middle == "int" { "0xffffffffU" } else { wide_umax.as_str() };
702        d.set(&format!("__INT_FAST{width}_TYPE__"), fast_middle);
703        d.set(&format!("__UINT_FAST{width}_TYPE__"), unsigned);
704        d.set(&format!("__INT_FAST{width}_MAX__"), max);
705        d.set(&format!("__UINT_FAST{width}_MAX__"), umax);
706    }
707    d.set("__INT_FAST64_TYPE__", wide);
708    d.set("__UINT_FAST64_TYPE__", wide_unsigned);
709    d.set("__INT_FAST64_MAX__", &wide_max);
710    d.set("__UINT_FAST64_MAX__", &wide_umax);
711
712    widths(d, target, &wchar, &wint, if fast_is_wide { 64 } else { 32 });
713}
714
715/// The widths, which C23's `limits.h` and `stdint.h` are written out of.
716///
717/// Twenty macros and not a few more: there is no `__INT8_WIDTH__`, because the width of an
718/// exact width type is in its name and gcc does not define one, and there is no unsigned member
719/// of any of these pairs, because a signed type and its unsigned counterpart have the same
720/// width and `UINTMAX_WIDTH` is written `__INTMAX_WIDTH__` in every header that needs it.
721///
722/// Each of these says how many value bits and sign bits the type has, which is not the same as
723/// how many bits it occupies. They agree for every type on every target here, and the day one of
724/// them does not, this is the family that has to say the smaller number.
725fn widths(d: &mut Defs, target: &TargetInfo, wchar: &Wchar, wint: &Wint, fast_middle: u32) {
726    let pointer = target.pointer_width;
727    d.set("__SCHAR_WIDTH__", "8");
728    d.set("__SHRT_WIDTH__", "16");
729    d.set("__INT_WIDTH__", "32");
730    d.set("__LONG_WIDTH__", &target.long_width.to_string());
731    d.set("__LONG_LONG_WIDTH__", "64");
732    d.set("__INTMAX_WIDTH__", "64");
733    d.set("__INTPTR_WIDTH__", &pointer.to_string());
734    d.set("__PTRDIFF_WIDTH__", &pointer.to_string());
735    d.set("__SIZE_WIDTH__", &pointer.to_string());
736    d.set("__SIG_ATOMIC_WIDTH__", "32");
737    d.set("__WCHAR_WIDTH__", &(wchar.size * 8).to_string());
738    d.set("__WINT_WIDTH__", &wint.width.to_string());
739    for width in [8, 16, 32, 64] {
740        d.set(&format!("__INT_LEAST{width}_WIDTH__"), &width.to_string());
741    }
742    d.set("__INT_FAST8_WIDTH__", "8");
743    d.set("__INT_FAST16_WIDTH__", &fast_middle.to_string());
744    d.set("__INT_FAST32_WIDTH__", &fast_middle.to_string());
745    d.set("__INT_FAST64_WIDTH__", "64");
746}
747
748/// One width of the exact and least families, which are the same types.
749fn exact(
750    d: &mut Defs,
751    width: u32,
752    signed: &str,
753    unsigned: &str,
754    max: &str,
755    umax: &str,
756    // The suffix the width needs and nothing more, so `""`, `"L"` or `"LL"`. The `U` that
757    // makes a constant unsigned is added below and is not part of this, because a caller that
758    // wrote it here would produce `UU` on the unsigned macro and a stray `U` on the signed one.
759    width_suffix: &str,
760) {
761    d.set(&format!("__INT{width}_TYPE__"), signed);
762    d.set(&format!("__UINT{width}_TYPE__"), unsigned);
763    d.set(&format!("__INT{width}_MAX__"), max);
764    d.set(&format!("__UINT{width}_MAX__"), umax);
765    d.set(&format!("__INT_LEAST{width}_TYPE__"), signed);
766    d.set(&format!("__UINT_LEAST{width}_TYPE__"), unsigned);
767    d.set(&format!("__INT_LEAST{width}_MAX__"), max);
768    d.set(&format!("__UINT_LEAST{width}_MAX__"), umax);
769    // The constant makers. `__INT8_C(1)` is `1` and not `1 ## `, because a paste with nothing
770    // on the right is not a token the expander should have to think about.
771    //
772    // The `U` goes on only where the type is still unsigned after promotion. `uint8_t` and
773    // `uint16_t` are narrower than `int`, so an integer promotion turns them into a signed
774    // `int` and `UINT8_C(1)` has that type in gcc and in the standard's own words. Writing
775    // `1U` there is not a harmless extra: `UINT8_C(1) - 2` comes out as four billion odd
776    // instead of minus one, and a `_Generic` on it picks the unsigned arm. Every target this
777    // compiler has makes `int` thirty two bits, which is what makes the width enough to decide.
778    let unsigned_after_promotion = width >= 32;
779    let u = if unsigned_after_promotion { "U" } else { "" };
780    if width_suffix.is_empty() && u.is_empty() {
781        d.set(&format!("__INT{width}_C(c)"), "c");
782        d.set(&format!("__UINT{width}_C(c)"), "c");
783    } else if width_suffix.is_empty() {
784        d.set(&format!("__INT{width}_C(c)"), "c");
785        d.set(&format!("__UINT{width}_C(c)"), &format!("c ## {u}"));
786    } else {
787        d.set(&format!("__INT{width}_C(c)"), &format!("c ## {width_suffix}"));
788        d.set(&format!("__UINT{width}_C(c)"), &format!("c ## {u}{width_suffix}"));
789    }
790}
791
792/// What a header needs to know about one floating format, as the text the macros expand to.
793///
794/// The four values are written to the digit gcc writes them to rather than rounded to something
795/// tidier, because a header carrying its own copy of a limit compares the two spellings and a
796/// difference in the last place is a difference.
797struct Characteristics {
798    mant_dig: &'static str,
799    dig: &'static str,
800    min_exp: &'static str,
801    min_10_exp: &'static str,
802    max_exp: &'static str,
803    max_10_exp: &'static str,
804    decimal_dig: &'static str,
805    max: &'static str,
806    /// The largest value with a full significand, which is `max` for every format whose values
807    /// all have one and is smaller for the double-double, whose largest values do not.
808    ///
809    /// A double-double's high half can be as large as a `double` gets while its low half is
810    /// nowhere near, and the sum is then a number above anything the format can write with a
811    /// hundred and six significand bits behind it. So `LDBL_MAX` on PowerPC is `DBL_MAX` and
812    /// `LDBL_NORM_MAX` is a bit under half of it, and a program that reaches for the largest
813    /// value it can compute with wants the second.
814    norm_max: &'static str,
815    min: &'static str,
816    epsilon: &'static str,
817    denorm_min: &'static str,
818    /// Whether the format is one IEC 60559 describes, which every one of them is but the brain
819    /// float, whose significand is a `float`'s with sixteen bits cut off the end of it, and the
820    /// double-double, which is not a binary floating point format in IEC 60559's sense at all.
821    is_iec_60559: &'static str,
822}
823
824/// IEEE binary16, which is `_Float16`.
825const HALF: Characteristics = Characteristics {
826    mant_dig: "11",
827    dig: "3",
828    min_exp: "(-13)",
829    min_10_exp: "(-4)",
830    max_exp: "16",
831    max_10_exp: "4",
832    decimal_dig: "5",
833    max: "6.55040000000000000000000000000000000e+4",
834    norm_max: "6.55040000000000000000000000000000000e+4",
835    min: "6.10351562500000000000000000000000000e-5",
836    epsilon: "9.76562500000000000000000000000000000e-4",
837    denorm_min: "5.96046447753906250000000000000000000e-8",
838    is_iec_60559: "1",
839};
840
841/// The brain float, which nothing here names yet and which every format table has a row for.
842const BFLOAT16: Characteristics = Characteristics {
843    mant_dig: "8",
844    dig: "2",
845    min_exp: "(-125)",
846    min_10_exp: "(-37)",
847    max_exp: "128",
848    max_10_exp: "38",
849    decimal_dig: "4",
850    max: "3.38953138925153547590470800371487867e+38",
851    norm_max: "3.38953138925153547590470800371487867e+38",
852    min: "1.17549435082228750796873653722224568e-38",
853    epsilon: "7.81250000000000000000000000000000000e-3",
854    denorm_min: "9.18354961579912115600575419704879436e-41",
855    is_iec_60559: "0",
856};
857
858/// IEEE binary32, which is `float` and `_Float32`.
859const SINGLE: Characteristics = Characteristics {
860    mant_dig: "24",
861    dig: "6",
862    min_exp: "(-125)",
863    min_10_exp: "(-37)",
864    max_exp: "128",
865    max_10_exp: "38",
866    decimal_dig: "9",
867    max: "3.40282346638528859811704183484516925e+38",
868    norm_max: "3.40282346638528859811704183484516925e+38",
869    min: "1.17549435082228750796873653722224568e-38",
870    epsilon: "1.19209289550781250000000000000000000e-7",
871    denorm_min: "1.40129846432481707092372958328991613e-45",
872    is_iec_60559: "1",
873};
874
875/// IEEE binary64, which is `double`, `_Float64`, `_Float32x` and `long double` on Apple and
876/// on Windows.
877const DOUBLE: Characteristics = Characteristics {
878    mant_dig: "53",
879    dig: "15",
880    min_exp: "(-1021)",
881    min_10_exp: "(-307)",
882    max_exp: "1024",
883    max_10_exp: "308",
884    decimal_dig: "17",
885    max: "1.79769313486231570814527423731704357e+308",
886    norm_max: "1.79769313486231570814527423731704357e+308",
887    min: "2.22507385850720138309023271733240406e-308",
888    epsilon: "2.22044604925031308084726333618164062e-16",
889    denorm_min: "4.94065645841246544176568792868221372e-324",
890    is_iec_60559: "1",
891};
892
893/// The x87 eighty bit format, which on x86-64 is both `long double` and `_Float64x`.
894const X87: Characteristics = Characteristics {
895    mant_dig: "64",
896    dig: "18",
897    min_exp: "(-16381)",
898    min_10_exp: "(-4931)",
899    max_exp: "16384",
900    max_10_exp: "4932",
901    decimal_dig: "21",
902    max: "1.18973149535723176502126385303097021e+4932",
903    norm_max: "1.18973149535723176502126385303097021e+4932",
904    min: "3.36210314311209350626267781732175260e-4932",
905    epsilon: "1.08420217248550443400745280086994171e-19",
906    denorm_min: "3.64519953188247460252840593361941982e-4951",
907    is_iec_60559: "1",
908};
909
910/// IEEE binary128, which is `_Float128`, `_Float64x` off x86 and `long double` on AArch64 and
911/// RISC-V Linux.
912const QUAD: Characteristics = Characteristics {
913    mant_dig: "113",
914    dig: "33",
915    min_exp: "(-16381)",
916    min_10_exp: "(-4931)",
917    max_exp: "16384",
918    max_10_exp: "4932",
919    decimal_dig: "36",
920    max: "1.18973149535723176508575932662800702e+4932",
921    norm_max: "1.18973149535723176508575932662800702e+4932",
922    min: "3.36210314311209350626267781732175260e-4932",
923    epsilon: "1.92592994438723585305597794258492732e-34",
924    denorm_min: "6.47517511943802511092443895822764655e-4966",
925    is_iec_60559: "1",
926};
927
928/// IBM double-double, which is `long double` on 64-bit PowerPC.
929///
930/// The row that does not follow from a precision and an exponent range, because the format has
931/// neither. `MANT_DIG` is 106 and `DIG` is 31, which are the figures near the top of the
932/// significand and not everywhere. `MAX` is a little above `DBL_MAX`, since the high half can be
933/// `DBL_MAX` and the low half then adds to it, and `NORM_MAX` is about half of that, so this is
934/// the one row where the two are different numbers. `EPSILON` is the same number as `DENORM_MIN`,
935/// two to the minus one thousand and seventy four, because the smallest value that changes a
936/// double-double near one is a subnormal in the low half rather than one unit in the last place
937/// of anything. `MIN` is two to the minus nine hundred and sixty nine rather than `DBL_MIN`,
938/// because below that the low half has no room left to be normal in.
939///
940/// Every value here is what the reference compiler prints for `powerpc64le-linux-gnu`, checked
941/// rather than derived, on the same terms as the data layouts in `rucc-abi`. The format is one
942/// where deriving them is how the four wrong numbers in those layouts happened.
943const DOUBLE_DOUBLE: Characteristics = Characteristics {
944    mant_dig: "106",
945    dig: "31",
946    min_exp: "(-968)",
947    min_10_exp: "(-291)",
948    max_exp: "1024",
949    max_10_exp: "308",
950    decimal_dig: "33",
951    max: "1.79769313486231580793728971405301e+308",
952    norm_max: "8.98846567431157953864652595394501e+307",
953    min: "2.00416836000897277799610805135016e-292",
954    epsilon: "4.94065645841246544176568792868221e-324",
955    denorm_min: "4.94065645841246544176568792868221e-324",
956    is_iec_60559: "0",
957};
958
959/// The row of the table a format has, so that a type the target chooses the format of can look
960/// its own limits up rather than have them written out again per architecture.
961const fn characteristics(format: Format) -> &'static Characteristics {
962    match format {
963        Format::Half => &HALF,
964        Format::BFloat16 => &BFLOAT16,
965        Format::Single => &SINGLE,
966        Format::Double => &DOUBLE,
967        Format::X87Extended => &X87,
968        Format::Quad => &QUAD,
969        Format::DoubleDouble => &DOUBLE_DOUBLE,
970    }
971}
972
973/// The `float.h` characteristics.
974///
975/// Nine families of them, which is `float`, `double` and `long double` and the six C23 named
976/// them after. Only two of the nine depend on the target, and they are the two whose format is
977/// a target property: `long double`, which is x87 on x86-64 Linux, quad on AArch64 and RISC-V
978/// Linux and a `double` on Apple and on Windows, and `_Float64x`, which is the widest format the
979/// processor has and so does not follow `long double` down on the targets that shrink it.
980///
981/// `__FLT128X_*__` is deliberately missing. `_Float128x` is a type no target gcc supports has,
982/// so gcc defines nothing for it and neither does this.
983fn floats(d: &mut Defs, target: &TargetInfo) {
984    d.set("__FLT_RADIX__", "2");
985    // Real arithmetic follows IEC 60559 in every format on every target here, which is what
986    // the value two says. Not `__GCC_IEC_559_COMPLEX`, which is the same claim about complex
987    // arithmetic and would not be true: multiplication and division of complex values are not
988    // lowered yet, and Annex G is mostly about what those two do with an infinity.
989    d.set("__GCC_IEC_559", "2");
990    // Every operation is done in the type of its operands, which is what SSE2 and the AArch64
991    // and RISC-V floating units all do. The other two names are the same answer asked under the
992    // rules of C99 and of TS 18661-3, which are the same rules for a target with no excess
993    // precision to have, and glibc's `<math.h>` reads the last of the three.
994    d.set("__FLT_EVAL_METHOD__", "0");
995    d.set("__FLT_EVAL_METHOD_C99__", "0");
996    d.set("__FLT_EVAL_METHOD_TS_18661_3__", "0");
997
998    family(d, "FLT", &SINGLE, |value| format!("{value}F"));
999    // gcc writes the `double` values as `long double` constants cast back down, which is exact
1000    // in every format `long double` has and is the one family whose values are not a suffix.
1001    family(d, "DBL", &DOUBLE, |value| format!("((double){value}L)"));
1002    family(d, "LDBL", characteristics(target.long_double_format), |value| format!("{value}L"));
1003
1004    family(d, "FLT16", &HALF, |value| format!("{value}F16"));
1005    family(d, "FLT32", &SINGLE, |value| format!("{value}F32"));
1006    family(d, "FLT64", &DOUBLE, |value| format!("{value}F64"));
1007    family(d, "FLT128", &QUAD, |value| format!("{value}F128"));
1008    family(d, "FLT32X", &DOUBLE, |value| format!("{value}F32x"));
1009    family(d, "FLT64X", characteristics(target.float64x_format), |value| format!("{value}F64x"));
1010
1011    // The number itself rather than the name of the other macro. The value is the same either
1012    // way, since `long double` is the widest format here, but the two are not the same thing to
1013    // read: `-dM` prints what the macro is, and a program that undefines `__LDBL_DECIMAL_DIG__`
1014    // takes this one with it. gcc writes the number.
1015    d.set("__DECIMAL_DIG__", characteristics(target.long_double_format).decimal_dig);
1016}
1017
1018/// One family of `float.h` macros, named `__{prefix}_*__`.
1019///
1020/// `write` turns a value into the constant its macro expands to, which is a suffix for every
1021/// family but `double`.
1022fn family(d: &mut Defs, prefix: &str, c: &Characteristics, write: impl Fn(&str) -> String) {
1023    d.set(&format!("__{prefix}_MANT_DIG__"), c.mant_dig);
1024    d.set(&format!("__{prefix}_DIG__"), c.dig);
1025    d.set(&format!("__{prefix}_MIN_EXP__"), c.min_exp);
1026    d.set(&format!("__{prefix}_MIN_10_EXP__"), c.min_10_exp);
1027    d.set(&format!("__{prefix}_MAX_EXP__"), c.max_exp);
1028    d.set(&format!("__{prefix}_MAX_10_EXP__"), c.max_10_exp);
1029    d.set(&format!("__{prefix}_DECIMAL_DIG__"), c.decimal_dig);
1030    d.set(&format!("__{prefix}_MAX__"), &write(c.max));
1031    d.set(&format!("__{prefix}_NORM_MAX__"), &write(c.norm_max));
1032    d.set(&format!("__{prefix}_MIN__"), &write(c.min));
1033    d.set(&format!("__{prefix}_EPSILON__"), &write(c.epsilon));
1034    d.set(&format!("__{prefix}_DENORM_MIN__"), &write(c.denorm_min));
1035    d.set(&format!("__{prefix}_IS_IEC_60559__"), c.is_iec_60559);
1036    d.set(&format!("__{prefix}_HAS_DENORM__"), "1");
1037    d.set(&format!("__{prefix}_HAS_INFINITY__"), "1");
1038    d.set(&format!("__{prefix}_HAS_QUIET_NAN__"), "1");
1039}
1040
1041#[cfg(test)]
1042mod tests {
1043    use rucc_target::Triple;
1044
1045    use super::*;
1046
1047    fn set_for(triple: &str) -> String {
1048        let triple: Triple = triple.parse().expect("a triple the compiler supports");
1049        built_in(&TargetInfo::new(triple), &Predef::new())
1050    }
1051
1052    fn has(text: &str, line: &str) -> bool {
1053        text.lines().any(|l| l == line)
1054    }
1055
1056    #[test]
1057    fn the_set_is_driven_by_the_target_rather_than_by_the_host() {
1058        let x86 = set_for("x86_64-unknown-linux-gnu");
1059        let arm = set_for("aarch64-unknown-linux-gnu");
1060        assert!(has(&x86, "#define __x86_64__ 1"));
1061        assert!(!has(&x86, "#define __aarch64__ 1"));
1062        assert!(has(&arm, "#define __aarch64__ 1"));
1063        assert!(!has(&arm, "#define __x86_64__ 1"));
1064        assert!(has(&x86, "#define __linux__ 1") && has(&arm, "#define __linux__ 1"));
1065    }
1066
1067    #[test]
1068    fn windows_is_the_target_that_makes_long_thirty_two_bits() {
1069        let windows = set_for("x86_64-pc-windows-msvc");
1070        let linux = set_for("x86_64-unknown-linux-gnu");
1071        assert!(has(&windows, "#define __SIZEOF_LONG__ 4"));
1072        assert!(has(&windows, "#define __SIZE_TYPE__ long long unsigned int"));
1073        assert!(has(&windows, "#define __INT64_TYPE__ long long int"));
1074        assert!(!has(&windows, "#define __LP64__ 1"));
1075        assert!(has(&linux, "#define __SIZEOF_LONG__ 8"));
1076        assert!(has(&linux, "#define __SIZE_TYPE__ long unsigned int"));
1077        assert!(has(&linux, "#define __INT64_TYPE__ long int"));
1078        assert!(has(&linux, "#define __LP64__ 1"));
1079    }
1080
1081    #[test]
1082    fn wchar_t_is_the_type_that_divides_the_targets() {
1083        // Signed on x86-64 Linux, unsigned on AArch64 Linux, and sixteen bits on Windows.
1084        assert!(has(&set_for("x86_64-unknown-linux-gnu"), "#define __WCHAR_TYPE__ int"));
1085        assert!(has(&set_for("aarch64-unknown-linux-gnu"), "#define __WCHAR_TYPE__ unsigned int"));
1086        let windows = set_for("x86_64-pc-windows-msvc");
1087        assert!(has(&windows, "#define __WCHAR_TYPE__ short unsigned int"));
1088        assert!(has(&windows, "#define __SIZEOF_WCHAR_T__ 2"));
1089    }
1090
1091    #[test]
1092    fn apple_spells_the_architecture_its_own_way_and_its_headers_only_know_that_spelling() {
1093        // sys/cdefs.h reaches #error "Unsupported architecture" without these, which is the
1094        // first line of the first header of every program on the platform.
1095        let darwin = set_for("aarch64-apple-darwin");
1096        assert!(has(&darwin, "#define __arm64__ 1"));
1097        assert!(has(&darwin, "#define __arm64 1"));
1098        assert!(has(&darwin, "#define __aarch64__ 1"), "the portable spelling stays too");
1099        let linux = set_for("aarch64-unknown-linux-gnu");
1100        assert!(!has(&linux, "#define __arm64__ 1"), "Apple's spelling is Apple's alone");
1101        assert!(!has(&set_for("x86_64-apple-darwin"), "#define __arm64__ 1"));
1102    }
1103
1104    #[test]
1105    fn every_limit_is_spelled_in_hexadecimal_the_way_gcc_spells_it() {
1106        // The value was never in question and the spelling is, because these macros reach a
1107        // program's text. glibc's `limits.h` writes `#define INT_MAX __INT_MAX__`, openssl
1108        // writes `((unsigned int)INT_MAX + 1)`, and `-E` over that header printed a decimal
1109        // number where gcc printed a hexadecimal one. The type is the same either way here,
1110        // which is why the suffixes are unchanged: `0x7fffffff` and `2147483647` are both
1111        // `int`, and `0xffffffffffffffffUL` and its decimal twin are both `unsigned long`.
1112        let linux = set_for("x86_64-unknown-linux-gnu");
1113        for line in [
1114            "#define __SCHAR_MAX__ 0x7f",
1115            "#define __SHRT_MAX__ 0x7fff",
1116            "#define __INT_MAX__ 0x7fffffff",
1117            "#define __LONG_MAX__ 0x7fffffffffffffffL",
1118            "#define __LONG_LONG_MAX__ 0x7fffffffffffffffLL",
1119            "#define __INTMAX_MAX__ 0x7fffffffffffffffL",
1120            "#define __UINTMAX_MAX__ 0xffffffffffffffffUL",
1121            "#define __SIZE_MAX__ 0xffffffffffffffffUL",
1122            "#define __PTRDIFF_MAX__ 0x7fffffffffffffffL",
1123            "#define __SIG_ATOMIC_MAX__ 0x7fffffff",
1124            "#define __INT8_MAX__ 0x7f",
1125            "#define __UINT8_MAX__ 0xff",
1126            "#define __INT16_MAX__ 0x7fff",
1127            "#define __UINT16_MAX__ 0xffff",
1128            "#define __INT32_MAX__ 0x7fffffff",
1129            "#define __UINT32_MAX__ 0xffffffffU",
1130            "#define __INT64_MAX__ 0x7fffffffffffffffL",
1131            "#define __UINT64_MAX__ 0xffffffffffffffffUL",
1132            "#define __INT_FAST8_MAX__ 0x7f",
1133            "#define __UINT_FAST8_MAX__ 0xff",
1134        ] {
1135            assert!(has(&linux, line), "{line}");
1136        }
1137        // Windows, where `long` is thirty two bits, so the wide suffix moves and the narrow
1138        // `long` limit is not the same number.
1139        let windows = set_for("x86_64-pc-windows-msvc");
1140        assert!(has(&windows, "#define __LONG_MAX__ 0x7fffffffL"));
1141        assert!(has(&windows, "#define __INTMAX_MAX__ 0x7fffffffffffffffLL"));
1142        assert!(has(&windows, "#define __UINTMAX_MAX__ 0xffffffffffffffffULL"));
1143    }
1144
1145    #[test]
1146    fn wint_t_does_not_follow_wchar_t() {
1147        // Apple makes it signed so that WEOF is negative the way EOF is. Linux does not.
1148        let darwin = set_for("aarch64-apple-darwin");
1149        assert!(has(&darwin, "#define __WINT_TYPE__ int"));
1150        assert!(has(&darwin, "#define __WINT_MAX__ 0x7fffffff"));
1151        assert!(has(&darwin, "#define __WCHAR_TYPE__ int"));
1152        let linux = set_for("aarch64-unknown-linux-gnu");
1153        assert!(has(&linux, "#define __WINT_TYPE__ unsigned int"));
1154        assert!(has(&linux, "#define __WINT_MAX__ 0xffffffffU"));
1155        assert!(has(&linux, "#define __WCHAR_TYPE__ unsigned int"), "and wchar_t is its own");
1156        assert!(has(
1157            &set_for("x86_64-pc-windows-msvc"),
1158            "#define __WINT_TYPE__ short unsigned int"
1159        ));
1160    }
1161
1162    #[test]
1163    fn the_widths_say_what_the_type_holds_and_follow_the_target_that_changes_it() {
1164        // Twenty of them, which is gcc's set: no exact width member, since the width of an
1165        // `int32_t` is in its name, and no unsigned member, since a header that wants
1166        // `UINTMAX_WIDTH` writes `__INTMAX_WIDTH__`.
1167        let linux = set_for("x86_64-unknown-linux-gnu");
1168        assert_eq!(linux.lines().filter(|line| line.contains("_WIDTH__")).count(), 20);
1169        assert!(has(&linux, "#define __LONG_WIDTH__ 64"));
1170        assert!(has(&linux, "#define __SIZE_WIDTH__ 64"));
1171        assert!(has(&linux, "#define __WCHAR_WIDTH__ 32"));
1172        assert!(has(&linux, "#define __INT_LEAST16_WIDTH__ 16"));
1173        // x86-64 glibc is where `int_fast16_t` is a `long`, and the width has to say so or a
1174        // program that switches on it picks the wrong branch.
1175        assert!(has(&linux, "#define __INT_FAST16_WIDTH__ 64"));
1176        assert!(has(&set_for("x86_64-unknown-linux-musl"), "#define __INT_FAST16_WIDTH__ 32"));
1177        // Windows has a thirty two bit `long` and a sixteen bit `wint_t`, and the pointer
1178        // sized types stay sixty four bits wide whatever `long` does.
1179        let windows = set_for("x86_64-pc-windows-msvc");
1180        assert!(has(&windows, "#define __LONG_WIDTH__ 32"));
1181        assert!(has(&windows, "#define __WINT_WIDTH__ 16"));
1182        assert!(has(&windows, "#define __SIZE_WIDTH__ 64"));
1183        assert!(has(&windows, "#define __INTMAX_WIDTH__ 64"));
1184    }
1185
1186    #[test]
1187    fn a_constant_maker_gets_the_suffix_its_width_needs_and_no_other() {
1188        // Found by diffing `-dM` against the system compiler. The 32 bit row was passing `U`
1189        // as its width suffix, which put a `U` on the signed macro and two on the unsigned
1190        // one, and `UINT32_C(1)` expanded to `1UU`, which is not a token.
1191        let linux = set_for("x86_64-unknown-linux-gnu");
1192        assert!(has(&linux, "#define __INT32_C(c) c"));
1193        assert!(has(&linux, "#define __UINT32_C(c) c ## U"));
1194        assert!(has(&linux, "#define __INT16_C(c) c"));
1195        // No `U` on the two narrow ones, because `uint8_t` and `uint16_t` promote to a
1196        // signed `int` and the constant has that type. gcc leaves it off for the same reason.
1197        assert!(has(&linux, "#define __UINT16_C(c) c"));
1198        assert!(has(&linux, "#define __UINT8_C(c) c"));
1199        // The wide ones do take a suffix, and the `U` goes in front of it.
1200        assert!(has(&linux, "#define __INT64_C(c) c ## L"));
1201        assert!(has(&linux, "#define __UINT64_C(c) c ## UL"));
1202        // Windows has a thirty two bit `long`, so its sixty four bit constants are `long long`.
1203        let windows = set_for("x86_64-pc-windows-msvc");
1204        assert!(has(&windows, "#define __INT64_C(c) c ## LL"));
1205        assert!(has(&windows, "#define __UINT64_C(c) c ## ULL"));
1206    }
1207
1208    #[test]
1209    fn the_symbol_prefix_is_defined_everywhere_including_where_it_is_empty() {
1210        // Empty is not the same as absent, because glibc stringifies it. Leaving it undefined
1211        // turns `__asm__ (__ASMNAME ("__xpg_strerror_r"))` into an asm name of
1212        // "__USER_LABEL_PREFIX__" "__xpg_strerror_r", which renames the function instead of
1213        // failing, and that is a bug found at link time or later.
1214        for triple in
1215            ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
1216        {
1217            assert!(has(&set_for(triple), "#define __USER_LABEL_PREFIX__ "), "{triple}");
1218        }
1219        // Mach-O keeps the underscore that ELF dropped.
1220        assert!(has(&set_for("aarch64-apple-darwin"), "#define __USER_LABEL_PREFIX__ _"));
1221    }
1222
1223    /// The set gcc defines that headers read and that are true here. Written out one line at a
1224    /// time rather than counted, because the value is the whole point of each of them: a header
1225    /// asking `#if __FINITE_MATH_ONLY__` wants the number and not the existence.
1226    #[test]
1227    fn the_toolchain_macros_gcc_defines_are_defined_with_gccs_values() {
1228        let linux = set_for("x86_64-unknown-linux-gnu");
1229        for line in [
1230            "#define __GNUC_EXECUTION_CHARSET_NAME \"UTF-8\"",
1231            "#define __GNUC_WIDE_EXECUTION_CHARSET_NAME \"UTF-32LE\"",
1232            "#define __GXX_ABI_VERSION 1021",
1233            "#define __REGISTER_PREFIX__ ",
1234            "#define __FINITE_MATH_ONLY__ 0",
1235            "#define __GCC_IEC_559 2",
1236            "#define __GCC_CONSTRUCTIVE_SIZE 64",
1237            "#define __GCC_DESTRUCTIVE_SIZE 64",
1238            "#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1",
1239            "#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1",
1240            "#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1",
1241            "#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1",
1242            "#define __ATOMIC_HLE_ACQUIRE 65536",
1243            "#define __ATOMIC_HLE_RELEASE 131072",
1244            "#define __FXSR__ 1",
1245            "#define __MMX_WITH_SSE__ 1",
1246            "#define __code_model_small__ 1",
1247        ] {
1248            assert!(has(&linux, line), "{line}");
1249        }
1250        // The complex half of the IEC 60559 claim is not made, because complex multiplication
1251        // and division are not lowered and Annex G is mostly about what those two do.
1252        assert!(!linux.contains("__GCC_IEC_559_COMPLEX"));
1253        // The five that are the processor's rather than the compiler's stay on the processor.
1254        let arm = set_for("aarch64-unknown-linux-gnu");
1255        for name in ["__ATOMIC_HLE_ACQUIRE", "__FXSR__", "__MMX_WITH_SSE__", "__code_model_small__"]
1256        {
1257            assert!(!arm.contains(name), "{name}");
1258        }
1259        assert!(has(&arm, "#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1"));
1260        // A wide character is sixteen bits on Windows, so a wide string is UTF-16 there.
1261        let windows = set_for("x86_64-pc-windows-msvc");
1262        assert!(has(&windows, "#define __GNUC_WIDE_EXECUTION_CHARSET_NAME \"UTF-16LE\""));
1263    }
1264
1265    #[test]
1266    fn the_memory_orders_are_there_even_without_atomics() {
1267        // musl's stdatomic.h writes `memory_order_relaxed = __ATOMIC_RELAXED` with no test
1268        // around it, so these are not a promise about `_Atomic`, they are the numbering the
1269        // builtins take, and a compiler without them prints an enumerator whose value is an
1270        // identifier.
1271        let linux = set_for("x86_64-unknown-linux-gnu");
1272        assert!(has(&linux, "#define __ATOMIC_RELAXED 0"));
1273        assert!(has(&linux, "#define __ATOMIC_SEQ_CST 5"));
1274        assert!(has(&linux, "#define __STDC_NO_ATOMICS__ 1"), "and we still have no _Atomic");
1275        assert!(has(&linux, "#define __GCC_ATOMIC_INT_LOCK_FREE 2"));
1276        assert!(has(&linux, "#define __GCC_ATOMIC_LLONG_LOCK_FREE 2"));
1277        assert!(has(&set_for("x86_64-pc-windows-msvc"), "#define __GCC_ATOMIC_LLONG_LOCK_FREE 2"));
1278    }
1279
1280    #[test]
1281    fn long_double_is_three_types_and_the_macros_say_which() {
1282        assert!(has(&set_for("x86_64-unknown-linux-gnu"), "#define __LDBL_MANT_DIG__ 64"));
1283        assert!(has(&set_for("aarch64-unknown-linux-gnu"), "#define __LDBL_MANT_DIG__ 113"));
1284        assert!(has(&set_for("aarch64-apple-darwin"), "#define __LDBL_MANT_DIG__ 53"));
1285    }
1286
1287    #[test]
1288    fn the_extended_floating_types_have_the_limits_their_formats_have() {
1289        // Every one of these but `_Float64x` is the same format on every target, which is the
1290        // point of the interchange types, so the limits are the same everywhere too.
1291        let linux = set_for("x86_64-unknown-linux-gnu");
1292        assert!(has(&linux, "#define __FLT16_MANT_DIG__ 11"));
1293        assert!(has(&linux, "#define __FLT32_MANT_DIG__ 24"));
1294        assert!(has(&linux, "#define __FLT64_MANT_DIG__ 53"));
1295        assert!(has(&linux, "#define __FLT128_MANT_DIG__ 113"));
1296        assert!(has(&linux, "#define __FLT32X_MANT_DIG__ 53"));
1297        // Each family writes its values with its own suffix, so a header that assigns one to an
1298        // object of the type gets the type back rather than a conversion.
1299        assert!(has(&linux, "#define __FLT16_MAX__ 6.55040000000000000000000000000000000e+4F16"));
1300        assert!(has(
1301            &linux,
1302            "#define __FLT32X_MIN__ 2.22507385850720138309023271733240406e-308F32x"
1303        ));
1304        // `_Float128x` is a type no target has, so gcc defines nothing for it and neither
1305        // does this.
1306        assert!(!linux.contains("__FLT128X_"));
1307    }
1308
1309    #[test]
1310    fn float64x_keeps_the_width_that_long_double_loses_on_apple() {
1311        // The two are the same eighty bit x87 format on x86-64 and part company everywhere
1312        // else, because `_Float64x` follows the processor and `long double` follows the ABI.
1313        let linux = set_for("x86_64-unknown-linux-gnu");
1314        assert!(has(&linux, "#define __FLT64X_MANT_DIG__ 64"));
1315        assert!(has(&linux, "#define __LDBL_MANT_DIG__ 64"));
1316        let mac = set_for("aarch64-apple-darwin");
1317        assert!(has(&mac, "#define __FLT64X_MANT_DIG__ 113"));
1318        assert!(has(&mac, "#define __LDBL_MANT_DIG__ 53"));
1319        let windows = set_for("x86_64-pc-windows-msvc");
1320        assert!(has(&windows, "#define __FLT64X_MANT_DIG__ 64"));
1321        assert!(has(&windows, "#define __LDBL_MANT_DIG__ 53"));
1322    }
1323
1324    #[test]
1325    fn the_largest_value_of_an_ieee_format_is_also_its_largest_normal_one() {
1326        // `NORM_MAX` is only ever smaller than `MAX` for a format that holds values above its
1327        // largest normal one, and no IEEE encoding does. The double-double does, which is why
1328        // the two are separate fields now, and no target here has one.
1329        let linux = set_for("x86_64-unknown-linux-gnu");
1330        for prefix in ["FLT", "DBL", "LDBL", "FLT16", "FLT32", "FLT64", "FLT128", "FLT32X"] {
1331            let value = |suffix: &str| {
1332                let name = format!("#define __{prefix}_{suffix}__ ");
1333                let line = linux
1334                    .lines()
1335                    .find(|line| line.starts_with(&name))
1336                    .unwrap_or_else(|| panic!("__{prefix}_{suffix}__ is defined"));
1337                line[name.len()..].to_owned()
1338            };
1339            assert_eq!(value("MAX"), value("NORM_MAX"), "__{prefix}_NORM_MAX__");
1340        }
1341    }
1342
1343    #[test]
1344    fn the_double_double_is_the_row_where_the_largest_value_is_not_the_largest_normal_one() {
1345        // No target here has a double-double `long double`, so this asks the row rather than the
1346        // macros. It is the reason `norm_max` is a field: a program that wants the largest value
1347        // it can still compute a full significand with wants `NORM_MAX`, and on PowerPC that is
1348        // a bit under half of `MAX`.
1349        let c = characteristics(Format::DoubleDouble);
1350        assert_ne!(c.max, c.norm_max);
1351        // `NORM_MAX` is two to the one thousand and twenty three, which is about half of `MAX`,
1352        // and `MAX` is a shade above `DBL_MAX` because the high half can be `DBL_MAX` and the low
1353        // half then adds to it. Both are what the reference prints.
1354        assert!(c.norm_max.starts_with("8.98846567431157953864652595394501e+307"));
1355        assert!(c.max.starts_with("1.7976931348623158"));
1356        // Epsilon is the odd one. The smallest value that changes a double-double near one is a
1357        // subnormal in the low half rather than one unit in the last place of anything, so it is
1358        // the same number as this format's own `DENORM_MIN`, which no other row can say.
1359        assert_eq!(c.epsilon, c.denorm_min);
1360        for format in [Format::Half, Format::Single, Format::Double, Format::X87Extended] {
1361            assert_ne!(characteristics(format).epsilon, characteristics(format).denorm_min);
1362        }
1363        // And it is not an IEC 60559 format, which only the brain float can also say.
1364        assert_eq!(c.is_iec_60559, "0");
1365    }
1366
1367    #[test]
1368    fn the_widest_bit_int_is_said_in_every_dialect() {
1369        // gcc defines it under `-std=c17` as well as `-std=c23`, and a header that reaches for
1370        // `_BitInt` tests the macro rather than the version, so an absent one reads as a
1371        // compiler without the type at all.
1372        let mut opts = Predef::new();
1373        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1374        assert!(has(&built_in(&target, &opts), "#define __BITINT_MAXWIDTH__ 128"));
1375        opts.std = Std::C17;
1376        assert!(has(&built_in(&target, &opts), "#define __BITINT_MAXWIDTH__ 128"));
1377    }
1378
1379    #[test]
1380    fn char_signedness_is_recorded_only_when_it_is_unsigned() {
1381        // Which is how GCC does it: the macro exists to mark the unusual case.
1382        assert!(has(&set_for("aarch64-unknown-linux-gnu"), "#define __CHAR_UNSIGNED__ 1"));
1383        assert!(!has(&set_for("x86_64-unknown-linux-gnu"), "#define __CHAR_UNSIGNED__ 1"));
1384    }
1385
1386    #[test]
1387    fn the_dialect_decides_the_standard_macros() {
1388        let mut opts = Predef::new();
1389        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1390        assert!(has(&built_in(&target, &opts), "#define __STDC_VERSION__ 202311L"));
1391        assert!(!has(&built_in(&target, &opts), "#define __STRICT_ANSI__ 1"));
1392        assert!(has(&built_in(&target, &opts), "#define linux 1"));
1393
1394        opts.gnu_extensions = false;
1395        assert!(has(&built_in(&target, &opts), "#define __STRICT_ANSI__ 1"));
1396        assert!(!has(&built_in(&target, &opts), "#define linux 1"), "not a reserved name");
1397
1398        opts.std = Std::C89;
1399        let c89 = built_in(&target, &opts);
1400        assert!(!c89.contains("__STDC_VERSION__"), "C89 does not define it at all");
1401        assert!(has(&c89, "#define __STDC__ 1"));
1402    }
1403
1404    /// The conditional feature macros are claims not to have something, and a claim that is
1405    /// not true changes what a header declares rather than turning anything off.
1406    #[test]
1407    fn the_only_things_claimed_missing_are_the_ones_that_are_missing() {
1408        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1409        let opts = Predef::new();
1410        let set = built_in(&target, &opts);
1411        assert!(has(&set, "#define __STDC_NO_ATOMICS__ 1"), "there is no stdatomic.h to include");
1412        assert!(has(&set, "#define __STDC_NO_THREADS__ 1"), "nor a threads.h");
1413        assert!(has(&set, "#define __STDC_NO_COMPLEX__ 1"), "the arithmetic is not lowered");
1414        assert!(!set.contains("__STDC_NO_VLA__"), "variable length arrays work");
1415    }
1416
1417    /// gcc's own `stdatomic.h` declares `atomic_char8_t` under `#ifdef __CHAR8_TYPE__`, so a
1418    /// compiler that defines it in C17 declares a type gcc does not and one that never defines
1419    /// it is missing one in C23. Both were caught by preprocessing that header both ways.
1420    #[test]
1421    fn the_type_behind_char8_t_is_defined_in_c23_and_in_no_dialect_before_it() {
1422        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1423        let mut opts = Predef::new();
1424        assert!(has(&built_in(&target, &opts), "#define __CHAR8_TYPE__ unsigned char"));
1425
1426        for older in [Std::C17, Std::C11, Std::C99, Std::C89] {
1427            opts.std = older;
1428            assert!(!built_in(&target, &opts).contains("__CHAR8_TYPE__"), "{older:?}");
1429        }
1430    }
1431
1432    #[test]
1433    fn the_optimizer_level_is_visible_to_the_preprocessor() {
1434        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1435        let mut opts = Predef::new();
1436        assert!(has(&built_in(&target, &opts), "#define __NO_INLINE__ 1"));
1437        assert!(!built_in(&target, &opts).contains("__OPTIMIZE__"));
1438
1439        opts.opt_level = OptLevel::O2;
1440        assert!(has(&built_in(&target, &opts), "#define __OPTIMIZE__ 1"));
1441        assert!(!built_in(&target, &opts).contains("__OPTIMIZE_SIZE__"));
1442
1443        opts.opt_level = OptLevel::Os;
1444        assert!(has(&built_in(&target, &opts), "#define __OPTIMIZE_SIZE__ 1"));
1445    }
1446
1447    #[test]
1448    fn a_command_line_define_with_no_value_is_one() {
1449        let mut opts = Predef::new();
1450        opts.defines = vec!["FOO".to_owned(), "BAR=2".to_owned(), "F(x)=x + 1".to_owned()];
1451        opts.undefines = vec!["__linux__".to_owned()];
1452        let text = command_line(&opts);
1453        assert!(has(&text, "#define FOO 1"));
1454        assert!(has(&text, "#define BAR 2"));
1455        assert!(has(&text, "#define F(x) x + 1"));
1456        // The undefine comes last, because `-U` beats `-D` whichever side of it it was on.
1457        assert!(text.trim_end().ends_with("#undef __linux__"));
1458    }
1459
1460    #[test]
1461    fn no_command_line_macros_is_no_file_at_all() {
1462        assert!(command_line(&Predef::new()).is_empty());
1463    }
1464
1465    #[test]
1466    fn a_date_is_spelled_the_way_the_standard_fixes() {
1467        // The epoch itself, and a day that needs the space padding the format asks for.
1468        let epoch = Timestamp::from_unix(0);
1469        assert_eq!(epoch.date, "Jan  1 1970");
1470        assert_eq!(epoch.time, "00:00:00");
1471        let leap = Timestamp::from_unix(1_709_164_800);
1472        assert_eq!(leap.date, "Feb 29 2024", "2024 is a leap year");
1473        let late = Timestamp::from_unix(1_735_689_599);
1474        assert_eq!(late.date, "Dec 31 2024");
1475        assert_eq!(late.time, "23:59:59");
1476    }
1477
1478    #[test]
1479    fn a_date_before_the_epoch_still_comes_out_right() {
1480        // Not because anyone compiles in 1969, but because the arithmetic that gets this
1481        // wrong is the same arithmetic that gets a time zone offset wrong.
1482        assert_eq!(Timestamp::from_unix(-1).date, "Dec 31 1969");
1483        assert_eq!(Timestamp::from_unix(-1).time, "23:59:59");
1484    }
1485
1486    #[test]
1487    fn the_gnuc_version_is_a_knob_rather_than_a_constant() {
1488        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1489        let mut opts = Predef::new();
1490        assert!(has(&built_in(&target, &opts), "#define __GNUC__ 7"));
1491        opts.gnuc = GnucVersion { major: 15, minor: 1, patch: 0 };
1492        assert!(has(&built_in(&target, &opts), "#define __GNUC__ 15"));
1493        assert!(has(&built_in(&target, &opts), "#define __GNUC_MINOR__ 1"));
1494    }
1495
1496    /// Which of the two inline macros is defined, over the two things that decide it.
1497    ///
1498    /// Exactly one of them is defined at a time, which is what a header reads: glibc's
1499    /// `__extern_inline` writes `extern __inline` under one and adds `__gnu_inline__` under the
1500    /// other, so both being defined or neither being defined is a header taking a path it was
1501    /// never meant to take.
1502    #[test]
1503    fn one_of_the_two_inline_macros_is_defined_and_three_things_can_pick_which() {
1504        let target = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1505        let gnu = "#define __GNUC_GNU_INLINE__ 1";
1506        let stdc = "#define __GNUC_STDC_INLINE__ 1";
1507
1508        let mut opts = Predef::new();
1509        assert!(has(&built_in(&target, &opts), stdc));
1510        assert!(!has(&built_in(&target, &opts), gnu));
1511
1512        opts.gnu89_inline = true;
1513        assert!(has(&built_in(&target, &opts), gnu));
1514        assert!(!has(&built_in(&target, &opts), stdc));
1515
1516        // The dialect on its own, which is where the older reading came from.
1517        let mut opts = Predef::new();
1518        opts.std = Std::C89;
1519        assert!(has(&built_in(&target, &opts), gnu));
1520        assert!(!has(&built_in(&target, &opts), stdc));
1521    }
1522
1523    #[test]
1524    fn musl_and_glibc_disagree_about_the_fast_types_on_the_same_processor() {
1525        // The same x86-64 machine, two libcs, two answers. GCC built for glibc says `long int`
1526        // and GCC built for musl says `int`, because musl defines `int_fast16_t` as `int32_t`
1527        // everywhere. It shows in `stdatomic.h`, which GCC writes out of these macros, so
1528        // getting it wrong makes every atomic fast type the wrong width.
1529        let gnu = set_for("x86_64-unknown-linux-gnu");
1530        let musl = set_for("x86_64-unknown-linux-musl");
1531        assert!(has(&gnu, "#define __INT_FAST16_TYPE__ long int"));
1532        assert!(has(&gnu, "#define __INT_FAST32_TYPE__ long int"));
1533        assert!(has(&gnu, "#define __UINT_FAST16_TYPE__ long unsigned int"));
1534        assert!(has(&musl, "#define __INT_FAST16_TYPE__ int"));
1535        assert!(has(&musl, "#define __INT_FAST32_TYPE__ int"));
1536        assert!(has(&musl, "#define __UINT_FAST16_TYPE__ unsigned int"));
1537        // The limits have to move with the types or a header that checks them stops agreeing
1538        // with the header that uses them.
1539        assert!(has(&gnu, "#define __INT_FAST16_MAX__ 0x7fffffffffffffffL"));
1540        assert!(has(&musl, "#define __INT_FAST16_MAX__ 0x7fffffff"));
1541        assert!(has(&musl, "#define __UINT_FAST16_MAX__ 0xffffffffU"));
1542    }
1543
1544    #[test]
1545    fn the_libc_only_moves_the_two_fast_types_it_is_allowed_to_move() {
1546        // 8 and 64 are the same on both, and so is everything outside the fast family. A libc
1547        // is not a processor and this is the whole of what it is permitted to change here.
1548        let gnu = set_for("x86_64-unknown-linux-gnu");
1549        let musl = set_for("x86_64-unknown-linux-musl");
1550        for line in [
1551            "#define __INT_FAST8_TYPE__ signed char",
1552            "#define __INT_FAST64_TYPE__ long int",
1553            "#define __INT64_TYPE__ long int",
1554            "#define __SIZE_TYPE__ long unsigned int",
1555            "#define __SIZEOF_LONG__ 8",
1556            "#define __LP64__ 1",
1557        ] {
1558            assert!(has(&gnu, line), "glibc lost {line}");
1559            assert!(has(&musl, line), "musl lost {line}");
1560        }
1561    }
1562
1563    #[test]
1564    fn a_non_x86_target_has_int_sized_fast_types_whatever_the_libc() {
1565        // The `long` answer was always specific to x86-64. aarch64 glibc says `int` too, so
1566        // adding the libc axis must not have turned into a second way to say x86-64.
1567        let arm_gnu = set_for("aarch64-unknown-linux-gnu");
1568        let arm_musl = set_for("aarch64-unknown-linux-musl");
1569        assert!(has(&arm_gnu, "#define __INT_FAST16_TYPE__ int"));
1570        assert!(has(&arm_musl, "#define __INT_FAST16_TYPE__ int"));
1571    }
1572}