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