Skip to main content

rucc_driver/
lib.rs

1//! The driver: command line parsing, the phase graph, job scheduling and the linker
2//! invocation.
3//!
4//! Design: `spec/04-driver-and-cli.md`. Layer rank 13, see `spec/18-package-layout.md`.
5//!
6//! This is the only crate that is allowed to know the process exists. It reads the command
7//! line, touches the file system, spawns the linker and writes to the terminal, and it hands
8//! everything below it a [`Session`]. The binary crate is a `main` that calls
9//! [`run`] and nothing else, so that the whole driver is reachable from a test.
10//!
11//! # Status
12//!
13//! `--help`, `--version` and `--print-config` are real, which is the `M0` exit criterion in
14//! `spec/17-milestones.md`. The phase graph is real and `-###` prints it, and the scheduler
15//! that will run it is real and tested.
16//!
17//! Two phases run. `-E` reads the file, runs phase 4 over it and writes the result, to `-o` or
18//! to standard output. `--emit=tast` carries on through phase 7, the parse and the checking,
19//! and writes the typed tree. The flags those two read are real with them, which is `-D`, `-U`,
20//! `-I`, `-I-`, `-iquote`, `-isystem`, `-idirafter`, `-iprefix`, `-iwithprefix`,
21//! `-iwithprefixbefore`, `-include`, `-imacros`, `--sysroot=`, `-isysroot`, `-P`, `-std=`,
22//! `-fgnuc-version=`, `-ansi`, `-ffreestanding`, `-fno-builtin`, `-fno-builtin-<name>`,
23//! `-fgnu89-inline`, `-pedantic` and `-Werror`.
24//! The phases after them still say they are not implemented.
25//!
26//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
27//! explicitly unstable and will change without a major version bump.
28
29#![doc(html_root_url = "https://docs.rs/rucc-driver/0.11.13")]
30
31pub mod assemble;
32pub mod cache;
33pub mod compile;
34pub mod deps;
35pub mod fetch;
36mod glibc;
37pub mod install;
38pub mod library;
39pub mod link;
40mod map;
41pub mod msvc;
42pub mod phase;
43pub mod preprocess;
44pub mod schedule;
45mod shapes;
46
47use std::fmt::Write as _;
48use std::io::Write as _;
49use std::path::PathBuf;
50
51use rucc_codegen::coverage::{self, Fired};
52use rucc_codegen::lowering::Lowerings;
53use rucc_codegen::pressure::Pressure;
54use rucc_pp::Dependency;
55use rucc_session::{
56    Compress, Control, Dumps, EmitKind, Hook, Math, Options, Pic, PrefixMap, Preinclude, Protector,
57    SaveTemps, Session, Std, Wrapping, runtime,
58};
59use rucc_sysroot::{Manifest, Sysroot};
60use rucc_target::{ObjectFormat, Triple};
61use rucc_tuple::TargetTuple;
62
63use crate::link::LinkOptions;
64
65pub use crate::assemble::assemble;
66pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
67pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan, Role};
68pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
69pub use crate::schedule::Jobs;
70
71/// The compiler's version, taken from the workspace manifest.
72pub const VERSION: &str = env!("CARGO_PKG_VERSION");
73
74/// What the command line asked for.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum Action {
77    /// Print usage and exit successfully.
78    Help,
79    /// Print the version and exit successfully.
80    Version,
81    /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
82    ///
83    /// A build system asks these before it compiles anything, and what it does with the answer
84    /// is paste it into a path or into another command line, so each one is a single line with
85    /// no decoration around it.
86    Print(String),
87    /// Print the resolved configuration and exit successfully.
88    PrintConfig(Box<Options>),
89    /// Print the passes the level will run and exit successfully.
90    PrintPipeline(Box<Options>),
91    /// Print the phase plan and the link line and exit successfully, which is `-###`.
92    PrintPlan {
93        /// The resolved options, which is what says what the link line is for.
94        opts: Box<Options>,
95        /// What to do to each input, and in what order.
96        plan: Box<Plan>,
97        /// What the command line said about linking.
98        link: Box<LinkOptions>,
99    },
100    /// `--fetch <tuple>`, which gets the sysroot this release pins for a target and installs it.
101    ///
102    /// The only action in this compiler that may run another program to move bytes onto the
103    /// machine, which is `spec/cross-compile/13-distribution.md` section 13.8's rule rather than a
104    /// property of how this happens to be written: a compilation has no branch that reaches it.
105    Fetch {
106        /// The artifact, from the table in [`rucc_sysroot::artifact`]. Resolved here rather than where the
107        /// work happens, so that a target nothing is pinned for is a refusal from the parser like
108        /// every other thing a command line can ask for and not have.
109        what: &'static rucc_sysroot::Pinned,
110        /// The target, which names the directory under the cache the tree is installed at and is
111        /// checked against the record inside the artifact.
112        target: TargetTuple,
113        /// Where the cache is, read where everything else that needs it reads it.
114        cache: PathBuf,
115    },
116    /// `--fetch-msvc-sdk <tuple>`, which gets what is behind Microsoft's licence wall.
117    ///
118    /// The other action that may run another program to move bytes onto the machine, and the only
119    /// one that asks a person to accept somebody else's licence first.
120    /// `spec/cross-compile/13-distribution.md` section 13.4 is why it is a command of its own
121    /// rather than something `--fetch` does when it recognises the target: no release pins an
122    /// artifact for these, and nothing about this may ever happen because a compile wanted it to.
123    FetchMsvcSdk {
124        /// The target, which says which architecture's CRT library package is wanted.
125        target: TargetTuple,
126        /// Whether `--accept-licence` was on the command line. Without it the licence and the list
127        /// are printed and nothing is downloaded, which is the whole of what the flag is for.
128        accepted: bool,
129        /// Where the cache is, read where everything else that needs it reads it.
130        cache: PathBuf,
131    },
132    /// Compile the given inputs.
133    Compile {
134        /// The resolved options.
135        opts: Box<Options>,
136        /// What to do to each input, and in what order.
137        plan: Box<Plan>,
138        /// What the command line said about linking.
139        link: Box<LinkOptions>,
140        /// How many translation units to compile at once.
141        jobs: Jobs,
142        /// Whether `-v` asked for the plan to be printed while it runs.
143        verbose: bool,
144        /// What is worth saying about the command line before anything is compiled, printed as
145        /// warnings and once for the whole run rather than once per file.
146        ///
147        /// These are not diagnostics. A diagnostic is about a piece of source and has a span to
148        /// point at, and these are about the way two flags were combined, so there is nothing to
149        /// point at and nowhere below the driver that knows both halves. `-w` does not reach them
150        /// for the same reason it does not reach a refusal from the parser.
151        notes: Vec<String>,
152    },
153}
154
155/// Why a command line was rejected.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct CliError {
158    /// The message, lowercase and without a trailing period, in the same shape as any other
159    /// diagnostic.
160    pub message: String,
161}
162
163impl std::fmt::Display for CliError {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        f.write_str(&self.message)
166    }
167}
168
169impl std::error::Error for CliError {}
170
171fn err(message: impl Into<String>) -> CliError {
172    CliError { message: message.into() }
173}
174
175/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
176///
177/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
178/// the only one that lets a directory whose name contains an `=` be the old half. It also means
179/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
180/// trap until you notice the alternative traps the far more common case.
181fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
182    let rest = &arg[flag.len()..];
183    PrefixMap::split(rest).ok_or_else(|| {
184        let flag = flag.trim_end_matches('=');
185        err(format!(
186            "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
187        ))
188    })
189}
190
191/// A question the command line asked instead of asking for a compilation.
192///
193/// These are answered after the loop rather than where they are read, because every one of them
194/// is about the target or about the library search and the last word on both is the end of the
195/// command line.
196enum Query {
197    /// `-dumpmachine`, the triple.
198    Machine,
199    /// `-dumpversion` and `-dumpfullversion`, which are the same three numbers here.
200    Version,
201    /// `-print-multiarch`, the directory name a distribution files this target under.
202    Multiarch,
203    /// `-print-search-dirs`, in the three lines GCC prints.
204    SearchDirs,
205    /// `-print-sysroot`, the root the headers and the libraries are read under.
206    Sysroot,
207    /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
208    SysrootProvenance,
209    /// `-print-sysroot-digest`, the one number that names all of it.
210    SysrootDigest,
211    /// `-print-file-name=<name>`, the full path of a library file.
212    FileName(String),
213    /// `-print-prog-name=<name>`, the full path of a program.
214    ProgName(String),
215    /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
216    Libgcc,
217}
218
219/// Usage text.
220///
221/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
222/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
223pub const USAGE: &str = "\
224rucc, an optimizing C compiler
225
226usage: rucc [options] file...
227
228options:
229  -c                     compile and assemble, do not link
230  -S                     compile only, emit assembly
231  -E                     preprocess only
232  -o <file>              write output to <file>, or to standard output for -
233  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
234  -I <dir>               add <dir> to the include search path
235  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
236  -I-, -iprefix <p>, -iwithprefix[before] <dir>   the older spellings of those
237  -include <file>, -imacros <file>    read <file> first, the second for its macros only
238  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
239  -P, -dM                with -E: leave out the markers, or dump the macros
240  -M -MM -MD -MMD        write a make rule for the source, the last two compile as well
241  -MF <file> -MT <t> -MQ <t> -MP   where the rule goes, what it builds, targets with no recipe
242  -std=<dialect>         c89 through c2y, and the gnu spellings
243  -fgnuc-version=<v>     the GCC release to claim, default 16.0.0
244  -x <lang>              treat later inputs as <lang>, or none to stop
245  -O<level>              optimize: 0, 1, 2, 3, s, z, fast
246  -fsafety=<tier>        check memory safety: off, detect, enforce, kernel
247  -f[no-]sanitize=<what>   the negative is taken, the positive is refused by name
248  -f[no-]safety-subobject   a write has to stay inside the member it names
249  -f[no-]safety-restrict    two restrict pointers of one block may not meet
250  -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
251  -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n>   stop a pass, or all of them, after n
252  -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>]   run a pass on some functions only
253  -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone   debug info, frame pointer, red zone
254  -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf   compress debug sections, one file not two
255  -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects   read, and not done yet
256  -fprofile-use[=<path>] -fprofile-dir=<dir>   read too, where -fprofile-generate is refused
257  -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
258  -ffunction-sections -fdata-sections   a section per function or variable, for --gc-sections
259  -fvisibility=<what>    default, hidden, internal or protected, when nothing in the source said
260  -l<name>, -L <dir>, -B <dir>   link a library, where to look for one, where our own tools are
261  -fPIC -fpic -fPIE -fpie, -fno-common, -pipe   what it does anyway
262  -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks   what it assumes anyway
263  -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s   how to link
264  -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name>   hand an argument to the linker, or pick one
265  -Werror -pedantic -pedantic-errors -w -W[no-]system-headers   how much to say, and how fatal
266  -m64 -march= -mtune= -mcpu= -mabi= -mcmodel=   what machine to generate for
267  -pg -p, -mfentry -mno-fentry   call a profiler on the way in, and where that call goes
268  -fpatchable-function-entry=<n>[,<m>]   room at the top of every function to patch later
269  -fwrapv, -fwrapv-pointer, -fno-strict-overflow   signed or pointer overflow wraps
270  -ftrapv                signed overflow stops the program instead
271  -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums   change the ABI
272  -ffp-contract=<how>    fuse a multiply and an addition: fast, on or off
273  -f[no-]fast-math and each of its members, -f[no-]rounding-math, -fexcess-precision=<how>
274  -ffile-prefix-map=<old>=<new>   rewrite that front of every path we put in the output
275  -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map=   the same, one output each
276  -pthread               build for more than one thread, and link the library for it
277  -dumpmachine -dumpversion -print-multiarch -print-search-dirs   what this compiler is
278  -print-file-name=<name> -print-prog-name=<name>   where a file or a program is
279  -print-sysroot         the root the headers and the libraries are read under
280  -print-sysroot-provenance   every input under it, where it came from and its licence
281  -print-sysroot-digest   the sha256 of that record, which names the whole sysroot in one line
282  --fetch <tuple>        get the sysroot this release pins for <tuple> and install it in the cache
283  --fetch-msvc-sdk <tuple>   Microsoft's licence, then the SDK behind it with --accept-licence
284  --offline              never download anything, which a compilation never does anyway
285  -j[n]                  compile n translation units at once, default all
286  -v, -###               print each phase as it runs, or without running any
287  -save-temps[=cwd|obj], -time   keep the .i and the .s, say how long each step took
288  --target=<triple>      generate code for <triple>, which a name like <triple>-rucc also does
289  --emit=<kind>          exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
290                         safety-summary, type-granules
291  --print-config, --print-pipeline    print the configuration or the pipeline, and exit
292  --version              print the version and exit
293  -h, --help             print this message and exit
294
295See spec/04-driver-and-cli.md for the full flag reference.
296";
297
298/// The argument of a flag that may be joined to it or may be the next word.
299///
300/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
301fn joined_or_next(
302    arg: &str,
303    at: usize,
304    args: &[String],
305    i: &mut usize,
306) -> Result<String, CliError> {
307    if arg.len() > at {
308        return Ok(arg[at..].to_owned());
309    }
310    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
311    *i += 1;
312    Ok(next.clone())
313}
314
315/// The smallest boundary a function is put on when the command line asked for no alignment at all.
316///
317/// Eight bytes, which is what gcc 16 gives `-fno-align-functions` on x86-64 and is a boundary every
318/// target this compiler has is happy with. It is not zero: a function still has to start somewhere
319/// an instruction may start, and the flag asks for the target's minimum rather than for none.
320const MIN_FUNC_ALIGN: u32 = 8;
321
322/// What `-falign-functions=N` asks for, as a power of two, or `None` for the target's own answer.
323///
324/// Zero and one both mean the default, which is gcc's reading of them, and everything else is
325/// rounded up to the next power of two, which is also gcc's: `-falign-functions=3` puts a function
326/// on a four byte boundary rather than being refused. Gives back `Err` shaped as an outer `None`
327/// only when the text is not a number, since that is the one thing gcc will not read either. A
328/// number larger than any alignment makes sense at is clamped rather than refused, for the same
329/// reason: this is a preference about speed and a build that wrote a silly one still deserves to
330/// compile.
331fn function_alignment(text: &str) -> Option<Option<u32>> {
332    // gcc takes `N:M:N2:M2`, where everything after the first number is about how far it is willing
333    // to go to reach the boundary. Only the boundary is answerable here, so the rest is read to
334    // check that it is numbers and then dropped.
335    let mut parts = text.split(':');
336    let first = parts.next()?;
337    if parts.any(|part| part.parse::<u64>().is_err()) {
338        return None;
339    }
340    let want: u64 = first.parse().ok()?;
341    if want <= 1 {
342        return Some(None);
343    }
344    let bytes = want.min(1 << 16).next_power_of_two();
345    Some(Some(u32::try_from(bytes).ok()?))
346}
347
348/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
349/// own.
350///
351/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
352/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
353/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
354/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
355/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
356/// because none of them is implemented.
357///
358/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
359/// those two spellings is read rather than by being on this list.
360const SANITIZERS: [&str; 34] = [
361    "address",
362    "kernel-address",
363    "hwaddress",
364    "kernel-hwaddress",
365    "pointer-compare",
366    "pointer-subtract",
367    "thread",
368    "leak",
369    "undefined",
370    "shift",
371    "shift-base",
372    "shift-exponent",
373    "integer-divide-by-zero",
374    "unreachable",
375    "vla-bound",
376    "null",
377    "return",
378    "signed-integer-overflow",
379    "bounds",
380    "bounds-strict",
381    "alignment",
382    "object-size",
383    "float-divide-by-zero",
384    "float-cast-overflow",
385    "nonnull-attribute",
386    "returns-nonnull-attribute",
387    "bool",
388    "enum",
389    "vptr",
390    "pointer-overflow",
391    "builtin",
392    "alias",
393    "restrict",
394    "memory",
395];
396
397/// Parses a command line, without the program name.
398///
399/// # Errors
400///
401/// Returns the message to print when the arguments do not name a compilation this compiler
402/// can attempt.
403pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
404    let host = Triple::host()
405        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
406    let mut opts = Options::new(host);
407    // Where the compiler is running, which is what `DW_AT_comp_dir` is and what a debugger joins a
408    // relative file name onto. Asked here rather than where the debug sections are written, because
409    // this is the one layer that is allowed to look at the process it is in, and because a command
410    // line that compiles four files should give the same answer for all four.
411    opts.working_dir = std::env::current_dir().ok().map(|dir| dir.to_string_lossy().into_owned());
412    let mut inputs: Vec<Input> = Vec::new();
413    let mut print_config = false;
414    let mut print_pipeline = false;
415    let mut print_plan = false;
416    let mut verbose = false;
417    let mut jobs = Jobs::default();
418    let mut nostdinc = false;
419    let mut sysroot: Option<PathBuf> = None;
420    // What the command line is worth warning about, filled in after the loop rather than during it,
421    // because every question of this kind is about two flags and the last word on both of them is
422    // the end of the loop.
423    let mut notes: Vec<String> = Vec::new();
424    // The whole ten field target, kept beside the three field one because `--target=` can pin a
425    // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
426    // else today, and `None` is a command line that named no target, which is this machine.
427    let mut pinned: Option<TargetTuple> = None;
428    let mut min_version: Option<rucc_tuple::Version> = None;
429    let mut output = None;
430    let mut link = LinkOptions::default();
431    let mut query: Option<Query> = None;
432    // What `--fetch` named, and whether `--offline` forbade it. Both are weighed after the loop
433    // because either can be written after the other.
434    let mut fetch: Option<String> = None;
435    // The other fetch, kept apart from the one above because they are different commands with
436    // different rules, and weighed after the loop for the same reason that one is.
437    let mut fetch_msvc: Option<String> = None;
438    let mut accepted = false;
439    let mut offline = false;
440    let mut threads = false;
441    // Which sanitizers are still asked for by the end of the command line. Accumulated across the
442    // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
443    // build that asks for a check and then takes it back has asked for nothing. What happens to a
444    // set that is not empty is decided after the loop.
445    let mut sanitizers: Vec<&str> = Vec::new();
446    // The `-ffast-math` family in the order it was written, replayed after the loop on top of
447    // what `-Ofast` implies. gcc applies a level's defaults before any flag and the flags in order
448    // after that, so `-fno-fast-math -Ofast` is not fast math, and only a replay can say so.
449    let mut math_flags: Vec<&str> = Vec::new();
450    let mut ofast = false;
451    // `-mdaz-ftz` and `-mno-daz-ftz`, which decide the startup file directly and outrank the
452    // family on that one question.
453    let mut daz_ftz: Option<bool> = None;
454    // `-x` applies to inputs that come after it and stays in effect until the next one, which
455    // is why it is tracked across the loop rather than attached to a single argument.
456    let mut forced: Option<InputKind> = None;
457    // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
458    // the flags after it and not the ones before, so a command line may set it more than once.
459    // GCC's default is its own installed header directory with the last component taken off,
460    // which is a path a cross compiler's build system knows and passes; there is no equivalent
461    // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
462    // outright.
463    let mut iprefix = String::new();
464
465    let mut i = 0;
466    while i < args.len() {
467        let arg = args[i].as_str();
468        i += 1;
469        match arg {
470            "-h" | "--help" => return Ok(Action::Help),
471            "--version" => return Ok(Action::Version),
472            // The sysroot fetch, which is weighed after the loop rather than acted on here, because
473            // `--offline` written after it has to be able to forbid it. Both spellings, since a
474            // flag that takes a tuple gets written both ways and neither is a guess at what the
475            // other meant.
476            "--fetch" => {
477                let value = args
478                    .get(i)
479                    .ok_or_else(|| err("--fetch requires the target to get a sysroot for"))?;
480                i += 1;
481                fetch = Some(value.clone());
482            }
483            _ if arg.starts_with("--fetch=") => {
484                fetch = Some(arg["--fetch=".len()..].to_owned());
485            }
486            // The other fetch, which is section 13.4's. Same two spellings for the same reason,
487            // and weighed after the loop so that `--offline` and `--accept-licence` written after
488            // it are read whichever order somebody put them in.
489            "--fetch-msvc-sdk" => {
490                let value = args.get(i).ok_or_else(|| {
491                    err("--fetch-msvc-sdk requires the target to get the SDK for")
492                })?;
493                i += 1;
494                fetch_msvc = Some(value.clone());
495            }
496            _ if arg.starts_with("--fetch-msvc-sdk=") => {
497                fetch_msvc = Some(arg["--fetch-msvc-sdk=".len()..].to_owned());
498            }
499            // Both spellings of the word, because the compiler's own prose uses one of them and
500            // most of the people typing this will reach for the other, and being told that a flag
501            // is not a flag over the letter in the middle of it is a puzzle rather than a message.
502            "--accept-licence" | "--accept-license" => accepted = true,
503            // Accepted on any command line and only ever read by the fetch, because an ordinary
504            // compile downloads nothing with or without it. So this flag takes nothing away today,
505            // which is the property section 13.2 asks for rather than an omission: a build that
506            // passes it is saying what it expects of this compiler, and what it expects is already
507            // true.
508            "--offline" => offline = true,
509            "--print-config" => print_config = true,
510            "--print-pipeline" => print_pipeline = true,
511            "-###" => print_plan = true,
512            "-v" => verbose = true,
513            // The files a compilation goes through, kept rather than thrown away. The bare
514            // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
515            // gcc 16 does; `SaveTemps::Object` carries the measurement.
516            "-save-temps" => opts.save_temps = SaveTemps::Object,
517            _ if arg.starts_with("-save-temps=") => {
518                opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
519            }
520            // How long each step took. A misspelling of this is worth rejecting rather than
521            // ignoring, since a run that says nothing looks like a compilation that took no time.
522            "-time" => opts.time = true,
523            "-c" => opts.emit = EmitKind::Object,
524            "-S" => opts.emit = EmitKind::Asm,
525            "-E" => opts.emit = EmitKind::Preprocessed,
526            "-g" => opts.debug_info = true,
527            // GCC's own levels of how much debug information to write. Zero is none and every
528            // other number is some, and this compiler has one amount, so the numbers above zero
529            // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
530            // debugger on the machine prefers, which is what we emit anyway.
531            "-g0" => opts.debug_info = false,
532            "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
533                opts.debug_info = true;
534            }
535            // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
536            // asks for another version is told rather than handed a file it cannot read.
537            "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
538            _ if arg.starts_with("-gdwarf-") => {
539                return Err(err(format!(
540                    "{arg}: this compiler writes DWARF 5 and no other version, see \
541                     spec/11-debug-info.md"
542                )));
543            }
544            // Whether the debug information goes in a file of its own beside the object. gcc
545            // writes that `.dwo` whether or not it found anything to put in it, which means a
546            // build system that declares the file as an output gets one and a make rule that
547            // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
548            // flag that changes nothing and refuses one that changes what is produced, and a file
549            // that does not appear is the plainest change of that kind there is. The negative
550            // spelling is taken, because putting it all in the object is what happens anyway.
551            "-gno-split-dwarf" => {}
552            "-gsplit-dwarf" => {
553                return Err(err(format!(
554                    "{arg}: this compiler writes no separate `.dwo` file, and a build that \
555                     expects one beside each object would wait for a file that never arrives, \
556                     see spec/11-debug-info.md"
557                )));
558            }
559            // How the debug sections are compressed. There are none yet, so every answer produces
560            // the same bytes and taking the flag promises nothing that is not kept. The value is
561            // still checked, because a typo in a distribution's flags is worth finding when the
562            // compiler reads it rather than when somebody later wonders why nothing got smaller.
563            // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
564            "-gz" => opts.compress = Compress::Zlib,
565            _ if arg.starts_with("-gz=") => {
566                let how = &arg["-gz=".len()..];
567                opts.compress = how.parse().map_err(|()| {
568                    err(format!(
569                        "`{how}` is not a way to compress debug sections, which is none, zlib, \
570                         zlib-gnu or zstd"
571                    ))
572                })?;
573            }
574            "-Werror" => opts.warnings_are_errors = true,
575            // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
576            // through rather than here, so that a warning `-w` dropped is not counted either.
577            "-w" => opts.warnings = false,
578            // Off by default, the way gcc has it off. A header that came with the machine is not
579            // one the person compiling can change, so a warning about it is noise, and under
580            // `-Werror` it is a build that stops on a line nobody in the project wrote. Somebody
581            // porting a header does want to hear all of it, which is what the flag is for.
582            "-Wsystem-headers" => opts.system_header_warnings = true,
583            "-Wno-system-headers" => opts.system_header_warnings = false,
584            "-pedantic-errors" => {
585                opts.pedantic = true;
586                opts.warnings_are_errors = true;
587            }
588            "-P" => opts.line_markers = false,
589            // The dependency family, which section 4.4 calls required because every build system
590            // that generates its own makefiles asks for it. The two that end in `D` write a file
591            // beside the object and let the compilation happen, and the two that do not write to
592            // standard output and stop after it. Nothing here turns the system headers back on
593            // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
594            // `-MM`: the flag asking for fewer of them is the one with something to say.
595            "-M" => {
596                opts.deps.emit = true;
597                opts.deps.instead_of_compiling = true;
598            }
599            "-MM" => {
600                opts.deps.emit = true;
601                opts.deps.instead_of_compiling = true;
602                opts.deps.system_headers = false;
603            }
604            "-MD" => opts.deps.emit = true,
605            "-MMD" => {
606                opts.deps.emit = true;
607                opts.deps.system_headers = false;
608            }
609            "-MP" => opts.deps.phony = true,
610            // These three take a word and only in the separated form, which is how GCC spells
611            // them and how every build system writes them.
612            "-MF" | "-MT" | "-MQ" => {
613                let value =
614                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
615                i += 1;
616                match arg {
617                    "-MF" => opts.deps.file = Some(value.clone()),
618                    // The whole of the difference between the two. `-MT` is for a build that has
619                    // already escaped what it is passing, and `-MQ` is for one that has a name
620                    // and wants it to arrive as that name.
621                    "-MT" => opts.deps.targets.push(value.clone()),
622                    _ => opts.deps.targets.push(deps::escaped(value)),
623                }
624            }
625            // The questions a build system asks before it compiles anything. Answered after the
626            // loop, because each one is about the target or the library search and the command
627            // line has not finished saying what those are.
628            "-dumpmachine" => query = Some(Query::Machine),
629            "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
630            "-print-multiarch" => query = Some(Query::Multiarch),
631            "-print-search-dirs" => query = Some(Query::SearchDirs),
632            "-print-sysroot" => query = Some(Query::Sysroot),
633            // Both spellings, because this one is ours rather than GCC's and our own documents
634            // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
635            // two dashes like the other flags we invented, and document 12's table gives it one
636            // like the `-print-` family it sits in. A person who reads either and types what it
637            // says is right, so neither is refused.
638            "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
639                query = Some(Query::SysrootProvenance);
640            }
641            "-print-sysroot-digest" | "--print-sysroot-digest" => {
642                query = Some(Query::SysrootDigest);
643            }
644            "-print-libgcc-file-name" => query = Some(Query::Libgcc),
645            _ if arg.starts_with("-print-file-name=") => {
646                query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
647            }
648            _ if arg.starts_with("-print-prog-name=") => {
649                query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
650            }
651            // A program built to run in more than one thread. On every platform this compiler
652            // targets that is a macro the library's headers read and one more library on the
653            // link line, and the library is added after the loop so that it lands after the
654            // objects that refer to it.
655            "-pthread" | "-pthreads" => {
656                opts.defines.push("_REENTRANT".to_owned());
657                threads = true;
658            }
659            "-ansi" => {
660                opts.std = Std::C89;
661                opts.gnu_extensions = false;
662            }
663            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
664            // the spelling a build system that groups its warning flags tends to write.
665            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
666            // Both directions, because a build that needs this for one directory turns it back
667            // off for the next one rather than leaving it on for the whole tree.
668            "-fpermissive" => opts.permissive = true,
669            "-fno-permissive" => opts.permissive = false,
670            "-ffreestanding" => opts.hosted = false,
671            "-fhosted" => opts.hosted = true,
672            "-fno-builtin" => opts.builtins = false,
673            "-fbuiltin" => opts.builtins = true,
674            // The C89 dialects are under GNU's reading whatever this says, so turning it off
675            // there is turning off something the dialect asked for, which is accepted and does
676            // nothing. gcc refuses that command line, and there is nothing it could have meant.
677            "-fgnu89-inline" => opts.gnu89_inline = true,
678            "-fno-gnu89-inline" => opts.gnu89_inline = false,
679            // Both directions of each, because a build system that wants one of these usually
680            // writes it beside the flag that turns it back off for one directory.
681            "-fno-omit-frame-pointer" => opts.frame_pointer = true,
682            "-fomit-frame-pointer" => opts.frame_pointer = false,
683            // Both directions again, for the same reason, and a third answer for a command line
684            // that wrote neither: see `reorder_blocks` in `rucc_session`.
685            "-freorder-blocks" => opts.reorder_blocks = Some(true),
686            "-fno-reorder-blocks" => opts.reorder_blocks = Some(false),
687            // gcc's name for the scheduler that runs after the registers are handed out, which is
688            // the only one rucc has: see `schedule_insns` in `rucc_session`. gcc also takes
689            // `-fschedule-insns` for the pass before allocation, and taking that one here would be
690            // a flag that says a pass ran when none did.
691            "-fschedule-insns2" => opts.schedule_insns = Some(true),
692            "-fno-schedule-insns2" => opts.schedule_insns = Some(false),
693            "-mno-red-zone" => opts.red_zone = false,
694            "-mred-zone" => opts.red_zone = true,
695            // Four flags rather than one with an argument, which is how gcc spells them and how
696            // every build line writes them. Last one wins, because a package build puts
697            // `-fstack-protector-strong` in its global flags and a directory that cannot have one
698            // turns it back off on the line after.
699            "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
700                opts.protector = Protector::None;
701            }
702            "-fstack-protector" => opts.protector = Protector::Buffers,
703            "-fstack-protector-strong" => opts.protector = Protector::Strong,
704            "-fstack-protector-all" => opts.protector = Protector::All,
705            // The other half of what a hardened build asks for, and it is a question about the
706            // frame rather than about the function, so it is a switch rather than a level.
707            "-fstack-clash-protection" => opts.stack_clash = true,
708            "-fno-stack-clash-protection" => opts.stack_clash = false,
709            // The third of them, and the one that is a question with an argument rather than a
710            // family of spellings, because what it asks about is which of the two edges of a
711            // control flow transfer is checked. Bare is both of them, which is what gcc does.
712            "-fcf-protection" => opts.control = Control::Full,
713            "-fno-cf-protection" => opts.control = Control::None,
714            // Two spellings of the same request, which is what gcc has as well. `-p` was the older
715            // profiler and `-pg` the one that also recorded who called whom, and on every platform
716            // this compiler targets there is now one hook and both ask for it.
717            "-pg" | "-p" => {
718                opts.profile = true;
719                link.profile = true;
720            }
721            // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
722            // say where the call goes and a command line that asked for no call has nowhere to put
723            // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
724            // directory is a build system that would otherwise fail on every other directory.
725            "-mfentry" => opts.hook = Hook::Early,
726            "-mno-fentry" => opts.hook = Hook::Late,
727            // GCC drops its own include directory along with the system ones, because its
728            // headers are half of a pair with the library's and half a pair is worse than
729            // none. A build that passes this is supplying the whole set itself.
730            "-nostdinc" => nostdinc = true,
731            "-o" => {
732                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
733                i += 1;
734            }
735            // The flags that take a directory only in the separated form. GCC spells them
736            // this way and nothing writes `-iquotedir`, so accepting the joined form would
737            // mean guessing at a path that starts with the flag's own letters.
738            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
739            // two mean the same thing here: the configured directories are under there rather
740            // than under the root.
741            "-isysroot" => {
742                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
743                i += 1;
744                sysroot = Some(PathBuf::from(dir));
745            }
746            "-iquote" | "-isystem" | "-idirafter" => {
747                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
748                i += 1;
749                match arg {
750                    "-iquote" => opts.search.push_quote(dir.clone()),
751                    "-isystem" => opts.search.push_system(dir.clone()),
752                    _ => opts.search.push_after(dir.clone()),
753                }
754            }
755            "-iprefix" => {
756                iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
757                i += 1;
758            }
759            // Where GCC puts these is not where its manual says it puts them, and this is the
760            // measured answer rather than the documented one: `-iwithprefix` lands in the
761            // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
762            // the `-I` slot. A cross build that uses them is relying on the behaviour, since
763            // that is the compiler it was developed against.
764            "-iwithprefix" | "-iwithprefixbefore" => {
765                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
766                i += 1;
767                let dir = format!("{iprefix}{dir}");
768                if arg == "-iwithprefix" {
769                    opts.search.push_system(dir);
770                } else {
771                    opts.search.push_bracket(dir);
772                }
773            }
774            "-include" | "-imacros" => {
775                let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
776                i += 1;
777                opts.preincludes
778                    .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
779            }
780            // The flag `-iquote` was introduced to replace, still passed by build systems old
781            // enough to predate the replacement. It is not a directory: it says that every `-I`
782            // so far is for quoted includes only, and that a quoted include stops looking next
783            // to the file that wrote it.
784            "-I-" => opts.search.split_quote_chain(),
785            "-x" => {
786                let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
787                i += 1;
788                forced = if lang == "none" {
789                    None
790                } else {
791                    Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
792                };
793            }
794            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
795            // translation units in one process rather than making the build system fork, and
796            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
797            // to exist and has to be spelled the way `make` spells it.
798            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
799            // and a build system may produce either, so both are read here rather than
800            // being normalised by whatever generated the command line.
801            _ if arg.starts_with("-D") => {
802                let value = joined_or_next(arg, 2, args, &mut i)?;
803                opts.defines.push(value);
804            }
805            _ if arg.starts_with("-U") => {
806                let value = joined_or_next(arg, 2, args, &mut i)?;
807                opts.undefines.push(value);
808            }
809            _ if arg.starts_with("-I") => {
810                let dir = joined_or_next(arg, 2, args, &mut i)?;
811                opts.search.push_bracket(dir);
812            }
813            _ if arg.starts_with("-std=") => {
814                let name = &arg["-std=".len()..];
815                let (std, gnu) = Std::from_flag(name)
816                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
817                opts.std = std;
818                opts.gnu_extensions = gnu;
819            }
820            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
821            // handed, so a differential run that does not set it is comparing two compilers
822            // that believe they are different compilers.
823            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
824            // that we have not written yet are accepted and ignored, because a dump is a
825            // debugging aid and a build that asks for one should still compile. A letter
826            // outside the family falls through to the unknown option error, which is what
827            // keeps `-dumpversion` from being read as a dump of nothing.
828            _ if Dumps::is_family(arg) => {
829                opts.dumps.add(&arg[2..]);
830            }
831            // One name at a time, which is what a build that means its own `memcpy` and the
832            // library's everything else writes. The name is not checked against a list, because
833            // the flag is about what the program means by a name and a program is allowed to mean
834            // something by a name this compiler has never heard of.
835            _ if arg.starts_with("-fno-builtin-") => {
836                opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
837            }
838            _ if arg.starts_with("-fgnuc-version=") => {
839                let v = &arg["-fgnuc-version=".len()..];
840                opts.gnuc = v.parse().map_err(err)?;
841            }
842            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
843            // than the unknown option one, because a build reaching for it is asking for a feature
844            // and deserves to be told it is not coming rather than told the spelling is wrong.
845            // The negative form is what this compiler does anyway, so it is taken and dropped.
846            "-fnested-functions" => {
847                return Err(err(
848                    "nested functions are not supported: a call to one goes through a trampoline \
849                     written on the stack, which no target that enforces an unexecutable stack \
850                     allows",
851                ));
852            }
853            "-fno-nested-functions" => {}
854            // Which of the two links the output is for, which is a real difference and not a
855            // description of what happens anyway. Everything here is position independent either
856            // way, and what these decide is whether a name may be one another object defines or
857            // replaces, because a link that produces an executable puts every name in the same
858            // program and a link that produces a shared library does not.
859            //
860            // It matters that they are accepted at all, whatever they then do. Every autoconf and
861            // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
862            // be the `CC` of a project that has a configure script, whatever else it can do. That
863            // is how this was found: building SQLite's test fixture stopped on it.
864            "-fPIC" | "-fpic" => opts.pic = Pic::Library,
865            // Not a synonym of the pair above, which is what they were treated as until #756. The
866            // library is the expensive answer and gcc makes it the one that has to be asked for,
867            // so this is also what nothing at all means.
868            "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
869            // A different question from the pair above, and the one every distribution build of a
870            // shared library answers. `-fPIC` decides how an address is reached, and this decides
871            // whether the optimizer may believe a body it can see, because an exported name is one
872            // the dynamic linker may find another definition of first. On by default, which is
873            // gcc's arrangement and is the honest answer, and off is a promise the build makes and
874            // nothing checks.
875            "-fsemantic-interposition" => opts.interposition = true,
876            "-fno-semantic-interposition" => opts.interposition = false,
877            // Two requests rather than one, and the same table answers both, so what decides is
878            // whether either of them is standing. gcc arranges it the same way: the asynchronous
879            // one is the default here and it implies the other, and a line that asks for a table
880            // and against an asynchronous one gets a table.
881            "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
882            "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
883            "-funwind-tables" => opts.unwind_tables = true,
884            "-fno-unwind-tables" => opts.unwind_tables = false,
885            // The other direction is a request, not a description, and it is one this compiler
886            // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
887            // option error. Answering it by carrying on would be answering a different question:
888            // the code would still be position independent, which is correct everywhere an
889            // ordinary program runs and is wrong in a kernel, where the flag is written precisely
890            // because there is no loader to fill a global offset table in.
891            "-fno-pic" | "-fno-pie" => {
892                return Err(err(
893                    "position dependent code is not supported: an address that may be in another \
894                     object is loaded out of the global offset table, and nothing here emits the \
895                     absolute form this asks for. Use -no-pie if what you meant was how to link",
896                ));
897            }
898            // A section per function and a section per variable, which is what makes
899            // `--gc-sections` able to drop anything: a linker can leave out a section nothing
900            // reaches and cannot leave out half of one. Both directions are taken, and the off
901            // one is the default rather than a refusal, since a build that writes it is asking
902            // for what happens anyway.
903            "-ffunction-sections" => opts.function_sections = true,
904            "-fno-function-sections" => opts.function_sections = false,
905            "-fdata-sections" => opts.data_sections = true,
906            "-fno-data-sections" => opts.data_sections = false,
907            // Another description of what this compiler does. A file scope declaration with no
908            // initializer is written into `.bss` as an ordinary defined symbol, not offered to the
909            // linker as a common one for it to merge, which is what `-fno-common` asks for and what
910            // gcc has done by default since 10. Nothing in the front end produces `Linkage::Common`
911            // at all.
912            "-fno-common" => {}
913            // What overflows rather than being undefined. Every one of these takes something away
914            // from the optimizer rather than asking it to do anything, which is why the negative
915            // spellings are the interesting ones and the positive spellings are the default.
916            //
917            // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
918            // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
919            // written here as the pair rather than kept as a third thing to test everywhere.
920            //
921            // `-ftrapv` is the exception and is the one that asks for something. It is the other
922            // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
923            // the other, which makes the last one on the command line the one that counts. That is
924            // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
925            // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
926            // question is left alone by both, because neither has anything to say about it.
927            "-fwrapv" => {
928                opts.wrapping.signed = true;
929                opts.wrapping.trap = false;
930            }
931            "-fno-wrapv" => opts.wrapping.signed = false,
932            "-fwrapv-pointer" => opts.wrapping.pointer = true,
933            "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
934            "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
935            // Which does not clear the checked one, because gcc does not: `-ftrapv
936            // -fstrict-overflow` still emits the calls. It says what is assumed and not what
937            // happens.
938            "-fstrict-overflow" => {
939                opts.wrapping.signed = false;
940                opts.wrapping.pointer = false;
941            }
942            "-ftrapv" => {
943                opts.wrapping.trap = true;
944                opts.wrapping.signed = false;
945            }
946            "-fno-trapv" => opts.wrapping.trap = false,
947            // The two flags that say what a plain `char` is, which is one question with two
948            // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
949            // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
950            // answers and the last one written wins. Nothing is set until one of them is given,
951            // because the target's own ABI is the answer otherwise and it is not the same answer
952            // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
953            "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
954            "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
955            // And the size of an enumeration, which is the other thing in this group that changes
956            // the ABI rather than the code.
957            "-fshort-enums" => opts.short_enums = true,
958            "-fno-short-enums" => opts.short_enums = false,
959            // And Microsoft's reading of an anonymous member, which changes the layout of every
960            // record that writes a tag on one. Nothing is set until one of them is given, because
961            // the target is the answer otherwise: gcc's mingw build has this on and its Linux
962            // build has it off.
963            "-fms-extensions" => opts.ms_extensions = Some(true),
964            "-fno-ms-extensions" => opts.ms_extensions = Some(false),
965            // And the request, which is the one that cannot be granted. It is a real difference and
966            // not a preference: two files each writing `int g;` link under `-fcommon` and are a
967            // duplicate definition without it, which is the whole reason the flag survives.
968            "-fcommon" => {
969                return Err(err(
970                    "a tentative definition is written into .bss as its own symbol here, and \
971                     nothing emits the common symbol this asks the linker to merge. Give the \
972                     variable a definition in one file and declare it extern in the others",
973                ));
974            }
975            // Both directions of this one are recorded, and what they decide is whether lowering
976            // names the type each access goes through. Turning it off is the front end leaving the
977            // name off rather than a pass being told to ignore one it can see, which is one
978            // condition in one place, and it is the reading that survives link time optimization:
979            // a unit built with the flag off keeps its own answer when its bodies end up in a
980            // module beside bodies that were not.
981            //
982            // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
983            // and is tested, and no pass at any level asks the alias analysis anything today, so
984            // no program compiles differently for having passed this. The flag is wired anyway,
985            // because the change that makes a pass ask is not the change anybody will remember to
986            // wire it in, and a flag that is taken and dropped once the names mean something is
987            // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
988            // words.
989            "-fstrict-aliasing" => opts.strict_aliasing = true,
990            "-fno-strict-aliasing" => opts.strict_aliasing = false,
991            // The same shape of answer for the same reason, and the flag the kernel writes beside
992            // the one above it.
993            //
994            // Nothing here concludes that a pointer is not null from the fact that it was
995            // dereferenced. There is no such conclusion to draw from, because no pass records one:
996            // a load says where it read and nothing else, and a comparison against null is an
997            // ordinary comparison of two values the optimizer has no fact about. So a function
998            // that reads through a pointer and then tests it keeps the test, which is what the
999            // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
1000            // to be asked for because it draws the conclusion by default.
1001            //
1002            // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
1003            // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
1004            // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
1005            "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
1006            // The floating point group, which goes the same way and for the same reason, and which
1007            // is worth writing out because the reason is easy to get backwards.
1008            //
1009            // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
1010            // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
1011            // changed and that an exception raised by an operation may be looked at, so an
1012            // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
1013            // whose exception the program does not get. Nothing here folds any floating point
1014            // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
1015            // that runs, at every level. So both of those describe what already happens.
1016            //
1017            // The permissive ones are the other half, and they are licences rather than requests
1018            // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
1019            // `-fno-trapping-math` says nothing looks at the exceptions, which together are
1020            // permission to fold. Not folding is the conservative side of that permission and is
1021            // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
1022            // speed and not correctness, which is the test section 4.1 puts a licence through.
1023            "-frounding-math" | "-fno-rounding-math" => {}
1024            // `-fno-trapping-math` is the one of the four that is kept, because there is one
1025            // conversion this compiler does not fold and gcc folds under it, and the two answers
1026            // differ. Converting a constant floating value to an integer type it does not fit in
1027            // is undefined behaviour rather than a value: left to the hardware it is one
1028            // instruction and the answer is the integer indefinite value, and folded it is the
1029            // nearest end of the integer's range. Both compilers leave it to the instruction by
1030            // default and gcc folds it under this flag, so a program built with it and compiled
1031            // without it gets a different number rather than a slower one. `-ftrapping-math` is
1032            // gcc's default, so a build spelling it out is asking for what it already has.
1033            //
1034            // The rest of the family goes with it, `-ffast-math` included, and all of them are
1035            // taken now. Each is a licence rather than a request and nothing here folds floating
1036            // point arithmetic, so the code does not change. What does change is the macros gcc
1037            // defines for each licence, which a header reads, and the startup file `-ffast-math`
1038            // links, which puts the hardware in flush to zero mode. Both are done after the loop,
1039            // because the family is a set of switches over the same fields and the last word on
1040            // each of them is the end of the command line.
1041            "-ftrapping-math"
1042            | "-fno-trapping-math"
1043            | "-ffast-math"
1044            | "-fno-fast-math"
1045            | "-funsafe-math-optimizations"
1046            | "-fno-unsafe-math-optimizations"
1047            | "-fmath-errno"
1048            | "-fno-math-errno"
1049            | "-ffinite-math-only"
1050            | "-fno-finite-math-only"
1051            | "-fsigned-zeros"
1052            | "-fno-signed-zeros"
1053            | "-freciprocal-math"
1054            | "-fno-reciprocal-math"
1055            | "-fassociative-math"
1056            | "-fno-associative-math" => math_flags.push(arg),
1057            // Whether the startup file that sets flush to zero is linked, asked directly. gcc
1058            // links it for a shared object too when this is written, which the family does not.
1059            "-mdaz-ftz" => daz_ftz = Some(true),
1060            "-mno-daz-ftz" => daz_ftz = Some(false),
1061            // About temporary files rather than about code. There is nothing between the phases of
1062            // one compilation here to write to a file in the first place.
1063            "-pipe" => {}
1064            // Nothing here writes colour, so all of these are the same answer, and it is the answer
1065            // that costs nothing: the diagnostics come out plain either way and no build depends on
1066            // an escape sequence being there. Taken rather than refused because cmake writes
1067            // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
1068            // makes this the second most common flag after `-fPIC` to stop a build over a question
1069            // about how the text looks.
1070            "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
1071            _ if arg.starts_with("-fdiagnostics-color=") => {}
1072            // The link flags. None of them changes the compilation, which is why they are
1073            // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
1074            // error: it is a thing said to a linker that is not going to run.
1075            "-static" => link.is_static = true,
1076            "-shared" => link.shared = true,
1077            "-pie" => link.pie = Some(true),
1078            "-no-pie" | "-nopie" => link.pie = Some(false),
1079            "-nostdlib" => link.no_stdlib = true,
1080            "-nostartfiles" => link.no_startfiles = true,
1081            "-nodefaultlibs" => link.no_defaultlibs = true,
1082            "-fno-builtins-lib" => link.no_builtins_lib = true,
1083            "-fbuiltins-lib" => link.no_builtins_lib = false,
1084            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
1085            "-s" => link.strip = true,
1086            // Into the ordered input list rather than a list of its own, because a great many of
1087            // the linker's options are a bracket around the files after them and an option that
1088            // lost its place among them says nothing. `--whole-archive` is the one that found this.
1089            "-Xlinker" => {
1090                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
1091                i += 1;
1092                inputs.push(Input::linker(next));
1093            }
1094            _ if arg.starts_with("-Wl,") => {
1095                // Commas separate arguments rather than being part of one, which is what makes
1096                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
1097                inputs.extend(arg["-Wl,".len()..].split(',').map(Input::linker));
1098            }
1099            _ if arg.starts_with("-fuse-ld=") => {
1100                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
1101            }
1102            _ if arg.starts_with("-l") && arg.len() > 2 => {
1103                inputs.push(Input::library(&arg[2..]));
1104            }
1105            "-l" => {
1106                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
1107                i += 1;
1108                inputs.push(Input::library(next));
1109            }
1110            _ if arg.starts_with("-L") => {
1111                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1112            }
1113            _ if arg.starts_with("-B") => {
1114                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1115            }
1116            _ if arg.starts_with("-j") => {
1117                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
1118            }
1119            _ if arg.starts_with("--sysroot=") => {
1120                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
1121            }
1122            _ if arg.starts_with("--target=") => {
1123                let t = &arg["--target=".len()..];
1124                // The same string again, as the model that has room for a libc version. A spelling
1125                // the three field parser took and this one does not is not an error, because the
1126                // one that decides what is compiled has already accepted it and the only thing
1127                // lost is a version nobody asked for.
1128                pinned = t.parse().ok();
1129                // The other way round is a deployment target the three field parser has no room
1130                // for, `aarch64-macos.13`, and the triple is the one the tuple narrows to.
1131                opts.target = match t.parse() {
1132                    Ok(triple) => triple,
1133                    Err(e) => {
1134                        pinned.and_then(Triple::from_tuple).ok_or_else(|| err(format!("{e}")))?
1135                    }
1136                };
1137            }
1138            _ if arg.starts_with("--emit=") => {
1139                let k = &arg["--emit=".len()..];
1140                opts.emit = k
1141                    .parse()
1142                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
1143            }
1144            // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
1145            // to write. `-Og` is GCC's level for a build somebody is going to step through, and
1146            // it is `-O1` with the transformations that move code around left out; this compiler
1147            // has no such level yet, so it is the nearest one and `--print-pipeline` says what
1148            // that came to rather than the flag pretending otherwise.
1149            "-O" | "-Og" => {
1150                opts.opt_level = rucc_session::OptLevel::O1;
1151                ofast = false;
1152            }
1153            // The union of `-O3` and `-ffast-math`. The second half is a default rather than a
1154            // flag, which is why it is remembered here and applied after the loop: a later level
1155            // takes it back, and so does a `-fno-fast-math` written on either side of it.
1156            "-Ofast" => {
1157                opts.opt_level = rucc_session::OptLevel::O3;
1158                ofast = true;
1159            }
1160            _ if arg.starts_with("-O") => {
1161                ofast = false;
1162                opts.opt_level = arg[2..]
1163                    .parse()
1164                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
1165            }
1166            // How far a multiply and an addition may be fused into one rounding. Before the
1167            // optimizer's `-f` family below for the reason the ones under it are, and kept rather
1168            // than dropped because it is the one flag in its group this compiler could act on: it
1169            // rides into the IR as an attribute on each function with a body, so the day the code
1170            // generator forms an `fma` it already knows which functions were given permission.
1171            // Nothing forms one today, under any value of this and under any `-march=`.
1172            _ if arg.starts_with("-ffp-contract=") => {
1173                let how = &arg["-ffp-contract=".len()..];
1174                opts.fp_contract = how.parse().map_err(|()| {
1175                    err(format!("`{how}` is not a contraction, which is fast, on or off"))
1176                })?;
1177            }
1178            // How much of an expression may be computed wider than it was written. The values are
1179            // gcc's and so is the refusal of anything else, and none of the three changes anything
1180            // here: an operation is computed in the type C says it is on every target this compiler
1181            // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
1182            // happens. `fast` and `16` are permission to be wider, which is a licence this takes
1183            // and does not use, the same way the two above are. The flag is worth taking because
1184            // glibc's headers and a good deal of configure output write it, and because the answer
1185            // it asks about is one this compiler can state rather than guess at: there is no x87
1186            // target here, which is the machine the whole question was invented for.
1187            // Whether a local and a spilled value that are never both wanted may be the same bytes
1188            // of the frame. gcc's three values, and two of them mean the same thing here: what rucc
1189            // shares is a local whose address provably never leaves the function, which is narrower
1190            // than `named_vars` and narrower still than `all`, so both of them get it. `none` is
1191            // the one that changes anything, and it is the flag a program that reads a local
1192            // through a pointer it kept past the end of the block writes.
1193            _ if arg.starts_with("-fstack-reuse=") => {
1194                let how = &arg["-fstack-reuse=".len()..];
1195                opts.stack_reuse = match how {
1196                    "all" | "named_vars" => Some(true),
1197                    "none" => Some(false),
1198                    _ => {
1199                        return Err(err(format!(
1200                            "`{how}` is not a stack reuse, which is all, named_vars or none"
1201                        )));
1202                    }
1203                };
1204            }
1205            _ if arg.starts_with("-fexcess-precision=") => {
1206                let how = &arg["-fexcess-precision=".len()..];
1207                if !matches!(how, "16" | "fast" | "standard") {
1208                    return Err(err(format!(
1209                        "`{how}` is not an excess precision, which is 16, fast or standard"
1210                    )));
1211                }
1212            }
1213            // Which front of a path is rewritten before it reaches the output, which is how a
1214            // build gets the same bytes out of two different directories. The four spellings are
1215            // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
1216            // once. Only the macro list does anything today, because `__FILE__` is the only place
1217            // a path reaches the output: there is no DWARF and no profile data yet, so the other
1218            // two are recorded for the work that will read them. The argument splits at the last
1219            // `=` rather than the first, which is gcc's rule and is what lets a directory with an
1220            // `=` in its name be the old half.
1221            _ if arg.starts_with("-fmacro-prefix-map=") => {
1222                let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1223                opts.prefix_map.macros.push(old, new);
1224            }
1225            _ if arg.starts_with("-fdebug-prefix-map=") => {
1226                let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1227                opts.prefix_map.debug.push(old, new);
1228            }
1229            _ if arg.starts_with("-fprofile-prefix-map=") => {
1230                let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1231                opts.prefix_map.profile.push(old, new);
1232            }
1233            _ if arg.starts_with("-ffile-prefix-map=") => {
1234                let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1235                opts.prefix_map.macros.push(old, new);
1236                opts.prefix_map.debug.push(old, new);
1237                opts.prefix_map.profile.push(old, new);
1238            }
1239            // A whole optimization rather than a flag, and the family is taken rather than
1240            // refused because of what ignoring it does. There is none of it here yet, so a build
1241            // that asks for it gets a program that is correct and slower than it could have been,
1242            // which is what section 4.1 means by a hint about speed and what every compilation at
1243            // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1244            // holds the bytecode and no machine code at all, and every object here holds the code,
1245            // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1246            // to this compiler gets objects that are more usable than the ones it asked for rather
1247            // than different ones. Every value is still checked against gcc's, because somebody
1248            // who wrote `-flto=thin` meant clang and had better hear about it here.
1249            "-flto" => opts.lto.requested = true,
1250            "-fno-lto" => opts.lto.requested = false,
1251            _ if arg.starts_with("-flto=") => {
1252                let how = &arg["-flto=".len()..];
1253                opts.lto.jobs = how.parse().map_err(|()| {
1254                    err(format!(
1255                        "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1256                         count above zero"
1257                    ))
1258                })?;
1259                opts.lto.requested = true;
1260            }
1261            _ if arg.starts_with("-flto-partition=") => {
1262                let how = &arg["-flto-partition=".len()..];
1263                opts.lto.partition = how.parse().map_err(|()| {
1264                    err(format!(
1265                        "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1266                         or none"
1267                    ))
1268                })?;
1269            }
1270            _ if arg.starts_with("-flto-compression-level=") => {
1271                let how = &arg["-flto-compression-level=".len()..];
1272                let level =
1273                    how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1274                        err(format!("`{how}` is not a compression level, 0 to 19"))
1275                    })?;
1276                opts.lto.compression = Some(level);
1277            }
1278            // Whether the object keeps its machine code as well as the bytecode. It always does
1279            // here, so the first of these describes what happens and the second asks for an object
1280            // with less in it, which is a smaller file and not a different program, so both are
1281            // taken.
1282            "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1283            // Whether the linker is handed a plugin that does the link time work. The design in
1284            // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1285            // plugin into anybody, so neither answer is a question it has to hold.
1286            "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1287            // Reading a profile back. Taken for the reason the family above it is: nothing here
1288            // reads one, so a build that asks gets the program it would have got anyway, and gcc
1289            // itself produces a byte for byte identical object from `-fprofile-use` when there are
1290            // no counts beside the file. The path is recorded for the pass that will read it. The
1291            // warning gcc prints when it looked and found nothing is deliberately not copied,
1292            // because nothing here looks, and a warning about a file that was never opened would
1293            // fire on the builds that have a perfectly good profile as well as on the ones that
1294            // do not.
1295            "-fprofile-use" => opts.profile_data.requested = true,
1296            "-fno-profile-use" => opts.profile_data.requested = false,
1297            _ if arg.starts_with("-fprofile-use=") => {
1298                opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1299                opts.profile_data.requested = true;
1300            }
1301            _ if arg.starts_with("-fprofile-dir=") => {
1302                opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1303            }
1304            "-fprofile-abs-path" => opts.profile_data.absolute = true,
1305            "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1306            "-fprofile-correction" => opts.profile_data.correction = true,
1307            "-fno-profile-correction" => opts.profile_data.correction = false,
1308            "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1309            "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1310            // Writing the counts rather than reading them, which is refused rather than taken and
1311            // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1312            // file a build declared as an output never appears: the instrumented program writes a
1313            // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1314            // two stage build that got neither would go on to optimize against no counts at all
1315            // and report coverage of nothing, with nothing along the way saying so. The objects
1316            // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1317            // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1318            // this is a flag that changes the output rather than a hint about speed.
1319            "-fprofile-arcs"
1320            | "--coverage"
1321            | "-fcondition-coverage"
1322            | "-fpath-coverage"
1323            | "-fprofile-generate" => {
1324                return Err(err(format!(
1325                    "{arg}: this compiler does not instrument for profiling, and a build that \
1326                     expects the counts a run of the instrumented program writes would optimize \
1327                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1328                )));
1329            }
1330            _ if arg.starts_with("-fprofile-generate=") => {
1331                return Err(err(format!(
1332                    "{arg}: this compiler does not instrument for profiling, and a build that \
1333                     expects the counts a run of the instrumented program writes would optimize \
1334                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1335                )));
1336            }
1337            "-ftest-coverage" => {
1338                return Err(err(format!(
1339                    "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1340                     that expects one would wait for a file that never arrives, see \
1341                     spec/04-driver-and-cli.md"
1342                )));
1343            }
1344            // The rest of the family describes instrumentation that is refused above, so what is
1345            // left to do with them is check them and drop them. They are checked because a
1346            // misspelling in a distribution's flags is worth finding here rather than on the day
1347            // the instrumentation lands, and dropped because there is nothing for an answer about
1348            // how a counter is written to be an answer about.
1349            _ if arg.starts_with("-fprofile-update=") => {
1350                let how = &arg["-fprofile-update=".len()..];
1351                if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1352                    return Err(err(format!(
1353                        "`{how}` is not a profile update method, which is single, atomic or \
1354                         prefer-atomic"
1355                    )));
1356                }
1357            }
1358            _ if arg.starts_with("-fprofile-reproducible=") => {
1359                let how = &arg["-fprofile-reproducible=".len()..];
1360                if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1361                    return Err(err(format!(
1362                        "`{how}` is not a profile reproducibility method, which is serial, \
1363                         parallel-runs or multithreaded"
1364                    )));
1365                }
1366            }
1367            "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1368            "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1369            _ if arg.starts_with("-fprofile-filter-files=")
1370                || arg.starts_with("-fprofile-exclude-files=")
1371                || arg.starts_with("-fprofile-note=") => {}
1372            // What every name gets when nothing in the source said, which the attribute in the
1373            // source overrides rather than the other way round. Before the optimizer's `-f`
1374            // family below for the reason the tier below it is.
1375            _ if arg.starts_with("-fvisibility=") => {
1376                let seen = &arg["-fvisibility=".len()..];
1377                opts.visibility = seen.parse().map_err(|()| {
1378                    err(format!(
1379                        "`{seen}` is not a visibility, which is default, hidden, internal or \
1380                         protected"
1381                    ))
1382                })?;
1383            }
1384            // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1385            // family below for the reason the two above it are, and last of the three so that the
1386            // bare spelling and the negative one are matched exactly rather than by this.
1387            _ if arg.starts_with("-fcf-protection=") => {
1388                let edges = &arg["-fcf-protection=".len()..];
1389                opts.control = edges.parse().map_err(|()| {
1390                    err(format!(
1391                        "`{edges}` is not a control flow protection, which is full, branch, \
1392                         return, none or check"
1393                    ))
1394                })?;
1395            }
1396            // How much room every function opens with for something to be written over later.
1397            // Before the optimizer's `-f` family below for the reason the ones above it are.
1398            _ if arg.starts_with("-fpatchable-function-entry=") => {
1399                let room = &arg["-fpatchable-function-entry=".len()..];
1400                opts.patchable = room.parse().map_err(|()| {
1401                    err(format!(
1402                        "`{room}` is not an amount of room to reserve, which is a number of bytes                          and then, after a comma, how many of them go in front of the function's                          own label"
1403                    ))
1404                })?;
1405            }
1406            // The memory safety monitor, from section 15.4 of
1407            // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1408            // because a pass that took the name `safety=detect` would otherwise be handed the
1409            // flag, and the tier is not a pass.
1410            _ if arg.starts_with("-fsafety=") => {
1411                let tier = &arg["-fsafety=".len()..];
1412                opts.safety = tier.parse().map_err(|()| {
1413                    err(format!(
1414                        "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1415                    ))
1416                })?;
1417            }
1418            // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1419            // than folded into the tier because it is a departure somebody who has read that
1420            // section makes, and the two defaults it describes are a property of what is being
1421            // built rather than of how much checking is wanted.
1422            _ if arg.starts_with("-fsafety-init=") => {
1423                let mode = &arg["-fsafety-init=".len()..];
1424                opts.padding = mode.parse().map_err(|()| {
1425                    err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1426                })?;
1427            }
1428            // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1429            // strict form of that section needs a member id the front end does not name yet and
1430            // accepting the spelling for it would be accepting a promise this build cannot keep.
1431            // Before `-fno-` is looked at below, for the reason the tier is.
1432            "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1433            "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1434            _ if arg.starts_with("-fsafety-subobject=") => {
1435                let form = &arg["-fsafety-subobject=".len()..];
1436                return Err(err(format!(
1437                    "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1438                     the strict form of section 9.4 is tamnd/rucc#967"
1439                )));
1440            }
1441            // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1442            // the one above has none: there is one form of this check and a spelling that suggested
1443            // otherwise would be promising something. Before `-fno-` is looked at below, the same
1444            // way.
1445            "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1446            "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1447            _ if arg.starts_with("-fsafety-restrict=") => {
1448                let form = &arg["-fsafety-restrict=".len()..];
1449                return Err(err(format!(
1450                    "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1451                )));
1452            }
1453            // Section 9.5's races, which take a value because the section gives them three modes
1454            // and the difference between two of them is which classes get reported rather than how
1455            // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1456            // reason the two above spell theirs out.
1457            _ if arg.starts_with("-fsafety-races=") => {
1458                let mode = &arg["-fsafety-races=".len()..];
1459                opts.races = mode.parse().map_err(|()| {
1460                    err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1461                })?;
1462            }
1463            "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1464            // The sanitizers of document 12, which are checks at run time rather than a way of
1465            // generating the same program. Each name is held to gcc 16's list, and what is still
1466            // asked for by the end of the line is answered after the loop, so that a command line
1467            // which turns one on and then off again is a command line that asked for nothing.
1468            //
1469            // Before the optimizer's `-f` family below, for the reason the tier above it is.
1470            _ if arg.starts_with("-fsanitize=") => {
1471                for one in arg["-fsanitize=".len()..].split(',') {
1472                    if one == "all" {
1473                        // gcc takes `all` only in the negative, because turning every check on at
1474                        // once includes checks that contradict each other.
1475                        return Err(err(
1476                            "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1477                        ));
1478                    }
1479                    if !SANITIZERS.contains(&one) {
1480                        return Err(err(format!(
1481                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1482                        )));
1483                    }
1484                    if !sanitizers.contains(&one) {
1485                        sanitizers.push(one);
1486                    }
1487                }
1488            }
1489            _ if arg.starts_with("-fno-sanitize=") => {
1490                for one in arg["-fno-sanitize=".len()..].split(',') {
1491                    if one == "all" {
1492                        sanitizers.clear();
1493                        continue;
1494                    }
1495                    if !SANITIZERS.contains(&one) {
1496                        return Err(err(format!(
1497                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1498                        )));
1499                    }
1500                    sanitizers.retain(|asked| *asked != one);
1501                }
1502            }
1503            // What a check does when it fires, and where the records about the checked objects go.
1504            // Each of them is an answer about the sanitizers refused after the loop, so there is
1505            // nothing left for them to change here. The names are still held to the list, because
1506            // a misspelling in a build's flags is worth finding when the compiler reads it.
1507            _ if arg.starts_with("-fsanitize-recover=")
1508                || arg.starts_with("-fno-sanitize-recover=")
1509                || arg.starts_with("-fsanitize-trap=")
1510                || arg.starts_with("-fno-sanitize-trap=") =>
1511            {
1512                // The guard above matched on a spelling that has an `=` in it, so the tail is
1513                // whatever follows the first one.
1514                let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1515                for one in how.split(',') {
1516                    if one != "all" && !SANITIZERS.contains(&one) {
1517                        return Err(err(format!(
1518                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1519                        )));
1520                    }
1521                }
1522            }
1523            "-fsanitize-undefined-trap-on-error"
1524            | "-fsanitize-address-use-after-scope"
1525            | "-fno-sanitize-address-use-after-scope" => {}
1526            _ if arg.starts_with("-fsanitize-sections=") => {}
1527            // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1528            // keeping. Refused rather than dropped, because a fuzzer whose calls into
1529            // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1530            // and there is no point in the campaign where that announces itself.
1531            _ if arg.starts_with("-fsanitize-coverage=") => {
1532                let how = &arg["-fsanitize-coverage=".len()..];
1533                for one in how.split(',') {
1534                    if !matches!(one, "trace-pc" | "trace-cmp") {
1535                        return Err(err(format!(
1536                            "`{one}` is not a coverage instrumentation, which is trace-pc or \
1537                             trace-cmp"
1538                        )));
1539                    }
1540                }
1541                return Err(err(format!(
1542                    "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1543                     with it would run without any feedback at all, see \
1544                     spec/04-driver-and-cli.md section 4.7"
1545                )));
1546            }
1547            // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1548            // after every `-f` the rest of the compiler answers to, so a pass can never take a
1549            // name that already means something else on the command line.
1550            _ if arg.starts_with("-fpass-fuel=") => {
1551                let (name, count) = arg["-fpass-fuel=".len()..]
1552                    .split_once('=')
1553                    .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1554                if rucc_opt::pass::find(name).is_none() {
1555                    return Err(err(format!(
1556                        "`{name}` is not a pass this compiler has, see --print-pipeline"
1557                    )));
1558                }
1559                let count: u32 = count
1560                    .parse()
1561                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1562                opts.pass_fuel.push((name.to_owned(), count));
1563            }
1564            _ if arg.starts_with("-fpass-fuel-global=") => {
1565                let count = &arg["-fpass-fuel-global=".len()..];
1566                let count: u32 = count
1567                    .parse()
1568                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1569                opts.pass_fuel_global = Some(count);
1570            }
1571            // Everything from `-fopt-info` to the end of the argument, which is optional
1572            // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1573            // where the remarks are printed, because by then the compilation somebody wanted
1574            // to hear about is over.
1575            _ if arg == "-fopt-info"
1576                || arg.starts_with("-fopt-info=")
1577                || arg.starts_with("-fopt-info-") =>
1578            {
1579                let rest = &arg["-fopt-info".len()..];
1580                let (kinds, file) = match rest.split_once('=') {
1581                    Some((kinds, file)) => (kinds, Some(file)),
1582                    None => (rest, None),
1583                };
1584                let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1585                rucc_opt::Wants::none().add(kinds).map_err(err)?;
1586                opts.opt_info.push(kinds.to_owned());
1587                if let Some(file) = file {
1588                    if file.is_empty() {
1589                        return Err(err("-fopt-info= was given no file to write to"));
1590                    }
1591                    opts.opt_info_file = Some(file.to_owned());
1592                }
1593            }
1594            _ if arg.starts_with("-fdump-ir=") => {
1595                // Checked here rather than where the dumps are taken, because the compilation
1596                // that would have been dumped is over by then.
1597                let spec = &arg["-fdump-ir=".len()..];
1598                rucc_opt::Dumps::default().add(spec).map_err(err)?;
1599                opts.dump_ir.push(spec.to_owned());
1600            }
1601            // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1602            // otherwise take the flag away from the gate. Checked here rather than where the
1603            // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1604            // name that quietly gated nothing looks exactly like a pass that is not the guilty
1605            // one, and a bisection would carry on past the thing it was looking for.
1606            _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1607                let on = arg.starts_with("-fenable-");
1608                let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1609                rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1610                opts.pass_gates.push((on, spec.to_owned()));
1611            }
1612            // gcc's spelling for a pass this compiler has under a shorter name. It goes above the
1613            // two arms below rather than into the pile of gcc pass names further down, because the
1614            // pass is here: dropping the flag would leave a build that asked for unrolling without
1615            // it, and refusing it stops the build outright, which is what libtommath's makefile
1616            // ran into. `-funroll-all-loops` is deliberately not in here: gcc's is the one that
1617            // unrolls without a trip count, which is a different and usually worse thing.
1618            "-funroll-loops" => opts.passes.push(("unroll".to_owned(), true)),
1619            "-fno-unroll-loops" => opts.passes.push(("unroll".to_owned(), false)),
1620            // Here rather than through the two arms below, because what this names is not a
1621            // `rucc_opt::Pass`. Section 34.6's propagation is a module at a time and everything in
1622            // the pass list is one function at a time. `-fipa-cp-clone` is deliberately not here:
1623            // gcc turns that one on at `-O3` and it is in the list of what M4 does not build.
1624            "-fipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), true)),
1625            "-fno-ipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), false)),
1626            // The other half of the same section, here for the same reason, and `-fipa-sra` in gcc
1627            // is the aggregate splitting as well as the parameter removal. Asking for it gets the
1628            // half that is built.
1629            "-fipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), true)),
1630            "-fno-ipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), false)),
1631            // And the printf family fold, which is a module at a time for the same reason and so is
1632            // not a `rucc_opt::Pass` either. gcc has no flag of its own for this one, since
1633            // `-fno-builtin` already turns it off along with everything else the standard names
1634            // mean. This spelling is for taking one thing away during a bisection without taking
1635            // the rest of section 20.1 away with it.
1636            "-flibcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), true)),
1637            "-fno-libcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), false)),
1638            _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1639                opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1640            }
1641            _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1642                opts.passes.push((arg["-f".len()..].to_owned(), true));
1643            }
1644            // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1645            // program reduced from a miscompilation usually names the pass that miscompiled it on
1646            // its `dg-options` line, and they arrive from hand written build files for the same
1647            // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1648            // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1649            // for a compiler that does not exist here, and the program it is attached to is a
1650            // correctness test that passes either way. Turning on a pass we do not have costs
1651            // speed, turning off a pass we do not have costs nothing, and neither changes what the
1652            // program computes.
1653            //
1654            // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1655            // compiler has rather than landing here, and the day one of these names becomes a pass
1656            // here it stops being taken and dropped without anybody editing this list.
1657            //
1658            // Two of them are prefixes rather than names, which is the one place this file takes a
1659            // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1660            // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1661            // nothing else, and there is no member of either that changes the meaning of a program
1662            // that was already correct. The rest are written out one at a time, because they live
1663            // in the flat `-f` namespace where the neighbours do change meanings.
1664            _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1665            _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1666            "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1667            "-fmodulo-sched" | "-fno-modulo-sched" => {}
1668            "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1669            _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1670            }
1671            "-fearly-inlining" | "-fno-early-inlining" => {}
1672            // The one of the family that does reach the optimizer, since the step it names is built:
1673            // `-fno-inline` stops a function declared `inline` from being inlined and leaves
1674            // `always_inline` alone, which is what it does in gcc.
1675            "-finline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), true)),
1676            "-fno-inline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), false)),
1677            "-finline-functions"
1678            | "-fno-inline-functions"
1679            | "-finline-small-functions"
1680            | "-fno-inline-small-functions"
1681            | "-finline-functions-called-once"
1682            | "-fno-inline-functions-called-once" => {}
1683            "-foptimize-strlen" | "-fno-optimize-strlen" => {}
1684            "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
1685            // Where a function starts, which is a thing this compiler already decides and so is a
1686            // request it can answer rather than one it has to drop. The bare form asks for the
1687            // target's default and the default here is the sixteen bytes gcc also gives, so it
1688            // says nothing; a number is a floor under every function that did not ask for more
1689            // itself; and the negative form asks for the smallest boundary the target has. gcc 16
1690            // rounds a number that is not a power of two up rather than refusing it, which is what
1691            // `=3` giving `.p2align 2` on x86-64 means, so this rounds too.
1692            "-falign-functions" => opts.align_functions = None,
1693            "-fno-align-functions" => opts.align_functions = Some(MIN_FUNC_ALIGN),
1694            _ if arg.starts_with("-falign-functions=") => {
1695                opts.align_functions = function_alignment(&arg["-falign-functions=".len()..])
1696                    .ok_or_else(|| {
1697                        err(format!("{arg}: the alignment has to be a number of bytes"))
1698                    })?;
1699            }
1700            // The head of every hot loop, which is padded when this is asked for so that a loop that
1701            // fits in a 64 byte line does not cross one. Both directions of the plain form are
1702            // answered. A number is taken and says nothing, because the boundary here is the
1703            // line's and a build that names another is asking for speed rather than for a
1704            // different program.
1705            "-falign-loops" => opts.align_loops = Some(true),
1706            "-fno-align-loops" => opts.align_loops = Some(false),
1707            // The other two of the family, which are about padding in front of any label and in
1708            // front of a label only a jump reaches. This compiler writes neither, and what they
1709            // ask for is speed: a label on a boundary computes what a label off one computes. So
1710            // they are taken and dropped for the reason `-march=` is, and the numbered form of
1711            // the loop flag with them.
1712            _ if arg.starts_with("-falign-labels")
1713                || arg.starts_with("-falign-loops=")
1714                || arg.starts_with("-falign-jumps")
1715                || arg.starts_with("-fno-align-labels")
1716                || arg.starts_with("-fno-align-jumps") => {}
1717            // The charset flags are not in that pile, because an encoding is a statement about
1718            // what the bytes of the source mean rather than about how fast the output is. The
1719            // preprocessor reads UTF-8 and has no converter, so the one name that describes what
1720            // already happens is taken and every other name is refused. Spelled without regard to
1721            // case and with both of the spellings iconv answers to, since a build writes whichever
1722            // one its author typed.
1723            _ if arg.starts_with("-finput-charset=") => {
1724                let name = &arg["-finput-charset=".len()..];
1725                if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
1726                    return Err(err(format!(
1727                        "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
1728                         converter, so a file in another encoding would be read as though it were \
1729                         UTF-8 rather than converted",
1730                    )));
1731                }
1732            }
1733            // The one that came in on the same `dg-options` lines as `-ffast-math` and is the other
1734            // half of section 4.1's rule, because it changes what the program does and not how
1735            // fast it does it. The negative form is what this compiler does anyway, so it is taken
1736            // and dropped, which is the shape `-fnested-functions` has above.
1737            "-fnon-call-exceptions" => {
1738                return Err(err(
1739                    "-fnon-call-exceptions is a promise that an instruction which is not a call \
1740                     can raise an exception the unwinder finds a handler for, and nothing here \
1741                     produces a landing pad for a trapping instruction. A program built without it \
1742                     would unwind past the handler it wrote",
1743                ));
1744            }
1745            "-fno-non-call-exceptions" => {}
1746            "-finstrument-functions" => opts.instrument_functions = true,
1747            "-fno-instrument-functions" => opts.instrument_functions = false,
1748            // The unstable options, spelled the way rustc spells them and carrying the same
1749            // promise, which is none: one of these may change or go away in any release. They are
1750            // measurements and debugging aids rather than things a build asks for, which is why
1751            // none of them is in the usage text and all of them are in section 4.11 of
1752            // `spec/04-driver-and-cli.md`.
1753            "-Zverify-each" => opts.verify_each = true,
1754            _ if arg.starts_with("-Zrule-coverage=") => {
1755                let file = &arg["-Zrule-coverage=".len()..];
1756                if file.is_empty() {
1757                    return Err(err("-Zrule-coverage= needs a file to write to"));
1758                }
1759                opts.rule_coverage = Some(file.to_owned());
1760            }
1761            _ if arg.starts_with("-Zcycle-accurate-model=") => {
1762                let value = &arg["-Zcycle-accurate-model=".len()..];
1763                opts.cycle_accurate_model = match value {
1764                    "yes" | "1" => Some(true),
1765                    "no" | "0" => Some(false),
1766                    _ => {
1767                        return Err(err("-Zcycle-accurate-model= takes yes or no"));
1768                    }
1769                };
1770            }
1771            _ if arg.starts_with("-Zswitch=") => {
1772                let shape = &arg["-Zswitch=".len()..];
1773                if rucc_codegen::switch::Force::named(shape).is_none() {
1774                    return Err(err("-Zswitch= takes table, tree or walk"));
1775                }
1776                opts.switch_shape = Some(shape.to_owned());
1777            }
1778            _ if arg.starts_with("-Zlowering=") => {
1779                let file = &arg["-Zlowering=".len()..];
1780                if file.is_empty() {
1781                    return Err(err("-Zlowering= needs a file to write to"));
1782                }
1783                opts.lowering_dump = Some(file.to_owned());
1784            }
1785            _ if arg.starts_with("-Zregister-pressure=") => {
1786                let file = &arg["-Zregister-pressure=".len()..];
1787                if file.is_empty() {
1788                    return Err(err("-Zregister-pressure= needs a file to write to"));
1789                }
1790                opts.register_pressure = Some(file.to_owned());
1791            }
1792            _ if arg.starts_with("-Z") => {
1793                return Err(err(format!(
1794                    "`{arg}` is not an unstable option this compiler has, see \
1795                     spec/04-driver-and-cli.md section 4.11 for the ones it does"
1796                )));
1797            }
1798            // The word size, which is a statement about the target and is taken as one. A build
1799            // that says the size the target already has is saying nothing, and one that says the
1800            // other size is asking for a target this compiler does not have, which it is told
1801            // rather than being given the wrong one.
1802            "-m64" | "-m32" | "-mx32" => {
1803                let want: u32 = match arg {
1804                    "-m64" => 64,
1805                    _ => 32,
1806                };
1807                let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
1808                if have != want {
1809                    return Err(err(format!(
1810                        "{arg} asks for a {want} bit target and {} is {have} bit, use \
1811                         --target= to name the one you mean",
1812                        opts.target
1813                    )));
1814                }
1815            }
1816            // Which processor in the family to generate for. This compiler emits the base
1817            // instruction set of the architecture and nothing above it, so a program built with
1818            // any of these runs on the machine that was named; it is a program that could have
1819            // been faster rather than a program that is wrong, which is what makes these safe to
1820            // take and ignore where a flag that changed the meaning of the code would not be.
1821            _ if arg.starts_with("-march=")
1822                || arg.starts_with("-mtune=")
1823                || arg.starts_with("-mcpu=") => {}
1824            // The calling convention, which is not safe to ignore. Taken when it names the one
1825            // the target already uses and refused otherwise.
1826            _ if arg.starts_with("-mabi=") => {
1827                let want = &arg["-mabi=".len()..];
1828                let have = match opts.target.arch {
1829                    rucc_target::Arch::X86_64 => "sysv",
1830                    rucc_target::Arch::Aarch64 => "lp64",
1831                    rucc_target::Arch::Riscv64 => "lp64d",
1832                };
1833                if want != have {
1834                    return Err(err(format!(
1835                        "{arg}: {} uses the {have} convention and this compiler has no other",
1836                        opts.target
1837                    )));
1838                }
1839            }
1840            // How far apart the pieces of the program may be. The small model is what we emit and
1841            // it is every hosted program's default; the kernel model is a different one and a
1842            // build that asks for it and does not get it links and then does not run.
1843            "-mcmodel=small" => {}
1844            // clang's spellings of the deployment target, which it takes over a version in the
1845            // tuple. gcc on a Mac takes the first. A target that is not Apple ignores it, as
1846            // clang does, so a makefile that always passes it still builds for Linux.
1847            _ if arg.starts_with("-mmacosx-version-min=")
1848                || arg.starts_with("-mmacos-version-min=") =>
1849            {
1850                let text = &arg[arg.find('=').map_or(arg.len(), |i| i + 1)..];
1851                let version = rucc_tuple::Version::parse(text)
1852                    .ok_or_else(|| err(format!("`{text}` in `{arg}` is not a version")))?;
1853                min_version = Some(version);
1854            }
1855            _ if arg.starts_with("-mcmodel=") => {
1856                return Err(err(format!(
1857                    "{arg}: this compiler emits the small code model and no other, see \
1858                     spec/12-targets.md"
1859                )));
1860            }
1861            // GCC's own scripting language for how the driver builds a command line.
1862            // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
1863            // build reaching for it is told which flags do the same job.
1864            _ if arg.starts_with("-specs=") => {
1865                return Err(err(
1866                    "-specs= is not supported: the parts of it builds rely on are -B, -L, \
1867                     -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
1868                     section 4.4",
1869                ));
1870            }
1871            // Arguments meant for a separate assembler or preprocessor, which this compiler does
1872            // not have: both are inside it and neither reads a command line. Refused rather than
1873            // dropped, because every one of these says something about the output and a build
1874            // that asked for `-Wa,--noexecstack` and was silently given an executable stack got
1875            // the opposite of what it asked for.
1876            _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
1877                return Err(err(format!(
1878                    "`{arg}` is an argument for a separate assembler or preprocessor, and both \
1879                     are inside this compiler rather than programs it runs"
1880                )));
1881            }
1882            "-Xassembler" | "-Xpreprocessor" => {
1883                return Err(err(format!(
1884                    "{arg} hands an argument to a separate assembler or preprocessor, and both \
1885                     are inside this compiler rather than programs it runs"
1886                )));
1887            }
1888            // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
1889            // this one as a rule about build systems rather than about warnings: autoconf finds
1890            // out whether a warning flag exists by passing it and looking at the exit status, so
1891            // a compiler that refuses one it has not heard of fails a configure script written
1892            // for a GCC newer than itself. The names are not checked against a list because this
1893            // compiler has no warning groups for a list to be of, which #485 is about.
1894            _ if arg.starts_with("-W") => {}
1895            // Flags that name something this compiler does not do and would not do differently
1896            // if it did. `-fno-ident` is about a comment in the output that we do not write
1897            // either way, and the others are about a way of ordering the compilation that has
1898            // been GCC's only way for twenty years. Section 4.1 asks for the list to be short
1899            // and for adding to it to be deliberate, which is why it is written out here.
1900            "-fno-ident"
1901            | "-fident"
1902            | "-funit-at-a-time"
1903            | "-fno-unit-at-a-time"
1904            | "-shared-libgcc"
1905            | "-static-libgcc" => {}
1906            _ if arg.starts_with('-') && arg.len() > 1 => {
1907                // Silently ignoring an unknown flag is how a build ends up not doing what
1908                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
1909                // for the flags that change code generation, and the safe default until the
1910                // flag table is populated is to reject everything we do not know.
1911                return Err(err(format!("unknown option `{arg}`")));
1912            }
1913            _ => inputs.push(Input { path: arg.to_owned(), forced, role: Role::File }),
1914        }
1915    }
1916
1917    // The fetch, before anything that resolves a compilation, because `--fetch` does not describe
1918    // one. It is here rather than in the loop so that `--offline` can forbid it whichever order the
1919    // two were written in, and it is before the refusals below so that a command line asking for a
1920    // sysroot is not told about a sanitizer.
1921    if let Some(named) = fetch {
1922        if fetch_msvc.is_some() {
1923            return Err(err(
1924                "--fetch and --fetch-msvc-sdk are two different commands and this command line \
1925                 asked for both. --fetch gets a sysroot this release pins by URL and by hash, and \
1926                 --fetch-msvc-sdk gets what is behind Microsoft's licence wall, which no release \
1927                 pins and which nobody may republish. Run whichever one you meant",
1928            ));
1929        }
1930        return fetch_action(&named, offline, &inputs);
1931    }
1932    if let Some(named) = fetch_msvc {
1933        return fetch_msvc_action(&named, offline, accepted, &inputs);
1934    }
1935    if accepted {
1936        return Err(err(
1937            "--accept-licence says that Microsoft's Visual Studio Build Tools licence is accepted, \
1938             and nothing on this command line asked for anything that licence covers. \
1939             --fetch-msvc-sdk <tuple> is the command it belongs to, and an ordinary compile \
1940             downloads nothing with it or without it",
1941        ));
1942    }
1943
1944    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
1945    // order: a directory the user names outranks the compiler's own, and the compiler's own
1946    // outranks the library's. It is pushed after the loop rather than before it because
1947    // `SearchPath` appends within a group and the position is what the order is.
1948    // The same directory the headers were looked for under, because a sysroot is a statement
1949    // about a whole installation and not about half of one.
1950    // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
1951    // command line that turns a check on and off again has asked for nothing. What is left is
1952    // refused rather than dropped, and it is the one place in this parser where the reason is not
1953    // that the output would differ. A sanitizer is a promise that the program is watched while it
1954    // runs, so a build that asks for one and is quietly given a program with no checks in it does
1955    // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
1956    // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
1957    // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
1958    // options.
1959    if let Some(first) = sanitizers.first() {
1960        return Err(err(format!(
1961            "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
1962             asked for one and got none would run its tests unchecked, see \
1963             spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
1964             compiler does have"
1965        )));
1966    }
1967    // The fast math family, replayed in order on top of what `-Ofast` implies. The startup file is
1968    // gcc's spec rather than the fields: it is linked when `-Ofast`, `-ffast-math` or
1969    // `-funsafe-math-optimizations` is still in force at the end of the line, whatever a later
1970    // member took back, and `-mdaz-ftz` decides it outright.
1971    let mut math = Math::default();
1972    let mut trapping = if ofast { math.set_fast(true) } else { true };
1973    for flag in &math_flags {
1974        match *flag {
1975            "-ftrapping-math" => trapping = true,
1976            "-fno-trapping-math" => trapping = false,
1977            "-ffast-math" => trapping = math.set_fast(true),
1978            "-fno-fast-math" => trapping = math.set_fast(false),
1979            "-funsafe-math-optimizations" => trapping = math.set_unsafe(true),
1980            "-fno-unsafe-math-optimizations" => trapping = math.set_unsafe(false),
1981            "-fmath-errno" => math.errno = true,
1982            "-fno-math-errno" => math.errno = false,
1983            "-ffinite-math-only" => math.finite_only = true,
1984            "-fno-finite-math-only" => math.finite_only = false,
1985            "-fsigned-zeros" => math.signed_zeros = true,
1986            "-fno-signed-zeros" => math.signed_zeros = false,
1987            "-freciprocal-math" => math.reciprocal = true,
1988            "-fno-reciprocal-math" => math.reciprocal = false,
1989            "-fassociative-math" => math.associative = true,
1990            "-fno-associative-math" => math.associative = false,
1991            _ => unreachable!("{flag} is not in the family"),
1992        }
1993    }
1994    opts.trapping_math = trapping;
1995    opts.math = math;
1996    let last = |on: &str, off: &str| {
1997        math_flags.iter().rev().find(|f| **f == on || **f == off).is_some_and(|f| *f == on)
1998    };
1999    link.fast_math = ofast
2000        || last("-ffast-math", "-fno-fast-math")
2001        || last("-funsafe-math-optimizations", "-fno-unsafe-math-optimizations");
2002    link.daz_ftz = daz_ftz;
2003    link.sysroot = sysroot.clone();
2004    // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
2005    // inside the link line, because a link line that read the environment could only be tested on a
2006    // machine whose environment said the right thing, and the link line is the last thing that
2007    // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
2008    link.cache = Some(cache::dir());
2009    // And where a distribution's cross packages would have put a tree for the target, which is only
2010    // read when the target is not this machine and there is no sysroot of ours for it.
2011    link.usr = Some(PathBuf::from("/usr"));
2012    // And the ten field spelling of the target, because the release on it decides two things the
2013    // three field one cannot say: whether a target that is this architecture is still a cross
2014    // compile, and which directory under the cache it is against. After the loop because the last
2015    // `--target=` on the command line is the one that counts.
2016    link.pinned = pinned;
2017    // The deployment target, from the flag if there was one and from the tuple otherwise. Only an
2018    // Apple platform has one: anywhere else a version on the tuple is a libc or a preview number.
2019    if opts.target.os == rucc_target::Os::Darwin {
2020        opts.os_version = min_version.or_else(|| pinned.and_then(TargetTuple::os_version));
2021    }
2022    // After the loop rather than where `-pthread` was read, so that it lands after the objects
2023    // that refer to it. A static link takes the definitions it needs from a library when it
2024    // reaches it and not afterwards, so a library before the objects is a library that answers
2025    // nothing.
2026    if threads {
2027        inputs.push(Input::library("pthread"));
2028    }
2029    if let Some(query) = query {
2030        return Ok(Action::Print(answer(&query, &opts, &link)?));
2031    }
2032    // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
2033    // else the command line asked for. Read here rather than where the flag was, because a `-c`
2034    // written after it has to lose and the loop cannot know that until it has ended. The output
2035    // file is where the rule goes rather than where an object would have gone, and the last
2036    // phase being the preprocessor is what makes that true without a second rule for it.
2037    if opts.deps.instead_of_compiling {
2038        opts.emit = EmitKind::Preprocessed;
2039    }
2040    if !nostdinc {
2041        opts.search.push_system(runtime::DIR);
2042        // And the library's after ours, which is the other half of the same order. They go on
2043        // here rather than at the point `--target=` or `--sysroot=` was read because either
2044        // one changes the answer and the last word on both is the end of the loop.
2045        //
2046        // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
2047        // that the headers and the libraries come from the same place. A target that is this
2048        // machine reads this machine's headers, and a target that is not reads the ones in the
2049        // sysroot for it rather than the ones next door.
2050        let cross = link::cross_sysroot(opts.target, &link);
2051        let kernel = link::cross_kernel(opts.target, &link);
2052        let distro = link::distro_cross(opts.target, &link);
2053        // And the version of those headers, which only the bundled tree has an answer for. A host
2054        // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
2055        // and a second definition with a different value is a warning on every file, so the
2056        // condition is the same one that chose the directories.
2057        if cross.is_some() {
2058            let target = pinned.unwrap_or_else(|| opts.target.tuple());
2059            opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
2060                err(format!(
2061                    "{skew}; pin a release the tree has, or name a tree that has that one \
2062                     with --sysroot"
2063                ))
2064            })?;
2065        }
2066        let system = library::header_dirs(
2067            opts.target,
2068            sysroot.as_deref(),
2069            cross.as_ref(),
2070            kernel.as_ref(),
2071            distro.as_ref(),
2072        );
2073        // The two licence walls of `spec/cross-compile/13-distribution.md` section 13.4, which are
2074        // the only way step 3 comes back with nothing on a hosted target. Section 8.6 asks for the
2075        // answer to name the licence and the lawful ways to get what is behind it, rather than
2076        // leaving a person with an `#include` that failed as though a directory had gone missing.
2077        //
2078        // It is left on the search path instead of refused here, because a program that includes
2079        // none of the library needs none of the SDK and section 8.6 is explicit that targeting the
2080        // platform has to keep working. So the reason waits until an include has actually failed,
2081        // which is the only moment it helps and the only moment it is true.
2082        //
2083        // The condition is that step 3 found nothing at all, so an `SDKROOT`, an `INCLUDE` or a mac
2084        // with Xcode on it all pass through untouched, and `-nostdinc` never reaches this block. A
2085        // `--sysroot` or `-isysroot` passes through as well, even when the tree it names turns out to
2086        // be empty or absent: somebody who wrote a path has already answered the question this
2087        // message asks, and answering it again over the top of a mistyped directory would hide the
2088        // mistake behind a licence notice.
2089        if system.is_empty() && sysroot.is_none() {
2090            let tuple = pinned.unwrap_or_else(|| opts.target.tuple());
2091            if let Some(wall) = rucc_sysroot::Wall::of(tuple) {
2092                opts.search.explain_missing_system(wall.no_headers(&tuple.to_canonical_string()));
2093            }
2094        }
2095        // And whether the tree somebody named is the release they asked for, which is the one
2096        // question left once the directories are settled and the only place both halves of it are
2097        // known. Only for a named tree, because that is the case where the release in the target
2098        // stops deciding anything, and `crate::glibc` is where the rest of the reasoning is.
2099        if sysroot.is_some() {
2100            notes.extend(glibc::skew(opts.target, pinned, &system));
2101        }
2102        for dir in system {
2103            opts.search.push_system(dir);
2104        }
2105    }
2106    // Once, here, rather than as each directory is pushed. A `-I` that names a system
2107    // directory has to lose to the system entry and the system entry is added last, so the
2108    // question cannot be answered until the whole path is known.
2109    opts.search.remove_duplicates();
2110
2111    // The target has to be resolved before the configuration is printed, so this check comes
2112    // after the loop rather than at the point `--print-config` was seen.
2113    if print_config {
2114        return Ok(Action::PrintConfig(Box::new(opts)));
2115    }
2116    if print_pipeline {
2117        return Ok(Action::PrintPipeline(Box::new(opts)));
2118    }
2119    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
2120    if print_plan {
2121        return Ok(Action::PrintPlan {
2122            opts: Box::new(opts),
2123            plan: Box::new(plan),
2124            link: Box::new(link),
2125        });
2126    }
2127    Ok(Action::Compile {
2128        opts: Box::new(opts),
2129        plan: Box::new(plan),
2130        link: Box::new(link),
2131        jobs,
2132        verbose,
2133        notes,
2134    })
2135}
2136
2137/// What `--fetch <tuple>` asked for, or why it is not a thing that can be done.
2138///
2139/// The lookup happens here rather than at the point the bytes would move, so that a target this
2140/// release pins nothing for is a refusal from the parser and the only code that runs a downloader is
2141/// code that already knows what it is getting.
2142///
2143/// # Errors
2144///
2145/// [`CliError`] when `--offline` forbade it, when there are input files as well, when the tuple is
2146/// not a target this compiler knows, when its sysroot is behind one of section 13.4's licence walls,
2147/// and when this release pins no artifact for it.
2148fn fetch_action(named: &str, offline: bool, inputs: &[Input]) -> Result<Action, CliError> {
2149    // Not a precedence question. Section 13.2 says `--offline` forbids a fetch entirely, so a
2150    // command line that writes both has asked for two opposite things and the answer is to say so
2151    // rather than to pick one of them.
2152    if offline {
2153        return Err(err(
2154            "--fetch asks for a download and --offline forbids every download, so this command \
2155             line asks for two opposite things. Drop one of them: --offline is how a build says it \
2156             will not reach the network, and --fetch is one of the two things in this compiler \
2157             that reaches it",
2158        ));
2159    }
2160    if let Some(first) = inputs.first() {
2161        return Err(err(format!(
2162            "--fetch gets a sysroot and compiles nothing, so `{}` on the same command line is an \
2163             input that nothing would read",
2164            first.path
2165        )));
2166    }
2167    let target: TargetTuple = named
2168        .parse()
2169        .map_err(|why| err(format!("--fetch {named}: {why}, so there is no sysroot to get")))?;
2170    // The canonical spelling, because that is what a row is named by and what the directory under
2171    // the cache is called, and a person is free to write a tuple the long way round.
2172    let tuple = target.to_canonical_string();
2173    // Before the table is consulted, because a target behind a licence wall is not a row that has not
2174    // been written yet. Section 13.4 is that no release pins one of these ever, so the message says
2175    // the licence and the two lawful ways rather than naming the producer that will publish the rest.
2176    if let Some(wall) = rucc_sysroot::Wall::of(target) {
2177        return Err(err(format!("--fetch {tuple}: {}", wall.no_fetch(&tuple))));
2178    }
2179    let Some(what) = rucc_sysroot::pinned_for_target(target) else {
2180        return Err(err(unpinned(&tuple)));
2181    };
2182    Ok(Action::Fetch { what, target, cache: cache::dir() })
2183}
2184
2185/// What `--fetch-msvc-sdk <tuple>` asks for, weighed the same way the fetch above is.
2186///
2187/// The target is resolved here rather than where the work happens, so that a tuple this compiler
2188/// does not know and a target that is not behind Microsoft's wall are refusals from the parser like
2189/// every other thing a command line can ask for and not have. Whether the licence was accepted is
2190/// carried rather than acted on, because what it changes is what the command does and not whether
2191/// the command line made sense.
2192///
2193/// # Errors
2194///
2195/// [`CliError`] when `--offline` forbade it, when there are input files as well, and when the tuple
2196/// is not a target this compiler knows.
2197fn fetch_msvc_action(
2198    named: &str,
2199    offline: bool,
2200    accepted: bool,
2201    inputs: &[Input],
2202) -> Result<Action, CliError> {
2203    if offline {
2204        return Err(err(
2205            "--fetch-msvc-sdk asks for a download and --offline forbids every download, so this \
2206             command line asks for two opposite things. Drop one of them: --offline is how a build \
2207             says it will not reach the network",
2208        ));
2209    }
2210    if let Some(first) = inputs.first() {
2211        return Err(err(format!(
2212            "--fetch-msvc-sdk gets an SDK and compiles nothing, so `{}` on the same command line \
2213             is an input that nothing would read",
2214            first.path
2215        )));
2216    }
2217    let target: TargetTuple = named.parse().map_err(|why| {
2218        err(format!("--fetch-msvc-sdk {named}: {why}, so there is no SDK to get"))
2219    })?;
2220    Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir() })
2221}
2222
2223/// Why there is nothing to fetch for a target, which is a different sentence when the table is
2224/// empty.
2225///
2226/// A release that pins nothing and a release that pins eleven targets and not this one are two
2227/// situations, and a message that did not tell them apart would send somebody looking for a typo in
2228/// their tuple when the answer is that this work is not finished.
2229fn unpinned(tuple: &str) -> String {
2230    let pinned = rucc_sysroot::pinned_targets();
2231    if pinned.is_empty() {
2232        return format!(
2233            "this release pins no sysroot for {tuple}, and it pins none for any target yet. A \
2234             sysroot is built and published by the producer in tamnd/rucc-cross, per \
2235             spec/cross-compile/13-distribution.md section 13.8, and a release of this compiler \
2236             names one by URL and by hash afterwards. Until then, pass --sysroot=<dir> to compile \
2237             against a tree you have already"
2238        );
2239    }
2240    format!(
2241        "this release pins no sysroot for {tuple}. What it pins is {}. Pass --sysroot=<dir> to \
2242         compile against a tree you have already",
2243        pinned.join(", ")
2244    )
2245}
2246
2247/// Gets the artifact and installs it, saying what each step did.
2248///
2249/// The steps are section 13.8's and so are the messages: the transport is somebody else's program
2250/// and the check is ours, so a person reading this wants to know which downloader ran, that the
2251/// bytes matched, how many files the record named and where the tree ended up. A fetch of something
2252/// that is already there says that instead and moves nothing.
2253///
2254/// A Linux target is two artifacts, its own sysroot and the kernel header tree every Linux target
2255/// shares, and `kernel` is the second one when the target reads it. It is fetched after the sysroot
2256/// and by the same two steps, so a machine that has fetched one Linux target already has it and a
2257/// second target's fetch says so and moves nothing.
2258fn fetch_sysroot(
2259    what: &rucc_sysroot::Pinned,
2260    kernel: Option<&rucc_sysroot::Pinned>,
2261    target: TargetTuple,
2262    cache: &std::path::Path,
2263) -> i32 {
2264    let tuple = target.to_canonical_string();
2265    let say = |line: &str| println!("rucc: {tuple}: {line}");
2266    if let Err(why) = bring(what, cache, &say) {
2267        return complain(why);
2268    }
2269    let archive = what.archive_in(cache);
2270    match install::install(&archive, what.sha256, target, cache) {
2271        Ok(done) => report(&done, "sysroot", &say),
2272        Err(why) => return complain(why),
2273    }
2274    let Some(kernel) = kernel else { return 0 };
2275    if let Err(why) = bring(kernel, cache, &say) {
2276        return complain(why);
2277    }
2278    match install::install_kernel(&kernel.archive_in(cache), kernel.sha256, cache) {
2279        Ok(done) => {
2280            report(&done, "kernel header tree", &say);
2281            0
2282        }
2283        Err(why) => complain(why),
2284    }
2285}
2286
2287/// The download half of a fetch, for one artifact.
2288fn bring(
2289    what: &rucc_sysroot::Pinned,
2290    cache: &std::path::Path,
2291    say: &impl Fn(&str),
2292) -> Result<(), CliError> {
2293    let archive = what.archive_in(cache);
2294    match fetch::fetch(what.url, what.sha256, &archive)? {
2295        fetch::Fetched::AlreadyThere => {
2296            say(&format!("{} is already here and matches the hash", archive.display()));
2297        }
2298        fetch::Fetched::Downloaded(by) => {
2299            say(&format!("downloaded {} with {}", what.url, by.program()));
2300        }
2301    }
2302    Ok(())
2303}
2304
2305/// What an install did, in the words a person reading a fetch wants.
2306fn report(done: &install::Installed, what: &str, say: &impl Fn(&str)) {
2307    match &done.before {
2308        install::Before::Nothing => {
2309            say(&format!("{} files installed at {}", done.files, done.root.display()));
2310        }
2311        install::Before::TheSame => {
2312            say(&format!(
2313                "the same {what} is already at {}, so nothing moved",
2314                done.root.display()
2315            ));
2316        }
2317        install::Before::Different(was) => {
2318            say(&format!(
2319                "{} files installed at {}, over a tree whose record digested to {was}",
2320                done.files,
2321                done.root.display()
2322            ));
2323        }
2324    }
2325    say(&format!("the {what}'s record digests to {}", done.digest));
2326}
2327
2328/// What one of the `-dump` and `-print` flags prints.
2329///
2330/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
2331/// which is what makes the answer safe to paste into a link line whether or not the file is
2332/// there, and this does the same.
2333fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
2334    let found = |name: &str| {
2335        link::find_in_search(link, opts.target, name)
2336            .map_or_else(|| name.to_owned(), |path| path.display().to_string())
2337    };
2338    Ok(match query {
2339        Query::Machine => opts.target.to_string(),
2340        Query::Version => VERSION.to_owned(),
2341        Query::Multiarch => link::multiarch(opts.target),
2342        // The three lines GCC prints, in its order and with its punctuation, because what reads
2343        // them is a script written against that shape. There is no installation directory to
2344        // report: this compiler is one binary that works wherever it is copied, and the headers
2345        // it ships are inside it, so `install` is where the binary is and nothing is under it.
2346        Query::SearchDirs => {
2347            let here = std::env::current_exe()
2348                .ok()
2349                .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
2350                .unwrap_or_default();
2351            let list = |dirs: &[PathBuf]| {
2352                dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
2353            };
2354            let libraries = link::search_dirs(link, opts.target);
2355            format!(
2356                "install: {}\nprograms: ={}\nlibraries: ={}",
2357                here.display(),
2358                list(&link.prefixes),
2359                list(&libraries)
2360            )
2361        }
2362        // The root the rest of the answers are under, which a build system asks for when it wants
2363        // to find a file itself rather than ask for one by name, and which is the first thing to
2364        // look at when a cross build read a header nobody expected. A native compile has no
2365        // sysroot and the answer is the empty line, which is what GCC prints when it was
2366        // configured without one. `--sysroot` wins over ours because it wins everywhere else.
2367        Query::Sysroot => {
2368            sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
2369        }
2370        // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
2371        // compiler's own code, what it is, where it was got, its hash, its licence and whether it
2372        // was bundled, generated or fetched. What is printed is the manifest the sysroot already
2373        // carries rather than a second format saying the same things, because the three uses 13.5
2374        // gives for this are a licence notice, a reproducibility check and a security audit, and all
2375        // three are somebody else parsing it. One format is one parser to write.
2376        // Read and rendered rather than copied out, so that what comes back is the format this
2377        // build understands. The last newline comes off because whatever prints an answer adds
2378        // one, the way it does for every other query here. Keeping it would put a blank line at
2379        // the end of the one answer that is a file somebody diffs against the file it came from.
2380        Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
2381            Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
2382            None => String::new(),
2383        },
2384        // Section 13.2 of the same document, which asks for the hash of a cache directory's
2385        // contents in the directory's name. A name cannot carry one, because the path has to be
2386        // computable before anything has been read, by the producer about to write the files and by
2387        // the compiler about to read them, and neither has the contents when it asks. So the number
2388        // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
2389        // which means `sha256sum` over the manifest answers the same thing.
2390        Query::SysrootDigest => match sysroot_manifest(opts, link)? {
2391            Some(manifest) => manifest.digest(),
2392            None => String::new(),
2393        },
2394        Query::FileName(name) => found(name),
2395        // The name GCC gives the library of routines a compiler's output calls that the C
2396        // library does not have. Ours is built in and there is no file, so the answer is the
2397        // name itself, which is what GCC prints when it cannot find one either.
2398        Query::Libgcc => found("libgcc.a"),
2399        // A program rather than a library: the linker and the archiver are the ones a build asks
2400        // about, and this compiler finds them on the path or under `-B` rather than shipping
2401        // them, so the name back is the honest answer unless a `-B` prefix holds one.
2402        Query::ProgName(name) => link
2403            .prefixes
2404            .iter()
2405            .map(|dir| dir.join(name))
2406            .find(|path| path.is_file())
2407            .map_or_else(|| name.clone(), |path| path.display().to_string()),
2408    })
2409}
2410
2411/// The root every sysroot answer is about.
2412///
2413/// One function rather than a copy in each, because the other flags exist to say what is inside the
2414/// tree this one names, and two answers that disagreed about which tree that is would be a
2415/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
2416/// else.
2417fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
2418    link.sysroot
2419        .clone()
2420        .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
2421}
2422
2423/// The record of the sysroot this command line reads, when there is one to read.
2424///
2425/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
2426/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
2427/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
2428/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
2429/// inputs in it because that one still has its header lines.
2430///
2431/// # Errors
2432///
2433/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
2434/// record we could not read on to whoever asked would make their parser the one that finds the
2435/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
2436/// output.
2437fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
2438    let Some(root) = sysroot_root(opts, link) else {
2439        return Ok(None);
2440    };
2441    let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
2442    match std::fs::read_to_string(&path) {
2443        Ok(text) => Manifest::parse(&text)
2444            .map(Some)
2445            .map_err(|why| err(format!("{}: {why}", path.display()))),
2446        Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
2447        Err(why) => Err(err(format!("{}: {why}", path.display()))),
2448    }
2449}
2450
2451/// Renders the passes this level will run, in order, with what each one does.
2452///
2453/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
2454/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
2455/// emerges from which flags happen to be set, and this is how that list is read.
2456#[must_use]
2457pub fn print_pipeline(opts: &Options) -> String {
2458    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
2459    settings.toggles.clone_from(&opts.passes);
2460    settings.global_fuel = opts.pass_fuel_global;
2461    for (on, spec) in &opts.pass_gates {
2462        // Every spelling was checked while the arguments were parsed, so there is nothing here
2463        // this can refuse, and a listing is not the place to report it if there were.
2464        let _ = settings.gates.add(*on, spec);
2465    }
2466    rucc_opt::pipeline::print(&settings)
2467}
2468
2469/// Renders the resolved configuration.
2470///
2471/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
2472/// this output is diffed across hosts in CI and a reordering would read as a change.
2473#[must_use]
2474pub fn print_config(opts: &Options) -> String {
2475    let sess = Session::new(opts.clone());
2476    let t = &sess.target;
2477    let mut out = String::new();
2478    let _ = writeln!(out, "version: {VERSION}");
2479    // The three field triple the driver was given rather than the ten field tuple it widens to,
2480    // because this output is what a build system reads to find out what it asked for. The tuple is
2481    // the compiler's model of the machine and this line is a receipt for a command line.
2482    let _ = writeln!(out, "target: {}", opts.target);
2483    let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
2484    let _ = writeln!(out, "os: {}", opts.target.os.as_str());
2485    let _ = writeln!(out, "env: {}", opts.target.env.as_str());
2486    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
2487    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
2488    let _ = writeln!(out, "long-width: {}", t.long_width);
2489    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
2490    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
2491    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
2492    let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
2493    // The register file as a count per class, which is enough to tell a target whose registers
2494    // are described from one whose are not without printing sixteen names nobody asked for.
2495    let regs: Vec<String> = t
2496        .regs
2497        .classes()
2498        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
2499        .collect();
2500    let _ = writeln!(
2501        out,
2502        "registers: {}",
2503        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
2504    );
2505    // What the schedule was chosen with, which is a sentence rather than a name on purpose: two
2506    // runs of a benchmark that disagree are usually two models and not two compilers.
2507    let _ = writeln!(out, "timing-model: {}", t.timing.map_or("none", |timing| timing.model));
2508    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
2509    let _ = writeln!(out, "safety: {}", sess.opts.safety);
2510    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
2511    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
2512    let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
2513    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
2514    let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
2515    let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
2516    let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
2517    let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
2518    let _ = writeln!(out, "profile: {}", sess.opts.profile);
2519    let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
2520    // Last because it is the one key with more than one line under it, and the only one
2521    // whose value is a property of the machine rather than of the command line.
2522    for dir in sess.opts.search.dirs() {
2523        let system = if dir.is_system { " (system)" } else { "" };
2524        let _ = writeln!(out, "include: {}{system}", dir.path.display());
2525    }
2526    out
2527}
2528
2529/// The output name the make target is taken from, which is the `-o` argument or nothing.
2530///
2531/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
2532/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
2533/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
2534/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
2535/// `-S` on the argument does name what the rule builds, and it is used as written.
2536fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
2537    if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
2538}
2539
2540/// Writes to a path the command line named rather than one the plan derived, where `-` is
2541/// standard output.
2542fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
2543    if path == "-" {
2544        return write_out(&Output::Stdout, bytes);
2545    }
2546    write_out(&Output::File(path.to_owned()), bytes)
2547}
2548
2549/// Writes the make rule for one input, and reports whether it got there.
2550///
2551/// A rule with no file of its own goes where the compilation it replaced would have written,
2552/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
2553/// `$@`, and the same line with the `-o` left off puts it on standard output.
2554fn write_deps(
2555    opts: &Options,
2556    plan: &Plan,
2557    job: &Job,
2558    found: &[Dependency],
2559    stderr: &mut impl std::io::Write,
2560) -> bool {
2561    let targets = if opts.deps.targets.is_empty() {
2562        vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
2563    } else {
2564        opts.deps.targets.clone()
2565    };
2566    let rule = deps::rule(&opts.deps, &targets, &job.input, found);
2567    // The file, on the other hand, is named after the `-o` in every mode that still has one to
2568    // spend, which is every mode except the two that spend it on the rule.
2569    let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
2570        // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
2571        // named empty rather than absent, because a makefile that named it as a target of its
2572        // own is a makefile that will look for it.
2573        Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
2574            if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
2575        }),
2576        None => write_out(&job.output, rule.as_bytes()),
2577    };
2578    if let Err(e) = wrote {
2579        let _ = writeln!(stderr, "rucc: error: {e}");
2580        return false;
2581    }
2582    true
2583}
2584
2585/// Runs phase 4 over every input that has one, and writes what came out.
2586///
2587/// One input that fails does not stop the others. A build that reports every file it could
2588/// not preprocess in one run is worth more than one that stops at the first, and the exit
2589/// status is still a failure either way.
2590fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
2591    let fs = OsFileSystem::new();
2592    let mut stderr = std::io::stderr().lock();
2593    let mut failed = false;
2594    for job in &plan.jobs {
2595        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
2596            // An input that is already preprocessed, or an object file. GCC passes these
2597            // through untouched, and the plan has already said so in its notes.
2598            continue;
2599        }
2600        let started = std::time::Instant::now();
2601        let result = preprocess(opts, &job.input, &fs);
2602        if opts.time {
2603            say_time(&job.input, started.elapsed(), &mut stderr);
2604        }
2605        for message in &result.messages {
2606            let _ = writeln!(stderr, "{message}");
2607        }
2608        if result.failed() {
2609            failed = true;
2610            continue;
2611        }
2612        if opts.deps.emit {
2613            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2614            // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
2615            // to write. The other two asked for both and fall through to the text below.
2616            if opts.deps.instead_of_compiling {
2617                continue;
2618            }
2619        }
2620        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
2621            let _ = writeln!(stderr, "rucc: error: {e}");
2622            failed = true;
2623        }
2624    }
2625    i32::from(failed)
2626}
2627
2628/// Whether this job is a file of assembly that has to be assembled and that nothing here assembles.
2629///
2630/// The phases rather than the kind, because there are two kinds of assembly input and one of them
2631/// is preprocessed first, and because an object file also has no compile phase and is not this: it
2632/// has no phases at all and goes to the linker as it is. A `.s` on a `-c` line has exactly
2633/// [`Phase::Assemble`] left, and a `.S` has the preprocessor in front of it, and neither has
2634/// anything the front end can do.
2635fn needs_an_assembler(job: &Job) -> bool {
2636    job.phases.contains(&Phase::Assemble) && !job.phases.contains(&Phase::Compile)
2637}
2638
2639/// Whether the preprocessor runs over it on the way in, which is the whole difference between the
2640/// two kinds of assembly input.
2641fn assembly_wants_cpp(job: &Job) -> bool {
2642    job.phases.contains(&Phase::Preprocess)
2643}
2644
2645/// Runs the front end over every input that has a compile phase, and writes what came out.
2646///
2647/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
2648/// exit status is a failure either way. An input that is already assembly or an object has no
2649/// compile phase and is passed over here, which the plan has already said in its notes.
2650fn compile_all(opts: &Options, plan: &Plan) -> i32 {
2651    let fs = OsFileSystem::new();
2652    let mut stderr = std::io::stderr().lock();
2653    let mut failed = false;
2654    let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2655    failed |= !ok;
2656    let mut fired = Fired::new();
2657    let mut pressure = Pressure::new();
2658    let mut lowerings = Lowerings::new();
2659    for job in &plan.jobs {
2660        if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
2661            continue;
2662        }
2663        // An input of IR is read back rather than compiled, since the C it came from is not
2664        // here any more. A file of assembly does not go through the front end at all and is
2665        // read by the assembler instead. Everything after this is the same for all three, so
2666        // the paths meet again at the messages and the file the result is written to.
2667        let started = std::time::Instant::now();
2668        let result = if needs_an_assembler(job) {
2669            assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
2670        } else if job.kind == InputKind::Ir {
2671            compile_ir(opts, &job.input, &fs)
2672        } else {
2673            compile(opts, &job.input, &fs)
2674        };
2675        if opts.time {
2676            say_time(&job.input, started.elapsed(), &mut stderr);
2677        }
2678        fired.merge(&result.fired);
2679        pressure.merge(&result.pressure);
2680        lowerings.merge(&result.lowerings);
2681        failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
2682        failed |= !remarks.write(&result.remarks, &mut stderr);
2683        for message in &result.messages {
2684            let _ = writeln!(stderr, "{message}");
2685        }
2686        // Before the failure below, because a compilation that stopped in the back end is exactly
2687        // the one whose preprocessed source somebody wants to look at.
2688        failed |= !write_temps(job, &result.temps, &mut stderr);
2689        if result.failed() {
2690            failed = true;
2691            continue;
2692        }
2693        // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
2694        // this is the one path where both files come out of the same run. An input of IR has no
2695        // dependencies to report and produces an empty list, which produces a rule naming only
2696        // itself, and that is the honest answer rather than a missing file.
2697        if opts.deps.emit {
2698            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2699        }
2700        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
2701            let _ = writeln!(stderr, "rucc: error: {e}");
2702            failed = true;
2703        }
2704    }
2705    failed |= !write_coverage(opts, &fired, &mut stderr);
2706    failed |= !write_pressure(opts, &pressure, &mut stderr);
2707    failed |= !write_lowering(opts, &lowerings, &mut stderr);
2708    i32::from(failed)
2709}
2710
2711/// A directory for the object files only the link step ever sees, removed when it goes away.
2712///
2713/// `-c` writes its object where the user can see it and linking does not, which is the whole of
2714/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
2715/// every other compiler. Removing them on drop rather than at the end of a function is so that a
2716/// link that failed leaves nothing behind either.
2717struct Scratch {
2718    /// Where the objects go.
2719    dir: PathBuf,
2720}
2721
2722impl Scratch {
2723    /// Makes one, under whatever the platform calls its temporary directory.
2724    ///
2725    /// The name carries the process id so that two compilers running at once do not share a
2726    /// directory, which they would otherwise do the moment two of them compiled a file of the
2727    /// same name.
2728    fn new() -> Result<Scratch, String> {
2729        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
2730        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
2731        Ok(Scratch { dir })
2732    }
2733}
2734
2735impl Drop for Scratch {
2736    fn drop(&mut self) {
2737        let _ = std::fs::remove_dir_all(&self.dir);
2738    }
2739}
2740
2741/// The link line the plan describes, for `-###`.
2742///
2743/// The names in it are the hints the plan carries rather than the temporaries a real compilation
2744/// would choose, because `-###` prints the line without having compiled anything and so has
2745/// nothing to point at. That also makes the printed line readable rather than naming a directory
2746/// that only exists while a compilation is running.
2747fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
2748    let linker = link::find(opts.target, link)?;
2749    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
2750    Ok(link::render(&linker, &args))
2751}
2752
2753/// Compiles everything, then links it.
2754///
2755/// The objects go in a directory that is removed afterwards, which is why this is not
2756/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
2757/// and does not say where, because where is a question that only has an answer once something is
2758/// running.
2759fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
2760    let Some(job) = &plan.link else {
2761        // Every path into here comes from a plan whose last phase is the link, and such a plan
2762        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
2763        let mut stderr = std::io::stderr().lock();
2764        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
2765        return 1;
2766    };
2767    // Before anything is compiled, because a linker that is not on the machine is worth knowing
2768    // about in the second it takes to look rather than after the compilation.
2769    // And before that, whether this link has a line at all and whether what it reads is on the
2770    // machine. Both are answerable now, and a target whose sysroot has not been built is worth
2771    // saying so about before the compilation rather than after it.
2772    if let Err(why) = link::preflight(opts.target, link) {
2773        return complain(why);
2774    }
2775    let linker = match link::find(opts.target, link) {
2776        Ok(linker) => linker,
2777        Err(why) => return complain(why),
2778    };
2779    // And whether the one that was found can do this link, which for one linker and one target is
2780    // a question only the linker itself can answer. Here rather than inside the search, because
2781    // what it does is refuse rather than move on to the next candidate: nothing else in the list
2782    // links a produced Windows sysroot either.
2783    if let Err(why) = link::suitable(opts.target, &linker) {
2784        return complain(why);
2785    }
2786    // The glibc stubs, which are the one part of a cross sysroot written here rather than fetched.
2787    // Before compiling for the same reason as the rest, and never for `-###`, which writes nothing.
2788    if let Err(why) = link::write_stubs(opts.target, link) {
2789        return complain(why);
2790    }
2791
2792    let scratch = match Scratch::new() {
2793        Ok(scratch) => scratch,
2794        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
2795    };
2796
2797    let fs = OsFileSystem::new();
2798    let mut failed = false;
2799    // One per job, in job order, which is what lets the link line below be rebuilt with the real
2800    // paths in it: every job contributes exactly one file to the line and does so in this order.
2801    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
2802    let mut fired = Fired::new();
2803    let mut pressure = Pressure::new();
2804    let mut lowerings = Lowerings::new();
2805    {
2806        let mut stderr = std::io::stderr().lock();
2807        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2808        failed |= !ok;
2809        for (at, job) in plan.jobs.iter().enumerate() {
2810            let out = match &job.output {
2811                Output::Temporary(hint) => {
2812                    // The index because two inputs in different directories can have the same
2813                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
2814                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
2815                }
2816                Output::File(path) => path.clone(),
2817                // A job feeding the linker never writes to standard output, since the plan gives
2818                // it a temporary. This is here so that the match is total rather than a panic.
2819                Output::Stdout => continue,
2820            };
2821            produced.push(out.clone());
2822            if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
2823                continue;
2824            }
2825            let started = std::time::Instant::now();
2826            let result = if needs_an_assembler(job) {
2827                assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
2828            } else if job.kind == InputKind::Ir {
2829                compile_ir(opts, &job.input, &fs)
2830            } else {
2831                compile(opts, &job.input, &fs)
2832            };
2833            if opts.time {
2834                say_time(&job.input, started.elapsed(), &mut stderr);
2835            }
2836            fired.merge(&result.fired);
2837            pressure.merge(&result.pressure);
2838            lowerings.merge(&result.lowerings);
2839            failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
2840            failed |= !remarks.write(&result.remarks, &mut stderr);
2841            for message in &result.messages {
2842                let _ = writeln!(stderr, "{message}");
2843            }
2844            failed |= !write_temps(job, &result.temps, &mut stderr);
2845            if result.failed() {
2846                failed = true;
2847                continue;
2848            }
2849            // A `-MD` on a command line that links writes the rule next to the executable and
2850            // names the executable as its target, since that is the file this source builds
2851            // here. The object it went through is in a temporary directory and is gone by the
2852            // time `make` reads any of this.
2853            if opts.deps.emit {
2854                failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2855            }
2856            if !matches!(result.artifact, Artifact::Object { .. }) {
2857                // Worth saying rather than writing whatever it is and letting the linker read it.
2858                // An empty file is a valid empty linker script, so a link handed one gets as far
2859                // as reporting every symbol of this file undefined, which is a page of messages
2860                // about something that went wrong here.
2861                let _ = writeln!(
2862                    stderr,
2863                    "rucc: internal error: {}: no object file was produced for the link",
2864                    job.input
2865                );
2866                failed = true;
2867                continue;
2868            }
2869            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
2870                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
2871                failed = true;
2872            }
2873        }
2874        failed |= !write_coverage(opts, &fired, &mut stderr);
2875        failed |= !write_pressure(opts, &pressure, &mut stderr);
2876        failed |= !write_lowering(opts, &lowerings, &mut stderr);
2877        failed |= !write_lowering(opts, &lowerings, &mut stderr);
2878    }
2879    if failed {
2880        // Nothing is linked from a compilation that did not finish. A linker run over the objects
2881        // that did compile would report every function of the file that did not as undefined,
2882        // which is a page of messages about a mistake already reported once.
2883        return 1;
2884    }
2885
2886    // The items in command line order with the temporaries filled in. A library and a word for the
2887    // linker contribute no job and pass through, and every file item takes the next job's real
2888    // output, which is what keeps whatever was written between two objects between them here.
2889    let mut outputs = produced.into_iter();
2890    let mut items = Vec::with_capacity(job.inputs.len());
2891    for item in &job.inputs {
2892        match item {
2893            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
2894            link::Item::Linker(arg) => items.push(link::Item::Linker(arg.clone())),
2895            link::Item::File(_) => match outputs.next() {
2896                Some(path) => items.push(link::Item::File(path)),
2897                None => return complain("the plan asks the linker for a file nothing produced"),
2898            },
2899        }
2900    }
2901
2902    let args = match link::line(opts.target, link, &items, &job.output) {
2903        Ok(args) => args,
2904        Err(why) => return complain(why),
2905    };
2906    if verbose {
2907        let mut stderr = std::io::stderr().lock();
2908        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
2909    }
2910    let started = std::time::Instant::now();
2911    let ran = link::run(&linker, &args);
2912    if opts.time {
2913        // The one step of a compilation that really is another program, so this line is the same
2914        // measurement gcc's is and names the linker the way gcc names `collect2`.
2915        let mut stderr = std::io::stderr().lock();
2916        say_time(&linker.name, started.elapsed(), &mut stderr);
2917    }
2918    match ran {
2919        Ok(()) => 0,
2920        // The linker has already said what was wrong on its own error output, and repeating that
2921        // linking failed would only push its message further up the screen.
2922        Err(link::Error::Refused { .. }) => 1,
2923        Err(why) => complain(why),
2924    }
2925}
2926
2927/// Compiles everything and writes the objects into one static library.
2928///
2929/// No temporary directory and no second program. The objects never reach the file system at all:
2930/// they go from the compiler into the archive writer, which is both faster than writing a directory
2931/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
2932/// member's index entries are the names the object writer says it wrote, and the only thing that
2933/// knows those is the run that wrote it.
2934///
2935/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
2936/// person can find, and they are written there as well as put in the archive.
2937fn archive_all(opts: &Options, plan: &Plan) -> i32 {
2938    let Some(job) = &plan.archive else {
2939        // Every path into here comes from a plan whose last phase is the archive, and such a plan
2940        // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
2941        return complain("there is nothing to put in an archive");
2942    };
2943    // Before anything is compiled, because a format this has no container for is worth knowing
2944    // about in the second it takes to look rather than after the whole compilation.
2945    let flavour = match opts.target.os.object_format() {
2946        ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
2947        ObjectFormat::Coff => rucc_archive::Flavour::Coff,
2948        // Mach-O wants the BSD flavour, whose index is a different member under a different name,
2949        // and wasm has no archives of its own at all. Neither has an object writer either, so a
2950        // command line reaching this would have failed in the next step regardless.
2951        format @ (ObjectFormat::MachO | ObjectFormat::Wasm) => {
2952            return complain(format!(
2953                "there is no archive format for {} objects in this compiler yet",
2954                format.as_str()
2955            ));
2956        }
2957    };
2958
2959    let fs = OsFileSystem::new();
2960    let mut failed = false;
2961    let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
2962    let mut names = job.members.iter();
2963    let mut fired = Fired::new();
2964    let mut pressure = Pressure::new();
2965    let mut lowerings = Lowerings::new();
2966    {
2967        let mut stderr = std::io::stderr().lock();
2968        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2969        failed |= !ok;
2970        for plan_job in &plan.jobs {
2971            // What the plan called this member. The two lists are walked together rather than the
2972            // name being worked out again here, so that what `-###` printed and what goes in the
2973            // file cannot come apart.
2974            let Some(member) = names.next() else {
2975                return complain("the plan asks the archive for a member nothing produced");
2976            };
2977            if !plan_job.phases.contains(&Phase::Compile) && !needs_an_assembler(plan_job) {
2978                // Neither something to compile nor something to assemble, so there is nothing to
2979                // put in, and an archive quietly missing a member is worse than a message.
2980                let _ = writeln!(
2981                    &mut stderr,
2982                    "rucc: error: {}: this compiler makes an archive out of what it compiles, and \
2983                     there is nothing here for it to do",
2984                    plan_job.input
2985                );
2986                failed = true;
2987                continue;
2988            }
2989            let started = std::time::Instant::now();
2990            let result = if needs_an_assembler(plan_job) {
2991                assemble(opts, &plan_job.input, assembly_wants_cpp(plan_job), &fs)
2992            } else if plan_job.kind == InputKind::Ir {
2993                compile_ir(opts, &plan_job.input, &fs)
2994            } else {
2995                compile(opts, &plan_job.input, &fs)
2996            };
2997            if opts.time {
2998                say_time(&plan_job.input, started.elapsed(), &mut stderr);
2999            }
3000            fired.merge(&result.fired);
3001            pressure.merge(&result.pressure);
3002            lowerings.merge(&result.lowerings);
3003            failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
3004            failed |= !remarks.write(&result.remarks, &mut stderr);
3005            for message in &result.messages {
3006                let _ = writeln!(stderr, "{message}");
3007            }
3008            failed |= !write_temps(plan_job, &result.temps, &mut stderr);
3009            if result.failed() {
3010                failed = true;
3011                continue;
3012            }
3013            if opts.deps.emit {
3014                failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
3015            }
3016            let Artifact::Object { bytes, defines } = result.artifact else {
3017                let _ = writeln!(
3018                    stderr,
3019                    "rucc: internal error: {}: no object file was produced for the archive",
3020                    plan_job.input
3021                );
3022                failed = true;
3023                continue;
3024            };
3025            // Under `-save-temps` the plan gave the object a name a person can find, so it is
3026            // written there too. Otherwise it is only ever a member and never a file.
3027            if let Output::File(path) = &plan_job.output {
3028                if let Err(e) = std::fs::write(path, &bytes) {
3029                    let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3030                    failed = true;
3031                }
3032            }
3033            members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
3034        }
3035        failed |= !write_coverage(opts, &fired, &mut stderr);
3036        failed |= !write_pressure(opts, &pressure, &mut stderr);
3037        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3038        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3039    }
3040    if failed {
3041        // Nothing is written from a compilation that did not finish, for the reason the link gives:
3042        // an archive missing the file that failed is one a link reports every name of as undefined,
3043        // which is a page of messages about a mistake already reported once.
3044        return 1;
3045    }
3046
3047    let bytes = match rucc_archive::write(flavour, &members) {
3048        Ok(bytes) => bytes,
3049        // Every one of these is a bug here rather than a program's mistake: the names came from the
3050        // object writer and the bodies came from this process.
3051        Err(why) => return complain(format!("the archive could not be written: {why}")),
3052    };
3053    match std::fs::write(&job.output, &bytes) {
3054        Ok(()) => 0,
3055        Err(e) => complain(format!("{}: {e}", job.output)),
3056    }
3057}
3058
3059/// Prints one driver level message and gives back the exit status that goes with it.
3060fn complain(why: impl std::fmt::Display) -> i32 {
3061    let mut stderr = std::io::stderr().lock();
3062    let _ = writeln!(stderr, "rucc: error: {why}");
3063    1
3064}
3065
3066/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
3067///
3068/// Once for the whole command line rather than once per input, because the question is which
3069/// lowering rules this run of the compiler reached and a file per input would leave the reader
3070/// unioning files to find out something one process already knew.
3071///
3072/// A file that could not be written is a failure and not a warning. What asks for this is a
3073/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
3074fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
3075    let Some(path) = &opts.rule_coverage else { return true };
3076    let Some(table) = coverage::table(opts.target.arch) else {
3077        let _ = writeln!(
3078            stderr,
3079            "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
3080             to report",
3081            opts.target
3082        );
3083        return false;
3084    };
3085    match std::fs::write(path, fired.listing(table)) {
3086        Ok(()) => true,
3087        Err(e) => {
3088            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3089            false
3090        }
3091    }
3092}
3093
3094/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
3095///
3096/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3097/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
3098/// rule table here, since every target this compiles for has an allocator, and a run that reached
3099/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
3100/// produced no code is still an answer and it is the honest one.
3101fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
3102    let Some(path) = &opts.register_pressure else { return true };
3103    match std::fs::write(path, pressure.listing()) {
3104        Ok(()) => true,
3105        Err(e) => {
3106            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3107            false
3108        }
3109    }
3110}
3111
3112/// Writes what `-Zlowering=FILE` asked for, and says whether it could.
3113///
3114/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3115/// not be written is a failure for the reason it gives too. A run that reached no back end writes
3116/// an empty listing rather than nothing, the way [`write_pressure`] does and for the same reason.
3117fn write_lowering(opts: &Options, lowerings: &Lowerings, stderr: &mut impl std::io::Write) -> bool {
3118    let Some(path) = &opts.lowering_dump else { return true };
3119    match std::fs::write(path, lowerings.listing()) {
3120        Ok(()) => true,
3121        Err(e) => {
3122            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3123            false
3124        }
3125    }
3126}
3127
3128/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
3129///
3130/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
3131/// A file rather than the diagnostic stream is what a harness wants: the corpus in
3132/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
3133/// a few thousand remarks mixed into that would bury it.
3134struct Remarks {
3135    /// The file, if there is one.
3136    file: Option<String>,
3137    /// Whether anything has been written to it yet, which decides between truncating and
3138    /// appending. One file holds the whole run rather than the last input in it.
3139    started: bool,
3140}
3141
3142impl Remarks {
3143    /// Prepares the destination, emptying the file if there is one.
3144    ///
3145    /// Emptied here rather than at the first remark, because a run where no pass had anything to
3146    /// say should leave an empty file and not yesterday's. An absent file and an empty one are
3147    /// different facts and something reading this will act on the difference.
3148    fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
3149        let mut ok = true;
3150        if let Some(path) = file {
3151            if let Err(e) = std::fs::write(path, "") {
3152                let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3153                ok = false;
3154            }
3155        }
3156        (Self { file: file.cloned(), started: false }, ok)
3157    }
3158
3159    /// Writes one input's remarks, and says whether that worked.
3160    ///
3161    /// A file that cannot be written is a failure and not a warning, for the reason
3162    /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
3163    /// where nothing happened.
3164    fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
3165        if text.is_empty() {
3166            return true;
3167        }
3168        let Some(path) = &self.file else {
3169            let _ = write!(stderr, "{text}");
3170            return true;
3171        };
3172        let opened = std::fs::OpenOptions::new()
3173            .write(true)
3174            .append(self.started)
3175            .truncate(!self.started)
3176            .create(true)
3177            .open(path);
3178        self.started = true;
3179        let result =
3180            opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
3181        if let Err(e) = result {
3182            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3183            return false;
3184        }
3185        true
3186    }
3187}
3188
3189/// Writes what `-fdump-ir=` asked to see, one file per dump.
3190///
3191/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
3192/// after a run is the passes in the order they ran, per input. They go in the working directory
3193/// rather than beside the output, because a dump is something a person asked for at a prompt and
3194/// the working directory is where that person is.
3195///
3196/// A file that could not be written is a failure and not a warning, for the reason
3197/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
3198/// quietly did not happen looks exactly like a pass that did not run.
3199fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
3200    let stem = std::path::Path::new(input)
3201        .file_name()
3202        .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
3203    let mut ok = true;
3204    for dump in dumps {
3205        let path = format!("{stem}.{}.ir", dump.name);
3206        if let Err(e) = std::fs::write(&path, &dump.text) {
3207            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3208            ok = false;
3209        }
3210    }
3211    ok
3212}
3213
3214/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
3215///
3216/// A file that could not be written is a failure rather than a warning, for the reason
3217/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
3218/// looks like a compilation that never went through that step.
3219fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
3220    let mut ok = true;
3221    let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
3222    for (path, text) in kept {
3223        // A step the compilation did not reach has nothing to keep, and a job that is not keeping
3224        // that step has nowhere to put it. Either way there is no file here.
3225        let (Some(path), Some(text)) = (path, text) else { continue };
3226        if let Err(e) = std::fs::write(&path, text) {
3227            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3228            ok = false;
3229        }
3230    }
3231    ok
3232}
3233
3234/// One line of `-time`, which is what a step was called and how long it took.
3235///
3236/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
3237/// no subprocess for anything but the link, so what is measured here is the wall clock of the
3238/// step and the second column is always zero. The shape of the line is kept because a person
3239/// reading it next to gcc's should not have to work out which column is which.
3240fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
3241    let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
3242}
3243
3244/// Writes one job's result where the plan said it goes.
3245///
3246/// # Errors
3247///
3248/// Returns the message to print, which names the file when there is one, because "permission
3249/// denied" on its own does not say which file was refused.
3250fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
3251    match output {
3252        Output::Stdout => {
3253            let mut stdout = std::io::stdout().lock();
3254            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
3255        }
3256        Output::File(path) | Output::Temporary(path) => {
3257            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
3258        }
3259    }
3260}
3261
3262/// The target a program name asks for, the way `aarch64-linux-gnu-gcc` is gcc for that target.
3263///
3264/// `program` is the path the compiler was started as. The name without its directory and without a
3265/// trailing `.exe` has to end in `-rucc`, and what comes before that has to be a target this
3266/// compiler knows, or there is no answer and the name means nothing. A link named `my-rucc` is
3267/// therefore just rucc and not an error.
3268pub fn target_from_program(program: &str) -> Option<String> {
3269    let name = program.rsplit(['/', '\\']).next()?;
3270    let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
3271    let triple = name.strip_suffix("-rucc")?;
3272    triple.parse::<Triple>().ok()?;
3273    Some(triple.to_owned())
3274}
3275
3276/// [`run`] for a compiler started as `program`, which is `argv[0]`.
3277///
3278/// A target taken from the name goes in front of `args`, so a `--target=` written on the command
3279/// line comes later and wins, which is what gcc and clang do with a prefixed name.
3280pub fn run_as(program: &str, args: &[String]) -> i32 {
3281    match target_from_program(program) {
3282        Some(triple) => {
3283            let mut all = Vec::with_capacity(args.len() + 1);
3284            all.push(format!("--target={triple}"));
3285            all.extend_from_slice(args);
3286            run(&all)
3287        }
3288        None => run(args),
3289    }
3290}
3291
3292/// Runs the driver and returns the process exit code.
3293///
3294/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
3295/// is the one place in the compiler that is true.
3296pub fn run(args: &[String]) -> i32 {
3297    match parse_args(args) {
3298        Ok(Action::Help) => {
3299            print!("{USAGE}");
3300            0
3301        }
3302        Ok(Action::Version) => {
3303            println!("rucc {VERSION}");
3304            0
3305        }
3306        Ok(Action::Print(line)) => {
3307            println!("{line}");
3308            0
3309        }
3310        Ok(Action::PrintConfig(opts)) => {
3311            print!("{}", print_config(&opts));
3312            0
3313        }
3314        Ok(Action::PrintPipeline(opts)) => {
3315            print!("{}", print_pipeline(&opts));
3316            0
3317        }
3318        Ok(Action::PrintPlan { opts, plan, link }) => {
3319            print!("{}", plan.render());
3320            // The line as it would be typed, which is the half of `-###` that section 4.3 says
3321            // arrives with the link. It is printed even when the linker is not on this machine,
3322            // because what a build wants from `-###` is what the compiler would do.
3323            if let Some(job) = &plan.link {
3324                match link_line(&opts, &link, job) {
3325                    Ok(line) => println!("{line}"),
3326                    Err(why) => {
3327                        let mut stderr = std::io::stderr().lock();
3328                        let _ = writeln!(stderr, "rucc: error: {why}");
3329                        return 1;
3330                    }
3331                }
3332            }
3333            0
3334        }
3335        Ok(Action::Fetch { what, target, cache }) => {
3336            let kernel = rucc_sysroot::Kernel::for_target(&cache, target)
3337                .map(|_| &rucc_sysroot::KERNEL_HEADERS);
3338            fetch_sysroot(what, kernel, target, &cache)
3339        }
3340        Ok(Action::FetchMsvcSdk { target, accepted, cache }) => {
3341            msvc::fetch_msvc_sdk(target, accepted, &cache)
3342        }
3343        Ok(Action::Compile { opts, plan, link, jobs, verbose, notes }) => {
3344            {
3345                let mut stderr = std::io::stderr().lock();
3346                // Before the plan rather than after it, because a note is about the command line
3347                // and the plan is what the command line was read as, so the reader wants the two
3348                // in that order.
3349                for note in &notes {
3350                    let _ = writeln!(stderr, "rucc: warning: {note}");
3351                }
3352                if verbose {
3353                    let _ = write!(stderr, "{}", plan.render());
3354                    let _ = writeln!(stderr, "workers: {}", jobs.count());
3355                }
3356            }
3357            if opts.emit == EmitKind::Preprocessed {
3358                return preprocess_all(&opts, &plan);
3359            }
3360            if opts.emit == EmitKind::Archive {
3361                return archive_all(&opts, &plan);
3362            }
3363            if opts.emit != EmitKind::Executable {
3364                return compile_all(&opts, &plan);
3365            }
3366            link_all(&opts, &plan, &link, verbose)
3367        }
3368        Err(e) => {
3369            let mut stderr = std::io::stderr().lock();
3370            let _ = writeln!(stderr, "rucc: error: {e}");
3371            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
3372            1
3373        }
3374    }
3375}
3376
3377#[cfg(test)]
3378mod tests {
3379    use rucc_session::{
3380        Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
3381    };
3382
3383    use super::*;
3384
3385    fn args(s: &[&str]) -> Vec<String> {
3386        s.iter().map(|x| (*x).to_owned()).collect()
3387    }
3388
3389    /// A target to write down where the host would otherwise decide, for the tests whose answer
3390    /// would be a different one on a different machine.
3391    ///
3392    /// Most of the tests here never name a target, which is right, because most of what the driver
3393    /// does with a command line is the same wherever it runs and a test that pinned one would be
3394    /// saying so in every case for the sake of the two that need it. The two that need it are the
3395    /// ones whose answer comes off the target rather than off the command line: the name an object
3396    /// gets, which is `a.o` here and `a.obj` on Windows, and whether Microsoft's reading of a
3397    /// nameless member is on, which is off here and on there. Both are the compiler being right, and
3398    /// a test that leaves the target to the host is asking a question with two correct answers.
3399    const LINUX: &str = "--target=x86_64-unknown-linux-gnu";
3400
3401    #[test]
3402    fn help_and_version_win_over_everything_else() {
3403        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
3404        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
3405    }
3406
3407    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
3408        match parse_args(&args(s)).expect("expected a compilation") {
3409            Action::Compile { opts, plan, .. } => (opts, plan),
3410            other => panic!("expected a compilation, got {other:?}"),
3411        }
3412    }
3413
3414    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
3415        match parse_args(&args(s)).expect("expected a compilation") {
3416            Action::Compile { link, plan, .. } => (link, plan),
3417            other => panic!("expected a compilation, got {other:?}"),
3418        }
3419    }
3420
3421    fn notes(s: &[&str]) -> Vec<String> {
3422        match parse_args(&args(s)).expect("expected a compilation") {
3423            Action::Compile { notes, .. } => notes,
3424            other => panic!("expected a compilation, got {other:?}"),
3425        }
3426    }
3427
3428    /// The ordinary command line has nothing to say about itself, which is the property that makes
3429    /// a note worth reading when there is one.
3430    #[test]
3431    fn a_command_line_with_nothing_wrong_with_it_carries_no_notes() {
3432        assert_eq!(notes(&["-c", "a.c"]), Vec::<String>::new());
3433    }
3434
3435    /// A directory that is not there contributes nothing to the search path, so there is no tree to
3436    /// read a release out of and nothing to compare the pin against. Said as a test because this is
3437    /// the shape a hermetic machine takes: the probe reads the disk and every other machine has a
3438    /// different disk, so what can be asserted here is the silence.
3439    #[test]
3440    fn a_named_tree_that_is_not_on_the_machine_is_not_a_release_mismatch() {
3441        let said =
3442            notes(&["--target=x86_64-linux-gnu.2.28", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3443        assert_eq!(said, Vec::<String>::new());
3444    }
3445
3446    #[test]
3447    fn collects_inputs_and_flags() {
3448        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
3449        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
3450        assert_eq!(paths, vec!["a.c", "b.c"]);
3451        assert_eq!(opts.opt_level, OptLevel::O2);
3452        assert_eq!(opts.emit, EmitKind::Object);
3453        assert!(opts.debug_info);
3454    }
3455
3456    /// The unstable options, which are spelled apart from everything else on purpose: what is
3457    /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
3458    #[test]
3459    fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
3460        let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
3461        assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
3462
3463        let (plain, _) = compile(&["-c", "a.c"]);
3464        assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
3465
3466        assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
3467        let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
3468        assert!(unknown.message.contains("4.11"), "{}", unknown.message);
3469    }
3470
3471    /// The other measurement written to a file, which reads the same way and fails the same way.
3472    #[test]
3473    fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
3474        let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
3475        assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
3476
3477        let (plain, _) = compile(&["-c", "a.c"]);
3478        assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
3479
3480        assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
3481    }
3482
3483    /// The third one, which says what the pre-selection lowering group did.
3484    #[test]
3485    fn a_switch_shape_is_forced_by_name_and_only_by_one_it_has() {
3486        let (opts, _) = compile(&["-c", "-O2", "-Zswitch=walk", "a.c"]);
3487        assert_eq!(opts.switch_shape.as_deref(), Some("walk"));
3488        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3489        assert_eq!(plain.switch_shape, None, "nothing is forced unless it was asked for");
3490        assert!(parse_args(&args(&["-Zswitch=bit-test", "a.c"])).is_err(), "not a shape it forces");
3491    }
3492
3493    #[test]
3494    fn where_the_lowering_dump_goes_is_asked_for_the_same_way() {
3495        let (opts, _) = compile(&["-c", "-O2", "-Zlowering=/tmp/lowering.txt", "a.c"]);
3496        assert_eq!(opts.lowering_dump.as_deref(), Some("/tmp/lowering.txt"));
3497
3498        let (plain, _) = compile(&["-c", "a.c"]);
3499        assert_eq!(plain.lowering_dump, None, "nothing is dumped unless it was asked for");
3500
3501        assert!(parse_args(&args(&["-Zlowering=", "a.c"])).is_err(), "no file named");
3502    }
3503
3504    /// Scheduling, which has the three way answer every optimization flag has: on, off, and
3505    /// nothing said, which is whatever the optimization level asks for. The name is gcc's, and
3506    /// gcc's has a two in it because gcc has a scheduler before allocation and one after and this
3507    /// is the one after.
3508    #[test]
3509    fn scheduling_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
3510        let (on, _) = compile(&["-c", "-O0", "-fschedule-insns2", "a.c"]);
3511        assert_eq!(on.schedule_insns, Some(true));
3512
3513        let (off, _) = compile(&["-c", "-O2", "-fno-schedule-insns2", "a.c"]);
3514        assert_eq!(off.schedule_insns, Some(false));
3515
3516        let (quiet, _) = compile(&["-c", "-O2", "a.c"]);
3517        assert_eq!(quiet.schedule_insns, None, "nothing said, so the level decides");
3518        assert!(quiet.opt_level.schedules(), "and at this level the level says yes");
3519
3520        let (none, _) = compile(&["-c", "a.c"]);
3521        assert!(!none.opt_level.schedules(), "at no optimization it says no");
3522    }
3523
3524    /// Whether the timing model is worth holding an instruction back over, which is a `-Z` because
3525    /// it is a question about a target's description rather than about the program being compiled.
3526    #[test]
3527    fn whether_the_timing_model_is_cycle_accurate_can_be_overridden() {
3528        let (yes, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=yes", "a.c"]);
3529        assert_eq!(yes.cycle_accurate_model, Some(true));
3530
3531        let (no, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=no", "a.c"]);
3532        assert_eq!(no.cycle_accurate_model, Some(false));
3533
3534        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3535        assert_eq!(plain.cycle_accurate_model, None, "the target's own answer stands");
3536
3537        let bad = parse_args(&args(&["-Zcycle-accurate-model=maybe", "a.c"]))
3538            .expect_err("it takes yes or no");
3539        assert!(bad.message.contains("yes or no"), "{}", bad.message);
3540    }
3541
3542    #[test]
3543    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
3544        let (opts, _) = compile(&["-O", "a.c"]);
3545        assert_eq!(opts.opt_level, OptLevel::O1);
3546    }
3547
3548    #[test]
3549    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
3550        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
3551        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
3552        assert_eq!(plan.jobs[1].kind, InputKind::C);
3553        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
3554    }
3555
3556    #[test]
3557    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
3558        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
3559            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
3560            other => panic!("expected a compilation, got {other:?}"),
3561        };
3562        assert_eq!(jobs.count(), 4);
3563
3564        let default = match parse_args(&args(&["a.c"])).unwrap() {
3565            Action::Compile { jobs, .. } => jobs,
3566            other => panic!("expected a compilation, got {other:?}"),
3567        };
3568        assert_eq!(default, Jobs::available());
3569        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
3570    }
3571
3572    #[test]
3573    fn triple_hash_prints_the_plan_and_runs_nothing() {
3574        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
3575        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
3576        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
3577    }
3578
3579    #[test]
3580    fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
3581        // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
3582        // this, and following the compiler is what makes a build that reads either of them find
3583        // the files where they are.
3584        assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
3585        assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
3586        assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
3587        assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
3588        // The last one on the line decides, the way it does for every other flag with an
3589        // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
3590        // nothing and said nothing looks exactly like one where the files were not produced.
3591        let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
3592        assert_eq!(opts.save_temps, SaveTemps::Cwd);
3593        let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
3594        assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
3595    }
3596
3597    #[test]
3598    fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
3599        let (opts, plan) = compile(&["-c", "-time", "a.c"]);
3600        let (plain, without) = compile(&["-c", "a.c"]);
3601        assert!(opts.time);
3602        assert!(!plain.time);
3603        // Against the same line without the flag rather than against a spelling of the object's
3604        // name, since what the object is called is the host's business and this is not about that.
3605        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
3606    }
3607
3608    #[test]
3609    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
3610        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
3611        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
3612    }
3613
3614    /// What `--fetch` says for a target this release pins nothing for, which today is every target
3615    /// but the three windows-gnu ones, the four musl ones and the eight glibc ones.
3616    #[test]
3617    fn a_fetch_of_a_target_nothing_is_pinned_for_says_so_rather_than_reaching_the_network() {
3618        let e = parse_args(&args(&["--fetch", "x86_64-linux-gnux32"])).unwrap_err();
3619        assert!(e.message.contains("pins no sysroot for x86_64-linux-gnux32"), "{}", e.message);
3620        // And what it does pin, because a release with some rows in the table and a release with
3621        // none are two situations and the second sentence is what tells them apart.
3622        assert!(e.message.contains("x86_64-windows-gnu"), "{}", e.message);
3623        // The joined spelling is the same flag.
3624        let joined = parse_args(&args(&["--fetch=x86_64-linux-gnux32"])).unwrap_err();
3625        assert_eq!(joined, e);
3626    }
3627
3628    /// The two targets a release will never pin, which is a different answer from the one above.
3629    ///
3630    /// Section 13.4. A person who reads "this release pins no sysroot yet" waits for a release that
3631    /// does, and no release of this compiler can ship either of these, so the message names the
3632    /// licence that decides it and what to do instead.
3633    #[test]
3634    fn a_fetch_of_a_target_behind_a_licence_wall_says_so_rather_than_saying_not_yet() {
3635        let e = parse_args(&args(&["--fetch", "aarch64-macos"])).unwrap_err();
3636        assert!(e.message.contains("Xcode licence"), "{}", e.message);
3637        assert!(e.message.contains("there never will be"), "{}", e.message);
3638        assert!(!e.message.contains("tamnd/rucc-cross"), "{}", e.message);
3639
3640        let e = parse_args(&args(&["--fetch", "x86_64-windows-msvc"])).unwrap_err();
3641        assert!(e.message.contains("redistributed"), "{}", e.message);
3642        // The way out of this one is a target rather than a download, and it is the default already.
3643        assert!(e.message.contains("mingw-w64"), "{}", e.message);
3644        // And the mingw-w64 target next to it is ours to ship and published, so the same flag has
3645        // something to get rather than a licence to explain.
3646        let action = parse_args(&args(&["--fetch", "x86_64-windows-gnu"])).expect("it is pinned");
3647        let Action::Fetch { what, .. } = action else { panic!("{action:?}") };
3648        assert_eq!(what.tuple, "x86_64-windows-gnu");
3649    }
3650
3651    #[test]
3652    fn the_other_fetch_takes_a_target_behind_microsofts_wall_and_carries_the_acceptance() {
3653        // Both spellings of the flag, because a flag that takes a tuple gets written both ways.
3654        for line in [
3655            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc"],
3656            vec!["--fetch-msvc-sdk=x86_64-windows-msvc"],
3657        ] {
3658            let action = parse_args(&args(&line)).expect("that is a target behind the wall");
3659            let Action::FetchMsvcSdk { target, accepted, .. } = action else {
3660                panic!("{action:?}")
3661            };
3662            assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
3663            // Nothing on the line accepted anything, so nothing did.
3664            assert!(!accepted);
3665        }
3666
3667        // And both spellings of the word, because the prose here uses one and most of the people
3668        // typing this will reach for the other.
3669        for word in ["--accept-licence", "--accept-license"] {
3670            let action = parse_args(&args(&["--fetch-msvc-sdk", "aarch64-windows-msvc", word]))
3671                .expect("that is a target behind the wall");
3672            let Action::FetchMsvcSdk { target, accepted, .. } = action else {
3673                panic!("{action:?}")
3674            };
3675            assert_eq!(target.to_canonical_string(), "aarch64-windows-msvc");
3676            assert!(accepted, "{word} should have been read");
3677        }
3678    }
3679
3680    #[test]
3681    fn the_other_fetch_refuses_the_command_lines_that_do_not_mean_anything() {
3682        // A tuple is what it gets, so a flag with nothing after it is not a command.
3683        let e = parse_args(&args(&["--fetch-msvc-sdk"])).unwrap_err();
3684        assert!(e.message.contains("requires the target"), "{}", e.message);
3685        let e = parse_args(&args(&["--fetch-msvc-sdk", "not-a-target"])).unwrap_err();
3686        assert!(e.message.contains("there is no SDK to get"), "{}", e.message);
3687
3688        // `--offline` forbids every download and this one asks for one, whichever order they came
3689        // in, which is the same answer `--fetch` gives.
3690        for line in [
3691            vec!["--offline", "--fetch-msvc-sdk", "x86_64-windows-msvc"],
3692            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc", "--offline"],
3693        ] {
3694            let e = parse_args(&args(&line)).unwrap_err();
3695            assert!(e.message.contains("two opposite things"), "{}", e.message);
3696        }
3697
3698        // It gets an SDK and compiles nothing, so a file on the same line would be read by nothing.
3699        let e = parse_args(&args(&["--fetch-msvc-sdk", "x86_64-windows-msvc", "a.c"])).unwrap_err();
3700        assert!(e.message.contains("compiles nothing"), "{}", e.message);
3701
3702        // The two fetches are two commands and a line that asked for both asked for neither.
3703        let e = parse_args(&args(&[
3704            "--fetch",
3705            "x86_64-windows-gnu",
3706            "--fetch-msvc-sdk",
3707            "x86_64-windows-msvc",
3708        ]))
3709        .unwrap_err();
3710        assert!(e.message.contains("two different commands"), "{}", e.message);
3711
3712        // And an acceptance with nothing to accept for is a command line that says something about
3713        // a licence no part of it goes near.
3714        let e = parse_args(&args(&["--accept-licence", "-c", "a.c"])).unwrap_err();
3715        assert!(e.message.contains("--fetch-msvc-sdk <tuple> is the command"), "{}", e.message);
3716    }
3717
3718    /// An Apple target on a machine with no SDK, which is section 8.6's other host.
3719    ///
3720    /// Not run on a mac, where the SDK this is about is installed and the compile is the ordinary one
3721    /// that uses it. What the reason says is asserted in `rucc_sysroot::wall` and where it is printed
3722    /// is asserted in `rucc-pp`, so what is left here is that the driver works it out and leaves it
3723    /// where the preprocessor will find it, and that neither way past the wall leaves one behind.
3724    #[test]
3725    fn an_apple_target_with_no_sdk_anywhere_carries_the_licence_rather_than_a_missing_directory() {
3726        if cfg!(target_os = "macos") || std::env::var_os("SDKROOT").is_some() {
3727            return;
3728        }
3729        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
3730        let why = opts.search.missing_system().expect("the wall is the reason there are none");
3731        assert!(why.contains("aarch64-macos needs a macOS SDK"), "{why}");
3732        assert!(why.contains("Xcode licence"), "{why}");
3733        assert!(why.contains("-isysroot"), "{why}");
3734
3735        // A program that includes none of the library needs none of the SDK, which is what section
3736        // 8.6 means by being able to target the platform without one, so there is nothing to explain.
3737        let (opts, _) = compile(&["--target=aarch64-macos", "-nostdinc", "-c", "a.c"]);
3738        assert_eq!(opts.search.missing_system(), None);
3739        // And naming a path is the other way through, whether or not the path is there: a mistyped
3740        // directory is a mistake to report on its own terms rather than a licence to explain.
3741        let (opts, _) = compile(&["--target=aarch64-macos", "-isysroot", "/opt/sdk", "-c", "a.c"]);
3742        assert_eq!(opts.search.missing_system(), None);
3743    }
3744
3745    /// The same wall on the compile side of an MSVC target, where the way past it is a tuple.
3746    ///
3747    /// Not run on Windows, for the same reason the one above is not run on a mac: the wall stands in
3748    /// front of an SDK this machine does not have, and a Windows machine is the kind that does. The
3749    /// driver asks `vswhere` where Visual Studio is and takes the newest kit under it, so on a box
3750    /// with the build tools installed there are headers, no wall and nothing here to be about.
3751    /// `INCLUDE` is the other way a machine has one and is the other half of the guard, since a
3752    /// person can set that anywhere while Visual Studio is only found on the platform it runs on.
3753    #[test]
3754    fn an_msvc_target_with_no_sdk_named_says_which_environment_needs_nothing_installed() {
3755        if cfg!(target_os = "windows") || std::env::var_os("INCLUDE").is_some() {
3756            return;
3757        }
3758        let (opts, _) = compile(&["--target=x86_64-windows-msvc", "-c", "a.c"]);
3759        let why = opts.search.missing_system().expect("the wall is the reason there are none");
3760        assert!(why.contains("the Windows SDK and its universal CRT"), "{why}");
3761        assert!(why.contains("mingw-w64"), "{why}");
3762        // And the mingw-w64 target has its headers from us, so nothing is missing to explain.
3763        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-c", "a.c"]);
3764        assert_eq!(opts.search.missing_system(), None);
3765    }
3766
3767    #[test]
3768    fn a_fetch_with_no_target_and_a_fetch_of_a_tuple_that_is_not_one_both_say_which() {
3769        let e = parse_args(&args(&["--fetch"])).unwrap_err();
3770        assert!(e.message.contains("--fetch requires"), "{}", e.message);
3771        let e = parse_args(&args(&["--fetch", "sparc64-solaris-gnu"])).unwrap_err();
3772        assert!(e.message.contains("--fetch sparc64-solaris-gnu"), "{}", e.message);
3773        assert!(e.message.contains("no sysroot to get"), "{}", e.message);
3774    }
3775
3776    /// Both flags on one line ask for opposite things, in either order.
3777    #[test]
3778    fn a_fetch_and_offline_together_is_a_refusal_whichever_way_round_they_are_written() {
3779        for line in [
3780            vec!["--offline", "--fetch", "x86_64-linux-musl"],
3781            vec!["--fetch", "x86_64-linux-musl", "--offline"],
3782        ] {
3783            let e = parse_args(&args(&line)).unwrap_err();
3784            assert!(e.message.contains("two opposite things"), "{}", e.message);
3785        }
3786    }
3787
3788    #[test]
3789    fn a_fetch_does_not_compile_anything_and_says_so_when_it_is_handed_a_file() {
3790        let e = parse_args(&args(&["--fetch", "x86_64-linux-musl", "a.c"])).unwrap_err();
3791        assert!(e.message.contains("compiles nothing"), "{}", e.message);
3792        assert!(e.message.contains("a.c"), "{}", e.message);
3793    }
3794
3795    /// `--offline` on its own is accepted and changes nothing, because an ordinary compile
3796    /// downloads nothing with or without it. A build that passes it everywhere is the case this is
3797    /// for, and it must not lose the compilation it was passed beside.
3798    #[test]
3799    fn offline_on_a_compilation_is_the_same_compilation() {
3800        let (opts, plan) = compile(&["-c", "--offline", "a.c"]);
3801        let (plain, without) = compile(&["-c", "a.c"]);
3802        assert_eq!(opts.target, plain.target);
3803        assert_eq!(plan.jobs.len(), without.jobs.len());
3804        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
3805    }
3806
3807    #[test]
3808    fn a_deployment_target_comes_from_the_tuple_or_from_the_flag() {
3809        let version = |v: &str| rucc_tuple::Version::parse(v);
3810        let (opts, _) = compile(&["--target=aarch64-macos.13", "-c", "a.c"]);
3811        assert_eq!(opts.target, "aarch64-apple-darwin".parse().unwrap());
3812        assert_eq!(opts.os_version, version("13"));
3813        // The flag wins over the tuple, as it does under clang, and either spelling of it works.
3814        let (opts, _) =
3815            compile(&["--target=aarch64-macos.13", "-mmacosx-version-min=14.2", "-c", "a.c"]);
3816        assert_eq!(opts.os_version, version("14.2"));
3817        let (opts, _) = compile(&["--target=x86_64-macos", "-mmacos-version-min=12", "-c", "a.c"]);
3818        assert_eq!(opts.os_version, version("12"));
3819        // Nothing said leaves the platform's default to the target description.
3820        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
3821        assert_eq!(opts.os_version, None);
3822        // A Linux build that always passes the flag is not an Apple build because of it.
3823        let (opts, _) =
3824            compile(&["--target=aarch64-linux-gnu", "-mmacosx-version-min=13", "-c", "a.c"]);
3825        assert_eq!(opts.os_version, None);
3826        let e = parse_args(&args(&["-mmacosx-version-min=thirteen", "a.c"])).unwrap_err();
3827        assert!(e.message.contains("is not a version"), "{}", e.message);
3828    }
3829
3830    #[test]
3831    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
3832        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
3833        assert!(e.message.contains("unknown option"), "{}", e.message);
3834    }
3835
3836    /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
3837    /// one directory needs the older rules and the rest of the tree does not.
3838    #[test]
3839    fn permissive_reads_in_both_directions_and_the_last_one_wins() {
3840        let (opts, _) = compile(&["-c", "a.c"]);
3841        assert!(!opts.permissive, "off unless it is asked for");
3842
3843        let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
3844        assert!(opts.permissive);
3845
3846        let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
3847        assert!(!opts.permissive);
3848    }
3849
3850    #[test]
3851    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
3852        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
3853        assert!(e.message.contains("trampoline"), "{}", e.message);
3854        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
3855    }
3856
3857    #[test]
3858    fn the_flag_every_configure_script_writes_is_taken() {
3859        // All four spellings, because a build writes whichever one its macros picked and a
3860        // compiler that takes three of them is a compiler that fails on the fourth.
3861        for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
3862            let (opts, _) = compile(&["-c", flag, "a.c"]);
3863            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3864        }
3865    }
3866
3867    #[test]
3868    fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
3869        let (opts, _) = compile(&["-c", "a.c"]);
3870        assert!(opts.unwinds(), "the default is off");
3871        let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
3872        assert!(!opts.unwinds(), "the build was not taken at its word");
3873        let (opts, _) = compile(&[
3874            "-c",
3875            "-fno-asynchronous-unwind-tables",
3876            "-fasynchronous-unwind-tables",
3877            "a.c",
3878        ]);
3879        assert!(opts.unwinds(), "the last flag did not win");
3880        // The weaker request, which the same table answers, so a line that asks for a table and
3881        // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
3882        // build turns the asynchronous one off globally and a directory asks for a table back.
3883        let (opts, _) =
3884            compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
3885        assert!(opts.unwinds(), "the weaker request was dropped");
3886        let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
3887        assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
3888        let (opts, _) =
3889            compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
3890        assert!(!opts.unwinds(), "both were turned off and one stayed on");
3891    }
3892
3893    #[test]
3894    fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
3895        // Every one of these is on a real build line somewhere and every one of them was an
3896        // unknown option. What they have in common is that the answer rucc gives is the answer
3897        // they ask for, so there is nothing to implement and nothing to refuse.
3898        for flag in [
3899            "-fno-common",
3900            "-fstrict-aliasing",
3901            "-fno-strict-aliasing",
3902            "-fdelete-null-pointer-checks",
3903            "-fno-delete-null-pointer-checks",
3904            "-frounding-math",
3905            "-fno-rounding-math",
3906            "-fexcess-precision=standard",
3907            "-fexcess-precision=fast",
3908            "-fexcess-precision=16",
3909            "-pipe",
3910            "-fdiagnostics-color",
3911            "-fno-diagnostics-color",
3912            "-fdiagnostics-color=always",
3913            "-fdiagnostics-color=never",
3914            "-fdiagnostics-color=auto",
3915        ] {
3916            let (opts, _) = compile(&["-c", flag, "a.c"]);
3917            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3918        }
3919    }
3920
3921    #[test]
3922    fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
3923        let (opts, _) = compile(&["-c", "a.c"]);
3924        assert!(opts.trapping_math, "the default was not gcc's");
3925        let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
3926        assert!(!opts.trapping_math);
3927        let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
3928        assert!(opts.trapping_math, "spelling out the default turned it off");
3929        // The last one written wins, which is how a build line that inherits a flag from one
3930        // place and overrides it in another is read.
3931        let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
3932        assert!(opts.trapping_math);
3933    }
3934
3935    /// The flags a torture program writes on its own `dg-options` line, which is where most of
3936    /// these come from: a program reduced from a miscompilation names the pass that miscompiled
3937    /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
3938    /// tamnd/rucc#1019 is the list.
3939    #[test]
3940    fn no_inline_turns_off_the_inlining_of_a_function_declared_inline() {
3941        let (opts, _) = compile(&["-c", "-O2", "-fno-inline", "a.c"]);
3942        assert_eq!(opts.passes, [(rucc_opt::inline::NAME.to_owned(), false)]);
3943    }
3944
3945    #[test]
3946    fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
3947        for flag in [
3948            "-fno-tree-ccp",
3949            "-fno-tree-dominator-opts",
3950            "-fno-tree-vrp",
3951            "-fno-tree-bit-ccp",
3952            "-fno-tree-coalesce-vars",
3953            "-ftree-vectorize",
3954            "-ftree-loop-distribution",
3955            "-fipa-pta",
3956            "-fmodulo-sched",
3957            "-fno-vect-cost-model",
3958            "-fvect-cost-model=unlimited",
3959            "-fsimd-cost-model=cheap",
3960            "-fexpensive-optimizations",
3961            "-fno-early-inlining",
3962            "-finline-functions",
3963            "-foptimize-strlen",
3964            "-fno-ira-share-spill-slots",
3965        ] {
3966            let (opts, _) = compile(&["-c", flag, "a.c"]);
3967            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3968            assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
3969        }
3970    }
3971
3972    /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
3973    /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
3974    #[test]
3975    fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
3976        for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
3977            let (opts, _) = compile(&["-c", flag, "a.c"]);
3978            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3979        }
3980    }
3981
3982    /// A pass this compiler has keeps its flag, since the arms that read the registry are above
3983    /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
3984    /// is the program that writes it.
3985    #[test]
3986    fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
3987        let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
3988        assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
3989    }
3990
3991    /// gcc's name for the unroller reaches the unroller, in both directions. libtommath puts
3992    /// `-funroll-loops` in `CFLAGS` unconditionally, and before this it was an unknown option and
3993    /// the build stopped on its first file.
3994    #[test]
3995    fn the_gcc_spelling_of_the_unroller_turns_the_unroller_on_and_off() {
3996        let (opts, _) = compile(&["-c", "-funroll-loops", "a.c"]);
3997        assert_eq!(opts.passes, vec![("unroll".to_owned(), true)]);
3998        let (opts, _) = compile(&["-c", "-fno-unroll-loops", "a.c"]);
3999        assert_eq!(opts.passes, vec![("unroll".to_owned(), false)]);
4000    }
4001
4002    /// The three transformations that are a module at a time are named by a flag as well, even
4003    /// though none of them is a `rucc_opt::Pass` and so none is reached by the generic arms.
4004    ///
4005    /// A bisection over a miscompilation turns one thing off at a time, and a transformation with
4006    /// no spelling of its own cannot be the one turned off.
4007    #[test]
4008    fn the_transformations_that_are_not_passes_are_still_named_by_a_flag() {
4009        let (opts, _) = compile(&["-c", "-fno-ipa-cp", "-fipa-sra", "-fno-libcall", "a.c"]);
4010        assert_eq!(
4011            opts.passes,
4012            vec![
4013                (rucc_opt::ipcp::NAME.to_owned(), false),
4014                (rucc_opt::ipasra::NAME.to_owned(), true),
4015                (rucc_opt::libcall::NAME.to_owned(), false),
4016            ]
4017        );
4018        let (opts, _) = compile(&["-c", "-flibcall", "a.c"]);
4019        assert_eq!(opts.passes, vec![(rucc_opt::libcall::NAME.to_owned(), true)]);
4020    }
4021
4022    /// Where a function starts is a question this compiler answers, so the flag that asks about it
4023    /// is answered rather than dropped. femtolisp's Makefile writes the bare form on every compile
4024    /// of the project, and before this it was an unknown option and the build stopped on its first
4025    /// file. The numbers are gcc 16's, read off `-S` on x86-64: nothing and the bare form both
4026    /// give `.p2align 4`, `=32` gives 5, `=3` gives 2, and the negative form gives `.align 8`.
4027    #[test]
4028    fn the_alignment_of_a_function_is_a_request_this_compiler_can_answer() {
4029        let (opts, _) = compile(&["-c", "-falign-functions", "a.c"]);
4030        assert_eq!(opts.align_functions, None, "the bare form asks for the default");
4031
4032        let (opts, _) = compile(&["-c", "-falign-functions=32", "a.c"]);
4033        assert_eq!(opts.align_functions, Some(32));
4034
4035        let (opts, _) = compile(&["-c", "-falign-functions=3", "a.c"]);
4036        assert_eq!(opts.align_functions, Some(4), "rounded up rather than refused");
4037
4038        let (opts, _) = compile(&["-c", "-falign-functions=32:8", "a.c"]);
4039        assert_eq!(opts.align_functions, Some(32), "the boundary is the answerable half");
4040
4041        for flag in ["-falign-functions=0", "-falign-functions=1"] {
4042            let (opts, _) = compile(&["-c", flag, "a.c"]);
4043            assert_eq!(opts.align_functions, None, "{flag} means the default");
4044        }
4045
4046        let (opts, _) = compile(&["-c", "-fno-align-functions", "a.c"]);
4047        assert_eq!(opts.align_functions, Some(8), "the smallest boundary the target has");
4048
4049        // The last one on the line wins, which is how gcc reads a repeated flag.
4050        let (opts, _) = compile(&["-c", "-falign-functions=32", "-falign-functions", "a.c"]);
4051        assert_eq!(opts.align_functions, None);
4052
4053        let e = parse_args(&args(&["-c", "-falign-functions=big", "a.c"])).unwrap_err();
4054        assert!(e.message.contains("number of bytes"), "{}", e.message);
4055    }
4056
4057    /// The other three of the family are about padding inside a body, so none of them is about
4058    /// where a function starts. Every spelling of each, since a build writes whichever one its
4059    /// author typed.
4060    #[test]
4061    fn the_alignment_flags_about_the_inside_of_a_body_are_taken_and_say_nothing() {
4062        for flag in [
4063            "-falign-labels",
4064            "-falign-loops",
4065            "-falign-jumps",
4066            "-falign-loops=16",
4067            "-falign-labels=32",
4068            "-fno-align-loops",
4069            "-fno-align-labels",
4070            "-fno-align-jumps",
4071        ] {
4072            let (opts, _) = compile(&["-c", flag, "a.c"]);
4073            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4074            assert_eq!(opts.align_functions, None, "{flag} is not about where a function starts");
4075        }
4076    }
4077
4078    /// The loop flag in either direction is an answer, and a command line that wrote neither
4079    /// leaves the level to decide.
4080    #[test]
4081    fn the_loop_alignment_flag_is_answered_both_ways() {
4082        assert_eq!(compile(&["-c", "-O2", "a.c"]).0.align_loops, None);
4083        assert_eq!(compile(&["-c", "-O0", "-falign-loops", "a.c"]).0.align_loops, Some(true));
4084        assert_eq!(compile(&["-c", "-O2", "-fno-align-loops", "a.c"]).0.align_loops, Some(false));
4085        assert_eq!(compile(&["-c", "-falign-loops=32", "a.c"]).0.align_loops, None, "a number");
4086    }
4087
4088    /// The encoding of the source is not a question about speed, so the one name that describes
4089    /// what the preprocessor does is taken and every other name is refused.
4090    #[test]
4091    fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
4092        for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
4093            let (opts, _) = compile(&["-c", flag, "a.c"]);
4094            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4095        }
4096
4097        let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
4098        assert!(e.message.contains("latin1"), "{}", e.message);
4099        assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
4100    }
4101
4102    /// The other half of the same rule. This one changes what the program does rather than how
4103    /// fast it does it, so it is refused with the reason, and its negative is what happens anyway
4104    /// and is taken.
4105    #[test]
4106    fn the_one_that_changes_the_answer_is_refused_and_its_negative_is_taken() {
4107        let e = parse_args(&args(&["-c", "-fnon-call-exceptions", "a.c"])).unwrap_err();
4108        assert!(e.message.contains("landing pad"), "{}", e.message);
4109        assert!(!e.message.contains("unknown option"), "it deserves a reason");
4110
4111        let (opts, _) = compile(&["-c", "-fno-non-call-exceptions", "a.c"]);
4112        assert_eq!(opts.emit, EmitKind::Object);
4113    }
4114
4115    /// `-ffast-math` used to be refused beside it and is the family it names now, with each
4116    /// member settable on its own and the last word on each winning, which is gcc's reading.
4117    #[test]
4118    fn fast_math_is_the_family_it_names_and_the_last_word_on_each_member_wins() {
4119        let both = |line: &[&str]| {
4120            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4121            let (link, _) = linking(&[line, &["a.c"]].concat());
4122            (opts, link)
4123        };
4124        let (opts, link) = both(&[]);
4125        assert_eq!(opts.math, Math::default());
4126        assert!(opts.trapping_math);
4127        assert!(!link.fast_math);
4128
4129        let (opts, link) = both(&["-ffast-math"]);
4130        assert!(opts.math.fast(opts.trapping_math), "{:?}", opts.math);
4131        assert!(!opts.trapping_math, "fast math turns trapping off");
4132        assert!(link.fast_math, "and it links the startup file");
4133
4134        // Taking one member back leaves the rest, and the whole is not fast math any more.
4135        let (opts, link) = both(&["-ffast-math", "-fno-finite-math-only"]);
4136        assert!(!opts.math.finite_only);
4137        assert!(!opts.math.errno && !opts.math.signed_zeros && opts.math.reciprocal);
4138        assert!(!opts.math.fast(opts.trapping_math));
4139        assert!(link.fast_math, "gcc's spec reads the flag and not the fields");
4140
4141        let (opts, _) = both(&["-ffast-math", "-ftrapping-math"]);
4142        assert!(opts.trapping_math);
4143        assert!(!opts.math.fast(opts.trapping_math));
4144        assert!(!opts.math.associative(opts.trapping_math));
4145
4146        let (opts, link) = both(&["-ffast-math", "-fno-fast-math"]);
4147        assert_eq!(opts.math, Math::default());
4148        assert!(opts.trapping_math);
4149        assert!(!link.fast_math);
4150
4151        // A member written alone is only that member.
4152        let (opts, link) = both(&["-fno-math-errno"]);
4153        assert_eq!(opts.math, Math { errno: false, ..Math::default() });
4154        assert!(opts.math.iec_559(opts.trapping_math), "errno is not an IEC 60559 question");
4155        assert!(!link.fast_math);
4156
4157        let (opts, link) = both(&["-funsafe-math-optimizations"]);
4158        assert!(opts.math.unsafe_math && opts.math.associative(opts.trapping_math));
4159        assert!(opts.math.errno && !opts.math.finite_only);
4160        assert!(link.fast_math);
4161    }
4162
4163    /// `-Ofast` is `-O3` with fast math as a default, which a later level and a
4164    /// `-fno-fast-math` on either side of it both take back.
4165    #[test]
4166    fn ofast_is_o3_with_fast_math_as_a_default_a_flag_can_take_back() {
4167        let both = |line: &[&str]| {
4168            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4169            let (link, _) = linking(&[line, &["a.c"]].concat());
4170            (opts, link)
4171        };
4172        let (opts, link) = both(&["-Ofast"]);
4173        assert_eq!(opts.opt_level, OptLevel::O3);
4174        assert!(opts.math.fast(opts.trapping_math));
4175        assert!(link.fast_math);
4176
4177        for line in [&["-Ofast", "-O2"][..], &["-fno-fast-math", "-Ofast"]] {
4178            let (opts, _) = both(line);
4179            assert!(!opts.math.fast(opts.trapping_math), "{line:?}");
4180        }
4181
4182        let (_, link) = both(&["-Ofast", "-mno-daz-ftz"]);
4183        assert_eq!(link.daz_ftz, Some(false));
4184    }
4185
4186    /// `-finstrument-functions` used to be refused beside those two, and it is taken now that the
4187    /// hooks are called. The last of it and its negative is the one that counts, as with any pair.
4188    #[test]
4189    fn instrument_functions_is_taken_and_the_last_of_the_pair_wins() {
4190        let (opts, _) = compile(&["-c", "-finstrument-functions", "a.c"]);
4191        assert!(opts.instrument_functions);
4192        let (opts, _) =
4193            compile(&["-c", "-finstrument-functions", "-fno-instrument-functions", "a.c"]);
4194        assert!(!opts.instrument_functions);
4195    }
4196
4197    #[test]
4198    fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
4199        // The one of that family that is a request rather than a description, and it is a real
4200        // difference: two files each writing `int g;` link under it and do not without it.
4201        let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
4202        assert!(e.message.contains(".bss"), "{}", e.message);
4203        assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
4204    }
4205
4206    #[test]
4207    fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
4208        for flag in ["-fno-pic", "-fno-pie"] {
4209            let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
4210            assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
4211            // The one it may have meant, since the two are a letter apart and one of them is
4212            // about linking and is taken.
4213            assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
4214        }
4215    }
4216
4217    #[test]
4218    fn a_program_name_with_a_known_target_in_front_of_rucc_picks_that_target() {
4219        let t = |p: &str| target_from_program(p);
4220        assert_eq!(t("aarch64-linux-gnu-rucc").as_deref(), Some("aarch64-linux-gnu"));
4221        assert_eq!(t("/usr/bin/riscv64-linux-musl-rucc").as_deref(), Some("riscv64-linux-musl"));
4222        assert_eq!(t(r"C:\bin\x86_64-windows-gnu-rucc.exe").as_deref(), Some("x86_64-windows-gnu"));
4223        assert_eq!(t("rucc"), None);
4224        assert_eq!(t("/usr/local/bin/rucc"), None);
4225        assert_eq!(t("my-rucc"), None);
4226        assert_eq!(t("sparc64-linux-gnu-rucc"), None);
4227        assert_eq!(t("aarch64-linux-gnu-gcc"), None);
4228    }
4229
4230    #[test]
4231    fn an_unsupported_target_names_itself() {
4232        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
4233        assert!(e.message.contains("sparc64"), "{}", e.message);
4234    }
4235
4236    #[test]
4237    fn no_inputs_is_an_error_but_print_config_needs_none() {
4238        assert!(parse_args(&args(&[])).is_err());
4239        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
4240    }
4241
4242    #[test]
4243    fn print_config_reports_the_target_it_was_given_not_the_host() {
4244        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
4245        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
4246        let text = print_config(&opts);
4247        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
4248        assert!(text.contains("char-signed: false"), "{text}");
4249        assert!(text.contains("object-format: elf"), "{text}");
4250        assert!(text.contains("va-list: void-pointer"), "{text}");
4251        // RISC-V has a register file and this compiler has not written it down yet, and the
4252        // dump says which of those two it is rather than leaving the line out.
4253        assert!(text.contains("registers: none"), "{text}");
4254        assert!(text.contains("timing-model: none"), "{text}");
4255    }
4256
4257    /// The model the schedule was chosen with, which is a receipt anybody comparing two runs of a
4258    /// benchmark needs: two numbers that disagree are usually two models and not two compilers.
4259    #[test]
4260    fn print_config_names_the_model_the_schedule_was_chosen_with() {
4261        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4262        let text = print_config(&opts);
4263        let line = text.lines().find(|l| l.starts_with("timing-model:")).expect("the model");
4264        assert!(line.contains("Skylake"), "{line}");
4265        assert!(line.contains("published"), "a sentence saying where it came from: {line}");
4266    }
4267
4268    #[test]
4269    fn print_config_has_one_key_per_line_and_a_fixed_order() {
4270        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4271        let text = print_config(&opts);
4272        let keys: Vec<&str> =
4273            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
4274        assert_eq!(keys[0], "version");
4275        assert_eq!(keys[1], "target");
4276        assert_eq!(keys.len(), 26);
4277        assert!(text.ends_with('\n'));
4278    }
4279
4280    #[test]
4281    fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4282        let (opts, _) = compile(&["a.c"]);
4283        assert_eq!(opts.safety, rucc_session::Safety::Off);
4284
4285        for (flag, tier) in [
4286            ("-fsafety=detect", rucc_session::Safety::Detect),
4287            ("-fsafety=enforce", rucc_session::Safety::Enforce),
4288            ("-fsafety=kernel", rucc_session::Safety::Kernel),
4289            ("-fsafety=off", rucc_session::Safety::Off),
4290        ] {
4291            let (opts, _) = compile(&[flag, "a.c"]);
4292            assert_eq!(opts.safety, tier, "{flag}");
4293        }
4294
4295        // The last one wins, the way every other repeated flag on this command line does.
4296        let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
4297        assert_eq!(opts.safety, rucc_session::Safety::Off);
4298
4299        // A misspelled tier is refused rather than ignored. Silently compiling without the
4300        // monitor a build asked for is the one failure mode this feature cannot have.
4301        let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
4302        assert!(e.message.contains("is not a safety tier"), "{}", e.message);
4303        assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
4304    }
4305
4306    #[test]
4307    fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4308        // The default is the one section 9.3 of document 09 gives library code, which is that
4309        // padding does not participate, so a record filled a member at a time is not reported.
4310        let (opts, _) = compile(&["a.c"]);
4311        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4312
4313        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
4314        assert_eq!(opts.padding, rucc_session::Padding::Tracked);
4315
4316        let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
4317        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4318
4319        // The tier is still a tier. A flag whose name starts the same way must not be eaten by
4320        // the one above it, which is the thing worth pinning about a pair of names like these.
4321        let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
4322        assert_eq!(opts.safety, rucc_session::Safety::Off);
4323
4324        let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
4325        assert!(e.message.contains("is not a padding mode"), "{}", e.message);
4326    }
4327
4328    #[test]
4329    fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
4330        // Off by default, because a store to allocated storage sets its effective type and C 6.5
4331        // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
4332        let (opts, _) = compile(&["a.c"]);
4333        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4334
4335        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
4336        assert_eq!(opts.subobject, rucc_session::Subobject::Members);
4337
4338        let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
4339        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4340
4341        // It takes no value. The form that would take one is the strict reading of section 9.4,
4342        // which is not written yet, so say so rather than accept a spelling that does nothing.
4343        let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
4344        assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
4345    }
4346
4347    #[test]
4348    fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
4349        // Off by default, because the record a block keeps is the union of what each pointer
4350        // reached, so two pointers striding through one array without landing on the same byte are
4351        // reported and by the letter of the standard those are different objects. Row Y8 is a build
4352        // deciding it would rather know.
4353        let (opts, _) = compile(&["a.c"]);
4354        assert_eq!(opts.promise, rucc_session::Promise::Off);
4355
4356        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
4357        assert_eq!(opts.promise, rucc_session::Promise::Blocks);
4358
4359        let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
4360        assert_eq!(opts.promise, rucc_session::Promise::Off);
4361
4362        // The tier is still a tier, which is the thing worth pinning about a pair of names where
4363        // one is the front of the other.
4364        let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
4365        assert_eq!(opts.safety, rucc_session::Safety::Off);
4366
4367        let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
4368        assert!(e.message.contains("takes no value"), "{}", e.message);
4369    }
4370
4371    #[test]
4372    fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
4373        // Three modes rather than a bare flag, because section 9.5 gives two answers that record
4374        // the same thing and report different classes, so a flag with no value could not say which
4375        // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
4376        // argument: this is the one plane where an edge nobody interposed costs a false report.
4377        let (opts, _) = compile(&["a.c"]);
4378        assert_eq!(opts.races, rucc_session::Races::Off);
4379
4380        let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
4381        assert_eq!(opts.races, rucc_session::Races::Metadata);
4382
4383        let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
4384        assert_eq!(opts.races, rucc_session::Races::Pointer);
4385
4386        // Last one wins, as it does for every other mode flag here.
4387        let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
4388        assert_eq!(opts.races, rucc_session::Races::Off);
4389
4390        let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
4391        assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
4392    }
4393
4394    #[test]
4395    fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
4396        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4397        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4398        let text = print_pipeline(&opts);
4399        assert!(text.starts_with("level: -O2\n"), "{text}");
4400        assert!(text.contains("fold"), "{text}");
4401
4402        let a = parse_args(&args(&["--print-pipeline"])).unwrap();
4403        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4404        // Two passes run at `-O0` and neither is an optimization. The first moves what
4405        // `__builtin_expect` said onto the branch and takes the instruction away, so that nothing
4406        // past the optimizer has to know the instruction exists. The second removes code nothing
4407        // reaches. See issue 359.
4408        assert!(print_pipeline(&opts).contains("1: expect,"), "{}", print_pipeline(&opts));
4409        assert!(print_pipeline(&opts).contains("2: simplify-cfg,"), "{}", print_pipeline(&opts));
4410
4411        let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
4412        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4413        // The second turns off and the first does not, because nothing below the optimizer lowers
4414        // what it removes, so `-fno-expect` is a compile that stops rather than one that runs.
4415        let text = print_pipeline(&opts);
4416        assert!(text.contains("1: expect,"), "{text}");
4417        assert!(!text.contains("simplify-cfg"), "{text}");
4418    }
4419
4420    #[test]
4421    fn print_pipeline_takes_the_toggles_into_account() {
4422        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
4423        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4424        let text = print_pipeline(&opts);
4425        // The one that was named is gone and the rest of the level is not, which is the whole
4426        // of what a toggle promises.
4427        assert!(!text.contains("fold"), "{text}");
4428        assert!(text.contains("dce"), "{text}");
4429
4430        // Every pass the compiler has, named off. Built from the registry rather than written
4431        // out, so a pass added later is turned off here too and this keeps testing the thing it
4432        // is about, which is that the toggles can empty a level down to the passes that are not
4433        // optional. Those are named, because a listing that is all of them is a level nobody
4434        // emptied and the assertion would pass while saying nothing.
4435        let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
4436        off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
4437        let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
4438        let a = parse_args(&args(&spelled)).unwrap();
4439        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4440        let text = print_pipeline(&opts);
4441        let left: Vec<&str> =
4442            rucc_opt::PASSES.iter().filter(|p| p.required()).map(|p| p.name()).collect();
4443        assert_eq!(left, vec!["expect", "constant-p"], "{text}");
4444        for (at, name) in left.iter().enumerate() {
4445            assert!(text.contains(&format!("{}: {name},", at + 1)), "{text}");
4446        }
4447        assert!(!text.contains("dce"), "{text}");
4448    }
4449
4450    #[test]
4451    fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
4452        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4453        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4454        assert!(!print_pipeline(&opts).contains("global fuel"));
4455
4456        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
4457        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4458        let text = print_pipeline(&opts);
4459        // Because the listing is the answer to what this compilation will do, and a run that
4460        // stops after four rewrites is not doing what the level says it does.
4461        assert!(text.contains("global fuel: 4"), "{text}");
4462    }
4463
4464    /// A pass is turned on and off by its own name, and the order the flags were given in is
4465    /// kept, because the last spelling of a name is the one that decides.
4466    #[test]
4467    fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
4468        let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
4469        assert_eq!(
4470            opts.passes,
4471            [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
4472        );
4473
4474        let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
4475        assert!(e.message.contains("unknown option"), "{}", e.message);
4476    }
4477
4478    #[test]
4479    fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
4480        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
4481        assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
4482
4483        let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
4484        assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
4485        let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
4486        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
4487        let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
4488        assert!(e.message.contains("not a number"), "{}", e.message);
4489    }
4490
4491    #[test]
4492    fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
4493        let (opts, _) = compile(&["-c", "-O2", "a.c"]);
4494        assert_eq!(opts.pass_fuel_global, None);
4495
4496        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
4497        assert_eq!(opts.pass_fuel_global, Some(12));
4498        // And it is not the per pass flag with a longer name, so neither spelling swallows the
4499        // other.
4500        assert!(opts.pass_fuel.is_empty());
4501
4502        let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
4503        assert!(e.message.contains("not a number"), "{}", e.message);
4504    }
4505
4506    #[test]
4507    fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
4508        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
4509        assert_eq!(
4510            opts.pass_gates,
4511            [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
4512            "the order is what decides, so it has to survive the parse"
4513        );
4514
4515        let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
4516        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
4517        let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
4518        assert!(e.message.contains("ends before it starts"), "{}", e.message);
4519        let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
4520        assert!(e.message.contains("is empty"), "{}", e.message);
4521    }
4522
4523    #[test]
4524    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
4525        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
4526        let text = print_pipeline(&opts);
4527        assert!(text.contains("fold, "), "{text}");
4528        assert!(text.contains("[off for main]"), "{text}");
4529    }
4530
4531    /// The spelling is checked while the arguments are read, because a dump that names a pass
4532    /// this compiler does not have is a typo, and a typo found after the compilation has run is
4533    /// found too late to be any use.
4534    #[test]
4535    fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
4536        let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
4537        assert_eq!(opts.dump_ir, ["all", "after-fold"]);
4538
4539        let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
4540        assert!(e.message.contains("nosuch"), "{}", e.message);
4541        assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
4542    }
4543
4544    /// Every spelling `-fopt-info` takes, and the one it does not.
4545    ///
4546    /// The keywords are checked here for the same reason a dump's pass name is: a person who
4547    /// misspelled one gets no output, and no output is also what a compilation where nothing
4548    /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
4549    #[test]
4550    fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
4551        let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
4552        assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
4553        assert_eq!(opts.opt_info_file, None, "and goes to standard error");
4554
4555        let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
4556        assert_eq!(opts.opt_info, ["missed-note"]);
4557
4558        // Two flags add up rather than the second replacing the first, and the file is the last
4559        // one that named a file, which is how GCC treats both.
4560        let (opts, _) =
4561            compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
4562        assert_eq!(opts.opt_info, ["missed", "all"]);
4563        assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
4564
4565        let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
4566        assert!(e.message.contains("vectorized"), "{}", e.message);
4567        assert!(e.message.contains("`missed`"), "{}", e.message);
4568        let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
4569        assert!(e.message.contains("no file"), "{}", e.message);
4570    }
4571
4572    #[test]
4573    fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
4574        let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
4575        assert!(opts.verify_each);
4576        assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
4577    }
4578
4579    #[test]
4580    fn dash_o_needs_an_argument() {
4581        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
4582        assert_eq!(e.message, "-o requires an argument");
4583    }
4584
4585    #[test]
4586    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
4587        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
4588        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
4589        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
4590    }
4591
4592    #[test]
4593    fn the_include_flags_land_on_the_chain_each_one_names() {
4594        // A sysroot with nothing under it, so that the library's own directories are the
4595        // same on every machine this test runs on, which is none of them.
4596        let (opts, _) = compile(&[
4597            "-Ii",
4598            "-iquote",
4599            "q",
4600            "-isystem",
4601            "sys",
4602            "-idirafter",
4603            "after",
4604            "--sysroot=/nowhere-at-all",
4605            "a.c",
4606        ]);
4607        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4608        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
4609        // which is where GCC puts its own: a directory the user named outranks ours.
4610        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
4611        assert!(!opts.search.dirs()[1].is_system);
4612        assert!(opts.search.dirs()[2].is_system);
4613    }
4614
4615    #[test]
4616    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
4617        // Which machine this runs on decides what is on the path, so the test is about the
4618        // order rather than about the names: ours is on it, the library's follow it, and
4619        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
4620        let (opts, _) = compile(&["a.c"]);
4621        let dirs = opts.search.dirs();
4622        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
4623        assert_eq!(ours, Some(0), "{dirs:?}");
4624        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
4625        let (bare, _) = compile(&["-nostdinc", "a.c"]);
4626        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
4627    }
4628
4629    #[test]
4630    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
4631        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
4632        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4633        assert_eq!(dirs, ["sys", runtime::DIR]);
4634    }
4635
4636    #[test]
4637    fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
4638        // The target is not the machine this test runs on wherever it runs, so the answer is the
4639        // same on all of them: the libc's two include directories for that target, the kernel's
4640        // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
4641        // program that builds on the build machine and is wrong everywhere else.
4642        let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
4643        let dirs: Vec<&std::path::Path> =
4644            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4645        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
4646        let kernel = cache::dir().join("kernel-headers");
4647        assert_eq!(dirs.len(), 5, "{dirs:?}");
4648        assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
4649        assert_eq!(dirs[1], root.join("include").join("riscv64"));
4650        assert_eq!(dirs[2], root.join("include").join("generic"));
4651        // The kernel's, which are beside the sysroots rather than inside one, because every target
4652        // that shares an architecture reads the same files.
4653        assert_eq!(dirs[3], kernel.join("riscv"));
4654        assert_eq!(dirs[4], kernel.join("generic"));
4655    }
4656
4657    #[test]
4658    fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
4659        // The other side of the same answer. Windows has its own system headers and no `linux/` at
4660        // all, so the list is the libc's own and the question never arises, which is the `None` that
4661        // `link::cross_kernel` returns rather than a directory nothing would be found in.
4662        //
4663        // The libc's own is one directory rather than two here, because mingw-w64 publishes a single
4664        // header tree for every architecture and `Sysroot::splits_by_arch` says so.
4665        let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
4666        let dirs: Vec<&std::path::Path> =
4667            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4668        assert_eq!(dirs.len(), 2, "{dirs:?}");
4669        assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
4670    }
4671
4672    #[test]
4673    fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
4674        // One tree serves every glibc release, so the release is what the target supplies, and the
4675        // condition is the same one that chose the directories. A host glibc and a tree somebody
4676        // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
4677        // different values is a warning on every compilation of every file.
4678        //
4679        // The architecture is chosen against this machine's rather than written down, because the
4680        // bundled tree is only in effect for a target that is not this machine. The first version of
4681        // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
4682        // Linux runner, so it passed here and failed there.
4683        //
4684        // Unless this machine has the distribution's cross packages for it and nothing fetched, and
4685        // then those are the headers and their own `features.h` says the release, as it does for a
4686        // tree somebody named.
4687        let gnu = format!("--target={}-linux-gnu", cross_arch());
4688        let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
4689        let (link, _) = linking(&[&gnu, "-c", "a.c"]);
4690        let distro = link::distro_cross(bundled.target, &link).is_some();
4691        assert_eq!(bundled.glibc_minor, if distro { None } else { Some(44) });
4692        let pin = format!("{gnu}.2.28");
4693        let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
4694        assert_eq!(pinned.glibc_minor, Some(28));
4695
4696        let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
4697        assert_eq!(named.glibc_minor, None);
4698        let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
4699        assert_eq!(none.glibc_minor, None);
4700        let musl = format!("--target={}-linux-musl", cross_arch());
4701        let (musl, _) = compile(&[&musl, "-c", "a.c"]);
4702        assert_eq!(musl.glibc_minor, None);
4703
4704        // And this machine's own target gets nothing, whatever this machine is, because its headers
4705        // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
4706        // that is the case this test had backwards; on a mac it is true for the other reason, which
4707        // is that Darwin is not a glibc target at all.
4708        if let Some(host) = Triple::host() {
4709            let native = format!("--target={}", host.tuple());
4710            let (native, _) = compile(&[&native, "-c", "a.c"]);
4711            assert_eq!(native.glibc_minor, None);
4712        }
4713    }
4714
4715    #[test]
4716    fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
4717        // The end to end half of the answer in `link::cross_for`. A release named for this machine's
4718        // own target is a cross compile, so the headers are the bundled tree's and the macro says
4719        // what was asked for rather than what this machine has.
4720        //
4721        // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
4722        // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
4723        // where the case lives.
4724        let Some(host) = Triple::host() else { return };
4725        if host.env != rucc_target::Env::Gnu {
4726            return;
4727        }
4728        let pin = format!("--target={}.2.28", host.tuple());
4729        let (opts, _) = compile(&[&pin, "-c", "a.c"]);
4730        assert_eq!(opts.glibc_minor, Some(28));
4731        let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
4732        let dirs: Vec<&std::path::Path> =
4733            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4734        assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
4735        // And nothing of this machine's, which is the failure this was: a program compiled against
4736        // 2.44 declarations and told it was 2.28.
4737        assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
4738    }
4739
4740    /// An architecture that is not this machine's, out of the three the driver has targets for.
4741    ///
4742    /// A test about the bundled sysroot has to name a target that is not the host, because a target
4743    /// that is the host reads the host's own headers and libraries. Asking which machine this is
4744    /// beats picking a row and hoping, and it is two lines.
4745    fn cross_arch() -> &'static str {
4746        match Triple::host().map(|host| host.arch) {
4747            Some(rucc_target::Arch::X86_64) => "aarch64",
4748            _ => "x86_64",
4749        }
4750    }
4751
4752    #[test]
4753    fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
4754        // Both versions in the message, because the two things a person can do about it are pin a
4755        // release the tree has and name a sysroot that has the one they asked for, and neither is a
4756        // choice they can make without knowing which release the tree is.
4757        //
4758        // Not this machine's architecture, for the reason the test above gives: the refusal is about
4759        // the bundled tree, and the bundled tree is not what a target that is this machine reads.
4760        let target = format!("--target={}-linux-gnu.2.99", cross_arch());
4761        let message = refused(&[&target, "-c", "a.c"]);
4762        assert!(message.contains("asked for glibc 2.99"), "{message}");
4763        assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
4764        assert!(message.contains("--sysroot"), "{message}");
4765    }
4766
4767    #[test]
4768    fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
4769        // The tree somebody assembled beats the one we would build, on the headers as on the
4770        // libraries. It is empty here, which is why the list comes out short: the directories under
4771        // it are checked for rather than assumed, and a tree that is not there offers nothing.
4772        let (opts, _) =
4773            compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
4774        let dirs: Vec<&std::path::Path> =
4775            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4776        assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
4777    }
4778
4779    #[test]
4780    fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
4781        let (opts, _) =
4782            compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
4783        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4784        assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
4785        // An angled include sees only what came after the flag.
4786        assert_eq!(opts.search.start(IncludeForm::Angled), 2);
4787        assert!(!opts.search.searches_current_dir());
4788    }
4789
4790    #[test]
4791    fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
4792        let (opts, _) = compile(&[
4793            "-iprefix",
4794            "/tools/",
4795            "-iwithprefix",
4796            "late",
4797            "-iwithprefixbefore",
4798            "early",
4799            "-iprefix",
4800            "/other/",
4801            "-iwithprefix",
4802            "last",
4803            "-nostdinc",
4804            "a.c",
4805        ]);
4806        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4807        // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
4808        // puts them rather than where its manual says it does.
4809        assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
4810        assert!(!opts.search.dirs()[0].is_system);
4811        assert!(opts.search.dirs()[1].is_system);
4812    }
4813
4814    #[test]
4815    fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
4816        let (opts, _) =
4817            compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
4818        let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
4819        assert_eq!(names, ["one.h", "two.h", "3.h"]);
4820        assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
4821    }
4822
4823    #[test]
4824    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
4825        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
4826        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4827        assert_eq!(dirs, ["i"]);
4828    }
4829
4830    #[test]
4831    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
4832        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
4833        assert_eq!(opts.std, Std::C11);
4834        assert!(opts.gnu_extensions);
4835
4836        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
4837        assert_eq!(opts.std, Std::C99);
4838        assert!(!opts.gnu_extensions);
4839
4840        let (opts, _) = compile(&["-ansi", "a.c"]);
4841        assert_eq!(opts.std, Std::C89);
4842        assert!(!opts.gnu_extensions);
4843
4844        let (opts, _) = compile(&["-std=gnu2y", "a.c"]);
4845        assert_eq!(opts.std, Std::C2y);
4846        assert!(opts.gnu_extensions);
4847
4848        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
4849        assert!(e.message.contains("unknown dialect"), "{}", e.message);
4850    }
4851
4852    #[test]
4853    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
4854        let (opts, _) = compile(&["-dM", "a.c"]);
4855        assert!(opts.dumps.macros);
4856
4857        // Packed, the way GCC takes them, and a letter in the family we have not written yet
4858        // is accepted and does nothing rather than failing a build.
4859        let (opts, _) = compile(&["-dDM", "a.c"]);
4860        assert!(opts.dumps.macros);
4861        let (opts, _) = compile(&["-dD", "a.c"]);
4862        assert!(!opts.dumps.macros);
4863
4864        let (opts, _) = compile(&["a.c"]);
4865        assert!(!opts.dumps.any());
4866
4867        // `-dumpversion` is a different flag that happens to start the same way, and it is read
4868        // as itself rather than as a dump of nothing.
4869        assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
4870    }
4871
4872    #[test]
4873    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
4874        let (opts, _) = compile(&["a.c"]);
4875        assert_eq!(
4876            opts.gnuc,
4877            GnucVersion { major: 16, minor: 0, patch: 0 },
4878            "the release this compiler is written against, and the earliest one of that series"
4879        );
4880
4881        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
4882        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
4883
4884        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
4885        // patchlevel and a harness that pastes that back has to be understood.
4886        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
4887        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
4888
4889        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
4890        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
4891
4892        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
4893        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
4894
4895        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
4896        assert!(e.message.contains("more than three"), "{}", e.message);
4897    }
4898
4899    #[test]
4900    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
4901        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
4902        assert!(opts.pedantic);
4903        assert_eq!(opts.std, Std::C17);
4904
4905        // The `-W` family's name for it, which is what a build that groups its warning flags
4906        // tends to write.
4907        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
4908        assert!(opts.pedantic);
4909
4910        let (opts, _) = compile(&["-std=c17", "a.c"]);
4911        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
4912    }
4913
4914    #[test]
4915    fn dash_p_and_dash_ffreestanding_reach_the_options() {
4916        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
4917        assert!(!opts.line_markers);
4918        assert!(!opts.hosted);
4919        assert_eq!(opts.emit, EmitKind::Preprocessed);
4920    }
4921
4922    /// The two ways a build says it means its own function by a name the C library also has.
4923    ///
4924    /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
4925    /// build writes when it means its own `memcpy` and the library's everything else. The name is
4926    /// kept as it was written and not checked against anything, because a program is allowed to
4927    /// mean something by a name this compiler has never heard of.
4928    #[test]
4929    fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
4930        let (opts, _) = compile(&["-c", "a.c"]);
4931        assert!(opts.builtins, "a library name means the library function by default");
4932        assert!(opts.no_builtin.is_empty());
4933
4934        let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
4935        assert!(!opts.builtins);
4936
4937        let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
4938        assert!(opts.builtins, "the last mention decides");
4939
4940        let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
4941        assert!(opts.builtins, "one name is not the family");
4942        assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
4943    }
4944
4945    /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
4946    /// and which was refused as an unknown option until now.
4947    ///
4948    /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
4949    /// the address across a component boundary, and nothing derives anything from that promise
4950    /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
4951    /// over a distinction this compiler does not make.
4952    #[test]
4953    fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
4954        let (opts, _) = compile(&["-c", "a.c"]);
4955        assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
4956
4957        for (written, wanted) in [
4958            ("default", Visibility::Default),
4959            ("hidden", Visibility::Hidden),
4960            ("internal", Visibility::Hidden),
4961            ("protected", Visibility::Protected),
4962        ] {
4963            let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
4964            assert_eq!(opts.visibility, wanted, "{written}");
4965        }
4966
4967        // The last mention decides, which is what every other flag of this shape does and what a
4968        // build that turns something off for one directory relies on.
4969        let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
4970        assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
4971
4972        // A spelling gcc does not take is refused rather than read as the default, because a
4973        // build that meant hidden and got exported is a library with the wrong interface and
4974        // nothing said about it anywhere.
4975        let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
4976        assert!(failed.to_string().contains("is not a visibility"), "{failed}");
4977    }
4978
4979    /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
4980    /// described, and the values are gcc 16's three.
4981    #[test]
4982    fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
4983        let (opts, _) = compile(&["-c", "a.c"]);
4984        assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
4985
4986        for (written, wanted) in
4987            [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
4988        {
4989            let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
4990            assert_eq!(opts.fp_contract, wanted, "{written}");
4991        }
4992
4993        let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
4994        assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
4995
4996        // Refused rather than read as one of the three, because a build that asked for no fusing
4997        // and was given the default would be one whose numbers change and whose command line says
4998        // they should not. gcc refuses the same spellings and names the same three in its message.
4999        for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
5000            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5001            assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
5002        }
5003
5004        // And the other one that takes a value, which is taken and kept nowhere: every operation
5005        // here is computed in the type it was written in, so `standard` is what happens and the
5006        // other two are permission to do something this does not do.
5007        let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
5008        assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
5009    }
5010
5011    /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
5012    /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
5013    /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
5014    #[test]
5015    fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
5016        let (opts, _) = compile(&["-c", "a.c"]);
5017        assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
5018        assert!(opts.prefix_map.debug.is_empty(), "nor here");
5019        assert!(opts.prefix_map.profile.is_empty(), "nor here");
5020
5021        let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
5022        assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
5023        assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
5024
5025        let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
5026        assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
5027        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5028
5029        let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
5030        assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
5031        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5032
5033        let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
5034        for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
5035            assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
5036        }
5037
5038        // Every mention is kept and the last one that matches wins, unlike the flags above whose
5039        // last mention replaces the earlier ones. A build writes one of these per source root and
5040        // expects all of them to be in force, which is the whole point of a list.
5041        let (opts, _) =
5042            compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
5043        assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
5044        assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
5045
5046        // An argument with no `=` is refused rather than ignored, because a build whose paths were
5047        // meant to be rewritten and were not is one that ships the build directory's name and says
5048        // nothing about it. gcc refuses the same thing.
5049        for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
5050            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5051            assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
5052        }
5053    }
5054
5055    /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
5056    /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
5057    /// one. A kernel and an embedded image are both linked that way.
5058    ///
5059    /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
5060    /// the other is a build that measured something: splitting the code is nearly free at link time
5061    /// and splitting the data can defeat the linker's ordering of what is next to what.
5062    #[test]
5063    fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
5064        let (opts, _) = compile(&["-c", "a.c"]);
5065        assert!(!opts.function_sections, "one text section unless something says otherwise");
5066        assert!(!opts.data_sections);
5067
5068        let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
5069        assert!(opts.function_sections);
5070        assert!(!opts.data_sections, "one flag is not the other");
5071
5072        let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
5073        assert!(opts.data_sections);
5074        assert!(!opts.function_sections);
5075
5076        // Both directions taken, and the off one is what happens anyway rather than a refusal,
5077        // since a build that writes it is asking for the default.
5078        let (opts, _) = compile(&[
5079            "-c",
5080            "-ffunction-sections",
5081            "-fno-function-sections",
5082            "-fdata-sections",
5083            "-fno-data-sections",
5084            "a.c",
5085        ]);
5086        assert!(!opts.function_sections, "the last mention decides");
5087        assert!(!opts.data_sections, "the last mention decides");
5088    }
5089
5090    /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
5091    /// line, since the dialect asks for GNU's reading further in rather than through this.
5092    #[test]
5093    fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
5094        let (opts, _) = compile(&["-c", "a.c"]);
5095        assert!(!opts.gnu89_inline, "C's reading of inline by default");
5096
5097        let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
5098        assert!(opts.gnu89_inline);
5099
5100        let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
5101        assert!(!opts.gnu89_inline, "the last mention decides");
5102
5103        // The C89 dialects are under GNU's reading whether this was written or not, so the flag
5104        // stays off there and the dialect is what the checker and the macro set both ask. That is
5105        // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
5106        // dialect already has. gcc refuses that command line, which is measured in the issue.
5107        let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
5108        assert!(!opts.gnu89_inline);
5109    }
5110
5111    /// Both spellings of both frame flags, since a build that wants one usually writes the
5112    /// other beside it for the one file that has to be compiled the ordinary way.
5113    #[test]
5114    fn the_two_frame_flags_are_read_in_both_directions() {
5115        let (opts, _) = compile(&["-c", "a.c"]);
5116        assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
5117        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
5118
5119        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
5120        assert!(opts.frame_pointer);
5121        assert!(!opts.red_zone);
5122
5123        let (opts, _) = compile(&[
5124            "-c",
5125            "-fno-omit-frame-pointer",
5126            "-fomit-frame-pointer",
5127            "-mno-red-zone",
5128            "-mred-zone",
5129            "a.c",
5130        ]);
5131        assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
5132        assert!(opts.red_zone);
5133    }
5134
5135    /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
5136    /// spelled three ways because a build that turns one off writes whichever it turned on.
5137    #[test]
5138    fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
5139        let (opts, _) = compile(&["-c", "a.c"]);
5140        assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
5141
5142        for (flag, want) in [
5143            ("-fstack-protector", Protector::Buffers),
5144            ("-fstack-protector-strong", Protector::Strong),
5145            ("-fstack-protector-all", Protector::All),
5146        ] {
5147            let (opts, _) = compile(&["-c", flag, "a.c"]);
5148            assert_eq!(opts.protector, want, "{flag}");
5149        }
5150
5151        // What a package build does: the strong one in the global flags and one directory that
5152        // cannot have a protector turning it off on the line after.
5153        for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
5154            let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
5155            assert_eq!(opts.protector, Protector::None, "{off}");
5156        }
5157        let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
5158        assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
5159    }
5160
5161    /// A switch rather than a level, because how a frame is taken is one question and which
5162    /// functions get a canary is another, and gcc spells it that way for the same reason.
5163    #[test]
5164    fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
5165        let (opts, _) = compile(&["-c", "a.c"]);
5166        assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
5167
5168        let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
5169        assert!(opts.stack_clash);
5170
5171        // The same shape a package build uses for the protector: on in the global flags and off
5172        // for the one directory that cannot have it.
5173        let (opts, _) =
5174            compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
5175        assert!(!opts.stack_clash);
5176        let (opts, _) =
5177            compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
5178        assert!(opts.stack_clash, "the last one wins either way round");
5179
5180        // The two are independent, since one is about the frame and the other about the function.
5181        let (opts, _) =
5182            compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
5183        assert!(opts.stack_clash);
5184        assert_eq!(opts.protector, Protector::Strong);
5185    }
5186
5187    /// One flag with an argument rather than a family of spellings, because what it asks about is
5188    /// which of the two edges of a control flow transfer is checked and the two are not separate
5189    /// questions to the hardware.
5190    #[test]
5191    fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
5192        let (opts, _) = compile(&["-c", "a.c"]);
5193        assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
5194
5195        for (arg, want) in [
5196            ("-fcf-protection", Control::Full),
5197            ("-fcf-protection=full", Control::Full),
5198            ("-fcf-protection=branch", Control::Branch),
5199            ("-fcf-protection=return", Control::Return),
5200            ("-fcf-protection=none", Control::None),
5201            ("-fcf-protection=check", Control::Check),
5202        ] {
5203            let (opts, _) = compile(&["-c", arg, "a.c"]);
5204            assert_eq!(opts.control, want, "{arg}");
5205        }
5206
5207        // The shape a package build uses: on in the global flags and off for the one directory
5208        // that cannot have it, whichever of the two spellings of off it reaches for.
5209        let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
5210        assert_eq!(opts.control, Control::None);
5211        let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
5212        assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
5213    }
5214
5215    /// The profiler is asked for by two spellings, and where its hook goes by two more.
5216    ///
5217    /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
5218    /// asks for no call, which is what gcc does with it, and a build system that sets it globally
5219    /// and asks for the profile per directory needs that to be true rather than an error.
5220    ///
5221    /// The link is asserted alongside, because the flag changes it too and a build that compiled
5222    /// with it and linked without it is a program that calls the hook everywhere and never writes a
5223    /// profile.
5224    #[test]
5225    fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
5226        let (opts, _) = compile(&["-c", "a.c"]);
5227        assert!(!opts.profile);
5228        assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
5229
5230        for arg in ["-pg", "-p"] {
5231            let (opts, _) = compile(&["-c", arg, "a.c"]);
5232            assert!(opts.profile, "{arg}");
5233            let (link, _) = linking(&[arg, "a.c"]);
5234            assert!(link.profile, "{arg} changes the link as well");
5235        }
5236
5237        for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
5238            let (opts, _) = compile(&["-c", arg, "a.c"]);
5239            assert_eq!(opts.hook, want, "{arg}");
5240            assert!(!opts.profile, "{arg} asks for no call of its own");
5241        }
5242
5243        let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
5244        assert_eq!(opts.hook, Hook::Late, "the last one wins");
5245        assert!(opts.profile);
5246    }
5247
5248    /// How much room a patcher is promised, which is one number or two.
5249    ///
5250    /// A command line that did not ask is asserted alongside, because the flag has to be written to
5251    /// mean anything and a build that reserved room nobody asked for would grow every function in
5252    /// it for nothing.
5253    #[test]
5254    fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
5255        let (opts, _) = compile(&["-c", "a.c"]);
5256        assert_eq!(opts.patchable, Patchable::default());
5257        assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
5258
5259        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
5260        assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
5261
5262        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
5263        assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
5264        assert_eq!(opts.patchable.after(), 2);
5265
5266        // The last one wins, which is what every other flag of this shape does and what a build
5267        // that adds one to a command line it did not write is relying on.
5268        let (opts, _) = compile(&[
5269            "-c",
5270            "-fpatchable-function-entry=5,3",
5271            "-fpatchable-function-entry=2",
5272            "a.c",
5273        ]);
5274        assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
5275    }
5276
5277    /// And a request nothing could satisfy is refused rather than rounded into one that can be.
5278    #[test]
5279    fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
5280        for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
5281            let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
5282            assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
5283        }
5284    }
5285
5286    /// What wraps rather than being undefined, which is two questions and three flags.
5287    ///
5288    /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
5289    /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
5290    /// only what it asked for.
5291    #[test]
5292    fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
5293        let (opts, _) = compile(&["-c", "a.c"]);
5294        assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
5295
5296        let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
5297        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5298
5299        let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
5300        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
5301
5302        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
5303        assert_eq!(opts.wrapping, Wrapping::ALL);
5304
5305        // And the last one wins, in both directions. A build that turns one of these on globally
5306        // and off for one directory is relying on that, and so is one that writes the pair and
5307        // then takes half of it back.
5308        let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
5309        assert_eq!(opts.wrapping, Wrapping::NONE);
5310
5311        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
5312        assert_eq!(opts.wrapping, Wrapping::NONE);
5313
5314        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
5315        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5316    }
5317
5318    /// And the other answer to the signed question cannot be held at the same time as the first.
5319    ///
5320    /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
5321    /// resolves it by letting the last one win rather than by reporting anything. That was measured
5322    /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
5323    /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
5324    #[test]
5325    fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
5326        let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
5327        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5328
5329        let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
5330        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5331
5332        let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
5333        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5334
5335        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
5336        assert_eq!(opts.wrapping, Wrapping::ALL);
5337
5338        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
5339        assert_eq!(opts.wrapping, Wrapping::NONE);
5340
5341        // And the flag that says what may be assumed says nothing about what happens, so it leaves
5342        // this alone where it takes the wrapping away. gcc does the same.
5343        let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
5344        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5345    }
5346
5347    /// What a plain `char` is, which is four spellings of two answers and nothing by default.
5348    ///
5349    /// Nothing is the target's own answer and has to stay distinct from both of the others, since
5350    /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
5351    /// The negative spellings are the other flag rather than a way of asking for the default, which
5352    /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
5353    /// `-fno-unsigned-char` does not.
5354    #[test]
5355    fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
5356        let (opts, _) = compile(&["-c", "a.c"]);
5357        assert_eq!(opts.char_signed, None);
5358
5359        for flag in ["-fsigned-char", "-fno-unsigned-char"] {
5360            let (opts, _) = compile(&["-c", flag, "a.c"]);
5361            assert_eq!(opts.char_signed, Some(true), "{flag}");
5362        }
5363
5364        for flag in ["-funsigned-char", "-fno-signed-char"] {
5365            let (opts, _) = compile(&["-c", flag, "a.c"]);
5366            assert_eq!(opts.char_signed, Some(false), "{flag}");
5367        }
5368
5369        // And the last one wins, which is what a build that sets one globally and the other for a
5370        // directory relies on.
5371        let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
5372        assert_eq!(opts.char_signed, Some(true));
5373
5374        // And what is asked for reaches the target, because that is what every other part of the
5375        // compiler asks. The triple is one whose own answer is the opposite, so a session that
5376        // ignored the flag would still read as signed here.
5377        let (opts, _) =
5378            compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
5379        assert!(Session::new(*opts).target.char_is_signed);
5380        let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
5381        assert!(!Session::new(*opts).target.char_is_signed);
5382    }
5383
5384    /// And the size of an enumeration, which is one question with two spellings.
5385    #[test]
5386    fn the_smallest_enumeration_is_asked_for_and_taken_back() {
5387        let (opts, _) = compile(&["-c", "a.c"]);
5388        assert!(!opts.short_enums);
5389
5390        let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
5391        assert!(opts.short_enums);
5392
5393        let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
5394        assert!(!opts.short_enums);
5395
5396        let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
5397        assert!(opts.short_enums);
5398    }
5399
5400    /// And Microsoft's reading of an anonymous member, which the target answers where the command
5401    /// line said nothing. gcc's mingw build has it on and its Linux build has it off, so a header
5402    /// that closes a nameless union with a macro that expands to nothing is read the way the
5403    /// compiler that platform ships would read it.
5404    #[test]
5405    fn the_microsoft_reading_of_a_member_follows_the_target_until_it_is_asked_for() {
5406        // Named rather than left to the host, since the answer this asks for is the one a target
5407        // that is not Windows gives and on a Windows machine the host is not one of those.
5408        let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
5409        assert!(!Session::new(*opts).ms_extensions());
5410
5411        let (opts, _) = compile(&["-c", "--target=x86_64-pc-windows-gnu", "a.c"]);
5412        assert!(Session::new(*opts).ms_extensions());
5413
5414        let (opts, _) = compile(&["-c", "-fms-extensions", "a.c"]);
5415        assert!(Session::new(*opts).ms_extensions());
5416
5417        let (opts, _) =
5418            compile(&["-c", "--target=x86_64-pc-windows-gnu", "-fno-ms-extensions", "a.c"]);
5419        assert!(!Session::new(*opts).ms_extensions());
5420    }
5421
5422    /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
5423    ///
5424    /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
5425    /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
5426    /// family would report it as an unknown pass. Neither is the news the build wants.
5427    #[test]
5428    fn a_control_flow_protection_nothing_means_is_refused() {
5429        let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
5430        assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
5431        assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
5432    }
5433
5434    #[test]
5435    fn the_link_flags_are_collected_apart_from_the_compilation() {
5436        let (link, _) = linking(&[
5437            "-static",
5438            "-nostartfiles",
5439            "-rdynamic",
5440            "-s",
5441            "-fuse-ld=mold",
5442            "-L/opt/lib",
5443            "-B",
5444            "/opt/tools",
5445            "a.c",
5446        ]);
5447        assert!(link.is_static);
5448        assert!(link.no_startfiles);
5449        assert!(link.export_dynamic);
5450        assert!(link.strip);
5451        assert_eq!(link.use_ld.as_deref(), Some("mold"));
5452        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
5453        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
5454    }
5455
5456    #[test]
5457    fn a_comma_in_dash_wl_separates_two_arguments() {
5458        // The target is written down because the name of the object is derived from it, and `a.o`
5459        // on a Linux host is `a.obj` on a Windows one. What is under test is the splitting of the
5460        // argument, which has nothing to do with either.
5461        let (_, plan) = linking(&[LINUX, "-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
5462        let link = plan.link.expect("expected a link step");
5463        assert_eq!(
5464            link.inputs,
5465            vec![
5466                link::Item::Linker("-rpath".into()),
5467                link::Item::Linker("/opt/lib".into()),
5468                link::Item::Linker("--as-needed".into()),
5469                link::Item::File("a.o".into()),
5470            ]
5471        );
5472    }
5473
5474    #[test]
5475    fn a_word_for_the_linker_keeps_its_place_among_the_files_too() {
5476        // What libtool writes around a set of convenience archives, and what #1279 was. Both words
5477        // are about the files between them, so the pair collected out of the line and appended to
5478        // the end is two options that bracket nothing and an archive that went in empty.
5479        let (_, plan) = linking(&[
5480            "--target=x86_64-unknown-linux-gnu",
5481            "a.c",
5482            "-Wl,--whole-archive",
5483            "libaesni.a",
5484            "-Wl,--no-whole-archive",
5485            "-lm",
5486        ]);
5487        let link = plan.link.expect("expected a link step");
5488        assert_eq!(
5489            link.inputs,
5490            vec![
5491                link::Item::File("a.o".into()),
5492                link::Item::Linker("--whole-archive".into()),
5493                link::Item::File("libaesni.a".into()),
5494                link::Item::Linker("--no-whole-archive".into()),
5495                link::Item::Library("m".into()),
5496            ]
5497        );
5498        // And it is not a job, because there is nothing to compile in a word for the linker.
5499        assert_eq!(plan.jobs.len(), 2);
5500    }
5501
5502    #[test]
5503    fn a_word_for_the_linker_on_a_dash_c_line_is_dropped_without_a_word() {
5504        // GCC says nothing about one either. `-Wl,` on a compile line is what a build system
5505        // writes when one variable holds the flags for both, and a note here would be a note on
5506        // every compile of every autotools project.
5507        let (_, plan) = linking(&["-c", "-Wl,--as-needed", "a.c"]);
5508        assert!(plan.link.is_none());
5509        assert!(plan.notes.is_empty(), "{:?}", plan.notes);
5510        assert_eq!(plan.jobs.len(), 1);
5511    }
5512
5513    #[test]
5514    fn a_library_keeps_its_place_between_the_objects() {
5515        // Link order is semantic: `-lm` written between two files resolves for the one before
5516        // it and not for the one after, so a library cannot be collected into a list of its own.
5517        // The target is named because the suffix of an object is the target's and this asserts
5518        // on the names: the same command line on a Windows host plans two `.obj` files.
5519        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
5520        let link = plan.link.expect("expected a link step");
5521        assert_eq!(
5522            link.inputs,
5523            vec![
5524                link::Item::File("a.o".into()),
5525                link::Item::Library("m".into()),
5526                link::Item::File("b.o".into()),
5527            ]
5528        );
5529        // And it is not a job, because there is nothing to compile in a library.
5530        assert_eq!(plan.jobs.len(), 2);
5531    }
5532
5533    #[test]
5534    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
5535        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
5536        assert!(plan.link.is_none());
5537        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
5538    }
5539
5540    #[test]
5541    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
5542        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
5543        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
5544    }
5545
5546    fn printed(s: &[&str]) -> String {
5547        match parse_args(&args(s)).expect("expected an answer") {
5548            Action::Print(line) => line,
5549            other => panic!("expected an answer, got {other:?}"),
5550        }
5551    }
5552
5553    fn refused(s: &[&str]) -> String {
5554        parse_args(&args(s)).expect_err("expected a refusal").message
5555    }
5556
5557    #[test]
5558    fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
5559        // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
5560        // out whether a warning flag exists by passing it and looking at the exit status, so a
5561        // compiler that refuses one it does not know fails a script written for a newer GCC.
5562        let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
5563        assert!(!opts.warnings_are_errors);
5564        assert!(opts.warnings);
5565        // The two spellings that do mean something are still read.
5566        let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
5567        assert!(opts.warnings_are_errors);
5568        let (opts, _) = compile(&["-w", "-c", "a.c"]);
5569        assert!(!opts.warnings);
5570        // Off without being asked, the way gcc has it off, and both spellings are read.
5571        let (opts, _) = compile(&["-c", "a.c"]);
5572        assert!(!opts.system_header_warnings);
5573        let (opts, _) = compile(&["-Wsystem-headers", "-c", "a.c"]);
5574        assert!(opts.system_header_warnings);
5575        let (opts, _) = compile(&["-Wsystem-headers", "-Wno-system-headers", "-c", "a.c"]);
5576        assert!(!opts.system_header_warnings);
5577        let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
5578        assert!(opts.pedantic && opts.warnings_are_errors);
5579    }
5580
5581    #[test]
5582    fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
5583        // Every one of these says something about the output, so the wrong answer is silence.
5584        assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
5585        assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
5586        assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
5587        assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
5588        assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
5589        // The word size the target does not have, which is a target this compiler was not asked
5590        // for rather than a flag it does not know.
5591        let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
5592        assert!(no32.contains("32 bit target"), "{no32}");
5593    }
5594
5595    /// `-gz` and the two spellings of the split, which are the two questions about the shape of
5596    /// the debug output rather than about how much of it there is.
5597    ///
5598    /// Both answers here are about what happens when there is debug information to shape, and
5599    /// there is none yet, so what is being asserted is that the flags are read and remembered
5600    /// rather than that anything changed in the output. That is the whole of what taking them
5601    /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
5602    /// it comes to find out what the command line said.
5603    #[test]
5604    fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
5605        let (opts, _) = compile(&["-c", "a.c"]);
5606        assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
5607
5608        // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
5609        // which describes the flag without ever saying which algorithm it picks.
5610        assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
5611        for (spelling, want) in [
5612            ("none", Compress::None),
5613            ("zlib", Compress::Zlib),
5614            ("zlib-gnu", Compress::ZlibGnu),
5615            ("zstd", Compress::Zstd),
5616        ] {
5617            let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
5618            assert_eq!(opts.compress, want, "{spelling}");
5619        }
5620
5621        // A value nothing here has heard of is refused rather than rounded to the nearest one,
5622        // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
5623        // reader may not understand and would have no way of finding out.
5624        for bad in ["-gz=gzip", "-gz="] {
5625            let failed = refused(&[bad, "-c", "a.c"]);
5626            assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
5627        }
5628
5629        // The split is refused in the direction that would have written a file and taken in the
5630        // direction that describes what happens. A build system that names the `.dwo` as an
5631        // output has to hear about it now rather than at the point the file is missing.
5632        let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
5633        assert!(opts.debug_info, "the negative spelling says nothing about how much");
5634        let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
5635        assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
5636    }
5637
5638    /// The `-flto` family, which is the whole of an optimization this compiler does not do.
5639    ///
5640    /// Taken rather than refused because ignoring it gives a correct program that is slower than
5641    /// it could have been, which is section 4.1's hint about speed. The values are still held to
5642    /// gcc's, so a command line written for clang is told rather than quietly taken.
5643    #[test]
5644    fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
5645        let (opts, _) = compile(&["-c", "a.c"]);
5646        assert!(!opts.lto.requested, "nothing asks unless the command line does");
5647
5648        let (opts, _) = compile(&["-flto", "-c", "a.c"]);
5649        assert!(opts.lto.requested);
5650        assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
5651
5652        // The last of the two directions wins, the same as every other pair of `-f` spellings.
5653        assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
5654        assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
5655
5656        // A count is a count, and asking for one implies asking for the optimization.
5657        for (spelling, want) in [
5658            ("auto", LtoJobs::Auto),
5659            ("jobserver", LtoJobs::Jobserver),
5660            ("1", LtoJobs::One),
5661            ("8", LtoJobs::Count(8)),
5662        ] {
5663            let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
5664            assert_eq!(opts.lto.jobs, want, "{spelling}");
5665            assert!(opts.lto.requested, "{spelling} asks for it too");
5666        }
5667
5668        // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
5669        // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
5670        // different compiler and gets told so here rather than getting a serial link.
5671        for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
5672            let failed = refused(&[bad, "-c", "a.c"]);
5673            assert!(failed.contains("link time jobs"), "{bad}: {failed}");
5674        }
5675
5676        // How the program is cut up before the work is spread over it.
5677        assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
5678        for (spelling, want) in [
5679            ("balanced", Partition::Balanced),
5680            ("1to1", Partition::OneToOne),
5681            ("one", Partition::One),
5682            ("max", Partition::Max),
5683            ("none", Partition::None),
5684        ] {
5685            let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
5686            assert_eq!(opts.lto.partition, want, "{spelling}");
5687        }
5688        assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
5689
5690        // And how hard the bytecode is compressed on its way into the object, which is zstd's
5691        // range of levels and is the range gcc checks an argument against.
5692        assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
5693        assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
5694        let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
5695        assert_eq!(opts.lto.compression, Some(19));
5696        for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
5697            let failed = refused(&[bad, "-c", "a.c"]);
5698            assert!(failed.contains("compression level"), "{bad}: {failed}");
5699        }
5700
5701        // The two pairs that describe an arrangement rather than ask for one. Every object here
5702        // holds its machine code, so the fat spelling is what already happens and the other is a
5703        // smaller file rather than a different program, and the plugin pair is about a tool the
5704        // design in `spec/09-optimizer.md` never loads.
5705        for taken in [
5706            "-ffat-lto-objects",
5707            "-fno-fat-lto-objects",
5708            "-fuse-linker-plugin",
5709            "-fno-use-linker-plugin",
5710        ] {
5711            let (opts, _) = compile(&[taken, "-c", "a.c"]);
5712            assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
5713        }
5714    }
5715
5716    /// The profile family, which is the only one here that splits down the middle.
5717    ///
5718    /// Reading a profile is taken and writing one is refused, and the line between them is the one
5719    /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
5720    /// slower than it could have been, and ignoring a request to write them means a file the build
5721    /// declared as an output never appears.
5722    #[test]
5723    fn reading_a_profile_is_taken_and_writing_one_is_refused() {
5724        let (opts, _) = compile(&["-c", "a.c"]);
5725        assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
5726        assert_eq!(opts.profile_data.path, None);
5727
5728        let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
5729        assert!(opts.profile_data.requested);
5730        assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
5731
5732        let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
5733        assert!(opts.profile_data.requested, "naming a path asks for it too");
5734        assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
5735
5736        // The last of the two directions wins, the same as every other pair of `-f` spellings.
5737        assert!(
5738            !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
5739        );
5740        assert!(
5741            compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
5742        );
5743
5744        // The rest of the reading half, which is where the files are and three answers about what
5745        // to make of what is in them.
5746        let (opts, _) = compile(&[
5747            "-fprofile-dir=/build/profiles",
5748            "-fprofile-abs-path",
5749            "-fprofile-correction",
5750            "-fprofile-partial-training",
5751            "-c",
5752            "a.c",
5753        ]);
5754        assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
5755        assert!(opts.profile_data.absolute);
5756        assert!(opts.profile_data.correction);
5757        assert!(opts.profile_data.partial_training);
5758
5759        // Writing one, which is refused by name. The first four instrument the program and the
5760        // last writes a file beside the object, and a build that got neither and no message would
5761        // go on to optimize against counts that were never gathered.
5762        for writing in [
5763            "-fprofile-generate",
5764            "-fprofile-generate=/build/profiles",
5765            "-fprofile-arcs",
5766            "--coverage",
5767            "-fcondition-coverage",
5768            "-fpath-coverage",
5769        ] {
5770            let failed = refused(&[writing, "-c", "a.c"]);
5771            assert!(failed.contains("instrument"), "{writing}: {failed}");
5772        }
5773        assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
5774
5775        // The negative spellings of the refused half are what already happens, so they are taken.
5776        for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
5777            let (opts, _) = compile(&[taken, "-c", "a.c"]);
5778            assert!(!opts.profile_data.requested, "{taken} asks for nothing");
5779        }
5780
5781        // And the flags that describe the instrumentation that is refused above, which are checked
5782        // and dropped. Checked because a typo is worth finding here rather than on the day the
5783        // instrumentation lands.
5784        for taken in [
5785            "-fprofile-update=single",
5786            "-fprofile-update=atomic",
5787            "-fprofile-update=prefer-atomic",
5788            "-fprofile-reproducible=serial",
5789            "-fprofile-reproducible=parallel-runs",
5790            "-fprofile-reproducible=multithreaded",
5791            "-fprofile-values",
5792            "-fno-profile-values",
5793            "-fprofile-info-section",
5794            "-fprofile-filter-files=a.c",
5795            "-fprofile-exclude-files=b.c",
5796            "-fprofile-note=a.gcno",
5797        ] {
5798            let (opts, _) = compile(&[taken, "-c", "a.c"]);
5799            assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
5800        }
5801        assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
5802        assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
5803    }
5804
5805    /// The sanitizers, which are refused by name and are the one family refused for a reason that
5806    /// is not about the bytes.
5807    ///
5808    /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
5809    /// for one and was quietly given a program with no checks in it gets a test suite that passes
5810    /// for the wrong reason rather than a slower program.
5811    #[test]
5812    fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
5813        for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
5814            let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
5815            assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
5816            assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
5817        }
5818
5819        // A list is every name in it, and the first one still standing is the one named.
5820        let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
5821        assert!(failed.contains("address"), "{failed}");
5822
5823        // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
5824        // with a typo in it has a different problem from somebody who wrote a real one.
5825        for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
5826            let failed = refused(&[bad, "-c", "a.c"]);
5827            assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
5828        }
5829
5830        // gcc takes `all` only in the negative, and so does this.
5831        assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
5832
5833        // Asking and then taking it back is asking for nothing, which is why the answer waits for
5834        // the end of the line. A build whose shared flags turn a check on and whose rule for one
5835        // file turns it off again compiles that file here.
5836        for pair in [
5837            ["-fsanitize=address", "-fno-sanitize=address"],
5838            ["-fsanitize=address,undefined", "-fno-sanitize=all"],
5839            ["-fsanitize=undefined", "-fno-sanitize=undefined"],
5840        ] {
5841            let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
5842            assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
5843        }
5844        // And the other order still asks, because the last word is the one that counts.
5845        assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
5846
5847        // What a check does when it fires is an answer about checks that are refused, so there is
5848        // nothing left for it to change and it is taken.
5849        for taken in [
5850            "-fsanitize-recover=undefined",
5851            "-fno-sanitize-recover=all",
5852            "-fsanitize-trap=undefined",
5853            "-fno-sanitize-trap=all",
5854            "-fsanitize-undefined-trap-on-error",
5855            "-fsanitize-address-use-after-scope",
5856            "-fno-sanitize-address-use-after-scope",
5857            "-fsanitize-sections=.data",
5858        ] {
5859            let (opts, _) = compile(&[taken, "-c", "a.c"]);
5860            assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
5861        }
5862        assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
5863
5864        // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
5865        // feedback runs blind and never says so.
5866        let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
5867        assert!(failed.contains("feedback"), "{failed}");
5868        let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
5869        assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
5870    }
5871
5872    #[test]
5873    fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
5874        assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
5875        assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
5876        assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
5877    }
5878
5879    #[test]
5880    fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
5881        let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
5882        let (opts, _) =
5883            compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
5884        assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
5885        let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
5886        assert!(wrong.contains("sysv convention"), "{wrong}");
5887    }
5888
5889    #[test]
5890    fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
5891        let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
5892        assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
5893        // After the input, because a static link takes what it needs from a library when it
5894        // reaches it and not afterwards.
5895        let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
5896        assert_eq!(names, vec!["a.c"]);
5897    }
5898
5899    #[test]
5900    fn the_questions_a_build_system_asks_before_it_compiles_anything() {
5901        let target = "--target=x86_64-unknown-linux-gnu";
5902        assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
5903        assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
5904        assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
5905        assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
5906        // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
5907        // answer safe to paste into a link line whether or not the file is there.
5908        assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
5909        assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
5910        let dirs = printed(&[target, "-print-search-dirs"]);
5911        assert!(dirs.starts_with("install: "), "{dirs}");
5912        assert!(dirs.contains("\nlibraries: ="), "{dirs}");
5913    }
5914
5915    #[test]
5916    fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
5917        // A tree the user named is the answer whatever the target is, because it is the answer to
5918        // every other question too.
5919        assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
5920
5921        // A target that is no machine this suite runs on is read under the cache, and the answer is
5922        // the root rather than one of the directories under it, since what asks is looking for a
5923        // file of its own.
5924        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
5925        assert_eq!(
5926            printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
5927            root.display().to_string()
5928        );
5929
5930        // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
5931        // was configured without one rather than a `/` that would be a claim about the filesystem.
5932        let host = Triple::host().expect("a host this compiler knows");
5933        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot"]), "");
5934    }
5935
5936    #[test]
5937    fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
5938        // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
5939        // is the record that already has them, so the flag prints that rather than a second format.
5940        let manifest = "rucc sysroot manifest 3\n\
5941                        target\tx86_64-linux-musl\n\
5942                        kernel\t6.12\n\
5943                        include/generic/stdio.h\tmusl-1.2.5\t\
5944                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
5945                        0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
5946                        bundled\n\
5947                        lib/libc.so\tmusl-1.2.5\t\
5948                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
5949                        1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
5950                        generated\n";
5951        let tree = TempTree::new("provenance", &[("manifest", manifest)]);
5952        let sysroot = format!("--sysroot={}", tree.0.display());
5953        // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
5954        // the flag parses the record and renders it again rather than picking fields out of it. That
5955        // is the reason it prints a manifest and not a format of its own.
5956        //
5957        // The answer is the file without its last newline, because whatever prints it adds one. The
5958        // file is what somebody diffs the output against, so the two have to be the same bytes.
5959        assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
5960
5961        // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
5962        // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
5963        // tell it from a manifest with no inputs because that one still has its two header lines.
5964        let bare = TempTree::new("provenance-bare", &[]);
5965        assert_eq!(
5966            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
5967            ""
5968        );
5969
5970        // And a compile for this machine has no sysroot at all, which is the same empty answer
5971        // `-print-sysroot` gives for it.
5972        let host = Triple::host().expect("a host this compiler knows");
5973        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
5974
5975        // And the other spelling, which section 13.5 is the document that writes.
5976        assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
5977
5978        // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
5979        // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
5980        // the bytes it is over are the bytes of the file. The number here is that hash of the
5981        // fixture above, computed by `sha256sum` rather than by this compiler.
5982        assert_eq!(
5983            printed(&[&sysroot, "-print-sysroot-digest"]),
5984            "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
5985        );
5986        assert_eq!(
5987            printed(&[&sysroot, "--print-sysroot-digest"]),
5988            printed(&[&sysroot, "-print-sysroot-digest"])
5989        );
5990
5991        // And the two empty answers are empty here too, because a digest of nothing would read as a
5992        // claim about a sysroot rather than as the absence of one.
5993        assert_eq!(
5994            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
5995            ""
5996        );
5997        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
5998    }
5999
6000    #[test]
6001    fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
6002        // Passing a file we could not parse to whoever asked would make their parser the one that
6003        // finds the problem, and the three uses section 13.5 gives for this are all somebody else
6004        // parsing it.
6005        let tree = TempTree::new(
6006            "provenance-bad",
6007            &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
6008        );
6009        let message =
6010            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
6011        assert!(message.contains("manifest"), "{message}");
6012        assert!(message.contains("1 fields where an input has six"), "{message}");
6013
6014        // The digest is refused for the same file and for a stronger reason: a hash of bytes this
6015        // build cannot read would be a number that names a record nobody can act on.
6016        let digest =
6017            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
6018        assert_eq!(digest, message);
6019    }
6020
6021    #[test]
6022    fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
6023        let (opts, _) = compile(&["-M", "a.c"]);
6024        assert!(opts.deps.emit && opts.deps.instead_of_compiling);
6025        assert!(opts.deps.system_headers, "plain -M lists them");
6026        assert_eq!(opts.emit, EmitKind::Preprocessed);
6027
6028        // Even where a later flag asked for something else, because the family is a mode and
6029        // the mode is what the run is for.
6030        let (opts, _) = compile(&["-M", "-c", "a.c"]);
6031        assert_eq!(opts.emit, EmitKind::Preprocessed);
6032
6033        let (opts, _) = compile(&["-MM", "a.c"]);
6034        assert!(!opts.deps.system_headers);
6035    }
6036
6037    #[test]
6038    fn the_two_that_end_in_d_leave_the_compilation_alone() {
6039        let (opts, _) = compile(&["-MD", "-c", "a.c"]);
6040        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6041        assert!(opts.deps.system_headers);
6042        assert_eq!(opts.emit, EmitKind::Object);
6043
6044        let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
6045        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6046        assert!(!opts.deps.system_headers);
6047    }
6048
6049    #[test]
6050    fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
6051        // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
6052        // the answer, because the other one never asked the question.
6053        let (opts, _) = compile(&["-MM", "-M", "a.c"]);
6054        assert!(!opts.deps.system_headers);
6055        let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
6056        assert!(!opts.deps.system_headers);
6057        let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
6058        assert!(!opts.deps.system_headers);
6059    }
6060
6061    #[test]
6062    fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
6063        let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
6064        assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
6065    }
6066
6067    #[test]
6068    fn the_rest_of_the_family_is_a_file_and_a_switch() {
6069        let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
6070        assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
6071        assert!(opts.deps.phony);
6072
6073        for flag in ["-MF", "-MT", "-MQ"] {
6074            let e = parse_args(&args(&[flag])).unwrap_err();
6075            assert!(e.message.contains("requires an argument"), "{}", e.message);
6076        }
6077    }
6078
6079    /// A directory of sources for one test, removed when the test is done with it.
6080    struct TempTree(PathBuf);
6081
6082    impl Drop for TempTree {
6083        fn drop(&mut self) {
6084            let _ = std::fs::remove_dir_all(&self.0);
6085        }
6086    }
6087
6088    impl TempTree {
6089        fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
6090            let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
6091            let _ = std::fs::remove_dir_all(&dir);
6092            std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
6093            for (path, text) in files {
6094                let at = dir.join(path);
6095                if let Some(parent) = at.parent() {
6096                    std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
6097                }
6098                std::fs::write(&at, text).expect("writing a temporary file should work");
6099            }
6100            TempTree(dir)
6101        }
6102
6103        fn path(&self, name: &str) -> String {
6104            self.0.join(name).to_string_lossy().into_owned()
6105        }
6106    }
6107
6108    #[test]
6109    fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
6110        // End to end, because the list comes from the preprocessor and the format comes from
6111        // somewhere else, and a test of either half on its own would pass with the two of them
6112        // wired up backwards.
6113        let tree = TempTree::new(
6114            "found",
6115            &[
6116                ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
6117                ("one.h", "#define X 0\n"),
6118                ("two.h", "#include \"one.h\"\n"),
6119            ],
6120        );
6121        let out = tree.path("dep.d");
6122        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6123        assert_eq!(code, 0);
6124
6125        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6126        let names: Vec<&str> = text.split_whitespace().collect();
6127        // The target, the source, and each header once however many times it was reached.
6128        assert_eq!(names.first(), Some(&"a.o:"), "{text}");
6129        assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
6130        assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
6131        // And the `-o` went to the file the rule replaced, which is left empty rather than
6132        // absent because a makefile that named it as a target will look for it.
6133        assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
6134    }
6135
6136    #[test]
6137    fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
6138        // The multiple-include optimization means the second reach never opens the file. It is
6139        // still a file this translation unit was built from, so it is still in the rule.
6140        let tree = TempTree::new(
6141            "guarded",
6142            &[
6143                ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
6144                ("g.h", "#ifndef G\n#define G\n#endif\n"),
6145            ],
6146        );
6147        let out = tree.path("dep.d");
6148        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6149        assert_eq!(code, 0);
6150        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6151        assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
6152    }
6153
6154    #[test]
6155    fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
6156        // Measured against GCC rather than read: the two flags the other way round produce the
6157        // same output byte for byte, so the command line order between the two families does not
6158        // decide anything and the order within one does. The `-include` file here can only see
6159        // the definition if the `-imacros` file that was written after it ran first.
6160        let tree = TempTree::new(
6161            "preinclude",
6162            &[
6163                ("a.c", "int main(void) { return 0; }\n"),
6164                ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
6165                ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
6166            ],
6167        );
6168        let out = tree.path("a.i");
6169        let code = run(&args(&[
6170            "-E",
6171            "-include",
6172            &tree.path("i.h"),
6173            "-imacros",
6174            &tree.path("m.h"),
6175            "-o",
6176            &out,
6177            &tree.path("a.c"),
6178        ]));
6179        assert_eq!(code, 0);
6180        let text = std::fs::read_to_string(&out).expect("the output should have been written");
6181        assert!(text.contains("saw_it"), "{text}");
6182        // And the text of the `-imacros` file is thrown away, which is the whole difference
6183        // between the two flags.
6184        assert!(!text.contains("macros_text"), "{text}");
6185    }
6186
6187    #[test]
6188    fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
6189        let tree = TempTree::new(
6190            "preinclude-deps",
6191            &[
6192                ("a.c", "int main(void) { return 0; }\n"),
6193                ("i.h", "int from_include;\n"),
6194                ("m.h", "#define M 1\n"),
6195            ],
6196        );
6197        let out = tree.path("dep.d");
6198        let code = run(&args(&[
6199            "-MM",
6200            "-MF",
6201            &out,
6202            "-include",
6203            &tree.path("i.h"),
6204            "-imacros",
6205            &tree.path("m.h"),
6206            "-o",
6207            &tree.path("a.i"),
6208            &tree.path("a.c"),
6209        ]));
6210        assert_eq!(code, 0);
6211        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6212        assert!(text.contains("i.h"), "{text}");
6213        assert!(text.contains("m.h"), "{text}");
6214    }
6215
6216    #[test]
6217    fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
6218        // Including the directory of the source file, which is not on the path for these: the
6219        // command line was not written there, so a name in it is relative to where the compiler
6220        // was run rather than to where the source sits.
6221        let tree = TempTree::new(
6222            "preinclude-missing",
6223            &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
6224        );
6225        let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
6226        assert_eq!(code, 1);
6227    }
6228
6229    #[test]
6230    fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
6231        // The object a link goes through is in a temporary directory and is gone before `make`
6232        // reads any of this, so the rule that named it would be a rule for a file that is never
6233        // there. The target and the file are both the `-o`, which is the executable.
6234        let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
6235        assert_eq!(plan.output.as_deref(), Some("prog"));
6236        assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
6237        assert_eq!(
6238            deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
6239            Some("prog.d")
6240        );
6241    }
6242
6243    #[test]
6244    fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
6245        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
6246        assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
6247        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
6248        assert_eq!(plan.output, None);
6249    }
6250
6251    #[test]
6252    fn usage_fits_on_a_screen() {
6253        // Not a style preference. A help text that scrolls is one nobody reads, and this is
6254        // the cheapest way to keep it honest as flags accumulate. The number goes up only when
6255        // a family of flags arrives that has nowhere to share a line, which the two pass gates
6256        // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
6257        // the lines that family took. The four it went up by last are the flags a build system
6258        // passes without being asked to: how much to say, what machine to generate for, threads,
6259        // and the questions `configure` asks before it compiles anything. The one it went up by
6260        // last is the second line of `--emit`, whose kinds are a family that has now outgrown
6261        // one line and has nowhere else to go. The two it went up by last are the dependency
6262        // family, which is eight flags that share nothing with anything above them. The one it
6263        // went up by last is the four spellings of position independent code, which every
6264        // configure script writes and which could only have shared the link line, and that line
6265        // is already four characters short of the limit. The two it went up by last are the rest
6266        // of the include family, which is six more flags that change where a header is looked for
6267        // and two that name a header outright. The one it went up by last is the pair that keeps
6268        // the intermediate files and times the steps, which belong next to the two flags above
6269        // them that are also about watching a compilation rather than changing one. The two it
6270        // went up by last are the section flags and the visibility flag, which are what a build
6271        // that cares about the size of what it ships and about which names it exports writes, and
6272        // the second of them was already taken and only missing from here. The one it went up by
6273        // last is the stack protector, which is four spellings of one question and which every
6274        // distribution puts on every command line it issues, so a build that reads this list
6275        // looking for it and does not find it has to go and read the specification instead. The one
6276        // it went up by last is the profiler, which is two spellings of the request and two of
6277        // where the call goes, and which is about watching a program run rather than about what is
6278        // generated, so it shares its subject with nothing above it. The one it went up by last is
6279        // the room a function opens with for something to be written over it later, which takes an
6280        // argument of its own shape and is what a kernel build asks for, so it fits beside the
6281        // profiler and nothing else. The one it went up by last is what overflows rather than being
6282        // undefined, which is three spellings of two questions and which a kernel build and a great
6283        // deal of code written before the standard settled both pass. The one it went up by last is
6284        // the other answer to the first of those questions, which could not share the line because
6285        // what it asks for is the opposite of what the flags on that line ask for. The one it went
6286        // up by last is the split of the line that lists what this compiler does anyway into that
6287        // and what it assumes anyway, which are two different claims that were sharing a line until
6288        // the second of them got a second flag and the line stopped fitting. The one it went up by
6289        // last is the three flags that change the ABI rather than the code, which have to be given
6290        // to every file in a program or none of them and which therefore belong somewhere a person
6291        // reading this list will see them. The one it went up by last is the floating point group,
6292        // which is two lines rather than one because the first of them is a choice this compiler
6293        // records and the rest are claims about what it does anyway, and putting a real setting on
6294        // the same line as three flags that change nothing would be misleading about both. The one
6295        // it went up by last is the flag that says a write has to stay inside the member it names,
6296        // which is a setting rather than a claim and so cannot share the line above it, that being
6297        // the one that picks a tier. The two it went up by last are the prefix mapping family,
6298        // which is four flags whose whole job is to keep a build's output the same from two
6299        // different directories, and which a person chasing a reproducible build comes here
6300        // looking for by name. The one it went up by last is how the debug sections are compressed
6301        // and whether they go in a file of their own, which are two questions about the shape of
6302        // the debug output, where the line above them is about how much of it there is. The one it
6303        // went up by last is the `restrict` contract, which is a setting for the same reason the
6304        // flag that keeps a write inside its member is and which is the check a person who has been
6305        // bitten by a vectorizer comes here looking for. The one it went up by last is link time
6306        // optimization, which is a whole optimization rather than a flag and which says so on its
6307        // own line, because a build that passes it and reads this looking for what it got is
6308        // asking a question no other line here answers. The one it went up by last is the sysroot,
6309        // which is the question somebody asks when a cross build read a file nobody expected, and
6310        // which has no room on the line above it because the answers there are a path each and this
6311        // one is the root all of them are under. The one it went up by last is what is inside that
6312        // root and where each of it came from, which is a question about a whole tree rather than
6313        // about a path and which is long enough on its own that it could not have shared a line with
6314        // anything. The one it went up by last is the profile family, which splits down the middle
6315        // where no other family here does, so the line has to name the half that is taken and the
6316        // half that is refused or it would be read as taking both. The one it went up by last is
6317        // the sanitizers, which are what somebody reaching for a checked build writes first and
6318        // which belong beside the tier that is the nearest thing here to what they asked for. The
6319        // one it went up by last is the digest of that record, which is the same tree as one number
6320        // and could not share the line above it because that line prints a few hundred lines and
6321        // this one prints sixty four characters, and a reader who wants the short answer is looking
6322        // for it by name rather than reading the long one. The one it went up by last is the
6323        // sysroot fetch, which is the only command here that gets something from somewhere else and
6324        // is therefore the one a person wants to have read before they run it rather than after.
6325        // And the flag beside it that forbids every download, which earns its line by being what a
6326        // build in a sealed environment passes and by meaning something even though an ordinary
6327        // compile downloads nothing either way. The one it went up by last is the other fetch, the
6328        // one behind Microsoft's licence wall, which is a line rather than a paragraph because what
6329        // a person needs from here is that the command exists and that it will not do anything
6330        // until they have read a licence it prints for them.
6331        assert!(USAGE.lines().count() < 73, "usage text has grown past one screen");
6332    }
6333}