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