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