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.15.3")]
30
31pub mod assemble;
32pub mod cache;
33pub mod compile;
34pub mod deps;
35pub mod fetch;
36mod glibc;
37pub mod install;
38pub mod library;
39pub mod link;
40mod map;
41pub mod msvc;
42pub mod phase;
43pub mod preprocess;
44pub mod schedule;
45mod shapes;
46pub mod trace;
47mod warnings;
48
49use std::fmt::Write as _;
50use std::io::Write as _;
51use std::path::PathBuf;
52
53use rucc_codegen::coverage::{self, Fired};
54use rucc_codegen::lowering::Lowerings;
55use rucc_codegen::pressure::Pressure;
56use rucc_pp::Dependency;
57use rucc_session::{
58    Compress, Control, Dumps, EmitKind, Hook, Math, Options, Pic, PrefixMap, Preinclude, Protector,
59    SaveTemps, Session, Std, Wrapping, runtime,
60};
61use rucc_sysroot::{Manifest, Sysroot};
62use rucc_target::{ObjectFormat, Triple};
63use rucc_tuple::TargetTuple;
64
65use crate::link::LinkOptions;
66
67pub use crate::assemble::assemble;
68pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
69pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan, Role};
70pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
71pub use crate::schedule::Jobs;
72
73/// The compiler's version, taken from the workspace manifest.
74pub const VERSION: &str = env!("CARGO_PKG_VERSION");
75
76/// What the command line asked for.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum Action {
79    /// Print usage and exit successfully.
80    Help,
81    /// Print the version and exit successfully.
82    Version,
83    /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
84    ///
85    /// A build system asks these before it compiles anything, and what it does with the answer
86    /// is paste it into a path or into another command line, so each one is a single line with
87    /// no decoration around it.
88    Print(String),
89    /// Print the resolved configuration and exit successfully.
90    PrintConfig(Box<Options>),
91    /// Print the passes the level will run and exit successfully.
92    PrintPipeline(Box<Options>),
93    /// Print the phase plan and the link line and exit successfully, which is `-###`.
94    PrintPlan {
95        /// The resolved options, which is what says what the link line is for.
96        opts: Box<Options>,
97        /// What to do to each input, and in what order.
98        plan: Box<Plan>,
99        /// What the command line said about linking.
100        link: Box<LinkOptions>,
101    },
102    /// `--fetch <tuple>`, which gets the sysroot this release pins for a target and installs it.
103    ///
104    /// The only action in this compiler that may run another program to move bytes onto the
105    /// machine, which is `spec/cross-compile/13-distribution.md` section 13.8's rule rather than a
106    /// property of how this happens to be written: a compilation has no branch that reaches it.
107    Fetch {
108        /// The artifact, from the table in [`rucc_sysroot::artifact`]. Resolved here rather than where the
109        /// work happens, so that a target nothing is pinned for is a refusal from the parser like
110        /// every other thing a command line can ask for and not have.
111        what: &'static rucc_sysroot::Pinned,
112        /// The target, which names the directory under the cache the tree is installed at and is
113        /// checked against the record inside the artifact.
114        target: TargetTuple,
115        /// Where the cache is, read where everything else that needs it reads it.
116        cache: PathBuf,
117    },
118    /// `--fetch-msvc-sdk <tuple>`, which gets what is behind Microsoft's licence wall.
119    ///
120    /// The other action that may run another program to move bytes onto the machine, and the only
121    /// one that asks a person to accept somebody else's licence first.
122    /// `spec/cross-compile/13-distribution.md` section 13.4 is why no release pins an artifact
123    /// for these, and nothing about this may ever happen because a compile wanted it to. `--fetch`
124    /// of an MSVC target is this action too, starting from the build this release pins rather than
125    /// from the one Microsoft's channel names today.
126    FetchMsvcSdk {
127        /// The target, which says which architecture's CRT library package is wanted.
128        target: TargetTuple,
129        /// Whether `--accept-licence` was on the command line. Without it the licence and the list
130        /// are printed and nothing is downloaded, which is the whole of what the flag is for.
131        accepted: bool,
132        /// Where the cache is, read where everything else that needs it reads it.
133        cache: PathBuf,
134        /// Whether the documents at the top of the chain are [`rucc_sysroot::PINNED_BUILD`]'s,
135        /// which is `--fetch`, rather than the current channel's, which is `--fetch-msvc-sdk`.
136        pinned: bool,
137    },
138    /// Compile the given inputs.
139    Compile {
140        /// The resolved options.
141        opts: Box<Options>,
142        /// What to do to each input, and in what order.
143        plan: Box<Plan>,
144        /// What the command line said about linking.
145        link: Box<LinkOptions>,
146        /// How many translation units to compile at once.
147        jobs: Jobs,
148        /// Whether `-v` asked for the plan to be printed while it runs.
149        verbose: bool,
150        /// What is worth saying about the command line before anything is compiled, printed as
151        /// warnings and once for the whole run rather than once per file.
152        ///
153        /// These are not diagnostics. A diagnostic is about a piece of source and has a span to
154        /// point at, and these are about the way two flags were combined, so there is nothing to
155        /// point at and nowhere below the driver that knows both halves. `-w` does not reach them
156        /// for the same reason it does not reach a refusal from the parser.
157        notes: Vec<String>,
158    },
159}
160
161/// Why a command line was rejected.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct CliError {
164    /// The message, lowercase and without a trailing period, in the same shape as any other
165    /// diagnostic.
166    pub message: String,
167}
168
169impl std::fmt::Display for CliError {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        f.write_str(&self.message)
172    }
173}
174
175impl std::error::Error for CliError {}
176
177fn err(message: impl Into<String>) -> CliError {
178    CliError { message: message.into() }
179}
180
181/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
182///
183/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
184/// the only one that lets a directory whose name contains an `=` be the old half. It also means
185/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
186/// trap until you notice the alternative traps the far more common case.
187fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
188    let rest = &arg[flag.len()..];
189    PrefixMap::split(rest).ok_or_else(|| {
190        let flag = flag.trim_end_matches('=');
191        err(format!(
192            "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
193        ))
194    })
195}
196
197/// A question the command line asked instead of asking for a compilation.
198///
199/// These are answered after the loop rather than where they are read, because every one of them
200/// is about the target or about the library search and the last word on both is the end of the
201/// command line.
202enum Query {
203    /// `-dumpmachine`, the triple.
204    Machine,
205    /// `-dumpversion`, the major number of the GCC release this compiler claims to be.
206    Version,
207    /// `-dumpfullversion`, the same release in all three numbers.
208    FullVersion,
209    /// `-print-multiarch`, the directory name a distribution files this target under.
210    Multiarch,
211    /// `-print-search-dirs`, in the three lines GCC prints.
212    SearchDirs,
213    /// `-print-sysroot`, the root the headers and the libraries are read under.
214    Sysroot,
215    /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
216    SysrootProvenance,
217    /// `-print-sysroot-digest`, the one number that names all of it.
218    SysrootDigest,
219    /// `-print-file-name=<name>`, the full path of a library file.
220    FileName(String),
221    /// `-print-prog-name=<name>`, the full path of a program.
222    ProgName(String),
223    /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
224    Libgcc,
225}
226
227/// Usage text.
228///
229/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
230/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
231pub const USAGE: &str = "\
232rucc, an optimizing C compiler
233
234usage: rucc [options] file...
235
236options:
237  -c                     compile and assemble, do not link
238  -S                     compile only, emit assembly
239  -E                     preprocess only
240  -o <file>              write output to <file>, or to standard output for -
241  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
242  -I <dir>               add <dir> to the include search path
243  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
244  -I-, -iprefix <p>, -iwithprefix[before] <dir>   the older spellings of those
245  -include <file>, -imacros <file>    read <file> first, the second for its macros only
246  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
247  -P, -dM                with -E: leave out the markers, or dump the macros
248  -M -MM -MD -MMD        write a make rule for the source, the last two compile as well
249  -MF <file> -MT <t> -MQ <t> -MP   where the rule goes, what it builds, targets with no recipe
250  -std=<dialect>         c89 through c2y, and the gnu spellings
251  -fgnuc-version=<v> -fms-compatibility-version=<v>   the GCC (16.0.0) or MSVC (19.40) to claim
252  -x <lang>              treat later inputs as <lang>, or none to stop
253  -O<level>              optimize: 0, 1, 2, 3, s, z, fast
254  -fsafety=<tier>        check memory safety: off, detect, enforce, kernel
255  -f[no-]sanitize=<what>   the negative is taken, the positive is refused by name
256  -f[no-]safety-subobject   a write has to stay inside the member it names
257  -f[no-]safety-restrict    two restrict pointers of one block may not meet
258  -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
259  -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n>   stop a pass, or all of them, after n
260  -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>]   run a pass on some functions only
261  -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone   debug info, frame pointer, red zone
262  -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf   compress debug sections, one file not two
263  -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects   read, and not done yet
264  -fprofile-use[=<path>] -fprofile-dir=<dir>   read too, where -fprofile-generate is refused
265  -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
266  -ffunction-sections -fdata-sections   a section per function or variable, for --gc-sections
267  -fvisibility=<what>    default, hidden, internal or protected, when nothing in the source said
268  -l<name>, -L <dir>, -B <dir>   link a library, where to look for one, where our own tools are
269  -fPIC -fpic -fPIE -fpie, -pipe   what it does anyway, and -f[no-]common as the target's cc
270  -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks   what it assumes anyway
271  -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s   how to link
272  -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name>   hand an argument to the linker, or pick one
273  -Werror -pedantic -pedantic-errors -w -W[no-]system-headers   how much to say, and how fatal
274  -m64 -march= -mtune= -mcpu= -mabi= -mcmodel=   what machine to generate for
275  -pg -p, -mfentry -mno-fentry   call a profiler on the way in, and where that call goes
276  -fpatchable-function-entry=<n>[,<m>]   room at the top of every function to patch later
277  -fwrapv, -fwrapv-pointer, -fno-strict-overflow, -ftrapv   overflow wraps, or stops the program
278  -f[no-]exceptions, -f[no-]non-call-exceptions   let an exception unwind through the code
279  -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums   change the ABI
280  -ffp-contract=<how>    fuse a multiply and an addition: fast, on or off
281  -f[no-]fast-math and each of its members, -f[no-]rounding-math, -fexcess-precision=<how>
282  -ffile-prefix-map=<old>=<new>   rewrite that front of every path we put in the output
283  -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map=   the same, one output each
284  -pthread               build for more than one thread, and link the library for it
285  -dumpmachine -dumpversion -print-multiarch -print-search-dirs   what this compiler is
286  -print-file-name=<name> -print-prog-name=<name>   where a file or a program is
287  -print-sysroot         the root the headers and the libraries are read under
288  -print-sysroot-provenance   every input under it, where it came from and its licence
289  -print-sysroot-digest   the sha256 of that record, which names the whole sysroot in one line
290  --fetch <tuple>        get the sysroot this release pins for <tuple> and install it in the cache
291  --fetch-msvc-sdk <tuple>   the same for *-windows-msvc, from Microsoft's current build
292  --offline              never download anything, which a compilation never does anyway
293  -j[n]                  compile n translation units at once, default all
294  -v, -###               print each phase as it runs, or without running any
295  -save-temps[=cwd|obj], -fstack-usage, -time   keep the .i and .s, write a .su, time each step
296  --target=<triple>      generate code for <triple>, which a name like <triple>-rucc also does
297  --emit=<kind>          exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
298                         safety-summary, type-granules
299  --print-config, --print-pipeline    print the configuration or the pipeline, and exit
300  --version              print the version and exit
301  -h, --help             print this message and exit
302
303See spec/04-driver-and-cli.md for the full flag reference.
304";
305
306/// The argument of a flag that may be joined to it or may be the next word.
307///
308/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
309fn joined_or_next(
310    arg: &str,
311    at: usize,
312    args: &[String],
313    i: &mut usize,
314) -> Result<String, CliError> {
315    if arg.len() > at {
316        return Ok(arg[at..].to_owned());
317    }
318    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
319    *i += 1;
320    Ok(next.clone())
321}
322
323/// The smallest boundary a function is put on when the command line asked for no alignment at all.
324///
325/// Eight bytes, which is what gcc 16 gives `-fno-align-functions` on x86-64 and is a boundary every
326/// target this compiler has is happy with. It is not zero: a function still has to start somewhere
327/// an instruction may start, and the flag asks for the target's minimum rather than for none.
328const MIN_FUNC_ALIGN: u32 = 8;
329
330/// What `-falign-functions=N` asks for, as a power of two, or `None` for the target's own answer.
331///
332/// Zero and one both mean the default, which is gcc's reading of them, and everything else is
333/// rounded up to the next power of two, which is also gcc's: `-falign-functions=3` puts a function
334/// on a four byte boundary rather than being refused. Gives back `Err` shaped as an outer `None`
335/// only when the text is not a number, since that is the one thing gcc will not read either. A
336/// number larger than any alignment makes sense at is clamped rather than refused, for the same
337/// reason: this is a preference about speed and a build that wrote a silly one still deserves to
338/// compile.
339fn function_alignment(text: &str) -> Option<Option<u32>> {
340    // gcc takes `N:M:N2:M2`, where everything after the first number is about how far it is willing
341    // to go to reach the boundary. Only the boundary is answerable here, so the rest is read to
342    // check that it is numbers and then dropped.
343    let mut parts = text.split(':');
344    let first = parts.next()?;
345    if parts.any(|part| part.parse::<u64>().is_err()) {
346        return None;
347    }
348    let want: u64 = first.parse().ok()?;
349    if want <= 1 {
350        return Some(None);
351    }
352    let bytes = want.min(1 << 16).next_power_of_two();
353    Some(Some(u32::try_from(bytes).ok()?))
354}
355
356/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
357/// own.
358///
359/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
360/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
361/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
362/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
363/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
364/// because none of them is implemented.
365///
366/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
367/// those two spellings is read rather than by being on this list.
368const SANITIZERS: [&str; 34] = [
369    "address",
370    "kernel-address",
371    "hwaddress",
372    "kernel-hwaddress",
373    "pointer-compare",
374    "pointer-subtract",
375    "thread",
376    "leak",
377    "undefined",
378    "shift",
379    "shift-base",
380    "shift-exponent",
381    "integer-divide-by-zero",
382    "unreachable",
383    "vla-bound",
384    "null",
385    "return",
386    "signed-integer-overflow",
387    "bounds",
388    "bounds-strict",
389    "alignment",
390    "object-size",
391    "float-divide-by-zero",
392    "float-cast-overflow",
393    "nonnull-attribute",
394    "returns-nonnull-attribute",
395    "bool",
396    "enum",
397    "vptr",
398    "pointer-overflow",
399    "builtin",
400    "alias",
401    "restrict",
402    "memory",
403];
404
405/// The command line with every `@file` replaced by the words in the file, the way gcc does it.
406///
407/// Meson writes the link of a large target this way, so that a command line holding a thousand
408/// objects stays under the limit the system puts on one. Postgres's `postgres` executable is the
409/// one link in its tree that meson writes as `@postgres.rsp`, and before this the name went to
410/// the linker as it was. GNU ld reads response files itself, so it opened the file and found
411/// `-Wl,--as-needed` in it, which is a driver flag it has never heard of.
412///
413/// The rules are libiberty's `expandargv`, since that is what gcc and every other GNU tool read
414/// these files with. Words are split on white space, a single or a double quote keeps white
415/// space in a word until the matching quote, and a backslash makes the character after it an
416/// ordinary one, inside quotes as well as outside. A word the file gives that starts with `@` is
417/// read as a response file in turn. A name that cannot be opened is left on the command line as
418/// it was, which is what gcc does and which is how a file really called `@x.c` still reaches the
419/// loop, where it is refused as an unknown input rather than swallowed. The depth is capped so a
420/// file that names itself is an error and not a hang.
421fn response_files(args: &[String]) -> Result<Vec<String>, CliError> {
422    const DEEPEST: usize = 64;
423    fn expand(args: &[String], depth: usize, out: &mut Vec<String>) -> Result<(), CliError> {
424        for arg in args {
425            let Some(name) = arg.strip_prefix('@') else {
426                out.push(arg.clone());
427                continue;
428            };
429            let Ok(text) = std::fs::read_to_string(name) else {
430                out.push(arg.clone());
431                continue;
432            };
433            if depth == DEEPEST {
434                return Err(err(format!("response file '{name}' is nested too deeply")));
435            }
436            expand(&response_words(&text), depth + 1, out)?;
437        }
438        Ok(())
439    }
440    if !args.iter().any(|arg| arg.starts_with('@')) {
441        return Ok(args.to_vec());
442    }
443    let mut out = Vec::with_capacity(args.len());
444    expand(args, 0, &mut out)?;
445    Ok(out)
446}
447
448/// The words of one response file, split the way libiberty's `buildargv` splits them.
449fn response_words(text: &str) -> Vec<String> {
450    let mut words = Vec::new();
451    let mut word = String::new();
452    // Whether a word has begun, which is not the same as `word` having something in it: `''` is
453    // an empty word of its own and has to reach the command line as one.
454    let mut begun = false;
455    let mut quote: Option<char> = None;
456    let mut chars = text.chars();
457    while let Some(c) = chars.next() {
458        match c {
459            '\\' => {
460                if let Some(next) = chars.next() {
461                    word.push(next);
462                }
463                begun = true;
464            }
465            _ if quote == Some(c) => quote = None,
466            _ if quote.is_some() => word.push(c),
467            '\'' | '"' => {
468                quote = Some(c);
469                begun = true;
470            }
471            _ if c.is_whitespace() => {
472                if begun {
473                    words.push(std::mem::take(&mut word));
474                    begun = false;
475                }
476            }
477            _ => {
478                word.push(c);
479                begun = true;
480            }
481        }
482    }
483    if begun {
484        words.push(word);
485    }
486    words
487}
488
489/// The command line with every `-Wp,` this compiler understands spelled as its own flags.
490///
491/// The preprocessor is inside this compiler, so what a build hands it through `-Wp,` has to be
492/// read here. Kbuild is the reason: every object in the Linux kernel and in busybox is compiled
493/// with `-Wp,-MD,dir/.name.o.d`, which is cpp's spelling of `-MD -MF dir/.name.o.d`. cpp's `-MD`
494/// and `-MMD` take the file as their next word where the driver's do not, and the rest are the
495/// same flags in both. A `-Wp,` holding anything else is left as it was so the loop refuses it,
496/// because dropping part of what a build asked the preprocessor for would be the silent kind of
497/// wrong.
498fn preprocessor_args(args: &[String]) -> Vec<String> {
499    let mut out = Vec::with_capacity(args.len());
500    for arg in args {
501        let Some(list) = arg.strip_prefix("-Wp,") else {
502            out.push(arg.clone());
503            continue;
504        };
505        let words: Vec<&str> = list.split(',').collect();
506        let mut spelled = Vec::new();
507        let mut i = 0;
508        let understood = loop {
509            let Some(&word) = words.get(i) else {
510                break true;
511            };
512            i += 1;
513            match word {
514                "-MD" | "-MMD" | "-MF" | "-MT" | "-MQ" => {
515                    let Some(&value) = words.get(i) else {
516                        break false;
517                    };
518                    i += 1;
519                    if word == "-MD" || word == "-MMD" {
520                        spelled.extend([word.to_owned(), "-MF".to_owned()]);
521                    } else {
522                        spelled.push(word.to_owned());
523                    }
524                    spelled.push(value.to_owned());
525                }
526                "-MP" => spelled.push(word.to_owned()),
527                _ if word.len() > 2
528                    && (word.starts_with("-D")
529                        || word.starts_with("-U")
530                        || word.starts_with("-I")) =>
531                {
532                    spelled.push(word.to_owned());
533                }
534                _ => break false,
535            }
536        };
537        if understood {
538            out.extend(spelled);
539        } else {
540            out.push(arg.clone());
541        }
542    }
543    out
544}
545
546/// The extension a `-m` flag names and whether it turns it on, when it names one.
547///
548/// `-mno-` is the off form of every one of them, which is also how gcc spells it. A flag that is
549/// not an extension, `-mno-red-zone` say, is `None` and is left to the rest of the parser.
550fn isa_name(arg: &str) -> Option<(&str, rucc_target::Feature, bool)> {
551    let rest = arg.strip_prefix("-m")?;
552    let (name, on) = match rest.strip_prefix("no-") {
553        Some(name) => (name, false),
554        None => (rest, true),
555    };
556    let known =
557        if on { rucc_target::Feature::named(name) } else { rucc_target::Feature::named_off(name) };
558    known.map(|feature| (name, feature, on))
559}
560
561/// The extensions the machine running the compiler has, which is what `-march=native` means.
562///
563/// Asked of the processor with `cpuid`, through the standard library, and only when the compiler
564/// is running on an x86-64 at all. Anywhere else there is no processor to ask about an x86-64 one,
565/// and gcc on such a machine builds for the baseline, which is what this does. The list is the
566/// extensions whose names are stable in the standard library at this workspace's minimum Rust
567/// version, which covers everything [`rucc_target::Feature::honoured`] says yes to and a good deal
568/// that it does not.
569fn native_isa() -> rucc_target::Isa {
570    let base = rucc_target::Isa::baseline();
571    #[cfg(target_arch = "x86_64")]
572    {
573        let mut isa = rucc_target::Choices::new();
574        macro_rules! asked {
575            ($($detected:tt => $name:literal),* $(,)?) => {
576                $(if std::arch::is_x86_feature_detected!($detected) {
577                    isa.read($name).expect("a name gcc knows");
578                })*
579            };
580        }
581        asked! {
582            "sse3" => "sse3",
583            "ssse3" => "ssse3",
584            "sse4.1" => "sse4.1",
585            "sse4.2" => "sse4.2",
586            "sse4a" => "sse4a",
587            "popcnt" => "popcnt",
588            "avx" => "avx",
589            "avx2" => "avx2",
590            "fma" => "fma",
591            "f16c" => "f16c",
592            "bmi1" => "bmi",
593            "bmi2" => "bmi2",
594            "lzcnt" => "lzcnt",
595            "xsave" => "xsave",
596            "aes" => "aes",
597            "pclmulqdq" => "pclmul",
598            "sha" => "sha",
599            "cmpxchg16b" => "cx16",
600            "adx" => "adx",
601            "rdrand" => "rdrnd",
602            "rdseed" => "rdseed",
603        }
604        isa.over(base)
605    }
606    #[cfg(not(target_arch = "x86_64"))]
607    base
608}
609
610/// Parses a command line, without the program name.
611///
612/// # Errors
613///
614/// Returns the message to print when the arguments do not name a compilation this compiler
615/// can attempt.
616pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
617    let expanded = preprocessor_args(&response_files(args)?);
618    let args = expanded.as_slice();
619    let host = Triple::host()
620        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
621    let mut opts = Options::new(host);
622    // Where the compiler is running, which is what `DW_AT_comp_dir` is and what a debugger joins a
623    // relative file name onto. Asked here rather than where the debug sections are written, because
624    // this is the one layer that is allowed to look at the process it is in, and because a command
625    // line that compiles four files should give the same answer for all four.
626    opts.working_dir = std::env::current_dir().ok().map(|dir| dir.to_string_lossy().into_owned());
627    let mut inputs: Vec<Input> = Vec::new();
628    let mut print_config = false;
629    let mut print_pipeline = false;
630    let mut print_plan = false;
631    let mut verbose = false;
632    let mut jobs = Jobs::default();
633    let mut nostdinc = false;
634    let mut sysroot: Option<PathBuf> = None;
635    // What the command line is worth warning about, filled in after the loop rather than during it,
636    // because every question of this kind is about two flags and the last word on both of them is
637    // the end of the loop.
638    let mut notes: Vec<String> = Vec::new();
639    // The whole ten field target, kept beside the three field one because `--target=` can pin a
640    // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
641    // else today, and `None` is a command line that named no target, which is this machine.
642    let mut pinned: Option<TargetTuple> = None;
643    let mut min_version: Option<rucc_tuple::Version> = None;
644    let mut output = None;
645    let mut link = LinkOptions::default();
646    let mut query: Option<Query> = None;
647    // What `--fetch` named, and whether `--offline` forbade it. Both are weighed after the loop
648    // because either can be written after the other.
649    let mut fetch: Option<String> = None;
650    // The other fetch, kept apart from the one above because they are different commands with
651    // different rules, and weighed after the loop for the same reason that one is.
652    let mut fetch_msvc: Option<String> = None;
653    let mut accepted = false;
654    let mut offline = false;
655    let mut threads = false;
656    // Which sanitizers are still asked for by the end of the command line. Accumulated across the
657    // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
658    // build that asks for a check and then takes it back has asked for nothing. What happens to a
659    // set that is not empty is decided after the loop.
660    let mut sanitizers: Vec<&str> = Vec::new();
661    // The `-ffast-math` family in the order it was written, replayed after the loop on top of
662    // what `-Ofast` implies. gcc applies a level's defaults before any flag and the flags in order
663    // after that, so `-fno-fast-math -Ofast` is not fast math, and only a replay can say so.
664    let mut math_flags: Vec<&str> = Vec::new();
665    let mut ofast = false;
666    // `-mdaz-ftz` and `-mno-daz-ftz`, which decide the startup file directly and outrank the
667    // family on that one question.
668    let mut daz_ftz: Option<bool> = None;
669    // The instruction set extensions the `-m` flags named, in order, and the processor `-march`
670    // named last. Both are weighed after the loop, because a processor supplies only what no flag
671    // spoke for whichever order they came in, and because `--target=` may come after either and
672    // decide that neither means anything. See `rucc_target::isa`.
673    let mut isa = rucc_target::Choices::new();
674    let mut isa_flag: Option<&str> = None;
675    let mut march: Option<&str> = None;
676    // What `-fexceptions` and `-fno-exceptions` last said, if either was written. It is kept apart
677    // from the field because `-fnon-call-exceptions` turns exceptions on only when neither was,
678    // which is gcc's rule and is why `-fno-exceptions -fnon-call-exceptions` defines no
679    // `__EXCEPTIONS` whichever order the two come in.
680    let mut exceptions: Option<bool> = None;
681    // `-x` applies to inputs that come after it and stays in effect until the next one, which
682    // is why it is tracked across the loop rather than attached to a single argument.
683    let mut forced: Option<InputKind> = None;
684    // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
685    // the flags after it and not the ones before, so a command line may set it more than once.
686    // GCC's default is its own installed header directory with the last component taken off,
687    // which is a path a cross compiler's build system knows and passes; there is no equivalent
688    // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
689    // outright.
690    let mut iprefix = String::new();
691
692    let mut i = 0;
693    while i < args.len() {
694        let arg = args[i].as_str();
695        i += 1;
696        match arg {
697            "-h" | "--help" => return Ok(Action::Help),
698            "--version" => return Ok(Action::Version),
699            // The sysroot fetch, which is weighed after the loop rather than acted on here, because
700            // `--offline` written after it has to be able to forbid it. Both spellings, since a
701            // flag that takes a tuple gets written both ways and neither is a guess at what the
702            // other meant.
703            "--fetch" => {
704                let value = args
705                    .get(i)
706                    .ok_or_else(|| err("--fetch requires the target to get a sysroot for"))?;
707                i += 1;
708                fetch = Some(value.clone());
709            }
710            _ if arg.starts_with("--fetch=") => {
711                fetch = Some(arg["--fetch=".len()..].to_owned());
712            }
713            // The other fetch, which is section 13.4's. Same two spellings for the same reason,
714            // and weighed after the loop so that `--offline` and `--accept-licence` written after
715            // it are read whichever order somebody put them in.
716            "--fetch-msvc-sdk" => {
717                let value = args.get(i).ok_or_else(|| {
718                    err("--fetch-msvc-sdk requires the target to get the SDK for")
719                })?;
720                i += 1;
721                fetch_msvc = Some(value.clone());
722            }
723            _ if arg.starts_with("--fetch-msvc-sdk=") => {
724                fetch_msvc = Some(arg["--fetch-msvc-sdk=".len()..].to_owned());
725            }
726            // Both spellings of the word, because the compiler's own prose uses one of them and
727            // most of the people typing this will reach for the other, and being told that a flag
728            // is not a flag over the letter in the middle of it is a puzzle rather than a message.
729            "--accept-licence" | "--accept-license" => accepted = true,
730            // Accepted on any command line and only ever read by the fetch, because an ordinary
731            // compile downloads nothing with or without it. So this flag takes nothing away today,
732            // which is the property section 13.2 asks for rather than an omission: a build that
733            // passes it is saying what it expects of this compiler, and what it expects is already
734            // true.
735            "--offline" => offline = true,
736            "--print-config" => print_config = true,
737            "--print-pipeline" => print_pipeline = true,
738            "-###" => print_plan = true,
739            "-v" => verbose = true,
740            // The files a compilation goes through, kept rather than thrown away. The bare
741            // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
742            // gcc 16 does; `SaveTemps::Object` carries the measurement.
743            "-save-temps" => opts.save_temps = SaveTemps::Object,
744            _ if arg.starts_with("-save-temps=") => {
745                opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
746            }
747            // A `.su` beside every file compiled, one line per function saying how much stack it
748            // takes. Where the file goes is the plan's business, see `Job::stack_usage`.
749            "-fstack-usage" => opts.stack_usage = true,
750            "-fno-stack-usage" => opts.stack_usage = false,
751            // How long each step took. A misspelling of this is worth rejecting rather than
752            // ignoring, since a run that says nothing looks like a compilation that took no time.
753            "-time" => opts.time = true,
754            "-c" => opts.emit = EmitKind::Object,
755            "-S" => opts.emit = EmitKind::Asm,
756            "-E" => opts.emit = EmitKind::Preprocessed,
757            "-fsyntax-only" => opts.emit = EmitKind::SyntaxOnly,
758            "-g" => opts.debug_info = true,
759            // GCC's own levels of how much debug information to write. Zero is none and every
760            // other number is some, and this compiler has one amount, so the numbers above zero
761            // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
762            // debugger on the machine prefers, which is what we emit anyway.
763            "-g0" => opts.debug_info = false,
764            "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
765                opts.debug_info = true;
766            }
767            // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
768            // asks for another version is told rather than handed a file it cannot read.
769            "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
770            _ if arg.starts_with("-gdwarf-") => {
771                return Err(err(format!(
772                    "{arg}: this compiler writes DWARF 5 and no other version, see \
773                     spec/11-debug-info.md"
774                )));
775            }
776            // Whether the debug information goes in a file of its own beside the object. gcc
777            // writes that `.dwo` whether or not it found anything to put in it, which means a
778            // build system that declares the file as an output gets one and a make rule that
779            // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
780            // flag that changes nothing and refuses one that changes what is produced, and a file
781            // that does not appear is the plainest change of that kind there is. The negative
782            // spelling is taken, because putting it all in the object is what happens anyway.
783            "-gno-split-dwarf" => {}
784            "-gsplit-dwarf" => {
785                return Err(err(format!(
786                    "{arg}: this compiler writes no separate `.dwo` file, and a build that \
787                     expects one beside each object would wait for a file that never arrives, \
788                     see spec/11-debug-info.md"
789                )));
790            }
791            // How the debug sections are compressed. There are none yet, so every answer produces
792            // the same bytes and taking the flag promises nothing that is not kept. The value is
793            // still checked, because a typo in a distribution's flags is worth finding when the
794            // compiler reads it rather than when somebody later wonders why nothing got smaller.
795            // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
796            "-gz" => opts.compress = Compress::Zlib,
797            _ if arg.starts_with("-gz=") => {
798                let how = &arg["-gz=".len()..];
799                opts.compress = how.parse().map_err(|()| {
800                    err(format!(
801                        "`{how}` is not a way to compress debug sections, which is none, zlib, \
802                         zlib-gnu or zstd"
803                    ))
804                })?;
805            }
806            "-Werror" => opts.warnings_are_errors = true,
807            // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
808            // through rather than here, so that a warning `-w` dropped is not counted either.
809            "-w" => opts.warnings = false,
810            // Off by default, the way gcc has it off. A header that came with the machine is not
811            // one the person compiling can change, so a warning about it is noise, and under
812            // `-Werror` it is a build that stops on a line nobody in the project wrote. Somebody
813            // porting a header does want to hear all of it, which is what the flag is for.
814            "-Wsystem-headers" => opts.system_header_warnings = true,
815            "-Wno-system-headers" => opts.system_header_warnings = false,
816            "-pedantic-errors" => {
817                opts.pedantic = true;
818                opts.warnings_are_errors = true;
819            }
820            "-P" => opts.line_markers = false,
821            // The dependency family, which section 4.4 calls required because every build system
822            // that generates its own makefiles asks for it. The two that end in `D` write a file
823            // beside the object and let the compilation happen, and the two that do not write to
824            // standard output and stop after it. Nothing here turns the system headers back on
825            // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
826            // `-MM`: the flag asking for fewer of them is the one with something to say.
827            "-M" => {
828                opts.deps.emit = true;
829                opts.deps.instead_of_compiling = true;
830            }
831            "-MM" => {
832                opts.deps.emit = true;
833                opts.deps.instead_of_compiling = true;
834                opts.deps.system_headers = false;
835            }
836            "-MD" => opts.deps.emit = true,
837            "-MMD" => {
838                opts.deps.emit = true;
839                opts.deps.system_headers = false;
840            }
841            "-MP" => opts.deps.phony = true,
842            // These three take a word and only in the separated form, which is how GCC spells
843            // them and how every build system writes them.
844            "-MF" | "-MT" | "-MQ" => {
845                let value =
846                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
847                i += 1;
848                match arg {
849                    "-MF" => opts.deps.file = Some(value.clone()),
850                    // The whole of the difference between the two. `-MT` is for a build that has
851                    // already escaped what it is passing, and `-MQ` is for one that has a name
852                    // and wants it to arrive as that name.
853                    "-MT" => opts.deps.targets.push(value.clone()),
854                    _ => opts.deps.targets.push(deps::escaped(value)),
855                }
856            }
857            // The questions a build system asks before it compiles anything. Answered after the
858            // loop, because each one is about the target or the library search and the command
859            // line has not finished saying what those are.
860            "-dumpmachine" => query = Some(Query::Machine),
861            // Both answer with the GCC release in `__GNUC__` rather than our own version, because
862            // what asks is a build script deciding which GCC it is talking to, and `0.11` reads as
863            // a GCC too old to have anything. GCC 7 and later print only the major number for the
864            // first one, and that is the shape the scripts were written against.
865            "-dumpversion" => query = Some(Query::Version),
866            "-dumpfullversion" => query = Some(Query::FullVersion),
867            "-print-multiarch" => query = Some(Query::Multiarch),
868            "-print-search-dirs" => query = Some(Query::SearchDirs),
869            "-print-sysroot" => query = Some(Query::Sysroot),
870            // Both spellings, because this one is ours rather than GCC's and our own documents
871            // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
872            // two dashes like the other flags we invented, and document 12's table gives it one
873            // like the `-print-` family it sits in. A person who reads either and types what it
874            // says is right, so neither is refused.
875            "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
876                query = Some(Query::SysrootProvenance);
877            }
878            "-print-sysroot-digest" | "--print-sysroot-digest" => {
879                query = Some(Query::SysrootDigest);
880            }
881            "-print-libgcc-file-name" => query = Some(Query::Libgcc),
882            _ if arg.starts_with("-print-file-name=") => {
883                query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
884            }
885            _ if arg.starts_with("-print-prog-name=") => {
886                query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
887            }
888            // A program built to run in more than one thread. On every platform this compiler
889            // targets that is a macro the library's headers read and one more library on the
890            // link line, and the library is added after the loop so that it lands after the
891            // objects that refer to it.
892            "-pthread" | "-pthreads" => {
893                opts.defines.push("_REENTRANT".to_owned());
894                threads = true;
895            }
896            "-ansi" => {
897                opts.std = Std::C89;
898                opts.gnu_extensions = false;
899            }
900            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
901            // the spelling a build system that groups its warning flags tends to write.
902            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
903            // Both directions, because a build that needs this for one directory turns it back
904            // off for the next one rather than leaving it on for the whole tree.
905            "-fpermissive" => opts.permissive = true,
906            "-fno-permissive" => opts.permissive = false,
907            "-ffreestanding" => opts.hosted = false,
908            "-fhosted" => opts.hosted = true,
909            "-fno-builtin" => opts.builtins = false,
910            "-fbuiltin" => opts.builtins = true,
911            // The C89 dialects are under GNU's reading whatever this says, so turning it off
912            // there is turning off something the dialect asked for, which is accepted and does
913            // nothing. gcc refuses that command line, and there is nothing it could have meant.
914            "-fgnu89-inline" => opts.gnu89_inline = true,
915            "-fno-gnu89-inline" => opts.gnu89_inline = false,
916            // Both directions of each, because a build system that wants one of these usually
917            // writes it beside the flag that turns it back off for one directory.
918            "-fno-omit-frame-pointer" => opts.frame_pointer = Some(true),
919            "-fomit-frame-pointer" => opts.frame_pointer = Some(false),
920            // Both directions again, for the same reason, and a third answer for a command line
921            // that wrote neither: see `reorder_blocks` in `rucc_session`.
922            "-freorder-blocks" => opts.reorder_blocks = Some(true),
923            "-fno-reorder-blocks" => opts.reorder_blocks = Some(false),
924            // gcc's name for the scheduler that runs after the registers are handed out, which is
925            // the only one rucc has: see `schedule_insns` in `rucc_session`. gcc also takes
926            // `-fschedule-insns` for the pass before allocation, and taking that one here would be
927            // a flag that says a pass ran when none did.
928            "-fschedule-insns2" => opts.schedule_insns = Some(true),
929            "-fno-schedule-insns2" => opts.schedule_insns = Some(false),
930            // A call in tail position as a jump: see `sibling_calls` in `rucc_session`.
931            "-foptimize-sibling-calls" => opts.sibling_calls = Some(true),
932            "-fno-optimize-sibling-calls" => opts.sibling_calls = Some(false),
933            "-mno-red-zone" => opts.red_zone = false,
934            "-mred-zone" => opts.red_zone = true,
935            // Four flags rather than one with an argument, which is how gcc spells them and how
936            // every build line writes them. Last one wins, because a package build puts
937            // `-fstack-protector-strong` in its global flags and a directory that cannot have one
938            // turns it back off on the line after.
939            "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
940                opts.protector = Protector::None;
941            }
942            "-fstack-protector" => opts.protector = Protector::Buffers,
943            "-fstack-protector-strong" => opts.protector = Protector::Strong,
944            "-fstack-protector-all" => opts.protector = Protector::All,
945            // The other half of what a hardened build asks for, and it is a question about the
946            // frame rather than about the function, so it is a switch rather than a level.
947            "-fstack-clash-protection" => opts.stack_clash = true,
948            "-fno-stack-clash-protection" => opts.stack_clash = false,
949            // The third of them, and the one that is a question with an argument rather than a
950            // family of spellings, because what it asks about is which of the two edges of a
951            // control flow transfer is checked. Bare is both of them, which is what gcc does.
952            "-fcf-protection" => opts.control = Control::Full,
953            "-fno-cf-protection" => opts.control = Control::None,
954            // Two spellings of the same request, which is what gcc has as well. `-p` was the older
955            // profiler and `-pg` the one that also recorded who called whom, and on every platform
956            // this compiler targets there is now one hook and both ask for it.
957            "-pg" | "-p" => {
958                opts.profile = true;
959                link.profile = true;
960            }
961            // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
962            // say where the call goes and a command line that asked for no call has nowhere to put
963            // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
964            // directory is a build system that would otherwise fail on every other directory.
965            "-mfentry" => opts.hook = Hook::Early,
966            "-mno-fentry" => opts.hook = Hook::Late,
967            // GCC drops its own include directory along with the system ones, because its
968            // headers are half of a pair with the library's and half a pair is worse than
969            // none. A build that passes this is supplying the whole set itself.
970            "-nostdinc" => nostdinc = true,
971            "-o" => {
972                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
973                i += 1;
974            }
975            // What the files kept beside an output are named after, which is `-save-temps` and
976            // `-fstack-usage` so far. gcc takes each of the three in the separated form only, and
977            // its driver passes them to every compilation it runs, so a build that copied a
978            // command line out of gcc's `-v` has them. See `phase::aux_base` for what they do.
979            "-dumpbase" | "-dumpbase-ext" | "-dumpdir" => {
980                let value =
981                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?.clone();
982                i += 1;
983                match arg {
984                    "-dumpbase" => opts.dump_base = Some(value),
985                    "-dumpbase-ext" => opts.dump_base_ext = Some(value),
986                    _ => opts.dump_dir = Some(value),
987                }
988            }
989            // The flags that take a directory only in the separated form. GCC spells them
990            // this way and nothing writes `-iquotedir`, so accepting the joined form would
991            // mean guessing at a path that starts with the flag's own letters.
992            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
993            // two mean the same thing here: the configured directories are under there rather
994            // than under the root.
995            "-isysroot" => {
996                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
997                i += 1;
998                sysroot = Some(PathBuf::from(dir));
999            }
1000            "-iquote" | "-isystem" | "-idirafter" => {
1001                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1002                i += 1;
1003                match arg {
1004                    "-iquote" => opts.search.push_quote(dir.clone()),
1005                    "-isystem" => opts.search.push_system(dir.clone()),
1006                    _ => opts.search.push_after(dir.clone()),
1007                }
1008            }
1009            "-iprefix" => {
1010                iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
1011                i += 1;
1012            }
1013            // Where GCC puts these is not where its manual says it puts them, and this is the
1014            // measured answer rather than the documented one: `-iwithprefix` lands in the
1015            // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
1016            // the `-I` slot. A cross build that uses them is relying on the behaviour, since
1017            // that is the compiler it was developed against.
1018            "-iwithprefix" | "-iwithprefixbefore" => {
1019                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1020                i += 1;
1021                let dir = format!("{iprefix}{dir}");
1022                if arg == "-iwithprefix" {
1023                    opts.search.push_system(dir);
1024                } else {
1025                    opts.search.push_bracket(dir);
1026                }
1027            }
1028            "-include" | "-imacros" => {
1029                let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1030                i += 1;
1031                opts.preincludes
1032                    .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
1033            }
1034            // The flag `-iquote` was introduced to replace, still passed by build systems old
1035            // enough to predate the replacement. It is not a directory: it says that every `-I`
1036            // so far is for quoted includes only, and that a quoted include stops looking next
1037            // to the file that wrote it.
1038            "-I-" => opts.search.split_quote_chain(),
1039            // `-x c` and `-xc`, both of which gcc takes. busybox and toybox probe the compiler
1040            // with the joined one.
1041            _ if arg.starts_with("-x") => {
1042                let lang = joined_or_next(arg, 2, args, &mut i)?;
1043                forced = if lang == "none" {
1044                    None
1045                } else {
1046                    Some(InputKind::from_x_arg(&lang).map_err(|e| err(format!("{e}")))?)
1047                };
1048            }
1049            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
1050            // translation units in one process rather than making the build system fork, and
1051            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
1052            // to exist and has to be spelled the way `make` spells it.
1053            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
1054            // and a build system may produce either, so both are read here rather than
1055            // being normalised by whatever generated the command line.
1056            _ if arg.starts_with("-D") => {
1057                let value = joined_or_next(arg, 2, args, &mut i)?;
1058                opts.defines.push(value);
1059            }
1060            _ if arg.starts_with("-U") => {
1061                let value = joined_or_next(arg, 2, args, &mut i)?;
1062                opts.undefines.push(value);
1063            }
1064            _ if arg.starts_with("-I") => {
1065                let dir = joined_or_next(arg, 2, args, &mut i)?;
1066                opts.search.push_bracket(dir);
1067            }
1068            _ if arg.starts_with("-std=") => {
1069                let name = &arg["-std=".len()..];
1070                let (std, gnu) = Std::from_flag(name)
1071                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
1072                opts.std = std;
1073                opts.gnu_extensions = gnu;
1074            }
1075            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
1076            // handed, so a differential run that does not set it is comparing two compilers
1077            // that believe they are different compilers.
1078            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
1079            // that we have not written yet are accepted and ignored, because a dump is a
1080            // debugging aid and a build that asks for one should still compile. A letter
1081            // outside the family falls through to the unknown option error, which is what
1082            // keeps `-dumpversion` from being read as a dump of nothing.
1083            _ if Dumps::is_family(arg) => {
1084                opts.dumps.add(&arg[2..]);
1085            }
1086            // One name at a time, which is what a build that means its own `memcpy` and the
1087            // library's everything else writes. The name is not checked against a list, because
1088            // the flag is about what the program means by a name and a program is allowed to mean
1089            // something by a name this compiler has never heard of.
1090            _ if arg.starts_with("-fno-builtin-") => {
1091                opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
1092            }
1093            _ if arg.starts_with("-fgnuc-version=") => {
1094                let v = &arg["-fgnuc-version=".len()..];
1095                opts.gnuc = v.parse().map_err(err)?;
1096                opts.gnuc_given = true;
1097            }
1098            // The MSVC release an MSVC row claims, which is `_MSC_VER` and nothing else here.
1099            _ if arg.starts_with("-fms-compatibility-version=") => {
1100                let v = &arg["-fms-compatibility-version=".len()..];
1101                opts.msc = v.parse().map_err(err)?;
1102            }
1103            // Which of Microsoft's C runtimes an MSVC row links against, in clang's spelling of
1104            // `cl.exe`'s `/MT` and `/MD`. The headers are told through `_DLL` and the link through
1105            // the libraries it names, so it is both a compile flag and a link one. The two debug
1106            // runtimes are refused by name rather than taken as the release ones, since what they
1107            // link is a different set of libraries and a program that asked for one wants its
1108            // checks.
1109            _ if arg.starts_with("-fms-runtime-lib=") => {
1110                let dll = match &arg["-fms-runtime-lib=".len()..] {
1111                    "static" => false,
1112                    "dll" => true,
1113                    debug @ ("static_dbg" | "dll_dbg") => {
1114                        return Err(err(format!(
1115                            "-fms-runtime-lib={debug} asks for Microsoft's debug C runtime, which \
1116                             this compiler does not link against yet. static and dll are the two \
1117                             it has"
1118                        )));
1119                    }
1120                    other => {
1121                        return Err(err(format!(
1122                            "-fms-runtime-lib= takes static or dll, and `{other}` is neither"
1123                        )));
1124                    }
1125                };
1126                opts.ms_dll_runtime = dll;
1127                link.crt = if dll { rucc_sysroot::Crt::Dll } else { rucc_sysroot::Crt::Static };
1128            }
1129            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
1130            // than the unknown option one, because a build reaching for it is asking for a feature
1131            // and deserves to be told it is not coming rather than told the spelling is wrong.
1132            // The negative form is what this compiler does anyway, so it is taken and dropped.
1133            "-fnested-functions" => {
1134                return Err(err(
1135                    "nested functions are not supported: a call to one goes through a trampoline \
1136                     written on the stack, which no target that enforces an unexecutable stack \
1137                     allows",
1138                ));
1139            }
1140            "-fno-nested-functions" => {}
1141            // Which of the two links the output is for, which is a real difference and not a
1142            // description of what happens anyway. Everything here is position independent either
1143            // way, and what these decide is whether a name may be one another object defines or
1144            // replaces, because a link that produces an executable puts every name in the same
1145            // program and a link that produces a shared library does not.
1146            //
1147            // It matters that they are accepted at all, whatever they then do. Every autoconf and
1148            // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
1149            // be the `CC` of a project that has a configure script, whatever else it can do. That
1150            // is how this was found: building SQLite's test fixture stopped on it.
1151            "-fPIC" | "-fpic" => opts.pic = Pic::Library,
1152            // Not a synonym of the pair above, which is what they were treated as until #756. The
1153            // library is the expensive answer and gcc makes it the one that has to be asked for,
1154            // so this is also what nothing at all means.
1155            "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
1156            // A different question from the pair above, and the one every distribution build of a
1157            // shared library answers. `-fPIC` decides how an address is reached, and this decides
1158            // whether the optimizer may believe a body it can see, because an exported name is one
1159            // the dynamic linker may find another definition of first. On by default, which is
1160            // gcc's arrangement and is the honest answer, and off is a promise the build makes and
1161            // nothing checks.
1162            "-fsemantic-interposition" => opts.interposition = true,
1163            "-fno-semantic-interposition" => opts.interposition = false,
1164            // Two requests rather than one, and the same table answers both, so what decides is
1165            // whether either of them is standing. gcc arranges it the same way: the asynchronous
1166            // one is the default here and it implies the other, and a line that asks for a table
1167            // and against an asynchronous one gets a table.
1168            "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
1169            "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
1170            "-funwind-tables" => opts.unwind_tables = true,
1171            "-fno-unwind-tables" => opts.unwind_tables = false,
1172            // The other direction is a request, not a description, and it is one this compiler
1173            // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
1174            // option error. Answering it by carrying on would be answering a different question:
1175            // the code would still be position independent, which is correct everywhere an
1176            // ordinary program runs and is wrong in a kernel, where the flag is written precisely
1177            // because there is no loader to fill a global offset table in.
1178            "-fno-pic" | "-fno-pie" => {
1179                return Err(err(
1180                    "position dependent code is not supported: an address that may be in another \
1181                     object is loaded out of the global offset table, and nothing here emits the \
1182                     absolute form this asks for. Use -no-pie if what you meant was how to link",
1183                ));
1184            }
1185            // A section per function and a section per variable, which is what makes
1186            // `--gc-sections` able to drop anything: a linker can leave out a section nothing
1187            // reaches and cannot leave out half of one. Both directions are taken, and the off
1188            // one is the default rather than a refusal, since a build that writes it is asking
1189            // for what happens anyway.
1190            "-ffunction-sections" => opts.function_sections = true,
1191            "-fno-function-sections" => opts.function_sections = false,
1192            "-fdata-sections" => opts.data_sections = true,
1193            "-fno-data-sections" => opts.data_sections = false,
1194            // Whether a file scope declaration with no initializer is offered to the linker as a
1195            // common symbol for it to merge, or written into `.bss` as an ordinary defined one.
1196            // Unwritten, the target answers, which is on for Darwin and off everywhere else.
1197            "-fcommon" => opts.common = Some(true),
1198            "-fno-common" => opts.common = Some(false),
1199            // What overflows rather than being undefined. Every one of these takes something away
1200            // from the optimizer rather than asking it to do anything, which is why the negative
1201            // spellings are the interesting ones and the positive spellings are the default.
1202            //
1203            // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
1204            // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
1205            // written here as the pair rather than kept as a third thing to test everywhere.
1206            //
1207            // `-ftrapv` is the exception and is the one that asks for something. It is the other
1208            // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
1209            // the other, which makes the last one on the command line the one that counts. That is
1210            // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
1211            // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
1212            // question is left alone by both, because neither has anything to say about it.
1213            "-fwrapv" => {
1214                opts.wrapping.signed = true;
1215                opts.wrapping.trap = false;
1216            }
1217            "-fno-wrapv" => opts.wrapping.signed = false,
1218            "-fwrapv-pointer" => opts.wrapping.pointer = true,
1219            "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
1220            "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
1221            // Which does not clear the checked one, because gcc does not: `-ftrapv
1222            // -fstrict-overflow` still emits the calls. It says what is assumed and not what
1223            // happens.
1224            "-fstrict-overflow" => {
1225                opts.wrapping.signed = false;
1226                opts.wrapping.pointer = false;
1227            }
1228            "-ftrapv" => {
1229                opts.wrapping.trap = true;
1230                opts.wrapping.signed = false;
1231            }
1232            "-fno-trapv" => opts.wrapping.trap = false,
1233            // The two flags that say what a plain `char` is, which is one question with two
1234            // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
1235            // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
1236            // answers and the last one written wins. Nothing is set until one of them is given,
1237            // because the target's own ABI is the answer otherwise and it is not the same answer
1238            // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
1239            "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
1240            "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
1241            // And the size of an enumeration, which is the other thing in this group that changes
1242            // the ABI rather than the code.
1243            "-fshort-enums" => opts.short_enums = true,
1244            "-fno-short-enums" => opts.short_enums = false,
1245            // And Microsoft's reading of an anonymous member, which changes the layout of every
1246            // record that writes a tag on one. Nothing is set until one of them is given, because
1247            // the target is the answer otherwise: gcc's mingw build has this on and its Linux
1248            // build has it off.
1249            "-fms-extensions" => opts.ms_extensions = Some(true),
1250            "-fno-ms-extensions" => opts.ms_extensions = Some(false),
1251            // Both directions of this one are recorded, and what they decide is whether lowering
1252            // names the type each access goes through. Turning it off is the front end leaving the
1253            // name off rather than a pass being told to ignore one it can see, which is one
1254            // condition in one place, and it is the reading that survives link time optimization:
1255            // a unit built with the flag off keeps its own answer when its bodies end up in a
1256            // module beside bodies that were not.
1257            //
1258            // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
1259            // and is tested, and no pass at any level asks the alias analysis anything today, so
1260            // no program compiles differently for having passed this. The flag is wired anyway,
1261            // because the change that makes a pass ask is not the change anybody will remember to
1262            // wire it in, and a flag that is taken and dropped once the names mean something is
1263            // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
1264            // words.
1265            "-fstrict-aliasing" => opts.strict_aliasing = true,
1266            "-fno-strict-aliasing" => opts.strict_aliasing = false,
1267            // The same shape of answer for the same reason, and the flag the kernel writes beside
1268            // the one above it.
1269            //
1270            // Nothing here concludes that a pointer is not null from the fact that it was
1271            // dereferenced. There is no such conclusion to draw from, because no pass records one:
1272            // a load says where it read and nothing else, and a comparison against null is an
1273            // ordinary comparison of two values the optimizer has no fact about. So a function
1274            // that reads through a pointer and then tests it keeps the test, which is what the
1275            // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
1276            // to be asked for because it draws the conclusion by default.
1277            //
1278            // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
1279            // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
1280            // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
1281            "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
1282            // The floating point group, which goes the same way and for the same reason, and which
1283            // is worth writing out because the reason is easy to get backwards.
1284            //
1285            // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
1286            // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
1287            // changed and that an exception raised by an operation may be looked at, so an
1288            // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
1289            // whose exception the program does not get. Nothing here folds any floating point
1290            // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
1291            // that runs, at every level. So both of those describe what already happens.
1292            //
1293            // The permissive ones are the other half, and they are licences rather than requests
1294            // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
1295            // `-fno-trapping-math` says nothing looks at the exceptions, which together are
1296            // permission to fold. Not folding is the conservative side of that permission and is
1297            // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
1298            // speed and not correctness, which is the test section 4.1 puts a licence through.
1299            "-frounding-math" | "-fno-rounding-math" => {}
1300            // `-fno-trapping-math` is the one of the four that is kept, because there is one
1301            // conversion this compiler does not fold and gcc folds under it, and the two answers
1302            // differ. Converting a constant floating value to an integer type it does not fit in
1303            // is undefined behaviour rather than a value: left to the hardware it is one
1304            // instruction and the answer is the integer indefinite value, and folded it is the
1305            // nearest end of the integer's range. Both compilers leave it to the instruction by
1306            // default and gcc folds it under this flag, so a program built with it and compiled
1307            // without it gets a different number rather than a slower one. `-ftrapping-math` is
1308            // gcc's default, so a build spelling it out is asking for what it already has.
1309            //
1310            // The rest of the family goes with it, `-ffast-math` included, and all of them are
1311            // taken now. Each is a licence rather than a request and nothing here folds floating
1312            // point arithmetic, so the code does not change. What does change is the macros gcc
1313            // defines for each licence, which a header reads, and the startup file `-ffast-math`
1314            // links, which puts the hardware in flush to zero mode. Both are done after the loop,
1315            // because the family is a set of switches over the same fields and the last word on
1316            // each of them is the end of the command line.
1317            "-ftrapping-math"
1318            | "-fno-trapping-math"
1319            | "-ffast-math"
1320            | "-fno-fast-math"
1321            | "-funsafe-math-optimizations"
1322            | "-fno-unsafe-math-optimizations"
1323            | "-fmath-errno"
1324            | "-fno-math-errno"
1325            | "-ffinite-math-only"
1326            | "-fno-finite-math-only"
1327            | "-fsigned-zeros"
1328            | "-fno-signed-zeros"
1329            | "-freciprocal-math"
1330            | "-fno-reciprocal-math"
1331            | "-fassociative-math"
1332            | "-fno-associative-math" => math_flags.push(arg),
1333            // Whether the startup file that sets flush to zero is linked, asked directly. gcc
1334            // links it for a shared object too when this is written, which the family does not.
1335            "-mdaz-ftz" => daz_ftz = Some(true),
1336            "-mno-daz-ftz" => daz_ftz = Some(false),
1337            // About temporary files rather than about code. There is nothing between the phases of
1338            // one compilation here to write to a file in the first place.
1339            "-pipe" => {}
1340            // Preprocess the input, which a C compile always does. GCC has it for Fortran, and
1341            // meson writes it when it asks a compiler for its predefined macros.
1342            "-cpp" => {}
1343            // Nothing here writes colour, so all of these are the same answer, and it is the answer
1344            // that costs nothing: the diagnostics come out plain either way and no build depends on
1345            // an escape sequence being there. Taken rather than refused because cmake writes
1346            // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
1347            // makes this the second most common flag after `-fPIC` to stop a build over a question
1348            // about how the text looks.
1349            "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
1350            _ if arg.starts_with("-fdiagnostics-color=") => {}
1351            // The link flags. None of them changes the compilation, which is why they are
1352            // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
1353            // error: it is a thing said to a linker that is not going to run.
1354            "-static" => link.is_static = true,
1355            "-shared" => link.shared = true,
1356            "-r" => link.relocatable = true,
1357            "-pie" => link.pie = Some(true),
1358            "-no-pie" | "-nopie" => link.pie = Some(false),
1359            "-nostdlib" => link.no_stdlib = true,
1360            "-nostartfiles" => link.no_startfiles = true,
1361            "-nodefaultlibs" => link.no_defaultlibs = true,
1362            "-fno-builtins-lib" => link.no_builtins_lib = true,
1363            "-fbuiltins-lib" => link.no_builtins_lib = false,
1364            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
1365            "-s" => link.strip = true,
1366            // mingw-w64's three. `-mwindows` and `-mconsole` pick the subsystem, last one wins,
1367            // and `-municode` picks the start file and tells the headers through `UNICODE`, which is
1368            // what gcc's spec does with it. All three are taken and ignored for other targets, as gcc
1369            // built for mingw is the only gcc that knows them and a Makefile written for it is what
1370            // passes them.
1371            "-mwindows" => link.gui = true,
1372            "-mconsole" => link.gui = false,
1373            "-municode" => {
1374                link.unicode = true;
1375                opts.defines.push("UNICODE".to_owned());
1376            }
1377            // Into the ordered input list rather than a list of its own, because a great many of
1378            // the linker's options are a bracket around the files after them and an option that
1379            // lost its place among them says nothing. `--whole-archive` is the one that found this.
1380            "-Xlinker" => {
1381                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
1382                i += 1;
1383                inputs.push(Input::linker(next));
1384            }
1385            _ if arg.starts_with("-Wl,") => {
1386                // Commas separate arguments rather than being part of one, which is what makes
1387                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
1388                inputs.extend(arg["-Wl,".len()..].split(',').map(Input::linker));
1389            }
1390            _ if arg.starts_with("-fuse-ld=") => {
1391                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
1392            }
1393            _ if arg.starts_with("-l") && arg.len() > 2 => {
1394                inputs.push(Input::library(&arg[2..]));
1395            }
1396            "-l" => {
1397                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
1398                i += 1;
1399                inputs.push(Input::library(next));
1400            }
1401            _ if arg.starts_with("-L") => {
1402                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1403            }
1404            _ if arg.starts_with("-B") => {
1405                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1406            }
1407            _ if arg.starts_with("-j") => {
1408                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
1409            }
1410            _ if arg.starts_with("--sysroot=") => {
1411                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
1412            }
1413            _ if arg.starts_with("--target=") => {
1414                let t = &arg["--target=".len()..];
1415                // The same string again, as the model that has room for a libc version. A spelling
1416                // the three field parser took and this one does not is not an error, because the
1417                // one that decides what is compiled has already accepted it and the only thing
1418                // lost is a version nobody asked for.
1419                pinned = t.parse().ok();
1420                // The other way round is a deployment target the three field parser has no room
1421                // for, `aarch64-macos.13`, and the triple is the one the tuple narrows to.
1422                opts.target = match t.parse() {
1423                    Ok(triple) => triple,
1424                    Err(e) => {
1425                        pinned.and_then(Triple::from_tuple).ok_or_else(|| err(format!("{e}")))?
1426                    }
1427                };
1428            }
1429            _ if arg.starts_with("--emit=") => {
1430                let k = &arg["--emit=".len()..];
1431                opts.emit = k
1432                    .parse()
1433                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
1434            }
1435            // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
1436            // to write. `-Og` is GCC's level for a build somebody is going to step through, and
1437            // it is `-O1` with the transformations that move code around left out; this compiler
1438            // has no such level yet, so it is the nearest one and `--print-pipeline` says what
1439            // that came to rather than the flag pretending otherwise.
1440            "-O" | "-Og" => {
1441                opts.opt_level = rucc_session::OptLevel::O1;
1442                ofast = false;
1443            }
1444            // The union of `-O3` and `-ffast-math`. The second half is a default rather than a
1445            // flag, which is why it is remembered here and applied after the loop: a later level
1446            // takes it back, and so does a `-fno-fast-math` written on either side of it.
1447            "-Ofast" => {
1448                opts.opt_level = rucc_session::OptLevel::O3;
1449                ofast = true;
1450            }
1451            _ if arg.starts_with("-O") => {
1452                ofast = false;
1453                opts.opt_level = arg[2..]
1454                    .parse()
1455                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
1456            }
1457            // How far a multiply and an addition may be fused into one rounding. Before the
1458            // optimizer's `-f` family below for the reason the ones under it are, and kept rather
1459            // than dropped because it is the one flag in its group this compiler could act on: it
1460            // rides into the IR as an attribute on each function with a body, so the day the code
1461            // generator forms an `fma` it already knows which functions were given permission.
1462            // Nothing forms one today, under any value of this and under any `-march=`.
1463            _ if arg.starts_with("-ffp-contract=") => {
1464                let how = &arg["-ffp-contract=".len()..];
1465                opts.fp_contract = how.parse().map_err(|()| {
1466                    err(format!("`{how}` is not a contraction, which is fast, on or off"))
1467                })?;
1468            }
1469            // How much of an expression may be computed wider than it was written. The values are
1470            // gcc's and so is the refusal of anything else, and none of the three changes anything
1471            // here: an operation is computed in the type C says it is on every target this compiler
1472            // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
1473            // happens. `fast` and `16` are permission to be wider, which is a licence this takes
1474            // and does not use, the same way the two above are. The flag is worth taking because
1475            // glibc's headers and a good deal of configure output write it, and because the answer
1476            // it asks about is one this compiler can state rather than guess at: there is no x87
1477            // target here, which is the machine the whole question was invented for.
1478            // Whether a local and a spilled value that are never both wanted may be the same bytes
1479            // of the frame. gcc's three values, and two of them mean the same thing here: what rucc
1480            // shares is a local whose address provably never leaves the function, which is narrower
1481            // than `named_vars` and narrower still than `all`, so both of them get it. `none` is
1482            // the one that changes anything, and it is the flag a program that reads a local
1483            // through a pointer it kept past the end of the block writes.
1484            _ if arg.starts_with("-fstack-reuse=") => {
1485                let how = &arg["-fstack-reuse=".len()..];
1486                opts.stack_reuse = match how {
1487                    "all" | "named_vars" => Some(true),
1488                    "none" => Some(false),
1489                    _ => {
1490                        return Err(err(format!(
1491                            "`{how}` is not a stack reuse, which is all, named_vars or none"
1492                        )));
1493                    }
1494                };
1495            }
1496            _ if arg.starts_with("-fexcess-precision=") => {
1497                let how = &arg["-fexcess-precision=".len()..];
1498                if !matches!(how, "16" | "fast" | "standard") {
1499                    return Err(err(format!(
1500                        "`{how}` is not an excess precision, which is 16, fast or standard"
1501                    )));
1502                }
1503            }
1504            // Which front of a path is rewritten before it reaches the output, which is how a
1505            // build gets the same bytes out of two different directories. The four spellings are
1506            // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
1507            // once. Only the macro list does anything today, because `__FILE__` is the only place
1508            // a path reaches the output: there is no DWARF and no profile data yet, so the other
1509            // two are recorded for the work that will read them. The argument splits at the last
1510            // `=` rather than the first, which is gcc's rule and is what lets a directory with an
1511            // `=` in its name be the old half.
1512            _ if arg.starts_with("-fmacro-prefix-map=") => {
1513                let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1514                opts.prefix_map.macros.push(old, new);
1515            }
1516            _ if arg.starts_with("-fdebug-prefix-map=") => {
1517                let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1518                opts.prefix_map.debug.push(old, new);
1519            }
1520            _ if arg.starts_with("-fprofile-prefix-map=") => {
1521                let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1522                opts.prefix_map.profile.push(old, new);
1523            }
1524            _ if arg.starts_with("-ffile-prefix-map=") => {
1525                let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1526                opts.prefix_map.macros.push(old, new);
1527                opts.prefix_map.debug.push(old, new);
1528                opts.prefix_map.profile.push(old, new);
1529            }
1530            // A whole optimization rather than a flag, and the family is taken rather than
1531            // refused because of what ignoring it does. There is none of it here yet, so a build
1532            // that asks for it gets a program that is correct and slower than it could have been,
1533            // which is what section 4.1 means by a hint about speed and what every compilation at
1534            // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1535            // holds the bytecode and no machine code at all, and every object here holds the code,
1536            // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1537            // to this compiler gets objects that are more usable than the ones it asked for rather
1538            // than different ones. Every value is still checked against gcc's, because somebody
1539            // who wrote `-flto=thin` meant clang and had better hear about it here.
1540            "-flto" => opts.lto.requested = true,
1541            "-fno-lto" => opts.lto.requested = false,
1542            _ if arg.starts_with("-flto=") => {
1543                let how = &arg["-flto=".len()..];
1544                opts.lto.jobs = how.parse().map_err(|()| {
1545                    err(format!(
1546                        "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1547                         count above zero"
1548                    ))
1549                })?;
1550                opts.lto.requested = true;
1551            }
1552            _ if arg.starts_with("-flto-partition=") => {
1553                let how = &arg["-flto-partition=".len()..];
1554                opts.lto.partition = how.parse().map_err(|()| {
1555                    err(format!(
1556                        "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1557                         or none"
1558                    ))
1559                })?;
1560            }
1561            _ if arg.starts_with("-flto-compression-level=") => {
1562                let how = &arg["-flto-compression-level=".len()..];
1563                let level =
1564                    how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1565                        err(format!("`{how}` is not a compression level, 0 to 19"))
1566                    })?;
1567                opts.lto.compression = Some(level);
1568            }
1569            // Whether the object keeps its machine code as well as the bytecode. It always does
1570            // here, so the first of these describes what happens and the second asks for an object
1571            // with less in it, which is a smaller file and not a different program, so both are
1572            // taken.
1573            "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1574            // Whether the linker is handed a plugin that does the link time work. The design in
1575            // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1576            // plugin into anybody, so neither answer is a question it has to hold.
1577            "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1578            // Reading a profile back. Taken for the reason the family above it is: nothing here
1579            // reads one, so a build that asks gets the program it would have got anyway, and gcc
1580            // itself produces a byte for byte identical object from `-fprofile-use` when there are
1581            // no counts beside the file. The path is recorded for the pass that will read it. The
1582            // warning gcc prints when it looked and found nothing is deliberately not copied,
1583            // because nothing here looks, and a warning about a file that was never opened would
1584            // fire on the builds that have a perfectly good profile as well as on the ones that
1585            // do not.
1586            "-fprofile-use" => opts.profile_data.requested = true,
1587            "-fno-profile-use" => opts.profile_data.requested = false,
1588            _ if arg.starts_with("-fprofile-use=") => {
1589                opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1590                opts.profile_data.requested = true;
1591            }
1592            _ if arg.starts_with("-fprofile-dir=") => {
1593                opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1594            }
1595            "-fprofile-abs-path" => opts.profile_data.absolute = true,
1596            "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1597            "-fprofile-correction" => opts.profile_data.correction = true,
1598            "-fno-profile-correction" => opts.profile_data.correction = false,
1599            "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1600            "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1601            // Writing the counts rather than reading them, which is refused rather than taken and
1602            // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1603            // file a build declared as an output never appears: the instrumented program writes a
1604            // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1605            // two stage build that got neither would go on to optimize against no counts at all
1606            // and report coverage of nothing, with nothing along the way saying so. The objects
1607            // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1608            // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1609            // this is a flag that changes the output rather than a hint about speed.
1610            "-fprofile-arcs"
1611            | "--coverage"
1612            | "-fcondition-coverage"
1613            | "-fpath-coverage"
1614            | "-fprofile-generate" => {
1615                return Err(err(format!(
1616                    "{arg}: this compiler does not instrument for profiling, and a build that \
1617                     expects the counts a run of the instrumented program writes would optimize \
1618                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1619                )));
1620            }
1621            _ if arg.starts_with("-fprofile-generate=") => {
1622                return Err(err(format!(
1623                    "{arg}: this compiler does not instrument for profiling, and a build that \
1624                     expects the counts a run of the instrumented program writes would optimize \
1625                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1626                )));
1627            }
1628            "-ftest-coverage" => {
1629                return Err(err(format!(
1630                    "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1631                     that expects one would wait for a file that never arrives, see \
1632                     spec/04-driver-and-cli.md"
1633                )));
1634            }
1635            // The rest of the family describes instrumentation that is refused above, so what is
1636            // left to do with them is check them and drop them. They are checked because a
1637            // misspelling in a distribution's flags is worth finding here rather than on the day
1638            // the instrumentation lands, and dropped because there is nothing for an answer about
1639            // how a counter is written to be an answer about.
1640            _ if arg.starts_with("-fprofile-update=") => {
1641                let how = &arg["-fprofile-update=".len()..];
1642                if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1643                    return Err(err(format!(
1644                        "`{how}` is not a profile update method, which is single, atomic or \
1645                         prefer-atomic"
1646                    )));
1647                }
1648            }
1649            _ if arg.starts_with("-fprofile-reproducible=") => {
1650                let how = &arg["-fprofile-reproducible=".len()..];
1651                if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1652                    return Err(err(format!(
1653                        "`{how}` is not a profile reproducibility method, which is serial, \
1654                         parallel-runs or multithreaded"
1655                    )));
1656                }
1657            }
1658            "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1659            "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1660            _ if arg.starts_with("-fprofile-filter-files=")
1661                || arg.starts_with("-fprofile-exclude-files=")
1662                || arg.starts_with("-fprofile-note=") => {}
1663            // What every name gets when nothing in the source said, which the attribute in the
1664            // source overrides rather than the other way round. Before the optimizer's `-f`
1665            // family below for the reason the tier below it is.
1666            _ if arg.starts_with("-fvisibility=") => {
1667                let seen = &arg["-fvisibility=".len()..];
1668                opts.visibility = seen.parse().map_err(|()| {
1669                    err(format!(
1670                        "`{seen}` is not a visibility, which is default, hidden, internal or \
1671                         protected"
1672                    ))
1673                })?;
1674            }
1675            // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1676            // family below for the reason the two above it are, and last of the three so that the
1677            // bare spelling and the negative one are matched exactly rather than by this.
1678            _ if arg.starts_with("-fcf-protection=") => {
1679                let edges = &arg["-fcf-protection=".len()..];
1680                opts.control = edges.parse().map_err(|()| {
1681                    err(format!(
1682                        "`{edges}` is not a control flow protection, which is full, branch, \
1683                         return, none or check"
1684                    ))
1685                })?;
1686            }
1687            // How much room every function opens with for something to be written over later.
1688            // Before the optimizer's `-f` family below for the reason the ones above it are.
1689            _ if arg.starts_with("-fpatchable-function-entry=") => {
1690                let room = &arg["-fpatchable-function-entry=".len()..];
1691                opts.patchable = room.parse().map_err(|()| {
1692                    err(format!(
1693                        "`{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"
1694                    ))
1695                })?;
1696            }
1697            // The memory safety monitor, from section 15.4 of
1698            // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1699            // because a pass that took the name `safety=detect` would otherwise be handed the
1700            // flag, and the tier is not a pass.
1701            _ if arg.starts_with("-fsafety=") => {
1702                let tier = &arg["-fsafety=".len()..];
1703                opts.safety = tier.parse().map_err(|()| {
1704                    err(format!(
1705                        "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1706                    ))
1707                })?;
1708            }
1709            // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1710            // than folded into the tier because it is a departure somebody who has read that
1711            // section makes, and the two defaults it describes are a property of what is being
1712            // built rather than of how much checking is wanted.
1713            _ if arg.starts_with("-fsafety-init=") => {
1714                let mode = &arg["-fsafety-init=".len()..];
1715                opts.padding = mode.parse().map_err(|()| {
1716                    err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1717                })?;
1718            }
1719            // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1720            // strict form of that section needs a member id the front end does not name yet and
1721            // accepting the spelling for it would be accepting a promise this build cannot keep.
1722            // Before `-fno-` is looked at below, for the reason the tier is.
1723            "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1724            "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1725            _ if arg.starts_with("-fsafety-subobject=") => {
1726                let form = &arg["-fsafety-subobject=".len()..];
1727                return Err(err(format!(
1728                    "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1729                     the strict form of section 9.4 is tamnd/rucc#967"
1730                )));
1731            }
1732            // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1733            // the one above has none: there is one form of this check and a spelling that suggested
1734            // otherwise would be promising something. Before `-fno-` is looked at below, the same
1735            // way.
1736            "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1737            "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1738            _ if arg.starts_with("-fsafety-restrict=") => {
1739                let form = &arg["-fsafety-restrict=".len()..];
1740                return Err(err(format!(
1741                    "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1742                )));
1743            }
1744            // Section 9.5's races, which take a value because the section gives them three modes
1745            // and the difference between two of them is which classes get reported rather than how
1746            // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1747            // reason the two above spell theirs out.
1748            _ if arg.starts_with("-fsafety-races=") => {
1749                let mode = &arg["-fsafety-races=".len()..];
1750                opts.races = mode.parse().map_err(|()| {
1751                    err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1752                })?;
1753            }
1754            "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1755            // The sanitizers of document 12, which are checks at run time rather than a way of
1756            // generating the same program. Each name is held to gcc 16's list, and what is still
1757            // asked for by the end of the line is answered after the loop, so that a command line
1758            // which turns one on and then off again is a command line that asked for nothing.
1759            //
1760            // Before the optimizer's `-f` family below, for the reason the tier above it is.
1761            _ if arg.starts_with("-fsanitize=") => {
1762                for one in arg["-fsanitize=".len()..].split(',') {
1763                    if one == "all" {
1764                        // gcc takes `all` only in the negative, because turning every check on at
1765                        // once includes checks that contradict each other.
1766                        return Err(err(
1767                            "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1768                        ));
1769                    }
1770                    if !SANITIZERS.contains(&one) {
1771                        return Err(err(format!(
1772                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1773                        )));
1774                    }
1775                    if !sanitizers.contains(&one) {
1776                        sanitizers.push(one);
1777                    }
1778                }
1779            }
1780            _ if arg.starts_with("-fno-sanitize=") => {
1781                for one in arg["-fno-sanitize=".len()..].split(',') {
1782                    if one == "all" {
1783                        sanitizers.clear();
1784                        continue;
1785                    }
1786                    if !SANITIZERS.contains(&one) {
1787                        return Err(err(format!(
1788                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1789                        )));
1790                    }
1791                    sanitizers.retain(|asked| *asked != one);
1792                }
1793            }
1794            // What a check does when it fires, and where the records about the checked objects go.
1795            // Each of them is an answer about the sanitizers refused after the loop, so there is
1796            // nothing left for them to change here. The names are still held to the list, because
1797            // a misspelling in a build's flags is worth finding when the compiler reads it.
1798            _ if arg.starts_with("-fsanitize-recover=")
1799                || arg.starts_with("-fno-sanitize-recover=")
1800                || arg.starts_with("-fsanitize-trap=")
1801                || arg.starts_with("-fno-sanitize-trap=") =>
1802            {
1803                // The guard above matched on a spelling that has an `=` in it, so the tail is
1804                // whatever follows the first one.
1805                let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1806                for one in how.split(',') {
1807                    if one != "all" && !SANITIZERS.contains(&one) {
1808                        return Err(err(format!(
1809                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1810                        )));
1811                    }
1812                }
1813            }
1814            "-fsanitize-undefined-trap-on-error"
1815            | "-fsanitize-address-use-after-scope"
1816            | "-fno-sanitize-address-use-after-scope" => {}
1817            _ if arg.starts_with("-fsanitize-sections=") => {}
1818            // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1819            // keeping. Refused rather than dropped, because a fuzzer whose calls into
1820            // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1821            // and there is no point in the campaign where that announces itself.
1822            _ if arg.starts_with("-fsanitize-coverage=") => {
1823                let how = &arg["-fsanitize-coverage=".len()..];
1824                for one in how.split(',') {
1825                    if !matches!(one, "trace-pc" | "trace-cmp") {
1826                        return Err(err(format!(
1827                            "`{one}` is not a coverage instrumentation, which is trace-pc or \
1828                             trace-cmp"
1829                        )));
1830                    }
1831                }
1832                return Err(err(format!(
1833                    "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1834                     with it would run without any feedback at all, see \
1835                     spec/04-driver-and-cli.md section 4.7"
1836                )));
1837            }
1838            // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1839            // after every `-f` the rest of the compiler answers to, so a pass can never take a
1840            // name that already means something else on the command line.
1841            _ if arg.starts_with("-fpass-fuel=") => {
1842                let (name, count) = arg["-fpass-fuel=".len()..]
1843                    .split_once('=')
1844                    .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1845                if rucc_opt::pass::find(name).is_none() {
1846                    return Err(err(format!(
1847                        "`{name}` is not a pass this compiler has, see --print-pipeline"
1848                    )));
1849                }
1850                let count: u32 = count
1851                    .parse()
1852                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1853                opts.pass_fuel.push((name.to_owned(), count));
1854            }
1855            _ if arg.starts_with("-fpass-fuel-global=") => {
1856                let count = &arg["-fpass-fuel-global=".len()..];
1857                let count: u32 = count
1858                    .parse()
1859                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1860                opts.pass_fuel_global = Some(count);
1861            }
1862            _ if arg.starts_with("-frucc-trace=") => {
1863                let path = &arg["-frucc-trace=".len()..];
1864                if path.is_empty() {
1865                    return Err(err("-frucc-trace= needs a file to write to"));
1866                }
1867                opts.trace = Some(path.to_owned());
1868            }
1869            // Everything from `-fopt-info` to the end of the argument, which is optional
1870            // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1871            // where the remarks are printed, because by then the compilation somebody wanted
1872            // to hear about is over.
1873            _ if arg == "-fopt-info"
1874                || arg.starts_with("-fopt-info=")
1875                || arg.starts_with("-fopt-info-") =>
1876            {
1877                let rest = &arg["-fopt-info".len()..];
1878                let (kinds, file) = match rest.split_once('=') {
1879                    Some((kinds, file)) => (kinds, Some(file)),
1880                    None => (rest, None),
1881                };
1882                let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1883                rucc_opt::Wants::none().add(kinds).map_err(err)?;
1884                opts.opt_info.push(kinds.to_owned());
1885                if let Some(file) = file {
1886                    if file.is_empty() {
1887                        return Err(err("-fopt-info= was given no file to write to"));
1888                    }
1889                    opts.opt_info_file = Some(file.to_owned());
1890                }
1891            }
1892            _ if arg.starts_with("-fdump-ir=") => {
1893                // Checked here rather than where the dumps are taken, because the compilation
1894                // that would have been dumped is over by then.
1895                let spec = &arg["-fdump-ir=".len()..];
1896                rucc_opt::Dumps::default().add(spec).map_err(err)?;
1897                opts.dump_ir.push(spec.to_owned());
1898            }
1899            // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1900            // otherwise take the flag away from the gate. Checked here rather than where the
1901            // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1902            // name that quietly gated nothing looks exactly like a pass that is not the guilty
1903            // one, and a bisection would carry on past the thing it was looking for.
1904            _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1905                let on = arg.starts_with("-fenable-");
1906                let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1907                rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1908                opts.pass_gates.push((on, spec.to_owned()));
1909            }
1910            // gcc's spelling for a pass this compiler has under a shorter name. It goes above the
1911            // two arms below rather than into the pile of gcc pass names further down, because the
1912            // pass is here: dropping the flag would leave a build that asked for unrolling without
1913            // it, and refusing it stops the build outright, which is what libtommath's makefile
1914            // ran into. `-funroll-all-loops` is deliberately not in here: gcc's is the one that
1915            // unrolls without a trip count, which is a different and usually worse thing.
1916            "-funroll-loops" => opts.passes.push(("unroll".to_owned(), true)),
1917            "-fno-unroll-loops" => opts.passes.push(("unroll".to_owned(), false)),
1918            // Here rather than through the two arms below, because what this names is not a
1919            // `rucc_opt::Pass`. Section 34.6's propagation is a module at a time and everything in
1920            // the pass list is one function at a time. `-fipa-cp-clone` is deliberately not here:
1921            // gcc turns that one on at `-O3` and it is in the list of what M4 does not build.
1922            "-fipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), true)),
1923            "-fno-ipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), false)),
1924            // The other half of the same section, here for the same reason, and `-fipa-sra` in gcc
1925            // is the aggregate splitting as well as the parameter removal. Asking for it gets the
1926            // half that is built.
1927            "-fipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), true)),
1928            "-fno-ipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), false)),
1929            // And the printf family fold, which is a module at a time for the same reason and so is
1930            // not a `rucc_opt::Pass` either. gcc has no flag of its own for this one, since
1931            // `-fno-builtin` already turns it off along with everything else the standard names
1932            // mean. This spelling is for taking one thing away during a bisection without taking
1933            // the rest of section 20.1 away with it.
1934            "-flibcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), true)),
1935            "-fno-libcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), false)),
1936            _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1937                opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1938            }
1939            _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1940                opts.passes.push((arg["-f".len()..].to_owned(), true));
1941            }
1942            // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1943            // program reduced from a miscompilation usually names the pass that miscompiled it on
1944            // its `dg-options` line, and they arrive from hand written build files for the same
1945            // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1946            // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1947            // for a compiler that does not exist here, and the program it is attached to is a
1948            // correctness test that passes either way. Turning on a pass we do not have costs
1949            // speed, turning off a pass we do not have costs nothing, and neither changes what the
1950            // program computes.
1951            //
1952            // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1953            // compiler has rather than landing here, and the day one of these names becomes a pass
1954            // here it stops being taken and dropped without anybody editing this list.
1955            //
1956            // Two of them are prefixes rather than names, which is the one place this file takes a
1957            // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1958            // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1959            // nothing else, and there is no member of either that changes the meaning of a program
1960            // that was already correct. The rest are written out one at a time, because they live
1961            // in the flat `-f` namespace where the neighbours do change meanings.
1962            _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1963            _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1964            "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1965            "-fmodulo-sched" | "-fno-modulo-sched" => {}
1966            "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1967            _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1968            }
1969            "-fearly-inlining" | "-fno-early-inlining" => {}
1970            // The one of the family that does reach the optimizer, since the step it names is built:
1971            // `-fno-inline` stops a function declared `inline` from being inlined and leaves
1972            // `always_inline` alone, which is what it does in gcc.
1973            "-finline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), true)),
1974            "-fno-inline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), false)),
1975            // The called once half of the same step, on its own, which leaves the `inline` hint and
1976            // `always_inline` as they are. tamnd/rucc#1966.
1977            "-finline-functions-called-once" => {
1978                opts.passes.push((rucc_opt::inline::ONCE.to_owned(), true));
1979            }
1980            "-fno-inline-functions-called-once" => {
1981                opts.passes.push((rucc_opt::inline::ONCE.to_owned(), false));
1982            }
1983            "-finline-functions"
1984            | "-fno-inline-functions"
1985            | "-finline-small-functions"
1986            | "-fno-inline-small-functions" => {}
1987            "-foptimize-strlen" | "-fno-optimize-strlen" => {}
1988            "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
1989            // Where a function starts, which is a thing this compiler already decides and so is a
1990            // request it can answer rather than one it has to drop. The bare form asks for the
1991            // target's default and the default here is the sixteen bytes gcc also gives, so it
1992            // says nothing; a number is a floor under every function that did not ask for more
1993            // itself; and the negative form asks for the smallest boundary the target has. gcc 16
1994            // rounds a number that is not a power of two up rather than refusing it, which is what
1995            // `=3` giving `.p2align 2` on x86-64 means, so this rounds too.
1996            "-falign-functions" => opts.align_functions = None,
1997            "-fno-align-functions" => opts.align_functions = Some(MIN_FUNC_ALIGN),
1998            _ if arg.starts_with("-falign-functions=") => {
1999                opts.align_functions = function_alignment(&arg["-falign-functions=".len()..])
2000                    .ok_or_else(|| {
2001                        err(format!("{arg}: the alignment has to be a number of bytes"))
2002                    })?;
2003            }
2004            // The head of every hot loop, which is padded when this is asked for so that a loop that
2005            // fits in a 64 byte line does not cross one. Both directions of the plain form are
2006            // answered. A number is taken and says nothing, because the boundary here is the
2007            // line's and a build that names another is asking for speed rather than for a
2008            // different program.
2009            "-falign-loops" => opts.align_loops = Some(true),
2010            "-fno-align-loops" => opts.align_loops = Some(false),
2011            // The other two of the family, which are about padding in front of any label and in
2012            // front of a label only a jump reaches. This compiler writes neither, and what they
2013            // ask for is speed: a label on a boundary computes what a label off one computes. So
2014            // they are taken and dropped for the reason `-march=` is, and the numbered form of
2015            // the loop flag with them.
2016            _ if arg.starts_with("-falign-labels")
2017                || arg.starts_with("-falign-loops=")
2018                || arg.starts_with("-falign-jumps")
2019                || arg.starts_with("-fno-align-labels")
2020                || arg.starts_with("-fno-align-jumps") => {}
2021            // The charset flags are not in that pile, because an encoding is a statement about
2022            // what the bytes of the source mean rather than about how fast the output is. The
2023            // preprocessor reads UTF-8 and has no converter, so the one name that describes what
2024            // already happens is taken and every other name is refused. Spelled without regard to
2025            // case and with both of the spellings iconv answers to, since a build writes whichever
2026            // one its author typed.
2027            _ if arg.starts_with("-finput-charset=") => {
2028                let name = &arg["-finput-charset=".len()..];
2029                if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
2030                    return Err(err(format!(
2031                        "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
2032                         converter, so a file in another encoding would be read as though it were \
2033                         UTF-8 rather than converted",
2034                    )));
2035                }
2036            }
2037            // What C has of exceptions, which is a `cleanup` handler an unwind has to run and the
2038            // `__EXCEPTIONS` that tells a header so. The walk is what turns down the handler it has
2039            // no landing pad for, so a unit with none of them is taken whole.
2040            "-fexceptions" => exceptions = Some(true),
2041            "-fno-exceptions" => exceptions = Some(false),
2042            "-fnon-call-exceptions" => opts.non_call_exceptions = true,
2043            "-fno-non-call-exceptions" => opts.non_call_exceptions = false,
2044            // Whether an instruction that could raise one may still be deleted when nothing uses
2045            // what it computes. Nothing here keeps a dead one, and neither does gcc in a C unit
2046            // with no handler around it, so both spellings describe the code as it is.
2047            "-fdelete-dead-exceptions" | "-fno-delete-dead-exceptions" => {}
2048            "-finstrument-functions" => opts.instrument_functions = true,
2049            "-fno-instrument-functions" => opts.instrument_functions = false,
2050            // The unstable options, spelled the way rustc spells them and carrying the same
2051            // promise, which is none: one of these may change or go away in any release. They are
2052            // measurements and debugging aids rather than things a build asks for, which is why
2053            // none of them is in the usage text and all of them are in section 4.11 of
2054            // `spec/04-driver-and-cli.md`.
2055            "-Zverify-each" => opts.verify_each = true,
2056            _ if arg.starts_with("-Zrule-coverage=") => {
2057                let file = &arg["-Zrule-coverage=".len()..];
2058                if file.is_empty() {
2059                    return Err(err("-Zrule-coverage= needs a file to write to"));
2060                }
2061                opts.rule_coverage = Some(file.to_owned());
2062            }
2063            _ if arg.starts_with("-Zcycle-accurate-model=") => {
2064                let value = &arg["-Zcycle-accurate-model=".len()..];
2065                opts.cycle_accurate_model = match value {
2066                    "yes" | "1" => Some(true),
2067                    "no" | "0" => Some(false),
2068                    _ => {
2069                        return Err(err("-Zcycle-accurate-model= takes yes or no"));
2070                    }
2071                };
2072            }
2073            _ if arg.starts_with("-Zregalloc=") => {
2074                opts.backtracking = match &arg["-Zregalloc=".len()..] {
2075                    "backtracking" => Some(true),
2076                    "single" => Some(false),
2077                    _ => return Err(err("-Zregalloc= takes backtracking or single")),
2078                };
2079            }
2080            _ if arg.starts_with("-Zswitch=") => {
2081                let shape = &arg["-Zswitch=".len()..];
2082                if rucc_codegen::switch::Force::named(shape).is_none() {
2083                    return Err(err("-Zswitch= takes table, tree or walk"));
2084                }
2085                opts.switch_shape = Some(shape.to_owned());
2086            }
2087            _ if arg.starts_with("-Zlowering=") => {
2088                let file = &arg["-Zlowering=".len()..];
2089                if file.is_empty() {
2090                    return Err(err("-Zlowering= needs a file to write to"));
2091                }
2092                opts.lowering_dump = Some(file.to_owned());
2093            }
2094            _ if arg.starts_with("-Zregister-pressure=") => {
2095                let file = &arg["-Zregister-pressure=".len()..];
2096                if file.is_empty() {
2097                    return Err(err("-Zregister-pressure= needs a file to write to"));
2098                }
2099                opts.register_pressure = Some(file.to_owned());
2100            }
2101            _ if arg.starts_with("-Z") => {
2102                return Err(err(format!(
2103                    "`{arg}` is not an unstable option this compiler has, see \
2104                     spec/04-driver-and-cli.md section 4.11 for the ones it does"
2105                )));
2106            }
2107            // The word size, which is a statement about the target and is taken as one. A build
2108            // that says the size the target already has is saying nothing, and one that says the
2109            // other size is asking for a target this compiler does not have, which it is told
2110            // rather than being given the wrong one.
2111            "-m64" | "-m32" | "-mx32" => {
2112                let want: u32 = match arg {
2113                    "-m64" => 64,
2114                    _ => 32,
2115                };
2116                let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
2117                if have != want {
2118                    return Err(err(format!(
2119                        "{arg} asks for a {want} bit target and {} is {have} bit, use \
2120                         --target= to name the one you mean",
2121                        opts.target
2122                    )));
2123                }
2124            }
2125            // One extension of the x86-64 instruction set, on or off, which is `-msse4.2` and its
2126            // relatives. Only the ones this compiler has the intrinsics for may be turned on for a
2127            // whole unit, because what turning one on does here is define the macro, and a macro
2128            // is a promise to a header that the names behind it exist. Turning one off is taken
2129            // for any name gcc knows, since nothing is promised by it, except for the baseline:
2130            // SSE2 is where the psABI passes a `double`, so a unit without it is a different
2131            // calling convention and not a smaller instruction set.
2132            _ if isa_name(arg).is_some() => {
2133                let Some((_, feature, on)) = isa_name(arg) else { continue };
2134                if on && !feature.honoured() {
2135                    return Err(err(format!(
2136                        "{arg}: this compiler has no intrinsics for {} yet, so it cannot build a \
2137                         whole unit for it",
2138                        feature.name()
2139                    )));
2140                }
2141                if !on && rucc_target::Isa::baseline().has(feature) {
2142                    return Err(err(format!(
2143                        "{arg}: {} is part of the x86-64 baseline and the psABI passes values in \
2144                         it, so a unit built without it would call and be called differently",
2145                        feature.name()
2146                    )));
2147                }
2148                isa.read(&arg["-m".len()..]).map_err(|_| err(format!("unknown option `{arg}`")))?;
2149                isa_flag.get_or_insert(arg);
2150            }
2151            // Which processor in the family to build for. What it decides is the extensions of
2152            // the instruction set the unit may assume, which is the macros, and only on x86-64;
2153            // see `rucc_target::isa`. A processor it has no list for is built for as the
2154            // baseline, which is a program that could have been faster rather than a program
2155            // that is wrong, and the same goes for every other target's processors. `-mtune=`
2156            // says what to schedule for and changes nothing a program can see.
2157            _ if arg.starts_with("-march=") => march = Some(&arg["-march=".len()..]),
2158            _ if arg.starts_with("-mtune=") || arg.starts_with("-mcpu=") => {}
2159            // The calling convention, which is not safe to ignore. Taken when it names the one
2160            // the target already uses and refused otherwise.
2161            _ if arg.starts_with("-mabi=") => {
2162                let want = &arg["-mabi=".len()..];
2163                let have = match opts.target.arch {
2164                    rucc_target::Arch::X86_64 => "sysv",
2165                    rucc_target::Arch::Aarch64 => "lp64",
2166                    rucc_target::Arch::Riscv64 => "lp64d",
2167                };
2168                if want != have {
2169                    return Err(err(format!(
2170                        "{arg}: {} uses the {have} convention and this compiler has no other",
2171                        opts.target
2172                    )));
2173                }
2174            }
2175            // How far apart the pieces of the program may be. The small model is what we emit and
2176            // it is every hosted program's default; the kernel model is a different one and a
2177            // build that asks for it and does not get it links and then does not run.
2178            "-mcmodel=small" => {}
2179            // clang's spellings of the deployment target, which it takes over a version in the
2180            // tuple. gcc on a Mac takes the first. A target that is not Apple ignores it, as
2181            // clang does, so a makefile that always passes it still builds for Linux.
2182            _ if arg.starts_with("-mmacosx-version-min=")
2183                || arg.starts_with("-mmacos-version-min=") =>
2184            {
2185                let text = &arg[arg.find('=').map_or(arg.len(), |i| i + 1)..];
2186                let version = rucc_tuple::Version::parse(text)
2187                    .ok_or_else(|| err(format!("`{text}` in `{arg}` is not a version")))?;
2188                min_version = Some(version);
2189            }
2190            _ if arg.starts_with("-mcmodel=") => {
2191                return Err(err(format!(
2192                    "{arg}: this compiler emits the small code model and no other, see \
2193                     spec/12-targets.md"
2194                )));
2195            }
2196            // GCC's own scripting language for how the driver builds a command line.
2197            // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
2198            // build reaching for it is told which flags do the same job.
2199            _ if arg.starts_with("-specs=") => {
2200                return Err(err(
2201                    "-specs= is not supported: the parts of it builds rely on are -B, -L, \
2202                     -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
2203                     section 4.4",
2204                ));
2205            }
2206            // Arguments meant for a separate assembler, which this compiler does not have: it is
2207            // inside it and does not read a command line. Refused rather than dropped, because
2208            // every one of these says something about the output and a build that asked for
2209            // `-Wa,--noexecstack` and was silently given an executable stack got the opposite of
2210            // what it asked for. The `-Wp,` ones this compiler understands were turned into its
2211            // own flags before the loop, so one that reaches here is one it does not.
2212            _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
2213                return Err(err(format!(
2214                    "`{arg}` is an argument for a separate assembler or preprocessor, and both \
2215                     are inside this compiler rather than programs it runs"
2216                )));
2217            }
2218            "-Xassembler" | "-Xpreprocessor" => {
2219                return Err(err(format!(
2220                    "{arg} hands an argument to a separate assembler or preprocessor, and both \
2221                     are inside this compiler rather than programs it runs"
2222                )));
2223            }
2224            // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
2225            // this one as a rule about build systems rather than about warnings: autoconf and
2226            // meson find out whether a warning flag exists by passing it and looking at the exit
2227            // status, so the answer has to be gcc's. A name gcc knows is accepted, and one it does
2228            // not is refused, the way gcc refuses clang's names. `-Wno-` of a name nobody knows is
2229            // accepted, because gcc accepts it too, but `-Werror=` and `-Wno-error=` of one are
2230            // not. None of them turns anything on yet, which #485 is about.
2231            _ if arg.starts_with("-W") => {
2232                let name = &arg["-W".len()..];
2233                let named = name.strip_prefix("error=").or_else(|| name.strip_prefix("no-error="));
2234                if let Some(named) = named {
2235                    if !warnings::known(named) {
2236                        return Err(err(format!("`{arg}`: no option `-W{named}`")));
2237                    }
2238                } else if !name.is_empty() && !name.starts_with("no-") && !warnings::known(name) {
2239                    return Err(err(format!("unknown option `{arg}`")));
2240                }
2241            }
2242            // Flags that name something this compiler does not do and would not do differently
2243            // if it did. `-fno-ident` is about a comment in the output that we do not write
2244            // either way, and the others are about a way of ordering the compilation that has
2245            // been GCC's only way for twenty years. `-mthreads` is mingw's, and what it links is
2246            // `libmingwthrd.a`, which mingw-w64 keeps as an empty archive because its CRT does the
2247            // thread cleanup for every program. Section 4.1 asks for the list to be short and for
2248            // adding to it to be deliberate, which is why it is written out here.
2249            "-fno-ident"
2250            | "-fident"
2251            | "-funit-at-a-time"
2252            | "-fno-unit-at-a-time"
2253            | "-shared-libgcc"
2254            | "-static-libgcc"
2255            | "-mthreads"
2256            | "-fpch-deps"
2257            | "-fno-pch-deps" => {}
2258            _ if arg.starts_with('-') && arg.len() > 1 => {
2259                // Silently ignoring an unknown flag is how a build ends up not doing what
2260                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
2261                // for the flags that change code generation, and the safe default until the
2262                // flag table is populated is to reject everything we do not know.
2263                return Err(err(format!("unknown option `{arg}`")));
2264            }
2265            _ => inputs.push(Input { path: arg.to_owned(), forced, role: Role::File }),
2266        }
2267    }
2268
2269    // The fetch, before anything that resolves a compilation, because `--fetch` does not describe
2270    // one. It is here rather than in the loop so that `--offline` can forbid it whichever order the
2271    // two were written in, and it is before the refusals below so that a command line asking for a
2272    // sysroot is not told about a sanitizer.
2273    if let Some(named) = fetch {
2274        if fetch_msvc.is_some() {
2275            return Err(err(
2276                "--fetch and --fetch-msvc-sdk are two different commands and this command line \
2277                 asked for both. --fetch gets what this release pins by URL and by hash, which for \
2278                 a *-windows-msvc target is one Visual Studio build, and --fetch-msvc-sdk gets the \
2279                 build Microsoft's channel names today. Run whichever one you meant",
2280            ));
2281        }
2282        return fetch_action(&named, offline, accepted, &inputs);
2283    }
2284    if let Some(named) = fetch_msvc {
2285        return fetch_msvc_action(&named, offline, accepted, &inputs);
2286    }
2287    if accepted {
2288        return Err(err(
2289            "--accept-licence says that Microsoft's Visual Studio Build Tools licence is accepted, \
2290             and nothing on this command line asked for anything that licence covers. \
2291             --fetch <tuple> or --fetch-msvc-sdk <tuple> for a *-windows-msvc target is the \
2292             command it belongs to, and an ordinary compile downloads nothing with it or \
2293             without it",
2294        ));
2295    }
2296
2297    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
2298    // order: a directory the user names outranks the compiler's own, and the compiler's own
2299    // outranks the library's. It is pushed after the loop rather than before it because
2300    // `SearchPath` appends within a group and the position is what the order is.
2301    // The same directory the headers were looked for under, because a sysroot is a statement
2302    // about a whole installation and not about half of one.
2303    // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
2304    // command line that turns a check on and off again has asked for nothing. What is left is
2305    // refused rather than dropped, and it is the one place in this parser where the reason is not
2306    // that the output would differ. A sanitizer is a promise that the program is watched while it
2307    // runs, so a build that asks for one and is quietly given a program with no checks in it does
2308    // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
2309    // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
2310    // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
2311    // options.
2312    if let Some(first) = sanitizers.first() {
2313        return Err(err(format!(
2314            "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
2315             asked for one and got none would run its tests unchecked, see \
2316             spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
2317             compiler does have"
2318        )));
2319    }
2320    // The fast math family, replayed in order on top of what `-Ofast` implies. The startup file is
2321    // gcc's spec rather than the fields: it is linked when `-Ofast`, `-ffast-math` or
2322    // `-funsafe-math-optimizations` is still in force at the end of the line, whatever a later
2323    // member took back, and `-mdaz-ftz` decides it outright.
2324    let mut math = Math::default();
2325    let mut trapping = if ofast { math.set_fast(true) } else { true };
2326    for flag in &math_flags {
2327        match *flag {
2328            "-ftrapping-math" => trapping = true,
2329            "-fno-trapping-math" => trapping = false,
2330            "-ffast-math" => trapping = math.set_fast(true),
2331            "-fno-fast-math" => trapping = math.set_fast(false),
2332            "-funsafe-math-optimizations" => trapping = math.set_unsafe(true),
2333            "-fno-unsafe-math-optimizations" => trapping = math.set_unsafe(false),
2334            "-fmath-errno" => math.errno = true,
2335            "-fno-math-errno" => math.errno = false,
2336            "-ffinite-math-only" => math.finite_only = true,
2337            "-fno-finite-math-only" => math.finite_only = false,
2338            "-fsigned-zeros" => math.signed_zeros = true,
2339            "-fno-signed-zeros" => math.signed_zeros = false,
2340            "-freciprocal-math" => math.reciprocal = true,
2341            "-fno-reciprocal-math" => math.reciprocal = false,
2342            "-fassociative-math" => math.associative = true,
2343            "-fno-associative-math" => math.associative = false,
2344            _ => unreachable!("{flag} is not in the family"),
2345        }
2346    }
2347    opts.trapping_math = trapping;
2348    opts.math = math;
2349    let last = |on: &str, off: &str| {
2350        math_flags.iter().rev().find(|f| **f == on || **f == off).is_some_and(|f| *f == on)
2351    };
2352    link.fast_math = ofast
2353        || last("-ffast-math", "-fno-fast-math")
2354        || last("-funsafe-math-optimizations", "-fno-unsafe-math-optimizations");
2355    link.daz_ftz = daz_ftz;
2356    // The extensions, now that the target is known. On x86-64 the processor supplies whatever no
2357    // flag said. Anywhere else there are none to have, and a flag naming one is gcc's unknown
2358    // option there too, so it is refused the same way it would have been had it not looked like
2359    // an x86 flag.
2360    match opts.target.arch {
2361        rucc_target::Arch::X86_64 => {
2362            let base = match march {
2363                Some("native") => native_isa(),
2364                Some(name) => {
2365                    rucc_target::Isa::level(name).unwrap_or_else(rucc_target::Isa::baseline)
2366                }
2367                None => rucc_target::Isa::baseline(),
2368            };
2369            opts.isa = isa.over(base);
2370        }
2371        rucc_target::Arch::Aarch64 | rucc_target::Arch::Riscv64 => {
2372            if let Some(flag) = isa_flag {
2373                return Err(err(format!("unknown option `{flag}`")));
2374            }
2375            opts.isa = rucc_target::Isa::NONE;
2376        }
2377    }
2378    opts.exceptions = exceptions.unwrap_or(opts.non_call_exceptions);
2379    link.sysroot = sysroot.clone();
2380    // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
2381    // inside the link line, because a link line that read the environment could only be tested on a
2382    // machine whose environment said the right thing, and the link line is the last thing that
2383    // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
2384    link.cache = Some(cache::dir());
2385    // And where a distribution's cross packages would have put a tree for the target, which is only
2386    // read when the target is not this machine and there is no sysroot of ours for it.
2387    link.usr = Some(PathBuf::from("/usr"));
2388    // And the ten field spelling of the target, because the release on it decides two things the
2389    // three field one cannot say: whether a target that is this architecture is still a cross
2390    // compile, and which directory under the cache it is against. After the loop because the last
2391    // `--target=` on the command line is the one that counts.
2392    link.pinned = pinned;
2393    // The deployment target, from the flag if there was one and from the tuple otherwise. Only an
2394    // Apple platform has one: anywhere else a version on the tuple is a libc or a preview number.
2395    if opts.target.os == rucc_target::Os::Darwin {
2396        opts.os_version = min_version.or_else(|| pinned.and_then(TargetTuple::os_version));
2397        link.os_version = opts.os_version;
2398    }
2399    // After the loop rather than where `-pthread` was read, so that it lands after the objects
2400    // that refer to it. A static link takes the definitions it needs from a library when it
2401    // reaches it and not afterwards, so a library before the objects is a library that answers
2402    // nothing.
2403    if threads {
2404        inputs.push(Input::library("pthread"));
2405    }
2406    if let Some(query) = query {
2407        return Ok(Action::Print(answer(&query, &opts, &link)?));
2408    }
2409    // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
2410    // else the command line asked for. Read here rather than where the flag was, because a `-c`
2411    // written after it has to lose and the loop cannot know that until it has ended. The output
2412    // file is where the rule goes rather than where an object would have gone, and the last
2413    // phase being the preprocessor is what makes that true without a second rule for it.
2414    if opts.deps.instead_of_compiling {
2415        opts.emit = EmitKind::Preprocessed;
2416    }
2417    if !nostdinc {
2418        opts.search.push_system(runtime::DIR);
2419        // And the library's after ours, which is the other half of the same order. They go on
2420        // here rather than at the point `--target=` or `--sysroot=` was read because either
2421        // one changes the answer and the last word on both is the end of the loop.
2422        //
2423        // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
2424        // that the headers and the libraries come from the same place. A target that is this
2425        // machine reads this machine's headers, and a target that is not reads the ones in the
2426        // sysroot for it rather than the ones next door.
2427        let cross = link::cross_sysroot(opts.target, &link);
2428        let kernel = link::cross_kernel(opts.target, &link);
2429        let distro = link::distro_cross(opts.target, &link);
2430        // And the version of those headers, which only the bundled tree has an answer for. A host
2431        // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
2432        // and a second definition with a different value is a warning on every file, so the
2433        // condition is the same one that chose the directories.
2434        if cross.is_some() {
2435            let target = pinned.unwrap_or_else(|| opts.target.tuple());
2436            opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
2437                err(format!(
2438                    "{skew}; pin a release the tree has, or name a tree that has that one \
2439                     with --sysroot"
2440                ))
2441            })?;
2442        }
2443        let system = library::header_dirs(
2444            opts.target,
2445            sysroot.as_deref(),
2446            cross.as_ref(),
2447            kernel.as_ref(),
2448            distro.as_ref(),
2449        );
2450        // The two licence walls of `spec/cross-compile/13-distribution.md` section 13.4, which are
2451        // the only way step 3 comes back with nothing on a hosted target. Section 8.6 asks for the
2452        // answer to name the licence and the lawful ways to get what is behind it, rather than
2453        // leaving a person with an `#include` that failed as though a directory had gone missing.
2454        //
2455        // It is left on the search path instead of refused here, because a program that includes
2456        // none of the library needs none of the SDK and section 8.6 is explicit that targeting the
2457        // platform has to keep working. So the reason waits until an include has actually failed,
2458        // which is the only moment it helps and the only moment it is true.
2459        //
2460        // The condition is that step 3 found nothing at all, so an `SDKROOT`, an `INCLUDE` or a mac
2461        // with Xcode on it all pass through untouched, and `-nostdinc` never reaches this block. A
2462        // `--sysroot` or `-isysroot` passes through as well, even when the tree it names turns out to
2463        // be empty or absent: somebody who wrote a path has already answered the question this
2464        // message asks, and answering it again over the top of a mistyped directory would hide the
2465        // mistake behind a licence notice.
2466        if system.is_empty() && sysroot.is_none() {
2467            let tuple = pinned.unwrap_or_else(|| opts.target.tuple());
2468            if let Some(wall) = rucc_sysroot::Wall::of(tuple) {
2469                opts.search.explain_missing_system(wall.no_headers(&tuple.to_canonical_string()));
2470            }
2471        }
2472        // And whether the tree somebody named is the release they asked for, which is the one
2473        // question left once the directories are settled and the only place both halves of it are
2474        // known. Only for a named tree, because that is the case where the release in the target
2475        // stops deciding anything, and `crate::glibc` is where the rest of the reasoning is.
2476        if sysroot.is_some() {
2477            notes.extend(glibc::skew(opts.target, pinned, &system));
2478        }
2479        for dir in system {
2480            opts.search.push_system(dir);
2481        }
2482    }
2483    // Once, here, rather than as each directory is pushed. A `-I` that names a system
2484    // directory has to lose to the system entry and the system entry is added last, so the
2485    // question cannot be answered until the whole path is known.
2486    opts.search.remove_duplicates();
2487
2488    // The target has to be resolved before the configuration is printed, so this check comes
2489    // after the loop rather than at the point `--print-config` was seen.
2490    if print_config {
2491        return Ok(Action::PrintConfig(Box::new(opts)));
2492    }
2493    if print_pipeline {
2494        return Ok(Action::PrintPipeline(Box::new(opts)));
2495    }
2496    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
2497    if print_plan {
2498        return Ok(Action::PrintPlan {
2499            opts: Box::new(opts),
2500            plan: Box::new(plan),
2501            link: Box::new(link),
2502        });
2503    }
2504    Ok(Action::Compile {
2505        opts: Box::new(opts),
2506        plan: Box::new(plan),
2507        link: Box::new(link),
2508        jobs,
2509        verbose,
2510        notes,
2511    })
2512}
2513
2514/// What `--fetch <tuple>` asked for, or why it is not a thing that can be done.
2515///
2516/// The lookup happens here rather than at the point the bytes would move, so that a target this
2517/// release pins nothing for is a refusal from the parser and the only code that runs a downloader is
2518/// code that already knows what it is getting.
2519///
2520/// # Errors
2521///
2522/// [`CliError`] when `--offline` forbade it, when there are input files as well, when the tuple is
2523/// not a target this compiler knows, when its sysroot is behind Apple's licence wall, and when this
2524/// release pins no artifact for it.
2525fn fetch_action(
2526    named: &str,
2527    offline: bool,
2528    accepted: bool,
2529    inputs: &[Input],
2530) -> Result<Action, CliError> {
2531    // Not a precedence question. Section 13.2 says `--offline` forbids a fetch entirely, so a
2532    // command line that writes both has asked for two opposite things and the answer is to say so
2533    // rather than to pick one of them.
2534    if offline {
2535        return Err(err(
2536            "--fetch asks for a download and --offline forbids every download, so this command \
2537             line asks for two opposite things. Drop one of them: --offline is how a build says it \
2538             will not reach the network, and --fetch is one of the two things in this compiler \
2539             that reaches it",
2540        ));
2541    }
2542    if let Some(first) = inputs.first() {
2543        return Err(err(format!(
2544            "--fetch gets a sysroot and compiles nothing, so `{}` on the same command line is an \
2545             input that nothing would read",
2546            first.path
2547        )));
2548    }
2549    let target: TargetTuple = named
2550        .parse()
2551        .map_err(|why| err(format!("--fetch {named}: {why}, so there is no sysroot to get")))?;
2552    // The canonical spelling, because that is what a row is named by and what the directory under
2553    // the cache is called, and a person is free to write a tuple the long way round.
2554    let tuple = target.to_canonical_string();
2555    // Microsoft's side of the wall has something to fetch after all, which is the files its own
2556    // installer would fetch, from the build this release pins and only once the licence has been
2557    // accepted. Nothing of it is ours and nothing of it comes from us, which is why it is the other
2558    // action with a flag on it rather than a row in the table.
2559    if rucc_sysroot::Wall::of(target) == Some(rucc_sysroot::Wall::Microsoft) {
2560        return Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir(), pinned: true });
2561    }
2562    // Before the table is consulted, because a target behind a licence wall is not a row that has not
2563    // been written yet. Section 13.4 is that no release pins one of these ever, so the message says
2564    // the licence and the two lawful ways rather than naming the producer that will publish the rest.
2565    if let Some(wall) = rucc_sysroot::Wall::of(target) {
2566        return Err(err(format!("--fetch {tuple}: {}", wall.no_fetch(&tuple))));
2567    }
2568    let Some(what) = rucc_sysroot::pinned_for_target(target) else {
2569        return Err(err(unpinned(&tuple)));
2570    };
2571    Ok(Action::Fetch { what, target, cache: cache::dir() })
2572}
2573
2574/// What `--fetch-msvc-sdk <tuple>` asks for, weighed the same way the fetch above is.
2575///
2576/// The target is resolved here rather than where the work happens, so that a tuple this compiler
2577/// does not know and a target that is not behind Microsoft's wall are refusals from the parser like
2578/// every other thing a command line can ask for and not have. Whether the licence was accepted is
2579/// carried rather than acted on, because what it changes is what the command does and not whether
2580/// the command line made sense.
2581///
2582/// # Errors
2583///
2584/// [`CliError`] when `--offline` forbade it, when there are input files as well, and when the tuple
2585/// is not a target this compiler knows.
2586fn fetch_msvc_action(
2587    named: &str,
2588    offline: bool,
2589    accepted: bool,
2590    inputs: &[Input],
2591) -> Result<Action, CliError> {
2592    if offline {
2593        return Err(err(
2594            "--fetch-msvc-sdk asks for a download and --offline forbids every download, so this \
2595             command line asks for two opposite things. Drop one of them: --offline is how a build \
2596             says it will not reach the network",
2597        ));
2598    }
2599    if let Some(first) = inputs.first() {
2600        return Err(err(format!(
2601            "--fetch-msvc-sdk gets an SDK and compiles nothing, so `{}` on the same command line \
2602             is an input that nothing would read",
2603            first.path
2604        )));
2605    }
2606    let target: TargetTuple = named.parse().map_err(|why| {
2607        err(format!("--fetch-msvc-sdk {named}: {why}, so there is no SDK to get"))
2608    })?;
2609    Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir(), pinned: false })
2610}
2611
2612/// Why there is nothing to fetch for a target, which is a different sentence when the table is
2613/// empty.
2614///
2615/// A release that pins nothing and a release that pins eleven targets and not this one are two
2616/// situations, and a message that did not tell them apart would send somebody looking for a typo in
2617/// their tuple when the answer is that this work is not finished.
2618fn unpinned(tuple: &str) -> String {
2619    let pinned = rucc_sysroot::pinned_targets();
2620    if pinned.is_empty() {
2621        return format!(
2622            "this release pins no sysroot for {tuple}, and it pins none for any target yet. A \
2623             sysroot is built and published by the producer in tamnd/rucc-cross, per \
2624             spec/cross-compile/13-distribution.md section 13.8, and a release of this compiler \
2625             names one by URL and by hash afterwards. Until then, pass --sysroot=<dir> to compile \
2626             against a tree you have already"
2627        );
2628    }
2629    format!(
2630        "this release pins no sysroot for {tuple}. What it pins is {}. Pass --sysroot=<dir> to \
2631         compile against a tree you have already",
2632        pinned.join(", ")
2633    )
2634}
2635
2636/// Gets the artifact and installs it, saying what each step did.
2637///
2638/// The steps are section 13.8's and so are the messages: the transport is somebody else's program
2639/// and the check is ours, so a person reading this wants to know which downloader ran, that the
2640/// bytes matched, how many files the record named and where the tree ended up. A fetch of something
2641/// that is already there says that instead and moves nothing.
2642///
2643/// A Linux target is two artifacts, its own sysroot and the kernel header tree every Linux target
2644/// shares, and `kernel` is the second one when the target reads it. It is fetched after the sysroot
2645/// and by the same two steps, so a machine that has fetched one Linux target already has it and a
2646/// second target's fetch says so and moves nothing.
2647fn fetch_sysroot(
2648    what: &rucc_sysroot::Pinned,
2649    kernel: Option<&rucc_sysroot::Pinned>,
2650    target: TargetTuple,
2651    cache: &std::path::Path,
2652) -> i32 {
2653    let tuple = target.to_canonical_string();
2654    let say = |line: &str| println!("rucc: {tuple}: {line}");
2655    if let Err(why) = bring(what, cache, &say) {
2656        return complain(why);
2657    }
2658    let archive = what.archive_in(cache);
2659    match install::install(&archive, what.sha256, target, cache) {
2660        Ok(done) => report(&done, "sysroot", &say),
2661        Err(why) => return complain(why),
2662    }
2663    let Some(kernel) = kernel else { return 0 };
2664    if let Err(why) = bring(kernel, cache, &say) {
2665        return complain(why);
2666    }
2667    match install::install_kernel(&kernel.archive_in(cache), kernel.sha256, cache) {
2668        Ok(done) => {
2669            report(&done, "kernel header tree", &say);
2670            0
2671        }
2672        Err(why) => complain(why),
2673    }
2674}
2675
2676/// The download half of a fetch, for one artifact.
2677fn bring(
2678    what: &rucc_sysroot::Pinned,
2679    cache: &std::path::Path,
2680    say: &impl Fn(&str),
2681) -> Result<(), CliError> {
2682    let archive = what.archive_in(cache);
2683    match fetch::fetch(what.url, what.sha256, &archive)? {
2684        fetch::Fetched::AlreadyThere => {
2685            say(&format!("{} is already here and matches the hash", archive.display()));
2686        }
2687        fetch::Fetched::Downloaded(by) => {
2688            say(&format!("downloaded {} with {}", what.url, by.program()));
2689        }
2690    }
2691    Ok(())
2692}
2693
2694/// What an install did, in the words a person reading a fetch wants.
2695fn report(done: &install::Installed, what: &str, say: &impl Fn(&str)) {
2696    match &done.before {
2697        install::Before::Nothing => {
2698            say(&format!("{} files installed at {}", done.files, done.root.display()));
2699        }
2700        install::Before::TheSame => {
2701            say(&format!(
2702                "the same {what} is already at {}, so nothing moved",
2703                done.root.display()
2704            ));
2705        }
2706        install::Before::Different(was) => {
2707            say(&format!(
2708                "{} files installed at {}, over a tree whose record digested to {was}",
2709                done.files,
2710                done.root.display()
2711            ));
2712        }
2713    }
2714    say(&format!("the {what}'s record digests to {}", done.digest));
2715}
2716
2717/// What one of the `-dump` and `-print` flags prints.
2718///
2719/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
2720/// which is what makes the answer safe to paste into a link line whether or not the file is
2721/// there, and this does the same.
2722fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
2723    let found = |name: &str| {
2724        link::find_in_search(link, opts.target, name)
2725            .map_or_else(|| name.to_owned(), |path| path.display().to_string())
2726    };
2727    Ok(match query {
2728        Query::Machine => opts.target.to_string(),
2729        Query::Version => opts.gnuc.major.to_string(),
2730        Query::FullVersion => {
2731            format!("{}.{}.{}", opts.gnuc.major, opts.gnuc.minor, opts.gnuc.patch)
2732        }
2733        Query::Multiarch => link::multiarch(opts.target),
2734        // The three lines GCC prints, in its order and with its punctuation, because what reads
2735        // them is a script written against that shape. There is no installation directory to
2736        // report: this compiler is one binary that works wherever it is copied, and the headers
2737        // it ships are inside it, so `install` is where the binary is and nothing is under it.
2738        Query::SearchDirs => {
2739            let here = std::env::current_exe()
2740                .ok()
2741                .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
2742                .unwrap_or_default();
2743            let list = |dirs: &[PathBuf]| {
2744                dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
2745            };
2746            let libraries = link::search_dirs(link, opts.target);
2747            format!(
2748                "install: {}\nprograms: ={}\nlibraries: ={}",
2749                here.display(),
2750                list(&link.prefixes),
2751                list(&libraries)
2752            )
2753        }
2754        // The root the rest of the answers are under, which a build system asks for when it wants
2755        // to find a file itself rather than ask for one by name, and which is the first thing to
2756        // look at when a cross build read a header nobody expected. A native compile has no
2757        // sysroot and the answer is the empty line, which is what GCC prints when it was
2758        // configured without one. `--sysroot` wins over ours because it wins everywhere else.
2759        Query::Sysroot => {
2760            sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
2761        }
2762        // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
2763        // compiler's own code, what it is, where it was got, its hash, its licence and whether it
2764        // was bundled, generated or fetched. What is printed is the manifest the sysroot already
2765        // carries rather than a second format saying the same things, because the three uses 13.5
2766        // gives for this are a licence notice, a reproducibility check and a security audit, and all
2767        // three are somebody else parsing it. One format is one parser to write.
2768        // Read and rendered rather than copied out, so that what comes back is the format this
2769        // build understands. The last newline comes off because whatever prints an answer adds
2770        // one, the way it does for every other query here. Keeping it would put a blank line at
2771        // the end of the one answer that is a file somebody diffs against the file it came from.
2772        Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
2773            Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
2774            None => String::new(),
2775        },
2776        // Section 13.2 of the same document, which asks for the hash of a cache directory's
2777        // contents in the directory's name. A name cannot carry one, because the path has to be
2778        // computable before anything has been read, by the producer about to write the files and by
2779        // the compiler about to read them, and neither has the contents when it asks. So the number
2780        // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
2781        // which means `sha256sum` over the manifest answers the same thing.
2782        Query::SysrootDigest => match sysroot_manifest(opts, link)? {
2783            Some(manifest) => manifest.digest(),
2784            None => String::new(),
2785        },
2786        Query::FileName(name) => found(name),
2787        // The name GCC gives the library of routines a compiler's output calls that the C
2788        // library does not have. Ours is built in and there is no file, so the answer is the
2789        // name itself, which is what GCC prints when it cannot find one either.
2790        Query::Libgcc => found("libgcc.a"),
2791        // A program rather than a library: the linker and the archiver are the ones a build asks
2792        // about, and this compiler finds them on the path or under `-B` rather than shipping
2793        // them, so the name back is the honest answer unless a `-B` prefix holds one.
2794        Query::ProgName(name) => link
2795            .prefixes
2796            .iter()
2797            .map(|dir| dir.join(name))
2798            .find(|path| path.is_file())
2799            .map_or_else(|| name.clone(), |path| path.display().to_string()),
2800    })
2801}
2802
2803/// The root every sysroot answer is about.
2804///
2805/// One function rather than a copy in each, because the other flags exist to say what is inside the
2806/// tree this one names, and two answers that disagreed about which tree that is would be a
2807/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
2808/// else.
2809fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
2810    link.sysroot
2811        .clone()
2812        .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
2813}
2814
2815/// The record of the sysroot this command line reads, when there is one to read.
2816///
2817/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
2818/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
2819/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
2820/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
2821/// inputs in it because that one still has its header lines.
2822///
2823/// # Errors
2824///
2825/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
2826/// record we could not read on to whoever asked would make their parser the one that finds the
2827/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
2828/// output.
2829fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
2830    let Some(root) = sysroot_root(opts, link) else {
2831        return Ok(None);
2832    };
2833    let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
2834    match std::fs::read_to_string(&path) {
2835        Ok(text) => Manifest::parse(&text)
2836            .map(Some)
2837            .map_err(|why| err(format!("{}: {why}", path.display()))),
2838        Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
2839        Err(why) => Err(err(format!("{}: {why}", path.display()))),
2840    }
2841}
2842
2843/// Renders the passes this level will run, in order, with what each one does.
2844///
2845/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
2846/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
2847/// emerges from which flags happen to be set, and this is how that list is read.
2848#[must_use]
2849pub fn print_pipeline(opts: &Options) -> String {
2850    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
2851    settings.toggles.clone_from(&opts.passes);
2852    settings.global_fuel = opts.pass_fuel_global;
2853    for (on, spec) in &opts.pass_gates {
2854        // Every spelling was checked while the arguments were parsed, so there is nothing here
2855        // this can refuse, and a listing is not the place to report it if there were.
2856        let _ = settings.gates.add(*on, spec);
2857    }
2858    rucc_opt::pipeline::print(&settings)
2859}
2860
2861/// Renders the resolved configuration.
2862///
2863/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
2864/// this output is diffed across hosts in CI and a reordering would read as a change.
2865#[must_use]
2866pub fn print_config(opts: &Options) -> String {
2867    let sess = Session::new(opts.clone());
2868    let t = &sess.target;
2869    let mut out = String::new();
2870    let _ = writeln!(out, "version: {VERSION}");
2871    // The three field triple the driver was given rather than the ten field tuple it widens to,
2872    // because this output is what a build system reads to find out what it asked for. The tuple is
2873    // the compiler's model of the machine and this line is a receipt for a command line.
2874    let _ = writeln!(out, "target: {}", opts.target);
2875    let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
2876    let _ = writeln!(out, "os: {}", opts.target.os.as_str());
2877    let _ = writeln!(out, "env: {}", opts.target.env.as_str());
2878    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
2879    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
2880    let _ = writeln!(out, "long-width: {}", t.long_width);
2881    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
2882    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
2883    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
2884    let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
2885    // The register file as a count per class, which is enough to tell a target whose registers
2886    // are described from one whose are not without printing sixteen names nobody asked for.
2887    let regs: Vec<String> = t
2888        .regs
2889        .classes()
2890        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
2891        .collect();
2892    let _ = writeln!(
2893        out,
2894        "registers: {}",
2895        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
2896    );
2897    // What the schedule was chosen with, which is a sentence rather than a name on purpose: two
2898    // runs of a benchmark that disagree are usually two models and not two compilers.
2899    let _ = writeln!(out, "timing-model: {}", t.timing.map_or("none", |timing| timing.model));
2900    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
2901    let _ = writeln!(out, "safety: {}", sess.opts.safety);
2902    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
2903    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
2904    let _ = writeln!(out, "frame-pointer: {}", sess.opts.keeps_frame_pointer());
2905    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
2906    let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
2907    let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
2908    let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
2909    let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
2910    let _ = writeln!(out, "profile: {}", sess.opts.profile);
2911    let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
2912    // Last because it is the one key with more than one line under it, and the only one
2913    // whose value is a property of the machine rather than of the command line.
2914    for dir in sess.opts.search.dirs() {
2915        let system = if dir.is_system { " (system)" } else { "" };
2916        let _ = writeln!(out, "include: {}{system}", dir.path.display());
2917    }
2918    out
2919}
2920
2921/// The output name the make target is taken from, which is the `-o` argument or nothing.
2922///
2923/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
2924/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
2925/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
2926/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
2927/// `-S` on the argument does name what the rule builds, and it is used as written.
2928fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
2929    if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
2930}
2931
2932/// Writes to a path the command line named rather than one the plan derived, where `-` is
2933/// standard output.
2934fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
2935    if path == "-" {
2936        return write_out(&Output::Stdout, bytes);
2937    }
2938    write_out(&Output::File(path.to_owned()), bytes)
2939}
2940
2941/// Writes the make rule for one input, and reports whether it got there.
2942///
2943/// A rule with no file of its own goes where the compilation it replaced would have written,
2944/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
2945/// `$@`, and the same line with the `-o` left off puts it on standard output.
2946fn write_deps(
2947    opts: &Options,
2948    plan: &Plan,
2949    job: &Job,
2950    found: &[Dependency],
2951    stderr: &mut impl std::io::Write,
2952) -> bool {
2953    let targets = if opts.deps.targets.is_empty() {
2954        vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
2955    } else {
2956        opts.deps.targets.clone()
2957    };
2958    let rule = deps::rule(&opts.deps, &targets, &job.input, found);
2959    // The file, on the other hand, is named after the `-o` in every mode that still has one to
2960    // spend, which is every mode except the two that spend it on the rule.
2961    let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
2962        // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
2963        // named empty rather than absent, because a makefile that named it as a target of its
2964        // own is a makefile that will look for it.
2965        Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
2966            if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
2967        }),
2968        None => write_out(&job.output, rule.as_bytes()),
2969    };
2970    if let Err(e) = wrote {
2971        let _ = writeln!(stderr, "rucc: error: {e}");
2972        return false;
2973    }
2974    true
2975}
2976
2977/// Runs phase 4 over every input that has one, and writes what came out.
2978///
2979/// One input that fails does not stop the others. A build that reports every file it could
2980/// not preprocess in one run is worth more than one that stops at the first, and the exit
2981/// status is still a failure either way.
2982fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
2983    let fs = OsFileSystem::new();
2984    let mut stderr = std::io::stderr().lock();
2985    let mut failed = false;
2986    for job in &plan.jobs {
2987        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
2988            // An input that is already preprocessed, or an object file. GCC passes these
2989            // through untouched, and the plan has already said so in its notes.
2990            continue;
2991        }
2992        let started = std::time::Instant::now();
2993        let result = preprocess(opts, &job.input, &fs);
2994        if opts.time {
2995            say_time(&job.input, started.elapsed(), &mut stderr);
2996        }
2997        for message in &result.messages {
2998            let _ = writeln!(stderr, "{message}");
2999        }
3000        if result.failed() {
3001            failed = true;
3002            continue;
3003        }
3004        if opts.deps.emit {
3005            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3006            // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
3007            // to write. The other two asked for both and fall through to the text below.
3008            if opts.deps.instead_of_compiling {
3009                continue;
3010            }
3011        }
3012        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
3013            let _ = writeln!(stderr, "rucc: error: {e}");
3014            failed = true;
3015        }
3016    }
3017    i32::from(failed)
3018}
3019
3020/// Whether this job is a file of assembly that has to be assembled and that nothing here assembles.
3021///
3022/// The phases rather than the kind, because there are two kinds of assembly input and one of them
3023/// is preprocessed first, and because an object file also has no compile phase and is not this: it
3024/// has no phases at all and goes to the linker as it is. A `.s` on a `-c` line has exactly
3025/// [`Phase::Assemble`] left, and a `.S` has the preprocessor in front of it, and neither has
3026/// anything the front end can do.
3027fn needs_an_assembler(job: &Job) -> bool {
3028    job.phases.contains(&Phase::Assemble) && !job.phases.contains(&Phase::Compile)
3029}
3030
3031/// Whether the preprocessor runs over it on the way in, which is the whole difference between the
3032/// two kinds of assembly input.
3033fn assembly_wants_cpp(job: &Job) -> bool {
3034    job.phases.contains(&Phase::Preprocess)
3035}
3036
3037/// Runs the front end over every input that has a compile phase, and writes what came out.
3038///
3039/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
3040/// exit status is a failure either way. An input that is already assembly or an object has no
3041/// compile phase and is passed over here, which the plan has already said in its notes.
3042fn compile_all(opts: &Options, plan: &Plan) -> i32 {
3043    let fs = OsFileSystem::new();
3044    let mut stderr = std::io::stderr().lock();
3045    let mut failed = false;
3046    let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3047    failed |= !ok;
3048    let mut fired = Fired::new();
3049    let mut pressure = Pressure::new();
3050    let mut lowerings = Lowerings::new();
3051    for job in &plan.jobs {
3052        if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3053            continue;
3054        }
3055        // An input of IR is read back rather than compiled, since the C it came from is not
3056        // here any more. A file of assembly does not go through the front end at all and is
3057        // read by the assembler instead. Everything after this is the same for all three, so
3058        // the paths meet again at the messages and the file the result is written to.
3059        let started = std::time::Instant::now();
3060        let result = if needs_an_assembler(job) {
3061            assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3062        } else if job.kind == InputKind::Ir {
3063            compile_ir(opts, &job.input, &fs)
3064        } else {
3065            compile(opts, &job.input, &fs)
3066        };
3067        if opts.time {
3068            say_time(&job.input, started.elapsed(), &mut stderr);
3069        }
3070        failed |= !write_trace(opts, job, started, &result, &mut stderr);
3071        fired.merge(&result.fired);
3072        pressure.merge(&result.pressure);
3073        lowerings.merge(&result.lowerings);
3074        failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3075        failed |= !remarks.write(&result.remarks, &mut stderr);
3076        for message in &result.messages {
3077            let _ = writeln!(stderr, "{message}");
3078        }
3079        // Before the failure below, because a compilation that stopped in the back end is exactly
3080        // the one whose preprocessed source somebody wants to look at.
3081        failed |= !write_temps(job, &result.temps, &mut stderr);
3082        // Before it as well, because gcc leaves an empty report for a file that did not compile
3083        // and a build that looks for one beside every object should find one.
3084        failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3085        if result.failed() {
3086            failed = true;
3087            continue;
3088        }
3089        // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
3090        // this is the one path where both files come out of the same run. An input of IR has no
3091        // dependencies to report and produces an empty list, which produces a rule naming only
3092        // itself, and that is the honest answer rather than a missing file.
3093        if opts.deps.emit {
3094            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3095        }
3096        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
3097            let _ = writeln!(stderr, "rucc: error: {e}");
3098            failed = true;
3099        }
3100    }
3101    failed |= !write_coverage(opts, &fired, &mut stderr);
3102    failed |= !write_pressure(opts, &pressure, &mut stderr);
3103    failed |= !write_lowering(opts, &lowerings, &mut stderr);
3104    i32::from(failed)
3105}
3106
3107/// A directory for the object files only the link step ever sees, removed when it goes away.
3108///
3109/// `-c` writes its object where the user can see it and linking does not, which is the whole of
3110/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
3111/// every other compiler. Removing them on drop rather than at the end of a function is so that a
3112/// link that failed leaves nothing behind either.
3113struct Scratch {
3114    /// Where the objects go.
3115    dir: PathBuf,
3116}
3117
3118impl Scratch {
3119    /// Makes one, under whatever the platform calls its temporary directory.
3120    ///
3121    /// The name carries the process id so that two compilers running at once do not share a
3122    /// directory, which they would otherwise do the moment two of them compiled a file of the
3123    /// same name.
3124    fn new() -> Result<Scratch, String> {
3125        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
3126        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
3127        Ok(Scratch { dir })
3128    }
3129}
3130
3131impl Drop for Scratch {
3132    fn drop(&mut self) {
3133        let _ = std::fs::remove_dir_all(&self.dir);
3134    }
3135}
3136
3137/// The link line the plan describes, for `-###`.
3138///
3139/// The names in it are the hints the plan carries rather than the temporaries a real compilation
3140/// would choose, because `-###` prints the line without having compiled anything and so has
3141/// nothing to point at. That also makes the printed line readable rather than naming a directory
3142/// that only exists while a compilation is running.
3143fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
3144    let linker = link::find(opts.target, link)?;
3145    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
3146    Ok(link::render(&linker, &args))
3147}
3148
3149/// Compiles everything, then links it.
3150///
3151/// The objects go in a directory that is removed afterwards, which is why this is not
3152/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
3153/// and does not say where, because where is a question that only has an answer once something is
3154/// running.
3155fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
3156    let Some(job) = &plan.link else {
3157        // Every path into here comes from a plan whose last phase is the link, and such a plan
3158        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
3159        let mut stderr = std::io::stderr().lock();
3160        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
3161        return 1;
3162    };
3163    // Before anything is compiled, because a linker that is not on the machine is worth knowing
3164    // about in the second it takes to look rather than after the compilation.
3165    // And before that, whether this link has a line at all and whether what it reads is on the
3166    // machine. Both are answerable now, and a target whose sysroot has not been built is worth
3167    // saying so about before the compilation rather than after it.
3168    if let Err(why) = link::preflight(opts.target, link) {
3169        return complain(why);
3170    }
3171    let linker = match link::find(opts.target, link) {
3172        Ok(linker) => linker,
3173        Err(why) => return complain(why),
3174    };
3175    // Whether the one that was found can do this link is asked inside the search, which moves on
3176    // past an lld that is too old to a newer one somewhere else and refuses only when there is none.
3177    // The glibc stubs, which are the one part of a cross sysroot written here rather than fetched.
3178    // Before compiling for the same reason as the rest, and never for `-###`, which writes nothing.
3179    if let Err(why) = link::write_stubs(opts.target, link) {
3180        return complain(why);
3181    }
3182
3183    let scratch = match Scratch::new() {
3184        Ok(scratch) => scratch,
3185        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
3186    };
3187
3188    let fs = OsFileSystem::new();
3189    let mut failed = false;
3190    // One per job, in job order, which is what lets the link line below be rebuilt with the real
3191    // paths in it: every job contributes exactly one file to the line and does so in this order.
3192    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
3193    let mut fired = Fired::new();
3194    let mut pressure = Pressure::new();
3195    let mut lowerings = Lowerings::new();
3196    {
3197        let mut stderr = std::io::stderr().lock();
3198        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3199        failed |= !ok;
3200        for (at, job) in plan.jobs.iter().enumerate() {
3201            let out = match &job.output {
3202                Output::Temporary(hint) => {
3203                    // The index because two inputs in different directories can have the same
3204                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
3205                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
3206                }
3207                Output::File(path) => path.clone(),
3208                // A job feeding the linker never writes to standard output, since the plan gives
3209                // it a temporary. This is here so that the match is total rather than a panic.
3210                Output::Stdout => continue,
3211            };
3212            produced.push(out.clone());
3213            if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3214                continue;
3215            }
3216            let started = std::time::Instant::now();
3217            let result = if needs_an_assembler(job) {
3218                assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3219            } else if job.kind == InputKind::Ir {
3220                compile_ir(opts, &job.input, &fs)
3221            } else {
3222                compile(opts, &job.input, &fs)
3223            };
3224            if opts.time {
3225                say_time(&job.input, started.elapsed(), &mut stderr);
3226            }
3227            failed |= !write_trace(opts, job, started, &result, &mut stderr);
3228            fired.merge(&result.fired);
3229            pressure.merge(&result.pressure);
3230            lowerings.merge(&result.lowerings);
3231            failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3232            failed |= !remarks.write(&result.remarks, &mut stderr);
3233            for message in &result.messages {
3234                let _ = writeln!(stderr, "{message}");
3235            }
3236            failed |= !write_temps(job, &result.temps, &mut stderr);
3237            failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3238            if result.failed() {
3239                failed = true;
3240                continue;
3241            }
3242            // A `-MD` on a command line that links writes the rule next to the executable and
3243            // names the executable as its target, since that is the file this source builds
3244            // here. The object it went through is in a temporary directory and is gone by the
3245            // time `make` reads any of this.
3246            if opts.deps.emit {
3247                failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3248            }
3249            if !matches!(result.artifact, Artifact::Object { .. }) {
3250                // Worth saying rather than writing whatever it is and letting the linker read it.
3251                // An empty file is a valid empty linker script, so a link handed one gets as far
3252                // as reporting every symbol of this file undefined, which is a page of messages
3253                // about something that went wrong here.
3254                let _ = writeln!(
3255                    stderr,
3256                    "rucc: internal error: {}: no object file was produced for the link",
3257                    job.input
3258                );
3259                failed = true;
3260                continue;
3261            }
3262            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
3263                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
3264                failed = true;
3265            }
3266        }
3267        failed |= !write_coverage(opts, &fired, &mut stderr);
3268        failed |= !write_pressure(opts, &pressure, &mut stderr);
3269        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3270        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3271    }
3272    if failed {
3273        // Nothing is linked from a compilation that did not finish. A linker run over the objects
3274        // that did compile would report every function of the file that did not as undefined,
3275        // which is a page of messages about a mistake already reported once.
3276        return 1;
3277    }
3278
3279    // The items in command line order with the temporaries filled in. A library and a word for the
3280    // linker contribute no job and pass through, and every file item takes the next job's real
3281    // output, which is what keeps whatever was written between two objects between them here.
3282    let mut outputs = produced.into_iter();
3283    let mut items = Vec::with_capacity(job.inputs.len());
3284    for item in &job.inputs {
3285        match item {
3286            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
3287            link::Item::Linker(arg) => items.push(link::Item::Linker(arg.clone())),
3288            link::Item::File(_) => match outputs.next() {
3289                Some(path) => items.push(link::Item::File(path)),
3290                None => return complain("the plan asks the linker for a file nothing produced"),
3291            },
3292        }
3293    }
3294
3295    let args = match link::line(opts.target, link, &items, &job.output) {
3296        Ok(args) => args,
3297        Err(why) => return complain(why),
3298    };
3299    if verbose {
3300        let mut stderr = std::io::stderr().lock();
3301        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
3302    }
3303    let started = std::time::Instant::now();
3304    let ran = link::run(&linker, &args);
3305    if opts.time {
3306        // The one step of a compilation that really is another program, so this line is the same
3307        // measurement gcc's is and names the linker the way gcc names `collect2`.
3308        let mut stderr = std::io::stderr().lock();
3309        say_time(&linker.name, started.elapsed(), &mut stderr);
3310    }
3311    match ran {
3312        Ok(()) => 0,
3313        // The linker has already said what was wrong on its own error output, and repeating that
3314        // linking failed would only push its message further up the screen.
3315        Err(link::Error::Refused { .. }) => 1,
3316        Err(why) => complain(why),
3317    }
3318}
3319
3320/// Compiles everything and writes the objects into one static library.
3321///
3322/// No temporary directory and no second program. The objects never reach the file system at all:
3323/// they go from the compiler into the archive writer, which is both faster than writing a directory
3324/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
3325/// member's index entries are the names the object writer says it wrote, and the only thing that
3326/// knows those is the run that wrote it.
3327///
3328/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
3329/// person can find, and they are written there as well as put in the archive.
3330fn archive_all(opts: &Options, plan: &Plan) -> i32 {
3331    let Some(job) = &plan.archive else {
3332        // Every path into here comes from a plan whose last phase is the archive, and such a plan
3333        // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
3334        return complain("there is nothing to put in an archive");
3335    };
3336    // Before anything is compiled, because a format this has no container for is worth knowing
3337    // about in the second it takes to look rather than after the whole compilation.
3338    let flavour = match opts.target.os.object_format() {
3339        ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
3340        ObjectFormat::Coff => rucc_archive::Flavour::Coff,
3341        ObjectFormat::MachO => rucc_archive::Flavour::Bsd,
3342        // Wasm has no archives of its own at all.
3343        format @ ObjectFormat::Wasm => {
3344            return complain(format!(
3345                "there is no archive format for {} objects in this compiler yet",
3346                format.as_str()
3347            ));
3348        }
3349    };
3350
3351    let fs = OsFileSystem::new();
3352    let mut failed = false;
3353    let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
3354    let mut names = job.members.iter();
3355    let mut fired = Fired::new();
3356    let mut pressure = Pressure::new();
3357    let mut lowerings = Lowerings::new();
3358    {
3359        let mut stderr = std::io::stderr().lock();
3360        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3361        failed |= !ok;
3362        for plan_job in &plan.jobs {
3363            // What the plan called this member. The two lists are walked together rather than the
3364            // name being worked out again here, so that what `-###` printed and what goes in the
3365            // file cannot come apart.
3366            let Some(member) = names.next() else {
3367                return complain("the plan asks the archive for a member nothing produced");
3368            };
3369            if !plan_job.phases.contains(&Phase::Compile) && !needs_an_assembler(plan_job) {
3370                // Neither something to compile nor something to assemble, so there is nothing to
3371                // put in, and an archive quietly missing a member is worse than a message.
3372                let _ = writeln!(
3373                    &mut stderr,
3374                    "rucc: error: {}: this compiler makes an archive out of what it compiles, and \
3375                     there is nothing here for it to do",
3376                    plan_job.input
3377                );
3378                failed = true;
3379                continue;
3380            }
3381            let started = std::time::Instant::now();
3382            let result = if needs_an_assembler(plan_job) {
3383                assemble(opts, &plan_job.input, assembly_wants_cpp(plan_job), &fs)
3384            } else if plan_job.kind == InputKind::Ir {
3385                compile_ir(opts, &plan_job.input, &fs)
3386            } else {
3387                compile(opts, &plan_job.input, &fs)
3388            };
3389            if opts.time {
3390                say_time(&plan_job.input, started.elapsed(), &mut stderr);
3391            }
3392            failed |= !write_trace(opts, plan_job, started, &result, &mut stderr);
3393            fired.merge(&result.fired);
3394            pressure.merge(&result.pressure);
3395            lowerings.merge(&result.lowerings);
3396            failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
3397            failed |= !remarks.write(&result.remarks, &mut stderr);
3398            for message in &result.messages {
3399                let _ = writeln!(stderr, "{message}");
3400            }
3401            failed |= !write_temps(plan_job, &result.temps, &mut stderr);
3402            failed |= !write_stack_usage(plan_job, &result.stack_usage, &mut stderr);
3403            if result.failed() {
3404                failed = true;
3405                continue;
3406            }
3407            if opts.deps.emit {
3408                failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
3409            }
3410            let Artifact::Object { bytes, defines } = result.artifact else {
3411                let _ = writeln!(
3412                    stderr,
3413                    "rucc: internal error: {}: no object file was produced for the archive",
3414                    plan_job.input
3415                );
3416                failed = true;
3417                continue;
3418            };
3419            // Under `-save-temps` the plan gave the object a name a person can find, so it is
3420            // written there too. Otherwise it is only ever a member and never a file.
3421            if let Output::File(path) = &plan_job.output {
3422                if let Err(e) = std::fs::write(path, &bytes) {
3423                    let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3424                    failed = true;
3425                }
3426            }
3427            members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
3428        }
3429        failed |= !write_coverage(opts, &fired, &mut stderr);
3430        failed |= !write_pressure(opts, &pressure, &mut stderr);
3431        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3432        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3433    }
3434    if failed {
3435        // Nothing is written from a compilation that did not finish, for the reason the link gives:
3436        // an archive missing the file that failed is one a link reports every name of as undefined,
3437        // which is a page of messages about a mistake already reported once.
3438        return 1;
3439    }
3440
3441    let bytes = match rucc_archive::write(flavour, &members) {
3442        Ok(bytes) => bytes,
3443        // Every one of these is a bug here rather than a program's mistake: the names came from the
3444        // object writer and the bodies came from this process.
3445        Err(why) => return complain(format!("the archive could not be written: {why}")),
3446    };
3447    match std::fs::write(&job.output, &bytes) {
3448        Ok(()) => 0,
3449        Err(e) => complain(format!("{}: {e}", job.output)),
3450    }
3451}
3452
3453/// Prints one driver level message and gives back the exit status that goes with it.
3454fn complain(why: impl std::fmt::Display) -> i32 {
3455    let mut stderr = std::io::stderr().lock();
3456    let _ = writeln!(stderr, "rucc: error: {why}");
3457    1
3458}
3459
3460/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
3461///
3462/// Once for the whole command line rather than once per input, because the question is which
3463/// lowering rules this run of the compiler reached and a file per input would leave the reader
3464/// unioning files to find out something one process already knew.
3465///
3466/// A file that could not be written is a failure and not a warning. What asks for this is a
3467/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
3468fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
3469    let Some(path) = &opts.rule_coverage else { return true };
3470    let Some(table) = coverage::table(opts.target.arch) else {
3471        let _ = writeln!(
3472            stderr,
3473            "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
3474             to report",
3475            opts.target
3476        );
3477        return false;
3478    };
3479    match std::fs::write(path, fired.listing(table)) {
3480        Ok(()) => true,
3481        Err(e) => {
3482            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3483            false
3484        }
3485    }
3486}
3487
3488/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
3489///
3490/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3491/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
3492/// rule table here, since every target this compiles for has an allocator, and a run that reached
3493/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
3494/// produced no code is still an answer and it is the honest one.
3495fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
3496    let Some(path) = &opts.register_pressure else { return true };
3497    match std::fs::write(path, pressure.listing()) {
3498        Ok(()) => true,
3499        Err(e) => {
3500            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3501            false
3502        }
3503    }
3504}
3505
3506/// Writes what `-Zlowering=FILE` asked for, and says whether it could.
3507///
3508/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3509/// not be written is a failure for the reason it gives too. A run that reached no back end writes
3510/// an empty listing rather than nothing, the way [`write_pressure`] does and for the same reason.
3511fn write_lowering(opts: &Options, lowerings: &Lowerings, stderr: &mut impl std::io::Write) -> bool {
3512    let Some(path) = &opts.lowering_dump else { return true };
3513    match std::fs::write(path, lowerings.listing()) {
3514        Ok(()) => true,
3515        Err(e) => {
3516            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3517            false
3518        }
3519    }
3520}
3521
3522/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
3523///
3524/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
3525/// A file rather than the diagnostic stream is what a harness wants: the corpus in
3526/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
3527/// a few thousand remarks mixed into that would bury it.
3528struct Remarks {
3529    /// The file, if there is one.
3530    file: Option<String>,
3531    /// Whether anything has been written to it yet, which decides between truncating and
3532    /// appending. One file holds the whole run rather than the last input in it.
3533    started: bool,
3534}
3535
3536impl Remarks {
3537    /// Prepares the destination, emptying the file if there is one.
3538    ///
3539    /// Emptied here rather than at the first remark, because a run where no pass had anything to
3540    /// say should leave an empty file and not yesterday's. An absent file and an empty one are
3541    /// different facts and something reading this will act on the difference.
3542    fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
3543        let mut ok = true;
3544        if let Some(path) = file {
3545            if let Err(e) = std::fs::write(path, "") {
3546                let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3547                ok = false;
3548            }
3549        }
3550        (Self { file: file.cloned(), started: false }, ok)
3551    }
3552
3553    /// Writes one input's remarks, and says whether that worked.
3554    ///
3555    /// A file that cannot be written is a failure and not a warning, for the reason
3556    /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
3557    /// where nothing happened.
3558    fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
3559        if text.is_empty() {
3560            return true;
3561        }
3562        let Some(path) = &self.file else {
3563            let _ = write!(stderr, "{text}");
3564            return true;
3565        };
3566        let opened = std::fs::OpenOptions::new()
3567            .write(true)
3568            .append(self.started)
3569            .truncate(!self.started)
3570            .create(true)
3571            .open(path);
3572        self.started = true;
3573        let result =
3574            opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
3575        if let Err(e) = result {
3576            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3577            return false;
3578        }
3579        true
3580    }
3581}
3582
3583/// Writes what `-fdump-ir=` asked to see, one file per dump.
3584///
3585/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
3586/// after a run is the passes in the order they ran, per input. They go in the working directory
3587/// rather than beside the output, because a dump is something a person asked for at a prompt and
3588/// the working directory is where that person is.
3589///
3590/// A file that could not be written is a failure and not a warning, for the reason
3591/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
3592/// quietly did not happen looks exactly like a pass that did not run.
3593fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
3594    let stem = std::path::Path::new(input)
3595        .file_name()
3596        .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
3597    let mut ok = true;
3598    for dump in dumps {
3599        let path = format!("{stem}.{}.ir", dump.name);
3600        if let Err(e) = std::fs::write(&path, &dump.text) {
3601            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3602            ok = false;
3603        }
3604    }
3605    ok
3606}
3607
3608/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
3609///
3610/// A file that could not be written is a failure rather than a warning, for the reason
3611/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
3612/// looks like a compilation that never went through that step.
3613fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
3614    let mut ok = true;
3615    let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
3616    for (path, text) in kept {
3617        // A step the compilation did not reach has nothing to keep, and a job that is not keeping
3618        // that step has nowhere to put it. Either way there is no file here.
3619        let (Some(path), Some(text)) = (path, text) else { continue };
3620        if let Err(e) = std::fs::write(&path, text) {
3621            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3622            ok = false;
3623        }
3624    }
3625    ok
3626}
3627
3628/// Writes the `.su` file `-fstack-usage` asked for, where the plan said it goes.
3629///
3630/// Written even when it is empty, because gcc writes an empty `.su` for a file with no functions,
3631/// for `-fsyntax-only` and for a file that did not compile, and a tool that looks for one beside
3632/// every object should find one.
3633fn write_stack_usage(job: &Job, text: &str, stderr: &mut impl std::io::Write) -> bool {
3634    let Some(path) = &job.stack_usage else { return true };
3635    if let Err(e) = std::fs::write(path, text) {
3636        let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3637        return false;
3638    }
3639    true
3640}
3641
3642/// Appends the file's line to the `-frucc-trace` file, when there is one.
3643///
3644/// Returns whether that went well, and says why on standard error when it did not.
3645fn write_trace(
3646    opts: &Options,
3647    job: &Job,
3648    started: std::time::Instant,
3649    result: &Compiled,
3650    stderr: &mut impl std::io::Write,
3651) -> bool {
3652    let Some(path) = &opts.trace else {
3653        return true;
3654    };
3655    let output = match &job.output {
3656        Output::Stdout => "-",
3657        Output::File(path) | Output::Temporary(path) => path,
3658    };
3659    let record = trace::Record {
3660        input: &job.input,
3661        output,
3662        ok: !result.failed(),
3663        total: started.elapsed(),
3664        timing: &result.timing,
3665    };
3666    match trace::append(path, &record) {
3667        Ok(()) => true,
3668        Err(e) => {
3669            let _ = writeln!(stderr, "rucc: error: {e}");
3670            false
3671        }
3672    }
3673}
3674
3675/// One line of `-time`, which is what a step was called and how long it took.
3676///
3677/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
3678/// no subprocess for anything but the link, so what is measured here is the wall clock of the
3679/// step and the second column is always zero. The shape of the line is kept because a person
3680/// reading it next to gcc's should not have to work out which column is which.
3681fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
3682    let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
3683}
3684
3685/// Writes one job's result where the plan said it goes.
3686///
3687/// # Errors
3688///
3689/// Returns the message to print, which names the file when there is one, because "permission
3690/// denied" on its own does not say which file was refused.
3691fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
3692    match output {
3693        Output::Stdout => {
3694            let mut stdout = std::io::stdout().lock();
3695            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
3696        }
3697        Output::File(path) | Output::Temporary(path) => {
3698            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
3699        }
3700    }
3701}
3702
3703/// The target a program name asks for, the way `aarch64-linux-gnu-gcc` is gcc for that target.
3704///
3705/// `program` is the path the compiler was started as. The name without its directory and without a
3706/// trailing `.exe` has to end in `-rucc`, and what comes before that has to be a target this
3707/// compiler knows, or there is no answer and the name means nothing. A link named `my-rucc` is
3708/// therefore just rucc and not an error.
3709pub fn target_from_program(program: &str) -> Option<String> {
3710    let name = program.rsplit(['/', '\\']).next()?;
3711    let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
3712    let triple = name.strip_suffix("-rucc")?;
3713    triple.parse::<Triple>().ok()?;
3714    Some(triple.to_owned())
3715}
3716
3717/// [`run`] for a compiler started as `program`, which is `argv[0]`.
3718///
3719/// A target taken from the name goes in front of `args`, so a `--target=` written on the command
3720/// line comes later and wins, which is what gcc and clang do with a prefixed name.
3721pub fn run_as(program: &str, args: &[String]) -> i32 {
3722    match target_from_program(program) {
3723        Some(triple) => {
3724            let mut all = Vec::with_capacity(args.len() + 1);
3725            all.push(format!("--target={triple}"));
3726            all.extend_from_slice(args);
3727            run(&all)
3728        }
3729        None => run(args),
3730    }
3731}
3732
3733/// What `--version` prints.
3734///
3735/// The first line is ours and is the one every harness we have reads. The second is for build
3736/// systems that decide what kind of compiler they have by reading this text. Meson takes the GNU
3737/// path only when it finds "Free Software Foundation" here, and otherwise stops with "Unknown
3738/// compiler" before it has asked a single question, which is how the whole of a meson build is
3739/// lost to one sentence. Past that point meson reads the version from `__GNUC__` and asks the
3740/// preprocessor everything else, so the line decides the path and nothing more. It says what is
3741/// true, that rucc speaks the dialect of GCC 16, and it does not claim to be GCC.
3742fn banner() -> String {
3743    format!(
3744        "rucc {VERSION}\nA C compiler for the GNU C dialect of GCC 16 from the Free Software Foundation.\nThis is free software under the Apache License 2.0. There is NO warranty.\n"
3745    )
3746}
3747
3748/// Runs the driver and returns the process exit code.
3749///
3750/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
3751/// is the one place in the compiler that is true.
3752pub fn run(args: &[String]) -> i32 {
3753    match parse_args(args) {
3754        Ok(Action::Help) => {
3755            print!("{USAGE}");
3756            0
3757        }
3758        Ok(Action::Version) => {
3759            print!("{}", banner());
3760            0
3761        }
3762        Ok(Action::Print(line)) => {
3763            println!("{line}");
3764            0
3765        }
3766        Ok(Action::PrintConfig(opts)) => {
3767            print!("{}", print_config(&opts));
3768            0
3769        }
3770        Ok(Action::PrintPipeline(opts)) => {
3771            print!("{}", print_pipeline(&opts));
3772            0
3773        }
3774        Ok(Action::PrintPlan { opts, plan, link }) => {
3775            print!("{}", plan.render());
3776            // The line as it would be typed, which is the half of `-###` that section 4.3 says
3777            // arrives with the link. It is printed even when the linker is not on this machine,
3778            // because what a build wants from `-###` is what the compiler would do.
3779            if let Some(job) = &plan.link {
3780                match link_line(&opts, &link, job) {
3781                    Ok(line) => println!("{line}"),
3782                    Err(why) => {
3783                        let mut stderr = std::io::stderr().lock();
3784                        let _ = writeln!(stderr, "rucc: error: {why}");
3785                        return 1;
3786                    }
3787                }
3788            }
3789            0
3790        }
3791        Ok(Action::Fetch { what, target, cache }) => {
3792            let kernel = rucc_sysroot::Kernel::for_target(&cache, target)
3793                .map(|_| &rucc_sysroot::KERNEL_HEADERS);
3794            fetch_sysroot(what, kernel, target, &cache)
3795        }
3796        Ok(Action::FetchMsvcSdk { target, accepted, cache, pinned }) => msvc::fetch_msvc_sdk(
3797            target,
3798            accepted,
3799            &cache,
3800            pinned.then_some(&rucc_sysroot::PINNED_BUILD),
3801        ),
3802        Ok(Action::Compile { opts, plan, link, jobs, verbose, notes }) => {
3803            {
3804                let mut stderr = std::io::stderr().lock();
3805                // Before the plan rather than after it, because a note is about the command line
3806                // and the plan is what the command line was read as, so the reader wants the two
3807                // in that order.
3808                for note in &notes {
3809                    let _ = writeln!(stderr, "rucc: warning: {note}");
3810                }
3811                if verbose {
3812                    let _ = write!(stderr, "{}", plan.render());
3813                    let _ = writeln!(stderr, "workers: {}", jobs.count());
3814                    // What `gcc -v` says about headers, because meson and cmake read it to find the
3815                    // system directories.
3816                    let _ = write!(stderr, "{}", opts.search.render_gcc());
3817                }
3818            }
3819            if opts.emit == EmitKind::Preprocessed {
3820                return preprocess_all(&opts, &plan);
3821            }
3822            if opts.emit == EmitKind::Archive {
3823                return archive_all(&opts, &plan);
3824            }
3825            if opts.emit != EmitKind::Executable {
3826                return compile_all(&opts, &plan);
3827            }
3828            if let Some(why) = unlinkable(&opts) {
3829                let _ = writeln!(std::io::stderr().lock(), "rucc: error: {why}");
3830                return 1;
3831            }
3832            link_all(&opts, &plan, &link, verbose)
3833        }
3834        Err(e) => {
3835            let mut stderr = std::io::stderr().lock();
3836            let _ = writeln!(stderr, "rucc: error: {e}");
3837            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
3838            1
3839        }
3840    }
3841}
3842
3843/// Why a link that was asked for cannot be made, when that is known before anything is compiled.
3844///
3845/// The checked modes need `runtime/rucc-safe-rt` in the program, and that runtime is written
3846/// against Unix: shadow memory through `mmap`, reports through a signal handler, and the maps read
3847/// out of `/proc`. There is no Windows build of it, so a Windows program compiled with one used to
3848/// fail at the link with a page of undefined `__rucc_check_` names. Saying so before the link
3849/// is kinder until the port is done. Only the link is refused: an object or a listing built
3850/// with the checks in is still what was asked for, and is what a test of the instrumentation reads.
3851fn unlinkable(opts: &Options) -> Option<String> {
3852    (opts.safety.instruments() && opts.target.os == rucc_target::Os::Windows).then(|| {
3853        format!(
3854            "-fsafety={}: the checked modes are not available on a Windows target yet, because \
3855             the runtime they need has not been ported to Windows. -c still builds the object",
3856            opts.safety
3857        )
3858    })
3859}
3860
3861#[cfg(test)]
3862mod tests {
3863    use rucc_session::{
3864        Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
3865    };
3866
3867    use super::*;
3868
3869    fn args(s: &[&str]) -> Vec<String> {
3870        s.iter().map(|x| (*x).to_owned()).collect()
3871    }
3872
3873    /// A target to write down where the host would otherwise decide, for the tests whose answer
3874    /// would be a different one on a different machine.
3875    ///
3876    /// Most of the tests here never name a target, which is right, because most of what the driver
3877    /// does with a command line is the same wherever it runs and a test that pinned one would be
3878    /// saying so in every case for the sake of the two that need it. The two that need it are the
3879    /// ones whose answer comes off the target rather than off the command line: the name an object
3880    /// gets, which is `a.o` here and `a.obj` on Windows, and whether Microsoft's reading of a
3881    /// nameless member is on, which is off here and on there. Both are the compiler being right, and
3882    /// a test that leaves the target to the host is asking a question with two correct answers.
3883    const LINUX: &str = "--target=x86_64-unknown-linux-gnu";
3884
3885    #[test]
3886    fn a_response_file_is_split_the_way_libiberty_splits_one() {
3887        let words = response_words("-Wl,--as-needed  'a b' \"c d\"\ne\\ f '' \"it's\" g\\\\h\n");
3888        assert_eq!(words, ["-Wl,--as-needed", "a b", "c d", "e f", "", "it's", "g\\h"]);
3889        assert!(response_words(" \n\t").is_empty());
3890    }
3891
3892    #[test]
3893    fn a_response_file_on_the_command_line_is_read_in_its_place() {
3894        let dir = std::env::temp_dir().join(format!("rucc-rsp-{}", std::process::id()));
3895        std::fs::create_dir_all(&dir).unwrap();
3896        let inner = dir.join("inner.rsp");
3897        std::fs::write(&inner, "-lm\n").unwrap();
3898        let outer = dir.join("outer.rsp");
3899        // Backslashes doubled, because the file is split the way libiberty splits one and a
3900        // Windows path is full of them.
3901        let named = inner.display().to_string().replace('\\', "\\\\");
3902        std::fs::write(&outer, format!("-o 'my prog' -Wl,--as-needed @{named}\n")).unwrap();
3903        let line = args(&["x.o", &format!("@{}", outer.display()), "@no-such-file"]);
3904        assert_eq!(
3905            response_files(&line).unwrap(),
3906            args(&["x.o", "-o", "my prog", "-Wl,--as-needed", "-lm", "@no-such-file"])
3907        );
3908        let itself = dir.join("itself.rsp");
3909        let named = itself.display().to_string().replace('\\', "\\\\");
3910        std::fs::write(&itself, format!("@{named}")).unwrap();
3911        let looped = response_files(&args(&[&format!("@{}", itself.display())]));
3912        assert!(looped.is_err(), "a file that names itself should be refused");
3913        std::fs::remove_dir_all(&dir).unwrap();
3914    }
3915
3916    #[test]
3917    fn help_and_version_win_over_everything_else() {
3918        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
3919        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
3920    }
3921
3922    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
3923        match parse_args(&args(s)).expect("expected a compilation") {
3924            Action::Compile { opts, plan, .. } => (opts, plan),
3925            other => panic!("expected a compilation, got {other:?}"),
3926        }
3927    }
3928
3929    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
3930        match parse_args(&args(s)).expect("expected a compilation") {
3931            Action::Compile { link, plan, .. } => (link, plan),
3932            other => panic!("expected a compilation, got {other:?}"),
3933        }
3934    }
3935
3936    fn notes(s: &[&str]) -> Vec<String> {
3937        match parse_args(&args(s)).expect("expected a compilation") {
3938            Action::Compile { notes, .. } => notes,
3939            other => panic!("expected a compilation, got {other:?}"),
3940        }
3941    }
3942
3943    /// The ordinary command line has nothing to say about itself, which is the property that makes
3944    /// a note worth reading when there is one.
3945    #[test]
3946    fn a_command_line_with_nothing_wrong_with_it_carries_no_notes() {
3947        assert_eq!(notes(&["-c", "a.c"]), Vec::<String>::new());
3948    }
3949
3950    /// `-g` for Windows is kept, and says nothing, now that the COFF writer has DWARF sections.
3951    #[test]
3952    fn debug_information_for_coff_is_kept() {
3953        assert_eq!(
3954            notes(&["--target=x86_64-windows-gnu", "-g", "-c", "a.c"]),
3955            Vec::<String>::new()
3956        );
3957        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-g", "-c", "a.c"]);
3958        assert!(opts.debug_info);
3959    }
3960
3961    /// A directory that is not there contributes nothing to the search path, so there is no tree to
3962    /// read a release out of and nothing to compare the pin against. Said as a test because this is
3963    /// the shape a hermetic machine takes: the probe reads the disk and every other machine has a
3964    /// different disk, so what can be asserted here is the silence.
3965    #[test]
3966    fn a_named_tree_that_is_not_on_the_machine_is_not_a_release_mismatch() {
3967        let said =
3968            notes(&["--target=x86_64-linux-gnu.2.28", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3969        assert_eq!(said, Vec::<String>::new());
3970    }
3971
3972    #[test]
3973    fn collects_inputs_and_flags() {
3974        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
3975        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
3976        assert_eq!(paths, vec!["a.c", "b.c"]);
3977        assert_eq!(opts.opt_level, OptLevel::O2);
3978        assert_eq!(opts.emit, EmitKind::Object);
3979        assert!(opts.debug_info);
3980    }
3981
3982    /// The unstable options, which are spelled apart from everything else on purpose: what is
3983    /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
3984    #[test]
3985    fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
3986        let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
3987        assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
3988
3989        let (plain, _) = compile(&["-c", "a.c"]);
3990        assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
3991
3992        assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
3993        let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
3994        assert!(unknown.message.contains("4.11"), "{}", unknown.message);
3995    }
3996
3997    /// The other measurement written to a file, which reads the same way and fails the same way.
3998    #[test]
3999    fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
4000        let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
4001        assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
4002
4003        let (plain, _) = compile(&["-c", "a.c"]);
4004        assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
4005
4006        assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
4007    }
4008
4009    /// Which register allocator runs, asked for by name, and left to the level when it is not.
4010    #[test]
4011    fn the_register_allocator_is_asked_for_by_name() {
4012        let (opts, _) = compile(&["-c", "-O2", "-Zregalloc=backtracking", "a.c"]);
4013        assert_eq!(opts.backtracking, Some(true));
4014        let (opts, _) = compile(&["-c", "-O2", "-Zregalloc=single", "a.c"]);
4015        assert_eq!(opts.backtracking, Some(false));
4016        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
4017        assert_eq!(plain.backtracking, None, "the level decides unless it was asked for");
4018        assert!(parse_args(&args(&["-Zregalloc=graph", "a.c"])).is_err(), "not an allocator");
4019    }
4020
4021    /// The third one, which says what the pre-selection lowering group did.
4022    #[test]
4023    fn a_switch_shape_is_forced_by_name_and_only_by_one_it_has() {
4024        let (opts, _) = compile(&["-c", "-O2", "-Zswitch=walk", "a.c"]);
4025        assert_eq!(opts.switch_shape.as_deref(), Some("walk"));
4026        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
4027        assert_eq!(plain.switch_shape, None, "nothing is forced unless it was asked for");
4028        assert!(parse_args(&args(&["-Zswitch=bit-test", "a.c"])).is_err(), "not a shape it forces");
4029    }
4030
4031    #[test]
4032    fn where_the_lowering_dump_goes_is_asked_for_the_same_way() {
4033        let (opts, _) = compile(&["-c", "-O2", "-Zlowering=/tmp/lowering.txt", "a.c"]);
4034        assert_eq!(opts.lowering_dump.as_deref(), Some("/tmp/lowering.txt"));
4035
4036        let (plain, _) = compile(&["-c", "a.c"]);
4037        assert_eq!(plain.lowering_dump, None, "nothing is dumped unless it was asked for");
4038
4039        assert!(parse_args(&args(&["-Zlowering=", "a.c"])).is_err(), "no file named");
4040    }
4041
4042    /// Scheduling, which has the three way answer every optimization flag has: on, off, and
4043    /// nothing said, which is whatever the optimization level asks for. The name is gcc's, and
4044    /// gcc's has a two in it because gcc has a scheduler before allocation and one after and this
4045    /// is the one after.
4046    #[test]
4047    fn scheduling_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
4048        let (on, _) = compile(&["-c", "-O0", "-fschedule-insns2", "a.c"]);
4049        assert_eq!(on.schedule_insns, Some(true));
4050
4051        let (off, _) = compile(&["-c", "-O2", "-fno-schedule-insns2", "a.c"]);
4052        assert_eq!(off.schedule_insns, Some(false));
4053
4054        let (quiet, _) = compile(&["-c", "-O2", "a.c"]);
4055        assert_eq!(quiet.schedule_insns, None, "nothing said, so the level decides");
4056        assert!(quiet.opt_level.schedules(), "and at this level the level says yes");
4057
4058        let (none, _) = compile(&["-c", "a.c"]);
4059        assert!(!none.opt_level.schedules(), "at no optimization it says no");
4060    }
4061
4062    /// Tail calls, which gcc spells as sibling calls and turns on at `-O2` and `-Os`.
4063    #[test]
4064    fn sibling_calls_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
4065        let (on, _) = compile(&["-c", "-O1", "-foptimize-sibling-calls", "a.c"]);
4066        assert_eq!(on.sibling_calls, Some(true));
4067
4068        let (off, _) = compile(&["-c", "-O2", "-fno-optimize-sibling-calls", "a.c"]);
4069        assert_eq!(off.sibling_calls, Some(false));
4070
4071        let (quiet, _) = compile(&["-c", "-Os", "a.c"]);
4072        assert_eq!(quiet.sibling_calls, None, "nothing said, so the level decides");
4073        assert!(quiet.opt_level.sibling_calls(), "and at this level the level says yes");
4074
4075        let (one, _) = compile(&["-c", "-O1", "a.c"]);
4076        assert!(!one.opt_level.sibling_calls(), "gcc leaves them off at -O1");
4077    }
4078
4079    /// Whether the timing model is worth holding an instruction back over, which is a `-Z` because
4080    /// it is a question about a target's description rather than about the program being compiled.
4081    #[test]
4082    fn whether_the_timing_model_is_cycle_accurate_can_be_overridden() {
4083        let (yes, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=yes", "a.c"]);
4084        assert_eq!(yes.cycle_accurate_model, Some(true));
4085
4086        let (no, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=no", "a.c"]);
4087        assert_eq!(no.cycle_accurate_model, Some(false));
4088
4089        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
4090        assert_eq!(plain.cycle_accurate_model, None, "the target's own answer stands");
4091
4092        let bad = parse_args(&args(&["-Zcycle-accurate-model=maybe", "a.c"]))
4093            .expect_err("it takes yes or no");
4094        assert!(bad.message.contains("yes or no"), "{}", bad.message);
4095    }
4096
4097    #[test]
4098    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
4099        let (opts, _) = compile(&["-O", "a.c"]);
4100        assert_eq!(opts.opt_level, OptLevel::O1);
4101    }
4102
4103    #[test]
4104    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
4105        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
4106        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4107        assert_eq!(plan.jobs[1].kind, InputKind::C);
4108        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4109    }
4110
4111    #[test]
4112    fn dash_x_can_be_joined_to_its_language() {
4113        let (_, plan) = compile(&["a.o", "-xc", "b.txt", "-xnone", "c.o"]);
4114        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4115        assert_eq!(plan.jobs[1].kind, InputKind::C);
4116        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4117    }
4118
4119    #[test]
4120    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
4121        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
4122            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
4123            other => panic!("expected a compilation, got {other:?}"),
4124        };
4125        assert_eq!(jobs.count(), 4);
4126
4127        let default = match parse_args(&args(&["a.c"])).unwrap() {
4128            Action::Compile { jobs, .. } => jobs,
4129            other => panic!("expected a compilation, got {other:?}"),
4130        };
4131        assert_eq!(default, Jobs::available());
4132        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
4133    }
4134
4135    #[test]
4136    fn triple_hash_prints_the_plan_and_runs_nothing() {
4137        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
4138        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
4139        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
4140    }
4141
4142    #[test]
4143    fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
4144        // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
4145        // this, and following the compiler is what makes a build that reads either of them find
4146        // the files where they are.
4147        assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
4148        assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
4149        assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
4150        assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
4151        // The last one on the line decides, the way it does for every other flag with an
4152        // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
4153        // nothing and said nothing looks exactly like one where the files were not produced.
4154        let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
4155        assert_eq!(opts.save_temps, SaveTemps::Cwd);
4156        let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
4157        assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
4158    }
4159
4160    #[test]
4161    fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
4162        let (opts, plan) = compile(&["-c", "-time", "a.c"]);
4163        let (plain, without) = compile(&["-c", "a.c"]);
4164        assert!(opts.time);
4165        assert!(!plain.time);
4166        // Against the same line without the flag rather than against a spelling of the object's
4167        // name, since what the object is called is the host's business and this is not about that.
4168        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4169    }
4170
4171    #[test]
4172    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
4173        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
4174        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
4175    }
4176
4177    /// What `--fetch` says for a target this release pins nothing for, which today is every target
4178    /// but the three windows-gnu ones, the four musl ones and the eight glibc ones.
4179    #[test]
4180    fn a_fetch_of_a_target_nothing_is_pinned_for_says_so_rather_than_reaching_the_network() {
4181        let e = parse_args(&args(&["--fetch", "x86_64-linux-gnux32"])).unwrap_err();
4182        assert!(e.message.contains("pins no sysroot for x86_64-linux-gnux32"), "{}", e.message);
4183        // And what it does pin, because a release with some rows in the table and a release with
4184        // none are two situations and the second sentence is what tells them apart.
4185        assert!(e.message.contains("x86_64-windows-gnu"), "{}", e.message);
4186        // The joined spelling is the same flag.
4187        let joined = parse_args(&args(&["--fetch=x86_64-linux-gnux32"])).unwrap_err();
4188        assert_eq!(joined, e);
4189    }
4190
4191    /// The two targets a release will never pin, which is a different answer from the one above.
4192    ///
4193    /// Section 13.4. A person who reads "this release pins no sysroot yet" waits for a release that
4194    /// does, and no release of this compiler can ship either of these. An Apple target gets the
4195    /// licence and what to do instead, and a Microsoft one gets Microsoft's own files from
4196    /// Microsoft, which is the one lawful download either wall has behind it.
4197    #[test]
4198    fn a_fetch_of_a_target_behind_a_licence_wall_says_so_rather_than_saying_not_yet() {
4199        let e = parse_args(&args(&["--fetch", "aarch64-macos"])).unwrap_err();
4200        assert!(e.message.contains("Xcode licence"), "{}", e.message);
4201        assert!(e.message.contains("there never will be"), "{}", e.message);
4202        assert!(!e.message.contains("tamnd/rucc-cross"), "{}", e.message);
4203
4204        // Microsoft's side has a download behind it, which is Microsoft's own files from the build
4205        // this release pins, and the licence still has to be accepted for anything to move.
4206        let action = parse_args(&args(&["--fetch", "x86_64-windows-msvc"])).expect("pinned build");
4207        let Action::FetchMsvcSdk { target, accepted, pinned, .. } = action else {
4208            panic!("{action:?}")
4209        };
4210        assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
4211        assert!(pinned);
4212        assert!(!accepted);
4213        let action = parse_args(&args(&["--fetch=aarch64-windows-msvc", "--accept-licence"]))
4214            .expect("pinned build");
4215        let Action::FetchMsvcSdk { accepted, pinned, .. } = action else { panic!("{action:?}") };
4216        assert!(accepted && pinned);
4217        // And the mingw-w64 target next to it is ours to ship and published, so the same flag has
4218        // something to get rather than a licence to explain.
4219        let action = parse_args(&args(&["--fetch", "x86_64-windows-gnu"])).expect("it is pinned");
4220        let Action::Fetch { what, .. } = action else { panic!("{action:?}") };
4221        assert_eq!(what.tuple, "x86_64-windows-gnu");
4222    }
4223
4224    #[test]
4225    fn the_other_fetch_takes_a_target_behind_microsofts_wall_and_carries_the_acceptance() {
4226        // Both spellings of the flag, because a flag that takes a tuple gets written both ways.
4227        for line in [
4228            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc"],
4229            vec!["--fetch-msvc-sdk=x86_64-windows-msvc"],
4230        ] {
4231            let action = parse_args(&args(&line)).expect("that is a target behind the wall");
4232            let Action::FetchMsvcSdk { target, accepted, pinned, .. } = action else {
4233                panic!("{action:?}")
4234            };
4235            assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
4236            // Nothing on the line accepted anything, so nothing did.
4237            assert!(!accepted);
4238            // This one follows Microsoft's channel to whatever it names today.
4239            assert!(!pinned);
4240        }
4241
4242        // And both spellings of the word, because the prose here uses one and most of the people
4243        // typing this will reach for the other.
4244        for word in ["--accept-licence", "--accept-license"] {
4245            let action = parse_args(&args(&["--fetch-msvc-sdk", "aarch64-windows-msvc", word]))
4246                .expect("that is a target behind the wall");
4247            let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4248                panic!("{action:?}")
4249            };
4250            assert_eq!(target.to_canonical_string(), "aarch64-windows-msvc");
4251            assert!(accepted, "{word} should have been read");
4252        }
4253    }
4254
4255    #[test]
4256    fn the_other_fetch_refuses_the_command_lines_that_do_not_mean_anything() {
4257        // A tuple is what it gets, so a flag with nothing after it is not a command.
4258        let e = parse_args(&args(&["--fetch-msvc-sdk"])).unwrap_err();
4259        assert!(e.message.contains("requires the target"), "{}", e.message);
4260        let e = parse_args(&args(&["--fetch-msvc-sdk", "not-a-target"])).unwrap_err();
4261        assert!(e.message.contains("there is no SDK to get"), "{}", e.message);
4262
4263        // `--offline` forbids every download and this one asks for one, whichever order they came
4264        // in, which is the same answer `--fetch` gives.
4265        for line in [
4266            vec!["--offline", "--fetch-msvc-sdk", "x86_64-windows-msvc"],
4267            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc", "--offline"],
4268        ] {
4269            let e = parse_args(&args(&line)).unwrap_err();
4270            assert!(e.message.contains("two opposite things"), "{}", e.message);
4271        }
4272
4273        // It gets an SDK and compiles nothing, so a file on the same line would be read by nothing.
4274        let e = parse_args(&args(&["--fetch-msvc-sdk", "x86_64-windows-msvc", "a.c"])).unwrap_err();
4275        assert!(e.message.contains("compiles nothing"), "{}", e.message);
4276
4277        // The two fetches are two commands and a line that asked for both asked for neither.
4278        let e = parse_args(&args(&[
4279            "--fetch",
4280            "x86_64-windows-gnu",
4281            "--fetch-msvc-sdk",
4282            "x86_64-windows-msvc",
4283        ]))
4284        .unwrap_err();
4285        assert!(e.message.contains("two different commands"), "{}", e.message);
4286
4287        // And an acceptance with nothing to accept for is a command line that says something about
4288        // a licence no part of it goes near.
4289        let e = parse_args(&args(&["--accept-licence", "-c", "a.c"])).unwrap_err();
4290        assert!(e.message.contains("--fetch-msvc-sdk <tuple> for a"), "{}", e.message);
4291    }
4292
4293    /// An Apple target on a machine with no SDK, which is section 8.6's other host.
4294    ///
4295    /// Not run on a mac, where the SDK this is about is installed and the compile is the ordinary one
4296    /// that uses it. What the reason says is asserted in `rucc_sysroot::wall` and where it is printed
4297    /// is asserted in `rucc-pp`, so what is left here is that the driver works it out and leaves it
4298    /// where the preprocessor will find it, and that neither way past the wall leaves one behind.
4299    #[test]
4300    fn an_apple_target_with_no_sdk_anywhere_carries_the_licence_rather_than_a_missing_directory() {
4301        if cfg!(target_os = "macos") || std::env::var_os("SDKROOT").is_some() {
4302            return;
4303        }
4304        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4305        let why = opts.search.missing_system().expect("the wall is the reason there are none");
4306        assert!(why.contains("aarch64-macos needs a macOS SDK"), "{why}");
4307        assert!(why.contains("Xcode licence"), "{why}");
4308        assert!(why.contains("-isysroot"), "{why}");
4309
4310        // A program that includes none of the library needs none of the SDK, which is what section
4311        // 8.6 means by being able to target the platform without one, so there is nothing to explain.
4312        let (opts, _) = compile(&["--target=aarch64-macos", "-nostdinc", "-c", "a.c"]);
4313        assert_eq!(opts.search.missing_system(), None);
4314        // And naming a path is the other way through, whether or not the path is there: a mistyped
4315        // directory is a mistake to report on its own terms rather than a licence to explain.
4316        let (opts, _) = compile(&["--target=aarch64-macos", "-isysroot", "/opt/sdk", "-c", "a.c"]);
4317        assert_eq!(opts.search.missing_system(), None);
4318    }
4319
4320    /// The same wall on the compile side of an MSVC target, where the way past it is a tuple.
4321    ///
4322    /// Not run on Windows, for the same reason the one above is not run on a mac: the wall stands in
4323    /// front of an SDK this machine does not have, and a Windows machine is the kind that does. The
4324    /// driver asks `vswhere` where Visual Studio is and takes the newest kit under it, so on a box
4325    /// with the build tools installed there are headers, no wall and nothing here to be about.
4326    /// `INCLUDE` is the other way a machine has one and is the other half of the guard, since a
4327    /// person can set that anywhere while Visual Studio is only found on the platform it runs on.
4328    #[test]
4329    fn an_msvc_target_with_no_sdk_named_says_which_environment_needs_nothing_installed() {
4330        if cfg!(target_os = "windows") || std::env::var_os("INCLUDE").is_some() {
4331            return;
4332        }
4333        let (opts, _) = compile(&["--target=x86_64-windows-msvc", "-c", "a.c"]);
4334        let why = opts.search.missing_system().expect("the wall is the reason there are none");
4335        assert!(why.contains("the Windows SDK and its universal CRT"), "{why}");
4336        assert!(why.contains("mingw-w64"), "{why}");
4337        // And the mingw-w64 target has its headers from us, so nothing is missing to explain.
4338        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-c", "a.c"]);
4339        assert_eq!(opts.search.missing_system(), None);
4340    }
4341
4342    #[test]
4343    fn a_fetch_with_no_target_and_a_fetch_of_a_tuple_that_is_not_one_both_say_which() {
4344        let e = parse_args(&args(&["--fetch"])).unwrap_err();
4345        assert!(e.message.contains("--fetch requires"), "{}", e.message);
4346        let e = parse_args(&args(&["--fetch", "sparc64-solaris-gnu"])).unwrap_err();
4347        assert!(e.message.contains("--fetch sparc64-solaris-gnu"), "{}", e.message);
4348        assert!(e.message.contains("no sysroot to get"), "{}", e.message);
4349    }
4350
4351    /// Both flags on one line ask for opposite things, in either order.
4352    #[test]
4353    fn a_fetch_and_offline_together_is_a_refusal_whichever_way_round_they_are_written() {
4354        for line in [
4355            vec!["--offline", "--fetch", "x86_64-linux-musl"],
4356            vec!["--fetch", "x86_64-linux-musl", "--offline"],
4357        ] {
4358            let e = parse_args(&args(&line)).unwrap_err();
4359            assert!(e.message.contains("two opposite things"), "{}", e.message);
4360        }
4361    }
4362
4363    #[test]
4364    fn a_fetch_does_not_compile_anything_and_says_so_when_it_is_handed_a_file() {
4365        let e = parse_args(&args(&["--fetch", "x86_64-linux-musl", "a.c"])).unwrap_err();
4366        assert!(e.message.contains("compiles nothing"), "{}", e.message);
4367        assert!(e.message.contains("a.c"), "{}", e.message);
4368    }
4369
4370    /// `--offline` on its own is accepted and changes nothing, because an ordinary compile
4371    /// downloads nothing with or without it. A build that passes it everywhere is the case this is
4372    /// for, and it must not lose the compilation it was passed beside.
4373    #[test]
4374    fn offline_on_a_compilation_is_the_same_compilation() {
4375        let (opts, plan) = compile(&["-c", "--offline", "a.c"]);
4376        let (plain, without) = compile(&["-c", "a.c"]);
4377        assert_eq!(opts.target, plain.target);
4378        assert_eq!(plan.jobs.len(), without.jobs.len());
4379        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4380    }
4381
4382    #[test]
4383    fn a_deployment_target_comes_from_the_tuple_or_from_the_flag() {
4384        let version = |v: &str| rucc_tuple::Version::parse(v);
4385        let (opts, _) = compile(&["--target=aarch64-macos.13", "-c", "a.c"]);
4386        assert_eq!(opts.target, "aarch64-apple-darwin".parse().unwrap());
4387        assert_eq!(opts.os_version, version("13"));
4388        // The flag wins over the tuple, as it does under clang, and either spelling of it works.
4389        let (opts, _) =
4390            compile(&["--target=aarch64-macos.13", "-mmacosx-version-min=14.2", "-c", "a.c"]);
4391        assert_eq!(opts.os_version, version("14.2"));
4392        let (opts, _) = compile(&["--target=x86_64-macos", "-mmacos-version-min=12", "-c", "a.c"]);
4393        assert_eq!(opts.os_version, version("12"));
4394        // Nothing said leaves the platform's default to the target description.
4395        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4396        assert_eq!(opts.os_version, None);
4397        // A Linux build that always passes the flag is not an Apple build because of it.
4398        let (opts, _) =
4399            compile(&["--target=aarch64-linux-gnu", "-mmacosx-version-min=13", "-c", "a.c"]);
4400        assert_eq!(opts.os_version, None);
4401        let e = parse_args(&args(&["-mmacosx-version-min=thirteen", "a.c"])).unwrap_err();
4402        assert!(e.message.contains("is not a version"), "{}", e.message);
4403    }
4404
4405    #[test]
4406    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
4407        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
4408        assert!(e.message.contains("unknown option"), "{}", e.message);
4409    }
4410
4411    /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
4412    /// one directory needs the older rules and the rest of the tree does not.
4413    #[test]
4414    fn permissive_reads_in_both_directions_and_the_last_one_wins() {
4415        let (opts, _) = compile(&["-c", "a.c"]);
4416        assert!(!opts.permissive, "off unless it is asked for");
4417
4418        let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
4419        assert!(opts.permissive);
4420
4421        let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
4422        assert!(!opts.permissive);
4423    }
4424
4425    #[test]
4426    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
4427        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
4428        assert!(e.message.contains("trampoline"), "{}", e.message);
4429        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
4430    }
4431
4432    #[test]
4433    fn the_flag_every_configure_script_writes_is_taken() {
4434        // All four spellings, because a build writes whichever one its macros picked and a
4435        // compiler that takes three of them is a compiler that fails on the fourth.
4436        for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
4437            let (opts, _) = compile(&["-c", flag, "a.c"]);
4438            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4439        }
4440    }
4441
4442    #[test]
4443    fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
4444        let (opts, _) = compile(&["-c", "a.c"]);
4445        assert!(opts.unwinds(), "the default is off");
4446        let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
4447        assert!(!opts.unwinds(), "the build was not taken at its word");
4448        let (opts, _) = compile(&[
4449            "-c",
4450            "-fno-asynchronous-unwind-tables",
4451            "-fasynchronous-unwind-tables",
4452            "a.c",
4453        ]);
4454        assert!(opts.unwinds(), "the last flag did not win");
4455        // The weaker request, which the same table answers, so a line that asks for a table and
4456        // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
4457        // build turns the asynchronous one off globally and a directory asks for a table back.
4458        let (opts, _) =
4459            compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
4460        assert!(opts.unwinds(), "the weaker request was dropped");
4461        let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
4462        assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
4463        let (opts, _) =
4464            compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
4465        assert!(!opts.unwinds(), "both were turned off and one stayed on");
4466    }
4467
4468    #[test]
4469    fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
4470        // Every one of these is on a real build line somewhere and every one of them was an
4471        // unknown option. What they have in common is that the answer rucc gives is the answer
4472        // they ask for, so there is nothing to implement and nothing to refuse.
4473        for flag in [
4474            "-fstrict-aliasing",
4475            "-fno-strict-aliasing",
4476            "-fdelete-null-pointer-checks",
4477            "-fno-delete-null-pointer-checks",
4478            "-frounding-math",
4479            "-fno-rounding-math",
4480            "-fexcess-precision=standard",
4481            "-fexcess-precision=fast",
4482            "-fexcess-precision=16",
4483            "-pipe",
4484            "-cpp",
4485            "-fdiagnostics-color",
4486            "-fno-diagnostics-color",
4487            "-fdiagnostics-color=always",
4488            "-fdiagnostics-color=never",
4489            "-fdiagnostics-color=auto",
4490        ] {
4491            let (opts, _) = compile(&["-c", flag, "a.c"]);
4492            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4493        }
4494    }
4495
4496    #[test]
4497    fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
4498        let (opts, _) = compile(&["-c", "a.c"]);
4499        assert!(opts.trapping_math, "the default was not gcc's");
4500        let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
4501        assert!(!opts.trapping_math);
4502        let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
4503        assert!(opts.trapping_math, "spelling out the default turned it off");
4504        // The last one written wins, which is how a build line that inherits a flag from one
4505        // place and overrides it in another is read.
4506        let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
4507        assert!(opts.trapping_math);
4508    }
4509
4510    /// The flags a torture program writes on its own `dg-options` line, which is where most of
4511    /// these come from: a program reduced from a miscompilation names the pass that miscompiled
4512    /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
4513    /// tamnd/rucc#1019 is the list.
4514    #[test]
4515    fn no_inline_turns_off_the_inlining_of_a_function_declared_inline() {
4516        let (opts, _) = compile(&["-c", "-O2", "-fno-inline", "a.c"]);
4517        assert_eq!(opts.passes, [(rucc_opt::inline::NAME.to_owned(), false)]);
4518    }
4519
4520    #[test]
4521    fn inlining_a_function_called_once_is_turned_off_and_on_by_its_own_flag() {
4522        for level in ["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz", "-Og"] {
4523            let (opts, _) = compile(&["-c", level, "-fno-inline-functions-called-once", "a.c"]);
4524            assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), false)], "{level}");
4525            let (opts, _) = compile(&["-c", level, "-finline-functions-called-once", "a.c"]);
4526            assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), true)], "{level}");
4527        }
4528    }
4529
4530    #[test]
4531    fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
4532        for flag in [
4533            "-fno-tree-ccp",
4534            "-fno-tree-dominator-opts",
4535            "-fno-tree-vrp",
4536            "-fno-tree-bit-ccp",
4537            "-fno-tree-coalesce-vars",
4538            "-ftree-vectorize",
4539            "-ftree-loop-distribution",
4540            "-fipa-pta",
4541            "-fmodulo-sched",
4542            "-fno-vect-cost-model",
4543            "-fvect-cost-model=unlimited",
4544            "-fsimd-cost-model=cheap",
4545            "-fexpensive-optimizations",
4546            "-fno-early-inlining",
4547            "-finline-functions",
4548            "-foptimize-strlen",
4549            "-fno-ira-share-spill-slots",
4550        ] {
4551            let (opts, _) = compile(&["-c", flag, "a.c"]);
4552            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4553            assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
4554        }
4555    }
4556
4557    /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
4558    /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
4559    #[test]
4560    fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
4561        for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
4562            let (opts, _) = compile(&["-c", flag, "a.c"]);
4563            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4564        }
4565    }
4566
4567    /// A pass this compiler has keeps its flag, since the arms that read the registry are above
4568    /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
4569    /// is the program that writes it.
4570    #[test]
4571    fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
4572        let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
4573        assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
4574    }
4575
4576    /// gcc's name for the unroller reaches the unroller, in both directions. libtommath puts
4577    /// `-funroll-loops` in `CFLAGS` unconditionally, and before this it was an unknown option and
4578    /// the build stopped on its first file.
4579    #[test]
4580    fn the_gcc_spelling_of_the_unroller_turns_the_unroller_on_and_off() {
4581        let (opts, _) = compile(&["-c", "-funroll-loops", "a.c"]);
4582        assert_eq!(opts.passes, vec![("unroll".to_owned(), true)]);
4583        let (opts, _) = compile(&["-c", "-fno-unroll-loops", "a.c"]);
4584        assert_eq!(opts.passes, vec![("unroll".to_owned(), false)]);
4585    }
4586
4587    /// The three transformations that are a module at a time are named by a flag as well, even
4588    /// though none of them is a `rucc_opt::Pass` and so none is reached by the generic arms.
4589    ///
4590    /// A bisection over a miscompilation turns one thing off at a time, and a transformation with
4591    /// no spelling of its own cannot be the one turned off.
4592    #[test]
4593    fn the_transformations_that_are_not_passes_are_still_named_by_a_flag() {
4594        let (opts, _) = compile(&["-c", "-fno-ipa-cp", "-fipa-sra", "-fno-libcall", "a.c"]);
4595        assert_eq!(
4596            opts.passes,
4597            vec![
4598                (rucc_opt::ipcp::NAME.to_owned(), false),
4599                (rucc_opt::ipasra::NAME.to_owned(), true),
4600                (rucc_opt::libcall::NAME.to_owned(), false),
4601            ]
4602        );
4603        let (opts, _) = compile(&["-c", "-flibcall", "a.c"]);
4604        assert_eq!(opts.passes, vec![(rucc_opt::libcall::NAME.to_owned(), true)]);
4605    }
4606
4607    /// Where a function starts is a question this compiler answers, so the flag that asks about it
4608    /// is answered rather than dropped. femtolisp's Makefile writes the bare form on every compile
4609    /// of the project, and before this it was an unknown option and the build stopped on its first
4610    /// file. The numbers are gcc 16's, read off `-S` on x86-64: nothing and the bare form both
4611    /// give `.p2align 4`, `=32` gives 5, `=3` gives 2, and the negative form gives `.align 8`.
4612    #[test]
4613    fn the_alignment_of_a_function_is_a_request_this_compiler_can_answer() {
4614        let (opts, _) = compile(&["-c", "-falign-functions", "a.c"]);
4615        assert_eq!(opts.align_functions, None, "the bare form asks for the default");
4616
4617        let (opts, _) = compile(&["-c", "-falign-functions=32", "a.c"]);
4618        assert_eq!(opts.align_functions, Some(32));
4619
4620        let (opts, _) = compile(&["-c", "-falign-functions=3", "a.c"]);
4621        assert_eq!(opts.align_functions, Some(4), "rounded up rather than refused");
4622
4623        let (opts, _) = compile(&["-c", "-falign-functions=32:8", "a.c"]);
4624        assert_eq!(opts.align_functions, Some(32), "the boundary is the answerable half");
4625
4626        for flag in ["-falign-functions=0", "-falign-functions=1"] {
4627            let (opts, _) = compile(&["-c", flag, "a.c"]);
4628            assert_eq!(opts.align_functions, None, "{flag} means the default");
4629        }
4630
4631        let (opts, _) = compile(&["-c", "-fno-align-functions", "a.c"]);
4632        assert_eq!(opts.align_functions, Some(8), "the smallest boundary the target has");
4633
4634        // The last one on the line wins, which is how gcc reads a repeated flag.
4635        let (opts, _) = compile(&["-c", "-falign-functions=32", "-falign-functions", "a.c"]);
4636        assert_eq!(opts.align_functions, None);
4637
4638        let e = parse_args(&args(&["-c", "-falign-functions=big", "a.c"])).unwrap_err();
4639        assert!(e.message.contains("number of bytes"), "{}", e.message);
4640    }
4641
4642    /// The other three of the family are about padding inside a body, so none of them is about
4643    /// where a function starts. Every spelling of each, since a build writes whichever one its
4644    /// author typed.
4645    #[test]
4646    fn the_alignment_flags_about_the_inside_of_a_body_are_taken_and_say_nothing() {
4647        for flag in [
4648            "-falign-labels",
4649            "-falign-loops",
4650            "-falign-jumps",
4651            "-falign-loops=16",
4652            "-falign-labels=32",
4653            "-fno-align-loops",
4654            "-fno-align-labels",
4655            "-fno-align-jumps",
4656        ] {
4657            let (opts, _) = compile(&["-c", flag, "a.c"]);
4658            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4659            assert_eq!(opts.align_functions, None, "{flag} is not about where a function starts");
4660        }
4661    }
4662
4663    /// The loop flag in either direction is an answer, and a command line that wrote neither
4664    /// leaves the level to decide.
4665    #[test]
4666    fn the_loop_alignment_flag_is_answered_both_ways() {
4667        assert_eq!(compile(&["-c", "-O2", "a.c"]).0.align_loops, None);
4668        assert_eq!(compile(&["-c", "-O0", "-falign-loops", "a.c"]).0.align_loops, Some(true));
4669        assert_eq!(compile(&["-c", "-O2", "-fno-align-loops", "a.c"]).0.align_loops, Some(false));
4670        assert_eq!(compile(&["-c", "-falign-loops=32", "a.c"]).0.align_loops, None, "a number");
4671    }
4672
4673    /// The encoding of the source is not a question about speed, so the one name that describes
4674    /// what the preprocessor does is taken and every other name is refused.
4675    #[test]
4676    fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
4677        for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
4678            let (opts, _) = compile(&["-c", flag, "a.c"]);
4679            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4680        }
4681
4682        let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
4683        assert!(e.message.contains("latin1"), "{}", e.message);
4684        assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
4685    }
4686
4687    /// `-fnon-call-exceptions` turns exceptions on unless `-fexceptions` or `-fno-exceptions` was
4688    /// written, and the one written wins whichever side of it it is on, which is gcc 16's reading.
4689    #[test]
4690    fn exceptions_are_on_when_asked_for_and_non_call_ones_ask_unless_told_not_to() {
4691        let (opts, _) = compile(&["-c", "a.c"]);
4692        assert!(!opts.exceptions && !opts.non_call_exceptions, "gcc's default for C is off");
4693        let (opts, _) = compile(&["-c", "-fexceptions", "a.c"]);
4694        assert!(opts.exceptions && !opts.non_call_exceptions);
4695        let (opts, _) = compile(&["-c", "-fexceptions", "-fno-exceptions", "a.c"]);
4696        assert!(!opts.exceptions);
4697        let (opts, _) = compile(&["-c", "-fnon-call-exceptions", "a.c"]);
4698        assert!(opts.exceptions && opts.non_call_exceptions);
4699        for line in [
4700            ["-fno-exceptions", "-fnon-call-exceptions"],
4701            ["-fnon-call-exceptions", "-fno-exceptions"],
4702        ] {
4703            let (opts, _) = compile(&["-c", line[0], line[1], "a.c"]);
4704            assert!(!opts.exceptions && opts.non_call_exceptions, "{line:?}");
4705        }
4706        let (opts, _) =
4707            compile(&["-c", "-fnon-call-exceptions", "-fno-non-call-exceptions", "a.c"]);
4708        assert!(!opts.exceptions && !opts.non_call_exceptions);
4709        let (opts, _) = compile(&["-c", "-fno-delete-dead-exceptions", "a.c"]);
4710        assert_eq!(opts.emit, EmitKind::Object);
4711    }
4712
4713    /// `-ffast-math` used to be refused beside it and is the family it names now, with each
4714    /// member settable on its own and the last word on each winning, which is gcc's reading.
4715    #[test]
4716    fn fast_math_is_the_family_it_names_and_the_last_word_on_each_member_wins() {
4717        let both = |line: &[&str]| {
4718            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4719            let (link, _) = linking(&[line, &["a.c"]].concat());
4720            (opts, link)
4721        };
4722        let (opts, link) = both(&[]);
4723        assert_eq!(opts.math, Math::default());
4724        assert!(opts.trapping_math);
4725        assert!(!link.fast_math);
4726
4727        let (opts, link) = both(&["-ffast-math"]);
4728        assert!(opts.math.fast(opts.trapping_math), "{:?}", opts.math);
4729        assert!(!opts.trapping_math, "fast math turns trapping off");
4730        assert!(link.fast_math, "and it links the startup file");
4731
4732        // Taking one member back leaves the rest, and the whole is not fast math any more.
4733        let (opts, link) = both(&["-ffast-math", "-fno-finite-math-only"]);
4734        assert!(!opts.math.finite_only);
4735        assert!(!opts.math.errno && !opts.math.signed_zeros && opts.math.reciprocal);
4736        assert!(!opts.math.fast(opts.trapping_math));
4737        assert!(link.fast_math, "gcc's spec reads the flag and not the fields");
4738
4739        let (opts, _) = both(&["-ffast-math", "-ftrapping-math"]);
4740        assert!(opts.trapping_math);
4741        assert!(!opts.math.fast(opts.trapping_math));
4742        assert!(!opts.math.associative(opts.trapping_math));
4743
4744        let (opts, link) = both(&["-ffast-math", "-fno-fast-math"]);
4745        assert_eq!(opts.math, Math::default());
4746        assert!(opts.trapping_math);
4747        assert!(!link.fast_math);
4748
4749        // A member written alone is only that member.
4750        let (opts, link) = both(&["-fno-math-errno"]);
4751        assert_eq!(opts.math, Math { errno: false, ..Math::default() });
4752        assert!(opts.math.iec_559(opts.trapping_math), "errno is not an IEC 60559 question");
4753        assert!(!link.fast_math);
4754
4755        let (opts, link) = both(&["-funsafe-math-optimizations"]);
4756        assert!(opts.math.unsafe_math && opts.math.associative(opts.trapping_math));
4757        assert!(opts.math.errno && !opts.math.finite_only);
4758        assert!(link.fast_math);
4759    }
4760
4761    /// `-Ofast` is `-O3` with fast math as a default, which a later level and a
4762    /// `-fno-fast-math` on either side of it both take back.
4763    #[test]
4764    fn ofast_is_o3_with_fast_math_as_a_default_a_flag_can_take_back() {
4765        let both = |line: &[&str]| {
4766            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4767            let (link, _) = linking(&[line, &["a.c"]].concat());
4768            (opts, link)
4769        };
4770        let (opts, link) = both(&["-Ofast"]);
4771        assert_eq!(opts.opt_level, OptLevel::O3);
4772        assert!(opts.math.fast(opts.trapping_math));
4773        assert!(link.fast_math);
4774
4775        for line in [&["-Ofast", "-O2"][..], &["-fno-fast-math", "-Ofast"]] {
4776            let (opts, _) = both(line);
4777            assert!(!opts.math.fast(opts.trapping_math), "{line:?}");
4778        }
4779
4780        let (_, link) = both(&["-Ofast", "-mno-daz-ftz"]);
4781        assert_eq!(link.daz_ftz, Some(false));
4782    }
4783
4784    /// `-finstrument-functions` used to be refused beside those two, and it is taken now that the
4785    /// hooks are called. The last of it and its negative is the one that counts, as with any pair.
4786    #[test]
4787    fn instrument_functions_is_taken_and_the_last_of_the_pair_wins() {
4788        let (opts, _) = compile(&["-c", "-finstrument-functions", "a.c"]);
4789        assert!(opts.instrument_functions);
4790        let (opts, _) =
4791            compile(&["-c", "-finstrument-functions", "-fno-instrument-functions", "a.c"]);
4792        assert!(!opts.instrument_functions);
4793    }
4794
4795    #[test]
4796    fn a_tentative_definition_is_common_on_darwin_unless_told_otherwise() {
4797        // Two files each writing `int g;` link under `-fcommon` and do not without it, and Apple's
4798        // clang has it on where every other compiler rucc stands in for has it off.
4799        let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
4800        assert!(!Session::new(*opts).common());
4801
4802        let (opts, _) = compile(&["-c", "--target=aarch64-apple-darwin", "a.c"]);
4803        assert!(Session::new(*opts).common());
4804
4805        let (opts, _) = compile(&[LINUX, "-c", "-fcommon", "a.c"]);
4806        assert!(Session::new(*opts).common());
4807
4808        let (opts, _) =
4809            compile(&["-c", "--target=aarch64-apple-darwin", "-fcommon", "-fno-common", "a.c"]);
4810        assert!(!Session::new(*opts).common());
4811    }
4812
4813    #[test]
4814    fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
4815        for flag in ["-fno-pic", "-fno-pie"] {
4816            let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
4817            assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
4818            // The one it may have meant, since the two are a letter apart and one of them is
4819            // about linking and is taken.
4820            assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
4821        }
4822    }
4823
4824    #[test]
4825    fn a_program_name_with_a_known_target_in_front_of_rucc_picks_that_target() {
4826        let t = |p: &str| target_from_program(p);
4827        assert_eq!(t("aarch64-linux-gnu-rucc").as_deref(), Some("aarch64-linux-gnu"));
4828        assert_eq!(t("/usr/bin/riscv64-linux-musl-rucc").as_deref(), Some("riscv64-linux-musl"));
4829        assert_eq!(t(r"C:\bin\x86_64-windows-gnu-rucc.exe").as_deref(), Some("x86_64-windows-gnu"));
4830        assert_eq!(t("rucc"), None);
4831        assert_eq!(t("/usr/local/bin/rucc"), None);
4832        assert_eq!(t("my-rucc"), None);
4833        assert_eq!(t("sparc64-linux-gnu-rucc"), None);
4834        assert_eq!(t("aarch64-linux-gnu-gcc"), None);
4835    }
4836
4837    #[test]
4838    fn an_unsupported_target_names_itself() {
4839        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
4840        assert!(e.message.contains("sparc64"), "{}", e.message);
4841    }
4842
4843    #[test]
4844    fn no_inputs_is_an_error_but_print_config_needs_none() {
4845        assert!(parse_args(&args(&[])).is_err());
4846        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
4847    }
4848
4849    #[test]
4850    fn print_config_reports_the_target_it_was_given_not_the_host() {
4851        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
4852        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
4853        let text = print_config(&opts);
4854        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
4855        assert!(text.contains("char-signed: false"), "{text}");
4856        assert!(text.contains("object-format: elf"), "{text}");
4857        assert!(text.contains("va-list: void-pointer"), "{text}");
4858        // RISC-V has a register file and this compiler has not written it down yet, and the
4859        // dump says which of those two it is rather than leaving the line out.
4860        assert!(text.contains("registers: none"), "{text}");
4861        assert!(text.contains("timing-model: none"), "{text}");
4862    }
4863
4864    /// The model the schedule was chosen with, which is a receipt anybody comparing two runs of a
4865    /// benchmark needs: two numbers that disagree are usually two models and not two compilers.
4866    #[test]
4867    fn print_config_names_the_model_the_schedule_was_chosen_with() {
4868        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4869        let text = print_config(&opts);
4870        let line = text.lines().find(|l| l.starts_with("timing-model:")).expect("the model");
4871        assert!(line.contains("Skylake"), "{line}");
4872        assert!(line.contains("published"), "a sentence saying where it came from: {line}");
4873    }
4874
4875    #[test]
4876    fn print_config_has_one_key_per_line_and_a_fixed_order() {
4877        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4878        let text = print_config(&opts);
4879        let keys: Vec<&str> =
4880            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
4881        assert_eq!(keys[0], "version");
4882        assert_eq!(keys[1], "target");
4883        assert_eq!(keys.len(), 26);
4884        assert!(text.ends_with('\n'));
4885    }
4886
4887    #[test]
4888    fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4889        let (opts, _) = compile(&["a.c"]);
4890        assert_eq!(opts.safety, rucc_session::Safety::Off);
4891
4892        for (flag, tier) in [
4893            ("-fsafety=detect", rucc_session::Safety::Detect),
4894            ("-fsafety=enforce", rucc_session::Safety::Enforce),
4895            ("-fsafety=kernel", rucc_session::Safety::Kernel),
4896            ("-fsafety=off", rucc_session::Safety::Off),
4897        ] {
4898            let (opts, _) = compile(&[flag, "a.c"]);
4899            assert_eq!(opts.safety, tier, "{flag}");
4900        }
4901
4902        // The last one wins, the way every other repeated flag on this command line does.
4903        let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
4904        assert_eq!(opts.safety, rucc_session::Safety::Off);
4905
4906        // A misspelled tier is refused rather than ignored. Silently compiling without the
4907        // monitor a build asked for is the one failure mode this feature cannot have.
4908        let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
4909        assert!(e.message.contains("is not a safety tier"), "{}", e.message);
4910        assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
4911    }
4912
4913    /// A checked mode on a Windows target is refused at the link, with a message that says why,
4914    /// rather than left to fail there on names the runtime would have defined. The object is
4915    /// still built, and every other target links as before.
4916    #[test]
4917    fn a_checked_mode_on_windows_is_refused_at_the_link_and_nowhere_else() {
4918        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-fsafety=detect", "a.c"]);
4919        let why = unlinkable(&opts).expect("a refusal");
4920        assert!(why.contains("not available on a Windows target"), "{why}");
4921        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-fsafety=off", "a.c"]);
4922        assert_eq!(unlinkable(&opts), None);
4923        let (opts, _) = compile(&["--target=x86_64-linux-gnu", "-fsafety=detect", "a.c"]);
4924        assert_eq!(unlinkable(&opts), None);
4925    }
4926
4927    #[test]
4928    fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4929        // The default is the one section 9.3 of document 09 gives library code, which is that
4930        // padding does not participate, so a record filled a member at a time is not reported.
4931        let (opts, _) = compile(&["a.c"]);
4932        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4933
4934        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
4935        assert_eq!(opts.padding, rucc_session::Padding::Tracked);
4936
4937        let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
4938        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4939
4940        // The tier is still a tier. A flag whose name starts the same way must not be eaten by
4941        // the one above it, which is the thing worth pinning about a pair of names like these.
4942        let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
4943        assert_eq!(opts.safety, rucc_session::Safety::Off);
4944
4945        let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
4946        assert!(e.message.contains("is not a padding mode"), "{}", e.message);
4947    }
4948
4949    #[test]
4950    fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
4951        // Off by default, because a store to allocated storage sets its effective type and C 6.5
4952        // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
4953        let (opts, _) = compile(&["a.c"]);
4954        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4955
4956        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
4957        assert_eq!(opts.subobject, rucc_session::Subobject::Members);
4958
4959        let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
4960        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4961
4962        // It takes no value. The form that would take one is the strict reading of section 9.4,
4963        // which is not written yet, so say so rather than accept a spelling that does nothing.
4964        let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
4965        assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
4966    }
4967
4968    #[test]
4969    fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
4970        // Off by default, because the record a block keeps is the union of what each pointer
4971        // reached, so two pointers striding through one array without landing on the same byte are
4972        // reported and by the letter of the standard those are different objects. Row Y8 is a build
4973        // deciding it would rather know.
4974        let (opts, _) = compile(&["a.c"]);
4975        assert_eq!(opts.promise, rucc_session::Promise::Off);
4976
4977        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
4978        assert_eq!(opts.promise, rucc_session::Promise::Blocks);
4979
4980        let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
4981        assert_eq!(opts.promise, rucc_session::Promise::Off);
4982
4983        // The tier is still a tier, which is the thing worth pinning about a pair of names where
4984        // one is the front of the other.
4985        let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
4986        assert_eq!(opts.safety, rucc_session::Safety::Off);
4987
4988        let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
4989        assert!(e.message.contains("takes no value"), "{}", e.message);
4990    }
4991
4992    #[test]
4993    fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
4994        // Three modes rather than a bare flag, because section 9.5 gives two answers that record
4995        // the same thing and report different classes, so a flag with no value could not say which
4996        // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
4997        // argument: this is the one plane where an edge nobody interposed costs a false report.
4998        let (opts, _) = compile(&["a.c"]);
4999        assert_eq!(opts.races, rucc_session::Races::Off);
5000
5001        let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
5002        assert_eq!(opts.races, rucc_session::Races::Metadata);
5003
5004        let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
5005        assert_eq!(opts.races, rucc_session::Races::Pointer);
5006
5007        // Last one wins, as it does for every other mode flag here.
5008        let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
5009        assert_eq!(opts.races, rucc_session::Races::Off);
5010
5011        let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
5012        assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
5013    }
5014
5015    #[test]
5016    fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
5017        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
5018        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5019        let text = print_pipeline(&opts);
5020        assert!(text.starts_with("level: -O2\n"), "{text}");
5021        assert!(text.contains("fold"), "{text}");
5022
5023        let a = parse_args(&args(&["--print-pipeline"])).unwrap();
5024        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5025        // Two passes run at `-O0` and neither is an optimization. The first moves what
5026        // `__builtin_expect` said onto the branch and takes the instruction away, so that nothing
5027        // past the optimizer has to know the instruction exists. The second removes code nothing
5028        // reaches. See issue 359.
5029        assert!(print_pipeline(&opts).contains("1: expect,"), "{}", print_pipeline(&opts));
5030        assert!(print_pipeline(&opts).contains("2: simplify-cfg,"), "{}", print_pipeline(&opts));
5031
5032        let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
5033        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5034        // The second turns off and the first does not, because nothing below the optimizer lowers
5035        // what it removes, so `-fno-expect` is a compile that stops rather than one that runs.
5036        let text = print_pipeline(&opts);
5037        assert!(text.contains("1: expect,"), "{text}");
5038        assert!(!text.contains("simplify-cfg"), "{text}");
5039    }
5040
5041    #[test]
5042    fn print_pipeline_takes_the_toggles_into_account() {
5043        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
5044        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5045        let text = print_pipeline(&opts);
5046        // The one that was named is gone and the rest of the level is not, which is the whole
5047        // of what a toggle promises.
5048        assert!(!text.contains("fold"), "{text}");
5049        assert!(text.contains("dce"), "{text}");
5050
5051        // Every pass the compiler has, named off. Built from the registry rather than written
5052        // out, so a pass added later is turned off here too and this keeps testing the thing it
5053        // is about, which is that the toggles can empty a level down to the passes that are not
5054        // optional. Those are named, because a listing that is all of them is a level nobody
5055        // emptied and the assertion would pass while saying nothing.
5056        let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
5057        off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
5058        let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
5059        let a = parse_args(&args(&spelled)).unwrap();
5060        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5061        let text = print_pipeline(&opts);
5062        let left: Vec<&str> =
5063            rucc_opt::PASSES.iter().filter(|p| p.required()).map(|p| p.name()).collect();
5064        assert_eq!(left, vec!["expect", "constant-p"], "{text}");
5065        for (at, name) in left.iter().enumerate() {
5066            assert!(text.contains(&format!("{}: {name},", at + 1)), "{text}");
5067        }
5068        assert!(!text.contains("dce"), "{text}");
5069    }
5070
5071    #[test]
5072    fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
5073        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
5074        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5075        assert!(!print_pipeline(&opts).contains("global fuel"));
5076
5077        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
5078        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5079        let text = print_pipeline(&opts);
5080        // Because the listing is the answer to what this compilation will do, and a run that
5081        // stops after four rewrites is not doing what the level says it does.
5082        assert!(text.contains("global fuel: 4"), "{text}");
5083    }
5084
5085    /// A pass is turned on and off by its own name, and the order the flags were given in is
5086    /// kept, because the last spelling of a name is the one that decides.
5087    #[test]
5088    fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
5089        let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
5090        assert_eq!(
5091            opts.passes,
5092            [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
5093        );
5094
5095        let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
5096        assert!(e.message.contains("unknown option"), "{}", e.message);
5097    }
5098
5099    #[test]
5100    fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
5101        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
5102        assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
5103
5104        let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
5105        assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
5106        let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
5107        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
5108        let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
5109        assert!(e.message.contains("not a number"), "{}", e.message);
5110    }
5111
5112    #[test]
5113    fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
5114        let (opts, _) = compile(&["-c", "-O2", "a.c"]);
5115        assert_eq!(opts.pass_fuel_global, None);
5116
5117        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
5118        assert_eq!(opts.pass_fuel_global, Some(12));
5119        // And it is not the per pass flag with a longer name, so neither spelling swallows the
5120        // other.
5121        assert!(opts.pass_fuel.is_empty());
5122
5123        let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
5124        assert!(e.message.contains("not a number"), "{}", e.message);
5125    }
5126
5127    #[test]
5128    fn the_trace_file_is_taken_from_the_flag_and_an_empty_one_is_refused() {
5129        let (opts, _) = compile(&["-c", "a.c"]);
5130        assert_eq!(opts.trace, None);
5131        let (opts, _) = compile(&["-c", "-frucc-trace=/tmp/compile.jsonl", "a.c"]);
5132        assert_eq!(opts.trace.as_deref(), Some("/tmp/compile.jsonl"));
5133        let e = parse_args(&args(&["-frucc-trace=", "a.c"])).unwrap_err();
5134        assert!(e.message.contains("needs a file"), "{}", e.message);
5135    }
5136
5137    #[test]
5138    fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
5139        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
5140        assert_eq!(
5141            opts.pass_gates,
5142            [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
5143            "the order is what decides, so it has to survive the parse"
5144        );
5145
5146        let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
5147        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
5148        let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
5149        assert!(e.message.contains("ends before it starts"), "{}", e.message);
5150        let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
5151        assert!(e.message.contains("is empty"), "{}", e.message);
5152    }
5153
5154    #[test]
5155    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
5156        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
5157        let text = print_pipeline(&opts);
5158        assert!(text.contains("fold, "), "{text}");
5159        assert!(text.contains("[off for main]"), "{text}");
5160    }
5161
5162    /// The spelling is checked while the arguments are read, because a dump that names a pass
5163    /// this compiler does not have is a typo, and a typo found after the compilation has run is
5164    /// found too late to be any use.
5165    #[test]
5166    fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
5167        let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
5168        assert_eq!(opts.dump_ir, ["all", "after-fold"]);
5169
5170        let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
5171        assert!(e.message.contains("nosuch"), "{}", e.message);
5172        assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
5173    }
5174
5175    /// Every spelling `-fopt-info` takes, and the one it does not.
5176    ///
5177    /// The keywords are checked here for the same reason a dump's pass name is: a person who
5178    /// misspelled one gets no output, and no output is also what a compilation where nothing
5179    /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
5180    #[test]
5181    fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
5182        let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
5183        assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
5184        assert_eq!(opts.opt_info_file, None, "and goes to standard error");
5185
5186        let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
5187        assert_eq!(opts.opt_info, ["missed-note"]);
5188
5189        // Two flags add up rather than the second replacing the first, and the file is the last
5190        // one that named a file, which is how GCC treats both.
5191        let (opts, _) =
5192            compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
5193        assert_eq!(opts.opt_info, ["missed", "all"]);
5194        assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
5195
5196        let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
5197        assert!(e.message.contains("vectorized"), "{}", e.message);
5198        assert!(e.message.contains("`missed`"), "{}", e.message);
5199        let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
5200        assert!(e.message.contains("no file"), "{}", e.message);
5201    }
5202
5203    #[test]
5204    fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
5205        let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
5206        assert!(opts.verify_each);
5207        assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
5208    }
5209
5210    #[test]
5211    fn dash_o_needs_an_argument() {
5212        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
5213        assert_eq!(e.message, "-o requires an argument");
5214    }
5215
5216    #[test]
5217    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
5218        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
5219        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
5220        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
5221    }
5222
5223    #[test]
5224    fn the_include_flags_land_on_the_chain_each_one_names() {
5225        // A sysroot with nothing under it, so that the library's own directories are the
5226        // same on every machine this test runs on, which is none of them.
5227        let (opts, _) = compile(&[
5228            "-Ii",
5229            "-iquote",
5230            "q",
5231            "-isystem",
5232            "sys",
5233            "-idirafter",
5234            "after",
5235            "--sysroot=/nowhere-at-all",
5236            "a.c",
5237        ]);
5238        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5239        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
5240        // which is where GCC puts its own: a directory the user named outranks ours.
5241        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
5242        assert!(!opts.search.dirs()[1].is_system);
5243        assert!(opts.search.dirs()[2].is_system);
5244    }
5245
5246    #[test]
5247    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
5248        // Which machine this runs on decides what is on the path, so the test is about the
5249        // order rather than about the names: ours is on it, the library's follow it, and
5250        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
5251        let (opts, _) = compile(&["a.c"]);
5252        let dirs = opts.search.dirs();
5253        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
5254        assert_eq!(ours, Some(0), "{dirs:?}");
5255        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
5256        let (bare, _) = compile(&["-nostdinc", "a.c"]);
5257        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
5258    }
5259
5260    #[test]
5261    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
5262        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
5263        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5264        assert_eq!(dirs, ["sys", runtime::DIR]);
5265    }
5266
5267    #[test]
5268    fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
5269        // The target is not the machine this test runs on wherever it runs, so the answer is the
5270        // same on all of them: the libc's two include directories for that target, the kernel's
5271        // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
5272        // program that builds on the build machine and is wrong everywhere else.
5273        let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
5274        let dirs: Vec<&std::path::Path> =
5275            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5276        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
5277        let kernel = cache::dir().join("kernel-headers");
5278        assert_eq!(dirs.len(), 5, "{dirs:?}");
5279        assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
5280        assert_eq!(dirs[1], root.join("include").join("riscv64"));
5281        assert_eq!(dirs[2], root.join("include").join("generic"));
5282        // The kernel's, which are beside the sysroots rather than inside one, because every target
5283        // that shares an architecture reads the same files.
5284        assert_eq!(dirs[3], kernel.join("riscv"));
5285        assert_eq!(dirs[4], kernel.join("generic"));
5286    }
5287
5288    #[test]
5289    fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
5290        // The other side of the same answer. Windows has its own system headers and no `linux/` at
5291        // all, so the list is the libc's own and the question never arises, which is the `None` that
5292        // `link::cross_kernel` returns rather than a directory nothing would be found in.
5293        //
5294        // The libc's own is one directory rather than two here, because mingw-w64 publishes a single
5295        // header tree for every architecture and `Sysroot::splits_by_arch` says so.
5296        let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
5297        let dirs: Vec<&std::path::Path> =
5298            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5299        assert_eq!(dirs.len(), 2, "{dirs:?}");
5300        assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
5301    }
5302
5303    #[test]
5304    fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
5305        // One tree serves every glibc release, so the release is what the target supplies, and the
5306        // condition is the same one that chose the directories. A host glibc and a tree somebody
5307        // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
5308        // different values is a warning on every compilation of every file.
5309        //
5310        // The architecture is chosen against this machine's rather than written down, because the
5311        // bundled tree is only in effect for a target that is not this machine. The first version of
5312        // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
5313        // Linux runner, so it passed here and failed there.
5314        //
5315        // Unless this machine has the distribution's cross packages for it and nothing fetched, and
5316        // then those are the headers and their own `features.h` says the release, as it does for a
5317        // tree somebody named.
5318        let gnu = format!("--target={}-linux-gnu", cross_arch());
5319        let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
5320        let (link, _) = linking(&[&gnu, "-c", "a.c"]);
5321        let distro = link::distro_cross(bundled.target, &link).is_some();
5322        assert_eq!(bundled.glibc_minor, if distro { None } else { Some(44) });
5323        let pin = format!("{gnu}.2.28");
5324        let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
5325        assert_eq!(pinned.glibc_minor, Some(28));
5326
5327        let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5328        assert_eq!(named.glibc_minor, None);
5329        let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
5330        assert_eq!(none.glibc_minor, None);
5331        let musl = format!("--target={}-linux-musl", cross_arch());
5332        let (musl, _) = compile(&[&musl, "-c", "a.c"]);
5333        assert_eq!(musl.glibc_minor, None);
5334
5335        // And this machine's own target gets nothing, whatever this machine is, because its headers
5336        // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
5337        // that is the case this test had backwards; on a mac it is true for the other reason, which
5338        // is that Darwin is not a glibc target at all.
5339        if let Some(host) = Triple::host() {
5340            let native = format!("--target={}", host.tuple());
5341            let (native, _) = compile(&[&native, "-c", "a.c"]);
5342            assert_eq!(native.glibc_minor, None);
5343        }
5344    }
5345
5346    #[test]
5347    fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
5348        // The end to end half of the answer in `link::cross_for`. A release named for this machine's
5349        // own target is a cross compile, so the headers are the bundled tree's and the macro says
5350        // what was asked for rather than what this machine has.
5351        //
5352        // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
5353        // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
5354        // where the case lives.
5355        let Some(host) = Triple::host() else { return };
5356        if host.os != rucc_target::Os::Linux || host.env != rucc_target::Env::Gnu {
5357            return;
5358        }
5359        let pin = format!("--target={}.2.28", host.tuple());
5360        let (opts, _) = compile(&[&pin, "-c", "a.c"]);
5361        assert_eq!(opts.glibc_minor, Some(28));
5362        let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
5363        let dirs: Vec<&std::path::Path> =
5364            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5365        assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
5366        // And nothing of this machine's, which is the failure this was: a program compiled against
5367        // 2.44 declarations and told it was 2.28.
5368        assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
5369    }
5370
5371    /// An architecture that is not this machine's, out of the three the driver has targets for.
5372    ///
5373    /// A test about the bundled sysroot has to name a target that is not the host, because a target
5374    /// that is the host reads the host's own headers and libraries. Asking which machine this is
5375    /// beats picking a row and hoping, and it is two lines.
5376    fn cross_arch() -> &'static str {
5377        match Triple::host().map(|host| host.arch) {
5378            Some(rucc_target::Arch::X86_64) => "aarch64",
5379            _ => "x86_64",
5380        }
5381    }
5382
5383    #[test]
5384    fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
5385        // Both versions in the message, because the two things a person can do about it are pin a
5386        // release the tree has and name a sysroot that has the one they asked for, and neither is a
5387        // choice they can make without knowing which release the tree is.
5388        //
5389        // Not this machine's architecture, for the reason the test above gives: the refusal is about
5390        // the bundled tree, and the bundled tree is not what a target that is this machine reads.
5391        let target = format!("--target={}-linux-gnu.2.99", cross_arch());
5392        let message = refused(&[&target, "-c", "a.c"]);
5393        assert!(message.contains("asked for glibc 2.99"), "{message}");
5394        assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
5395        assert!(message.contains("--sysroot"), "{message}");
5396    }
5397
5398    #[test]
5399    fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
5400        // The tree somebody assembled beats the one we would build, on the headers as on the
5401        // libraries. It is empty here, which is why the list comes out short: the directories under
5402        // it are checked for rather than assumed, and a tree that is not there offers nothing.
5403        let (opts, _) =
5404            compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5405        let dirs: Vec<&std::path::Path> =
5406            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5407        assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
5408    }
5409
5410    #[test]
5411    fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
5412        let (opts, _) =
5413            compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
5414        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5415        assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
5416        // An angled include sees only what came after the flag.
5417        assert_eq!(opts.search.start(IncludeForm::Angled), 2);
5418        assert!(!opts.search.searches_current_dir());
5419    }
5420
5421    #[test]
5422    fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
5423        let (opts, _) = compile(&[
5424            "-iprefix",
5425            "/tools/",
5426            "-iwithprefix",
5427            "late",
5428            "-iwithprefixbefore",
5429            "early",
5430            "-iprefix",
5431            "/other/",
5432            "-iwithprefix",
5433            "last",
5434            "-nostdinc",
5435            "a.c",
5436        ]);
5437        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5438        // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
5439        // puts them rather than where its manual says it does.
5440        assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
5441        assert!(!opts.search.dirs()[0].is_system);
5442        assert!(opts.search.dirs()[1].is_system);
5443    }
5444
5445    #[test]
5446    fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
5447        let (opts, _) =
5448            compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
5449        let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
5450        assert_eq!(names, ["one.h", "two.h", "3.h"]);
5451        assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
5452    }
5453
5454    #[test]
5455    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
5456        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
5457        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5458        assert_eq!(dirs, ["i"]);
5459    }
5460
5461    #[test]
5462    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
5463        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
5464        assert_eq!(opts.std, Std::C11);
5465        assert!(opts.gnu_extensions);
5466
5467        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
5468        assert_eq!(opts.std, Std::C99);
5469        assert!(!opts.gnu_extensions);
5470
5471        let (opts, _) = compile(&["-ansi", "a.c"]);
5472        assert_eq!(opts.std, Std::C89);
5473        assert!(!opts.gnu_extensions);
5474
5475        let (opts, _) = compile(&["-std=gnu2y", "a.c"]);
5476        assert_eq!(opts.std, Std::C2y);
5477        assert!(opts.gnu_extensions);
5478
5479        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
5480        assert!(e.message.contains("unknown dialect"), "{}", e.message);
5481    }
5482
5483    #[test]
5484    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
5485        let (opts, _) = compile(&["-dM", "a.c"]);
5486        assert!(opts.dumps.macros);
5487
5488        // Packed, the way GCC takes them, and a letter in the family we have not written yet
5489        // is accepted and does nothing rather than failing a build.
5490        let (opts, _) = compile(&["-dDM", "a.c"]);
5491        assert!(opts.dumps.macros);
5492        let (opts, _) = compile(&["-dD", "a.c"]);
5493        assert!(!opts.dumps.macros);
5494
5495        let (opts, _) = compile(&["a.c"]);
5496        assert!(!opts.dumps.any());
5497
5498        // `-dumpversion` is a different flag that happens to start the same way, and it is read
5499        // as itself rather than as a dump of nothing.
5500        assert_eq!(printed(&["-dumpversion", "a.c"]), "16");
5501    }
5502
5503    #[test]
5504    fn the_msvc_runtime_is_a_compile_flag_and_a_link_one() {
5505        let (link, _) = linking(&["a.c"]);
5506        assert_eq!(link.crt, rucc_sysroot::Crt::Static);
5507        let (link, _) = linking(&["-fms-runtime-lib=dll", "a.c"]);
5508        assert_eq!(link.crt, rucc_sysroot::Crt::Dll);
5509        let (opts, _) = compile(&["-fms-runtime-lib=dll", "-c", "a.c"]);
5510        assert!(opts.ms_dll_runtime);
5511        let (opts, _) = compile(&["-fms-runtime-lib=dll", "-fms-runtime-lib=static", "-c", "a.c"]);
5512        assert!(!opts.ms_dll_runtime, "the last one wins");
5513        let e = parse_args(&args(&["-fms-runtime-lib=dll_dbg", "a.c"])).unwrap_err();
5514        assert!(e.message.contains("debug"), "{}", e.message);
5515        let e = parse_args(&args(&["-fms-runtime-lib=shared", "a.c"])).unwrap_err();
5516        assert!(e.message.contains("static or dll"), "{}", e.message);
5517    }
5518
5519    #[test]
5520    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
5521        let (opts, _) = compile(&["a.c"]);
5522        assert_eq!(
5523            opts.gnuc,
5524            GnucVersion { major: 16, minor: 0, patch: 0 },
5525            "the release this compiler is written against, and the earliest one of that series"
5526        );
5527
5528        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
5529        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
5530
5531        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
5532        // patchlevel and a harness that pastes that back has to be understood.
5533        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
5534        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
5535
5536        assert!(opts.gnuc_given, "a version that was written down is one that was given");
5537        assert!(!compile(&["a.c"]).0.gnuc_given);
5538
5539        let (opts, _) = compile(&["-fms-compatibility-version=19.29.30133", "a.c"]);
5540        assert_eq!(opts.msc.msc_ver(), 1929);
5541        assert_eq!(opts.msc.msc_full_ver(), 192_930_133);
5542
5543        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
5544        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
5545
5546        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
5547        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
5548
5549        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
5550        assert!(e.message.contains("more than three"), "{}", e.message);
5551    }
5552
5553    #[test]
5554    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
5555        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
5556        assert!(opts.pedantic);
5557        assert_eq!(opts.std, Std::C17);
5558
5559        // The `-W` family's name for it, which is what a build that groups its warning flags
5560        // tends to write.
5561        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
5562        assert!(opts.pedantic);
5563
5564        let (opts, _) = compile(&["-std=c17", "a.c"]);
5565        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
5566    }
5567
5568    #[test]
5569    fn dash_p_and_dash_ffreestanding_reach_the_options() {
5570        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
5571        assert!(!opts.line_markers);
5572        assert!(!opts.hosted);
5573        assert_eq!(opts.emit, EmitKind::Preprocessed);
5574    }
5575
5576    /// The two ways a build says it means its own function by a name the C library also has.
5577    ///
5578    /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
5579    /// build writes when it means its own `memcpy` and the library's everything else. The name is
5580    /// kept as it was written and not checked against anything, because a program is allowed to
5581    /// mean something by a name this compiler has never heard of.
5582    #[test]
5583    fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
5584        let (opts, _) = compile(&["-c", "a.c"]);
5585        assert!(opts.builtins, "a library name means the library function by default");
5586        assert!(opts.no_builtin.is_empty());
5587
5588        let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
5589        assert!(!opts.builtins);
5590
5591        let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
5592        assert!(opts.builtins, "the last mention decides");
5593
5594        let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
5595        assert!(opts.builtins, "one name is not the family");
5596        assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
5597    }
5598
5599    /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
5600    /// and which was refused as an unknown option until now.
5601    ///
5602    /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
5603    /// the address across a component boundary, and nothing derives anything from that promise
5604    /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
5605    /// over a distinction this compiler does not make.
5606    #[test]
5607    fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
5608        let (opts, _) = compile(&["-c", "a.c"]);
5609        assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
5610
5611        for (written, wanted) in [
5612            ("default", Visibility::Default),
5613            ("hidden", Visibility::Hidden),
5614            ("internal", Visibility::Hidden),
5615            ("protected", Visibility::Protected),
5616        ] {
5617            let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
5618            assert_eq!(opts.visibility, wanted, "{written}");
5619        }
5620
5621        // The last mention decides, which is what every other flag of this shape does and what a
5622        // build that turns something off for one directory relies on.
5623        let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
5624        assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
5625
5626        // A spelling gcc does not take is refused rather than read as the default, because a
5627        // build that meant hidden and got exported is a library with the wrong interface and
5628        // nothing said about it anywhere.
5629        let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
5630        assert!(failed.to_string().contains("is not a visibility"), "{failed}");
5631    }
5632
5633    /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
5634    /// described, and the values are gcc 16's three.
5635    #[test]
5636    fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
5637        let (opts, _) = compile(&["-c", "a.c"]);
5638        assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
5639
5640        for (written, wanted) in
5641            [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
5642        {
5643            let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
5644            assert_eq!(opts.fp_contract, wanted, "{written}");
5645        }
5646
5647        let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
5648        assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
5649
5650        // Refused rather than read as one of the three, because a build that asked for no fusing
5651        // and was given the default would be one whose numbers change and whose command line says
5652        // they should not. gcc refuses the same spellings and names the same three in its message.
5653        for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
5654            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5655            assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
5656        }
5657
5658        // And the other one that takes a value, which is taken and kept nowhere: every operation
5659        // here is computed in the type it was written in, so `standard` is what happens and the
5660        // other two are permission to do something this does not do.
5661        let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
5662        assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
5663    }
5664
5665    /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
5666    /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
5667    /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
5668    #[test]
5669    fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
5670        let (opts, _) = compile(&["-c", "a.c"]);
5671        assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
5672        assert!(opts.prefix_map.debug.is_empty(), "nor here");
5673        assert!(opts.prefix_map.profile.is_empty(), "nor here");
5674
5675        let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
5676        assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
5677        assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
5678
5679        let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
5680        assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
5681        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5682
5683        let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
5684        assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
5685        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5686
5687        let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
5688        for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
5689            assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
5690        }
5691
5692        // Every mention is kept and the last one that matches wins, unlike the flags above whose
5693        // last mention replaces the earlier ones. A build writes one of these per source root and
5694        // expects all of them to be in force, which is the whole point of a list.
5695        let (opts, _) =
5696            compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
5697        assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
5698        assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
5699
5700        // An argument with no `=` is refused rather than ignored, because a build whose paths were
5701        // meant to be rewritten and were not is one that ships the build directory's name and says
5702        // nothing about it. gcc refuses the same thing.
5703        for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
5704            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5705            assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
5706        }
5707    }
5708
5709    /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
5710    /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
5711    /// one. A kernel and an embedded image are both linked that way.
5712    ///
5713    /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
5714    /// the other is a build that measured something: splitting the code is nearly free at link time
5715    /// and splitting the data can defeat the linker's ordering of what is next to what.
5716    #[test]
5717    fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
5718        let (opts, _) = compile(&["-c", "a.c"]);
5719        assert!(!opts.function_sections, "one text section unless something says otherwise");
5720        assert!(!opts.data_sections);
5721
5722        let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
5723        assert!(opts.function_sections);
5724        assert!(!opts.data_sections, "one flag is not the other");
5725
5726        let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
5727        assert!(opts.data_sections);
5728        assert!(!opts.function_sections);
5729
5730        // Both directions taken, and the off one is what happens anyway rather than a refusal,
5731        // since a build that writes it is asking for the default.
5732        let (opts, _) = compile(&[
5733            "-c",
5734            "-ffunction-sections",
5735            "-fno-function-sections",
5736            "-fdata-sections",
5737            "-fno-data-sections",
5738            "a.c",
5739        ]);
5740        assert!(!opts.function_sections, "the last mention decides");
5741        assert!(!opts.data_sections, "the last mention decides");
5742    }
5743
5744    /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
5745    /// line, since the dialect asks for GNU's reading further in rather than through this.
5746    #[test]
5747    fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
5748        let (opts, _) = compile(&["-c", "a.c"]);
5749        assert!(!opts.gnu89_inline, "C's reading of inline by default");
5750
5751        let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
5752        assert!(opts.gnu89_inline);
5753
5754        let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
5755        assert!(!opts.gnu89_inline, "the last mention decides");
5756
5757        // The C89 dialects are under GNU's reading whether this was written or not, so the flag
5758        // stays off there and the dialect is what the checker and the macro set both ask. That is
5759        // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
5760        // dialect already has. gcc refuses that command line, which is measured in the issue.
5761        let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
5762        assert!(!opts.gnu89_inline);
5763    }
5764
5765    /// Both spellings of both frame flags, since a build that wants one usually writes the
5766    /// other beside it for the one file that has to be compiled the ordinary way.
5767    #[test]
5768    fn the_two_frame_flags_are_read_in_both_directions() {
5769        let (opts, _) = compile(&["-c", "a.c"]);
5770        assert_eq!(opts.frame_pointer, None, "nothing said, so the level decides");
5771        assert!(opts.keeps_frame_pointer(), "and at -O0 gcc keeps one, so this does too");
5772        let (opts, _) = compile(&["-c", "-O1", "a.c"]);
5773        assert!(!opts.keeps_frame_pointer(), "gcc omits it above -O0 and so does this");
5774        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
5775
5776        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
5777        assert_eq!(opts.frame_pointer, Some(true));
5778        assert!(!opts.red_zone);
5779
5780        let (opts, _) = compile(&[
5781            "-c",
5782            "-fno-omit-frame-pointer",
5783            "-fomit-frame-pointer",
5784            "-mno-red-zone",
5785            "-mred-zone",
5786            "a.c",
5787        ]);
5788        assert_eq!(opts.frame_pointer, Some(false), "the last one wins, as it does in gcc");
5789        assert!(!opts.keeps_frame_pointer(), "and it wins over the level too");
5790        assert!(opts.red_zone);
5791    }
5792
5793    /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
5794    /// spelled three ways because a build that turns one off writes whichever it turned on.
5795    #[test]
5796    fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
5797        let (opts, _) = compile(&["-c", "a.c"]);
5798        assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
5799
5800        for (flag, want) in [
5801            ("-fstack-protector", Protector::Buffers),
5802            ("-fstack-protector-strong", Protector::Strong),
5803            ("-fstack-protector-all", Protector::All),
5804        ] {
5805            let (opts, _) = compile(&["-c", flag, "a.c"]);
5806            assert_eq!(opts.protector, want, "{flag}");
5807        }
5808
5809        // What a package build does: the strong one in the global flags and one directory that
5810        // cannot have a protector turning it off on the line after.
5811        for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
5812            let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
5813            assert_eq!(opts.protector, Protector::None, "{off}");
5814        }
5815        let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
5816        assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
5817    }
5818
5819    /// A switch rather than a level, because how a frame is taken is one question and which
5820    /// functions get a canary is another, and gcc spells it that way for the same reason.
5821    #[test]
5822    fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
5823        let (opts, _) = compile(&["-c", "a.c"]);
5824        assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
5825
5826        let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
5827        assert!(opts.stack_clash);
5828
5829        // The same shape a package build uses for the protector: on in the global flags and off
5830        // for the one directory that cannot have it.
5831        let (opts, _) =
5832            compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
5833        assert!(!opts.stack_clash);
5834        let (opts, _) =
5835            compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
5836        assert!(opts.stack_clash, "the last one wins either way round");
5837
5838        // The two are independent, since one is about the frame and the other about the function.
5839        let (opts, _) =
5840            compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
5841        assert!(opts.stack_clash);
5842        assert_eq!(opts.protector, Protector::Strong);
5843    }
5844
5845    /// One flag with an argument rather than a family of spellings, because what it asks about is
5846    /// which of the two edges of a control flow transfer is checked and the two are not separate
5847    /// questions to the hardware.
5848    #[test]
5849    fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
5850        let (opts, _) = compile(&["-c", "a.c"]);
5851        assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
5852
5853        for (arg, want) in [
5854            ("-fcf-protection", Control::Full),
5855            ("-fcf-protection=full", Control::Full),
5856            ("-fcf-protection=branch", Control::Branch),
5857            ("-fcf-protection=return", Control::Return),
5858            ("-fcf-protection=none", Control::None),
5859            ("-fcf-protection=check", Control::Check),
5860        ] {
5861            let (opts, _) = compile(&["-c", arg, "a.c"]);
5862            assert_eq!(opts.control, want, "{arg}");
5863        }
5864
5865        // The shape a package build uses: on in the global flags and off for the one directory
5866        // that cannot have it, whichever of the two spellings of off it reaches for.
5867        let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
5868        assert_eq!(opts.control, Control::None);
5869        let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
5870        assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
5871    }
5872
5873    /// The profiler is asked for by two spellings, and where its hook goes by two more.
5874    ///
5875    /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
5876    /// asks for no call, which is what gcc does with it, and a build system that sets it globally
5877    /// and asks for the profile per directory needs that to be true rather than an error.
5878    ///
5879    /// The link is asserted alongside, because the flag changes it too and a build that compiled
5880    /// with it and linked without it is a program that calls the hook everywhere and never writes a
5881    /// profile.
5882    #[test]
5883    fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
5884        let (opts, _) = compile(&["-c", "a.c"]);
5885        assert!(!opts.profile);
5886        assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
5887
5888        for arg in ["-pg", "-p"] {
5889            let (opts, _) = compile(&["-c", arg, "a.c"]);
5890            assert!(opts.profile, "{arg}");
5891            let (link, _) = linking(&[arg, "a.c"]);
5892            assert!(link.profile, "{arg} changes the link as well");
5893        }
5894
5895        for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
5896            let (opts, _) = compile(&["-c", arg, "a.c"]);
5897            assert_eq!(opts.hook, want, "{arg}");
5898            assert!(!opts.profile, "{arg} asks for no call of its own");
5899        }
5900
5901        let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
5902        assert_eq!(opts.hook, Hook::Late, "the last one wins");
5903        assert!(opts.profile);
5904    }
5905
5906    /// How much room a patcher is promised, which is one number or two.
5907    ///
5908    /// A command line that did not ask is asserted alongside, because the flag has to be written to
5909    /// mean anything and a build that reserved room nobody asked for would grow every function in
5910    /// it for nothing.
5911    #[test]
5912    fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
5913        let (opts, _) = compile(&["-c", "a.c"]);
5914        assert_eq!(opts.patchable, Patchable::default());
5915        assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
5916
5917        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
5918        assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
5919
5920        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
5921        assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
5922        assert_eq!(opts.patchable.after(), 2);
5923
5924        // The last one wins, which is what every other flag of this shape does and what a build
5925        // that adds one to a command line it did not write is relying on.
5926        let (opts, _) = compile(&[
5927            "-c",
5928            "-fpatchable-function-entry=5,3",
5929            "-fpatchable-function-entry=2",
5930            "a.c",
5931        ]);
5932        assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
5933    }
5934
5935    /// And a request nothing could satisfy is refused rather than rounded into one that can be.
5936    #[test]
5937    fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
5938        for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
5939            let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
5940            assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
5941        }
5942    }
5943
5944    /// What wraps rather than being undefined, which is two questions and three flags.
5945    ///
5946    /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
5947    /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
5948    /// only what it asked for.
5949    #[test]
5950    fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
5951        let (opts, _) = compile(&["-c", "a.c"]);
5952        assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
5953
5954        let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
5955        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5956
5957        let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
5958        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
5959
5960        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
5961        assert_eq!(opts.wrapping, Wrapping::ALL);
5962
5963        // And the last one wins, in both directions. A build that turns one of these on globally
5964        // and off for one directory is relying on that, and so is one that writes the pair and
5965        // then takes half of it back.
5966        let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
5967        assert_eq!(opts.wrapping, Wrapping::NONE);
5968
5969        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
5970        assert_eq!(opts.wrapping, Wrapping::NONE);
5971
5972        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
5973        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5974    }
5975
5976    /// And the other answer to the signed question cannot be held at the same time as the first.
5977    ///
5978    /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
5979    /// resolves it by letting the last one win rather than by reporting anything. That was measured
5980    /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
5981    /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
5982    #[test]
5983    fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
5984        let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
5985        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5986
5987        let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
5988        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5989
5990        let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
5991        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5992
5993        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
5994        assert_eq!(opts.wrapping, Wrapping::ALL);
5995
5996        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
5997        assert_eq!(opts.wrapping, Wrapping::NONE);
5998
5999        // And the flag that says what may be assumed says nothing about what happens, so it leaves
6000        // this alone where it takes the wrapping away. gcc does the same.
6001        let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
6002        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
6003    }
6004
6005    /// What a plain `char` is, which is four spellings of two answers and nothing by default.
6006    ///
6007    /// Nothing is the target's own answer and has to stay distinct from both of the others, since
6008    /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
6009    /// The negative spellings are the other flag rather than a way of asking for the default, which
6010    /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
6011    /// `-fno-unsigned-char` does not.
6012    #[test]
6013    fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
6014        let (opts, _) = compile(&["-c", "a.c"]);
6015        assert_eq!(opts.char_signed, None);
6016
6017        for flag in ["-fsigned-char", "-fno-unsigned-char"] {
6018            let (opts, _) = compile(&["-c", flag, "a.c"]);
6019            assert_eq!(opts.char_signed, Some(true), "{flag}");
6020        }
6021
6022        for flag in ["-funsigned-char", "-fno-signed-char"] {
6023            let (opts, _) = compile(&["-c", flag, "a.c"]);
6024            assert_eq!(opts.char_signed, Some(false), "{flag}");
6025        }
6026
6027        // And the last one wins, which is what a build that sets one globally and the other for a
6028        // directory relies on.
6029        let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
6030        assert_eq!(opts.char_signed, Some(true));
6031
6032        // And what is asked for reaches the target, because that is what every other part of the
6033        // compiler asks. The triple is one whose own answer is the opposite, so a session that
6034        // ignored the flag would still read as signed here.
6035        let (opts, _) =
6036            compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
6037        assert!(Session::new(*opts).target.char_is_signed);
6038        let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
6039        assert!(!Session::new(*opts).target.char_is_signed);
6040    }
6041
6042    /// And the size of an enumeration, which is one question with two spellings.
6043    #[test]
6044    fn the_smallest_enumeration_is_asked_for_and_taken_back() {
6045        let (opts, _) = compile(&["-c", "a.c"]);
6046        assert!(!opts.short_enums);
6047
6048        let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
6049        assert!(opts.short_enums);
6050
6051        let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
6052        assert!(!opts.short_enums);
6053
6054        let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
6055        assert!(opts.short_enums);
6056    }
6057
6058    /// And Microsoft's reading of an anonymous member, which the target answers where the command
6059    /// line said nothing. gcc's mingw build has it on and its Linux build has it off, so a header
6060    /// that closes a nameless union with a macro that expands to nothing is read the way the
6061    /// compiler that platform ships would read it.
6062    #[test]
6063    fn the_microsoft_reading_of_a_member_follows_the_target_until_it_is_asked_for() {
6064        // Named rather than left to the host, since the answer this asks for is the one a target
6065        // that is not Windows gives and on a Windows machine the host is not one of those.
6066        let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
6067        assert!(!Session::new(*opts).ms_extensions());
6068
6069        let (opts, _) = compile(&["-c", "--target=x86_64-pc-windows-gnu", "a.c"]);
6070        assert!(Session::new(*opts).ms_extensions());
6071
6072        let (opts, _) = compile(&["-c", "-fms-extensions", "a.c"]);
6073        assert!(Session::new(*opts).ms_extensions());
6074
6075        let (opts, _) =
6076            compile(&["-c", "--target=x86_64-pc-windows-gnu", "-fno-ms-extensions", "a.c"]);
6077        assert!(!Session::new(*opts).ms_extensions());
6078    }
6079
6080    /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
6081    ///
6082    /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
6083    /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
6084    /// family would report it as an unknown pass. Neither is the news the build wants.
6085    #[test]
6086    fn a_control_flow_protection_nothing_means_is_refused() {
6087        let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
6088        assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
6089        assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
6090    }
6091
6092    #[test]
6093    fn mingw_subsystem_and_unicode_flags_are_taken_last_one_winning() {
6094        let (link, _) = linking(&["-mwindows", "-municode", "-mthreads", "-static-libgcc", "a.c"]);
6095        assert!(link.gui && link.unicode);
6096        let (link, _) = linking(&["-mwindows", "-mconsole", "a.c"]);
6097        assert!(!link.gui);
6098        let (opts, _) = compile(&["-municode", "-c", "a.c"]);
6099        assert!(opts.defines.iter().any(|define| define == "UNICODE"), "{:?}", opts.defines);
6100    }
6101
6102    #[test]
6103    fn the_link_flags_are_collected_apart_from_the_compilation() {
6104        let (link, _) = linking(&[
6105            "-static",
6106            "-nostartfiles",
6107            "-rdynamic",
6108            "-s",
6109            "-fuse-ld=mold",
6110            "-L/opt/lib",
6111            "-B",
6112            "/opt/tools",
6113            "a.c",
6114        ]);
6115        assert!(link.is_static);
6116        assert!(link.no_startfiles);
6117        assert!(link.export_dynamic);
6118        assert!(link.strip);
6119        assert_eq!(link.use_ld.as_deref(), Some("mold"));
6120        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
6121        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
6122    }
6123
6124    #[test]
6125    fn a_mingw_link_names_its_output_the_way_mingw_gcc_does() {
6126        // gcc puts `.exe` on a DLL's name as well when it has no extension, so `-shared` is not an
6127        // exception, and `-c` links nothing and is. tamnd/rucc#2152.
6128        let mingw = "--target=x86_64-windows-gnu";
6129        let (_, plan) = linking(&[mingw, "a.c", "-o", "foo"]);
6130        assert_eq!(plan.link.expect("expected a link step").output, "foo.exe");
6131        let (_, plan) = linking(&[mingw, "-shared", "a.c", "-o", "x"]);
6132        assert_eq!(plan.link.expect("expected a link step").output, "x.exe");
6133        let (_, plan) = linking(&[mingw, "-shared", "a.c", "-o", "x.dll"]);
6134        assert_eq!(plan.link.expect("expected a link step").output, "x.dll");
6135        let (_, plan) = compile(&[mingw, "-c", "a.c", "-o", "x"]);
6136        assert!(plan.link.is_none());
6137        assert_eq!(plan.jobs[0].output, Output::File("x".into()));
6138        let (_, plan) = linking(&[LINUX, "a.c", "-o", "foo"]);
6139        assert_eq!(plan.link.expect("expected a link step").output, "foo");
6140    }
6141
6142    #[test]
6143    fn a_comma_in_dash_wl_separates_two_arguments() {
6144        // The target is written down because the name of the object is derived from it, and `a.o`
6145        // on a Linux host is `a.obj` on a Windows one. What is under test is the splitting of the
6146        // argument, which has nothing to do with either.
6147        let (_, plan) = linking(&[LINUX, "-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
6148        let link = plan.link.expect("expected a link step");
6149        assert_eq!(
6150            link.inputs,
6151            vec![
6152                link::Item::Linker("-rpath".into()),
6153                link::Item::Linker("/opt/lib".into()),
6154                link::Item::Linker("--as-needed".into()),
6155                link::Item::File("a.o".into()),
6156            ]
6157        );
6158    }
6159
6160    #[test]
6161    fn a_word_for_the_linker_keeps_its_place_among_the_files_too() {
6162        // What libtool writes around a set of convenience archives, and what #1279 was. Both words
6163        // are about the files between them, so the pair collected out of the line and appended to
6164        // the end is two options that bracket nothing and an archive that went in empty.
6165        let (_, plan) = linking(&[
6166            "--target=x86_64-unknown-linux-gnu",
6167            "a.c",
6168            "-Wl,--whole-archive",
6169            "libaesni.a",
6170            "-Wl,--no-whole-archive",
6171            "-lm",
6172        ]);
6173        let link = plan.link.expect("expected a link step");
6174        assert_eq!(
6175            link.inputs,
6176            vec![
6177                link::Item::File("a.o".into()),
6178                link::Item::Linker("--whole-archive".into()),
6179                link::Item::File("libaesni.a".into()),
6180                link::Item::Linker("--no-whole-archive".into()),
6181                link::Item::Library("m".into()),
6182            ]
6183        );
6184        // And it is not a job, because there is nothing to compile in a word for the linker.
6185        assert_eq!(plan.jobs.len(), 2);
6186    }
6187
6188    #[test]
6189    fn a_word_for_the_linker_on_a_dash_c_line_is_dropped_without_a_word() {
6190        // GCC says nothing about one either. `-Wl,` on a compile line is what a build system
6191        // writes when one variable holds the flags for both, and a note here would be a note on
6192        // every compile of every autotools project.
6193        let (_, plan) = linking(&["-c", "-Wl,--as-needed", "a.c"]);
6194        assert!(plan.link.is_none());
6195        assert!(plan.notes.is_empty(), "{:?}", plan.notes);
6196        assert_eq!(plan.jobs.len(), 1);
6197    }
6198
6199    #[test]
6200    fn a_library_keeps_its_place_between_the_objects() {
6201        // Link order is semantic: `-lm` written between two files resolves for the one before
6202        // it and not for the one after, so a library cannot be collected into a list of its own.
6203        // The target is named because the suffix of an object is the target's and this asserts
6204        // on the names: the same command line on a Windows host plans two `.obj` files.
6205        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
6206        let link = plan.link.expect("expected a link step");
6207        assert_eq!(
6208            link.inputs,
6209            vec![
6210                link::Item::File("a.o".into()),
6211                link::Item::Library("m".into()),
6212                link::Item::File("b.o".into()),
6213            ]
6214        );
6215        // And it is not a job, because there is nothing to compile in a library.
6216        assert_eq!(plan.jobs.len(), 2);
6217    }
6218
6219    #[test]
6220    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
6221        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
6222        assert!(plan.link.is_none());
6223        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
6224    }
6225
6226    #[test]
6227    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
6228        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
6229        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
6230    }
6231
6232    fn printed(s: &[&str]) -> String {
6233        match parse_args(&args(s)).expect("expected an answer") {
6234            Action::Print(line) => line,
6235            other => panic!("expected an answer, got {other:?}"),
6236        }
6237    }
6238
6239    fn refused(s: &[&str]) -> String {
6240        parse_args(&args(s)).expect_err("expected a refusal").message
6241    }
6242
6243    #[test]
6244    fn a_warning_flag_gcc_knows_is_taken_even_though_nothing_reads_it() {
6245        // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
6246        // out whether a warning flag exists by passing it and looking at the exit status, so a
6247        // compiler that refuses one gcc knows fails a script written for gcc.
6248        let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
6249        assert!(!opts.warnings_are_errors);
6250        assert!(opts.warnings);
6251        // The two spellings that do mean something are still read.
6252        let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
6253        assert!(opts.warnings_are_errors);
6254        let (opts, _) = compile(&["-w", "-c", "a.c"]);
6255        assert!(!opts.warnings);
6256        // Off without being asked, the way gcc has it off, and both spellings are read.
6257        let (opts, _) = compile(&["-c", "a.c"]);
6258        assert!(!opts.system_header_warnings);
6259        let (opts, _) = compile(&["-Wsystem-headers", "-c", "a.c"]);
6260        assert!(opts.system_header_warnings);
6261        let (opts, _) = compile(&["-Wsystem-headers", "-Wno-system-headers", "-c", "a.c"]);
6262        assert!(!opts.system_header_warnings);
6263        let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
6264        assert!(opts.pedantic && opts.warnings_are_errors);
6265    }
6266
6267    #[test]
6268    fn a_warning_flag_gcc_refuses_is_refused_here_too() {
6269        // Postgres's meson build probes these, and with rucc taking them it ended up passing four
6270        // clang warnings that the gcc build had dropped.
6271        for flag in ["-Wcast-function-type-strict", "-Wunused-command-line-argument"] {
6272            assert_eq!(refused(&[flag, "-c", "a.c"]), format!("unknown option `{flag}`"));
6273        }
6274        assert_eq!(
6275            refused(&["-Werror=unguarded-availability-new", "-c", "a.c"]),
6276            "`-Werror=unguarded-availability-new`: no option `-Wunguarded-availability-new`"
6277        );
6278        assert!(refused(&["-Wno-error=nonsense", "-c", "a.c"]).contains("no option `-Wnonsense`"));
6279        // gcc takes `-Wno-` of a name it does not know, and says nothing unless something else
6280        // is said, and it takes C++ and Fortran names on a C compile.
6281        for flag in
6282            ["-Wno-cast-function-type-strict", "-Werror=format", "-Wformat=2", "-Wabi-tag", "-W"]
6283        {
6284            compile(&[flag, "-c", "a.c"]);
6285        }
6286    }
6287
6288    #[test]
6289    fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
6290        // Every one of these says something about the output, so the wrong answer is silence.
6291        assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
6292        assert!(refused(&["-Wp,-C", "-c", "a.c"]).contains("separate assembler"));
6293        assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
6294        assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
6295        assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
6296        // The word size the target does not have, which is a target this compiler was not asked
6297        // for rather than a flag it does not know.
6298        let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
6299        assert!(no32.contains("32 bit target"), "{no32}");
6300    }
6301
6302    /// `-gz` and the two spellings of the split, which are the two questions about the shape of
6303    /// the debug output rather than about how much of it there is.
6304    ///
6305    /// Both answers here are about what happens when there is debug information to shape, and
6306    /// there is none yet, so what is being asserted is that the flags are read and remembered
6307    /// rather than that anything changed in the output. That is the whole of what taking them
6308    /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
6309    /// it comes to find out what the command line said.
6310    #[test]
6311    fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
6312        let (opts, _) = compile(&["-c", "a.c"]);
6313        assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
6314
6315        // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
6316        // which describes the flag without ever saying which algorithm it picks.
6317        assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
6318        for (spelling, want) in [
6319            ("none", Compress::None),
6320            ("zlib", Compress::Zlib),
6321            ("zlib-gnu", Compress::ZlibGnu),
6322            ("zstd", Compress::Zstd),
6323        ] {
6324            let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
6325            assert_eq!(opts.compress, want, "{spelling}");
6326        }
6327
6328        // A value nothing here has heard of is refused rather than rounded to the nearest one,
6329        // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
6330        // reader may not understand and would have no way of finding out.
6331        for bad in ["-gz=gzip", "-gz="] {
6332            let failed = refused(&[bad, "-c", "a.c"]);
6333            assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
6334        }
6335
6336        // The split is refused in the direction that would have written a file and taken in the
6337        // direction that describes what happens. A build system that names the `.dwo` as an
6338        // output has to hear about it now rather than at the point the file is missing.
6339        let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
6340        assert!(opts.debug_info, "the negative spelling says nothing about how much");
6341        let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
6342        assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
6343    }
6344
6345    /// The `-flto` family, which is the whole of an optimization this compiler does not do.
6346    ///
6347    /// Taken rather than refused because ignoring it gives a correct program that is slower than
6348    /// it could have been, which is section 4.1's hint about speed. The values are still held to
6349    /// gcc's, so a command line written for clang is told rather than quietly taken.
6350    #[test]
6351    fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
6352        let (opts, _) = compile(&["-c", "a.c"]);
6353        assert!(!opts.lto.requested, "nothing asks unless the command line does");
6354
6355        let (opts, _) = compile(&["-flto", "-c", "a.c"]);
6356        assert!(opts.lto.requested);
6357        assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
6358
6359        // The last of the two directions wins, the same as every other pair of `-f` spellings.
6360        assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
6361        assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
6362
6363        // A count is a count, and asking for one implies asking for the optimization.
6364        for (spelling, want) in [
6365            ("auto", LtoJobs::Auto),
6366            ("jobserver", LtoJobs::Jobserver),
6367            ("1", LtoJobs::One),
6368            ("8", LtoJobs::Count(8)),
6369        ] {
6370            let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
6371            assert_eq!(opts.lto.jobs, want, "{spelling}");
6372            assert!(opts.lto.requested, "{spelling} asks for it too");
6373        }
6374
6375        // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
6376        // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
6377        // different compiler and gets told so here rather than getting a serial link.
6378        for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
6379            let failed = refused(&[bad, "-c", "a.c"]);
6380            assert!(failed.contains("link time jobs"), "{bad}: {failed}");
6381        }
6382
6383        // How the program is cut up before the work is spread over it.
6384        assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
6385        for (spelling, want) in [
6386            ("balanced", Partition::Balanced),
6387            ("1to1", Partition::OneToOne),
6388            ("one", Partition::One),
6389            ("max", Partition::Max),
6390            ("none", Partition::None),
6391        ] {
6392            let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
6393            assert_eq!(opts.lto.partition, want, "{spelling}");
6394        }
6395        assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
6396
6397        // And how hard the bytecode is compressed on its way into the object, which is zstd's
6398        // range of levels and is the range gcc checks an argument against.
6399        assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
6400        assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
6401        let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
6402        assert_eq!(opts.lto.compression, Some(19));
6403        for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
6404            let failed = refused(&[bad, "-c", "a.c"]);
6405            assert!(failed.contains("compression level"), "{bad}: {failed}");
6406        }
6407
6408        // The two pairs that describe an arrangement rather than ask for one. Every object here
6409        // holds its machine code, so the fat spelling is what already happens and the other is a
6410        // smaller file rather than a different program, and the plugin pair is about a tool the
6411        // design in `spec/09-optimizer.md` never loads.
6412        for taken in [
6413            "-ffat-lto-objects",
6414            "-fno-fat-lto-objects",
6415            "-fuse-linker-plugin",
6416            "-fno-use-linker-plugin",
6417        ] {
6418            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6419            assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
6420        }
6421    }
6422
6423    /// The profile family, which is the only one here that splits down the middle.
6424    ///
6425    /// Reading a profile is taken and writing one is refused, and the line between them is the one
6426    /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
6427    /// slower than it could have been, and ignoring a request to write them means a file the build
6428    /// declared as an output never appears.
6429    #[test]
6430    fn reading_a_profile_is_taken_and_writing_one_is_refused() {
6431        let (opts, _) = compile(&["-c", "a.c"]);
6432        assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
6433        assert_eq!(opts.profile_data.path, None);
6434
6435        let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
6436        assert!(opts.profile_data.requested);
6437        assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
6438
6439        let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
6440        assert!(opts.profile_data.requested, "naming a path asks for it too");
6441        assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
6442
6443        // The last of the two directions wins, the same as every other pair of `-f` spellings.
6444        assert!(
6445            !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
6446        );
6447        assert!(
6448            compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
6449        );
6450
6451        // The rest of the reading half, which is where the files are and three answers about what
6452        // to make of what is in them.
6453        let (opts, _) = compile(&[
6454            "-fprofile-dir=/build/profiles",
6455            "-fprofile-abs-path",
6456            "-fprofile-correction",
6457            "-fprofile-partial-training",
6458            "-c",
6459            "a.c",
6460        ]);
6461        assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
6462        assert!(opts.profile_data.absolute);
6463        assert!(opts.profile_data.correction);
6464        assert!(opts.profile_data.partial_training);
6465
6466        // Writing one, which is refused by name. The first four instrument the program and the
6467        // last writes a file beside the object, and a build that got neither and no message would
6468        // go on to optimize against counts that were never gathered.
6469        for writing in [
6470            "-fprofile-generate",
6471            "-fprofile-generate=/build/profiles",
6472            "-fprofile-arcs",
6473            "--coverage",
6474            "-fcondition-coverage",
6475            "-fpath-coverage",
6476        ] {
6477            let failed = refused(&[writing, "-c", "a.c"]);
6478            assert!(failed.contains("instrument"), "{writing}: {failed}");
6479        }
6480        assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
6481
6482        // The negative spellings of the refused half are what already happens, so they are taken.
6483        for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
6484            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6485            assert!(!opts.profile_data.requested, "{taken} asks for nothing");
6486        }
6487
6488        // And the flags that describe the instrumentation that is refused above, which are checked
6489        // and dropped. Checked because a typo is worth finding here rather than on the day the
6490        // instrumentation lands.
6491        for taken in [
6492            "-fprofile-update=single",
6493            "-fprofile-update=atomic",
6494            "-fprofile-update=prefer-atomic",
6495            "-fprofile-reproducible=serial",
6496            "-fprofile-reproducible=parallel-runs",
6497            "-fprofile-reproducible=multithreaded",
6498            "-fprofile-values",
6499            "-fno-profile-values",
6500            "-fprofile-info-section",
6501            "-fprofile-filter-files=a.c",
6502            "-fprofile-exclude-files=b.c",
6503            "-fprofile-note=a.gcno",
6504        ] {
6505            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6506            assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
6507        }
6508        assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
6509        assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
6510    }
6511
6512    /// The sanitizers, which are refused by name and are the one family refused for a reason that
6513    /// is not about the bytes.
6514    ///
6515    /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
6516    /// for one and was quietly given a program with no checks in it gets a test suite that passes
6517    /// for the wrong reason rather than a slower program.
6518    #[test]
6519    fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
6520        for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
6521            let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
6522            assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
6523            assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
6524        }
6525
6526        // A list is every name in it, and the first one still standing is the one named.
6527        let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
6528        assert!(failed.contains("address"), "{failed}");
6529
6530        // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
6531        // with a typo in it has a different problem from somebody who wrote a real one.
6532        for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
6533            let failed = refused(&[bad, "-c", "a.c"]);
6534            assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
6535        }
6536
6537        // gcc takes `all` only in the negative, and so does this.
6538        assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
6539
6540        // Asking and then taking it back is asking for nothing, which is why the answer waits for
6541        // the end of the line. A build whose shared flags turn a check on and whose rule for one
6542        // file turns it off again compiles that file here.
6543        for pair in [
6544            ["-fsanitize=address", "-fno-sanitize=address"],
6545            ["-fsanitize=address,undefined", "-fno-sanitize=all"],
6546            ["-fsanitize=undefined", "-fno-sanitize=undefined"],
6547        ] {
6548            let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
6549            assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
6550        }
6551        // And the other order still asks, because the last word is the one that counts.
6552        assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
6553
6554        // What a check does when it fires is an answer about checks that are refused, so there is
6555        // nothing left for it to change and it is taken.
6556        for taken in [
6557            "-fsanitize-recover=undefined",
6558            "-fno-sanitize-recover=all",
6559            "-fsanitize-trap=undefined",
6560            "-fno-sanitize-trap=all",
6561            "-fsanitize-undefined-trap-on-error",
6562            "-fsanitize-address-use-after-scope",
6563            "-fno-sanitize-address-use-after-scope",
6564            "-fsanitize-sections=.data",
6565        ] {
6566            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6567            assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
6568        }
6569        assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
6570
6571        // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
6572        // feedback runs blind and never says so.
6573        let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
6574        assert!(failed.contains("feedback"), "{failed}");
6575        let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
6576        assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
6577    }
6578
6579    #[test]
6580    fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
6581        assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6582        assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6583        assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
6584    }
6585
6586    #[test]
6587    fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
6588        let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
6589        let (opts, _) =
6590            compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
6591        assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
6592        let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
6593        assert!(wrong.contains("sysv convention"), "{wrong}");
6594    }
6595
6596    /// Whether a unit built with that command line has the extension called `name`.
6597    fn has(line: &[&str], name: &str) -> bool {
6598        let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6599        let (opts, _) = compile(&[&x86[..], line].concat());
6600        opts.isa.has(rucc_target::Feature::named(name).expect("a feature"))
6601    }
6602
6603    #[test]
6604    fn the_sse_flags_and_the_processor_levels_name_extensions() {
6605        // tamnd/rucc#2003. Every one of these was an unknown option before, and Postgres's
6606        // configure probe for the CRC-32C intrinsics is compiled with the first.
6607        assert!(has(&["-msse4.2"], "sse4.2") && has(&["-msse4.2"], "crc32"));
6608        assert!(has(&["-msse4.2"], "ssse3") && has(&["-msse4.2"], "popcnt"));
6609        assert!(!has(&[], "sse3") && !has(&[], "popcnt"));
6610        assert!(has(&["-mssse3"], "sse3") && !has(&["-mssse3"], "sse4.1"));
6611        assert!(has(&["-msse4"], "sse4.2") && !has(&["-msse4", "-mno-sse4"], "sse4.1"));
6612        assert!(has(&["-mpopcnt"], "popcnt") && !has(&["-mpopcnt"], "sse3"));
6613        assert!(has(&["-mcrc32"], "crc32"));
6614        assert!(has(&["-mxsave"], "xsave") && !has(&["-mxsave", "-mno-xsave"], "xsave"));
6615        assert!(!has(&["-msse4.2", "-mno-popcnt"], "popcnt"));
6616        // A processor supplies what no flag spoke for, whichever order they came in.
6617        assert!(has(&["-march=x86-64-v2"], "sse4.2"));
6618        assert!(!has(&["-march=x86-64-v2", "-mno-sse4.2"], "sse4.2"));
6619        assert!(!has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.2"));
6620        assert!(has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.1"));
6621        assert!(!has(&["-march=x86-64-v2", "-march=x86-64"], "sse3"));
6622        // One it has no list for is the baseline, as it was when all of them were.
6623        assert!(!has(&["-march=pentium-m"], "sse3"));
6624        assert!(has(&["-march=x86-64-v3"], "avx2"));
6625        // Turning off what is never on is nothing, and the flag is still gcc's.
6626        assert!(!has(&["-mno-avx512f"], "avx512f"));
6627    }
6628
6629    #[test]
6630    fn an_extension_this_compiler_cannot_provide_for_a_whole_unit_is_refused() {
6631        let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6632        let said = refused(&[&x86[..], &["-mavx2"]].concat());
6633        assert!(said.contains("no intrinsics for avx2"), "{said}");
6634        let said = refused(&[&x86[..], &["-mno-sse2"]].concat());
6635        assert!(said.contains("baseline"), "{said}");
6636        assert!(refused(&[&x86[..], &["-msse5"]].concat()).contains("unknown option"));
6637        // No other target has these, whichever side of the target the flag was written on.
6638        let said = refused(&["-msse4.2", "--target=aarch64-linux-gnu", "-c", "a.c"]);
6639        assert!(said.contains("unknown option `-msse4.2`"), "{said}");
6640        let (opts, _) = compile(&["--target=aarch64-linux-gnu", "-march=armv8-a+crc", "-c", "a.c"]);
6641        assert_eq!(opts.isa, rucc_target::Isa::NONE);
6642    }
6643
6644    #[test]
6645    fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
6646        let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
6647        assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
6648        // After the input, because a static link takes what it needs from a library when it
6649        // reaches it and not afterwards.
6650        let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
6651        assert_eq!(names, vec!["a.c"]);
6652    }
6653
6654    #[test]
6655    fn the_version_banner_keeps_our_first_line_and_takes_meson_down_the_gnu_path() {
6656        let text = banner();
6657        let mut lines = text.lines();
6658        // Every harness we have reads the first line and nothing else.
6659        assert_eq!(lines.next(), Some(format!("rucc {VERSION}").as_str()));
6660        // The words meson looks for, in `mesonbuild/compilers/detect.py`.
6661        assert!(text.contains("Free Software Foundation"), "{text}");
6662        // GCC's own banner has three lines and so does this one, and the claim is the dialect.
6663        assert!(lines.next().is_some_and(|l| l.contains("GCC 16")), "{text}");
6664        assert!(lines.next().is_some() && lines.next().is_none(), "{text}");
6665    }
6666
6667    #[test]
6668    fn the_questions_a_build_system_asks_before_it_compiles_anything() {
6669        let target = "--target=x86_64-unknown-linux-gnu";
6670        assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
6671        assert_eq!(printed(&[target, "-dumpversion"]), "16");
6672        assert_eq!(printed(&[target, "-dumpfullversion"]), "16.0.0");
6673        // They follow the release claimed, since that is the one `__GNUC__` says.
6674        assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpversion"]), "15");
6675        assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpfullversion"]), "15.2.0");
6676        assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
6677        // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
6678        // answer safe to paste into a link line whether or not the file is there.
6679        assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
6680        assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
6681        let dirs = printed(&[target, "-print-search-dirs"]);
6682        assert!(dirs.starts_with("install: "), "{dirs}");
6683        assert!(dirs.contains("\nlibraries: ="), "{dirs}");
6684    }
6685
6686    #[test]
6687    fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
6688        // A tree the user named is the answer whatever the target is, because it is the answer to
6689        // every other question too.
6690        assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
6691
6692        // A target that is no machine this suite runs on is read under the cache, and the answer is
6693        // the root rather than one of the directories under it, since what asks is looking for a
6694        // file of its own.
6695        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
6696        assert_eq!(
6697            printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
6698            root.display().to_string()
6699        );
6700
6701        // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
6702        // was configured without one rather than a `/` that would be a claim about the filesystem.
6703        // Except on Windows, which has no C library of its own and reads the fetched tree for its
6704        // own target as it would for any other.
6705        let host = Triple::host().expect("a host this compiler knows");
6706        let own = printed(&[&format!("--target={host}"), "-print-sysroot"]);
6707        if host.os == rucc_target::Os::Windows {
6708            let root = cache::dir().join("sysroots").join(host.tuple().to_string());
6709            assert_eq!(own, root.display().to_string());
6710        } else {
6711            assert_eq!(own, "");
6712        }
6713    }
6714
6715    #[test]
6716    fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
6717        // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
6718        // is the record that already has them, so the flag prints that rather than a second format.
6719        let manifest = "rucc sysroot manifest 3\n\
6720                        target\tx86_64-linux-musl\n\
6721                        kernel\t6.12\n\
6722                        include/generic/stdio.h\tmusl-1.2.5\t\
6723                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6724                        0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
6725                        bundled\n\
6726                        lib/libc.so\tmusl-1.2.5\t\
6727                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6728                        1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
6729                        generated\n";
6730        let tree = TempTree::new("provenance", &[("manifest", manifest)]);
6731        let sysroot = format!("--sysroot={}", tree.0.display());
6732        // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
6733        // the flag parses the record and renders it again rather than picking fields out of it. That
6734        // is the reason it prints a manifest and not a format of its own.
6735        //
6736        // The answer is the file without its last newline, because whatever prints it adds one. The
6737        // file is what somebody diffs the output against, so the two have to be the same bytes.
6738        assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
6739
6740        // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
6741        // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
6742        // tell it from a manifest with no inputs because that one still has its two header lines.
6743        let bare = TempTree::new("provenance-bare", &[]);
6744        assert_eq!(
6745            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
6746            ""
6747        );
6748
6749        // And a compile for this machine has no sysroot at all, which is the same empty answer
6750        // `-print-sysroot` gives for it.
6751        let host = Triple::host().expect("a host this compiler knows");
6752        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
6753
6754        // And the other spelling, which section 13.5 is the document that writes.
6755        assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
6756
6757        // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
6758        // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
6759        // the bytes it is over are the bytes of the file. The number here is that hash of the
6760        // fixture above, computed by `sha256sum` rather than by this compiler.
6761        assert_eq!(
6762            printed(&[&sysroot, "-print-sysroot-digest"]),
6763            "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
6764        );
6765        assert_eq!(
6766            printed(&[&sysroot, "--print-sysroot-digest"]),
6767            printed(&[&sysroot, "-print-sysroot-digest"])
6768        );
6769
6770        // And the two empty answers are empty here too, because a digest of nothing would read as a
6771        // claim about a sysroot rather than as the absence of one.
6772        assert_eq!(
6773            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
6774            ""
6775        );
6776        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
6777    }
6778
6779    #[test]
6780    fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
6781        // Passing a file we could not parse to whoever asked would make their parser the one that
6782        // finds the problem, and the three uses section 13.5 gives for this are all somebody else
6783        // parsing it.
6784        let tree = TempTree::new(
6785            "provenance-bad",
6786            &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
6787        );
6788        let message =
6789            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
6790        assert!(message.contains("manifest"), "{message}");
6791        assert!(message.contains("1 fields where an input has six"), "{message}");
6792
6793        // The digest is refused for the same file and for a stronger reason: a hash of bytes this
6794        // build cannot read would be a number that names a record nobody can act on.
6795        let digest =
6796            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
6797        assert_eq!(digest, message);
6798    }
6799
6800    #[test]
6801    fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
6802        let (opts, _) = compile(&["-M", "a.c"]);
6803        assert!(opts.deps.emit && opts.deps.instead_of_compiling);
6804        assert!(opts.deps.system_headers, "plain -M lists them");
6805        assert_eq!(opts.emit, EmitKind::Preprocessed);
6806
6807        // Even where a later flag asked for something else, because the family is a mode and
6808        // the mode is what the run is for.
6809        let (opts, _) = compile(&["-M", "-c", "a.c"]);
6810        assert_eq!(opts.emit, EmitKind::Preprocessed);
6811
6812        let (opts, _) = compile(&["-MM", "a.c"]);
6813        assert!(!opts.deps.system_headers);
6814    }
6815
6816    #[test]
6817    fn the_two_that_end_in_d_leave_the_compilation_alone() {
6818        let (opts, _) = compile(&["-MD", "-c", "a.c"]);
6819        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6820        assert!(opts.deps.system_headers);
6821        assert_eq!(opts.emit, EmitKind::Object);
6822
6823        let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
6824        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6825        assert!(!opts.deps.system_headers);
6826    }
6827
6828    #[test]
6829    fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
6830        // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
6831        // the answer, because the other one never asked the question.
6832        let (opts, _) = compile(&["-MM", "-M", "a.c"]);
6833        assert!(!opts.deps.system_headers);
6834        let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
6835        assert!(!opts.deps.system_headers);
6836        let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
6837        assert!(!opts.deps.system_headers);
6838    }
6839
6840    #[test]
6841    fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
6842        let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
6843        assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
6844    }
6845
6846    #[test]
6847    fn the_rest_of_the_family_is_a_file_and_a_switch() {
6848        let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
6849        assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
6850        assert!(opts.deps.phony);
6851
6852        for flag in ["-MF", "-MT", "-MQ"] {
6853            let e = parse_args(&args(&[flag])).unwrap_err();
6854            assert!(e.message.contains("requires an argument"), "{}", e.message);
6855        }
6856    }
6857
6858    /// Kbuild's spelling, which is how busybox and the kernel ask for every dependency file.
6859    #[test]
6860    fn a_dependency_file_asked_for_through_the_preprocessor_is_written_where_it_said() {
6861        let (opts, _) = compile(&["-Wp,-MD,applets/.applets.o.d", "-c", "a.c"]);
6862        assert!(opts.deps.emit);
6863        assert!(opts.deps.system_headers);
6864        assert_eq!(opts.deps.file.as_deref(), Some("applets/.applets.o.d"));
6865
6866        let (opts, _) = compile(&["-Wp,-MMD,x.d,-MP,-MT,x.o", "-c", "a.c"]);
6867        assert!(!opts.deps.system_headers);
6868        assert!(opts.deps.phony);
6869        assert_eq!(opts.deps.file.as_deref(), Some("x.d"));
6870        assert_eq!(opts.deps.targets, vec!["x.o".to_owned()]);
6871    }
6872
6873    #[test]
6874    fn a_preprocessor_flag_this_compiler_does_not_read_is_still_refused_whole() {
6875        assert!(refused(&["-Wp,-MD", "-c", "a.c"]).contains("separate assembler"));
6876        assert!(refused(&["-Wp,-MD,x.d,-C", "-c", "a.c"]).contains("-Wp,-MD,x.d,-C"));
6877    }
6878
6879    /// A directory of sources for one test, removed when the test is done with it.
6880    struct TempTree(PathBuf);
6881
6882    impl Drop for TempTree {
6883        fn drop(&mut self) {
6884            let _ = std::fs::remove_dir_all(&self.0);
6885        }
6886    }
6887
6888    impl TempTree {
6889        fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
6890            let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
6891            let _ = std::fs::remove_dir_all(&dir);
6892            std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
6893            for (path, text) in files {
6894                let at = dir.join(path);
6895                if let Some(parent) = at.parent() {
6896                    std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
6897                }
6898                std::fs::write(&at, text).expect("writing a temporary file should work");
6899            }
6900            TempTree(dir)
6901        }
6902
6903        fn path(&self, name: &str) -> String {
6904            self.0.join(name).to_string_lossy().into_owned()
6905        }
6906    }
6907
6908    #[test]
6909    fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
6910        // End to end, because the list comes from the preprocessor and the format comes from
6911        // somewhere else, and a test of either half on its own would pass with the two of them
6912        // wired up backwards.
6913        let tree = TempTree::new(
6914            "found",
6915            &[
6916                ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
6917                ("one.h", "#define X 0\n"),
6918                ("two.h", "#include \"one.h\"\n"),
6919            ],
6920        );
6921        let out = tree.path("dep.d");
6922        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6923        assert_eq!(code, 0);
6924
6925        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6926        let names: Vec<&str> = text.split_whitespace().collect();
6927        // The target, the source, and each header once however many times it was reached.
6928        assert_eq!(names.first(), Some(&"a.o:"), "{text}");
6929        assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
6930        assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
6931        // And the `-o` went to the file the rule replaced, which is left empty rather than
6932        // absent because a makefile that named it as a target will look for it.
6933        assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
6934    }
6935
6936    #[test]
6937    fn syntax_only_checks_the_file_and_writes_nothing() {
6938        // What meson's `has_header_symbol` probe does: compile with `-fsyntax-only` and read the
6939        // exit status. A good file passes and leaves no output behind, a bad one fails.
6940        let tree = TempTree::new(
6941            "syntax-only",
6942            &[
6943                ("good.c", "int f(int x) { return x + 1; }\n"),
6944                ("bad.c", "int f(void) { return y; }\n"),
6945            ],
6946        );
6947        let (opts, _) = compile(&["-fsyntax-only", "a.c"]);
6948        assert_eq!(opts.emit, EmitKind::SyntaxOnly);
6949
6950        let out = tree.path("good.o");
6951        assert_eq!(run(&args(&["-fsyntax-only", "-o", &out, &tree.path("good.c")])), 0);
6952        assert!(!std::path::Path::new(&out).exists(), "-fsyntax-only wrote {out}");
6953        assert!(!std::path::Path::new(&tree.path("good.s")).exists());
6954        assert_ne!(run(&args(&["-fsyntax-only", &tree.path("bad.c")])), 0);
6955    }
6956
6957    /// Where `-fstack-usage` puts each job's report, one entry per job, for a command line.
6958    fn stack_usage_files(line: &[&str]) -> Vec<Option<String>> {
6959        let mut words = vec![LINUX, "-fstack-usage"];
6960        words.extend_from_slice(line);
6961        let (_, plan) = compile(&words);
6962        plan.jobs.iter().map(|job| job.stack_usage.clone()).collect()
6963    }
6964
6965    #[test]
6966    fn a_stack_usage_file_is_named_the_way_gcc_names_it() {
6967        // Every row was run through gcc 16 with the same command line, and the name is the one it
6968        // wrote. `rpg frames` finds gcc's file and this compiler's by the same rule, so a name that
6969        // differs is a function that goes missing from the comparison.
6970        let cases: &[(&[&str], &[Option<&str>])] = &[
6971            (&["-c", "sub/a.c"], &[Some("a.su")]),
6972            (&["-c", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.su")]),
6973            (&["-c", "sub/a.c", "b.c"], &[Some("a.su"), Some("b.su")]),
6974            (&["-S", "sub/a.c", "-o", "out/y.s"], &[Some("out/y.su")]),
6975            (&["-S", "sub/a.c", "-o", "-"], &[Some("a.su")]),
6976            (&["-E", "sub/a.c", "-o", "out/z.i"], &[None]),
6977            (&["-fsyntax-only", "sub/a.c"], &[Some("a.su")]),
6978            (&["-fsyntax-only", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.o-a.su")]),
6979            (&["sub/a.c"], &[Some("a.su")]),
6980            (&["sub/a.c", "-lm"], &[Some("a.su")]),
6981            (&["sub/a.c", "b.c"], &[Some("a-a.su"), Some("a-b.su")]),
6982            (&["sub/a.c", "b.o"], &[Some("a-a.su"), None]),
6983            (&["sub/a.c", "-o", "out/prog"], &[Some("out/prog-a.su")]),
6984            (&["sub/a.c", "-o", "out/lib.so"], &[Some("out/lib.so-a.su")]),
6985            (&["sub/a.c", "-o", "out/prog.exe"], &[Some("out/prog-a.su")]),
6986            (&["sub/a.c", "-o", "out/prog", "-dumpbase", "zz"], &[Some("out/zz-a.su")]),
6987            (&["sub/a.c", "-o", "out/prog", "-dumpdir", "dd-"], &[Some("dd-a.su")]),
6988            (
6989                &["sub/a.c", "b.c", "-dumpdir", "dd/", "-dumpbase", "zz"],
6990                &[Some("dd/zz-a.su"), Some("dd/zz-b.su")],
6991            ),
6992            (&["-c", "sub/a.c", "-dumpbase", "foo", "-o", "out/w.o"], &[Some("out/foo.su")]),
6993            (&["-c", "sub/a.c", "-dumpdir", "dd/", "-dumpbase", "sub/zz"], &[Some("sub/zz.su")]),
6994            (&["-c", "sub/a.c", "-dumpbase", "zz.c", "-dumpbase-ext", ".c"], &[Some("zz.su")]),
6995            (&["-c", "sub/a.c", "-dumpdir", "pre", "-o", "out/x.o"], &[Some("prex.su")]),
6996            (&["-c", "sub/a.c", "-save-temps=cwd", "-o", "out/x.o"], &[Some("x.su")]),
6997        ];
6998        for (line, want) in cases {
6999            let want: Vec<Option<String>> = want.iter().map(|w| w.map(str::to_owned)).collect();
7000            assert_eq!(stack_usage_files(line), want, "{line:?}");
7001        }
7002        // Nothing at all without the flag.
7003        let (_, plan) = compile(&[LINUX, "-c", "sub/a.c"]);
7004        assert_eq!(plan.jobs[0].stack_usage, None);
7005    }
7006
7007    #[test]
7008    fn a_stack_usage_file_has_a_line_per_function_where_gcc_would_put_it() {
7009        let tree = TempTree::new(
7010            "stack-usage",
7011            &[
7012                ("inc/h.h", "static inline int twice(int x) { return x * 2; }\n"),
7013                (
7014                    "a.c",
7015                    "#include \"inc/h.h\"\n\
7016                     static int helper(int);\n\
7017                     int grows(int n) { char v[n]; v[0] = (char)n; return v[n - 1] + twice(n); }\n\
7018                     static int\n\
7019                     helper(int x)\n\
7020                     {\n\
7021                     return x + 1;\n\
7022                     }\n\
7023                     int calls(int x) { return helper(x) + grows(x); }\n",
7024                ),
7025            ],
7026        );
7027        let (source, object) = (tree.path("a.c"), tree.path("a.o"));
7028        assert_eq!(run(&args(&["-O0", "-fstack-usage", "-c", &source, "-o", &object])), 0);
7029        let text = std::fs::read_to_string(tree.path("a.su")).expect("a.su should be written");
7030
7031        let line = |function: &str| {
7032            let suffix = format!(":{function}");
7033            let line =
7034                text.lines().find(|line| line.split('\t').next().unwrap().ends_with(&suffix));
7035            line.unwrap_or_else(|| panic!("no line for {function} in\n{text}"))
7036        };
7037        let expect = |function: &str, at: String, qualifier: &str| {
7038            let fields: Vec<&str> = line(function).split('\t').collect();
7039            assert_eq!(fields.len(), 3, "{text}");
7040            assert_eq!(fields[0], format!("{at}:{function}"), "{text}");
7041            let bytes: u32 = fields[1].parse().expect("the bytes should be a number");
7042            assert!(bytes >= 8 && bytes % 8 == 0, "{function} takes {bytes} bytes");
7043            assert_eq!(fields[2], qualifier, "{text}");
7044        };
7045        // A variable length array makes the frame grow while the function runs.
7046        expect("grows", format!("{source}:3:5"), "dynamic");
7047        // The definition rather than the declaration above it, and the line the name is on
7048        // rather than the one the type is on.
7049        expect("helper", format!("{source}:5:1"), "static");
7050        expect("calls", format!("{source}:9:5"), "static");
7051        // A function from a header is reported against the header.
7052        expect("twice", format!("{}:1:19", tree.path("inc/h.h")), "static");
7053        assert_eq!(text.lines().count(), 4, "{text}");
7054    }
7055
7056    #[test]
7057    fn a_stack_usage_file_is_empty_when_there_is_nothing_to_report_and_absent_under_dash_e() {
7058        let tree = TempTree::new(
7059            "stack-usage-empty",
7060            &[
7061                ("good.c", "int f(int x) { return x + 1; }\n"),
7062                ("bad.c", "int f(void) { return y; }\n"),
7063            ],
7064        );
7065        let good = tree.path("good.c");
7066        // gcc writes an empty file for a check that compiles nothing and for a file that failed,
7067        // and a build that looks for one beside every object finds one.
7068        assert_eq!(
7069            run(&args(&["-fstack-usage", "-fsyntax-only", &good, "-o", &tree.path("x")])),
7070            0
7071        );
7072        assert_eq!(std::fs::read_to_string(tree.path("x-good.su")).unwrap(), "");
7073        let bad = tree.path("bad.c");
7074        assert_ne!(run(&args(&["-fstack-usage", "-c", &bad, "-o", &tree.path("bad.o")])), 0);
7075        assert_eq!(std::fs::read_to_string(tree.path("bad.su")).unwrap(), "");
7076        // And none under `-E`, which never reaches a function.
7077        assert_eq!(run(&args(&["-fstack-usage", "-E", &good, "-o", &tree.path("e.i")])), 0);
7078        assert!(!std::path::Path::new(&tree.path("e.su")).exists());
7079    }
7080
7081    #[test]
7082    fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
7083        // The multiple-include optimization means the second reach never opens the file. It is
7084        // still a file this translation unit was built from, so it is still in the rule.
7085        let tree = TempTree::new(
7086            "guarded",
7087            &[
7088                ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
7089                ("g.h", "#ifndef G\n#define G\n#endif\n"),
7090            ],
7091        );
7092        let out = tree.path("dep.d");
7093        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
7094        assert_eq!(code, 0);
7095        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
7096        assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
7097    }
7098
7099    #[test]
7100    fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
7101        // Measured against GCC rather than read: the two flags the other way round produce the
7102        // same output byte for byte, so the command line order between the two families does not
7103        // decide anything and the order within one does. The `-include` file here can only see
7104        // the definition if the `-imacros` file that was written after it ran first.
7105        let tree = TempTree::new(
7106            "preinclude",
7107            &[
7108                ("a.c", "int main(void) { return 0; }\n"),
7109                ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
7110                ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
7111            ],
7112        );
7113        let out = tree.path("a.i");
7114        let code = run(&args(&[
7115            "-E",
7116            "-include",
7117            &tree.path("i.h"),
7118            "-imacros",
7119            &tree.path("m.h"),
7120            "-o",
7121            &out,
7122            &tree.path("a.c"),
7123        ]));
7124        assert_eq!(code, 0);
7125        let text = std::fs::read_to_string(&out).expect("the output should have been written");
7126        assert!(text.contains("saw_it"), "{text}");
7127        // And the text of the `-imacros` file is thrown away, which is the whole difference
7128        // between the two flags.
7129        assert!(!text.contains("macros_text"), "{text}");
7130    }
7131
7132    #[test]
7133    fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
7134        let tree = TempTree::new(
7135            "preinclude-deps",
7136            &[
7137                ("a.c", "int main(void) { return 0; }\n"),
7138                ("i.h", "int from_include;\n"),
7139                ("m.h", "#define M 1\n"),
7140            ],
7141        );
7142        let out = tree.path("dep.d");
7143        let code = run(&args(&[
7144            "-MM",
7145            "-MF",
7146            &out,
7147            "-include",
7148            &tree.path("i.h"),
7149            "-imacros",
7150            &tree.path("m.h"),
7151            "-o",
7152            &tree.path("a.i"),
7153            &tree.path("a.c"),
7154        ]));
7155        assert_eq!(code, 0);
7156        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
7157        assert!(text.contains("i.h"), "{text}");
7158        assert!(text.contains("m.h"), "{text}");
7159    }
7160
7161    #[test]
7162    fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
7163        // Including the directory of the source file, which is not on the path for these: the
7164        // command line was not written there, so a name in it is relative to where the compiler
7165        // was run rather than to where the source sits.
7166        let tree = TempTree::new(
7167            "preinclude-missing",
7168            &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
7169        );
7170        let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
7171        assert_eq!(code, 1);
7172    }
7173
7174    #[test]
7175    fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
7176        // The object a link goes through is in a temporary directory and is gone before `make`
7177        // reads any of this, so the rule that named it would be a rule for a file that is never
7178        // there. The target and the file are both the `-o`, which is the executable.
7179        let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
7180        assert_eq!(plan.output.as_deref(), Some("prog"));
7181        assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
7182        assert_eq!(
7183            deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
7184            Some("prog.d")
7185        );
7186    }
7187
7188    #[test]
7189    fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
7190        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
7191        assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
7192        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
7193        assert_eq!(plan.output, None);
7194    }
7195
7196    #[test]
7197    fn usage_fits_on_a_screen() {
7198        // Not a style preference. A help text that scrolls is one nobody reads, and this is
7199        // the cheapest way to keep it honest as flags accumulate. The number goes up only when
7200        // a family of flags arrives that has nowhere to share a line, which the two pass gates
7201        // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
7202        // the lines that family took. The four it went up by last are the flags a build system
7203        // passes without being asked to: how much to say, what machine to generate for, threads,
7204        // and the questions `configure` asks before it compiles anything. The one it went up by
7205        // last is the second line of `--emit`, whose kinds are a family that has now outgrown
7206        // one line and has nowhere else to go. The two it went up by last are the dependency
7207        // family, which is eight flags that share nothing with anything above them. The one it
7208        // went up by last is the four spellings of position independent code, which every
7209        // configure script writes and which could only have shared the link line, and that line
7210        // is already four characters short of the limit. The two it went up by last are the rest
7211        // of the include family, which is six more flags that change where a header is looked for
7212        // and two that name a header outright. The one it went up by last is the pair that keeps
7213        // the intermediate files and times the steps, which belong next to the two flags above
7214        // them that are also about watching a compilation rather than changing one. The two it
7215        // went up by last are the section flags and the visibility flag, which are what a build
7216        // that cares about the size of what it ships and about which names it exports writes, and
7217        // the second of them was already taken and only missing from here. The one it went up by
7218        // last is the stack protector, which is four spellings of one question and which every
7219        // distribution puts on every command line it issues, so a build that reads this list
7220        // looking for it and does not find it has to go and read the specification instead. The one
7221        // it went up by last is the profiler, which is two spellings of the request and two of
7222        // where the call goes, and which is about watching a program run rather than about what is
7223        // generated, so it shares its subject with nothing above it. The one it went up by last is
7224        // the room a function opens with for something to be written over it later, which takes an
7225        // argument of its own shape and is what a kernel build asks for, so it fits beside the
7226        // profiler and nothing else. The one it went up by last is what overflows rather than being
7227        // undefined, which is three spellings of two questions and which a kernel build and a great
7228        // deal of code written before the standard settled both pass. The one it went up by last is
7229        // the other answer to the first of those questions, which could not share the line because
7230        // what it asks for is the opposite of what the flags on that line ask for. The one it went
7231        // up by last is the split of the line that lists what this compiler does anyway into that
7232        // and what it assumes anyway, which are two different claims that were sharing a line until
7233        // the second of them got a second flag and the line stopped fitting. The one it went up by
7234        // last is the three flags that change the ABI rather than the code, which have to be given
7235        // to every file in a program or none of them and which therefore belong somewhere a person
7236        // reading this list will see them. The one it went up by last is the floating point group,
7237        // which is two lines rather than one because the first of them is a choice this compiler
7238        // records and the rest are claims about what it does anyway, and putting a real setting on
7239        // the same line as three flags that change nothing would be misleading about both. The one
7240        // it went up by last is the flag that says a write has to stay inside the member it names,
7241        // which is a setting rather than a claim and so cannot share the line above it, that being
7242        // the one that picks a tier. The two it went up by last are the prefix mapping family,
7243        // which is four flags whose whole job is to keep a build's output the same from two
7244        // different directories, and which a person chasing a reproducible build comes here
7245        // looking for by name. The one it went up by last is how the debug sections are compressed
7246        // and whether they go in a file of their own, which are two questions about the shape of
7247        // the debug output, where the line above them is about how much of it there is. The one it
7248        // went up by last is the `restrict` contract, which is a setting for the same reason the
7249        // flag that keeps a write inside its member is and which is the check a person who has been
7250        // bitten by a vectorizer comes here looking for. The one it went up by last is link time
7251        // optimization, which is a whole optimization rather than a flag and which says so on its
7252        // own line, because a build that passes it and reads this looking for what it got is
7253        // asking a question no other line here answers. The one it went up by last is the sysroot,
7254        // which is the question somebody asks when a cross build read a file nobody expected, and
7255        // which has no room on the line above it because the answers there are a path each and this
7256        // one is the root all of them are under. The one it went up by last is what is inside that
7257        // root and where each of it came from, which is a question about a whole tree rather than
7258        // about a path and which is long enough on its own that it could not have shared a line with
7259        // anything. The one it went up by last is the profile family, which splits down the middle
7260        // where no other family here does, so the line has to name the half that is taken and the
7261        // half that is refused or it would be read as taking both. The one it went up by last is
7262        // the sanitizers, which are what somebody reaching for a checked build writes first and
7263        // which belong beside the tier that is the nearest thing here to what they asked for. The
7264        // one it went up by last is the digest of that record, which is the same tree as one number
7265        // and could not share the line above it because that line prints a few hundred lines and
7266        // this one prints sixty four characters, and a reader who wants the short answer is looking
7267        // for it by name rather than reading the long one. The one it went up by last is the
7268        // sysroot fetch, which is the only command here that gets something from somewhere else and
7269        // is therefore the one a person wants to have read before they run it rather than after.
7270        // And the flag beside it that forbids every download, which earns its line by being what a
7271        // build in a sealed environment passes and by meaning something even though an ordinary
7272        // compile downloads nothing either way. The one it went up by last is the other fetch, the
7273        // one behind Microsoft's licence wall, which is a line rather than a paragraph because what
7274        // a person needs from here is that the command exists and that it will not do anything
7275        // until they have read a licence it prints for them.
7276        assert!(USAGE.lines().count() < 73, "usage text has grown past one screen");
7277    }
7278}