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.16.1")]
30
31pub mod assemble;
32pub mod cache;
33pub mod compile;
34pub mod deps;
35pub mod dlltool;
36pub mod fetch;
37mod glibc;
38pub mod install;
39pub mod library;
40pub mod link;
41mod map;
42pub mod msvc;
43pub mod phase;
44pub mod preprocess;
45pub mod schedule;
46mod shapes;
47pub mod trace;
48mod warnings;
49
50use std::fmt::Write as _;
51use std::io::Write as _;
52use std::path::PathBuf;
53
54use rucc_codegen::coverage::{self, Fired};
55use rucc_codegen::lowering::Lowerings;
56use rucc_codegen::pressure::Pressure;
57use rucc_pp::Dependency;
58use rucc_session::{
59    Compress, Control, Dumps, EmitKind, Hook, Math, Options, Pic, PrefixMap, Preinclude, Protector,
60    SaveTemps, Session, Std, Wrapping, runtime,
61};
62use rucc_sysroot::{Manifest, Sysroot};
63use rucc_target::{ObjectFormat, Triple};
64use rucc_tuple::TargetTuple;
65
66use crate::link::LinkOptions;
67
68pub use crate::assemble::assemble;
69pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
70pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan, Role};
71pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
72pub use crate::schedule::Jobs;
73
74/// The compiler's version, taken from the workspace manifest.
75pub const VERSION: &str = env!("CARGO_PKG_VERSION");
76
77/// What the command line asked for.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum Action {
80    /// Print usage and exit successfully.
81    Help,
82    /// Print the version and exit successfully.
83    Version,
84    /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
85    ///
86    /// A build system asks these before it compiles anything, and what it does with the answer
87    /// is paste it into a path or into another command line, so each one is a single line with
88    /// no decoration around it.
89    Print(String),
90    /// Print the resolved configuration and exit successfully.
91    PrintConfig(Box<Options>),
92    /// Print the passes the level will run and exit successfully.
93    PrintPipeline(Box<Options>),
94    /// Print the phase plan and the link line and exit successfully, which is `-###`.
95    PrintPlan {
96        /// The resolved options, which is what says what the link line is for.
97        opts: Box<Options>,
98        /// What to do to each input, and in what order.
99        plan: Box<Plan>,
100        /// What the command line said about linking.
101        link: Box<LinkOptions>,
102    },
103    /// `--fetch <tuple>`, which gets the sysroot this release pins for a target and installs it.
104    ///
105    /// The only action in this compiler that may run another program to move bytes onto the
106    /// machine, which is `spec/cross-compile/13-distribution.md` section 13.8's rule rather than a
107    /// property of how this happens to be written: a compilation has no branch that reaches it.
108    Fetch {
109        /// The artifact, from the table in [`rucc_sysroot::artifact`]. Resolved here rather than where the
110        /// work happens, so that a target nothing is pinned for is a refusal from the parser like
111        /// every other thing a command line can ask for and not have.
112        what: &'static rucc_sysroot::Pinned,
113        /// The target, which names the directory under the cache the tree is installed at and is
114        /// checked against the record inside the artifact.
115        target: TargetTuple,
116        /// Where the cache is, read where everything else that needs it reads it.
117        cache: PathBuf,
118    },
119    /// `--fetch-msvc-sdk <tuple>`, which gets what is behind Microsoft's licence wall.
120    ///
121    /// The other action that may run another program to move bytes onto the machine, and the only
122    /// one that asks a person to accept somebody else's licence first.
123    /// `spec/cross-compile/13-distribution.md` section 13.4 is why no release pins an artifact
124    /// for these, and nothing about this may ever happen because a compile wanted it to. `--fetch`
125    /// of an MSVC target is this action too, starting from the build this release pins rather than
126    /// from the one Microsoft's channel names today.
127    FetchMsvcSdk {
128        /// The target, which says which architecture's CRT library package is wanted.
129        target: TargetTuple,
130        /// Whether `--accept-licence` was on the command line. Without it the licence and the list
131        /// are printed and nothing is downloaded, which is the whole of what the flag is for.
132        accepted: bool,
133        /// Where the cache is, read where everything else that needs it reads it.
134        cache: PathBuf,
135        /// Whether the documents at the top of the chain are [`rucc_sysroot::PINNED_BUILD`]'s,
136        /// which is `--fetch`, rather than the current channel's, which is `--fetch-msvc-sdk`.
137        pinned: bool,
138    },
139    /// Compile the given inputs.
140    Compile {
141        /// The resolved options.
142        opts: Box<Options>,
143        /// What to do to each input, and in what order.
144        plan: Box<Plan>,
145        /// What the command line said about linking.
146        link: Box<LinkOptions>,
147        /// How many translation units to compile at once.
148        jobs: Jobs,
149        /// Whether `-v` asked for the plan to be printed while it runs.
150        verbose: bool,
151        /// What is worth saying about the command line before anything is compiled, printed as
152        /// warnings and once for the whole run rather than once per file.
153        ///
154        /// These are not diagnostics. A diagnostic is about a piece of source and has a span to
155        /// point at, and these are about the way two flags were combined, so there is nothing to
156        /// point at and nowhere below the driver that knows both halves. `-w` does not reach them
157        /// for the same reason it does not reach a refusal from the parser.
158        notes: Vec<String>,
159    },
160}
161
162/// Why a command line was rejected.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct CliError {
165    /// The message, lowercase and without a trailing period, in the same shape as any other
166    /// diagnostic.
167    pub message: String,
168}
169
170impl std::fmt::Display for CliError {
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        f.write_str(&self.message)
173    }
174}
175
176impl std::error::Error for CliError {}
177
178fn err(message: impl Into<String>) -> CliError {
179    CliError { message: message.into() }
180}
181
182/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
183///
184/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
185/// the only one that lets a directory whose name contains an `=` be the old half. It also means
186/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
187/// trap until you notice the alternative traps the far more common case.
188fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
189    let rest = &arg[flag.len()..];
190    PrefixMap::split(rest).ok_or_else(|| {
191        let flag = flag.trim_end_matches('=');
192        err(format!(
193            "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
194        ))
195    })
196}
197
198/// A question the command line asked instead of asking for a compilation.
199///
200/// These are answered after the loop rather than where they are read, because every one of them
201/// is about the target or about the library search and the last word on both is the end of the
202/// command line.
203enum Query {
204    /// `-dumpmachine`, the triple.
205    Machine,
206    /// `-dumpversion`, the major number of the GCC release this compiler claims to be.
207    Version,
208    /// `-dumpfullversion`, the same release in all three numbers.
209    FullVersion,
210    /// `-print-multiarch`, the directory name a distribution files this target under.
211    Multiarch,
212    /// `-print-search-dirs`, in the three lines GCC prints.
213    SearchDirs,
214    /// `-print-sysroot`, the root the headers and the libraries are read under.
215    Sysroot,
216    /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
217    SysrootProvenance,
218    /// `-print-sysroot-digest`, the one number that names all of it.
219    SysrootDigest,
220    /// `-print-file-name=<name>`, the full path of a library file.
221    FileName(String),
222    /// `-print-prog-name=<name>`, the full path of a program.
223    ProgName(String),
224    /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
225    Libgcc,
226}
227
228/// Usage text.
229///
230/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
231/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
232pub const USAGE: &str = "\
233rucc, an optimizing C compiler
234
235usage: rucc [options] file...
236
237options:
238  -c                     compile and assemble, do not link
239  -S                     compile only, emit assembly
240  -E                     preprocess only
241  -o <file>              write output to <file>, or to standard output for -
242  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
243  -I <dir>               add <dir> to the include search path
244  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
245  -I-, -iprefix <p>, -iwithprefix[before] <dir>   the older spellings of those
246  -include <file>, -imacros <file>    read <file> first, the second for its macros only
247  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
248  -P, -dM                with -E: leave out the markers, or dump the macros
249  -M -MM -MD -MMD        write a make rule for the source, the last two compile as well
250  -MF <file> -MT <t> -MQ <t> -MP   where the rule goes, what it builds, targets with no recipe
251  -std=<dialect>         c89 through c2y, and the gnu spellings
252  -fgnuc-version=<v> -fms-compatibility-version=<v>   the GCC (16.0.0) or MSVC (19.40) to claim
253  -x <lang>              treat later inputs as <lang>, or none to stop
254  -O<level>              optimize: 0, 1, 2, 3, s, z, fast
255  -fsafety=<tier>        check memory safety: off, detect, enforce, kernel
256  -f[no-]sanitize=<what>   the negative is taken, the positive is refused by name
257  -f[no-]safety-subobject   a write has to stay inside the member it names
258  -f[no-]safety-restrict    two restrict pointers of one block may not meet
259  -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
260  -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n>   stop a pass, or all of them, after n
261  -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>]   run a pass on some functions only
262  -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone   debug info, frame pointer, red zone
263  -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf   compress debug sections, one file not two
264  -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects   read, and not done yet
265  -fprofile-use[=<path>] -fprofile-dir=<dir>   read too, where -fprofile-generate is refused
266  -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
267  -ffunction-sections -fdata-sections   a section per function or variable, for --gc-sections
268  -fvisibility=<what>    default, hidden, internal or protected, when nothing in the source said
269  -l<name>, -L <dir>, -B <dir>   link a library, where to look for one, where our own tools are
270  -fPIC -fpic -fPIE -fpie, -pipe   what it does anyway, and -f[no-]common as the target's cc
271  -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks   what it assumes anyway
272  -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s   how to link
273  -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name>   hand an argument to the linker, or pick one
274  -Werror -pedantic -pedantic-errors -w -W[no-]system-headers   how much to say, and how fatal
275  -m64 -march= -mtune= -mcpu= -mabi= -mcmodel=   what machine to generate for
276  -pg -p, -mfentry -mno-fentry   call a profiler on the way in, and where that call goes
277  -fpatchable-function-entry=<n>[,<m>]   room at the top of every function to patch later
278  -fwrapv, -fwrapv-pointer, -fno-strict-overflow, -ftrapv   overflow wraps, or stops the program
279  -f[no-]exceptions, -f[no-]non-call-exceptions   let an exception unwind through the code
280  -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums   change the ABI
281  -ffp-contract=<how>    fuse a multiply and an addition: fast, on or off
282  -f[no-]fast-math and each of its members, -f[no-]rounding-math, -fexcess-precision=<how>
283  -ffile-prefix-map=<old>=<new>   rewrite that front of every path we put in the output
284  -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map=   the same, one output each
285  -pthread               build for more than one thread, and link the library for it
286  -dumpmachine -dumpversion -print-multiarch -print-search-dirs   what this compiler is
287  -print-file-name=<name> -print-prog-name=<name>   where a file or a program is
288  -print-sysroot         the root the headers and the libraries are read under
289  -print-sysroot-provenance   every input under it, where it came from and its licence
290  -print-sysroot-digest   the sha256 of that record, which names the whole sysroot in one line
291  --fetch <tuple>        get the sysroot this release pins for <tuple> and install it in the cache
292  --fetch-msvc-sdk <tuple>   the same for *-windows-msvc, from Microsoft's current build
293  --offline              never download anything, which a compilation never does anyway
294  --dlltool <args>       write an import library from a .def, as dlltool; --dlltool --help says how
295  -j[n]                  compile n translation units at once, default all
296  -v, -###               print each phase as it runs, or without running any
297  -save-temps[=cwd|obj], -fstack-usage, -time   keep the .i and .s, write a .su, time each step
298  --target=<triple>      generate code for <triple>, which a name like <triple>-rucc also does
299  --emit=<kind>          exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
300                         safety-summary, type-granules
301  --print-config, --print-pipeline    print the configuration or the pipeline, and exit
302  --version              print the version and exit
303  -h, --help             print this message and exit
304
305See spec/04-driver-and-cli.md for the full flag reference.
306";
307
308/// The argument of a flag that may be joined to it or may be the next word.
309///
310/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
311fn joined_or_next(
312    arg: &str,
313    at: usize,
314    args: &[String],
315    i: &mut usize,
316) -> Result<String, CliError> {
317    if arg.len() > at {
318        return Ok(arg[at..].to_owned());
319    }
320    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
321    *i += 1;
322    Ok(next.clone())
323}
324
325/// The smallest boundary a function is put on when the command line asked for no alignment at all.
326///
327/// Eight bytes, which is what gcc 16 gives `-fno-align-functions` on x86-64 and is a boundary every
328/// target this compiler has is happy with. It is not zero: a function still has to start somewhere
329/// an instruction may start, and the flag asks for the target's minimum rather than for none.
330const MIN_FUNC_ALIGN: u32 = 8;
331
332/// What `-falign-functions=N` asks for, as a power of two, or `None` for the target's own answer.
333///
334/// Zero and one both mean the default, which is gcc's reading of them, and everything else is
335/// rounded up to the next power of two, which is also gcc's: `-falign-functions=3` puts a function
336/// on a four byte boundary rather than being refused. Gives back `Err` shaped as an outer `None`
337/// only when the text is not a number, since that is the one thing gcc will not read either. A
338/// number larger than any alignment makes sense at is clamped rather than refused, for the same
339/// reason: this is a preference about speed and a build that wrote a silly one still deserves to
340/// compile.
341fn function_alignment(text: &str) -> Option<Option<u32>> {
342    // gcc takes `N:M:N2:M2`, where everything after the first number is about how far it is willing
343    // to go to reach the boundary. Only the boundary is answerable here, so the rest is read to
344    // check that it is numbers and then dropped.
345    let mut parts = text.split(':');
346    let first = parts.next()?;
347    if parts.any(|part| part.parse::<u64>().is_err()) {
348        return None;
349    }
350    let want: u64 = first.parse().ok()?;
351    if want <= 1 {
352        return Some(None);
353    }
354    let bytes = want.min(1 << 16).next_power_of_two();
355    Some(Some(u32::try_from(bytes).ok()?))
356}
357
358/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
359/// own.
360///
361/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
362/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
363/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
364/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
365/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
366/// because none of them is implemented.
367///
368/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
369/// those two spellings is read rather than by being on this list.
370const SANITIZERS: [&str; 34] = [
371    "address",
372    "kernel-address",
373    "hwaddress",
374    "kernel-hwaddress",
375    "pointer-compare",
376    "pointer-subtract",
377    "thread",
378    "leak",
379    "undefined",
380    "shift",
381    "shift-base",
382    "shift-exponent",
383    "integer-divide-by-zero",
384    "unreachable",
385    "vla-bound",
386    "null",
387    "return",
388    "signed-integer-overflow",
389    "bounds",
390    "bounds-strict",
391    "alignment",
392    "object-size",
393    "float-divide-by-zero",
394    "float-cast-overflow",
395    "nonnull-attribute",
396    "returns-nonnull-attribute",
397    "bool",
398    "enum",
399    "vptr",
400    "pointer-overflow",
401    "builtin",
402    "alias",
403    "restrict",
404    "memory",
405];
406
407/// The command line with every `@file` replaced by the words in the file, the way gcc does it.
408///
409/// Meson writes the link of a large target this way, so that a command line holding a thousand
410/// objects stays under the limit the system puts on one. Postgres's `postgres` executable is the
411/// one link in its tree that meson writes as `@postgres.rsp`, and before this the name went to
412/// the linker as it was. GNU ld reads response files itself, so it opened the file and found
413/// `-Wl,--as-needed` in it, which is a driver flag it has never heard of.
414///
415/// The rules are libiberty's `expandargv`, since that is what gcc and every other GNU tool read
416/// these files with. Words are split on white space, a single or a double quote keeps white
417/// space in a word until the matching quote, and a backslash makes the character after it an
418/// ordinary one, inside quotes as well as outside. A word the file gives that starts with `@` is
419/// read as a response file in turn. A name that cannot be opened is left on the command line as
420/// it was, which is what gcc does and which is how a file really called `@x.c` still reaches the
421/// loop, where it is refused as an unknown input rather than swallowed. The depth is capped so a
422/// file that names itself is an error and not a hang.
423fn response_files(args: &[String]) -> Result<Vec<String>, CliError> {
424    const DEEPEST: usize = 64;
425    fn expand(args: &[String], depth: usize, out: &mut Vec<String>) -> Result<(), CliError> {
426        for arg in args {
427            let Some(name) = arg.strip_prefix('@') else {
428                out.push(arg.clone());
429                continue;
430            };
431            let Ok(text) = std::fs::read_to_string(name) else {
432                out.push(arg.clone());
433                continue;
434            };
435            if depth == DEEPEST {
436                return Err(err(format!("response file '{name}' is nested too deeply")));
437            }
438            expand(&response_words(&text), depth + 1, out)?;
439        }
440        Ok(())
441    }
442    if !args.iter().any(|arg| arg.starts_with('@')) {
443        return Ok(args.to_vec());
444    }
445    let mut out = Vec::with_capacity(args.len());
446    expand(args, 0, &mut out)?;
447    Ok(out)
448}
449
450/// The words of one response file, split the way libiberty's `buildargv` splits them.
451fn response_words(text: &str) -> Vec<String> {
452    let mut words = Vec::new();
453    let mut word = String::new();
454    // Whether a word has begun, which is not the same as `word` having something in it: `''` is
455    // an empty word of its own and has to reach the command line as one.
456    let mut begun = false;
457    let mut quote: Option<char> = None;
458    let mut chars = text.chars();
459    while let Some(c) = chars.next() {
460        match c {
461            '\\' => {
462                if let Some(next) = chars.next() {
463                    word.push(next);
464                }
465                begun = true;
466            }
467            _ if quote == Some(c) => quote = None,
468            _ if quote.is_some() => word.push(c),
469            '\'' | '"' => {
470                quote = Some(c);
471                begun = true;
472            }
473            _ if c.is_whitespace() => {
474                if begun {
475                    words.push(std::mem::take(&mut word));
476                    begun = false;
477                }
478            }
479            _ => {
480                word.push(c);
481                begun = true;
482            }
483        }
484    }
485    if begun {
486        words.push(word);
487    }
488    words
489}
490
491/// The command line with every `-Wp,` this compiler understands spelled as its own flags.
492///
493/// The preprocessor is inside this compiler, so what a build hands it through `-Wp,` has to be
494/// read here. Kbuild is the reason: every object in the Linux kernel and in busybox is compiled
495/// with `-Wp,-MD,dir/.name.o.d`, which is cpp's spelling of `-MD -MF dir/.name.o.d`. cpp's `-MD`
496/// and `-MMD` take the file as their next word where the driver's do not, and the rest are the
497/// same flags in both. A `-Wp,` holding anything else is left as it was so the loop refuses it,
498/// because dropping part of what a build asked the preprocessor for would be the silent kind of
499/// wrong.
500fn preprocessor_args(args: &[String]) -> Vec<String> {
501    let mut out = Vec::with_capacity(args.len());
502    for arg in args {
503        let Some(list) = arg.strip_prefix("-Wp,") else {
504            out.push(arg.clone());
505            continue;
506        };
507        let words: Vec<&str> = list.split(',').collect();
508        let mut spelled = Vec::new();
509        let mut i = 0;
510        let understood = loop {
511            let Some(&word) = words.get(i) else {
512                break true;
513            };
514            i += 1;
515            match word {
516                "-MD" | "-MMD" | "-MF" | "-MT" | "-MQ" => {
517                    let Some(&value) = words.get(i) else {
518                        break false;
519                    };
520                    i += 1;
521                    if word == "-MD" || word == "-MMD" {
522                        spelled.extend([word.to_owned(), "-MF".to_owned()]);
523                    } else {
524                        spelled.push(word.to_owned());
525                    }
526                    spelled.push(value.to_owned());
527                }
528                "-MP" => spelled.push(word.to_owned()),
529                _ if word.len() > 2
530                    && (word.starts_with("-D")
531                        || word.starts_with("-U")
532                        || word.starts_with("-I")) =>
533                {
534                    spelled.push(word.to_owned());
535                }
536                _ => break false,
537            }
538        };
539        if understood {
540            out.extend(spelled);
541        } else {
542            out.push(arg.clone());
543        }
544    }
545    out
546}
547
548/// The extension a `-m` flag names and whether it turns it on, when it names one.
549///
550/// `-mno-` is the off form of every one of them, which is also how gcc spells it. A flag that is
551/// not an extension, `-mno-red-zone` say, is `None` and is left to the rest of the parser.
552fn isa_name(arg: &str) -> Option<(&str, rucc_target::Feature, bool)> {
553    let rest = arg.strip_prefix("-m")?;
554    let (name, on) = match rest.strip_prefix("no-") {
555        Some(name) => (name, false),
556        None => (rest, true),
557    };
558    let known =
559        if on { rucc_target::Feature::named(name) } else { rucc_target::Feature::named_off(name) };
560    known.map(|feature| (name, feature, on))
561}
562
563/// The extensions the machine running the compiler has, which is what `-march=native` means.
564///
565/// Asked of the processor with `cpuid`, through the standard library, and only when the compiler
566/// is running on an x86-64 at all. Anywhere else there is no processor to ask about an x86-64 one,
567/// and gcc on such a machine builds for the baseline, which is what this does. The list is the
568/// extensions whose names are stable in the standard library at this workspace's minimum Rust
569/// version, which covers everything [`rucc_target::Feature::honoured`] says yes to and a good deal
570/// that it does not.
571fn native_isa() -> rucc_target::Isa {
572    let base = rucc_target::Isa::baseline();
573    #[cfg(target_arch = "x86_64")]
574    {
575        let mut isa = rucc_target::Choices::new();
576        macro_rules! asked {
577            ($($detected:tt => $name:literal),* $(,)?) => {
578                $(if std::arch::is_x86_feature_detected!($detected) {
579                    isa.read($name).expect("a name gcc knows");
580                })*
581            };
582        }
583        asked! {
584            "sse3" => "sse3",
585            "ssse3" => "ssse3",
586            "sse4.1" => "sse4.1",
587            "sse4.2" => "sse4.2",
588            "sse4a" => "sse4a",
589            "popcnt" => "popcnt",
590            "avx" => "avx",
591            "avx2" => "avx2",
592            "fma" => "fma",
593            "f16c" => "f16c",
594            "bmi1" => "bmi",
595            "bmi2" => "bmi2",
596            "lzcnt" => "lzcnt",
597            "xsave" => "xsave",
598            "aes" => "aes",
599            "pclmulqdq" => "pclmul",
600            "sha" => "sha",
601            "cmpxchg16b" => "cx16",
602            "adx" => "adx",
603            "rdrand" => "rdrnd",
604            "rdseed" => "rdseed",
605        }
606        isa.over(base)
607    }
608    #[cfg(not(target_arch = "x86_64"))]
609    base
610}
611
612/// The AArch64 extensions the machine running the compiler has, which is what `-march=native`
613/// means there.
614///
615/// Only the CRC32 extension, which is the one [`rucc_target::Isa::aarch64_march`] reads, asked
616/// of the processor through the standard library. On any other machine there is nothing to ask,
617/// and the answer is plain Armv8-A.
618fn native_aarch64() -> rucc_target::Isa {
619    #[cfg(target_arch = "aarch64")]
620    {
621        if std::arch::is_aarch64_feature_detected!("crc") {
622            return rucc_target::Isa::aarch64_march("armv8-a+crc");
623        }
624    }
625    rucc_target::Isa::NONE
626}
627
628/// Parses a command line, without the program name.
629///
630/// # Errors
631///
632/// Returns the message to print when the arguments do not name a compilation this compiler
633/// can attempt.
634pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
635    let expanded = preprocessor_args(&response_files(args)?);
636    let args = expanded.as_slice();
637    let host = Triple::host()
638        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
639    let mut opts = Options::new(host);
640    // Where the compiler is running, which is what `DW_AT_comp_dir` is and what a debugger joins a
641    // relative file name onto. Asked here rather than where the debug sections are written, because
642    // this is the one layer that is allowed to look at the process it is in, and because a command
643    // line that compiles four files should give the same answer for all four.
644    opts.working_dir = std::env::current_dir().ok().map(|dir| dir.to_string_lossy().into_owned());
645    let mut inputs: Vec<Input> = Vec::new();
646    let mut print_config = false;
647    let mut print_pipeline = false;
648    let mut print_plan = false;
649    let mut verbose = false;
650    let mut jobs = Jobs::default();
651    let mut nostdinc = false;
652    let mut sysroot: Option<PathBuf> = None;
653    // What the command line is worth warning about, filled in after the loop rather than during it,
654    // because every question of this kind is about two flags and the last word on both of them is
655    // the end of the loop.
656    let mut notes: Vec<String> = Vec::new();
657    // The whole ten field target, kept beside the three field one because `--target=` can pin a
658    // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
659    // else today, and `None` is a command line that named no target, which is this machine.
660    let mut pinned: Option<TargetTuple> = None;
661    let mut min_version: Option<rucc_tuple::Version> = None;
662    let mut output = None;
663    let mut link = LinkOptions::default();
664    let mut query: Option<Query> = None;
665    // What `--fetch` named, and whether `--offline` forbade it. Both are weighed after the loop
666    // because either can be written after the other.
667    let mut fetch: Option<String> = None;
668    // The other fetch, kept apart from the one above because they are different commands with
669    // different rules, and weighed after the loop for the same reason that one is.
670    let mut fetch_msvc: Option<String> = None;
671    let mut accepted = false;
672    let mut offline = false;
673    let mut threads = false;
674    // Which sanitizers are still asked for by the end of the command line. Accumulated across the
675    // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
676    // build that asks for a check and then takes it back has asked for nothing. What happens to a
677    // set that is not empty is decided after the loop.
678    let mut sanitizers: Vec<&str> = Vec::new();
679    // The `-ffast-math` family in the order it was written, replayed after the loop on top of
680    // what `-Ofast` implies. gcc applies a level's defaults before any flag and the flags in order
681    // after that, so `-fno-fast-math -Ofast` is not fast math, and only a replay can say so.
682    let mut math_flags: Vec<&str> = Vec::new();
683    let mut ofast = false;
684    // `-mdaz-ftz` and `-mno-daz-ftz`, which decide the startup file directly and outrank the
685    // family on that one question.
686    let mut daz_ftz: Option<bool> = None;
687    // The instruction set extensions the `-m` flags named, in order, and the processor `-march`
688    // named last. Both are weighed after the loop, because a processor supplies only what no flag
689    // spoke for whichever order they came in, and because `--target=` may come after either and
690    // decide that neither means anything. See `rucc_target::isa`.
691    let mut isa = rucc_target::Choices::new();
692    let mut isa_flag: Option<&str> = None;
693    let mut march: Option<&str> = None;
694    // What `-fexceptions` and `-fno-exceptions` last said, if either was written. It is kept apart
695    // from the field because `-fnon-call-exceptions` turns exceptions on only when neither was,
696    // which is gcc's rule and is why `-fno-exceptions -fnon-call-exceptions` defines no
697    // `__EXCEPTIONS` whichever order the two come in.
698    let mut exceptions: Option<bool> = None;
699    // `-x` applies to inputs that come after it and stays in effect until the next one, which
700    // is why it is tracked across the loop rather than attached to a single argument.
701    let mut forced: Option<InputKind> = None;
702    // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
703    // the flags after it and not the ones before, so a command line may set it more than once.
704    // GCC's default is its own installed header directory with the last component taken off,
705    // which is a path a cross compiler's build system knows and passes; there is no equivalent
706    // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
707    // outright.
708    let mut iprefix = String::new();
709
710    let mut i = 0;
711    while i < args.len() {
712        let arg = args[i].as_str();
713        i += 1;
714        match arg {
715            "-h" | "--help" => return Ok(Action::Help),
716            "--version" => return Ok(Action::Version),
717            // The sysroot fetch, which is weighed after the loop rather than acted on here, because
718            // `--offline` written after it has to be able to forbid it. Both spellings, since a
719            // flag that takes a tuple gets written both ways and neither is a guess at what the
720            // other meant.
721            "--fetch" => {
722                let value = args
723                    .get(i)
724                    .ok_or_else(|| err("--fetch requires the target to get a sysroot for"))?;
725                i += 1;
726                fetch = Some(value.clone());
727            }
728            _ if arg.starts_with("--fetch=") => {
729                fetch = Some(arg["--fetch=".len()..].to_owned());
730            }
731            // The other fetch, which is section 13.4's. Same two spellings for the same reason,
732            // and weighed after the loop so that `--offline` and `--accept-licence` written after
733            // it are read whichever order somebody put them in.
734            "--fetch-msvc-sdk" => {
735                let value = args.get(i).ok_or_else(|| {
736                    err("--fetch-msvc-sdk requires the target to get the SDK for")
737                })?;
738                i += 1;
739                fetch_msvc = Some(value.clone());
740            }
741            _ if arg.starts_with("--fetch-msvc-sdk=") => {
742                fetch_msvc = Some(arg["--fetch-msvc-sdk=".len()..].to_owned());
743            }
744            // Both spellings of the word, because the compiler's own prose uses one of them and
745            // most of the people typing this will reach for the other, and being told that a flag
746            // is not a flag over the letter in the middle of it is a puzzle rather than a message.
747            "--accept-licence" | "--accept-license" => accepted = true,
748            // Accepted on any command line and only ever read by the fetch, because an ordinary
749            // compile downloads nothing with or without it. So this flag takes nothing away today,
750            // which is the property section 13.2 asks for rather than an omission: a build that
751            // passes it is saying what it expects of this compiler, and what it expects is already
752            // true.
753            "--offline" => offline = true,
754            // Anywhere but first it would be a compiler command line with a dlltool one inside it,
755            // and there is no reading of that which is not a guess.
756            "--dlltool" => {
757                return Err(err(
758                    "--dlltool has to be the first argument, since everything after it is a \
759                     dlltool command line rather than a compiler one",
760                ));
761            }
762            "--print-config" => print_config = true,
763            "--print-pipeline" => print_pipeline = true,
764            "-###" => print_plan = true,
765            "-v" => verbose = true,
766            // The files a compilation goes through, kept rather than thrown away. The bare
767            // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
768            // gcc 16 does; `SaveTemps::Object` carries the measurement.
769            "-save-temps" => opts.save_temps = SaveTemps::Object,
770            _ if arg.starts_with("-save-temps=") => {
771                opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
772            }
773            // A `.su` beside every file compiled, one line per function saying how much stack it
774            // takes. Where the file goes is the plan's business, see `Job::stack_usage`.
775            "-fstack-usage" => opts.stack_usage = true,
776            "-fno-stack-usage" => opts.stack_usage = false,
777            // How long each step took. A misspelling of this is worth rejecting rather than
778            // ignoring, since a run that says nothing looks like a compilation that took no time.
779            "-time" => opts.time = true,
780            "-c" => opts.emit = EmitKind::Object,
781            "-S" => opts.emit = EmitKind::Asm,
782            "-E" => opts.emit = EmitKind::Preprocessed,
783            "-fsyntax-only" => opts.emit = EmitKind::SyntaxOnly,
784            "-g" => opts.debug_info = true,
785            // GCC's own levels of how much debug information to write. Zero is none and every
786            // other number is some, and this compiler has one amount, so the numbers above zero
787            // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
788            // debugger on the machine prefers, which is what we emit anyway.
789            "-g0" => opts.debug_info = false,
790            "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
791                opts.debug_info = true;
792            }
793            // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
794            // asks for another version is told rather than handed a file it cannot read.
795            "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
796            _ if arg.starts_with("-gdwarf-") => {
797                return Err(err(format!(
798                    "{arg}: this compiler writes DWARF 5 and no other version, see \
799                     spec/11-debug-info.md"
800                )));
801            }
802            // Whether the debug information goes in a file of its own beside the object. gcc
803            // writes that `.dwo` whether or not it found anything to put in it, which means a
804            // build system that declares the file as an output gets one and a make rule that
805            // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
806            // flag that changes nothing and refuses one that changes what is produced, and a file
807            // that does not appear is the plainest change of that kind there is. The negative
808            // spelling is taken, because putting it all in the object is what happens anyway.
809            "-gno-split-dwarf" => {}
810            "-gsplit-dwarf" => {
811                return Err(err(format!(
812                    "{arg}: this compiler writes no separate `.dwo` file, and a build that \
813                     expects one beside each object would wait for a file that never arrives, \
814                     see spec/11-debug-info.md"
815                )));
816            }
817            // How the debug sections are compressed. There are none yet, so every answer produces
818            // the same bytes and taking the flag promises nothing that is not kept. The value is
819            // still checked, because a typo in a distribution's flags is worth finding when the
820            // compiler reads it rather than when somebody later wonders why nothing got smaller.
821            // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
822            "-gz" => opts.compress = Compress::Zlib,
823            _ if arg.starts_with("-gz=") => {
824                let how = &arg["-gz=".len()..];
825                opts.compress = how.parse().map_err(|()| {
826                    err(format!(
827                        "`{how}` is not a way to compress debug sections, which is none, zlib, \
828                         zlib-gnu or zstd"
829                    ))
830                })?;
831            }
832            "-Werror" => opts.warnings_are_errors = true,
833            // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
834            // through rather than here, so that a warning `-w` dropped is not counted either.
835            "-w" => opts.warnings = false,
836            // Off by default, the way gcc has it off. A header that came with the machine is not
837            // one the person compiling can change, so a warning about it is noise, and under
838            // `-Werror` it is a build that stops on a line nobody in the project wrote. Somebody
839            // porting a header does want to hear all of it, which is what the flag is for.
840            "-Wsystem-headers" => opts.system_header_warnings = true,
841            "-Wno-system-headers" => opts.system_header_warnings = false,
842            "-pedantic-errors" => {
843                opts.pedantic = true;
844                opts.warnings_are_errors = true;
845            }
846            "-P" => opts.line_markers = false,
847            // The dependency family, which section 4.4 calls required because every build system
848            // that generates its own makefiles asks for it. The two that end in `D` write a file
849            // beside the object and let the compilation happen, and the two that do not write to
850            // standard output and stop after it. Nothing here turns the system headers back on
851            // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
852            // `-MM`: the flag asking for fewer of them is the one with something to say.
853            "-M" => {
854                opts.deps.emit = true;
855                opts.deps.instead_of_compiling = true;
856            }
857            "-MM" => {
858                opts.deps.emit = true;
859                opts.deps.instead_of_compiling = true;
860                opts.deps.system_headers = false;
861            }
862            "-MD" => opts.deps.emit = true,
863            "-MMD" => {
864                opts.deps.emit = true;
865                opts.deps.system_headers = false;
866            }
867            "-MP" => opts.deps.phony = true,
868            // These three take a word and only in the separated form, which is how GCC spells
869            // them and how every build system writes them.
870            "-MF" | "-MT" | "-MQ" => {
871                let value =
872                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
873                i += 1;
874                match arg {
875                    "-MF" => opts.deps.file = Some(value.clone()),
876                    // The whole of the difference between the two. `-MT` is for a build that has
877                    // already escaped what it is passing, and `-MQ` is for one that has a name
878                    // and wants it to arrive as that name.
879                    "-MT" => opts.deps.targets.push(value.clone()),
880                    _ => opts.deps.targets.push(deps::escaped(value)),
881                }
882            }
883            // The questions a build system asks before it compiles anything. Answered after the
884            // loop, because each one is about the target or the library search and the command
885            // line has not finished saying what those are.
886            "-dumpmachine" => query = Some(Query::Machine),
887            // Both answer with the GCC release in `__GNUC__` rather than our own version, because
888            // what asks is a build script deciding which GCC it is talking to, and `0.11` reads as
889            // a GCC too old to have anything. GCC 7 and later print only the major number for the
890            // first one, and that is the shape the scripts were written against.
891            "-dumpversion" => query = Some(Query::Version),
892            "-dumpfullversion" => query = Some(Query::FullVersion),
893            "-print-multiarch" => query = Some(Query::Multiarch),
894            "-print-search-dirs" => query = Some(Query::SearchDirs),
895            "-print-sysroot" => query = Some(Query::Sysroot),
896            // Both spellings, because this one is ours rather than GCC's and our own documents
897            // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
898            // two dashes like the other flags we invented, and document 12's table gives it one
899            // like the `-print-` family it sits in. A person who reads either and types what it
900            // says is right, so neither is refused.
901            "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
902                query = Some(Query::SysrootProvenance);
903            }
904            "-print-sysroot-digest" | "--print-sysroot-digest" => {
905                query = Some(Query::SysrootDigest);
906            }
907            "-print-libgcc-file-name" => query = Some(Query::Libgcc),
908            _ if arg.starts_with("-print-file-name=") => {
909                query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
910            }
911            _ if arg.starts_with("-print-prog-name=") => {
912                query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
913            }
914            // A program built to run in more than one thread. On every platform this compiler
915            // targets that is a macro the library's headers read and one more library on the
916            // link line, and the library is added after the loop so that it lands after the
917            // objects that refer to it.
918            "-pthread" | "-pthreads" => {
919                opts.defines.push("_REENTRANT".to_owned());
920                threads = true;
921            }
922            "-ansi" => {
923                opts.std = Std::C89;
924                opts.gnu_extensions = false;
925            }
926            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
927            // the spelling a build system that groups its warning flags tends to write.
928            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
929            // Both directions, because a build that needs this for one directory turns it back
930            // off for the next one rather than leaving it on for the whole tree.
931            "-fpermissive" => opts.permissive = true,
932            "-fno-permissive" => opts.permissive = false,
933            "-ffreestanding" => opts.hosted = false,
934            "-fhosted" => opts.hosted = true,
935            "-fno-builtin" => opts.builtins = false,
936            "-fbuiltin" => opts.builtins = true,
937            // The C89 dialects are under GNU's reading whatever this says, so turning it off
938            // there is turning off something the dialect asked for, which is accepted and does
939            // nothing. gcc refuses that command line, and there is nothing it could have meant.
940            "-fgnu89-inline" => opts.gnu89_inline = true,
941            "-fno-gnu89-inline" => opts.gnu89_inline = false,
942            // Both directions of each, because a build system that wants one of these usually
943            // writes it beside the flag that turns it back off for one directory.
944            "-fno-omit-frame-pointer" => opts.frame_pointer = Some(true),
945            "-fomit-frame-pointer" => opts.frame_pointer = Some(false),
946            // Both directions again, for the same reason, and a third answer for a command line
947            // that wrote neither: see `reorder_blocks` in `rucc_session`.
948            "-freorder-blocks" => opts.reorder_blocks = Some(true),
949            "-fno-reorder-blocks" => opts.reorder_blocks = Some(false),
950            // gcc's name for the scheduler that runs after the registers are handed out, which is
951            // the only one rucc has: see `schedule_insns` in `rucc_session`. gcc also takes
952            // `-fschedule-insns` for the pass before allocation, and taking that one here would be
953            // a flag that says a pass ran when none did.
954            "-fschedule-insns2" => opts.schedule_insns = Some(true),
955            "-fno-schedule-insns2" => opts.schedule_insns = Some(false),
956            // A call in tail position as a jump: see `sibling_calls` in `rucc_session`.
957            "-foptimize-sibling-calls" => opts.sibling_calls = Some(true),
958            "-fno-optimize-sibling-calls" => opts.sibling_calls = Some(false),
959            "-mno-red-zone" => opts.red_zone = false,
960            "-mred-zone" => opts.red_zone = true,
961            // Four flags rather than one with an argument, which is how gcc spells them and how
962            // every build line writes them. Last one wins, because a package build puts
963            // `-fstack-protector-strong` in its global flags and a directory that cannot have one
964            // turns it back off on the line after.
965            "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
966                opts.protector = Protector::None;
967            }
968            "-fstack-protector" => opts.protector = Protector::Buffers,
969            "-fstack-protector-strong" => opts.protector = Protector::Strong,
970            "-fstack-protector-all" => opts.protector = Protector::All,
971            // The other half of what a hardened build asks for, and it is a question about the
972            // frame rather than about the function, so it is a switch rather than a level.
973            "-fstack-clash-protection" => opts.stack_clash = true,
974            "-fno-stack-clash-protection" => opts.stack_clash = false,
975            // The third of them, and the one that is a question with an argument rather than a
976            // family of spellings, because what it asks about is which of the two edges of a
977            // control flow transfer is checked. Bare is both of them, which is what gcc does.
978            "-fcf-protection" => opts.control = Control::Full,
979            "-fno-cf-protection" => opts.control = Control::None,
980            // Two spellings of the same request, which is what gcc has as well. `-p` was the older
981            // profiler and `-pg` the one that also recorded who called whom, and on every platform
982            // this compiler targets there is now one hook and both ask for it.
983            "-pg" | "-p" => {
984                opts.profile = true;
985                link.profile = true;
986            }
987            // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
988            // say where the call goes and a command line that asked for no call has nowhere to put
989            // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
990            // directory is a build system that would otherwise fail on every other directory.
991            "-mfentry" => opts.hook = Hook::Early,
992            "-mno-fentry" => opts.hook = Hook::Late,
993            // GCC drops its own include directory along with the system ones, because its
994            // headers are half of a pair with the library's and half a pair is worse than
995            // none. A build that passes this is supplying the whole set itself.
996            "-nostdinc" => nostdinc = true,
997            "-o" => {
998                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
999                i += 1;
1000            }
1001            // What the files kept beside an output are named after, which is `-save-temps` and
1002            // `-fstack-usage` so far. gcc takes each of the three in the separated form only, and
1003            // its driver passes them to every compilation it runs, so a build that copied a
1004            // command line out of gcc's `-v` has them. See `phase::aux_base` for what they do.
1005            "-dumpbase" | "-dumpbase-ext" | "-dumpdir" => {
1006                let value =
1007                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?.clone();
1008                i += 1;
1009                match arg {
1010                    "-dumpbase" => opts.dump_base = Some(value),
1011                    "-dumpbase-ext" => opts.dump_base_ext = Some(value),
1012                    _ => opts.dump_dir = Some(value),
1013                }
1014            }
1015            // The flags that take a directory only in the separated form. GCC spells them
1016            // this way and nothing writes `-iquotedir`, so accepting the joined form would
1017            // mean guessing at a path that starts with the flag's own letters.
1018            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
1019            // two mean the same thing here: the configured directories are under there rather
1020            // than under the root.
1021            "-isysroot" => {
1022                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
1023                i += 1;
1024                sysroot = Some(PathBuf::from(dir));
1025            }
1026            "-iquote" | "-isystem" | "-idirafter" => {
1027                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1028                i += 1;
1029                match arg {
1030                    "-iquote" => opts.search.push_quote(dir.clone()),
1031                    "-isystem" => opts.search.push_system(dir.clone()),
1032                    _ => opts.search.push_after(dir.clone()),
1033                }
1034            }
1035            "-iprefix" => {
1036                iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
1037                i += 1;
1038            }
1039            // Where GCC puts these is not where its manual says it puts them, and this is the
1040            // measured answer rather than the documented one: `-iwithprefix` lands in the
1041            // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
1042            // the `-I` slot. A cross build that uses them is relying on the behaviour, since
1043            // that is the compiler it was developed against.
1044            "-iwithprefix" | "-iwithprefixbefore" => {
1045                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1046                i += 1;
1047                let dir = format!("{iprefix}{dir}");
1048                if arg == "-iwithprefix" {
1049                    opts.search.push_system(dir);
1050                } else {
1051                    opts.search.push_bracket(dir);
1052                }
1053            }
1054            "-include" | "-imacros" => {
1055                let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1056                i += 1;
1057                opts.preincludes
1058                    .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
1059            }
1060            // The flag `-iquote` was introduced to replace, still passed by build systems old
1061            // enough to predate the replacement. It is not a directory: it says that every `-I`
1062            // so far is for quoted includes only, and that a quoted include stops looking next
1063            // to the file that wrote it.
1064            "-I-" => opts.search.split_quote_chain(),
1065            // `-x c` and `-xc`, both of which gcc takes. busybox and toybox probe the compiler
1066            // with the joined one.
1067            _ if arg.starts_with("-x") => {
1068                let lang = joined_or_next(arg, 2, args, &mut i)?;
1069                forced = if lang == "none" {
1070                    None
1071                } else {
1072                    Some(InputKind::from_x_arg(&lang).map_err(|e| err(format!("{e}")))?)
1073                };
1074            }
1075            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
1076            // translation units in one process rather than making the build system fork, and
1077            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
1078            // to exist and has to be spelled the way `make` spells it.
1079            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
1080            // and a build system may produce either, so both are read here rather than
1081            // being normalised by whatever generated the command line.
1082            _ if arg.starts_with("-D") => {
1083                let value = joined_or_next(arg, 2, args, &mut i)?;
1084                opts.defines.push(value);
1085            }
1086            _ if arg.starts_with("-U") => {
1087                let value = joined_or_next(arg, 2, args, &mut i)?;
1088                opts.undefines.push(value);
1089            }
1090            _ if arg.starts_with("-I") => {
1091                let dir = joined_or_next(arg, 2, args, &mut i)?;
1092                opts.search.push_bracket(dir);
1093            }
1094            _ if arg.starts_with("-std=") => {
1095                let name = &arg["-std=".len()..];
1096                let (std, gnu) = Std::from_flag(name)
1097                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
1098                opts.std = std;
1099                opts.gnu_extensions = gnu;
1100            }
1101            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
1102            // handed, so a differential run that does not set it is comparing two compilers
1103            // that believe they are different compilers.
1104            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
1105            // that we have not written yet are accepted and ignored, because a dump is a
1106            // debugging aid and a build that asks for one should still compile. A letter
1107            // outside the family falls through to the unknown option error, which is what
1108            // keeps `-dumpversion` from being read as a dump of nothing.
1109            _ if Dumps::is_family(arg) => {
1110                opts.dumps.add(&arg[2..]);
1111            }
1112            // One name at a time, which is what a build that means its own `memcpy` and the
1113            // library's everything else writes. The name is not checked against a list, because
1114            // the flag is about what the program means by a name and a program is allowed to mean
1115            // something by a name this compiler has never heard of.
1116            _ if arg.starts_with("-fno-builtin-") => {
1117                opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
1118            }
1119            _ if arg.starts_with("-fgnuc-version=") => {
1120                let v = &arg["-fgnuc-version=".len()..];
1121                opts.gnuc = v.parse().map_err(err)?;
1122                opts.gnuc_given = true;
1123            }
1124            // The MSVC release an MSVC row claims, which is `_MSC_VER` and nothing else here.
1125            _ if arg.starts_with("-fms-compatibility-version=") => {
1126                let v = &arg["-fms-compatibility-version=".len()..];
1127                opts.msc = v.parse().map_err(err)?;
1128            }
1129            // Which of Microsoft's C runtimes an MSVC row links against, in clang's spelling of
1130            // `cl.exe`'s `/MT` and `/MD`. The headers are told through `_DLL` and the link through
1131            // the libraries it names, so it is both a compile flag and a link one. The two debug
1132            // runtimes are refused by name rather than taken as the release ones, since what they
1133            // link is a different set of libraries and a program that asked for one wants its
1134            // checks.
1135            _ if arg.starts_with("-fms-runtime-lib=") => {
1136                let dll = match &arg["-fms-runtime-lib=".len()..] {
1137                    "static" => false,
1138                    "dll" => true,
1139                    debug @ ("static_dbg" | "dll_dbg") => {
1140                        return Err(err(format!(
1141                            "-fms-runtime-lib={debug} asks for Microsoft's debug C runtime, which \
1142                             this compiler does not link against yet. static and dll are the two \
1143                             it has"
1144                        )));
1145                    }
1146                    other => {
1147                        return Err(err(format!(
1148                            "-fms-runtime-lib= takes static or dll, and `{other}` is neither"
1149                        )));
1150                    }
1151                };
1152                opts.ms_dll_runtime = dll;
1153                link.crt = if dll { rucc_sysroot::Crt::Dll } else { rucc_sysroot::Crt::Static };
1154            }
1155            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
1156            // than the unknown option one, because a build reaching for it is asking for a feature
1157            // and deserves to be told it is not coming rather than told the spelling is wrong.
1158            // The negative form is what this compiler does anyway, so it is taken and dropped.
1159            "-fnested-functions" => {
1160                return Err(err(
1161                    "nested functions are not supported: a call to one goes through a trampoline \
1162                     written on the stack, which no target that enforces an unexecutable stack \
1163                     allows",
1164                ));
1165            }
1166            "-fno-nested-functions" => {}
1167            // Which of the two links the output is for, which is a real difference and not a
1168            // description of what happens anyway. Everything here is position independent either
1169            // way, and what these decide is whether a name may be one another object defines or
1170            // replaces, because a link that produces an executable puts every name in the same
1171            // program and a link that produces a shared library does not.
1172            //
1173            // It matters that they are accepted at all, whatever they then do. Every autoconf and
1174            // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
1175            // be the `CC` of a project that has a configure script, whatever else it can do. That
1176            // is how this was found: building SQLite's test fixture stopped on it.
1177            "-fPIC" | "-fpic" => opts.pic = Pic::Library,
1178            // Not a synonym of the pair above, which is what they were treated as until #756. The
1179            // library is the expensive answer and gcc makes it the one that has to be asked for,
1180            // so this is also what nothing at all means.
1181            "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
1182            // A different question from the pair above, and the one every distribution build of a
1183            // shared library answers. `-fPIC` decides how an address is reached, and this decides
1184            // whether the optimizer may believe a body it can see, because an exported name is one
1185            // the dynamic linker may find another definition of first. On by default, which is
1186            // gcc's arrangement and is the honest answer, and off is a promise the build makes and
1187            // nothing checks.
1188            "-fsemantic-interposition" => opts.interposition = true,
1189            "-fno-semantic-interposition" => opts.interposition = false,
1190            // Two requests rather than one, and the same table answers both, so what decides is
1191            // whether either of them is standing. gcc arranges it the same way: the asynchronous
1192            // one is the default here and it implies the other, and a line that asks for a table
1193            // and against an asynchronous one gets a table.
1194            "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
1195            "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
1196            "-funwind-tables" => opts.unwind_tables = true,
1197            "-fno-unwind-tables" => opts.unwind_tables = false,
1198            // The other direction is a request, not a description, and it is one this compiler
1199            // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
1200            // option error. Answering it by carrying on would be answering a different question:
1201            // the code would still be position independent, which is correct everywhere an
1202            // ordinary program runs and is wrong in a kernel, where the flag is written precisely
1203            // because there is no loader to fill a global offset table in.
1204            "-fno-pic" | "-fno-pie" => {
1205                return Err(err(
1206                    "position dependent code is not supported: an address that may be in another \
1207                     object is loaded out of the global offset table, and nothing here emits the \
1208                     absolute form this asks for. Use -no-pie if what you meant was how to link",
1209                ));
1210            }
1211            // A section per function and a section per variable, which is what makes
1212            // `--gc-sections` able to drop anything: a linker can leave out a section nothing
1213            // reaches and cannot leave out half of one. Both directions are taken, and the off
1214            // one is the default rather than a refusal, since a build that writes it is asking
1215            // for what happens anyway.
1216            "-ffunction-sections" => opts.function_sections = true,
1217            "-fno-function-sections" => opts.function_sections = false,
1218            "-fdata-sections" => opts.data_sections = true,
1219            "-fno-data-sections" => opts.data_sections = false,
1220            // Whether a file scope declaration with no initializer is offered to the linker as a
1221            // common symbol for it to merge, or written into `.bss` as an ordinary defined one.
1222            // Unwritten, the target answers, which is on for Darwin and off everywhere else.
1223            "-fcommon" => opts.common = Some(true),
1224            "-fno-common" => opts.common = Some(false),
1225            // What overflows rather than being undefined. Every one of these takes something away
1226            // from the optimizer rather than asking it to do anything, which is why the negative
1227            // spellings are the interesting ones and the positive spellings are the default.
1228            //
1229            // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
1230            // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
1231            // written here as the pair rather than kept as a third thing to test everywhere.
1232            //
1233            // `-ftrapv` is the exception and is the one that asks for something. It is the other
1234            // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
1235            // the other, which makes the last one on the command line the one that counts. That is
1236            // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
1237            // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
1238            // question is left alone by both, because neither has anything to say about it.
1239            "-fwrapv" => {
1240                opts.wrapping.signed = true;
1241                opts.wrapping.trap = false;
1242            }
1243            "-fno-wrapv" => opts.wrapping.signed = false,
1244            "-fwrapv-pointer" => opts.wrapping.pointer = true,
1245            "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
1246            "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
1247            // Which does not clear the checked one, because gcc does not: `-ftrapv
1248            // -fstrict-overflow` still emits the calls. It says what is assumed and not what
1249            // happens.
1250            "-fstrict-overflow" => {
1251                opts.wrapping.signed = false;
1252                opts.wrapping.pointer = false;
1253            }
1254            "-ftrapv" => {
1255                opts.wrapping.trap = true;
1256                opts.wrapping.signed = false;
1257            }
1258            "-fno-trapv" => opts.wrapping.trap = false,
1259            // The two flags that say what a plain `char` is, which is one question with two
1260            // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
1261            // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
1262            // answers and the last one written wins. Nothing is set until one of them is given,
1263            // because the target's own ABI is the answer otherwise and it is not the same answer
1264            // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
1265            "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
1266            "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
1267            // And the size of an enumeration, which is the other thing in this group that changes
1268            // the ABI rather than the code.
1269            "-fshort-enums" => opts.short_enums = true,
1270            "-fno-short-enums" => opts.short_enums = false,
1271            // And Microsoft's reading of an anonymous member, which changes the layout of every
1272            // record that writes a tag on one. Nothing is set until one of them is given, because
1273            // the target is the answer otherwise: gcc's mingw build has this on and its Linux
1274            // build has it off.
1275            "-fms-extensions" => opts.ms_extensions = Some(true),
1276            "-fno-ms-extensions" => opts.ms_extensions = Some(false),
1277            // Both directions of this one are recorded, and what they decide is whether lowering
1278            // names the type each access goes through. Turning it off is the front end leaving the
1279            // name off rather than a pass being told to ignore one it can see, which is one
1280            // condition in one place, and it is the reading that survives link time optimization:
1281            // a unit built with the flag off keeps its own answer when its bodies end up in a
1282            // module beside bodies that were not.
1283            //
1284            // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
1285            // and is tested, and no pass at any level asks the alias analysis anything today, so
1286            // no program compiles differently for having passed this. The flag is wired anyway,
1287            // because the change that makes a pass ask is not the change anybody will remember to
1288            // wire it in, and a flag that is taken and dropped once the names mean something is
1289            // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
1290            // words.
1291            "-fstrict-aliasing" => opts.strict_aliasing = true,
1292            "-fno-strict-aliasing" => opts.strict_aliasing = false,
1293            // The same shape of answer for the same reason, and the flag the kernel writes beside
1294            // the one above it.
1295            //
1296            // Nothing here concludes that a pointer is not null from the fact that it was
1297            // dereferenced. There is no such conclusion to draw from, because no pass records one:
1298            // a load says where it read and nothing else, and a comparison against null is an
1299            // ordinary comparison of two values the optimizer has no fact about. So a function
1300            // that reads through a pointer and then tests it keeps the test, which is what the
1301            // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
1302            // to be asked for because it draws the conclusion by default.
1303            //
1304            // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
1305            // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
1306            // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
1307            "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
1308            // The floating point group, which goes the same way and for the same reason, and which
1309            // is worth writing out because the reason is easy to get backwards.
1310            //
1311            // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
1312            // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
1313            // changed and that an exception raised by an operation may be looked at, so an
1314            // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
1315            // whose exception the program does not get. Nothing here folds any floating point
1316            // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
1317            // that runs, at every level. So both of those describe what already happens.
1318            //
1319            // The permissive ones are the other half, and they are licences rather than requests
1320            // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
1321            // `-fno-trapping-math` says nothing looks at the exceptions, which together are
1322            // permission to fold. Not folding is the conservative side of that permission and is
1323            // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
1324            // speed and not correctness, which is the test section 4.1 puts a licence through.
1325            "-frounding-math" | "-fno-rounding-math" => {}
1326            // `-fno-trapping-math` is the one of the four that is kept, because there is one
1327            // conversion this compiler does not fold and gcc folds under it, and the two answers
1328            // differ. Converting a constant floating value to an integer type it does not fit in
1329            // is undefined behaviour rather than a value: left to the hardware it is one
1330            // instruction and the answer is the integer indefinite value, and folded it is the
1331            // nearest end of the integer's range. Both compilers leave it to the instruction by
1332            // default and gcc folds it under this flag, so a program built with it and compiled
1333            // without it gets a different number rather than a slower one. `-ftrapping-math` is
1334            // gcc's default, so a build spelling it out is asking for what it already has.
1335            //
1336            // The rest of the family goes with it, `-ffast-math` included, and all of them are
1337            // taken now. Each is a licence rather than a request and nothing here folds floating
1338            // point arithmetic, so the code does not change. What does change is the macros gcc
1339            // defines for each licence, which a header reads, and the startup file `-ffast-math`
1340            // links, which puts the hardware in flush to zero mode. Both are done after the loop,
1341            // because the family is a set of switches over the same fields and the last word on
1342            // each of them is the end of the command line.
1343            "-ftrapping-math"
1344            | "-fno-trapping-math"
1345            | "-ffast-math"
1346            | "-fno-fast-math"
1347            | "-funsafe-math-optimizations"
1348            | "-fno-unsafe-math-optimizations"
1349            | "-fmath-errno"
1350            | "-fno-math-errno"
1351            | "-ffinite-math-only"
1352            | "-fno-finite-math-only"
1353            | "-fsigned-zeros"
1354            | "-fno-signed-zeros"
1355            | "-freciprocal-math"
1356            | "-fno-reciprocal-math"
1357            | "-fassociative-math"
1358            | "-fno-associative-math" => math_flags.push(arg),
1359            // Whether the startup file that sets flush to zero is linked, asked directly. gcc
1360            // links it for a shared object too when this is written, which the family does not.
1361            "-mdaz-ftz" => daz_ftz = Some(true),
1362            "-mno-daz-ftz" => daz_ftz = Some(false),
1363            // About temporary files rather than about code. There is nothing between the phases of
1364            // one compilation here to write to a file in the first place.
1365            "-pipe" => {}
1366            // Preprocess the input, which a C compile always does. GCC has it for Fortran, and
1367            // meson writes it when it asks a compiler for its predefined macros.
1368            "-cpp" => {}
1369            // Nothing here writes colour, so all of these are the same answer, and it is the answer
1370            // that costs nothing: the diagnostics come out plain either way and no build depends on
1371            // an escape sequence being there. Taken rather than refused because cmake writes
1372            // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
1373            // makes this the second most common flag after `-fPIC` to stop a build over a question
1374            // about how the text looks.
1375            "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
1376            _ if arg.starts_with("-fdiagnostics-color=") => {}
1377            // The link flags. None of them changes the compilation, which is why they are
1378            // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
1379            // error: it is a thing said to a linker that is not going to run.
1380            "-static" => link.is_static = true,
1381            "-shared" => link.shared = true,
1382            "-r" => link.relocatable = true,
1383            "-pie" => link.pie = Some(true),
1384            "-no-pie" | "-nopie" => link.pie = Some(false),
1385            "-nostdlib" => link.no_stdlib = true,
1386            "-nostartfiles" => link.no_startfiles = true,
1387            "-nodefaultlibs" => link.no_defaultlibs = true,
1388            "-fno-builtins-lib" => link.no_builtins_lib = true,
1389            "-fbuiltins-lib" => link.no_builtins_lib = false,
1390            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
1391            "-s" => link.strip = true,
1392            // mingw-w64's three. `-mwindows` and `-mconsole` pick the subsystem, last one wins,
1393            // and `-municode` picks the start file and tells the headers through `UNICODE`, which is
1394            // what gcc's spec does with it. All three are taken and ignored for other targets, as gcc
1395            // built for mingw is the only gcc that knows them and a Makefile written for it is what
1396            // passes them.
1397            "-mwindows" => link.gui = true,
1398            "-mconsole" => link.gui = false,
1399            "-municode" => {
1400                link.unicode = true;
1401                opts.defines.push("UNICODE".to_owned());
1402            }
1403            // Into the ordered input list rather than a list of its own, because a great many of
1404            // the linker's options are a bracket around the files after them and an option that
1405            // lost its place among them says nothing. `--whole-archive` is the one that found this.
1406            "-Xlinker" => {
1407                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
1408                i += 1;
1409                inputs.push(Input::linker(next));
1410            }
1411            _ if arg.starts_with("-Wl,") => {
1412                // Commas separate arguments rather than being part of one, which is what makes
1413                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
1414                inputs.extend(arg["-Wl,".len()..].split(',').map(Input::linker));
1415            }
1416            _ if arg.starts_with("-fuse-ld=") => {
1417                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
1418            }
1419            _ if arg.starts_with("-l") && arg.len() > 2 => {
1420                inputs.push(Input::library(&arg[2..]));
1421            }
1422            "-l" => {
1423                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
1424                i += 1;
1425                inputs.push(Input::library(next));
1426            }
1427            _ if arg.starts_with("-L") => {
1428                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1429            }
1430            _ if arg.starts_with("-B") => {
1431                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1432            }
1433            _ if arg.starts_with("-j") => {
1434                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
1435            }
1436            _ if arg.starts_with("--sysroot=") => {
1437                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
1438            }
1439            _ if arg.starts_with("--target=") => {
1440                let t = &arg["--target=".len()..];
1441                // The same string again, as the model that has room for a libc version. A spelling
1442                // the three field parser took and this one does not is not an error, because the
1443                // one that decides what is compiled has already accepted it and the only thing
1444                // lost is a version nobody asked for.
1445                pinned = t.parse().ok();
1446                // The other way round is a deployment target the three field parser has no room
1447                // for, `aarch64-macos.13`, and the triple is the one the tuple narrows to.
1448                opts.target = match t.parse() {
1449                    Ok(triple) => triple,
1450                    Err(e) => {
1451                        pinned.and_then(Triple::from_tuple).ok_or_else(|| err(format!("{e}")))?
1452                    }
1453                };
1454            }
1455            _ if arg.starts_with("--emit=") => {
1456                let k = &arg["--emit=".len()..];
1457                opts.emit = k
1458                    .parse()
1459                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
1460            }
1461            // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
1462            // to write. `-Og` is GCC's level for a build somebody is going to step through, and
1463            // it is `-O1` with the transformations that move code around left out; this compiler
1464            // has no such level yet, so it is the nearest one and `--print-pipeline` says what
1465            // that came to rather than the flag pretending otherwise.
1466            "-O" | "-Og" => {
1467                opts.opt_level = rucc_session::OptLevel::O1;
1468                ofast = false;
1469            }
1470            // The union of `-O3` and `-ffast-math`. The second half is a default rather than a
1471            // flag, which is why it is remembered here and applied after the loop: a later level
1472            // takes it back, and so does a `-fno-fast-math` written on either side of it.
1473            "-Ofast" => {
1474                opts.opt_level = rucc_session::OptLevel::O3;
1475                ofast = true;
1476            }
1477            _ if arg.starts_with("-O") => {
1478                ofast = false;
1479                opts.opt_level = arg[2..]
1480                    .parse()
1481                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
1482            }
1483            // How far a multiply and an addition may be fused into one rounding. Before the
1484            // optimizer's `-f` family below for the reason the ones under it are, and kept rather
1485            // than dropped because it is the one flag in its group this compiler could act on: it
1486            // rides into the IR as an attribute on each function with a body, so the day the code
1487            // generator forms an `fma` it already knows which functions were given permission.
1488            // Nothing forms one today, under any value of this and under any `-march=`.
1489            _ if arg.starts_with("-ffp-contract=") => {
1490                let how = &arg["-ffp-contract=".len()..];
1491                opts.fp_contract = how.parse().map_err(|()| {
1492                    err(format!("`{how}` is not a contraction, which is fast, on or off"))
1493                })?;
1494            }
1495            // How much of an expression may be computed wider than it was written. The values are
1496            // gcc's and so is the refusal of anything else, and none of the three changes anything
1497            // here: an operation is computed in the type C says it is on every target this compiler
1498            // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
1499            // happens. `fast` and `16` are permission to be wider, which is a licence this takes
1500            // and does not use, the same way the two above are. The flag is worth taking because
1501            // glibc's headers and a good deal of configure output write it, and because the answer
1502            // it asks about is one this compiler can state rather than guess at: there is no x87
1503            // target here, which is the machine the whole question was invented for.
1504            // Whether a local and a spilled value that are never both wanted may be the same bytes
1505            // of the frame. gcc's three values, and two of them mean the same thing here: what rucc
1506            // shares is a local whose address provably never leaves the function, which is narrower
1507            // than `named_vars` and narrower still than `all`, so both of them get it. `none` is
1508            // the one that changes anything, and it is the flag a program that reads a local
1509            // through a pointer it kept past the end of the block writes.
1510            _ if arg.starts_with("-fstack-reuse=") => {
1511                let how = &arg["-fstack-reuse=".len()..];
1512                opts.stack_reuse = match how {
1513                    "all" | "named_vars" => Some(true),
1514                    "none" => Some(false),
1515                    _ => {
1516                        return Err(err(format!(
1517                            "`{how}` is not a stack reuse, which is all, named_vars or none"
1518                        )));
1519                    }
1520                };
1521            }
1522            _ if arg.starts_with("-fexcess-precision=") => {
1523                let how = &arg["-fexcess-precision=".len()..];
1524                if !matches!(how, "16" | "fast" | "standard") {
1525                    return Err(err(format!(
1526                        "`{how}` is not an excess precision, which is 16, fast or standard"
1527                    )));
1528                }
1529            }
1530            // Which front of a path is rewritten before it reaches the output, which is how a
1531            // build gets the same bytes out of two different directories. The four spellings are
1532            // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
1533            // once. Only the macro list does anything today, because `__FILE__` is the only place
1534            // a path reaches the output: there is no DWARF and no profile data yet, so the other
1535            // two are recorded for the work that will read them. The argument splits at the last
1536            // `=` rather than the first, which is gcc's rule and is what lets a directory with an
1537            // `=` in its name be the old half.
1538            _ if arg.starts_with("-fmacro-prefix-map=") => {
1539                let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1540                opts.prefix_map.macros.push(old, new);
1541            }
1542            _ if arg.starts_with("-fdebug-prefix-map=") => {
1543                let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1544                opts.prefix_map.debug.push(old, new);
1545            }
1546            _ if arg.starts_with("-fprofile-prefix-map=") => {
1547                let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1548                opts.prefix_map.profile.push(old, new);
1549            }
1550            _ if arg.starts_with("-ffile-prefix-map=") => {
1551                let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1552                opts.prefix_map.macros.push(old, new);
1553                opts.prefix_map.debug.push(old, new);
1554                opts.prefix_map.profile.push(old, new);
1555            }
1556            // A whole optimization rather than a flag, and the family is taken rather than
1557            // refused because of what ignoring it does. There is none of it here yet, so a build
1558            // that asks for it gets a program that is correct and slower than it could have been,
1559            // which is what section 4.1 means by a hint about speed and what every compilation at
1560            // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1561            // holds the bytecode and no machine code at all, and every object here holds the code,
1562            // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1563            // to this compiler gets objects that are more usable than the ones it asked for rather
1564            // than different ones. Every value is still checked against gcc's, because somebody
1565            // who wrote `-flto=thin` meant clang and had better hear about it here.
1566            "-flto" => opts.lto.requested = true,
1567            "-fno-lto" => opts.lto.requested = false,
1568            _ if arg.starts_with("-flto=") => {
1569                let how = &arg["-flto=".len()..];
1570                opts.lto.jobs = how.parse().map_err(|()| {
1571                    err(format!(
1572                        "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1573                         count above zero"
1574                    ))
1575                })?;
1576                opts.lto.requested = true;
1577            }
1578            _ if arg.starts_with("-flto-partition=") => {
1579                let how = &arg["-flto-partition=".len()..];
1580                opts.lto.partition = how.parse().map_err(|()| {
1581                    err(format!(
1582                        "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1583                         or none"
1584                    ))
1585                })?;
1586            }
1587            _ if arg.starts_with("-flto-compression-level=") => {
1588                let how = &arg["-flto-compression-level=".len()..];
1589                let level =
1590                    how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1591                        err(format!("`{how}` is not a compression level, 0 to 19"))
1592                    })?;
1593                opts.lto.compression = Some(level);
1594            }
1595            // Whether the object keeps its machine code as well as the bytecode. It always does
1596            // here, so the first of these describes what happens and the second asks for an object
1597            // with less in it, which is a smaller file and not a different program, so both are
1598            // taken.
1599            "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1600            // Whether the linker is handed a plugin that does the link time work. The design in
1601            // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1602            // plugin into anybody, so neither answer is a question it has to hold.
1603            "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1604            // Reading a profile back. Taken for the reason the family above it is: nothing here
1605            // reads one, so a build that asks gets the program it would have got anyway, and gcc
1606            // itself produces a byte for byte identical object from `-fprofile-use` when there are
1607            // no counts beside the file. The path is recorded for the pass that will read it. The
1608            // warning gcc prints when it looked and found nothing is deliberately not copied,
1609            // because nothing here looks, and a warning about a file that was never opened would
1610            // fire on the builds that have a perfectly good profile as well as on the ones that
1611            // do not.
1612            "-fprofile-use" => opts.profile_data.requested = true,
1613            "-fno-profile-use" => opts.profile_data.requested = false,
1614            _ if arg.starts_with("-fprofile-use=") => {
1615                opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1616                opts.profile_data.requested = true;
1617            }
1618            _ if arg.starts_with("-fprofile-dir=") => {
1619                opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1620            }
1621            "-fprofile-abs-path" => opts.profile_data.absolute = true,
1622            "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1623            "-fprofile-correction" => opts.profile_data.correction = true,
1624            "-fno-profile-correction" => opts.profile_data.correction = false,
1625            "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1626            "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1627            // Writing the counts rather than reading them, which is refused rather than taken and
1628            // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1629            // file a build declared as an output never appears: the instrumented program writes a
1630            // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1631            // two stage build that got neither would go on to optimize against no counts at all
1632            // and report coverage of nothing, with nothing along the way saying so. The objects
1633            // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1634            // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1635            // this is a flag that changes the output rather than a hint about speed.
1636            "-fprofile-arcs"
1637            | "--coverage"
1638            | "-fcondition-coverage"
1639            | "-fpath-coverage"
1640            | "-fprofile-generate" => {
1641                return Err(err(format!(
1642                    "{arg}: this compiler does not instrument for profiling, and a build that \
1643                     expects the counts a run of the instrumented program writes would optimize \
1644                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1645                )));
1646            }
1647            _ if arg.starts_with("-fprofile-generate=") => {
1648                return Err(err(format!(
1649                    "{arg}: this compiler does not instrument for profiling, and a build that \
1650                     expects the counts a run of the instrumented program writes would optimize \
1651                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1652                )));
1653            }
1654            "-ftest-coverage" => {
1655                return Err(err(format!(
1656                    "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1657                     that expects one would wait for a file that never arrives, see \
1658                     spec/04-driver-and-cli.md"
1659                )));
1660            }
1661            // The rest of the family describes instrumentation that is refused above, so what is
1662            // left to do with them is check them and drop them. They are checked because a
1663            // misspelling in a distribution's flags is worth finding here rather than on the day
1664            // the instrumentation lands, and dropped because there is nothing for an answer about
1665            // how a counter is written to be an answer about.
1666            _ if arg.starts_with("-fprofile-update=") => {
1667                let how = &arg["-fprofile-update=".len()..];
1668                if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1669                    return Err(err(format!(
1670                        "`{how}` is not a profile update method, which is single, atomic or \
1671                         prefer-atomic"
1672                    )));
1673                }
1674            }
1675            _ if arg.starts_with("-fprofile-reproducible=") => {
1676                let how = &arg["-fprofile-reproducible=".len()..];
1677                if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1678                    return Err(err(format!(
1679                        "`{how}` is not a profile reproducibility method, which is serial, \
1680                         parallel-runs or multithreaded"
1681                    )));
1682                }
1683            }
1684            "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1685            "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1686            _ if arg.starts_with("-fprofile-filter-files=")
1687                || arg.starts_with("-fprofile-exclude-files=")
1688                || arg.starts_with("-fprofile-note=") => {}
1689            // What every name gets when nothing in the source said, which the attribute in the
1690            // source overrides rather than the other way round. Before the optimizer's `-f`
1691            // family below for the reason the tier below it is.
1692            _ if arg.starts_with("-fvisibility=") => {
1693                let seen = &arg["-fvisibility=".len()..];
1694                opts.visibility = seen.parse().map_err(|()| {
1695                    err(format!(
1696                        "`{seen}` is not a visibility, which is default, hidden, internal or \
1697                         protected"
1698                    ))
1699                })?;
1700            }
1701            // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1702            // family below for the reason the two above it are, and last of the three so that the
1703            // bare spelling and the negative one are matched exactly rather than by this.
1704            _ if arg.starts_with("-fcf-protection=") => {
1705                let edges = &arg["-fcf-protection=".len()..];
1706                opts.control = edges.parse().map_err(|()| {
1707                    err(format!(
1708                        "`{edges}` is not a control flow protection, which is full, branch, \
1709                         return, none or check"
1710                    ))
1711                })?;
1712            }
1713            // How much room every function opens with for something to be written over later.
1714            // Before the optimizer's `-f` family below for the reason the ones above it are.
1715            _ if arg.starts_with("-fpatchable-function-entry=") => {
1716                let room = &arg["-fpatchable-function-entry=".len()..];
1717                opts.patchable = room.parse().map_err(|()| {
1718                    err(format!(
1719                        "`{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"
1720                    ))
1721                })?;
1722            }
1723            // The memory safety monitor, from section 15.4 of
1724            // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1725            // because a pass that took the name `safety=detect` would otherwise be handed the
1726            // flag, and the tier is not a pass.
1727            _ if arg.starts_with("-fsafety=") => {
1728                let tier = &arg["-fsafety=".len()..];
1729                opts.safety = tier.parse().map_err(|()| {
1730                    err(format!(
1731                        "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1732                    ))
1733                })?;
1734            }
1735            // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1736            // than folded into the tier because it is a departure somebody who has read that
1737            // section makes, and the two defaults it describes are a property of what is being
1738            // built rather than of how much checking is wanted.
1739            _ if arg.starts_with("-fsafety-init=") => {
1740                let mode = &arg["-fsafety-init=".len()..];
1741                opts.padding = mode.parse().map_err(|()| {
1742                    err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1743                })?;
1744            }
1745            // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1746            // strict form of that section needs a member id the front end does not name yet and
1747            // accepting the spelling for it would be accepting a promise this build cannot keep.
1748            // Before `-fno-` is looked at below, for the reason the tier is.
1749            "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1750            "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1751            _ if arg.starts_with("-fsafety-subobject=") => {
1752                let form = &arg["-fsafety-subobject=".len()..];
1753                return Err(err(format!(
1754                    "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1755                     the strict form of section 9.4 is tamnd/rucc#967"
1756                )));
1757            }
1758            // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1759            // the one above has none: there is one form of this check and a spelling that suggested
1760            // otherwise would be promising something. Before `-fno-` is looked at below, the same
1761            // way.
1762            "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1763            "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1764            _ if arg.starts_with("-fsafety-restrict=") => {
1765                let form = &arg["-fsafety-restrict=".len()..];
1766                return Err(err(format!(
1767                    "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1768                )));
1769            }
1770            // Section 9.5's races, which take a value because the section gives them three modes
1771            // and the difference between two of them is which classes get reported rather than how
1772            // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1773            // reason the two above spell theirs out.
1774            _ if arg.starts_with("-fsafety-races=") => {
1775                let mode = &arg["-fsafety-races=".len()..];
1776                opts.races = mode.parse().map_err(|()| {
1777                    err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1778                })?;
1779            }
1780            "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1781            // The sanitizers of document 12, which are checks at run time rather than a way of
1782            // generating the same program. Each name is held to gcc 16's list, and what is still
1783            // asked for by the end of the line is answered after the loop, so that a command line
1784            // which turns one on and then off again is a command line that asked for nothing.
1785            //
1786            // Before the optimizer's `-f` family below, for the reason the tier above it is.
1787            _ if arg.starts_with("-fsanitize=") => {
1788                for one in arg["-fsanitize=".len()..].split(',') {
1789                    if one == "all" {
1790                        // gcc takes `all` only in the negative, because turning every check on at
1791                        // once includes checks that contradict each other.
1792                        return Err(err(
1793                            "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1794                        ));
1795                    }
1796                    if !SANITIZERS.contains(&one) {
1797                        return Err(err(format!(
1798                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1799                        )));
1800                    }
1801                    if !sanitizers.contains(&one) {
1802                        sanitizers.push(one);
1803                    }
1804                }
1805            }
1806            _ if arg.starts_with("-fno-sanitize=") => {
1807                for one in arg["-fno-sanitize=".len()..].split(',') {
1808                    if one == "all" {
1809                        sanitizers.clear();
1810                        continue;
1811                    }
1812                    if !SANITIZERS.contains(&one) {
1813                        return Err(err(format!(
1814                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1815                        )));
1816                    }
1817                    sanitizers.retain(|asked| *asked != one);
1818                }
1819            }
1820            // What a check does when it fires, and where the records about the checked objects go.
1821            // Each of them is an answer about the sanitizers refused after the loop, so there is
1822            // nothing left for them to change here. The names are still held to the list, because
1823            // a misspelling in a build's flags is worth finding when the compiler reads it.
1824            _ if arg.starts_with("-fsanitize-recover=")
1825                || arg.starts_with("-fno-sanitize-recover=")
1826                || arg.starts_with("-fsanitize-trap=")
1827                || arg.starts_with("-fno-sanitize-trap=") =>
1828            {
1829                // The guard above matched on a spelling that has an `=` in it, so the tail is
1830                // whatever follows the first one.
1831                let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1832                for one in how.split(',') {
1833                    if one != "all" && !SANITIZERS.contains(&one) {
1834                        return Err(err(format!(
1835                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1836                        )));
1837                    }
1838                }
1839            }
1840            "-fsanitize-undefined-trap-on-error"
1841            | "-fsanitize-address-use-after-scope"
1842            | "-fno-sanitize-address-use-after-scope" => {}
1843            _ if arg.starts_with("-fsanitize-sections=") => {}
1844            // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1845            // keeping. Refused rather than dropped, because a fuzzer whose calls into
1846            // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1847            // and there is no point in the campaign where that announces itself.
1848            _ if arg.starts_with("-fsanitize-coverage=") => {
1849                let how = &arg["-fsanitize-coverage=".len()..];
1850                for one in how.split(',') {
1851                    if !matches!(one, "trace-pc" | "trace-cmp") {
1852                        return Err(err(format!(
1853                            "`{one}` is not a coverage instrumentation, which is trace-pc or \
1854                             trace-cmp"
1855                        )));
1856                    }
1857                }
1858                return Err(err(format!(
1859                    "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1860                     with it would run without any feedback at all, see \
1861                     spec/04-driver-and-cli.md section 4.7"
1862                )));
1863            }
1864            // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1865            // after every `-f` the rest of the compiler answers to, so a pass can never take a
1866            // name that already means something else on the command line.
1867            _ if arg.starts_with("-fpass-fuel=") => {
1868                let (name, count) = arg["-fpass-fuel=".len()..]
1869                    .split_once('=')
1870                    .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1871                if rucc_opt::pass::find(name).is_none() {
1872                    return Err(err(format!(
1873                        "`{name}` is not a pass this compiler has, see --print-pipeline"
1874                    )));
1875                }
1876                let count: u32 = count
1877                    .parse()
1878                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1879                opts.pass_fuel.push((name.to_owned(), count));
1880            }
1881            _ if arg.starts_with("-fpass-fuel-global=") => {
1882                let count = &arg["-fpass-fuel-global=".len()..];
1883                let count: u32 = count
1884                    .parse()
1885                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1886                opts.pass_fuel_global = Some(count);
1887            }
1888            _ if arg.starts_with("-frucc-trace=") => {
1889                let path = &arg["-frucc-trace=".len()..];
1890                if path.is_empty() {
1891                    return Err(err("-frucc-trace= needs a file to write to"));
1892                }
1893                opts.trace = Some(path.to_owned());
1894            }
1895            // Everything from `-fopt-info` to the end of the argument, which is optional
1896            // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1897            // where the remarks are printed, because by then the compilation somebody wanted
1898            // to hear about is over.
1899            _ if arg == "-fopt-info"
1900                || arg.starts_with("-fopt-info=")
1901                || arg.starts_with("-fopt-info-") =>
1902            {
1903                let rest = &arg["-fopt-info".len()..];
1904                let (kinds, file) = match rest.split_once('=') {
1905                    Some((kinds, file)) => (kinds, Some(file)),
1906                    None => (rest, None),
1907                };
1908                let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1909                rucc_opt::Wants::none().add(kinds).map_err(err)?;
1910                opts.opt_info.push(kinds.to_owned());
1911                if let Some(file) = file {
1912                    if file.is_empty() {
1913                        return Err(err("-fopt-info= was given no file to write to"));
1914                    }
1915                    opts.opt_info_file = Some(file.to_owned());
1916                }
1917            }
1918            _ if arg.starts_with("-fdump-ir=") => {
1919                // Checked here rather than where the dumps are taken, because the compilation
1920                // that would have been dumped is over by then.
1921                let spec = &arg["-fdump-ir=".len()..];
1922                rucc_opt::Dumps::default().add(spec).map_err(err)?;
1923                opts.dump_ir.push(spec.to_owned());
1924            }
1925            // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1926            // otherwise take the flag away from the gate. Checked here rather than where the
1927            // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1928            // name that quietly gated nothing looks exactly like a pass that is not the guilty
1929            // one, and a bisection would carry on past the thing it was looking for.
1930            _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1931                let on = arg.starts_with("-fenable-");
1932                let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1933                rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1934                opts.pass_gates.push((on, spec.to_owned()));
1935            }
1936            // gcc's spelling for a pass this compiler has under a shorter name. It goes above the
1937            // two arms below rather than into the pile of gcc pass names further down, because the
1938            // pass is here: dropping the flag would leave a build that asked for unrolling without
1939            // it, and refusing it stops the build outright, which is what libtommath's makefile
1940            // ran into. `-funroll-all-loops` is deliberately not in here: gcc's is the one that
1941            // unrolls without a trip count, which is a different and usually worse thing.
1942            "-funroll-loops" => opts.passes.push(("unroll".to_owned(), true)),
1943            "-fno-unroll-loops" => opts.passes.push(("unroll".to_owned(), false)),
1944            // Here rather than through the two arms below, because what this names is not a
1945            // `rucc_opt::Pass`. Section 34.6's propagation is a module at a time and everything in
1946            // the pass list is one function at a time. `-fipa-cp-clone` is deliberately not here:
1947            // gcc turns that one on at `-O3` and it is in the list of what M4 does not build.
1948            "-fipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), true)),
1949            "-fno-ipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), false)),
1950            // The other half of the same section, here for the same reason, and `-fipa-sra` in gcc
1951            // is the aggregate splitting as well as the parameter removal. Asking for it gets the
1952            // half that is built.
1953            "-fipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), true)),
1954            "-fno-ipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), false)),
1955            // And the printf family fold, which is a module at a time for the same reason and so is
1956            // not a `rucc_opt::Pass` either. gcc has no flag of its own for this one, since
1957            // `-fno-builtin` already turns it off along with everything else the standard names
1958            // mean. This spelling is for taking one thing away during a bisection without taking
1959            // the rest of section 20.1 away with it.
1960            "-flibcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), true)),
1961            "-fno-libcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), false)),
1962            _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1963                opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1964            }
1965            _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1966                opts.passes.push((arg["-f".len()..].to_owned(), true));
1967            }
1968            // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1969            // program reduced from a miscompilation usually names the pass that miscompiled it on
1970            // its `dg-options` line, and they arrive from hand written build files for the same
1971            // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1972            // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1973            // for a compiler that does not exist here, and the program it is attached to is a
1974            // correctness test that passes either way. Turning on a pass we do not have costs
1975            // speed, turning off a pass we do not have costs nothing, and neither changes what the
1976            // program computes.
1977            //
1978            // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1979            // compiler has rather than landing here, and the day one of these names becomes a pass
1980            // here it stops being taken and dropped without anybody editing this list.
1981            //
1982            // Two of them are prefixes rather than names, which is the one place this file takes a
1983            // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1984            // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1985            // nothing else, and there is no member of either that changes the meaning of a program
1986            // that was already correct. The rest are written out one at a time, because they live
1987            // in the flat `-f` namespace where the neighbours do change meanings.
1988            _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1989            _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1990            "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1991            "-fmodulo-sched" | "-fno-modulo-sched" => {}
1992            "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1993            _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1994            }
1995            "-fearly-inlining" | "-fno-early-inlining" => {}
1996            // The one of the family that does reach the optimizer, since the step it names is built:
1997            // `-fno-inline` stops a function declared `inline` from being inlined and leaves
1998            // `always_inline` alone, which is what it does in gcc.
1999            "-finline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), true)),
2000            "-fno-inline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), false)),
2001            // The called once half of the same step, on its own, which leaves the `inline` hint and
2002            // `always_inline` as they are. tamnd/rucc#1966.
2003            "-finline-functions-called-once" => {
2004                opts.passes.push((rucc_opt::inline::ONCE.to_owned(), true));
2005            }
2006            "-fno-inline-functions-called-once" => {
2007                opts.passes.push((rucc_opt::inline::ONCE.to_owned(), false));
2008            }
2009            "-finline-functions"
2010            | "-fno-inline-functions"
2011            | "-finline-small-functions"
2012            | "-fno-inline-small-functions" => {}
2013            "-foptimize-strlen" | "-fno-optimize-strlen" => {}
2014            "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
2015            // Where a function starts, which is a thing this compiler already decides and so is a
2016            // request it can answer rather than one it has to drop. The bare form asks for the
2017            // target's default and the default here is the sixteen bytes gcc also gives, so it
2018            // says nothing; a number is a floor under every function that did not ask for more
2019            // itself; and the negative form asks for the smallest boundary the target has. gcc 16
2020            // rounds a number that is not a power of two up rather than refusing it, which is what
2021            // `=3` giving `.p2align 2` on x86-64 means, so this rounds too.
2022            "-falign-functions" => opts.align_functions = None,
2023            "-fno-align-functions" => opts.align_functions = Some(MIN_FUNC_ALIGN),
2024            _ if arg.starts_with("-falign-functions=") => {
2025                opts.align_functions = function_alignment(&arg["-falign-functions=".len()..])
2026                    .ok_or_else(|| {
2027                        err(format!("{arg}: the alignment has to be a number of bytes"))
2028                    })?;
2029            }
2030            // The head of every hot loop, which is padded when this is asked for so that a loop that
2031            // fits in a 64 byte line does not cross one. Both directions of the plain form are
2032            // answered. A number is taken and says nothing, because the boundary here is the
2033            // line's and a build that names another is asking for speed rather than for a
2034            // different program.
2035            "-falign-loops" => opts.align_loops = Some(true),
2036            "-fno-align-loops" => opts.align_loops = Some(false),
2037            // The other two of the family, which are about padding in front of any label and in
2038            // front of a label only a jump reaches. This compiler writes neither, and what they
2039            // ask for is speed: a label on a boundary computes what a label off one computes. So
2040            // they are taken and dropped for the reason `-march=` is, and the numbered form of
2041            // the loop flag with them.
2042            _ if arg.starts_with("-falign-labels")
2043                || arg.starts_with("-falign-loops=")
2044                || arg.starts_with("-falign-jumps")
2045                || arg.starts_with("-fno-align-labels")
2046                || arg.starts_with("-fno-align-jumps") => {}
2047            // The charset flags are not in that pile, because an encoding is a statement about
2048            // what the bytes of the source mean rather than about how fast the output is. The
2049            // preprocessor reads UTF-8 and has no converter, so the one name that describes what
2050            // already happens is taken and every other name is refused. Spelled without regard to
2051            // case and with both of the spellings iconv answers to, since a build writes whichever
2052            // one its author typed.
2053            _ if arg.starts_with("-finput-charset=") => {
2054                let name = &arg["-finput-charset=".len()..];
2055                if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
2056                    return Err(err(format!(
2057                        "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
2058                         converter, so a file in another encoding would be read as though it were \
2059                         UTF-8 rather than converted",
2060                    )));
2061                }
2062            }
2063            // What C has of exceptions, which is a `cleanup` handler an unwind has to run and the
2064            // `__EXCEPTIONS` that tells a header so. The walk is what turns down the handler it has
2065            // no landing pad for, so a unit with none of them is taken whole.
2066            "-fexceptions" => exceptions = Some(true),
2067            "-fno-exceptions" => exceptions = Some(false),
2068            "-fnon-call-exceptions" => opts.non_call_exceptions = true,
2069            "-fno-non-call-exceptions" => opts.non_call_exceptions = false,
2070            // Whether an instruction that could raise one may still be deleted when nothing uses
2071            // what it computes. Nothing here keeps a dead one, and neither does gcc in a C unit
2072            // with no handler around it, so both spellings describe the code as it is.
2073            "-fdelete-dead-exceptions" | "-fno-delete-dead-exceptions" => {}
2074            "-finstrument-functions" => opts.instrument_functions = true,
2075            "-fno-instrument-functions" => opts.instrument_functions = false,
2076            // The unstable options, spelled the way rustc spells them and carrying the same
2077            // promise, which is none: one of these may change or go away in any release. They are
2078            // measurements and debugging aids rather than things a build asks for, which is why
2079            // none of them is in the usage text and all of them are in section 4.11 of
2080            // `spec/04-driver-and-cli.md`.
2081            "-Zverify-each" => opts.verify_each = true,
2082            _ if arg.starts_with("-Zrule-coverage=") => {
2083                let file = &arg["-Zrule-coverage=".len()..];
2084                if file.is_empty() {
2085                    return Err(err("-Zrule-coverage= needs a file to write to"));
2086                }
2087                opts.rule_coverage = Some(file.to_owned());
2088            }
2089            _ if arg.starts_with("-Zcycle-accurate-model=") => {
2090                let value = &arg["-Zcycle-accurate-model=".len()..];
2091                opts.cycle_accurate_model = match value {
2092                    "yes" | "1" => Some(true),
2093                    "no" | "0" => Some(false),
2094                    _ => {
2095                        return Err(err("-Zcycle-accurate-model= takes yes or no"));
2096                    }
2097                };
2098            }
2099            _ if arg.starts_with("-Zregalloc=") => {
2100                opts.backtracking = match &arg["-Zregalloc=".len()..] {
2101                    "backtracking" => Some(true),
2102                    "single" => Some(false),
2103                    _ => return Err(err("-Zregalloc= takes backtracking or single")),
2104                };
2105            }
2106            _ if arg.starts_with("-Zswitch=") => {
2107                let shape = &arg["-Zswitch=".len()..];
2108                if rucc_codegen::switch::Force::named(shape).is_none() {
2109                    return Err(err("-Zswitch= takes table, tree or walk"));
2110                }
2111                opts.switch_shape = Some(shape.to_owned());
2112            }
2113            _ if arg.starts_with("-Zlowering=") => {
2114                let file = &arg["-Zlowering=".len()..];
2115                if file.is_empty() {
2116                    return Err(err("-Zlowering= needs a file to write to"));
2117                }
2118                opts.lowering_dump = Some(file.to_owned());
2119            }
2120            _ if arg.starts_with("-Zregister-pressure=") => {
2121                let file = &arg["-Zregister-pressure=".len()..];
2122                if file.is_empty() {
2123                    return Err(err("-Zregister-pressure= needs a file to write to"));
2124                }
2125                opts.register_pressure = Some(file.to_owned());
2126            }
2127            _ if arg.starts_with("-Z") => {
2128                return Err(err(format!(
2129                    "`{arg}` is not an unstable option this compiler has, see \
2130                     spec/04-driver-and-cli.md section 4.11 for the ones it does"
2131                )));
2132            }
2133            // The word size, which is a statement about the target and is taken as one. A build
2134            // that says the size the target already has is saying nothing, and one that says the
2135            // other size is asking for a target this compiler does not have, which it is told
2136            // rather than being given the wrong one.
2137            "-m64" | "-m32" | "-mx32" => {
2138                let want: u32 = match arg {
2139                    "-m64" => 64,
2140                    _ => 32,
2141                };
2142                let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
2143                if have != want {
2144                    return Err(err(format!(
2145                        "{arg} asks for a {want} bit target and {} is {have} bit, use \
2146                         --target= to name the one you mean",
2147                        opts.target
2148                    )));
2149                }
2150            }
2151            // One extension of the x86-64 instruction set, on or off, which is `-msse4.2` and its
2152            // relatives. Only the ones this compiler has the intrinsics for may be turned on for a
2153            // whole unit, because what turning one on does here is define the macro, and a macro
2154            // is a promise to a header that the names behind it exist. Turning one off is taken
2155            // for any name gcc knows, since nothing is promised by it, except for the baseline:
2156            // SSE2 is where the psABI passes a `double`, so a unit without it is a different
2157            // calling convention and not a smaller instruction set.
2158            _ if isa_name(arg).is_some() => {
2159                let Some((_, feature, on)) = isa_name(arg) else { continue };
2160                if on && !feature.honoured() {
2161                    return Err(err(format!(
2162                        "{arg}: this compiler has no intrinsics for {} yet, so it cannot build a \
2163                         whole unit for it",
2164                        feature.name()
2165                    )));
2166                }
2167                if !on && rucc_target::Isa::baseline().has(feature) {
2168                    return Err(err(format!(
2169                        "{arg}: {} is part of the x86-64 baseline and the psABI passes values in \
2170                         it, so a unit built without it would call and be called differently",
2171                        feature.name()
2172                    )));
2173                }
2174                isa.read(&arg["-m".len()..]).map_err(|_| err(format!("unknown option `{arg}`")))?;
2175                isa_flag.get_or_insert(arg);
2176            }
2177            // Which processor in the family to build for. What it decides is the extensions of
2178            // the instruction set the unit may assume, which is the macros, on x86-64 and, for
2179            // the CRC32 extension alone, on AArch64; see `rucc_target::isa`. A processor it has
2180            // no list for is built for as the baseline, which is a program that could have been
2181            // faster rather than a program that is wrong, and the same goes for every other
2182            // target's processors. `-mtune=` says what to schedule for and changes nothing a
2183            // program can see.
2184            _ if arg.starts_with("-march=") => march = Some(&arg["-march=".len()..]),
2185            _ if arg.starts_with("-mtune=") || arg.starts_with("-mcpu=") => {}
2186            // The calling convention, which is not safe to ignore. Taken when it names the one
2187            // the target already uses and refused otherwise.
2188            _ if arg.starts_with("-mabi=") => {
2189                let want = &arg["-mabi=".len()..];
2190                let have = match opts.target.arch {
2191                    rucc_target::Arch::X86_64 => "sysv",
2192                    rucc_target::Arch::Aarch64 => "lp64",
2193                    rucc_target::Arch::Riscv64 => "lp64d",
2194                };
2195                if want != have {
2196                    return Err(err(format!(
2197                        "{arg}: {} uses the {have} convention and this compiler has no other",
2198                        opts.target
2199                    )));
2200                }
2201            }
2202            // How far apart the pieces of the program may be. The small model is what we emit and
2203            // it is every hosted program's default; the kernel model is a different one and a
2204            // build that asks for it and does not get it links and then does not run.
2205            "-mcmodel=small" => {}
2206            // clang's spellings of the deployment target, which it takes over a version in the
2207            // tuple. gcc on a Mac takes the first. A target that is not Apple ignores it, as
2208            // clang does, so a makefile that always passes it still builds for Linux.
2209            _ if arg.starts_with("-mmacosx-version-min=")
2210                || arg.starts_with("-mmacos-version-min=") =>
2211            {
2212                let text = &arg[arg.find('=').map_or(arg.len(), |i| i + 1)..];
2213                let version = rucc_tuple::Version::parse(text)
2214                    .ok_or_else(|| err(format!("`{text}` in `{arg}` is not a version")))?;
2215                min_version = Some(version);
2216            }
2217            _ if arg.starts_with("-mcmodel=") => {
2218                return Err(err(format!(
2219                    "{arg}: this compiler emits the small code model and no other, see \
2220                     spec/12-targets.md"
2221                )));
2222            }
2223            // GCC's own scripting language for how the driver builds a command line.
2224            // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
2225            // build reaching for it is told which flags do the same job.
2226            _ if arg.starts_with("-specs=") => {
2227                return Err(err(
2228                    "-specs= is not supported: the parts of it builds rely on are -B, -L, \
2229                     -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
2230                     section 4.4",
2231                ));
2232            }
2233            // Arguments meant for a separate assembler, which this compiler does not have: it is
2234            // inside it and does not read a command line. Refused rather than dropped, because
2235            // every one of these says something about the output and a build that asked for
2236            // `-Wa,--noexecstack` and was silently given an executable stack got the opposite of
2237            // what it asked for. The `-Wp,` ones this compiler understands were turned into its
2238            // own flags before the loop, so one that reaches here is one it does not.
2239            _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
2240                return Err(err(format!(
2241                    "`{arg}` is an argument for a separate assembler or preprocessor, and both \
2242                     are inside this compiler rather than programs it runs"
2243                )));
2244            }
2245            "-Xassembler" | "-Xpreprocessor" => {
2246                return Err(err(format!(
2247                    "{arg} hands an argument to a separate assembler or preprocessor, and both \
2248                     are inside this compiler rather than programs it runs"
2249                )));
2250            }
2251            // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
2252            // this one as a rule about build systems rather than about warnings: autoconf and
2253            // meson find out whether a warning flag exists by passing it and looking at the exit
2254            // status, so the answer has to be gcc's. A name gcc knows is accepted, and one it does
2255            // not is refused, the way gcc refuses clang's names. `-Wno-` of a name nobody knows is
2256            // accepted, because gcc accepts it too, but `-Werror=` and `-Wno-error=` of one are
2257            // not. None of them turns anything on yet, which #485 is about.
2258            _ if arg.starts_with("-W") => {
2259                let name = &arg["-W".len()..];
2260                let named = name.strip_prefix("error=").or_else(|| name.strip_prefix("no-error="));
2261                if let Some(named) = named {
2262                    if !warnings::known(named) {
2263                        return Err(err(format!("`{arg}`: no option `-W{named}`")));
2264                    }
2265                } else if !name.is_empty() && !name.starts_with("no-") && !warnings::known(name) {
2266                    return Err(err(format!("unknown option `{arg}`")));
2267                }
2268            }
2269            // Flags that name something this compiler does not do and would not do differently
2270            // if it did. `-fno-ident` is about a comment in the output that we do not write
2271            // either way, and the others are about a way of ordering the compilation that has
2272            // been GCC's only way for twenty years. `-mthreads` is mingw's, and what it links is
2273            // `libmingwthrd.a`, which mingw-w64 keeps as an empty archive because its CRT does the
2274            // thread cleanup for every program. Section 4.1 asks for the list to be short and for
2275            // adding to it to be deliberate, which is why it is written out here.
2276            "-fno-ident"
2277            | "-fident"
2278            | "-funit-at-a-time"
2279            | "-fno-unit-at-a-time"
2280            | "-shared-libgcc"
2281            | "-static-libgcc"
2282            | "-mthreads"
2283            | "-fpch-deps"
2284            | "-fno-pch-deps" => {}
2285            _ if arg.starts_with('-') && arg.len() > 1 => {
2286                // Silently ignoring an unknown flag is how a build ends up not doing what
2287                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
2288                // for the flags that change code generation, and the safe default until the
2289                // flag table is populated is to reject everything we do not know.
2290                return Err(err(format!("unknown option `{arg}`")));
2291            }
2292            _ => inputs.push(Input { path: arg.to_owned(), forced, role: Role::File }),
2293        }
2294    }
2295
2296    // The fetch, before anything that resolves a compilation, because `--fetch` does not describe
2297    // one. It is here rather than in the loop so that `--offline` can forbid it whichever order the
2298    // two were written in, and it is before the refusals below so that a command line asking for a
2299    // sysroot is not told about a sanitizer.
2300    if let Some(named) = fetch {
2301        if fetch_msvc.is_some() {
2302            return Err(err(
2303                "--fetch and --fetch-msvc-sdk are two different commands and this command line \
2304                 asked for both. --fetch gets what this release pins by URL and by hash, which for \
2305                 a *-windows-msvc target is one Visual Studio build, and --fetch-msvc-sdk gets the \
2306                 build Microsoft's channel names today. Run whichever one you meant",
2307            ));
2308        }
2309        return fetch_action(&named, offline, accepted, &inputs);
2310    }
2311    if let Some(named) = fetch_msvc {
2312        return fetch_msvc_action(&named, offline, accepted, &inputs);
2313    }
2314    if accepted {
2315        return Err(err(
2316            "--accept-licence says that Microsoft's Visual Studio Build Tools licence is accepted, \
2317             and nothing on this command line asked for anything that licence covers. \
2318             --fetch <tuple> or --fetch-msvc-sdk <tuple> for a *-windows-msvc target is the \
2319             command it belongs to, and an ordinary compile downloads nothing with it or \
2320             without it",
2321        ));
2322    }
2323
2324    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
2325    // order: a directory the user names outranks the compiler's own, and the compiler's own
2326    // outranks the library's. It is pushed after the loop rather than before it because
2327    // `SearchPath` appends within a group and the position is what the order is.
2328    // The same directory the headers were looked for under, because a sysroot is a statement
2329    // about a whole installation and not about half of one.
2330    // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
2331    // command line that turns a check on and off again has asked for nothing. What is left is
2332    // refused rather than dropped, and it is the one place in this parser where the reason is not
2333    // that the output would differ. A sanitizer is a promise that the program is watched while it
2334    // runs, so a build that asks for one and is quietly given a program with no checks in it does
2335    // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
2336    // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
2337    // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
2338    // options.
2339    if let Some(first) = sanitizers.first() {
2340        return Err(err(format!(
2341            "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
2342             asked for one and got none would run its tests unchecked, see \
2343             spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
2344             compiler does have"
2345        )));
2346    }
2347    // The fast math family, replayed in order on top of what `-Ofast` implies. The startup file is
2348    // gcc's spec rather than the fields: it is linked when `-Ofast`, `-ffast-math` or
2349    // `-funsafe-math-optimizations` is still in force at the end of the line, whatever a later
2350    // member took back, and `-mdaz-ftz` decides it outright.
2351    let mut math = Math::default();
2352    let mut trapping = if ofast { math.set_fast(true) } else { true };
2353    for flag in &math_flags {
2354        match *flag {
2355            "-ftrapping-math" => trapping = true,
2356            "-fno-trapping-math" => trapping = false,
2357            "-ffast-math" => trapping = math.set_fast(true),
2358            "-fno-fast-math" => trapping = math.set_fast(false),
2359            "-funsafe-math-optimizations" => trapping = math.set_unsafe(true),
2360            "-fno-unsafe-math-optimizations" => trapping = math.set_unsafe(false),
2361            "-fmath-errno" => math.errno = true,
2362            "-fno-math-errno" => math.errno = false,
2363            "-ffinite-math-only" => math.finite_only = true,
2364            "-fno-finite-math-only" => math.finite_only = false,
2365            "-fsigned-zeros" => math.signed_zeros = true,
2366            "-fno-signed-zeros" => math.signed_zeros = false,
2367            "-freciprocal-math" => math.reciprocal = true,
2368            "-fno-reciprocal-math" => math.reciprocal = false,
2369            "-fassociative-math" => math.associative = true,
2370            "-fno-associative-math" => math.associative = false,
2371            _ => unreachable!("{flag} is not in the family"),
2372        }
2373    }
2374    opts.trapping_math = trapping;
2375    opts.math = math;
2376    let last = |on: &str, off: &str| {
2377        math_flags.iter().rev().find(|f| **f == on || **f == off).is_some_and(|f| *f == on)
2378    };
2379    link.fast_math = ofast
2380        || last("-ffast-math", "-fno-fast-math")
2381        || last("-funsafe-math-optimizations", "-fno-unsafe-math-optimizations");
2382    link.daz_ftz = daz_ftz;
2383    // The extensions, now that the target is known. On x86-64 the processor supplies whatever no
2384    // flag said. On AArch64 `-march=` alone says them, with its `+crc` and the rest, and nowhere
2385    // else is there any to have. Off x86-64 a flag naming one of its extensions is gcc's unknown
2386    // option too, so it is refused the same way it would have been had it not looked like an x86
2387    // flag.
2388    match opts.target.arch {
2389        rucc_target::Arch::X86_64 => {
2390            let base = match march {
2391                Some("native") => native_isa(),
2392                Some(name) => {
2393                    rucc_target::Isa::level(name).unwrap_or_else(rucc_target::Isa::baseline)
2394                }
2395                None => rucc_target::Isa::baseline(),
2396            };
2397            opts.isa = isa.over(base);
2398        }
2399        rucc_target::Arch::Aarch64 | rucc_target::Arch::Riscv64 => {
2400            if let Some(flag) = isa_flag {
2401                return Err(err(format!("unknown option `{flag}`")));
2402            }
2403            opts.isa = match (opts.target.arch, march) {
2404                (rucc_target::Arch::Aarch64, Some(name)) => match name.strip_prefix("native") {
2405                    Some(modifiers) => native_aarch64().aarch64_modifiers(modifiers),
2406                    None => rucc_target::Isa::aarch64_march(name),
2407                },
2408                _ => rucc_target::Isa::NONE,
2409            };
2410        }
2411    }
2412    opts.exceptions = exceptions.unwrap_or(opts.non_call_exceptions);
2413    link.sysroot = sysroot.clone();
2414    // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
2415    // inside the link line, because a link line that read the environment could only be tested on a
2416    // machine whose environment said the right thing, and the link line is the last thing that
2417    // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
2418    link.cache = Some(cache::dir());
2419    // And where a distribution's cross packages would have put a tree for the target, which is only
2420    // read when the target is not this machine and there is no sysroot of ours for it.
2421    link.usr = Some(PathBuf::from("/usr"));
2422    // And the ten field spelling of the target, because the release on it decides two things the
2423    // three field one cannot say: whether a target that is this architecture is still a cross
2424    // compile, and which directory under the cache it is against. After the loop because the last
2425    // `--target=` on the command line is the one that counts.
2426    link.pinned = pinned;
2427    // The deployment target, from the flag if there was one and from the tuple otherwise. Only an
2428    // Apple platform has one: anywhere else a version on the tuple is a libc or a preview number.
2429    if opts.target.os == rucc_target::Os::Darwin {
2430        opts.os_version = min_version.or_else(|| pinned.and_then(TargetTuple::os_version));
2431        link.os_version = opts.os_version;
2432    }
2433    // After the loop rather than where `-pthread` was read, so that it lands after the objects
2434    // that refer to it. A static link takes the definitions it needs from a library when it
2435    // reaches it and not afterwards, so a library before the objects is a library that answers
2436    // nothing.
2437    if threads {
2438        inputs.push(Input::library("pthread"));
2439    }
2440    if let Some(query) = query {
2441        return Ok(Action::Print(answer(&query, &opts, &link)?));
2442    }
2443    // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
2444    // else the command line asked for. Read here rather than where the flag was, because a `-c`
2445    // written after it has to lose and the loop cannot know that until it has ended. The output
2446    // file is where the rule goes rather than where an object would have gone, and the last
2447    // phase being the preprocessor is what makes that true without a second rule for it.
2448    if opts.deps.instead_of_compiling {
2449        opts.emit = EmitKind::Preprocessed;
2450    }
2451    if !nostdinc {
2452        opts.search.push_system(runtime::DIR);
2453        // And the library's after ours, which is the other half of the same order. They go on
2454        // here rather than at the point `--target=` or `--sysroot=` was read because either
2455        // one changes the answer and the last word on both is the end of the loop.
2456        //
2457        // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
2458        // that the headers and the libraries come from the same place. A target that is this
2459        // machine reads this machine's headers, and a target that is not reads the ones in the
2460        // sysroot for it rather than the ones next door.
2461        let cross = link::cross_sysroot(opts.target, &link);
2462        let kernel = link::cross_kernel(opts.target, &link);
2463        let distro = link::distro_cross(opts.target, &link);
2464        // And the version of those headers, which only the bundled tree has an answer for. A host
2465        // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
2466        // and a second definition with a different value is a warning on every file, so the
2467        // condition is the same one that chose the directories.
2468        if cross.is_some() {
2469            let target = pinned.unwrap_or_else(|| opts.target.tuple());
2470            opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
2471                err(format!(
2472                    "{skew}; pin a release the tree has, or name a tree that has that one \
2473                     with --sysroot"
2474                ))
2475            })?;
2476        }
2477        let system = library::header_dirs(
2478            opts.target,
2479            sysroot.as_deref(),
2480            cross.as_ref(),
2481            kernel.as_ref(),
2482            distro.as_ref(),
2483        );
2484        // The two licence walls of `spec/cross-compile/13-distribution.md` section 13.4, which are
2485        // the only way step 3 comes back with nothing on a hosted target. Section 8.6 asks for the
2486        // answer to name the licence and the lawful ways to get what is behind it, rather than
2487        // leaving a person with an `#include` that failed as though a directory had gone missing.
2488        //
2489        // It is left on the search path instead of refused here, because a program that includes
2490        // none of the library needs none of the SDK and section 8.6 is explicit that targeting the
2491        // platform has to keep working. So the reason waits until an include has actually failed,
2492        // which is the only moment it helps and the only moment it is true.
2493        //
2494        // The condition is that step 3 found nothing at all, so an `SDKROOT`, an `INCLUDE` or a mac
2495        // with Xcode on it all pass through untouched, and `-nostdinc` never reaches this block. A
2496        // `--sysroot` or `-isysroot` passes through as well, even when the tree it names turns out to
2497        // be empty or absent: somebody who wrote a path has already answered the question this
2498        // message asks, and answering it again over the top of a mistyped directory would hide the
2499        // mistake behind a licence notice.
2500        if system.is_empty() && sysroot.is_none() {
2501            let tuple = pinned.unwrap_or_else(|| opts.target.tuple());
2502            if let Some(wall) = rucc_sysroot::Wall::of(tuple) {
2503                opts.search.explain_missing_system(wall.no_headers(&tuple.to_canonical_string()));
2504            }
2505        }
2506        // And whether the tree somebody named is the release they asked for, which is the one
2507        // question left once the directories are settled and the only place both halves of it are
2508        // known. Only for a named tree, because that is the case where the release in the target
2509        // stops deciding anything, and `crate::glibc` is where the rest of the reasoning is.
2510        if sysroot.is_some() {
2511            notes.extend(glibc::skew(opts.target, pinned, &system));
2512        }
2513        for dir in system {
2514            opts.search.push_system(dir);
2515        }
2516    }
2517    // Once, here, rather than as each directory is pushed. A `-I` that names a system
2518    // directory has to lose to the system entry and the system entry is added last, so the
2519    // question cannot be answered until the whole path is known.
2520    opts.search.remove_duplicates();
2521
2522    // The target has to be resolved before the configuration is printed, so this check comes
2523    // after the loop rather than at the point `--print-config` was seen.
2524    if print_config {
2525        return Ok(Action::PrintConfig(Box::new(opts)));
2526    }
2527    if print_pipeline {
2528        return Ok(Action::PrintPipeline(Box::new(opts)));
2529    }
2530    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
2531    if print_plan {
2532        return Ok(Action::PrintPlan {
2533            opts: Box::new(opts),
2534            plan: Box::new(plan),
2535            link: Box::new(link),
2536        });
2537    }
2538    Ok(Action::Compile {
2539        opts: Box::new(opts),
2540        plan: Box::new(plan),
2541        link: Box::new(link),
2542        jobs,
2543        verbose,
2544        notes,
2545    })
2546}
2547
2548/// What `--fetch <tuple>` asked for, or why it is not a thing that can be done.
2549///
2550/// The lookup happens here rather than at the point the bytes would move, so that a target this
2551/// release pins nothing for is a refusal from the parser and the only code that runs a downloader is
2552/// code that already knows what it is getting.
2553///
2554/// # Errors
2555///
2556/// [`CliError`] when `--offline` forbade it, when there are input files as well, when the tuple is
2557/// not a target this compiler knows, when its sysroot is behind Apple's licence wall, and when this
2558/// release pins no artifact for it.
2559fn fetch_action(
2560    named: &str,
2561    offline: bool,
2562    accepted: bool,
2563    inputs: &[Input],
2564) -> Result<Action, CliError> {
2565    // Not a precedence question. Section 13.2 says `--offline` forbids a fetch entirely, so a
2566    // command line that writes both has asked for two opposite things and the answer is to say so
2567    // rather than to pick one of them.
2568    if offline {
2569        return Err(err(
2570            "--fetch asks for a download and --offline forbids every download, so this command \
2571             line asks for two opposite things. Drop one of them: --offline is how a build says it \
2572             will not reach the network, and --fetch is one of the two things in this compiler \
2573             that reaches it",
2574        ));
2575    }
2576    if let Some(first) = inputs.first() {
2577        return Err(err(format!(
2578            "--fetch gets a sysroot and compiles nothing, so `{}` on the same command line is an \
2579             input that nothing would read",
2580            first.path
2581        )));
2582    }
2583    let target: TargetTuple = named
2584        .parse()
2585        .map_err(|why| err(format!("--fetch {named}: {why}, so there is no sysroot to get")))?;
2586    // The canonical spelling, because that is what a row is named by and what the directory under
2587    // the cache is called, and a person is free to write a tuple the long way round.
2588    let tuple = target.to_canonical_string();
2589    // Microsoft's side of the wall has something to fetch after all, which is the files its own
2590    // installer would fetch, from the build this release pins and only once the licence has been
2591    // accepted. Nothing of it is ours and nothing of it comes from us, which is why it is the other
2592    // action with a flag on it rather than a row in the table.
2593    if rucc_sysroot::Wall::of(target) == Some(rucc_sysroot::Wall::Microsoft) {
2594        return Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir(), pinned: true });
2595    }
2596    // Before the table is consulted, because a target behind a licence wall is not a row that has not
2597    // been written yet. Section 13.4 is that no release pins one of these ever, so the message says
2598    // the licence and the two lawful ways rather than naming the producer that will publish the rest.
2599    if let Some(wall) = rucc_sysroot::Wall::of(target) {
2600        return Err(err(format!("--fetch {tuple}: {}", wall.no_fetch(&tuple))));
2601    }
2602    let Some(what) = rucc_sysroot::pinned_for_target(target) else {
2603        return Err(err(unpinned(&tuple)));
2604    };
2605    Ok(Action::Fetch { what, target, cache: cache::dir() })
2606}
2607
2608/// What `--fetch-msvc-sdk <tuple>` asks for, weighed the same way the fetch above is.
2609///
2610/// The target is resolved here rather than where the work happens, so that a tuple this compiler
2611/// does not know and a target that is not behind Microsoft's wall are refusals from the parser like
2612/// every other thing a command line can ask for and not have. Whether the licence was accepted is
2613/// carried rather than acted on, because what it changes is what the command does and not whether
2614/// the command line made sense.
2615///
2616/// # Errors
2617///
2618/// [`CliError`] when `--offline` forbade it, when there are input files as well, and when the tuple
2619/// is not a target this compiler knows.
2620fn fetch_msvc_action(
2621    named: &str,
2622    offline: bool,
2623    accepted: bool,
2624    inputs: &[Input],
2625) -> Result<Action, CliError> {
2626    if offline {
2627        return Err(err(
2628            "--fetch-msvc-sdk asks for a download and --offline forbids every download, so this \
2629             command line asks for two opposite things. Drop one of them: --offline is how a build \
2630             says it will not reach the network",
2631        ));
2632    }
2633    if let Some(first) = inputs.first() {
2634        return Err(err(format!(
2635            "--fetch-msvc-sdk gets an SDK and compiles nothing, so `{}` on the same command line \
2636             is an input that nothing would read",
2637            first.path
2638        )));
2639    }
2640    let target: TargetTuple = named.parse().map_err(|why| {
2641        err(format!("--fetch-msvc-sdk {named}: {why}, so there is no SDK to get"))
2642    })?;
2643    Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir(), pinned: false })
2644}
2645
2646/// Why there is nothing to fetch for a target, which is a different sentence when the table is
2647/// empty.
2648///
2649/// A release that pins nothing and a release that pins eleven targets and not this one are two
2650/// situations, and a message that did not tell them apart would send somebody looking for a typo in
2651/// their tuple when the answer is that this work is not finished.
2652fn unpinned(tuple: &str) -> String {
2653    let pinned = rucc_sysroot::pinned_targets();
2654    if pinned.is_empty() {
2655        return format!(
2656            "this release pins no sysroot for {tuple}, and it pins none for any target yet. A \
2657             sysroot is built and published by the producer in tamnd/rucc-cross, per \
2658             spec/cross-compile/13-distribution.md section 13.8, and a release of this compiler \
2659             names one by URL and by hash afterwards. Until then, pass --sysroot=<dir> to compile \
2660             against a tree you have already"
2661        );
2662    }
2663    format!(
2664        "this release pins no sysroot for {tuple}. What it pins is {}. Pass --sysroot=<dir> to \
2665         compile against a tree you have already",
2666        pinned.join(", ")
2667    )
2668}
2669
2670/// Gets the artifact and installs it, saying what each step did.
2671///
2672/// The steps are section 13.8's and so are the messages: the transport is somebody else's program
2673/// and the check is ours, so a person reading this wants to know which downloader ran, that the
2674/// bytes matched, how many files the record named and where the tree ended up. A fetch of something
2675/// that is already there says that instead and moves nothing.
2676///
2677/// A Linux target is two artifacts, its own sysroot and the kernel header tree every Linux target
2678/// shares, and `kernel` is the second one when the target reads it. It is fetched after the sysroot
2679/// and by the same two steps, so a machine that has fetched one Linux target already has it and a
2680/// second target's fetch says so and moves nothing.
2681fn fetch_sysroot(
2682    what: &rucc_sysroot::Pinned,
2683    kernel: Option<&rucc_sysroot::Pinned>,
2684    target: TargetTuple,
2685    cache: &std::path::Path,
2686) -> i32 {
2687    let tuple = target.to_canonical_string();
2688    let say = |line: &str| println!("rucc: {tuple}: {line}");
2689    if let Err(why) = bring(what, cache, &say) {
2690        return complain(why);
2691    }
2692    let archive = what.archive_in(cache);
2693    match install::install(&archive, what.sha256, target, cache) {
2694        Ok(done) => report(&done, "sysroot", &say),
2695        Err(why) => return complain(why),
2696    }
2697    let Some(kernel) = kernel else { return 0 };
2698    if let Err(why) = bring(kernel, cache, &say) {
2699        return complain(why);
2700    }
2701    match install::install_kernel(&kernel.archive_in(cache), kernel.sha256, cache) {
2702        Ok(done) => {
2703            report(&done, "kernel header tree", &say);
2704            0
2705        }
2706        Err(why) => complain(why),
2707    }
2708}
2709
2710/// The download half of a fetch, for one artifact.
2711fn bring(
2712    what: &rucc_sysroot::Pinned,
2713    cache: &std::path::Path,
2714    say: &impl Fn(&str),
2715) -> Result<(), CliError> {
2716    let archive = what.archive_in(cache);
2717    match fetch::fetch(what.url, what.sha256, &archive)? {
2718        fetch::Fetched::AlreadyThere => {
2719            say(&format!("{} is already here and matches the hash", archive.display()));
2720        }
2721        fetch::Fetched::Downloaded(by) => {
2722            say(&format!("downloaded {} with {}", what.url, by.program()));
2723        }
2724    }
2725    Ok(())
2726}
2727
2728/// What an install did, in the words a person reading a fetch wants.
2729fn report(done: &install::Installed, what: &str, say: &impl Fn(&str)) {
2730    match &done.before {
2731        install::Before::Nothing => {
2732            say(&format!("{} files installed at {}", done.files, done.root.display()));
2733        }
2734        install::Before::TheSame => {
2735            say(&format!(
2736                "the same {what} is already at {}, so nothing moved",
2737                done.root.display()
2738            ));
2739        }
2740        install::Before::Different(was) => {
2741            say(&format!(
2742                "{} files installed at {}, over a tree whose record digested to {was}",
2743                done.files,
2744                done.root.display()
2745            ));
2746        }
2747    }
2748    say(&format!("the {what}'s record digests to {}", done.digest));
2749}
2750
2751/// What one of the `-dump` and `-print` flags prints.
2752///
2753/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
2754/// which is what makes the answer safe to paste into a link line whether or not the file is
2755/// there, and this does the same.
2756fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
2757    let found = |name: &str| {
2758        link::find_in_search(link, opts.target, name)
2759            .map_or_else(|| name.to_owned(), |path| path.display().to_string())
2760    };
2761    Ok(match query {
2762        Query::Machine => opts.target.to_string(),
2763        Query::Version => opts.gnuc.major.to_string(),
2764        Query::FullVersion => {
2765            format!("{}.{}.{}", opts.gnuc.major, opts.gnuc.minor, opts.gnuc.patch)
2766        }
2767        Query::Multiarch => link::multiarch(opts.target),
2768        // The three lines GCC prints, in its order and with its punctuation, because what reads
2769        // them is a script written against that shape. There is no installation directory to
2770        // report: this compiler is one binary that works wherever it is copied, and the headers
2771        // it ships are inside it, so `install` is where the binary is and nothing is under it.
2772        Query::SearchDirs => {
2773            let here = std::env::current_exe()
2774                .ok()
2775                .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
2776                .unwrap_or_default();
2777            let list = |dirs: &[PathBuf]| {
2778                dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
2779            };
2780            let libraries = link::search_dirs(link, opts.target);
2781            format!(
2782                "install: {}\nprograms: ={}\nlibraries: ={}",
2783                here.display(),
2784                list(&link.prefixes),
2785                list(&libraries)
2786            )
2787        }
2788        // The root the rest of the answers are under, which a build system asks for when it wants
2789        // to find a file itself rather than ask for one by name, and which is the first thing to
2790        // look at when a cross build read a header nobody expected. A native compile has no
2791        // sysroot and the answer is the empty line, which is what GCC prints when it was
2792        // configured without one. `--sysroot` wins over ours because it wins everywhere else.
2793        Query::Sysroot => {
2794            sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
2795        }
2796        // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
2797        // compiler's own code, what it is, where it was got, its hash, its licence and whether it
2798        // was bundled, generated or fetched. What is printed is the manifest the sysroot already
2799        // carries rather than a second format saying the same things, because the three uses 13.5
2800        // gives for this are a licence notice, a reproducibility check and a security audit, and all
2801        // three are somebody else parsing it. One format is one parser to write.
2802        // Read and rendered rather than copied out, so that what comes back is the format this
2803        // build understands. The last newline comes off because whatever prints an answer adds
2804        // one, the way it does for every other query here. Keeping it would put a blank line at
2805        // the end of the one answer that is a file somebody diffs against the file it came from.
2806        Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
2807            Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
2808            None => String::new(),
2809        },
2810        // Section 13.2 of the same document, which asks for the hash of a cache directory's
2811        // contents in the directory's name. A name cannot carry one, because the path has to be
2812        // computable before anything has been read, by the producer about to write the files and by
2813        // the compiler about to read them, and neither has the contents when it asks. So the number
2814        // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
2815        // which means `sha256sum` over the manifest answers the same thing.
2816        Query::SysrootDigest => match sysroot_manifest(opts, link)? {
2817            Some(manifest) => manifest.digest(),
2818            None => String::new(),
2819        },
2820        Query::FileName(name) => found(name),
2821        // The name GCC gives the library of routines a compiler's output calls that the C
2822        // library does not have. Ours is built in and there is no file, so the answer is the
2823        // name itself, which is what GCC prints when it cannot find one either.
2824        Query::Libgcc => found("libgcc.a"),
2825        // A program rather than a library: the linker and the archiver are the ones a build asks
2826        // about, and this compiler finds them on the path or under `-B` rather than shipping
2827        // them, so the name back is the honest answer unless a `-B` prefix holds one.
2828        Query::ProgName(name) => link
2829            .prefixes
2830            .iter()
2831            .map(|dir| dir.join(name))
2832            .find(|path| path.is_file())
2833            .map_or_else(|| name.clone(), |path| path.display().to_string()),
2834    })
2835}
2836
2837/// The root every sysroot answer is about.
2838///
2839/// One function rather than a copy in each, because the other flags exist to say what is inside the
2840/// tree this one names, and two answers that disagreed about which tree that is would be a
2841/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
2842/// else.
2843fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
2844    link.sysroot
2845        .clone()
2846        .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
2847}
2848
2849/// The record of the sysroot this command line reads, when there is one to read.
2850///
2851/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
2852/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
2853/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
2854/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
2855/// inputs in it because that one still has its header lines.
2856///
2857/// # Errors
2858///
2859/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
2860/// record we could not read on to whoever asked would make their parser the one that finds the
2861/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
2862/// output.
2863fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
2864    let Some(root) = sysroot_root(opts, link) else {
2865        return Ok(None);
2866    };
2867    let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
2868    match std::fs::read_to_string(&path) {
2869        Ok(text) => Manifest::parse(&text)
2870            .map(Some)
2871            .map_err(|why| err(format!("{}: {why}", path.display()))),
2872        Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
2873        Err(why) => Err(err(format!("{}: {why}", path.display()))),
2874    }
2875}
2876
2877/// Renders the passes this level will run, in order, with what each one does.
2878///
2879/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
2880/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
2881/// emerges from which flags happen to be set, and this is how that list is read.
2882#[must_use]
2883pub fn print_pipeline(opts: &Options) -> String {
2884    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
2885    settings.toggles.clone_from(&opts.passes);
2886    settings.global_fuel = opts.pass_fuel_global;
2887    for (on, spec) in &opts.pass_gates {
2888        // Every spelling was checked while the arguments were parsed, so there is nothing here
2889        // this can refuse, and a listing is not the place to report it if there were.
2890        let _ = settings.gates.add(*on, spec);
2891    }
2892    rucc_opt::pipeline::print(&settings)
2893}
2894
2895/// Renders the resolved configuration.
2896///
2897/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
2898/// this output is diffed across hosts in CI and a reordering would read as a change.
2899#[must_use]
2900pub fn print_config(opts: &Options) -> String {
2901    let sess = Session::new(opts.clone());
2902    let t = &sess.target;
2903    let mut out = String::new();
2904    let _ = writeln!(out, "version: {VERSION}");
2905    // The three field triple the driver was given rather than the ten field tuple it widens to,
2906    // because this output is what a build system reads to find out what it asked for. The tuple is
2907    // the compiler's model of the machine and this line is a receipt for a command line.
2908    let _ = writeln!(out, "target: {}", opts.target);
2909    let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
2910    let _ = writeln!(out, "os: {}", opts.target.os.as_str());
2911    let _ = writeln!(out, "env: {}", opts.target.env.as_str());
2912    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
2913    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
2914    let _ = writeln!(out, "long-width: {}", t.long_width);
2915    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
2916    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
2917    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
2918    let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
2919    // The register file as a count per class, which is enough to tell a target whose registers
2920    // are described from one whose are not without printing sixteen names nobody asked for.
2921    let regs: Vec<String> = t
2922        .regs
2923        .classes()
2924        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
2925        .collect();
2926    let _ = writeln!(
2927        out,
2928        "registers: {}",
2929        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
2930    );
2931    // What the schedule was chosen with, which is a sentence rather than a name on purpose: two
2932    // runs of a benchmark that disagree are usually two models and not two compilers.
2933    let _ = writeln!(out, "timing-model: {}", t.timing.map_or("none", |timing| timing.model));
2934    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
2935    let _ = writeln!(out, "safety: {}", sess.opts.safety);
2936    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
2937    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
2938    let _ = writeln!(out, "frame-pointer: {}", sess.opts.keeps_frame_pointer());
2939    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
2940    let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
2941    let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
2942    let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
2943    let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
2944    let _ = writeln!(out, "profile: {}", sess.opts.profile);
2945    let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
2946    // Last because it is the one key with more than one line under it, and the only one
2947    // whose value is a property of the machine rather than of the command line.
2948    for dir in sess.opts.search.dirs() {
2949        let system = if dir.is_system { " (system)" } else { "" };
2950        let _ = writeln!(out, "include: {}{system}", dir.path.display());
2951    }
2952    out
2953}
2954
2955/// The output name the make target is taken from, which is the `-o` argument or nothing.
2956///
2957/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
2958/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
2959/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
2960/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
2961/// `-S` on the argument does name what the rule builds, and it is used as written.
2962fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
2963    if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
2964}
2965
2966/// Writes to a path the command line named rather than one the plan derived, where `-` is
2967/// standard output.
2968fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
2969    if path == "-" {
2970        return write_out(&Output::Stdout, bytes);
2971    }
2972    write_out(&Output::File(path.to_owned()), bytes)
2973}
2974
2975/// Writes the make rule for one input, and reports whether it got there.
2976///
2977/// A rule with no file of its own goes where the compilation it replaced would have written,
2978/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
2979/// `$@`, and the same line with the `-o` left off puts it on standard output.
2980fn write_deps(
2981    opts: &Options,
2982    plan: &Plan,
2983    job: &Job,
2984    found: &[Dependency],
2985    stderr: &mut impl std::io::Write,
2986) -> bool {
2987    let targets = if opts.deps.targets.is_empty() {
2988        vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
2989    } else {
2990        opts.deps.targets.clone()
2991    };
2992    let rule = deps::rule(&opts.deps, &targets, &job.input, found);
2993    // The file, on the other hand, is named after the `-o` in every mode that still has one to
2994    // spend, which is every mode except the two that spend it on the rule.
2995    let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
2996        // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
2997        // named empty rather than absent, because a makefile that named it as a target of its
2998        // own is a makefile that will look for it.
2999        Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
3000            if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
3001        }),
3002        None => write_out(&job.output, rule.as_bytes()),
3003    };
3004    if let Err(e) = wrote {
3005        let _ = writeln!(stderr, "rucc: error: {e}");
3006        return false;
3007    }
3008    true
3009}
3010
3011/// Runs phase 4 over every input that has one, and writes what came out.
3012///
3013/// One input that fails does not stop the others. A build that reports every file it could
3014/// not preprocess in one run is worth more than one that stops at the first, and the exit
3015/// status is still a failure either way.
3016fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
3017    let fs = OsFileSystem::new();
3018    let mut stderr = std::io::stderr().lock();
3019    let mut failed = false;
3020    for job in &plan.jobs {
3021        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
3022            // An input that is already preprocessed, or an object file. GCC passes these
3023            // through untouched, and the plan has already said so in its notes.
3024            continue;
3025        }
3026        let started = std::time::Instant::now();
3027        let result = preprocess(opts, &job.input, &fs);
3028        if opts.time {
3029            say_time(&job.input, started.elapsed(), &mut stderr);
3030        }
3031        for message in &result.messages {
3032            let _ = writeln!(stderr, "{message}");
3033        }
3034        if result.failed() {
3035            failed = true;
3036            continue;
3037        }
3038        if opts.deps.emit {
3039            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3040            // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
3041            // to write. The other two asked for both and fall through to the text below.
3042            if opts.deps.instead_of_compiling {
3043                continue;
3044            }
3045        }
3046        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
3047            let _ = writeln!(stderr, "rucc: error: {e}");
3048            failed = true;
3049        }
3050    }
3051    i32::from(failed)
3052}
3053
3054/// Whether this job is a file of assembly that has to be assembled and that nothing here assembles.
3055///
3056/// The phases rather than the kind, because there are two kinds of assembly input and one of them
3057/// is preprocessed first, and because an object file also has no compile phase and is not this: it
3058/// has no phases at all and goes to the linker as it is. A `.s` on a `-c` line has exactly
3059/// [`Phase::Assemble`] left, and a `.S` has the preprocessor in front of it, and neither has
3060/// anything the front end can do.
3061fn needs_an_assembler(job: &Job) -> bool {
3062    job.phases.contains(&Phase::Assemble) && !job.phases.contains(&Phase::Compile)
3063}
3064
3065/// Whether the preprocessor runs over it on the way in, which is the whole difference between the
3066/// two kinds of assembly input.
3067fn assembly_wants_cpp(job: &Job) -> bool {
3068    job.phases.contains(&Phase::Preprocess)
3069}
3070
3071/// Runs the front end over every input that has a compile phase, and writes what came out.
3072///
3073/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
3074/// exit status is a failure either way. An input that is already assembly or an object has no
3075/// compile phase and is passed over here, which the plan has already said in its notes.
3076fn compile_all(opts: &Options, plan: &Plan) -> i32 {
3077    let fs = OsFileSystem::new();
3078    let mut stderr = std::io::stderr().lock();
3079    let mut failed = false;
3080    let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3081    failed |= !ok;
3082    let mut fired = Fired::new();
3083    let mut pressure = Pressure::new();
3084    let mut lowerings = Lowerings::new();
3085    for job in &plan.jobs {
3086        if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3087            continue;
3088        }
3089        // An input of IR is read back rather than compiled, since the C it came from is not
3090        // here any more. A file of assembly does not go through the front end at all and is
3091        // read by the assembler instead. Everything after this is the same for all three, so
3092        // the paths meet again at the messages and the file the result is written to.
3093        let started = std::time::Instant::now();
3094        let result = if needs_an_assembler(job) {
3095            assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3096        } else if job.kind == InputKind::Ir {
3097            compile_ir(opts, &job.input, &fs)
3098        } else {
3099            compile(opts, &job.input, &fs)
3100        };
3101        if opts.time {
3102            say_time(&job.input, started.elapsed(), &mut stderr);
3103        }
3104        failed |= !write_trace(opts, job, started, &result, &mut stderr);
3105        fired.merge(&result.fired);
3106        pressure.merge(&result.pressure);
3107        lowerings.merge(&result.lowerings);
3108        failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3109        failed |= !remarks.write(&result.remarks, &mut stderr);
3110        for message in &result.messages {
3111            let _ = writeln!(stderr, "{message}");
3112        }
3113        // Before the failure below, because a compilation that stopped in the back end is exactly
3114        // the one whose preprocessed source somebody wants to look at.
3115        failed |= !write_temps(job, &result.temps, &mut stderr);
3116        // Before it as well, because gcc leaves an empty report for a file that did not compile
3117        // and a build that looks for one beside every object should find one.
3118        failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3119        if result.failed() {
3120            failed = true;
3121            continue;
3122        }
3123        // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
3124        // this is the one path where both files come out of the same run. An input of IR has no
3125        // dependencies to report and produces an empty list, which produces a rule naming only
3126        // itself, and that is the honest answer rather than a missing file.
3127        if opts.deps.emit {
3128            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3129        }
3130        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
3131            let _ = writeln!(stderr, "rucc: error: {e}");
3132            failed = true;
3133        }
3134    }
3135    failed |= !write_coverage(opts, &fired, &mut stderr);
3136    failed |= !write_pressure(opts, &pressure, &mut stderr);
3137    failed |= !write_lowering(opts, &lowerings, &mut stderr);
3138    i32::from(failed)
3139}
3140
3141/// A directory for the object files only the link step ever sees, removed when it goes away.
3142///
3143/// `-c` writes its object where the user can see it and linking does not, which is the whole of
3144/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
3145/// every other compiler. Removing them on drop rather than at the end of a function is so that a
3146/// link that failed leaves nothing behind either.
3147struct Scratch {
3148    /// Where the objects go.
3149    dir: PathBuf,
3150}
3151
3152impl Scratch {
3153    /// Makes one, under whatever the platform calls its temporary directory.
3154    ///
3155    /// The name carries the process id so that two compilers running at once do not share a
3156    /// directory, which they would otherwise do the moment two of them compiled a file of the
3157    /// same name.
3158    fn new() -> Result<Scratch, String> {
3159        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
3160        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
3161        Ok(Scratch { dir })
3162    }
3163}
3164
3165impl Drop for Scratch {
3166    fn drop(&mut self) {
3167        let _ = std::fs::remove_dir_all(&self.dir);
3168    }
3169}
3170
3171/// The link line the plan describes, for `-###`.
3172///
3173/// The names in it are the hints the plan carries rather than the temporaries a real compilation
3174/// would choose, because `-###` prints the line without having compiled anything and so has
3175/// nothing to point at. That also makes the printed line readable rather than naming a directory
3176/// that only exists while a compilation is running.
3177fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
3178    let linker = link::find(opts.target, link)?;
3179    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
3180    Ok(link::render(&linker, &args))
3181}
3182
3183/// Compiles everything, then links it.
3184///
3185/// The objects go in a directory that is removed afterwards, which is why this is not
3186/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
3187/// and does not say where, because where is a question that only has an answer once something is
3188/// running.
3189fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
3190    let Some(job) = &plan.link else {
3191        // Every path into here comes from a plan whose last phase is the link, and such a plan
3192        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
3193        let mut stderr = std::io::stderr().lock();
3194        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
3195        return 1;
3196    };
3197    // Before anything is compiled, because a linker that is not on the machine is worth knowing
3198    // about in the second it takes to look rather than after the compilation.
3199    // And before that, whether this link has a line at all and whether what it reads is on the
3200    // machine. Both are answerable now, and a target whose sysroot has not been built is worth
3201    // saying so about before the compilation rather than after it.
3202    if let Err(why) = link::preflight(opts.target, link) {
3203        return complain(why);
3204    }
3205    let linker = match link::find(opts.target, link) {
3206        Ok(linker) => linker,
3207        Err(why) => return complain(why),
3208    };
3209    // Whether the one that was found can do this link is asked inside the search, which moves on
3210    // past an lld that is too old to a newer one somewhere else and refuses only when there is none.
3211    // The glibc stubs, which are the one part of a cross sysroot written here rather than fetched.
3212    // Before compiling for the same reason as the rest, and never for `-###`, which writes nothing.
3213    if let Err(why) = link::write_stubs(opts.target, link) {
3214        return complain(why);
3215    }
3216
3217    let scratch = match Scratch::new() {
3218        Ok(scratch) => scratch,
3219        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
3220    };
3221
3222    let fs = OsFileSystem::new();
3223    let mut failed = false;
3224    // One per job, in job order, which is what lets the link line below be rebuilt with the real
3225    // paths in it: every job contributes exactly one file to the line and does so in this order.
3226    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
3227    let mut fired = Fired::new();
3228    let mut pressure = Pressure::new();
3229    let mut lowerings = Lowerings::new();
3230    {
3231        let mut stderr = std::io::stderr().lock();
3232        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3233        failed |= !ok;
3234        for (at, job) in plan.jobs.iter().enumerate() {
3235            let out = match &job.output {
3236                Output::Temporary(hint) => {
3237                    // The index because two inputs in different directories can have the same
3238                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
3239                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
3240                }
3241                Output::File(path) => path.clone(),
3242                // A job feeding the linker never writes to standard output, since the plan gives
3243                // it a temporary. This is here so that the match is total rather than a panic.
3244                Output::Stdout => continue,
3245            };
3246            produced.push(out.clone());
3247            if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3248                continue;
3249            }
3250            let started = std::time::Instant::now();
3251            let result = if needs_an_assembler(job) {
3252                assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3253            } else if job.kind == InputKind::Ir {
3254                compile_ir(opts, &job.input, &fs)
3255            } else {
3256                compile(opts, &job.input, &fs)
3257            };
3258            if opts.time {
3259                say_time(&job.input, started.elapsed(), &mut stderr);
3260            }
3261            failed |= !write_trace(opts, job, started, &result, &mut stderr);
3262            fired.merge(&result.fired);
3263            pressure.merge(&result.pressure);
3264            lowerings.merge(&result.lowerings);
3265            failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3266            failed |= !remarks.write(&result.remarks, &mut stderr);
3267            for message in &result.messages {
3268                let _ = writeln!(stderr, "{message}");
3269            }
3270            failed |= !write_temps(job, &result.temps, &mut stderr);
3271            failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3272            if result.failed() {
3273                failed = true;
3274                continue;
3275            }
3276            // A `-MD` on a command line that links writes the rule next to the executable and
3277            // names the executable as its target, since that is the file this source builds
3278            // here. The object it went through is in a temporary directory and is gone by the
3279            // time `make` reads any of this.
3280            if opts.deps.emit {
3281                failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3282            }
3283            if !matches!(result.artifact, Artifact::Object { .. }) {
3284                // Worth saying rather than writing whatever it is and letting the linker read it.
3285                // An empty file is a valid empty linker script, so a link handed one gets as far
3286                // as reporting every symbol of this file undefined, which is a page of messages
3287                // about something that went wrong here.
3288                let _ = writeln!(
3289                    stderr,
3290                    "rucc: internal error: {}: no object file was produced for the link",
3291                    job.input
3292                );
3293                failed = true;
3294                continue;
3295            }
3296            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
3297                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
3298                failed = true;
3299            }
3300        }
3301        failed |= !write_coverage(opts, &fired, &mut stderr);
3302        failed |= !write_pressure(opts, &pressure, &mut stderr);
3303        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3304        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3305    }
3306    if failed {
3307        // Nothing is linked from a compilation that did not finish. A linker run over the objects
3308        // that did compile would report every function of the file that did not as undefined,
3309        // which is a page of messages about a mistake already reported once.
3310        return 1;
3311    }
3312
3313    // The items in command line order with the temporaries filled in. A library and a word for the
3314    // linker contribute no job and pass through, and every file item takes the next job's real
3315    // output, which is what keeps whatever was written between two objects between them here.
3316    let mut outputs = produced.into_iter();
3317    let mut items = Vec::with_capacity(job.inputs.len());
3318    for item in &job.inputs {
3319        match item {
3320            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
3321            link::Item::Linker(arg) => items.push(link::Item::Linker(arg.clone())),
3322            link::Item::File(_) => match outputs.next() {
3323                Some(path) => items.push(link::Item::File(path)),
3324                None => return complain("the plan asks the linker for a file nothing produced"),
3325            },
3326        }
3327    }
3328
3329    let args = match link::line(opts.target, link, &items, &job.output) {
3330        Ok(args) => args,
3331        Err(why) => return complain(why),
3332    };
3333    if verbose {
3334        let mut stderr = std::io::stderr().lock();
3335        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
3336    }
3337    let started = std::time::Instant::now();
3338    let ran = link::run(&linker, &args);
3339    if opts.time {
3340        // The one step of a compilation that really is another program, so this line is the same
3341        // measurement gcc's is and names the linker the way gcc names `collect2`.
3342        let mut stderr = std::io::stderr().lock();
3343        say_time(&linker.name, started.elapsed(), &mut stderr);
3344    }
3345    match ran {
3346        Ok(()) => 0,
3347        // The linker has already said what was wrong on its own error output, and repeating that
3348        // linking failed would only push its message further up the screen.
3349        Err(link::Error::Refused { .. }) => 1,
3350        Err(why) => complain(why),
3351    }
3352}
3353
3354/// Compiles everything and writes the objects into one static library.
3355///
3356/// No temporary directory and no second program. The objects never reach the file system at all:
3357/// they go from the compiler into the archive writer, which is both faster than writing a directory
3358/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
3359/// member's index entries are the names the object writer says it wrote, and the only thing that
3360/// knows those is the run that wrote it.
3361///
3362/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
3363/// person can find, and they are written there as well as put in the archive.
3364fn archive_all(opts: &Options, plan: &Plan) -> i32 {
3365    let Some(job) = &plan.archive else {
3366        // Every path into here comes from a plan whose last phase is the archive, and such a plan
3367        // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
3368        return complain("there is nothing to put in an archive");
3369    };
3370    // Before anything is compiled, because a format this has no container for is worth knowing
3371    // about in the second it takes to look rather than after the whole compilation.
3372    let flavour = match opts.target.os.object_format() {
3373        ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
3374        ObjectFormat::Coff => rucc_archive::Flavour::Coff,
3375        ObjectFormat::MachO => rucc_archive::Flavour::Bsd,
3376        // Wasm has no archives of its own at all.
3377        format @ ObjectFormat::Wasm => {
3378            return complain(format!(
3379                "there is no archive format for {} objects in this compiler yet",
3380                format.as_str()
3381            ));
3382        }
3383    };
3384
3385    let fs = OsFileSystem::new();
3386    let mut failed = false;
3387    let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
3388    let mut names = job.members.iter();
3389    let mut fired = Fired::new();
3390    let mut pressure = Pressure::new();
3391    let mut lowerings = Lowerings::new();
3392    {
3393        let mut stderr = std::io::stderr().lock();
3394        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3395        failed |= !ok;
3396        for plan_job in &plan.jobs {
3397            // What the plan called this member. The two lists are walked together rather than the
3398            // name being worked out again here, so that what `-###` printed and what goes in the
3399            // file cannot come apart.
3400            let Some(member) = names.next() else {
3401                return complain("the plan asks the archive for a member nothing produced");
3402            };
3403            if !plan_job.phases.contains(&Phase::Compile) && !needs_an_assembler(plan_job) {
3404                // Neither something to compile nor something to assemble, so there is nothing to
3405                // put in, and an archive quietly missing a member is worse than a message.
3406                let _ = writeln!(
3407                    &mut stderr,
3408                    "rucc: error: {}: this compiler makes an archive out of what it compiles, and \
3409                     there is nothing here for it to do",
3410                    plan_job.input
3411                );
3412                failed = true;
3413                continue;
3414            }
3415            let started = std::time::Instant::now();
3416            let result = if needs_an_assembler(plan_job) {
3417                assemble(opts, &plan_job.input, assembly_wants_cpp(plan_job), &fs)
3418            } else if plan_job.kind == InputKind::Ir {
3419                compile_ir(opts, &plan_job.input, &fs)
3420            } else {
3421                compile(opts, &plan_job.input, &fs)
3422            };
3423            if opts.time {
3424                say_time(&plan_job.input, started.elapsed(), &mut stderr);
3425            }
3426            failed |= !write_trace(opts, plan_job, started, &result, &mut stderr);
3427            fired.merge(&result.fired);
3428            pressure.merge(&result.pressure);
3429            lowerings.merge(&result.lowerings);
3430            failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
3431            failed |= !remarks.write(&result.remarks, &mut stderr);
3432            for message in &result.messages {
3433                let _ = writeln!(stderr, "{message}");
3434            }
3435            failed |= !write_temps(plan_job, &result.temps, &mut stderr);
3436            failed |= !write_stack_usage(plan_job, &result.stack_usage, &mut stderr);
3437            if result.failed() {
3438                failed = true;
3439                continue;
3440            }
3441            if opts.deps.emit {
3442                failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
3443            }
3444            let Artifact::Object { bytes, defines } = result.artifact else {
3445                let _ = writeln!(
3446                    stderr,
3447                    "rucc: internal error: {}: no object file was produced for the archive",
3448                    plan_job.input
3449                );
3450                failed = true;
3451                continue;
3452            };
3453            // Under `-save-temps` the plan gave the object a name a person can find, so it is
3454            // written there too. Otherwise it is only ever a member and never a file.
3455            if let Output::File(path) = &plan_job.output {
3456                if let Err(e) = std::fs::write(path, &bytes) {
3457                    let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3458                    failed = true;
3459                }
3460            }
3461            members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
3462        }
3463        failed |= !write_coverage(opts, &fired, &mut stderr);
3464        failed |= !write_pressure(opts, &pressure, &mut stderr);
3465        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3466        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3467    }
3468    if failed {
3469        // Nothing is written from a compilation that did not finish, for the reason the link gives:
3470        // an archive missing the file that failed is one a link reports every name of as undefined,
3471        // which is a page of messages about a mistake already reported once.
3472        return 1;
3473    }
3474
3475    let bytes = match rucc_archive::write(flavour, &members) {
3476        Ok(bytes) => bytes,
3477        // Every one of these is a bug here rather than a program's mistake: the names came from the
3478        // object writer and the bodies came from this process.
3479        Err(why) => return complain(format!("the archive could not be written: {why}")),
3480    };
3481    match std::fs::write(&job.output, &bytes) {
3482        Ok(()) => 0,
3483        Err(e) => complain(format!("{}: {e}", job.output)),
3484    }
3485}
3486
3487/// Prints one driver level message and gives back the exit status that goes with it.
3488fn complain(why: impl std::fmt::Display) -> i32 {
3489    let mut stderr = std::io::stderr().lock();
3490    let _ = writeln!(stderr, "rucc: error: {why}");
3491    1
3492}
3493
3494/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
3495///
3496/// Once for the whole command line rather than once per input, because the question is which
3497/// lowering rules this run of the compiler reached and a file per input would leave the reader
3498/// unioning files to find out something one process already knew.
3499///
3500/// A file that could not be written is a failure and not a warning. What asks for this is a
3501/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
3502fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
3503    let Some(path) = &opts.rule_coverage else { return true };
3504    let Some(table) = coverage::table(opts.target.arch) else {
3505        let _ = writeln!(
3506            stderr,
3507            "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
3508             to report",
3509            opts.target
3510        );
3511        return false;
3512    };
3513    match std::fs::write(path, fired.listing(table)) {
3514        Ok(()) => true,
3515        Err(e) => {
3516            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3517            false
3518        }
3519    }
3520}
3521
3522/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
3523///
3524/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3525/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
3526/// rule table here, since every target this compiles for has an allocator, and a run that reached
3527/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
3528/// produced no code is still an answer and it is the honest one.
3529fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
3530    let Some(path) = &opts.register_pressure else { return true };
3531    match std::fs::write(path, pressure.listing()) {
3532        Ok(()) => true,
3533        Err(e) => {
3534            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3535            false
3536        }
3537    }
3538}
3539
3540/// Writes what `-Zlowering=FILE` asked for, and says whether it could.
3541///
3542/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3543/// not be written is a failure for the reason it gives too. A run that reached no back end writes
3544/// an empty listing rather than nothing, the way [`write_pressure`] does and for the same reason.
3545fn write_lowering(opts: &Options, lowerings: &Lowerings, stderr: &mut impl std::io::Write) -> bool {
3546    let Some(path) = &opts.lowering_dump else { return true };
3547    match std::fs::write(path, lowerings.listing()) {
3548        Ok(()) => true,
3549        Err(e) => {
3550            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3551            false
3552        }
3553    }
3554}
3555
3556/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
3557///
3558/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
3559/// A file rather than the diagnostic stream is what a harness wants: the corpus in
3560/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
3561/// a few thousand remarks mixed into that would bury it.
3562struct Remarks {
3563    /// The file, if there is one.
3564    file: Option<String>,
3565    /// Whether anything has been written to it yet, which decides between truncating and
3566    /// appending. One file holds the whole run rather than the last input in it.
3567    started: bool,
3568}
3569
3570impl Remarks {
3571    /// Prepares the destination, emptying the file if there is one.
3572    ///
3573    /// Emptied here rather than at the first remark, because a run where no pass had anything to
3574    /// say should leave an empty file and not yesterday's. An absent file and an empty one are
3575    /// different facts and something reading this will act on the difference.
3576    fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
3577        let mut ok = true;
3578        if let Some(path) = file {
3579            if let Err(e) = std::fs::write(path, "") {
3580                let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3581                ok = false;
3582            }
3583        }
3584        (Self { file: file.cloned(), started: false }, ok)
3585    }
3586
3587    /// Writes one input's remarks, and says whether that worked.
3588    ///
3589    /// A file that cannot be written is a failure and not a warning, for the reason
3590    /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
3591    /// where nothing happened.
3592    fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
3593        if text.is_empty() {
3594            return true;
3595        }
3596        let Some(path) = &self.file else {
3597            let _ = write!(stderr, "{text}");
3598            return true;
3599        };
3600        let opened = std::fs::OpenOptions::new()
3601            .write(true)
3602            .append(self.started)
3603            .truncate(!self.started)
3604            .create(true)
3605            .open(path);
3606        self.started = true;
3607        let result =
3608            opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
3609        if let Err(e) = result {
3610            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3611            return false;
3612        }
3613        true
3614    }
3615}
3616
3617/// Writes what `-fdump-ir=` asked to see, one file per dump.
3618///
3619/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
3620/// after a run is the passes in the order they ran, per input. They go in the working directory
3621/// rather than beside the output, because a dump is something a person asked for at a prompt and
3622/// the working directory is where that person is.
3623///
3624/// A file that could not be written is a failure and not a warning, for the reason
3625/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
3626/// quietly did not happen looks exactly like a pass that did not run.
3627fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
3628    let stem = std::path::Path::new(input)
3629        .file_name()
3630        .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
3631    let mut ok = true;
3632    for dump in dumps {
3633        let path = format!("{stem}.{}.ir", dump.name);
3634        if let Err(e) = std::fs::write(&path, &dump.text) {
3635            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3636            ok = false;
3637        }
3638    }
3639    ok
3640}
3641
3642/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
3643///
3644/// A file that could not be written is a failure rather than a warning, for the reason
3645/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
3646/// looks like a compilation that never went through that step.
3647fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
3648    let mut ok = true;
3649    let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
3650    for (path, text) in kept {
3651        // A step the compilation did not reach has nothing to keep, and a job that is not keeping
3652        // that step has nowhere to put it. Either way there is no file here.
3653        let (Some(path), Some(text)) = (path, text) else { continue };
3654        if let Err(e) = std::fs::write(&path, text) {
3655            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3656            ok = false;
3657        }
3658    }
3659    ok
3660}
3661
3662/// Writes the `.su` file `-fstack-usage` asked for, where the plan said it goes.
3663///
3664/// Written even when it is empty, because gcc writes an empty `.su` for a file with no functions,
3665/// for `-fsyntax-only` and for a file that did not compile, and a tool that looks for one beside
3666/// every object should find one.
3667fn write_stack_usage(job: &Job, text: &str, stderr: &mut impl std::io::Write) -> bool {
3668    let Some(path) = &job.stack_usage else { return true };
3669    if let Err(e) = std::fs::write(path, text) {
3670        let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3671        return false;
3672    }
3673    true
3674}
3675
3676/// Appends the file's line to the `-frucc-trace` file, when there is one.
3677///
3678/// Returns whether that went well, and says why on standard error when it did not.
3679fn write_trace(
3680    opts: &Options,
3681    job: &Job,
3682    started: std::time::Instant,
3683    result: &Compiled,
3684    stderr: &mut impl std::io::Write,
3685) -> bool {
3686    let Some(path) = &opts.trace else {
3687        return true;
3688    };
3689    let output = match &job.output {
3690        Output::Stdout => "-",
3691        Output::File(path) | Output::Temporary(path) => path,
3692    };
3693    let record = trace::Record {
3694        input: &job.input,
3695        output,
3696        ok: !result.failed(),
3697        total: started.elapsed(),
3698        timing: &result.timing,
3699    };
3700    match trace::append(path, &record) {
3701        Ok(()) => true,
3702        Err(e) => {
3703            let _ = writeln!(stderr, "rucc: error: {e}");
3704            false
3705        }
3706    }
3707}
3708
3709/// One line of `-time`, which is what a step was called and how long it took.
3710///
3711/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
3712/// no subprocess for anything but the link, so what is measured here is the wall clock of the
3713/// step and the second column is always zero. The shape of the line is kept because a person
3714/// reading it next to gcc's should not have to work out which column is which.
3715fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
3716    let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
3717}
3718
3719/// Writes one job's result where the plan said it goes.
3720///
3721/// # Errors
3722///
3723/// Returns the message to print, which names the file when there is one, because "permission
3724/// denied" on its own does not say which file was refused.
3725fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
3726    match output {
3727        Output::Stdout => {
3728            let mut stdout = std::io::stdout().lock();
3729            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
3730        }
3731        Output::File(path) | Output::Temporary(path) => {
3732            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
3733        }
3734    }
3735}
3736
3737/// The target a program name asks for, the way `aarch64-linux-gnu-gcc` is gcc for that target.
3738///
3739/// `program` is the path the compiler was started as. The name without its directory and without a
3740/// trailing `.exe` has to end in `-rucc`, and what comes before that has to be a target this
3741/// compiler knows, or there is no answer and the name means nothing. A link named `my-rucc` is
3742/// therefore just rucc and not an error.
3743pub fn target_from_program(program: &str) -> Option<String> {
3744    let name = program.rsplit(['/', '\\']).next()?;
3745    let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
3746    let triple = name.strip_suffix("-rucc")?;
3747    triple.parse::<Triple>().ok()?;
3748    Some(triple.to_owned())
3749}
3750
3751/// [`run`] for a compiler started as `program`, which is `argv[0]`.
3752///
3753/// A target taken from the name goes in front of `args`, so a `--target=` written on the command
3754/// line comes later and wins, which is what gcc and clang do with a prefixed name.
3755///
3756/// A name ending in `dlltool`, or `--dlltool` as the first argument, is [`dlltool::run`] instead,
3757/// which writes an import library and compiles nothing.
3758pub fn run_as(program: &str, args: &[String]) -> i32 {
3759    if dlltool::is_dlltool(program) {
3760        return dlltool::run(program, args);
3761    }
3762    if args.first().is_some_and(|first| first == "--dlltool") {
3763        return dlltool::run(program, &args[1..]);
3764    }
3765    match target_from_program(program) {
3766        Some(triple) => {
3767            let mut all = Vec::with_capacity(args.len() + 1);
3768            all.push(format!("--target={triple}"));
3769            all.extend_from_slice(args);
3770            run(&all)
3771        }
3772        None => run(args),
3773    }
3774}
3775
3776/// What `--version` prints.
3777///
3778/// The first line is ours and is the one every harness we have reads. The second is for build
3779/// systems that decide what kind of compiler they have by reading this text. Meson takes the GNU
3780/// path only when it finds "Free Software Foundation" here, and otherwise stops with "Unknown
3781/// compiler" before it has asked a single question, which is how the whole of a meson build is
3782/// lost to one sentence. Past that point meson reads the version from `__GNUC__` and asks the
3783/// preprocessor everything else, so the line decides the path and nothing more. It says what is
3784/// true, that rucc speaks the dialect of GCC 16, and it does not claim to be GCC.
3785fn banner() -> String {
3786    format!(
3787        "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"
3788    )
3789}
3790
3791/// Runs the driver and returns the process exit code.
3792///
3793/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
3794/// is the one place in the compiler that is true.
3795pub fn run(args: &[String]) -> i32 {
3796    match parse_args(args) {
3797        Ok(Action::Help) => {
3798            print!("{USAGE}");
3799            0
3800        }
3801        Ok(Action::Version) => {
3802            print!("{}", banner());
3803            0
3804        }
3805        Ok(Action::Print(line)) => {
3806            println!("{line}");
3807            0
3808        }
3809        Ok(Action::PrintConfig(opts)) => {
3810            print!("{}", print_config(&opts));
3811            0
3812        }
3813        Ok(Action::PrintPipeline(opts)) => {
3814            print!("{}", print_pipeline(&opts));
3815            0
3816        }
3817        Ok(Action::PrintPlan { opts, plan, link }) => {
3818            print!("{}", plan.render());
3819            // The line as it would be typed, which is the half of `-###` that section 4.3 says
3820            // arrives with the link. It is printed even when the linker is not on this machine,
3821            // because what a build wants from `-###` is what the compiler would do.
3822            if let Some(job) = &plan.link {
3823                match link_line(&opts, &link, job) {
3824                    Ok(line) => println!("{line}"),
3825                    Err(why) => {
3826                        let mut stderr = std::io::stderr().lock();
3827                        let _ = writeln!(stderr, "rucc: error: {why}");
3828                        return 1;
3829                    }
3830                }
3831            }
3832            0
3833        }
3834        Ok(Action::Fetch { what, target, cache }) => {
3835            let kernel = rucc_sysroot::Kernel::for_target(&cache, target)
3836                .map(|_| &rucc_sysroot::KERNEL_HEADERS);
3837            fetch_sysroot(what, kernel, target, &cache)
3838        }
3839        Ok(Action::FetchMsvcSdk { target, accepted, cache, pinned }) => msvc::fetch_msvc_sdk(
3840            target,
3841            accepted,
3842            &cache,
3843            pinned.then_some(&rucc_sysroot::PINNED_BUILD),
3844        ),
3845        Ok(Action::Compile { opts, plan, link, jobs, verbose, notes }) => {
3846            {
3847                let mut stderr = std::io::stderr().lock();
3848                // Before the plan rather than after it, because a note is about the command line
3849                // and the plan is what the command line was read as, so the reader wants the two
3850                // in that order.
3851                for note in &notes {
3852                    let _ = writeln!(stderr, "rucc: warning: {note}");
3853                }
3854                if verbose {
3855                    let _ = write!(stderr, "{}", plan.render());
3856                    let _ = writeln!(stderr, "workers: {}", jobs.count());
3857                    // What `gcc -v` says about headers, because meson and cmake read it to find the
3858                    // system directories.
3859                    let _ = write!(stderr, "{}", opts.search.render_gcc());
3860                }
3861            }
3862            if opts.emit == EmitKind::Preprocessed {
3863                return preprocess_all(&opts, &plan);
3864            }
3865            if opts.emit == EmitKind::Archive {
3866                return archive_all(&opts, &plan);
3867            }
3868            if opts.emit != EmitKind::Executable {
3869                return compile_all(&opts, &plan);
3870            }
3871            if let Some(why) = unlinkable(&opts) {
3872                let _ = writeln!(std::io::stderr().lock(), "rucc: error: {why}");
3873                return 1;
3874            }
3875            link_all(&opts, &plan, &link, verbose)
3876        }
3877        Err(e) => {
3878            let mut stderr = std::io::stderr().lock();
3879            let _ = writeln!(stderr, "rucc: error: {e}");
3880            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
3881            1
3882        }
3883    }
3884}
3885
3886/// Why a link that was asked for cannot be made, when that is known before anything is compiled.
3887///
3888/// The checked modes need `runtime/rucc-safe-rt` in the program, and that runtime is written
3889/// against Unix: shadow memory through `mmap`, reports through a signal handler, and the maps read
3890/// out of `/proc`. There is no Windows build of it, so a Windows program compiled with one used to
3891/// fail at the link with a page of undefined `__rucc_check_` names. Saying so before the link
3892/// is kinder until the port is done. Only the link is refused: an object or a listing built
3893/// with the checks in is still what was asked for, and is what a test of the instrumentation reads.
3894fn unlinkable(opts: &Options) -> Option<String> {
3895    (opts.safety.instruments() && opts.target.os == rucc_target::Os::Windows).then(|| {
3896        format!(
3897            "-fsafety={}: the checked modes are not available on a Windows target yet, because \
3898             the runtime they need has not been ported to Windows. -c still builds the object",
3899            opts.safety
3900        )
3901    })
3902}
3903
3904#[cfg(test)]
3905mod tests {
3906    use rucc_session::{
3907        Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
3908    };
3909
3910    use super::*;
3911
3912    fn args(s: &[&str]) -> Vec<String> {
3913        s.iter().map(|x| (*x).to_owned()).collect()
3914    }
3915
3916    /// A target to write down where the host would otherwise decide, for the tests whose answer
3917    /// would be a different one on a different machine.
3918    ///
3919    /// Most of the tests here never name a target, which is right, because most of what the driver
3920    /// does with a command line is the same wherever it runs and a test that pinned one would be
3921    /// saying so in every case for the sake of the two that need it. The two that need it are the
3922    /// ones whose answer comes off the target rather than off the command line: the name an object
3923    /// gets, which is `a.o` here and `a.obj` on Windows, and whether Microsoft's reading of a
3924    /// nameless member is on, which is off here and on there. Both are the compiler being right, and
3925    /// a test that leaves the target to the host is asking a question with two correct answers.
3926    const LINUX: &str = "--target=x86_64-unknown-linux-gnu";
3927
3928    #[test]
3929    fn a_response_file_is_split_the_way_libiberty_splits_one() {
3930        let words = response_words("-Wl,--as-needed  'a b' \"c d\"\ne\\ f '' \"it's\" g\\\\h\n");
3931        assert_eq!(words, ["-Wl,--as-needed", "a b", "c d", "e f", "", "it's", "g\\h"]);
3932        assert!(response_words(" \n\t").is_empty());
3933    }
3934
3935    #[test]
3936    fn a_response_file_on_the_command_line_is_read_in_its_place() {
3937        let dir = std::env::temp_dir().join(format!("rucc-rsp-{}", std::process::id()));
3938        std::fs::create_dir_all(&dir).unwrap();
3939        let inner = dir.join("inner.rsp");
3940        std::fs::write(&inner, "-lm\n").unwrap();
3941        let outer = dir.join("outer.rsp");
3942        // Backslashes doubled, because the file is split the way libiberty splits one and a
3943        // Windows path is full of them.
3944        let named = inner.display().to_string().replace('\\', "\\\\");
3945        std::fs::write(&outer, format!("-o 'my prog' -Wl,--as-needed @{named}\n")).unwrap();
3946        let line = args(&["x.o", &format!("@{}", outer.display()), "@no-such-file"]);
3947        assert_eq!(
3948            response_files(&line).unwrap(),
3949            args(&["x.o", "-o", "my prog", "-Wl,--as-needed", "-lm", "@no-such-file"])
3950        );
3951        let itself = dir.join("itself.rsp");
3952        let named = itself.display().to_string().replace('\\', "\\\\");
3953        std::fs::write(&itself, format!("@{named}")).unwrap();
3954        let looped = response_files(&args(&[&format!("@{}", itself.display())]));
3955        assert!(looped.is_err(), "a file that names itself should be refused");
3956        std::fs::remove_dir_all(&dir).unwrap();
3957    }
3958
3959    #[test]
3960    fn dlltool_mode_is_asked_for_first_or_by_the_program_name() {
3961        let dir = std::env::temp_dir().join(format!("rucc-dlltool-mode-{}", std::process::id()));
3962        std::fs::create_dir_all(&dir).unwrap();
3963        let def = dir.join("w.def");
3964        std::fs::write(&def, "LIBRARY w.dll\nEXPORTS\nw\n").unwrap();
3965        let def = def.display().to_string();
3966        let first = dir.join("first.a").display().to_string();
3967        let named = dir.join("named.a").display().to_string();
3968        let line = args(&["--dlltool", "-m", "i386:x86-64", "-d", &def, "-l", &first]);
3969        assert_eq!(run_as("rucc", &line), 0);
3970        // The prefix says the machine, as it does for a prefixed GNU dlltool.
3971        let line = args(&["-d", &def, "-l", &named]);
3972        assert_eq!(run_as("/opt/bin/x86_64-w64-mingw32-dlltool", &line), 0);
3973        assert_eq!(std::fs::read(&first).unwrap(), std::fs::read(&named).unwrap());
3974        std::fs::remove_dir_all(&dir).unwrap();
3975
3976        let later = parse_args(&args(&["x.c", "--dlltool", "-d", "x.def"])).unwrap_err();
3977        assert!(later.to_string().contains("first argument"), "{later}");
3978    }
3979
3980    #[test]
3981    fn help_and_version_win_over_everything_else() {
3982        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
3983        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
3984    }
3985
3986    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
3987        match parse_args(&args(s)).expect("expected a compilation") {
3988            Action::Compile { opts, plan, .. } => (opts, plan),
3989            other => panic!("expected a compilation, got {other:?}"),
3990        }
3991    }
3992
3993    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
3994        match parse_args(&args(s)).expect("expected a compilation") {
3995            Action::Compile { link, plan, .. } => (link, plan),
3996            other => panic!("expected a compilation, got {other:?}"),
3997        }
3998    }
3999
4000    fn notes(s: &[&str]) -> Vec<String> {
4001        match parse_args(&args(s)).expect("expected a compilation") {
4002            Action::Compile { notes, .. } => notes,
4003            other => panic!("expected a compilation, got {other:?}"),
4004        }
4005    }
4006
4007    /// The ordinary command line has nothing to say about itself, which is the property that makes
4008    /// a note worth reading when there is one.
4009    #[test]
4010    fn a_command_line_with_nothing_wrong_with_it_carries_no_notes() {
4011        assert_eq!(notes(&["-c", "a.c"]), Vec::<String>::new());
4012    }
4013
4014    /// `-g` for Windows is kept, and says nothing, now that the COFF writer has DWARF sections.
4015    #[test]
4016    fn debug_information_for_coff_is_kept() {
4017        assert_eq!(
4018            notes(&["--target=x86_64-windows-gnu", "-g", "-c", "a.c"]),
4019            Vec::<String>::new()
4020        );
4021        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-g", "-c", "a.c"]);
4022        assert!(opts.debug_info);
4023    }
4024
4025    /// A directory that is not there contributes nothing to the search path, so there is no tree to
4026    /// read a release out of and nothing to compare the pin against. Said as a test because this is
4027    /// the shape a hermetic machine takes: the probe reads the disk and every other machine has a
4028    /// different disk, so what can be asserted here is the silence.
4029    #[test]
4030    fn a_named_tree_that_is_not_on_the_machine_is_not_a_release_mismatch() {
4031        let said =
4032            notes(&["--target=x86_64-linux-gnu.2.28", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
4033        assert_eq!(said, Vec::<String>::new());
4034    }
4035
4036    #[test]
4037    fn collects_inputs_and_flags() {
4038        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
4039        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
4040        assert_eq!(paths, vec!["a.c", "b.c"]);
4041        assert_eq!(opts.opt_level, OptLevel::O2);
4042        assert_eq!(opts.emit, EmitKind::Object);
4043        assert!(opts.debug_info);
4044    }
4045
4046    /// The unstable options, which are spelled apart from everything else on purpose: what is
4047    /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
4048    #[test]
4049    fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
4050        let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
4051        assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
4052
4053        let (plain, _) = compile(&["-c", "a.c"]);
4054        assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
4055
4056        assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
4057        let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
4058        assert!(unknown.message.contains("4.11"), "{}", unknown.message);
4059    }
4060
4061    /// The other measurement written to a file, which reads the same way and fails the same way.
4062    #[test]
4063    fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
4064        let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
4065        assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
4066
4067        let (plain, _) = compile(&["-c", "a.c"]);
4068        assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
4069
4070        assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
4071    }
4072
4073    /// Which register allocator runs, asked for by name, and left to the level when it is not.
4074    #[test]
4075    fn the_register_allocator_is_asked_for_by_name() {
4076        let (opts, _) = compile(&["-c", "-O2", "-Zregalloc=backtracking", "a.c"]);
4077        assert_eq!(opts.backtracking, Some(true));
4078        let (opts, _) = compile(&["-c", "-O2", "-Zregalloc=single", "a.c"]);
4079        assert_eq!(opts.backtracking, Some(false));
4080        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
4081        assert_eq!(plain.backtracking, None, "the level decides unless it was asked for");
4082        assert!(parse_args(&args(&["-Zregalloc=graph", "a.c"])).is_err(), "not an allocator");
4083    }
4084
4085    /// The third one, which says what the pre-selection lowering group did.
4086    #[test]
4087    fn a_switch_shape_is_forced_by_name_and_only_by_one_it_has() {
4088        let (opts, _) = compile(&["-c", "-O2", "-Zswitch=walk", "a.c"]);
4089        assert_eq!(opts.switch_shape.as_deref(), Some("walk"));
4090        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
4091        assert_eq!(plain.switch_shape, None, "nothing is forced unless it was asked for");
4092        assert!(parse_args(&args(&["-Zswitch=bit-test", "a.c"])).is_err(), "not a shape it forces");
4093    }
4094
4095    #[test]
4096    fn where_the_lowering_dump_goes_is_asked_for_the_same_way() {
4097        let (opts, _) = compile(&["-c", "-O2", "-Zlowering=/tmp/lowering.txt", "a.c"]);
4098        assert_eq!(opts.lowering_dump.as_deref(), Some("/tmp/lowering.txt"));
4099
4100        let (plain, _) = compile(&["-c", "a.c"]);
4101        assert_eq!(plain.lowering_dump, None, "nothing is dumped unless it was asked for");
4102
4103        assert!(parse_args(&args(&["-Zlowering=", "a.c"])).is_err(), "no file named");
4104    }
4105
4106    /// Scheduling, which has the three way answer every optimization flag has: on, off, and
4107    /// nothing said, which is whatever the optimization level asks for. The name is gcc's, and
4108    /// gcc's has a two in it because gcc has a scheduler before allocation and one after and this
4109    /// is the one after.
4110    #[test]
4111    fn scheduling_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
4112        let (on, _) = compile(&["-c", "-O0", "-fschedule-insns2", "a.c"]);
4113        assert_eq!(on.schedule_insns, Some(true));
4114
4115        let (off, _) = compile(&["-c", "-O2", "-fno-schedule-insns2", "a.c"]);
4116        assert_eq!(off.schedule_insns, Some(false));
4117
4118        let (quiet, _) = compile(&["-c", "-O2", "a.c"]);
4119        assert_eq!(quiet.schedule_insns, None, "nothing said, so the level decides");
4120        assert!(quiet.opt_level.schedules(), "and at this level the level says yes");
4121
4122        let (none, _) = compile(&["-c", "a.c"]);
4123        assert!(!none.opt_level.schedules(), "at no optimization it says no");
4124    }
4125
4126    /// Tail calls, which gcc spells as sibling calls and turns on at `-O2` and `-Os`.
4127    #[test]
4128    fn sibling_calls_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
4129        let (on, _) = compile(&["-c", "-O1", "-foptimize-sibling-calls", "a.c"]);
4130        assert_eq!(on.sibling_calls, Some(true));
4131
4132        let (off, _) = compile(&["-c", "-O2", "-fno-optimize-sibling-calls", "a.c"]);
4133        assert_eq!(off.sibling_calls, Some(false));
4134
4135        let (quiet, _) = compile(&["-c", "-Os", "a.c"]);
4136        assert_eq!(quiet.sibling_calls, None, "nothing said, so the level decides");
4137        assert!(quiet.opt_level.sibling_calls(), "and at this level the level says yes");
4138
4139        let (one, _) = compile(&["-c", "-O1", "a.c"]);
4140        assert!(!one.opt_level.sibling_calls(), "gcc leaves them off at -O1");
4141    }
4142
4143    /// Whether the timing model is worth holding an instruction back over, which is a `-Z` because
4144    /// it is a question about a target's description rather than about the program being compiled.
4145    #[test]
4146    fn whether_the_timing_model_is_cycle_accurate_can_be_overridden() {
4147        let (yes, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=yes", "a.c"]);
4148        assert_eq!(yes.cycle_accurate_model, Some(true));
4149
4150        let (no, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=no", "a.c"]);
4151        assert_eq!(no.cycle_accurate_model, Some(false));
4152
4153        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
4154        assert_eq!(plain.cycle_accurate_model, None, "the target's own answer stands");
4155
4156        let bad = parse_args(&args(&["-Zcycle-accurate-model=maybe", "a.c"]))
4157            .expect_err("it takes yes or no");
4158        assert!(bad.message.contains("yes or no"), "{}", bad.message);
4159    }
4160
4161    #[test]
4162    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
4163        let (opts, _) = compile(&["-O", "a.c"]);
4164        assert_eq!(opts.opt_level, OptLevel::O1);
4165    }
4166
4167    #[test]
4168    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
4169        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
4170        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4171        assert_eq!(plan.jobs[1].kind, InputKind::C);
4172        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4173    }
4174
4175    #[test]
4176    fn dash_x_can_be_joined_to_its_language() {
4177        let (_, plan) = compile(&["a.o", "-xc", "b.txt", "-xnone", "c.o"]);
4178        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4179        assert_eq!(plan.jobs[1].kind, InputKind::C);
4180        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4181    }
4182
4183    #[test]
4184    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
4185        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
4186            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
4187            other => panic!("expected a compilation, got {other:?}"),
4188        };
4189        assert_eq!(jobs.count(), 4);
4190
4191        let default = match parse_args(&args(&["a.c"])).unwrap() {
4192            Action::Compile { jobs, .. } => jobs,
4193            other => panic!("expected a compilation, got {other:?}"),
4194        };
4195        assert_eq!(default, Jobs::available());
4196        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
4197    }
4198
4199    #[test]
4200    fn triple_hash_prints_the_plan_and_runs_nothing() {
4201        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
4202        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
4203        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
4204    }
4205
4206    #[test]
4207    fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
4208        // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
4209        // this, and following the compiler is what makes a build that reads either of them find
4210        // the files where they are.
4211        assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
4212        assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
4213        assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
4214        assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
4215        // The last one on the line decides, the way it does for every other flag with an
4216        // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
4217        // nothing and said nothing looks exactly like one where the files were not produced.
4218        let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
4219        assert_eq!(opts.save_temps, SaveTemps::Cwd);
4220        let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
4221        assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
4222    }
4223
4224    #[test]
4225    fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
4226        let (opts, plan) = compile(&["-c", "-time", "a.c"]);
4227        let (plain, without) = compile(&["-c", "a.c"]);
4228        assert!(opts.time);
4229        assert!(!plain.time);
4230        // Against the same line without the flag rather than against a spelling of the object's
4231        // name, since what the object is called is the host's business and this is not about that.
4232        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4233    }
4234
4235    #[test]
4236    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
4237        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
4238        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
4239    }
4240
4241    /// What `--fetch` says for a target this release pins nothing for, which today is every target
4242    /// but the three windows-gnu ones, the four musl ones and the eight glibc ones.
4243    #[test]
4244    fn a_fetch_of_a_target_nothing_is_pinned_for_says_so_rather_than_reaching_the_network() {
4245        let e = parse_args(&args(&["--fetch", "x86_64-linux-gnux32"])).unwrap_err();
4246        assert!(e.message.contains("pins no sysroot for x86_64-linux-gnux32"), "{}", e.message);
4247        // And what it does pin, because a release with some rows in the table and a release with
4248        // none are two situations and the second sentence is what tells them apart.
4249        assert!(e.message.contains("x86_64-windows-gnu"), "{}", e.message);
4250        // The joined spelling is the same flag.
4251        let joined = parse_args(&args(&["--fetch=x86_64-linux-gnux32"])).unwrap_err();
4252        assert_eq!(joined, e);
4253    }
4254
4255    /// The two targets a release will never pin, which is a different answer from the one above.
4256    ///
4257    /// Section 13.4. A person who reads "this release pins no sysroot yet" waits for a release that
4258    /// does, and no release of this compiler can ship either of these. An Apple target gets the
4259    /// licence and what to do instead, and a Microsoft one gets Microsoft's own files from
4260    /// Microsoft, which is the one lawful download either wall has behind it.
4261    #[test]
4262    fn a_fetch_of_a_target_behind_a_licence_wall_says_so_rather_than_saying_not_yet() {
4263        let e = parse_args(&args(&["--fetch", "aarch64-macos"])).unwrap_err();
4264        assert!(e.message.contains("Xcode licence"), "{}", e.message);
4265        assert!(e.message.contains("there never will be"), "{}", e.message);
4266        assert!(!e.message.contains("tamnd/rucc-cross"), "{}", e.message);
4267
4268        // Microsoft's side has a download behind it, which is Microsoft's own files from the build
4269        // this release pins, and the licence still has to be accepted for anything to move.
4270        let action = parse_args(&args(&["--fetch", "x86_64-windows-msvc"])).expect("pinned build");
4271        let Action::FetchMsvcSdk { target, accepted, pinned, .. } = action else {
4272            panic!("{action:?}")
4273        };
4274        assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
4275        assert!(pinned);
4276        assert!(!accepted);
4277        let action = parse_args(&args(&["--fetch=aarch64-windows-msvc", "--accept-licence"]))
4278            .expect("pinned build");
4279        let Action::FetchMsvcSdk { accepted, pinned, .. } = action else { panic!("{action:?}") };
4280        assert!(accepted && pinned);
4281        // And the mingw-w64 target next to it is ours to ship and published, so the same flag has
4282        // something to get rather than a licence to explain.
4283        let action = parse_args(&args(&["--fetch", "x86_64-windows-gnu"])).expect("it is pinned");
4284        let Action::Fetch { what, .. } = action else { panic!("{action:?}") };
4285        assert_eq!(what.tuple, "x86_64-windows-gnu");
4286    }
4287
4288    #[test]
4289    fn the_other_fetch_takes_a_target_behind_microsofts_wall_and_carries_the_acceptance() {
4290        // Both spellings of the flag, because a flag that takes a tuple gets written both ways.
4291        for line in [
4292            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc"],
4293            vec!["--fetch-msvc-sdk=x86_64-windows-msvc"],
4294        ] {
4295            let action = parse_args(&args(&line)).expect("that is a target behind the wall");
4296            let Action::FetchMsvcSdk { target, accepted, pinned, .. } = action else {
4297                panic!("{action:?}")
4298            };
4299            assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
4300            // Nothing on the line accepted anything, so nothing did.
4301            assert!(!accepted);
4302            // This one follows Microsoft's channel to whatever it names today.
4303            assert!(!pinned);
4304        }
4305
4306        // And both spellings of the word, because the prose here uses one and most of the people
4307        // typing this will reach for the other.
4308        for word in ["--accept-licence", "--accept-license"] {
4309            let action = parse_args(&args(&["--fetch-msvc-sdk", "aarch64-windows-msvc", word]))
4310                .expect("that is a target behind the wall");
4311            let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4312                panic!("{action:?}")
4313            };
4314            assert_eq!(target.to_canonical_string(), "aarch64-windows-msvc");
4315            assert!(accepted, "{word} should have been read");
4316        }
4317    }
4318
4319    #[test]
4320    fn the_other_fetch_refuses_the_command_lines_that_do_not_mean_anything() {
4321        // A tuple is what it gets, so a flag with nothing after it is not a command.
4322        let e = parse_args(&args(&["--fetch-msvc-sdk"])).unwrap_err();
4323        assert!(e.message.contains("requires the target"), "{}", e.message);
4324        let e = parse_args(&args(&["--fetch-msvc-sdk", "not-a-target"])).unwrap_err();
4325        assert!(e.message.contains("there is no SDK to get"), "{}", e.message);
4326
4327        // `--offline` forbids every download and this one asks for one, whichever order they came
4328        // in, which is the same answer `--fetch` gives.
4329        for line in [
4330            vec!["--offline", "--fetch-msvc-sdk", "x86_64-windows-msvc"],
4331            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc", "--offline"],
4332        ] {
4333            let e = parse_args(&args(&line)).unwrap_err();
4334            assert!(e.message.contains("two opposite things"), "{}", e.message);
4335        }
4336
4337        // It gets an SDK and compiles nothing, so a file on the same line would be read by nothing.
4338        let e = parse_args(&args(&["--fetch-msvc-sdk", "x86_64-windows-msvc", "a.c"])).unwrap_err();
4339        assert!(e.message.contains("compiles nothing"), "{}", e.message);
4340
4341        // The two fetches are two commands and a line that asked for both asked for neither.
4342        let e = parse_args(&args(&[
4343            "--fetch",
4344            "x86_64-windows-gnu",
4345            "--fetch-msvc-sdk",
4346            "x86_64-windows-msvc",
4347        ]))
4348        .unwrap_err();
4349        assert!(e.message.contains("two different commands"), "{}", e.message);
4350
4351        // And an acceptance with nothing to accept for is a command line that says something about
4352        // a licence no part of it goes near.
4353        let e = parse_args(&args(&["--accept-licence", "-c", "a.c"])).unwrap_err();
4354        assert!(e.message.contains("--fetch-msvc-sdk <tuple> for a"), "{}", e.message);
4355    }
4356
4357    /// An Apple target on a machine with no SDK, which is section 8.6's other host.
4358    ///
4359    /// Not run on a mac, where the SDK this is about is installed and the compile is the ordinary one
4360    /// that uses it. What the reason says is asserted in `rucc_sysroot::wall` and where it is printed
4361    /// is asserted in `rucc-pp`, so what is left here is that the driver works it out and leaves it
4362    /// where the preprocessor will find it, and that neither way past the wall leaves one behind.
4363    #[test]
4364    fn an_apple_target_with_no_sdk_anywhere_carries_the_licence_rather_than_a_missing_directory() {
4365        if cfg!(target_os = "macos") || std::env::var_os("SDKROOT").is_some() {
4366            return;
4367        }
4368        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4369        let why = opts.search.missing_system().expect("the wall is the reason there are none");
4370        assert!(why.contains("aarch64-macos needs a macOS SDK"), "{why}");
4371        assert!(why.contains("Xcode licence"), "{why}");
4372        assert!(why.contains("-isysroot"), "{why}");
4373
4374        // A program that includes none of the library needs none of the SDK, which is what section
4375        // 8.6 means by being able to target the platform without one, so there is nothing to explain.
4376        let (opts, _) = compile(&["--target=aarch64-macos", "-nostdinc", "-c", "a.c"]);
4377        assert_eq!(opts.search.missing_system(), None);
4378        // And naming a path is the other way through, whether or not the path is there: a mistyped
4379        // directory is a mistake to report on its own terms rather than a licence to explain.
4380        let (opts, _) = compile(&["--target=aarch64-macos", "-isysroot", "/opt/sdk", "-c", "a.c"]);
4381        assert_eq!(opts.search.missing_system(), None);
4382    }
4383
4384    /// The same wall on the compile side of an MSVC target, where the way past it is a tuple.
4385    ///
4386    /// Not run on Windows, for the same reason the one above is not run on a mac: the wall stands in
4387    /// front of an SDK this machine does not have, and a Windows machine is the kind that does. The
4388    /// driver asks `vswhere` where Visual Studio is and takes the newest kit under it, so on a box
4389    /// with the build tools installed there are headers, no wall and nothing here to be about.
4390    /// `INCLUDE` is the other way a machine has one and is the other half of the guard, since a
4391    /// person can set that anywhere while Visual Studio is only found on the platform it runs on.
4392    #[test]
4393    fn an_msvc_target_with_no_sdk_named_says_which_environment_needs_nothing_installed() {
4394        if cfg!(target_os = "windows") || std::env::var_os("INCLUDE").is_some() {
4395            return;
4396        }
4397        let (opts, _) = compile(&["--target=x86_64-windows-msvc", "-c", "a.c"]);
4398        let why = opts.search.missing_system().expect("the wall is the reason there are none");
4399        assert!(why.contains("the Windows SDK and its universal CRT"), "{why}");
4400        assert!(why.contains("mingw-w64"), "{why}");
4401        // And the mingw-w64 target has its headers from us, so nothing is missing to explain.
4402        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-c", "a.c"]);
4403        assert_eq!(opts.search.missing_system(), None);
4404    }
4405
4406    #[test]
4407    fn a_fetch_with_no_target_and_a_fetch_of_a_tuple_that_is_not_one_both_say_which() {
4408        let e = parse_args(&args(&["--fetch"])).unwrap_err();
4409        assert!(e.message.contains("--fetch requires"), "{}", e.message);
4410        let e = parse_args(&args(&["--fetch", "sparc64-solaris-gnu"])).unwrap_err();
4411        assert!(e.message.contains("--fetch sparc64-solaris-gnu"), "{}", e.message);
4412        assert!(e.message.contains("no sysroot to get"), "{}", e.message);
4413    }
4414
4415    /// Both flags on one line ask for opposite things, in either order.
4416    #[test]
4417    fn a_fetch_and_offline_together_is_a_refusal_whichever_way_round_they_are_written() {
4418        for line in [
4419            vec!["--offline", "--fetch", "x86_64-linux-musl"],
4420            vec!["--fetch", "x86_64-linux-musl", "--offline"],
4421        ] {
4422            let e = parse_args(&args(&line)).unwrap_err();
4423            assert!(e.message.contains("two opposite things"), "{}", e.message);
4424        }
4425    }
4426
4427    #[test]
4428    fn a_fetch_does_not_compile_anything_and_says_so_when_it_is_handed_a_file() {
4429        let e = parse_args(&args(&["--fetch", "x86_64-linux-musl", "a.c"])).unwrap_err();
4430        assert!(e.message.contains("compiles nothing"), "{}", e.message);
4431        assert!(e.message.contains("a.c"), "{}", e.message);
4432    }
4433
4434    /// `--offline` on its own is accepted and changes nothing, because an ordinary compile
4435    /// downloads nothing with or without it. A build that passes it everywhere is the case this is
4436    /// for, and it must not lose the compilation it was passed beside.
4437    #[test]
4438    fn offline_on_a_compilation_is_the_same_compilation() {
4439        let (opts, plan) = compile(&["-c", "--offline", "a.c"]);
4440        let (plain, without) = compile(&["-c", "a.c"]);
4441        assert_eq!(opts.target, plain.target);
4442        assert_eq!(plan.jobs.len(), without.jobs.len());
4443        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4444    }
4445
4446    #[test]
4447    fn a_deployment_target_comes_from_the_tuple_or_from_the_flag() {
4448        let version = |v: &str| rucc_tuple::Version::parse(v);
4449        let (opts, _) = compile(&["--target=aarch64-macos.13", "-c", "a.c"]);
4450        assert_eq!(opts.target, "aarch64-apple-darwin".parse().unwrap());
4451        assert_eq!(opts.os_version, version("13"));
4452        // The flag wins over the tuple, as it does under clang, and either spelling of it works.
4453        let (opts, _) =
4454            compile(&["--target=aarch64-macos.13", "-mmacosx-version-min=14.2", "-c", "a.c"]);
4455        assert_eq!(opts.os_version, version("14.2"));
4456        let (opts, _) = compile(&["--target=x86_64-macos", "-mmacos-version-min=12", "-c", "a.c"]);
4457        assert_eq!(opts.os_version, version("12"));
4458        // Nothing said leaves the platform's default to the target description.
4459        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4460        assert_eq!(opts.os_version, None);
4461        // A Linux build that always passes the flag is not an Apple build because of it.
4462        let (opts, _) =
4463            compile(&["--target=aarch64-linux-gnu", "-mmacosx-version-min=13", "-c", "a.c"]);
4464        assert_eq!(opts.os_version, None);
4465        let e = parse_args(&args(&["-mmacosx-version-min=thirteen", "a.c"])).unwrap_err();
4466        assert!(e.message.contains("is not a version"), "{}", e.message);
4467    }
4468
4469    #[test]
4470    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
4471        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
4472        assert!(e.message.contains("unknown option"), "{}", e.message);
4473    }
4474
4475    /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
4476    /// one directory needs the older rules and the rest of the tree does not.
4477    #[test]
4478    fn permissive_reads_in_both_directions_and_the_last_one_wins() {
4479        let (opts, _) = compile(&["-c", "a.c"]);
4480        assert!(!opts.permissive, "off unless it is asked for");
4481
4482        let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
4483        assert!(opts.permissive);
4484
4485        let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
4486        assert!(!opts.permissive);
4487    }
4488
4489    #[test]
4490    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
4491        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
4492        assert!(e.message.contains("trampoline"), "{}", e.message);
4493        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
4494    }
4495
4496    #[test]
4497    fn the_flag_every_configure_script_writes_is_taken() {
4498        // All four spellings, because a build writes whichever one its macros picked and a
4499        // compiler that takes three of them is a compiler that fails on the fourth.
4500        for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
4501            let (opts, _) = compile(&["-c", flag, "a.c"]);
4502            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4503        }
4504    }
4505
4506    #[test]
4507    fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
4508        let (opts, _) = compile(&["-c", "a.c"]);
4509        assert!(opts.unwinds(), "the default is off");
4510        let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
4511        assert!(!opts.unwinds(), "the build was not taken at its word");
4512        let (opts, _) = compile(&[
4513            "-c",
4514            "-fno-asynchronous-unwind-tables",
4515            "-fasynchronous-unwind-tables",
4516            "a.c",
4517        ]);
4518        assert!(opts.unwinds(), "the last flag did not win");
4519        // The weaker request, which the same table answers, so a line that asks for a table and
4520        // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
4521        // build turns the asynchronous one off globally and a directory asks for a table back.
4522        let (opts, _) =
4523            compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
4524        assert!(opts.unwinds(), "the weaker request was dropped");
4525        let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
4526        assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
4527        let (opts, _) =
4528            compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
4529        assert!(!opts.unwinds(), "both were turned off and one stayed on");
4530    }
4531
4532    #[test]
4533    fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
4534        // Every one of these is on a real build line somewhere and every one of them was an
4535        // unknown option. What they have in common is that the answer rucc gives is the answer
4536        // they ask for, so there is nothing to implement and nothing to refuse.
4537        for flag in [
4538            "-fstrict-aliasing",
4539            "-fno-strict-aliasing",
4540            "-fdelete-null-pointer-checks",
4541            "-fno-delete-null-pointer-checks",
4542            "-frounding-math",
4543            "-fno-rounding-math",
4544            "-fexcess-precision=standard",
4545            "-fexcess-precision=fast",
4546            "-fexcess-precision=16",
4547            "-pipe",
4548            "-cpp",
4549            "-fdiagnostics-color",
4550            "-fno-diagnostics-color",
4551            "-fdiagnostics-color=always",
4552            "-fdiagnostics-color=never",
4553            "-fdiagnostics-color=auto",
4554        ] {
4555            let (opts, _) = compile(&["-c", flag, "a.c"]);
4556            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4557        }
4558    }
4559
4560    #[test]
4561    fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
4562        let (opts, _) = compile(&["-c", "a.c"]);
4563        assert!(opts.trapping_math, "the default was not gcc's");
4564        let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
4565        assert!(!opts.trapping_math);
4566        let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
4567        assert!(opts.trapping_math, "spelling out the default turned it off");
4568        // The last one written wins, which is how a build line that inherits a flag from one
4569        // place and overrides it in another is read.
4570        let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
4571        assert!(opts.trapping_math);
4572    }
4573
4574    /// The flags a torture program writes on its own `dg-options` line, which is where most of
4575    /// these come from: a program reduced from a miscompilation names the pass that miscompiled
4576    /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
4577    /// tamnd/rucc#1019 is the list.
4578    #[test]
4579    fn no_inline_turns_off_the_inlining_of_a_function_declared_inline() {
4580        let (opts, _) = compile(&["-c", "-O2", "-fno-inline", "a.c"]);
4581        assert_eq!(opts.passes, [(rucc_opt::inline::NAME.to_owned(), false)]);
4582    }
4583
4584    #[test]
4585    fn inlining_a_function_called_once_is_turned_off_and_on_by_its_own_flag() {
4586        for level in ["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz", "-Og"] {
4587            let (opts, _) = compile(&["-c", level, "-fno-inline-functions-called-once", "a.c"]);
4588            assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), false)], "{level}");
4589            let (opts, _) = compile(&["-c", level, "-finline-functions-called-once", "a.c"]);
4590            assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), true)], "{level}");
4591        }
4592    }
4593
4594    #[test]
4595    fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
4596        for flag in [
4597            "-fno-tree-ccp",
4598            "-fno-tree-dominator-opts",
4599            "-fno-tree-vrp",
4600            "-fno-tree-bit-ccp",
4601            "-fno-tree-coalesce-vars",
4602            "-ftree-vectorize",
4603            "-ftree-loop-distribution",
4604            "-fipa-pta",
4605            "-fmodulo-sched",
4606            "-fno-vect-cost-model",
4607            "-fvect-cost-model=unlimited",
4608            "-fsimd-cost-model=cheap",
4609            "-fexpensive-optimizations",
4610            "-fno-early-inlining",
4611            "-finline-functions",
4612            "-foptimize-strlen",
4613            "-fno-ira-share-spill-slots",
4614        ] {
4615            let (opts, _) = compile(&["-c", flag, "a.c"]);
4616            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4617            assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
4618        }
4619    }
4620
4621    /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
4622    /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
4623    #[test]
4624    fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
4625        for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
4626            let (opts, _) = compile(&["-c", flag, "a.c"]);
4627            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4628        }
4629    }
4630
4631    /// A pass this compiler has keeps its flag, since the arms that read the registry are above
4632    /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
4633    /// is the program that writes it.
4634    #[test]
4635    fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
4636        let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
4637        assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
4638    }
4639
4640    /// gcc's name for the unroller reaches the unroller, in both directions. libtommath puts
4641    /// `-funroll-loops` in `CFLAGS` unconditionally, and before this it was an unknown option and
4642    /// the build stopped on its first file.
4643    #[test]
4644    fn the_gcc_spelling_of_the_unroller_turns_the_unroller_on_and_off() {
4645        let (opts, _) = compile(&["-c", "-funroll-loops", "a.c"]);
4646        assert_eq!(opts.passes, vec![("unroll".to_owned(), true)]);
4647        let (opts, _) = compile(&["-c", "-fno-unroll-loops", "a.c"]);
4648        assert_eq!(opts.passes, vec![("unroll".to_owned(), false)]);
4649    }
4650
4651    /// The three transformations that are a module at a time are named by a flag as well, even
4652    /// though none of them is a `rucc_opt::Pass` and so none is reached by the generic arms.
4653    ///
4654    /// A bisection over a miscompilation turns one thing off at a time, and a transformation with
4655    /// no spelling of its own cannot be the one turned off.
4656    #[test]
4657    fn the_transformations_that_are_not_passes_are_still_named_by_a_flag() {
4658        let (opts, _) = compile(&["-c", "-fno-ipa-cp", "-fipa-sra", "-fno-libcall", "a.c"]);
4659        assert_eq!(
4660            opts.passes,
4661            vec![
4662                (rucc_opt::ipcp::NAME.to_owned(), false),
4663                (rucc_opt::ipasra::NAME.to_owned(), true),
4664                (rucc_opt::libcall::NAME.to_owned(), false),
4665            ]
4666        );
4667        let (opts, _) = compile(&["-c", "-flibcall", "a.c"]);
4668        assert_eq!(opts.passes, vec![(rucc_opt::libcall::NAME.to_owned(), true)]);
4669    }
4670
4671    /// Where a function starts is a question this compiler answers, so the flag that asks about it
4672    /// is answered rather than dropped. femtolisp's Makefile writes the bare form on every compile
4673    /// of the project, and before this it was an unknown option and the build stopped on its first
4674    /// file. The numbers are gcc 16's, read off `-S` on x86-64: nothing and the bare form both
4675    /// give `.p2align 4`, `=32` gives 5, `=3` gives 2, and the negative form gives `.align 8`.
4676    #[test]
4677    fn the_alignment_of_a_function_is_a_request_this_compiler_can_answer() {
4678        let (opts, _) = compile(&["-c", "-falign-functions", "a.c"]);
4679        assert_eq!(opts.align_functions, None, "the bare form asks for the default");
4680
4681        let (opts, _) = compile(&["-c", "-falign-functions=32", "a.c"]);
4682        assert_eq!(opts.align_functions, Some(32));
4683
4684        let (opts, _) = compile(&["-c", "-falign-functions=3", "a.c"]);
4685        assert_eq!(opts.align_functions, Some(4), "rounded up rather than refused");
4686
4687        let (opts, _) = compile(&["-c", "-falign-functions=32:8", "a.c"]);
4688        assert_eq!(opts.align_functions, Some(32), "the boundary is the answerable half");
4689
4690        for flag in ["-falign-functions=0", "-falign-functions=1"] {
4691            let (opts, _) = compile(&["-c", flag, "a.c"]);
4692            assert_eq!(opts.align_functions, None, "{flag} means the default");
4693        }
4694
4695        let (opts, _) = compile(&["-c", "-fno-align-functions", "a.c"]);
4696        assert_eq!(opts.align_functions, Some(8), "the smallest boundary the target has");
4697
4698        // The last one on the line wins, which is how gcc reads a repeated flag.
4699        let (opts, _) = compile(&["-c", "-falign-functions=32", "-falign-functions", "a.c"]);
4700        assert_eq!(opts.align_functions, None);
4701
4702        let e = parse_args(&args(&["-c", "-falign-functions=big", "a.c"])).unwrap_err();
4703        assert!(e.message.contains("number of bytes"), "{}", e.message);
4704    }
4705
4706    /// The other three of the family are about padding inside a body, so none of them is about
4707    /// where a function starts. Every spelling of each, since a build writes whichever one its
4708    /// author typed.
4709    #[test]
4710    fn the_alignment_flags_about_the_inside_of_a_body_are_taken_and_say_nothing() {
4711        for flag in [
4712            "-falign-labels",
4713            "-falign-loops",
4714            "-falign-jumps",
4715            "-falign-loops=16",
4716            "-falign-labels=32",
4717            "-fno-align-loops",
4718            "-fno-align-labels",
4719            "-fno-align-jumps",
4720        ] {
4721            let (opts, _) = compile(&["-c", flag, "a.c"]);
4722            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4723            assert_eq!(opts.align_functions, None, "{flag} is not about where a function starts");
4724        }
4725    }
4726
4727    /// The loop flag in either direction is an answer, and a command line that wrote neither
4728    /// leaves the level to decide.
4729    #[test]
4730    fn the_loop_alignment_flag_is_answered_both_ways() {
4731        assert_eq!(compile(&["-c", "-O2", "a.c"]).0.align_loops, None);
4732        assert_eq!(compile(&["-c", "-O0", "-falign-loops", "a.c"]).0.align_loops, Some(true));
4733        assert_eq!(compile(&["-c", "-O2", "-fno-align-loops", "a.c"]).0.align_loops, Some(false));
4734        assert_eq!(compile(&["-c", "-falign-loops=32", "a.c"]).0.align_loops, None, "a number");
4735    }
4736
4737    /// The encoding of the source is not a question about speed, so the one name that describes
4738    /// what the preprocessor does is taken and every other name is refused.
4739    #[test]
4740    fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
4741        for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
4742            let (opts, _) = compile(&["-c", flag, "a.c"]);
4743            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4744        }
4745
4746        let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
4747        assert!(e.message.contains("latin1"), "{}", e.message);
4748        assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
4749    }
4750
4751    /// `-fnon-call-exceptions` turns exceptions on unless `-fexceptions` or `-fno-exceptions` was
4752    /// written, and the one written wins whichever side of it it is on, which is gcc 16's reading.
4753    #[test]
4754    fn exceptions_are_on_when_asked_for_and_non_call_ones_ask_unless_told_not_to() {
4755        let (opts, _) = compile(&["-c", "a.c"]);
4756        assert!(!opts.exceptions && !opts.non_call_exceptions, "gcc's default for C is off");
4757        let (opts, _) = compile(&["-c", "-fexceptions", "a.c"]);
4758        assert!(opts.exceptions && !opts.non_call_exceptions);
4759        let (opts, _) = compile(&["-c", "-fexceptions", "-fno-exceptions", "a.c"]);
4760        assert!(!opts.exceptions);
4761        let (opts, _) = compile(&["-c", "-fnon-call-exceptions", "a.c"]);
4762        assert!(opts.exceptions && opts.non_call_exceptions);
4763        for line in [
4764            ["-fno-exceptions", "-fnon-call-exceptions"],
4765            ["-fnon-call-exceptions", "-fno-exceptions"],
4766        ] {
4767            let (opts, _) = compile(&["-c", line[0], line[1], "a.c"]);
4768            assert!(!opts.exceptions && opts.non_call_exceptions, "{line:?}");
4769        }
4770        let (opts, _) =
4771            compile(&["-c", "-fnon-call-exceptions", "-fno-non-call-exceptions", "a.c"]);
4772        assert!(!opts.exceptions && !opts.non_call_exceptions);
4773        let (opts, _) = compile(&["-c", "-fno-delete-dead-exceptions", "a.c"]);
4774        assert_eq!(opts.emit, EmitKind::Object);
4775    }
4776
4777    /// `-ffast-math` used to be refused beside it and is the family it names now, with each
4778    /// member settable on its own and the last word on each winning, which is gcc's reading.
4779    #[test]
4780    fn fast_math_is_the_family_it_names_and_the_last_word_on_each_member_wins() {
4781        let both = |line: &[&str]| {
4782            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4783            let (link, _) = linking(&[line, &["a.c"]].concat());
4784            (opts, link)
4785        };
4786        let (opts, link) = both(&[]);
4787        assert_eq!(opts.math, Math::default());
4788        assert!(opts.trapping_math);
4789        assert!(!link.fast_math);
4790
4791        let (opts, link) = both(&["-ffast-math"]);
4792        assert!(opts.math.fast(opts.trapping_math), "{:?}", opts.math);
4793        assert!(!opts.trapping_math, "fast math turns trapping off");
4794        assert!(link.fast_math, "and it links the startup file");
4795
4796        // Taking one member back leaves the rest, and the whole is not fast math any more.
4797        let (opts, link) = both(&["-ffast-math", "-fno-finite-math-only"]);
4798        assert!(!opts.math.finite_only);
4799        assert!(!opts.math.errno && !opts.math.signed_zeros && opts.math.reciprocal);
4800        assert!(!opts.math.fast(opts.trapping_math));
4801        assert!(link.fast_math, "gcc's spec reads the flag and not the fields");
4802
4803        let (opts, _) = both(&["-ffast-math", "-ftrapping-math"]);
4804        assert!(opts.trapping_math);
4805        assert!(!opts.math.fast(opts.trapping_math));
4806        assert!(!opts.math.associative(opts.trapping_math));
4807
4808        let (opts, link) = both(&["-ffast-math", "-fno-fast-math"]);
4809        assert_eq!(opts.math, Math::default());
4810        assert!(opts.trapping_math);
4811        assert!(!link.fast_math);
4812
4813        // A member written alone is only that member.
4814        let (opts, link) = both(&["-fno-math-errno"]);
4815        assert_eq!(opts.math, Math { errno: false, ..Math::default() });
4816        assert!(opts.math.iec_559(opts.trapping_math), "errno is not an IEC 60559 question");
4817        assert!(!link.fast_math);
4818
4819        let (opts, link) = both(&["-funsafe-math-optimizations"]);
4820        assert!(opts.math.unsafe_math && opts.math.associative(opts.trapping_math));
4821        assert!(opts.math.errno && !opts.math.finite_only);
4822        assert!(link.fast_math);
4823    }
4824
4825    /// `-Ofast` is `-O3` with fast math as a default, which a later level and a
4826    /// `-fno-fast-math` on either side of it both take back.
4827    #[test]
4828    fn ofast_is_o3_with_fast_math_as_a_default_a_flag_can_take_back() {
4829        let both = |line: &[&str]| {
4830            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4831            let (link, _) = linking(&[line, &["a.c"]].concat());
4832            (opts, link)
4833        };
4834        let (opts, link) = both(&["-Ofast"]);
4835        assert_eq!(opts.opt_level, OptLevel::O3);
4836        assert!(opts.math.fast(opts.trapping_math));
4837        assert!(link.fast_math);
4838
4839        for line in [&["-Ofast", "-O2"][..], &["-fno-fast-math", "-Ofast"]] {
4840            let (opts, _) = both(line);
4841            assert!(!opts.math.fast(opts.trapping_math), "{line:?}");
4842        }
4843
4844        let (_, link) = both(&["-Ofast", "-mno-daz-ftz"]);
4845        assert_eq!(link.daz_ftz, Some(false));
4846    }
4847
4848    /// `-finstrument-functions` used to be refused beside those two, and it is taken now that the
4849    /// hooks are called. The last of it and its negative is the one that counts, as with any pair.
4850    #[test]
4851    fn instrument_functions_is_taken_and_the_last_of_the_pair_wins() {
4852        let (opts, _) = compile(&["-c", "-finstrument-functions", "a.c"]);
4853        assert!(opts.instrument_functions);
4854        let (opts, _) =
4855            compile(&["-c", "-finstrument-functions", "-fno-instrument-functions", "a.c"]);
4856        assert!(!opts.instrument_functions);
4857    }
4858
4859    #[test]
4860    fn a_tentative_definition_is_common_on_darwin_unless_told_otherwise() {
4861        // Two files each writing `int g;` link under `-fcommon` and do not without it, and Apple's
4862        // clang has it on where every other compiler rucc stands in for has it off.
4863        let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
4864        assert!(!Session::new(*opts).common());
4865
4866        let (opts, _) = compile(&["-c", "--target=aarch64-apple-darwin", "a.c"]);
4867        assert!(Session::new(*opts).common());
4868
4869        let (opts, _) = compile(&[LINUX, "-c", "-fcommon", "a.c"]);
4870        assert!(Session::new(*opts).common());
4871
4872        let (opts, _) =
4873            compile(&["-c", "--target=aarch64-apple-darwin", "-fcommon", "-fno-common", "a.c"]);
4874        assert!(!Session::new(*opts).common());
4875    }
4876
4877    #[test]
4878    fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
4879        for flag in ["-fno-pic", "-fno-pie"] {
4880            let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
4881            assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
4882            // The one it may have meant, since the two are a letter apart and one of them is
4883            // about linking and is taken.
4884            assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
4885        }
4886    }
4887
4888    #[test]
4889    fn a_program_name_with_a_known_target_in_front_of_rucc_picks_that_target() {
4890        let t = |p: &str| target_from_program(p);
4891        assert_eq!(t("aarch64-linux-gnu-rucc").as_deref(), Some("aarch64-linux-gnu"));
4892        assert_eq!(t("/usr/bin/riscv64-linux-musl-rucc").as_deref(), Some("riscv64-linux-musl"));
4893        assert_eq!(t(r"C:\bin\x86_64-windows-gnu-rucc.exe").as_deref(), Some("x86_64-windows-gnu"));
4894        assert_eq!(t("rucc"), None);
4895        assert_eq!(t("/usr/local/bin/rucc"), None);
4896        assert_eq!(t("my-rucc"), None);
4897        assert_eq!(t("sparc64-linux-gnu-rucc"), None);
4898        assert_eq!(t("aarch64-linux-gnu-gcc"), None);
4899    }
4900
4901    #[test]
4902    fn an_unsupported_target_names_itself() {
4903        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
4904        assert!(e.message.contains("sparc64"), "{}", e.message);
4905    }
4906
4907    #[test]
4908    fn no_inputs_is_an_error_but_print_config_needs_none() {
4909        assert!(parse_args(&args(&[])).is_err());
4910        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
4911    }
4912
4913    #[test]
4914    fn print_config_reports_the_target_it_was_given_not_the_host() {
4915        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
4916        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
4917        let text = print_config(&opts);
4918        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
4919        assert!(text.contains("char-signed: false"), "{text}");
4920        assert!(text.contains("object-format: elf"), "{text}");
4921        assert!(text.contains("va-list: void-pointer"), "{text}");
4922        // RISC-V has a register file and this compiler has not written it down yet, and the
4923        // dump says which of those two it is rather than leaving the line out.
4924        assert!(text.contains("registers: none"), "{text}");
4925        assert!(text.contains("timing-model: none"), "{text}");
4926    }
4927
4928    /// The model the schedule was chosen with, which is a receipt anybody comparing two runs of a
4929    /// benchmark needs: two numbers that disagree are usually two models and not two compilers.
4930    #[test]
4931    fn print_config_names_the_model_the_schedule_was_chosen_with() {
4932        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4933        let text = print_config(&opts);
4934        let line = text.lines().find(|l| l.starts_with("timing-model:")).expect("the model");
4935        assert!(line.contains("Skylake"), "{line}");
4936        assert!(line.contains("published"), "a sentence saying where it came from: {line}");
4937    }
4938
4939    #[test]
4940    fn print_config_has_one_key_per_line_and_a_fixed_order() {
4941        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4942        let text = print_config(&opts);
4943        let keys: Vec<&str> =
4944            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
4945        assert_eq!(keys[0], "version");
4946        assert_eq!(keys[1], "target");
4947        assert_eq!(keys.len(), 26);
4948        assert!(text.ends_with('\n'));
4949    }
4950
4951    #[test]
4952    fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4953        let (opts, _) = compile(&["a.c"]);
4954        assert_eq!(opts.safety, rucc_session::Safety::Off);
4955
4956        for (flag, tier) in [
4957            ("-fsafety=detect", rucc_session::Safety::Detect),
4958            ("-fsafety=enforce", rucc_session::Safety::Enforce),
4959            ("-fsafety=kernel", rucc_session::Safety::Kernel),
4960            ("-fsafety=off", rucc_session::Safety::Off),
4961        ] {
4962            let (opts, _) = compile(&[flag, "a.c"]);
4963            assert_eq!(opts.safety, tier, "{flag}");
4964        }
4965
4966        // The last one wins, the way every other repeated flag on this command line does.
4967        let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
4968        assert_eq!(opts.safety, rucc_session::Safety::Off);
4969
4970        // A misspelled tier is refused rather than ignored. Silently compiling without the
4971        // monitor a build asked for is the one failure mode this feature cannot have.
4972        let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
4973        assert!(e.message.contains("is not a safety tier"), "{}", e.message);
4974        assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
4975    }
4976
4977    /// A checked mode on a Windows target is refused at the link, with a message that says why,
4978    /// rather than left to fail there on names the runtime would have defined. The object is
4979    /// still built, and every other target links as before.
4980    #[test]
4981    fn a_checked_mode_on_windows_is_refused_at_the_link_and_nowhere_else() {
4982        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-fsafety=detect", "a.c"]);
4983        let why = unlinkable(&opts).expect("a refusal");
4984        assert!(why.contains("not available on a Windows target"), "{why}");
4985        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-fsafety=off", "a.c"]);
4986        assert_eq!(unlinkable(&opts), None);
4987        let (opts, _) = compile(&["--target=x86_64-linux-gnu", "-fsafety=detect", "a.c"]);
4988        assert_eq!(unlinkable(&opts), None);
4989    }
4990
4991    #[test]
4992    fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4993        // The default is the one section 9.3 of document 09 gives library code, which is that
4994        // padding does not participate, so a record filled a member at a time is not reported.
4995        let (opts, _) = compile(&["a.c"]);
4996        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4997
4998        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
4999        assert_eq!(opts.padding, rucc_session::Padding::Tracked);
5000
5001        let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
5002        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
5003
5004        // The tier is still a tier. A flag whose name starts the same way must not be eaten by
5005        // the one above it, which is the thing worth pinning about a pair of names like these.
5006        let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
5007        assert_eq!(opts.safety, rucc_session::Safety::Off);
5008
5009        let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
5010        assert!(e.message.contains("is not a padding mode"), "{}", e.message);
5011    }
5012
5013    #[test]
5014    fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
5015        // Off by default, because a store to allocated storage sets its effective type and C 6.5
5016        // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
5017        let (opts, _) = compile(&["a.c"]);
5018        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
5019
5020        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
5021        assert_eq!(opts.subobject, rucc_session::Subobject::Members);
5022
5023        let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
5024        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
5025
5026        // It takes no value. The form that would take one is the strict reading of section 9.4,
5027        // which is not written yet, so say so rather than accept a spelling that does nothing.
5028        let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
5029        assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
5030    }
5031
5032    #[test]
5033    fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
5034        // Off by default, because the record a block keeps is the union of what each pointer
5035        // reached, so two pointers striding through one array without landing on the same byte are
5036        // reported and by the letter of the standard those are different objects. Row Y8 is a build
5037        // deciding it would rather know.
5038        let (opts, _) = compile(&["a.c"]);
5039        assert_eq!(opts.promise, rucc_session::Promise::Off);
5040
5041        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
5042        assert_eq!(opts.promise, rucc_session::Promise::Blocks);
5043
5044        let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
5045        assert_eq!(opts.promise, rucc_session::Promise::Off);
5046
5047        // The tier is still a tier, which is the thing worth pinning about a pair of names where
5048        // one is the front of the other.
5049        let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
5050        assert_eq!(opts.safety, rucc_session::Safety::Off);
5051
5052        let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
5053        assert!(e.message.contains("takes no value"), "{}", e.message);
5054    }
5055
5056    #[test]
5057    fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
5058        // Three modes rather than a bare flag, because section 9.5 gives two answers that record
5059        // the same thing and report different classes, so a flag with no value could not say which
5060        // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
5061        // argument: this is the one plane where an edge nobody interposed costs a false report.
5062        let (opts, _) = compile(&["a.c"]);
5063        assert_eq!(opts.races, rucc_session::Races::Off);
5064
5065        let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
5066        assert_eq!(opts.races, rucc_session::Races::Metadata);
5067
5068        let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
5069        assert_eq!(opts.races, rucc_session::Races::Pointer);
5070
5071        // Last one wins, as it does for every other mode flag here.
5072        let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
5073        assert_eq!(opts.races, rucc_session::Races::Off);
5074
5075        let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
5076        assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
5077    }
5078
5079    #[test]
5080    fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
5081        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
5082        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5083        let text = print_pipeline(&opts);
5084        assert!(text.starts_with("level: -O2\n"), "{text}");
5085        assert!(text.contains("fold"), "{text}");
5086
5087        let a = parse_args(&args(&["--print-pipeline"])).unwrap();
5088        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5089        // Two passes run at `-O0` and neither is an optimization. The first moves what
5090        // `__builtin_expect` said onto the branch and takes the instruction away, so that nothing
5091        // past the optimizer has to know the instruction exists. The second removes code nothing
5092        // reaches. See issue 359.
5093        assert!(print_pipeline(&opts).contains("1: expect,"), "{}", print_pipeline(&opts));
5094        assert!(print_pipeline(&opts).contains("2: simplify-cfg,"), "{}", print_pipeline(&opts));
5095
5096        let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
5097        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5098        // The second turns off and the first does not, because nothing below the optimizer lowers
5099        // what it removes, so `-fno-expect` is a compile that stops rather than one that runs.
5100        let text = print_pipeline(&opts);
5101        assert!(text.contains("1: expect,"), "{text}");
5102        assert!(!text.contains("simplify-cfg"), "{text}");
5103    }
5104
5105    #[test]
5106    fn print_pipeline_takes_the_toggles_into_account() {
5107        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
5108        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5109        let text = print_pipeline(&opts);
5110        // The one that was named is gone and the rest of the level is not, which is the whole
5111        // of what a toggle promises.
5112        assert!(!text.contains("fold"), "{text}");
5113        assert!(text.contains("dce"), "{text}");
5114
5115        // Every pass the compiler has, named off. Built from the registry rather than written
5116        // out, so a pass added later is turned off here too and this keeps testing the thing it
5117        // is about, which is that the toggles can empty a level down to the passes that are not
5118        // optional. Those are named, because a listing that is all of them is a level nobody
5119        // emptied and the assertion would pass while saying nothing.
5120        let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
5121        off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
5122        let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
5123        let a = parse_args(&args(&spelled)).unwrap();
5124        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5125        let text = print_pipeline(&opts);
5126        let left: Vec<&str> =
5127            rucc_opt::PASSES.iter().filter(|p| p.required()).map(|p| p.name()).collect();
5128        assert_eq!(left, vec!["expect", "constant-p"], "{text}");
5129        for (at, name) in left.iter().enumerate() {
5130            assert!(text.contains(&format!("{}: {name},", at + 1)), "{text}");
5131        }
5132        assert!(!text.contains("dce"), "{text}");
5133    }
5134
5135    #[test]
5136    fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
5137        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
5138        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5139        assert!(!print_pipeline(&opts).contains("global fuel"));
5140
5141        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
5142        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
5143        let text = print_pipeline(&opts);
5144        // Because the listing is the answer to what this compilation will do, and a run that
5145        // stops after four rewrites is not doing what the level says it does.
5146        assert!(text.contains("global fuel: 4"), "{text}");
5147    }
5148
5149    /// A pass is turned on and off by its own name, and the order the flags were given in is
5150    /// kept, because the last spelling of a name is the one that decides.
5151    #[test]
5152    fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
5153        let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
5154        assert_eq!(
5155            opts.passes,
5156            [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
5157        );
5158
5159        let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
5160        assert!(e.message.contains("unknown option"), "{}", e.message);
5161    }
5162
5163    #[test]
5164    fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
5165        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
5166        assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
5167
5168        let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
5169        assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
5170        let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
5171        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
5172        let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
5173        assert!(e.message.contains("not a number"), "{}", e.message);
5174    }
5175
5176    #[test]
5177    fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
5178        let (opts, _) = compile(&["-c", "-O2", "a.c"]);
5179        assert_eq!(opts.pass_fuel_global, None);
5180
5181        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
5182        assert_eq!(opts.pass_fuel_global, Some(12));
5183        // And it is not the per pass flag with a longer name, so neither spelling swallows the
5184        // other.
5185        assert!(opts.pass_fuel.is_empty());
5186
5187        let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
5188        assert!(e.message.contains("not a number"), "{}", e.message);
5189    }
5190
5191    #[test]
5192    fn the_trace_file_is_taken_from_the_flag_and_an_empty_one_is_refused() {
5193        let (opts, _) = compile(&["-c", "a.c"]);
5194        assert_eq!(opts.trace, None);
5195        let (opts, _) = compile(&["-c", "-frucc-trace=/tmp/compile.jsonl", "a.c"]);
5196        assert_eq!(opts.trace.as_deref(), Some("/tmp/compile.jsonl"));
5197        let e = parse_args(&args(&["-frucc-trace=", "a.c"])).unwrap_err();
5198        assert!(e.message.contains("needs a file"), "{}", e.message);
5199    }
5200
5201    #[test]
5202    fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
5203        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
5204        assert_eq!(
5205            opts.pass_gates,
5206            [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
5207            "the order is what decides, so it has to survive the parse"
5208        );
5209
5210        let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
5211        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
5212        let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
5213        assert!(e.message.contains("ends before it starts"), "{}", e.message);
5214        let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
5215        assert!(e.message.contains("is empty"), "{}", e.message);
5216    }
5217
5218    #[test]
5219    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
5220        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
5221        let text = print_pipeline(&opts);
5222        assert!(text.contains("fold, "), "{text}");
5223        assert!(text.contains("[off for main]"), "{text}");
5224    }
5225
5226    /// The spelling is checked while the arguments are read, because a dump that names a pass
5227    /// this compiler does not have is a typo, and a typo found after the compilation has run is
5228    /// found too late to be any use.
5229    #[test]
5230    fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
5231        let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
5232        assert_eq!(opts.dump_ir, ["all", "after-fold"]);
5233
5234        let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
5235        assert!(e.message.contains("nosuch"), "{}", e.message);
5236        assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
5237    }
5238
5239    /// Every spelling `-fopt-info` takes, and the one it does not.
5240    ///
5241    /// The keywords are checked here for the same reason a dump's pass name is: a person who
5242    /// misspelled one gets no output, and no output is also what a compilation where nothing
5243    /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
5244    #[test]
5245    fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
5246        let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
5247        assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
5248        assert_eq!(opts.opt_info_file, None, "and goes to standard error");
5249
5250        let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
5251        assert_eq!(opts.opt_info, ["missed-note"]);
5252
5253        // Two flags add up rather than the second replacing the first, and the file is the last
5254        // one that named a file, which is how GCC treats both.
5255        let (opts, _) =
5256            compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
5257        assert_eq!(opts.opt_info, ["missed", "all"]);
5258        assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
5259
5260        let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
5261        assert!(e.message.contains("vectorized"), "{}", e.message);
5262        assert!(e.message.contains("`missed`"), "{}", e.message);
5263        let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
5264        assert!(e.message.contains("no file"), "{}", e.message);
5265    }
5266
5267    #[test]
5268    fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
5269        let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
5270        assert!(opts.verify_each);
5271        assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
5272    }
5273
5274    #[test]
5275    fn dash_o_needs_an_argument() {
5276        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
5277        assert_eq!(e.message, "-o requires an argument");
5278    }
5279
5280    #[test]
5281    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
5282        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
5283        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
5284        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
5285    }
5286
5287    #[test]
5288    fn the_include_flags_land_on_the_chain_each_one_names() {
5289        // A sysroot with nothing under it, so that the library's own directories are the
5290        // same on every machine this test runs on, which is none of them.
5291        let (opts, _) = compile(&[
5292            "-Ii",
5293            "-iquote",
5294            "q",
5295            "-isystem",
5296            "sys",
5297            "-idirafter",
5298            "after",
5299            "--sysroot=/nowhere-at-all",
5300            "a.c",
5301        ]);
5302        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5303        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
5304        // which is where GCC puts its own: a directory the user named outranks ours.
5305        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
5306        assert!(!opts.search.dirs()[1].is_system);
5307        assert!(opts.search.dirs()[2].is_system);
5308    }
5309
5310    #[test]
5311    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
5312        // Which machine this runs on decides what is on the path, so the test is about the
5313        // order rather than about the names: ours is on it, the library's follow it, and
5314        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
5315        let (opts, _) = compile(&["a.c"]);
5316        let dirs = opts.search.dirs();
5317        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
5318        assert_eq!(ours, Some(0), "{dirs:?}");
5319        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
5320        let (bare, _) = compile(&["-nostdinc", "a.c"]);
5321        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
5322    }
5323
5324    #[test]
5325    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
5326        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
5327        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5328        assert_eq!(dirs, ["sys", runtime::DIR]);
5329    }
5330
5331    #[test]
5332    fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
5333        // The target is not the machine this test runs on wherever it runs, so the answer is the
5334        // same on all of them: the libc's two include directories for that target, the kernel's
5335        // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
5336        // program that builds on the build machine and is wrong everywhere else.
5337        let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
5338        let dirs: Vec<&std::path::Path> =
5339            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5340        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
5341        let kernel = cache::dir().join("kernel-headers");
5342        assert_eq!(dirs.len(), 5, "{dirs:?}");
5343        assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
5344        assert_eq!(dirs[1], root.join("include").join("riscv64"));
5345        assert_eq!(dirs[2], root.join("include").join("generic"));
5346        // The kernel's, which are beside the sysroots rather than inside one, because every target
5347        // that shares an architecture reads the same files.
5348        assert_eq!(dirs[3], kernel.join("riscv"));
5349        assert_eq!(dirs[4], kernel.join("generic"));
5350    }
5351
5352    #[test]
5353    fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
5354        // The other side of the same answer. Windows has its own system headers and no `linux/` at
5355        // all, so the list is the libc's own and the question never arises, which is the `None` that
5356        // `link::cross_kernel` returns rather than a directory nothing would be found in.
5357        //
5358        // The libc's own is one directory rather than two here, because mingw-w64 publishes a single
5359        // header tree for every architecture and `Sysroot::splits_by_arch` says so.
5360        let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
5361        let dirs: Vec<&std::path::Path> =
5362            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5363        assert_eq!(dirs.len(), 2, "{dirs:?}");
5364        assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
5365    }
5366
5367    #[test]
5368    fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
5369        // One tree serves every glibc release, so the release is what the target supplies, and the
5370        // condition is the same one that chose the directories. A host glibc and a tree somebody
5371        // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
5372        // different values is a warning on every compilation of every file.
5373        //
5374        // The architecture is chosen against this machine's rather than written down, because the
5375        // bundled tree is only in effect for a target that is not this machine. The first version of
5376        // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
5377        // Linux runner, so it passed here and failed there.
5378        //
5379        // Unless this machine has the distribution's cross packages for it and nothing fetched, and
5380        // then those are the headers and their own `features.h` says the release, as it does for a
5381        // tree somebody named.
5382        let gnu = format!("--target={}-linux-gnu", cross_arch());
5383        let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
5384        let (link, _) = linking(&[&gnu, "-c", "a.c"]);
5385        let distro = link::distro_cross(bundled.target, &link).is_some();
5386        assert_eq!(bundled.glibc_minor, if distro { None } else { Some(44) });
5387        let pin = format!("{gnu}.2.28");
5388        let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
5389        assert_eq!(pinned.glibc_minor, Some(28));
5390
5391        let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5392        assert_eq!(named.glibc_minor, None);
5393        let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
5394        assert_eq!(none.glibc_minor, None);
5395        let musl = format!("--target={}-linux-musl", cross_arch());
5396        let (musl, _) = compile(&[&musl, "-c", "a.c"]);
5397        assert_eq!(musl.glibc_minor, None);
5398
5399        // And this machine's own target gets nothing, whatever this machine is, because its headers
5400        // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
5401        // that is the case this test had backwards; on a mac it is true for the other reason, which
5402        // is that Darwin is not a glibc target at all.
5403        if let Some(host) = Triple::host() {
5404            let native = format!("--target={}", host.tuple());
5405            let (native, _) = compile(&[&native, "-c", "a.c"]);
5406            assert_eq!(native.glibc_minor, None);
5407        }
5408    }
5409
5410    #[test]
5411    fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
5412        // The end to end half of the answer in `link::cross_for`. A release named for this machine's
5413        // own target is a cross compile, so the headers are the bundled tree's and the macro says
5414        // what was asked for rather than what this machine has.
5415        //
5416        // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
5417        // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
5418        // where the case lives.
5419        let Some(host) = Triple::host() else { return };
5420        if host.os != rucc_target::Os::Linux || host.env != rucc_target::Env::Gnu {
5421            return;
5422        }
5423        let pin = format!("--target={}.2.28", host.tuple());
5424        let (opts, _) = compile(&[&pin, "-c", "a.c"]);
5425        assert_eq!(opts.glibc_minor, Some(28));
5426        let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
5427        let dirs: Vec<&std::path::Path> =
5428            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5429        assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
5430        // And nothing of this machine's, which is the failure this was: a program compiled against
5431        // 2.44 declarations and told it was 2.28.
5432        assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
5433    }
5434
5435    /// An architecture that is not this machine's, out of the three the driver has targets for.
5436    ///
5437    /// A test about the bundled sysroot has to name a target that is not the host, because a target
5438    /// that is the host reads the host's own headers and libraries. Asking which machine this is
5439    /// beats picking a row and hoping, and it is two lines.
5440    fn cross_arch() -> &'static str {
5441        match Triple::host().map(|host| host.arch) {
5442            Some(rucc_target::Arch::X86_64) => "aarch64",
5443            _ => "x86_64",
5444        }
5445    }
5446
5447    #[test]
5448    fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
5449        // Both versions in the message, because the two things a person can do about it are pin a
5450        // release the tree has and name a sysroot that has the one they asked for, and neither is a
5451        // choice they can make without knowing which release the tree is.
5452        //
5453        // Not this machine's architecture, for the reason the test above gives: the refusal is about
5454        // the bundled tree, and the bundled tree is not what a target that is this machine reads.
5455        let target = format!("--target={}-linux-gnu.2.99", cross_arch());
5456        let message = refused(&[&target, "-c", "a.c"]);
5457        assert!(message.contains("asked for glibc 2.99"), "{message}");
5458        assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
5459        assert!(message.contains("--sysroot"), "{message}");
5460    }
5461
5462    #[test]
5463    fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
5464        // The tree somebody assembled beats the one we would build, on the headers as on the
5465        // libraries. It is empty here, which is why the list comes out short: the directories under
5466        // it are checked for rather than assumed, and a tree that is not there offers nothing.
5467        let (opts, _) =
5468            compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5469        let dirs: Vec<&std::path::Path> =
5470            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5471        assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
5472    }
5473
5474    #[test]
5475    fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
5476        let (opts, _) =
5477            compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
5478        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5479        assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
5480        // An angled include sees only what came after the flag.
5481        assert_eq!(opts.search.start(IncludeForm::Angled), 2);
5482        assert!(!opts.search.searches_current_dir());
5483    }
5484
5485    #[test]
5486    fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
5487        let (opts, _) = compile(&[
5488            "-iprefix",
5489            "/tools/",
5490            "-iwithprefix",
5491            "late",
5492            "-iwithprefixbefore",
5493            "early",
5494            "-iprefix",
5495            "/other/",
5496            "-iwithprefix",
5497            "last",
5498            "-nostdinc",
5499            "a.c",
5500        ]);
5501        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5502        // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
5503        // puts them rather than where its manual says it does.
5504        assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
5505        assert!(!opts.search.dirs()[0].is_system);
5506        assert!(opts.search.dirs()[1].is_system);
5507    }
5508
5509    #[test]
5510    fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
5511        let (opts, _) =
5512            compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
5513        let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
5514        assert_eq!(names, ["one.h", "two.h", "3.h"]);
5515        assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
5516    }
5517
5518    #[test]
5519    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
5520        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
5521        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5522        assert_eq!(dirs, ["i"]);
5523    }
5524
5525    #[test]
5526    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
5527        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
5528        assert_eq!(opts.std, Std::C11);
5529        assert!(opts.gnu_extensions);
5530
5531        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
5532        assert_eq!(opts.std, Std::C99);
5533        assert!(!opts.gnu_extensions);
5534
5535        let (opts, _) = compile(&["-ansi", "a.c"]);
5536        assert_eq!(opts.std, Std::C89);
5537        assert!(!opts.gnu_extensions);
5538
5539        let (opts, _) = compile(&["-std=gnu2y", "a.c"]);
5540        assert_eq!(opts.std, Std::C2y);
5541        assert!(opts.gnu_extensions);
5542
5543        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
5544        assert!(e.message.contains("unknown dialect"), "{}", e.message);
5545    }
5546
5547    #[test]
5548    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
5549        let (opts, _) = compile(&["-dM", "a.c"]);
5550        assert!(opts.dumps.macros);
5551
5552        // Packed, the way GCC takes them, and a letter in the family we have not written yet
5553        // is accepted and does nothing rather than failing a build.
5554        let (opts, _) = compile(&["-dDM", "a.c"]);
5555        assert!(opts.dumps.macros);
5556        let (opts, _) = compile(&["-dD", "a.c"]);
5557        assert!(!opts.dumps.macros);
5558
5559        let (opts, _) = compile(&["a.c"]);
5560        assert!(!opts.dumps.any());
5561
5562        // `-dumpversion` is a different flag that happens to start the same way, and it is read
5563        // as itself rather than as a dump of nothing.
5564        assert_eq!(printed(&["-dumpversion", "a.c"]), "16");
5565    }
5566
5567    #[test]
5568    fn the_msvc_runtime_is_a_compile_flag_and_a_link_one() {
5569        let (link, _) = linking(&["a.c"]);
5570        assert_eq!(link.crt, rucc_sysroot::Crt::Static);
5571        let (link, _) = linking(&["-fms-runtime-lib=dll", "a.c"]);
5572        assert_eq!(link.crt, rucc_sysroot::Crt::Dll);
5573        let (opts, _) = compile(&["-fms-runtime-lib=dll", "-c", "a.c"]);
5574        assert!(opts.ms_dll_runtime);
5575        let (opts, _) = compile(&["-fms-runtime-lib=dll", "-fms-runtime-lib=static", "-c", "a.c"]);
5576        assert!(!opts.ms_dll_runtime, "the last one wins");
5577        let e = parse_args(&args(&["-fms-runtime-lib=dll_dbg", "a.c"])).unwrap_err();
5578        assert!(e.message.contains("debug"), "{}", e.message);
5579        let e = parse_args(&args(&["-fms-runtime-lib=shared", "a.c"])).unwrap_err();
5580        assert!(e.message.contains("static or dll"), "{}", e.message);
5581    }
5582
5583    #[test]
5584    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
5585        let (opts, _) = compile(&["a.c"]);
5586        assert_eq!(
5587            opts.gnuc,
5588            GnucVersion { major: 16, minor: 0, patch: 0 },
5589            "the release this compiler is written against, and the earliest one of that series"
5590        );
5591
5592        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
5593        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
5594
5595        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
5596        // patchlevel and a harness that pastes that back has to be understood.
5597        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
5598        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
5599
5600        assert!(opts.gnuc_given, "a version that was written down is one that was given");
5601        assert!(!compile(&["a.c"]).0.gnuc_given);
5602
5603        let (opts, _) = compile(&["-fms-compatibility-version=19.29.30133", "a.c"]);
5604        assert_eq!(opts.msc.msc_ver(), 1929);
5605        assert_eq!(opts.msc.msc_full_ver(), 192_930_133);
5606
5607        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
5608        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
5609
5610        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
5611        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
5612
5613        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
5614        assert!(e.message.contains("more than three"), "{}", e.message);
5615    }
5616
5617    #[test]
5618    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
5619        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
5620        assert!(opts.pedantic);
5621        assert_eq!(opts.std, Std::C17);
5622
5623        // The `-W` family's name for it, which is what a build that groups its warning flags
5624        // tends to write.
5625        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
5626        assert!(opts.pedantic);
5627
5628        let (opts, _) = compile(&["-std=c17", "a.c"]);
5629        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
5630    }
5631
5632    #[test]
5633    fn dash_p_and_dash_ffreestanding_reach_the_options() {
5634        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
5635        assert!(!opts.line_markers);
5636        assert!(!opts.hosted);
5637        assert_eq!(opts.emit, EmitKind::Preprocessed);
5638    }
5639
5640    /// The two ways a build says it means its own function by a name the C library also has.
5641    ///
5642    /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
5643    /// build writes when it means its own `memcpy` and the library's everything else. The name is
5644    /// kept as it was written and not checked against anything, because a program is allowed to
5645    /// mean something by a name this compiler has never heard of.
5646    #[test]
5647    fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
5648        let (opts, _) = compile(&["-c", "a.c"]);
5649        assert!(opts.builtins, "a library name means the library function by default");
5650        assert!(opts.no_builtin.is_empty());
5651
5652        let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
5653        assert!(!opts.builtins);
5654
5655        let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
5656        assert!(opts.builtins, "the last mention decides");
5657
5658        let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
5659        assert!(opts.builtins, "one name is not the family");
5660        assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
5661    }
5662
5663    /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
5664    /// and which was refused as an unknown option until now.
5665    ///
5666    /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
5667    /// the address across a component boundary, and nothing derives anything from that promise
5668    /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
5669    /// over a distinction this compiler does not make.
5670    #[test]
5671    fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
5672        let (opts, _) = compile(&["-c", "a.c"]);
5673        assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
5674
5675        for (written, wanted) in [
5676            ("default", Visibility::Default),
5677            ("hidden", Visibility::Hidden),
5678            ("internal", Visibility::Hidden),
5679            ("protected", Visibility::Protected),
5680        ] {
5681            let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
5682            assert_eq!(opts.visibility, wanted, "{written}");
5683        }
5684
5685        // The last mention decides, which is what every other flag of this shape does and what a
5686        // build that turns something off for one directory relies on.
5687        let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
5688        assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
5689
5690        // A spelling gcc does not take is refused rather than read as the default, because a
5691        // build that meant hidden and got exported is a library with the wrong interface and
5692        // nothing said about it anywhere.
5693        let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
5694        assert!(failed.to_string().contains("is not a visibility"), "{failed}");
5695    }
5696
5697    /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
5698    /// described, and the values are gcc 16's three.
5699    #[test]
5700    fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
5701        let (opts, _) = compile(&["-c", "a.c"]);
5702        assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
5703
5704        for (written, wanted) in
5705            [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
5706        {
5707            let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
5708            assert_eq!(opts.fp_contract, wanted, "{written}");
5709        }
5710
5711        let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
5712        assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
5713
5714        // Refused rather than read as one of the three, because a build that asked for no fusing
5715        // and was given the default would be one whose numbers change and whose command line says
5716        // they should not. gcc refuses the same spellings and names the same three in its message.
5717        for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
5718            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5719            assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
5720        }
5721
5722        // And the other one that takes a value, which is taken and kept nowhere: every operation
5723        // here is computed in the type it was written in, so `standard` is what happens and the
5724        // other two are permission to do something this does not do.
5725        let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
5726        assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
5727    }
5728
5729    /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
5730    /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
5731    /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
5732    #[test]
5733    fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
5734        let (opts, _) = compile(&["-c", "a.c"]);
5735        assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
5736        assert!(opts.prefix_map.debug.is_empty(), "nor here");
5737        assert!(opts.prefix_map.profile.is_empty(), "nor here");
5738
5739        let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
5740        assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
5741        assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
5742
5743        let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
5744        assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
5745        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5746
5747        let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
5748        assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
5749        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5750
5751        let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
5752        for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
5753            assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
5754        }
5755
5756        // Every mention is kept and the last one that matches wins, unlike the flags above whose
5757        // last mention replaces the earlier ones. A build writes one of these per source root and
5758        // expects all of them to be in force, which is the whole point of a list.
5759        let (opts, _) =
5760            compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
5761        assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
5762        assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
5763
5764        // An argument with no `=` is refused rather than ignored, because a build whose paths were
5765        // meant to be rewritten and were not is one that ships the build directory's name and says
5766        // nothing about it. gcc refuses the same thing.
5767        for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
5768            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5769            assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
5770        }
5771    }
5772
5773    /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
5774    /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
5775    /// one. A kernel and an embedded image are both linked that way.
5776    ///
5777    /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
5778    /// the other is a build that measured something: splitting the code is nearly free at link time
5779    /// and splitting the data can defeat the linker's ordering of what is next to what.
5780    #[test]
5781    fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
5782        let (opts, _) = compile(&["-c", "a.c"]);
5783        assert!(!opts.function_sections, "one text section unless something says otherwise");
5784        assert!(!opts.data_sections);
5785
5786        let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
5787        assert!(opts.function_sections);
5788        assert!(!opts.data_sections, "one flag is not the other");
5789
5790        let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
5791        assert!(opts.data_sections);
5792        assert!(!opts.function_sections);
5793
5794        // Both directions taken, and the off one is what happens anyway rather than a refusal,
5795        // since a build that writes it is asking for the default.
5796        let (opts, _) = compile(&[
5797            "-c",
5798            "-ffunction-sections",
5799            "-fno-function-sections",
5800            "-fdata-sections",
5801            "-fno-data-sections",
5802            "a.c",
5803        ]);
5804        assert!(!opts.function_sections, "the last mention decides");
5805        assert!(!opts.data_sections, "the last mention decides");
5806    }
5807
5808    /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
5809    /// line, since the dialect asks for GNU's reading further in rather than through this.
5810    #[test]
5811    fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
5812        let (opts, _) = compile(&["-c", "a.c"]);
5813        assert!(!opts.gnu89_inline, "C's reading of inline by default");
5814
5815        let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
5816        assert!(opts.gnu89_inline);
5817
5818        let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
5819        assert!(!opts.gnu89_inline, "the last mention decides");
5820
5821        // The C89 dialects are under GNU's reading whether this was written or not, so the flag
5822        // stays off there and the dialect is what the checker and the macro set both ask. That is
5823        // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
5824        // dialect already has. gcc refuses that command line, which is measured in the issue.
5825        let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
5826        assert!(!opts.gnu89_inline);
5827    }
5828
5829    /// Both spellings of both frame flags, since a build that wants one usually writes the
5830    /// other beside it for the one file that has to be compiled the ordinary way.
5831    #[test]
5832    fn the_two_frame_flags_are_read_in_both_directions() {
5833        let (opts, _) = compile(&["-c", "a.c"]);
5834        assert_eq!(opts.frame_pointer, None, "nothing said, so the level decides");
5835        assert!(opts.keeps_frame_pointer(), "and at -O0 gcc keeps one, so this does too");
5836        let (opts, _) = compile(&["-c", "-O1", "a.c"]);
5837        assert!(!opts.keeps_frame_pointer(), "gcc omits it above -O0 and so does this");
5838        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
5839
5840        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
5841        assert_eq!(opts.frame_pointer, Some(true));
5842        assert!(!opts.red_zone);
5843
5844        let (opts, _) = compile(&[
5845            "-c",
5846            "-fno-omit-frame-pointer",
5847            "-fomit-frame-pointer",
5848            "-mno-red-zone",
5849            "-mred-zone",
5850            "a.c",
5851        ]);
5852        assert_eq!(opts.frame_pointer, Some(false), "the last one wins, as it does in gcc");
5853        assert!(!opts.keeps_frame_pointer(), "and it wins over the level too");
5854        assert!(opts.red_zone);
5855    }
5856
5857    /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
5858    /// spelled three ways because a build that turns one off writes whichever it turned on.
5859    #[test]
5860    fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
5861        let (opts, _) = compile(&["-c", "a.c"]);
5862        assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
5863
5864        for (flag, want) in [
5865            ("-fstack-protector", Protector::Buffers),
5866            ("-fstack-protector-strong", Protector::Strong),
5867            ("-fstack-protector-all", Protector::All),
5868        ] {
5869            let (opts, _) = compile(&["-c", flag, "a.c"]);
5870            assert_eq!(opts.protector, want, "{flag}");
5871        }
5872
5873        // What a package build does: the strong one in the global flags and one directory that
5874        // cannot have a protector turning it off on the line after.
5875        for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
5876            let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
5877            assert_eq!(opts.protector, Protector::None, "{off}");
5878        }
5879        let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
5880        assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
5881    }
5882
5883    /// A switch rather than a level, because how a frame is taken is one question and which
5884    /// functions get a canary is another, and gcc spells it that way for the same reason.
5885    #[test]
5886    fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
5887        let (opts, _) = compile(&["-c", "a.c"]);
5888        assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
5889
5890        let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
5891        assert!(opts.stack_clash);
5892
5893        // The same shape a package build uses for the protector: on in the global flags and off
5894        // for the one directory that cannot have it.
5895        let (opts, _) =
5896            compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
5897        assert!(!opts.stack_clash);
5898        let (opts, _) =
5899            compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
5900        assert!(opts.stack_clash, "the last one wins either way round");
5901
5902        // The two are independent, since one is about the frame and the other about the function.
5903        let (opts, _) =
5904            compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
5905        assert!(opts.stack_clash);
5906        assert_eq!(opts.protector, Protector::Strong);
5907    }
5908
5909    /// One flag with an argument rather than a family of spellings, because what it asks about is
5910    /// which of the two edges of a control flow transfer is checked and the two are not separate
5911    /// questions to the hardware.
5912    #[test]
5913    fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
5914        let (opts, _) = compile(&["-c", "a.c"]);
5915        assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
5916
5917        for (arg, want) in [
5918            ("-fcf-protection", Control::Full),
5919            ("-fcf-protection=full", Control::Full),
5920            ("-fcf-protection=branch", Control::Branch),
5921            ("-fcf-protection=return", Control::Return),
5922            ("-fcf-protection=none", Control::None),
5923            ("-fcf-protection=check", Control::Check),
5924        ] {
5925            let (opts, _) = compile(&["-c", arg, "a.c"]);
5926            assert_eq!(opts.control, want, "{arg}");
5927        }
5928
5929        // The shape a package build uses: on in the global flags and off for the one directory
5930        // that cannot have it, whichever of the two spellings of off it reaches for.
5931        let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
5932        assert_eq!(opts.control, Control::None);
5933        let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
5934        assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
5935    }
5936
5937    /// The profiler is asked for by two spellings, and where its hook goes by two more.
5938    ///
5939    /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
5940    /// asks for no call, which is what gcc does with it, and a build system that sets it globally
5941    /// and asks for the profile per directory needs that to be true rather than an error.
5942    ///
5943    /// The link is asserted alongside, because the flag changes it too and a build that compiled
5944    /// with it and linked without it is a program that calls the hook everywhere and never writes a
5945    /// profile.
5946    #[test]
5947    fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
5948        let (opts, _) = compile(&["-c", "a.c"]);
5949        assert!(!opts.profile);
5950        assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
5951
5952        for arg in ["-pg", "-p"] {
5953            let (opts, _) = compile(&["-c", arg, "a.c"]);
5954            assert!(opts.profile, "{arg}");
5955            let (link, _) = linking(&[arg, "a.c"]);
5956            assert!(link.profile, "{arg} changes the link as well");
5957        }
5958
5959        for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
5960            let (opts, _) = compile(&["-c", arg, "a.c"]);
5961            assert_eq!(opts.hook, want, "{arg}");
5962            assert!(!opts.profile, "{arg} asks for no call of its own");
5963        }
5964
5965        let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
5966        assert_eq!(opts.hook, Hook::Late, "the last one wins");
5967        assert!(opts.profile);
5968    }
5969
5970    /// How much room a patcher is promised, which is one number or two.
5971    ///
5972    /// A command line that did not ask is asserted alongside, because the flag has to be written to
5973    /// mean anything and a build that reserved room nobody asked for would grow every function in
5974    /// it for nothing.
5975    #[test]
5976    fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
5977        let (opts, _) = compile(&["-c", "a.c"]);
5978        assert_eq!(opts.patchable, Patchable::default());
5979        assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
5980
5981        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
5982        assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
5983
5984        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
5985        assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
5986        assert_eq!(opts.patchable.after(), 2);
5987
5988        // The last one wins, which is what every other flag of this shape does and what a build
5989        // that adds one to a command line it did not write is relying on.
5990        let (opts, _) = compile(&[
5991            "-c",
5992            "-fpatchable-function-entry=5,3",
5993            "-fpatchable-function-entry=2",
5994            "a.c",
5995        ]);
5996        assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
5997    }
5998
5999    /// And a request nothing could satisfy is refused rather than rounded into one that can be.
6000    #[test]
6001    fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
6002        for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
6003            let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
6004            assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
6005        }
6006    }
6007
6008    /// What wraps rather than being undefined, which is two questions and three flags.
6009    ///
6010    /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
6011    /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
6012    /// only what it asked for.
6013    #[test]
6014    fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
6015        let (opts, _) = compile(&["-c", "a.c"]);
6016        assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
6017
6018        let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
6019        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
6020
6021        let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
6022        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
6023
6024        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
6025        assert_eq!(opts.wrapping, Wrapping::ALL);
6026
6027        // And the last one wins, in both directions. A build that turns one of these on globally
6028        // and off for one directory is relying on that, and so is one that writes the pair and
6029        // then takes half of it back.
6030        let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
6031        assert_eq!(opts.wrapping, Wrapping::NONE);
6032
6033        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
6034        assert_eq!(opts.wrapping, Wrapping::NONE);
6035
6036        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
6037        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
6038    }
6039
6040    /// And the other answer to the signed question cannot be held at the same time as the first.
6041    ///
6042    /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
6043    /// resolves it by letting the last one win rather than by reporting anything. That was measured
6044    /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
6045    /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
6046    #[test]
6047    fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
6048        let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
6049        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
6050
6051        let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
6052        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
6053
6054        let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
6055        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
6056
6057        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
6058        assert_eq!(opts.wrapping, Wrapping::ALL);
6059
6060        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
6061        assert_eq!(opts.wrapping, Wrapping::NONE);
6062
6063        // And the flag that says what may be assumed says nothing about what happens, so it leaves
6064        // this alone where it takes the wrapping away. gcc does the same.
6065        let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
6066        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
6067    }
6068
6069    /// What a plain `char` is, which is four spellings of two answers and nothing by default.
6070    ///
6071    /// Nothing is the target's own answer and has to stay distinct from both of the others, since
6072    /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
6073    /// The negative spellings are the other flag rather than a way of asking for the default, which
6074    /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
6075    /// `-fno-unsigned-char` does not.
6076    #[test]
6077    fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
6078        let (opts, _) = compile(&["-c", "a.c"]);
6079        assert_eq!(opts.char_signed, None);
6080
6081        for flag in ["-fsigned-char", "-fno-unsigned-char"] {
6082            let (opts, _) = compile(&["-c", flag, "a.c"]);
6083            assert_eq!(opts.char_signed, Some(true), "{flag}");
6084        }
6085
6086        for flag in ["-funsigned-char", "-fno-signed-char"] {
6087            let (opts, _) = compile(&["-c", flag, "a.c"]);
6088            assert_eq!(opts.char_signed, Some(false), "{flag}");
6089        }
6090
6091        // And the last one wins, which is what a build that sets one globally and the other for a
6092        // directory relies on.
6093        let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
6094        assert_eq!(opts.char_signed, Some(true));
6095
6096        // And what is asked for reaches the target, because that is what every other part of the
6097        // compiler asks. The triple is one whose own answer is the opposite, so a session that
6098        // ignored the flag would still read as signed here.
6099        let (opts, _) =
6100            compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
6101        assert!(Session::new(*opts).target.char_is_signed);
6102        let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
6103        assert!(!Session::new(*opts).target.char_is_signed);
6104    }
6105
6106    /// And the size of an enumeration, which is one question with two spellings.
6107    #[test]
6108    fn the_smallest_enumeration_is_asked_for_and_taken_back() {
6109        let (opts, _) = compile(&["-c", "a.c"]);
6110        assert!(!opts.short_enums);
6111
6112        let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
6113        assert!(opts.short_enums);
6114
6115        let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
6116        assert!(!opts.short_enums);
6117
6118        let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
6119        assert!(opts.short_enums);
6120    }
6121
6122    /// And Microsoft's reading of an anonymous member, which the target answers where the command
6123    /// line said nothing. gcc's mingw build has it on and its Linux build has it off, so a header
6124    /// that closes a nameless union with a macro that expands to nothing is read the way the
6125    /// compiler that platform ships would read it.
6126    #[test]
6127    fn the_microsoft_reading_of_a_member_follows_the_target_until_it_is_asked_for() {
6128        // Named rather than left to the host, since the answer this asks for is the one a target
6129        // that is not Windows gives and on a Windows machine the host is not one of those.
6130        let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
6131        assert!(!Session::new(*opts).ms_extensions());
6132
6133        let (opts, _) = compile(&["-c", "--target=x86_64-pc-windows-gnu", "a.c"]);
6134        assert!(Session::new(*opts).ms_extensions());
6135
6136        let (opts, _) = compile(&["-c", "-fms-extensions", "a.c"]);
6137        assert!(Session::new(*opts).ms_extensions());
6138
6139        let (opts, _) =
6140            compile(&["-c", "--target=x86_64-pc-windows-gnu", "-fno-ms-extensions", "a.c"]);
6141        assert!(!Session::new(*opts).ms_extensions());
6142    }
6143
6144    /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
6145    ///
6146    /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
6147    /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
6148    /// family would report it as an unknown pass. Neither is the news the build wants.
6149    #[test]
6150    fn a_control_flow_protection_nothing_means_is_refused() {
6151        let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
6152        assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
6153        assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
6154    }
6155
6156    #[test]
6157    fn mingw_subsystem_and_unicode_flags_are_taken_last_one_winning() {
6158        let (link, _) = linking(&["-mwindows", "-municode", "-mthreads", "-static-libgcc", "a.c"]);
6159        assert!(link.gui && link.unicode);
6160        let (link, _) = linking(&["-mwindows", "-mconsole", "a.c"]);
6161        assert!(!link.gui);
6162        let (opts, _) = compile(&["-municode", "-c", "a.c"]);
6163        assert!(opts.defines.iter().any(|define| define == "UNICODE"), "{:?}", opts.defines);
6164    }
6165
6166    #[test]
6167    fn the_link_flags_are_collected_apart_from_the_compilation() {
6168        let (link, _) = linking(&[
6169            "-static",
6170            "-nostartfiles",
6171            "-rdynamic",
6172            "-s",
6173            "-fuse-ld=mold",
6174            "-L/opt/lib",
6175            "-B",
6176            "/opt/tools",
6177            "a.c",
6178        ]);
6179        assert!(link.is_static);
6180        assert!(link.no_startfiles);
6181        assert!(link.export_dynamic);
6182        assert!(link.strip);
6183        assert_eq!(link.use_ld.as_deref(), Some("mold"));
6184        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
6185        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
6186    }
6187
6188    #[test]
6189    fn a_mingw_link_names_its_output_the_way_mingw_gcc_does() {
6190        // gcc puts `.exe` on a DLL's name as well when it has no extension, so `-shared` is not an
6191        // exception, and `-c` links nothing and is. tamnd/rucc#2152.
6192        let mingw = "--target=x86_64-windows-gnu";
6193        let (_, plan) = linking(&[mingw, "a.c", "-o", "foo"]);
6194        assert_eq!(plan.link.expect("expected a link step").output, "foo.exe");
6195        let (_, plan) = linking(&[mingw, "-shared", "a.c", "-o", "x"]);
6196        assert_eq!(plan.link.expect("expected a link step").output, "x.exe");
6197        let (_, plan) = linking(&[mingw, "-shared", "a.c", "-o", "x.dll"]);
6198        assert_eq!(plan.link.expect("expected a link step").output, "x.dll");
6199        let (_, plan) = compile(&[mingw, "-c", "a.c", "-o", "x"]);
6200        assert!(plan.link.is_none());
6201        assert_eq!(plan.jobs[0].output, Output::File("x".into()));
6202        let (_, plan) = linking(&[LINUX, "a.c", "-o", "foo"]);
6203        assert_eq!(plan.link.expect("expected a link step").output, "foo");
6204    }
6205
6206    #[test]
6207    fn a_comma_in_dash_wl_separates_two_arguments() {
6208        // The target is written down because the name of the object is derived from it, and `a.o`
6209        // on a Linux host is `a.obj` on a Windows one. What is under test is the splitting of the
6210        // argument, which has nothing to do with either.
6211        let (_, plan) = linking(&[LINUX, "-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
6212        let link = plan.link.expect("expected a link step");
6213        assert_eq!(
6214            link.inputs,
6215            vec![
6216                link::Item::Linker("-rpath".into()),
6217                link::Item::Linker("/opt/lib".into()),
6218                link::Item::Linker("--as-needed".into()),
6219                link::Item::File("a.o".into()),
6220            ]
6221        );
6222    }
6223
6224    #[test]
6225    fn a_word_for_the_linker_keeps_its_place_among_the_files_too() {
6226        // What libtool writes around a set of convenience archives, and what #1279 was. Both words
6227        // are about the files between them, so the pair collected out of the line and appended to
6228        // the end is two options that bracket nothing and an archive that went in empty.
6229        let (_, plan) = linking(&[
6230            "--target=x86_64-unknown-linux-gnu",
6231            "a.c",
6232            "-Wl,--whole-archive",
6233            "libaesni.a",
6234            "-Wl,--no-whole-archive",
6235            "-lm",
6236        ]);
6237        let link = plan.link.expect("expected a link step");
6238        assert_eq!(
6239            link.inputs,
6240            vec![
6241                link::Item::File("a.o".into()),
6242                link::Item::Linker("--whole-archive".into()),
6243                link::Item::File("libaesni.a".into()),
6244                link::Item::Linker("--no-whole-archive".into()),
6245                link::Item::Library("m".into()),
6246            ]
6247        );
6248        // And it is not a job, because there is nothing to compile in a word for the linker.
6249        assert_eq!(plan.jobs.len(), 2);
6250    }
6251
6252    #[test]
6253    fn a_word_for_the_linker_on_a_dash_c_line_is_dropped_without_a_word() {
6254        // GCC says nothing about one either. `-Wl,` on a compile line is what a build system
6255        // writes when one variable holds the flags for both, and a note here would be a note on
6256        // every compile of every autotools project.
6257        let (_, plan) = linking(&["-c", "-Wl,--as-needed", "a.c"]);
6258        assert!(plan.link.is_none());
6259        assert!(plan.notes.is_empty(), "{:?}", plan.notes);
6260        assert_eq!(plan.jobs.len(), 1);
6261    }
6262
6263    #[test]
6264    fn a_library_keeps_its_place_between_the_objects() {
6265        // Link order is semantic: `-lm` written between two files resolves for the one before
6266        // it and not for the one after, so a library cannot be collected into a list of its own.
6267        // The target is named because the suffix of an object is the target's and this asserts
6268        // on the names: the same command line on a Windows host plans two `.obj` files.
6269        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
6270        let link = plan.link.expect("expected a link step");
6271        assert_eq!(
6272            link.inputs,
6273            vec![
6274                link::Item::File("a.o".into()),
6275                link::Item::Library("m".into()),
6276                link::Item::File("b.o".into()),
6277            ]
6278        );
6279        // And it is not a job, because there is nothing to compile in a library.
6280        assert_eq!(plan.jobs.len(), 2);
6281    }
6282
6283    #[test]
6284    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
6285        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
6286        assert!(plan.link.is_none());
6287        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
6288    }
6289
6290    #[test]
6291    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
6292        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
6293        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
6294    }
6295
6296    fn printed(s: &[&str]) -> String {
6297        match parse_args(&args(s)).expect("expected an answer") {
6298            Action::Print(line) => line,
6299            other => panic!("expected an answer, got {other:?}"),
6300        }
6301    }
6302
6303    fn refused(s: &[&str]) -> String {
6304        parse_args(&args(s)).expect_err("expected a refusal").message
6305    }
6306
6307    #[test]
6308    fn a_warning_flag_gcc_knows_is_taken_even_though_nothing_reads_it() {
6309        // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
6310        // out whether a warning flag exists by passing it and looking at the exit status, so a
6311        // compiler that refuses one gcc knows fails a script written for gcc.
6312        let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
6313        assert!(!opts.warnings_are_errors);
6314        assert!(opts.warnings);
6315        // The two spellings that do mean something are still read.
6316        let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
6317        assert!(opts.warnings_are_errors);
6318        let (opts, _) = compile(&["-w", "-c", "a.c"]);
6319        assert!(!opts.warnings);
6320        // Off without being asked, the way gcc has it off, and both spellings are read.
6321        let (opts, _) = compile(&["-c", "a.c"]);
6322        assert!(!opts.system_header_warnings);
6323        let (opts, _) = compile(&["-Wsystem-headers", "-c", "a.c"]);
6324        assert!(opts.system_header_warnings);
6325        let (opts, _) = compile(&["-Wsystem-headers", "-Wno-system-headers", "-c", "a.c"]);
6326        assert!(!opts.system_header_warnings);
6327        let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
6328        assert!(opts.pedantic && opts.warnings_are_errors);
6329    }
6330
6331    #[test]
6332    fn a_warning_flag_gcc_refuses_is_refused_here_too() {
6333        // Postgres's meson build probes these, and with rucc taking them it ended up passing four
6334        // clang warnings that the gcc build had dropped.
6335        for flag in ["-Wcast-function-type-strict", "-Wunused-command-line-argument"] {
6336            assert_eq!(refused(&[flag, "-c", "a.c"]), format!("unknown option `{flag}`"));
6337        }
6338        assert_eq!(
6339            refused(&["-Werror=unguarded-availability-new", "-c", "a.c"]),
6340            "`-Werror=unguarded-availability-new`: no option `-Wunguarded-availability-new`"
6341        );
6342        assert!(refused(&["-Wno-error=nonsense", "-c", "a.c"]).contains("no option `-Wnonsense`"));
6343        // gcc takes `-Wno-` of a name it does not know, and says nothing unless something else
6344        // is said, and it takes C++ and Fortran names on a C compile.
6345        for flag in
6346            ["-Wno-cast-function-type-strict", "-Werror=format", "-Wformat=2", "-Wabi-tag", "-W"]
6347        {
6348            compile(&[flag, "-c", "a.c"]);
6349        }
6350    }
6351
6352    #[test]
6353    fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
6354        // Every one of these says something about the output, so the wrong answer is silence.
6355        assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
6356        assert!(refused(&["-Wp,-C", "-c", "a.c"]).contains("separate assembler"));
6357        assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
6358        assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
6359        assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
6360        // The word size the target does not have, which is a target this compiler was not asked
6361        // for rather than a flag it does not know.
6362        let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
6363        assert!(no32.contains("32 bit target"), "{no32}");
6364    }
6365
6366    /// `-gz` and the two spellings of the split, which are the two questions about the shape of
6367    /// the debug output rather than about how much of it there is.
6368    ///
6369    /// Both answers here are about what happens when there is debug information to shape, and
6370    /// there is none yet, so what is being asserted is that the flags are read and remembered
6371    /// rather than that anything changed in the output. That is the whole of what taking them
6372    /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
6373    /// it comes to find out what the command line said.
6374    #[test]
6375    fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
6376        let (opts, _) = compile(&["-c", "a.c"]);
6377        assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
6378
6379        // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
6380        // which describes the flag without ever saying which algorithm it picks.
6381        assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
6382        for (spelling, want) in [
6383            ("none", Compress::None),
6384            ("zlib", Compress::Zlib),
6385            ("zlib-gnu", Compress::ZlibGnu),
6386            ("zstd", Compress::Zstd),
6387        ] {
6388            let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
6389            assert_eq!(opts.compress, want, "{spelling}");
6390        }
6391
6392        // A value nothing here has heard of is refused rather than rounded to the nearest one,
6393        // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
6394        // reader may not understand and would have no way of finding out.
6395        for bad in ["-gz=gzip", "-gz="] {
6396            let failed = refused(&[bad, "-c", "a.c"]);
6397            assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
6398        }
6399
6400        // The split is refused in the direction that would have written a file and taken in the
6401        // direction that describes what happens. A build system that names the `.dwo` as an
6402        // output has to hear about it now rather than at the point the file is missing.
6403        let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
6404        assert!(opts.debug_info, "the negative spelling says nothing about how much");
6405        let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
6406        assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
6407    }
6408
6409    /// The `-flto` family, which is the whole of an optimization this compiler does not do.
6410    ///
6411    /// Taken rather than refused because ignoring it gives a correct program that is slower than
6412    /// it could have been, which is section 4.1's hint about speed. The values are still held to
6413    /// gcc's, so a command line written for clang is told rather than quietly taken.
6414    #[test]
6415    fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
6416        let (opts, _) = compile(&["-c", "a.c"]);
6417        assert!(!opts.lto.requested, "nothing asks unless the command line does");
6418
6419        let (opts, _) = compile(&["-flto", "-c", "a.c"]);
6420        assert!(opts.lto.requested);
6421        assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
6422
6423        // The last of the two directions wins, the same as every other pair of `-f` spellings.
6424        assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
6425        assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
6426
6427        // A count is a count, and asking for one implies asking for the optimization.
6428        for (spelling, want) in [
6429            ("auto", LtoJobs::Auto),
6430            ("jobserver", LtoJobs::Jobserver),
6431            ("1", LtoJobs::One),
6432            ("8", LtoJobs::Count(8)),
6433        ] {
6434            let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
6435            assert_eq!(opts.lto.jobs, want, "{spelling}");
6436            assert!(opts.lto.requested, "{spelling} asks for it too");
6437        }
6438
6439        // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
6440        // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
6441        // different compiler and gets told so here rather than getting a serial link.
6442        for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
6443            let failed = refused(&[bad, "-c", "a.c"]);
6444            assert!(failed.contains("link time jobs"), "{bad}: {failed}");
6445        }
6446
6447        // How the program is cut up before the work is spread over it.
6448        assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
6449        for (spelling, want) in [
6450            ("balanced", Partition::Balanced),
6451            ("1to1", Partition::OneToOne),
6452            ("one", Partition::One),
6453            ("max", Partition::Max),
6454            ("none", Partition::None),
6455        ] {
6456            let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
6457            assert_eq!(opts.lto.partition, want, "{spelling}");
6458        }
6459        assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
6460
6461        // And how hard the bytecode is compressed on its way into the object, which is zstd's
6462        // range of levels and is the range gcc checks an argument against.
6463        assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
6464        assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
6465        let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
6466        assert_eq!(opts.lto.compression, Some(19));
6467        for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
6468            let failed = refused(&[bad, "-c", "a.c"]);
6469            assert!(failed.contains("compression level"), "{bad}: {failed}");
6470        }
6471
6472        // The two pairs that describe an arrangement rather than ask for one. Every object here
6473        // holds its machine code, so the fat spelling is what already happens and the other is a
6474        // smaller file rather than a different program, and the plugin pair is about a tool the
6475        // design in `spec/09-optimizer.md` never loads.
6476        for taken in [
6477            "-ffat-lto-objects",
6478            "-fno-fat-lto-objects",
6479            "-fuse-linker-plugin",
6480            "-fno-use-linker-plugin",
6481        ] {
6482            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6483            assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
6484        }
6485    }
6486
6487    /// The profile family, which is the only one here that splits down the middle.
6488    ///
6489    /// Reading a profile is taken and writing one is refused, and the line between them is the one
6490    /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
6491    /// slower than it could have been, and ignoring a request to write them means a file the build
6492    /// declared as an output never appears.
6493    #[test]
6494    fn reading_a_profile_is_taken_and_writing_one_is_refused() {
6495        let (opts, _) = compile(&["-c", "a.c"]);
6496        assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
6497        assert_eq!(opts.profile_data.path, None);
6498
6499        let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
6500        assert!(opts.profile_data.requested);
6501        assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
6502
6503        let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
6504        assert!(opts.profile_data.requested, "naming a path asks for it too");
6505        assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
6506
6507        // The last of the two directions wins, the same as every other pair of `-f` spellings.
6508        assert!(
6509            !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
6510        );
6511        assert!(
6512            compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
6513        );
6514
6515        // The rest of the reading half, which is where the files are and three answers about what
6516        // to make of what is in them.
6517        let (opts, _) = compile(&[
6518            "-fprofile-dir=/build/profiles",
6519            "-fprofile-abs-path",
6520            "-fprofile-correction",
6521            "-fprofile-partial-training",
6522            "-c",
6523            "a.c",
6524        ]);
6525        assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
6526        assert!(opts.profile_data.absolute);
6527        assert!(opts.profile_data.correction);
6528        assert!(opts.profile_data.partial_training);
6529
6530        // Writing one, which is refused by name. The first four instrument the program and the
6531        // last writes a file beside the object, and a build that got neither and no message would
6532        // go on to optimize against counts that were never gathered.
6533        for writing in [
6534            "-fprofile-generate",
6535            "-fprofile-generate=/build/profiles",
6536            "-fprofile-arcs",
6537            "--coverage",
6538            "-fcondition-coverage",
6539            "-fpath-coverage",
6540        ] {
6541            let failed = refused(&[writing, "-c", "a.c"]);
6542            assert!(failed.contains("instrument"), "{writing}: {failed}");
6543        }
6544        assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
6545
6546        // The negative spellings of the refused half are what already happens, so they are taken.
6547        for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
6548            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6549            assert!(!opts.profile_data.requested, "{taken} asks for nothing");
6550        }
6551
6552        // And the flags that describe the instrumentation that is refused above, which are checked
6553        // and dropped. Checked because a typo is worth finding here rather than on the day the
6554        // instrumentation lands.
6555        for taken in [
6556            "-fprofile-update=single",
6557            "-fprofile-update=atomic",
6558            "-fprofile-update=prefer-atomic",
6559            "-fprofile-reproducible=serial",
6560            "-fprofile-reproducible=parallel-runs",
6561            "-fprofile-reproducible=multithreaded",
6562            "-fprofile-values",
6563            "-fno-profile-values",
6564            "-fprofile-info-section",
6565            "-fprofile-filter-files=a.c",
6566            "-fprofile-exclude-files=b.c",
6567            "-fprofile-note=a.gcno",
6568        ] {
6569            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6570            assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
6571        }
6572        assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
6573        assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
6574    }
6575
6576    /// The sanitizers, which are refused by name and are the one family refused for a reason that
6577    /// is not about the bytes.
6578    ///
6579    /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
6580    /// for one and was quietly given a program with no checks in it gets a test suite that passes
6581    /// for the wrong reason rather than a slower program.
6582    #[test]
6583    fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
6584        for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
6585            let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
6586            assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
6587            assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
6588        }
6589
6590        // A list is every name in it, and the first one still standing is the one named.
6591        let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
6592        assert!(failed.contains("address"), "{failed}");
6593
6594        // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
6595        // with a typo in it has a different problem from somebody who wrote a real one.
6596        for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
6597            let failed = refused(&[bad, "-c", "a.c"]);
6598            assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
6599        }
6600
6601        // gcc takes `all` only in the negative, and so does this.
6602        assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
6603
6604        // Asking and then taking it back is asking for nothing, which is why the answer waits for
6605        // the end of the line. A build whose shared flags turn a check on and whose rule for one
6606        // file turns it off again compiles that file here.
6607        for pair in [
6608            ["-fsanitize=address", "-fno-sanitize=address"],
6609            ["-fsanitize=address,undefined", "-fno-sanitize=all"],
6610            ["-fsanitize=undefined", "-fno-sanitize=undefined"],
6611        ] {
6612            let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
6613            assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
6614        }
6615        // And the other order still asks, because the last word is the one that counts.
6616        assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
6617
6618        // What a check does when it fires is an answer about checks that are refused, so there is
6619        // nothing left for it to change and it is taken.
6620        for taken in [
6621            "-fsanitize-recover=undefined",
6622            "-fno-sanitize-recover=all",
6623            "-fsanitize-trap=undefined",
6624            "-fno-sanitize-trap=all",
6625            "-fsanitize-undefined-trap-on-error",
6626            "-fsanitize-address-use-after-scope",
6627            "-fno-sanitize-address-use-after-scope",
6628            "-fsanitize-sections=.data",
6629        ] {
6630            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6631            assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
6632        }
6633        assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
6634
6635        // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
6636        // feedback runs blind and never says so.
6637        let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
6638        assert!(failed.contains("feedback"), "{failed}");
6639        let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
6640        assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
6641    }
6642
6643    #[test]
6644    fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
6645        assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6646        assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6647        assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
6648    }
6649
6650    #[test]
6651    fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
6652        let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
6653        let (opts, _) =
6654            compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
6655        assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
6656        let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
6657        assert!(wrong.contains("sysv convention"), "{wrong}");
6658    }
6659
6660    /// Whether a unit built with that command line has the extension called `name`.
6661    fn has(line: &[&str], name: &str) -> bool {
6662        let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6663        let (opts, _) = compile(&[&x86[..], line].concat());
6664        opts.isa.has(rucc_target::Feature::named(name).expect("a feature"))
6665    }
6666
6667    #[test]
6668    fn the_sse_flags_and_the_processor_levels_name_extensions() {
6669        // tamnd/rucc#2003. Every one of these was an unknown option before, and Postgres's
6670        // configure probe for the CRC-32C intrinsics is compiled with the first.
6671        assert!(has(&["-msse4.2"], "sse4.2") && has(&["-msse4.2"], "crc32"));
6672        assert!(has(&["-msse4.2"], "ssse3") && has(&["-msse4.2"], "popcnt"));
6673        assert!(!has(&[], "sse3") && !has(&[], "popcnt"));
6674        assert!(has(&["-mssse3"], "sse3") && !has(&["-mssse3"], "sse4.1"));
6675        assert!(has(&["-msse4"], "sse4.2") && !has(&["-msse4", "-mno-sse4"], "sse4.1"));
6676        assert!(has(&["-mpopcnt"], "popcnt") && !has(&["-mpopcnt"], "sse3"));
6677        assert!(has(&["-mcrc32"], "crc32"));
6678        assert!(has(&["-mxsave"], "xsave") && !has(&["-mxsave", "-mno-xsave"], "xsave"));
6679        assert!(!has(&["-msse4.2", "-mno-popcnt"], "popcnt"));
6680        // A processor supplies what no flag spoke for, whichever order they came in.
6681        assert!(has(&["-march=x86-64-v2"], "sse4.2"));
6682        assert!(!has(&["-march=x86-64-v2", "-mno-sse4.2"], "sse4.2"));
6683        assert!(!has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.2"));
6684        assert!(has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.1"));
6685        assert!(!has(&["-march=x86-64-v2", "-march=x86-64"], "sse3"));
6686        // One it has no list for is the baseline, as it was when all of them were.
6687        assert!(!has(&["-march=pentium-m"], "sse3"));
6688        assert!(has(&["-march=x86-64-v3"], "avx2"));
6689        // Turning off what is never on is nothing, and the flag is still gcc's.
6690        assert!(!has(&["-mno-avx512f"], "avx512f"));
6691    }
6692
6693    #[test]
6694    fn an_extension_this_compiler_cannot_provide_for_a_whole_unit_is_refused() {
6695        let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6696        let said = refused(&[&x86[..], &["-mavx2"]].concat());
6697        assert!(said.contains("no intrinsics for avx2"), "{said}");
6698        let said = refused(&[&x86[..], &["-mno-sse2"]].concat());
6699        assert!(said.contains("baseline"), "{said}");
6700        assert!(refused(&[&x86[..], &["-msse5"]].concat()).contains("unknown option"));
6701        // No other target has these, whichever side of the target the flag was written on.
6702        let said = refused(&["-msse4.2", "--target=aarch64-linux-gnu", "-c", "a.c"]);
6703        assert!(said.contains("unknown option `-msse4.2`"), "{said}");
6704        let (opts, _) = compile(&["--target=riscv64-linux-gnu", "-march=rv64gc", "-c", "a.c"]);
6705        assert_eq!(opts.isa, rucc_target::Isa::NONE);
6706    }
6707
6708    /// tamnd/rucc#2006. `-march=` on AArch64 decides the CRC32 extension, which is what
6709    /// `__ARM_FEATURE_CRC32` and the intrinsics in `<arm_acle.h>` follow. PostgreSQL's configure
6710    /// tries `-march=armv8-a+crc+simd` and then `-march=armv8-a+crc`, and gcc gives plain Armv8-A
6711    /// none of it.
6712    #[test]
6713    fn the_aarch64_march_decides_the_crc_extension() {
6714        let crc = |line: &[&str]| {
6715            let args = [&["--target=aarch64-linux-gnu", "-c", "a.c"][..], line].concat();
6716            let (opts, _) = compile(&args);
6717            opts.isa.has(rucc_target::Feature::aarch64("crc").expect("a feature"))
6718        };
6719        assert!(crc(&["-march=armv8-a+crc"]));
6720        assert!(crc(&["-march=armv8-a+crc+simd"]));
6721        assert!(crc(&["-march=armv8.1-a"]));
6722        assert!(crc(&["-march=armv9-a"]));
6723        assert!(!crc(&[]));
6724        assert!(!crc(&["-march=armv8-a"]));
6725        assert!(!crc(&["-march=armv8-a+simd"]));
6726        assert!(!crc(&["-march=armv8.2-a+nocrc"]));
6727        // The last one written is the one that counts, as it is for gcc.
6728        assert!(!crc(&["-march=armv8-a+crc", "-march=armv8-a"]));
6729        assert!(crc(&["-march=armv8-a", "-march=armv8-a+crc"]));
6730        // And `-march=` written before the target is still read for it.
6731        let (opts, _) = compile(&["-march=armv8-a+crc", "--target=aarch64-linux-gnu", "-c", "a.c"]);
6732        assert!(opts.isa.has(rucc_target::Feature::aarch64("crc").expect("a feature")));
6733    }
6734
6735    #[test]
6736    fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
6737        let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
6738        assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
6739        // After the input, because a static link takes what it needs from a library when it
6740        // reaches it and not afterwards.
6741        let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
6742        assert_eq!(names, vec!["a.c"]);
6743    }
6744
6745    #[test]
6746    fn the_version_banner_keeps_our_first_line_and_takes_meson_down_the_gnu_path() {
6747        let text = banner();
6748        let mut lines = text.lines();
6749        // Every harness we have reads the first line and nothing else.
6750        assert_eq!(lines.next(), Some(format!("rucc {VERSION}").as_str()));
6751        // The words meson looks for, in `mesonbuild/compilers/detect.py`.
6752        assert!(text.contains("Free Software Foundation"), "{text}");
6753        // GCC's own banner has three lines and so does this one, and the claim is the dialect.
6754        assert!(lines.next().is_some_and(|l| l.contains("GCC 16")), "{text}");
6755        assert!(lines.next().is_some() && lines.next().is_none(), "{text}");
6756    }
6757
6758    #[test]
6759    fn the_questions_a_build_system_asks_before_it_compiles_anything() {
6760        let target = "--target=x86_64-unknown-linux-gnu";
6761        assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
6762        assert_eq!(printed(&[target, "-dumpversion"]), "16");
6763        assert_eq!(printed(&[target, "-dumpfullversion"]), "16.0.0");
6764        // They follow the release claimed, since that is the one `__GNUC__` says.
6765        assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpversion"]), "15");
6766        assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpfullversion"]), "15.2.0");
6767        assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
6768        // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
6769        // answer safe to paste into a link line whether or not the file is there.
6770        assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
6771        assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
6772        let dirs = printed(&[target, "-print-search-dirs"]);
6773        assert!(dirs.starts_with("install: "), "{dirs}");
6774        assert!(dirs.contains("\nlibraries: ="), "{dirs}");
6775    }
6776
6777    #[test]
6778    fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
6779        // A tree the user named is the answer whatever the target is, because it is the answer to
6780        // every other question too.
6781        assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
6782
6783        // A target that is no machine this suite runs on is read under the cache, and the answer is
6784        // the root rather than one of the directories under it, since what asks is looking for a
6785        // file of its own.
6786        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
6787        assert_eq!(
6788            printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
6789            root.display().to_string()
6790        );
6791
6792        // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
6793        // was configured without one rather than a `/` that would be a claim about the filesystem.
6794        // Except on Windows, which has no C library of its own and reads the fetched tree for its
6795        // own target as it would for any other.
6796        let host = Triple::host().expect("a host this compiler knows");
6797        let own = printed(&[&format!("--target={host}"), "-print-sysroot"]);
6798        if host.os == rucc_target::Os::Windows {
6799            let root = cache::dir().join("sysroots").join(host.tuple().to_string());
6800            assert_eq!(own, root.display().to_string());
6801        } else {
6802            assert_eq!(own, "");
6803        }
6804    }
6805
6806    #[test]
6807    fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
6808        // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
6809        // is the record that already has them, so the flag prints that rather than a second format.
6810        let manifest = "rucc sysroot manifest 3\n\
6811                        target\tx86_64-linux-musl\n\
6812                        kernel\t6.12\n\
6813                        include/generic/stdio.h\tmusl-1.2.5\t\
6814                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6815                        0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
6816                        bundled\n\
6817                        lib/libc.so\tmusl-1.2.5\t\
6818                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6819                        1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
6820                        generated\n";
6821        let tree = TempTree::new("provenance", &[("manifest", manifest)]);
6822        let sysroot = format!("--sysroot={}", tree.0.display());
6823        // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
6824        // the flag parses the record and renders it again rather than picking fields out of it. That
6825        // is the reason it prints a manifest and not a format of its own.
6826        //
6827        // The answer is the file without its last newline, because whatever prints it adds one. The
6828        // file is what somebody diffs the output against, so the two have to be the same bytes.
6829        assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
6830
6831        // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
6832        // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
6833        // tell it from a manifest with no inputs because that one still has its two header lines.
6834        let bare = TempTree::new("provenance-bare", &[]);
6835        assert_eq!(
6836            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
6837            ""
6838        );
6839
6840        // And a compile for this machine has no sysroot at all, which is the same empty answer
6841        // `-print-sysroot` gives for it.
6842        let host = Triple::host().expect("a host this compiler knows");
6843        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
6844
6845        // And the other spelling, which section 13.5 is the document that writes.
6846        assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
6847
6848        // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
6849        // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
6850        // the bytes it is over are the bytes of the file. The number here is that hash of the
6851        // fixture above, computed by `sha256sum` rather than by this compiler.
6852        assert_eq!(
6853            printed(&[&sysroot, "-print-sysroot-digest"]),
6854            "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
6855        );
6856        assert_eq!(
6857            printed(&[&sysroot, "--print-sysroot-digest"]),
6858            printed(&[&sysroot, "-print-sysroot-digest"])
6859        );
6860
6861        // And the two empty answers are empty here too, because a digest of nothing would read as a
6862        // claim about a sysroot rather than as the absence of one.
6863        assert_eq!(
6864            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
6865            ""
6866        );
6867        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
6868    }
6869
6870    #[test]
6871    fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
6872        // Passing a file we could not parse to whoever asked would make their parser the one that
6873        // finds the problem, and the three uses section 13.5 gives for this are all somebody else
6874        // parsing it.
6875        let tree = TempTree::new(
6876            "provenance-bad",
6877            &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
6878        );
6879        let message =
6880            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
6881        assert!(message.contains("manifest"), "{message}");
6882        assert!(message.contains("1 fields where an input has six"), "{message}");
6883
6884        // The digest is refused for the same file and for a stronger reason: a hash of bytes this
6885        // build cannot read would be a number that names a record nobody can act on.
6886        let digest =
6887            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
6888        assert_eq!(digest, message);
6889    }
6890
6891    #[test]
6892    fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
6893        let (opts, _) = compile(&["-M", "a.c"]);
6894        assert!(opts.deps.emit && opts.deps.instead_of_compiling);
6895        assert!(opts.deps.system_headers, "plain -M lists them");
6896        assert_eq!(opts.emit, EmitKind::Preprocessed);
6897
6898        // Even where a later flag asked for something else, because the family is a mode and
6899        // the mode is what the run is for.
6900        let (opts, _) = compile(&["-M", "-c", "a.c"]);
6901        assert_eq!(opts.emit, EmitKind::Preprocessed);
6902
6903        let (opts, _) = compile(&["-MM", "a.c"]);
6904        assert!(!opts.deps.system_headers);
6905    }
6906
6907    #[test]
6908    fn the_two_that_end_in_d_leave_the_compilation_alone() {
6909        let (opts, _) = compile(&["-MD", "-c", "a.c"]);
6910        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6911        assert!(opts.deps.system_headers);
6912        assert_eq!(opts.emit, EmitKind::Object);
6913
6914        let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
6915        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6916        assert!(!opts.deps.system_headers);
6917    }
6918
6919    #[test]
6920    fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
6921        // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
6922        // the answer, because the other one never asked the question.
6923        let (opts, _) = compile(&["-MM", "-M", "a.c"]);
6924        assert!(!opts.deps.system_headers);
6925        let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
6926        assert!(!opts.deps.system_headers);
6927        let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
6928        assert!(!opts.deps.system_headers);
6929    }
6930
6931    #[test]
6932    fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
6933        let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
6934        assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
6935    }
6936
6937    #[test]
6938    fn the_rest_of_the_family_is_a_file_and_a_switch() {
6939        let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
6940        assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
6941        assert!(opts.deps.phony);
6942
6943        for flag in ["-MF", "-MT", "-MQ"] {
6944            let e = parse_args(&args(&[flag])).unwrap_err();
6945            assert!(e.message.contains("requires an argument"), "{}", e.message);
6946        }
6947    }
6948
6949    /// Kbuild's spelling, which is how busybox and the kernel ask for every dependency file.
6950    #[test]
6951    fn a_dependency_file_asked_for_through_the_preprocessor_is_written_where_it_said() {
6952        let (opts, _) = compile(&["-Wp,-MD,applets/.applets.o.d", "-c", "a.c"]);
6953        assert!(opts.deps.emit);
6954        assert!(opts.deps.system_headers);
6955        assert_eq!(opts.deps.file.as_deref(), Some("applets/.applets.o.d"));
6956
6957        let (opts, _) = compile(&["-Wp,-MMD,x.d,-MP,-MT,x.o", "-c", "a.c"]);
6958        assert!(!opts.deps.system_headers);
6959        assert!(opts.deps.phony);
6960        assert_eq!(opts.deps.file.as_deref(), Some("x.d"));
6961        assert_eq!(opts.deps.targets, vec!["x.o".to_owned()]);
6962    }
6963
6964    #[test]
6965    fn a_preprocessor_flag_this_compiler_does_not_read_is_still_refused_whole() {
6966        assert!(refused(&["-Wp,-MD", "-c", "a.c"]).contains("separate assembler"));
6967        assert!(refused(&["-Wp,-MD,x.d,-C", "-c", "a.c"]).contains("-Wp,-MD,x.d,-C"));
6968    }
6969
6970    /// A directory of sources for one test, removed when the test is done with it.
6971    struct TempTree(PathBuf);
6972
6973    impl Drop for TempTree {
6974        fn drop(&mut self) {
6975            let _ = std::fs::remove_dir_all(&self.0);
6976        }
6977    }
6978
6979    impl TempTree {
6980        fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
6981            let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
6982            let _ = std::fs::remove_dir_all(&dir);
6983            std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
6984            for (path, text) in files {
6985                let at = dir.join(path);
6986                if let Some(parent) = at.parent() {
6987                    std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
6988                }
6989                std::fs::write(&at, text).expect("writing a temporary file should work");
6990            }
6991            TempTree(dir)
6992        }
6993
6994        fn path(&self, name: &str) -> String {
6995            self.0.join(name).to_string_lossy().into_owned()
6996        }
6997    }
6998
6999    #[test]
7000    fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
7001        // End to end, because the list comes from the preprocessor and the format comes from
7002        // somewhere else, and a test of either half on its own would pass with the two of them
7003        // wired up backwards.
7004        let tree = TempTree::new(
7005            "found",
7006            &[
7007                ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
7008                ("one.h", "#define X 0\n"),
7009                ("two.h", "#include \"one.h\"\n"),
7010            ],
7011        );
7012        let out = tree.path("dep.d");
7013        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
7014        assert_eq!(code, 0);
7015
7016        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
7017        let names: Vec<&str> = text.split_whitespace().collect();
7018        // The target, the source, and each header once however many times it was reached.
7019        assert_eq!(names.first(), Some(&"a.o:"), "{text}");
7020        assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
7021        assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
7022        // And the `-o` went to the file the rule replaced, which is left empty rather than
7023        // absent because a makefile that named it as a target will look for it.
7024        assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
7025    }
7026
7027    #[test]
7028    fn syntax_only_checks_the_file_and_writes_nothing() {
7029        // What meson's `has_header_symbol` probe does: compile with `-fsyntax-only` and read the
7030        // exit status. A good file passes and leaves no output behind, a bad one fails.
7031        let tree = TempTree::new(
7032            "syntax-only",
7033            &[
7034                ("good.c", "int f(int x) { return x + 1; }\n"),
7035                ("bad.c", "int f(void) { return y; }\n"),
7036            ],
7037        );
7038        let (opts, _) = compile(&["-fsyntax-only", "a.c"]);
7039        assert_eq!(opts.emit, EmitKind::SyntaxOnly);
7040
7041        let out = tree.path("good.o");
7042        assert_eq!(run(&args(&["-fsyntax-only", "-o", &out, &tree.path("good.c")])), 0);
7043        assert!(!std::path::Path::new(&out).exists(), "-fsyntax-only wrote {out}");
7044        assert!(!std::path::Path::new(&tree.path("good.s")).exists());
7045        assert_ne!(run(&args(&["-fsyntax-only", &tree.path("bad.c")])), 0);
7046    }
7047
7048    /// Where `-fstack-usage` puts each job's report, one entry per job, for a command line.
7049    fn stack_usage_files(line: &[&str]) -> Vec<Option<String>> {
7050        let mut words = vec![LINUX, "-fstack-usage"];
7051        words.extend_from_slice(line);
7052        let (_, plan) = compile(&words);
7053        plan.jobs.iter().map(|job| job.stack_usage.clone()).collect()
7054    }
7055
7056    #[test]
7057    fn a_stack_usage_file_is_named_the_way_gcc_names_it() {
7058        // Every row was run through gcc 16 with the same command line, and the name is the one it
7059        // wrote. `rpg frames` finds gcc's file and this compiler's by the same rule, so a name that
7060        // differs is a function that goes missing from the comparison.
7061        let cases: &[(&[&str], &[Option<&str>])] = &[
7062            (&["-c", "sub/a.c"], &[Some("a.su")]),
7063            (&["-c", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.su")]),
7064            (&["-c", "sub/a.c", "b.c"], &[Some("a.su"), Some("b.su")]),
7065            (&["-S", "sub/a.c", "-o", "out/y.s"], &[Some("out/y.su")]),
7066            (&["-S", "sub/a.c", "-o", "-"], &[Some("a.su")]),
7067            (&["-E", "sub/a.c", "-o", "out/z.i"], &[None]),
7068            (&["-fsyntax-only", "sub/a.c"], &[Some("a.su")]),
7069            (&["-fsyntax-only", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.o-a.su")]),
7070            (&["sub/a.c"], &[Some("a.su")]),
7071            (&["sub/a.c", "-lm"], &[Some("a.su")]),
7072            (&["sub/a.c", "b.c"], &[Some("a-a.su"), Some("a-b.su")]),
7073            (&["sub/a.c", "b.o"], &[Some("a-a.su"), None]),
7074            (&["sub/a.c", "-o", "out/prog"], &[Some("out/prog-a.su")]),
7075            (&["sub/a.c", "-o", "out/lib.so"], &[Some("out/lib.so-a.su")]),
7076            (&["sub/a.c", "-o", "out/prog.exe"], &[Some("out/prog-a.su")]),
7077            (&["sub/a.c", "-o", "out/prog", "-dumpbase", "zz"], &[Some("out/zz-a.su")]),
7078            (&["sub/a.c", "-o", "out/prog", "-dumpdir", "dd-"], &[Some("dd-a.su")]),
7079            (
7080                &["sub/a.c", "b.c", "-dumpdir", "dd/", "-dumpbase", "zz"],
7081                &[Some("dd/zz-a.su"), Some("dd/zz-b.su")],
7082            ),
7083            (&["-c", "sub/a.c", "-dumpbase", "foo", "-o", "out/w.o"], &[Some("out/foo.su")]),
7084            (&["-c", "sub/a.c", "-dumpdir", "dd/", "-dumpbase", "sub/zz"], &[Some("sub/zz.su")]),
7085            (&["-c", "sub/a.c", "-dumpbase", "zz.c", "-dumpbase-ext", ".c"], &[Some("zz.su")]),
7086            (&["-c", "sub/a.c", "-dumpdir", "pre", "-o", "out/x.o"], &[Some("prex.su")]),
7087            (&["-c", "sub/a.c", "-save-temps=cwd", "-o", "out/x.o"], &[Some("x.su")]),
7088        ];
7089        for (line, want) in cases {
7090            let want: Vec<Option<String>> = want.iter().map(|w| w.map(str::to_owned)).collect();
7091            assert_eq!(stack_usage_files(line), want, "{line:?}");
7092        }
7093        // Nothing at all without the flag.
7094        let (_, plan) = compile(&[LINUX, "-c", "sub/a.c"]);
7095        assert_eq!(plan.jobs[0].stack_usage, None);
7096    }
7097
7098    #[test]
7099    fn a_stack_usage_file_has_a_line_per_function_where_gcc_would_put_it() {
7100        let tree = TempTree::new(
7101            "stack-usage",
7102            &[
7103                ("inc/h.h", "static inline int twice(int x) { return x * 2; }\n"),
7104                (
7105                    "a.c",
7106                    "#include \"inc/h.h\"\n\
7107                     static int helper(int);\n\
7108                     int grows(int n) { char v[n]; v[0] = (char)n; return v[n - 1] + twice(n); }\n\
7109                     static int\n\
7110                     helper(int x)\n\
7111                     {\n\
7112                     return x + 1;\n\
7113                     }\n\
7114                     int calls(int x) { return helper(x) + grows(x); }\n",
7115                ),
7116            ],
7117        );
7118        let (source, object) = (tree.path("a.c"), tree.path("a.o"));
7119        assert_eq!(run(&args(&["-O0", "-fstack-usage", "-c", &source, "-o", &object])), 0);
7120        let text = std::fs::read_to_string(tree.path("a.su")).expect("a.su should be written");
7121
7122        let line = |function: &str| {
7123            let suffix = format!(":{function}");
7124            let line =
7125                text.lines().find(|line| line.split('\t').next().unwrap().ends_with(&suffix));
7126            line.unwrap_or_else(|| panic!("no line for {function} in\n{text}"))
7127        };
7128        let expect = |function: &str, at: String, qualifier: &str| {
7129            let fields: Vec<&str> = line(function).split('\t').collect();
7130            assert_eq!(fields.len(), 3, "{text}");
7131            assert_eq!(fields[0], format!("{at}:{function}"), "{text}");
7132            let bytes: u32 = fields[1].parse().expect("the bytes should be a number");
7133            assert!(bytes >= 8 && bytes % 8 == 0, "{function} takes {bytes} bytes");
7134            assert_eq!(fields[2], qualifier, "{text}");
7135        };
7136        // A variable length array makes the frame grow while the function runs.
7137        expect("grows", format!("{source}:3:5"), "dynamic");
7138        // The definition rather than the declaration above it, and the line the name is on
7139        // rather than the one the type is on.
7140        expect("helper", format!("{source}:5:1"), "static");
7141        expect("calls", format!("{source}:9:5"), "static");
7142        // A function from a header is reported against the header.
7143        expect("twice", format!("{}:1:19", tree.path("inc/h.h")), "static");
7144        assert_eq!(text.lines().count(), 4, "{text}");
7145    }
7146
7147    #[test]
7148    fn a_stack_usage_file_is_empty_when_there_is_nothing_to_report_and_absent_under_dash_e() {
7149        let tree = TempTree::new(
7150            "stack-usage-empty",
7151            &[
7152                ("good.c", "int f(int x) { return x + 1; }\n"),
7153                ("bad.c", "int f(void) { return y; }\n"),
7154            ],
7155        );
7156        let good = tree.path("good.c");
7157        // gcc writes an empty file for a check that compiles nothing and for a file that failed,
7158        // and a build that looks for one beside every object finds one.
7159        assert_eq!(
7160            run(&args(&["-fstack-usage", "-fsyntax-only", &good, "-o", &tree.path("x")])),
7161            0
7162        );
7163        assert_eq!(std::fs::read_to_string(tree.path("x-good.su")).unwrap(), "");
7164        let bad = tree.path("bad.c");
7165        assert_ne!(run(&args(&["-fstack-usage", "-c", &bad, "-o", &tree.path("bad.o")])), 0);
7166        assert_eq!(std::fs::read_to_string(tree.path("bad.su")).unwrap(), "");
7167        // And none under `-E`, which never reaches a function.
7168        assert_eq!(run(&args(&["-fstack-usage", "-E", &good, "-o", &tree.path("e.i")])), 0);
7169        assert!(!std::path::Path::new(&tree.path("e.su")).exists());
7170    }
7171
7172    #[test]
7173    fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
7174        // The multiple-include optimization means the second reach never opens the file. It is
7175        // still a file this translation unit was built from, so it is still in the rule.
7176        let tree = TempTree::new(
7177            "guarded",
7178            &[
7179                ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
7180                ("g.h", "#ifndef G\n#define G\n#endif\n"),
7181            ],
7182        );
7183        let out = tree.path("dep.d");
7184        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
7185        assert_eq!(code, 0);
7186        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
7187        assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
7188    }
7189
7190    #[test]
7191    fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
7192        // Measured against GCC rather than read: the two flags the other way round produce the
7193        // same output byte for byte, so the command line order between the two families does not
7194        // decide anything and the order within one does. The `-include` file here can only see
7195        // the definition if the `-imacros` file that was written after it ran first.
7196        let tree = TempTree::new(
7197            "preinclude",
7198            &[
7199                ("a.c", "int main(void) { return 0; }\n"),
7200                ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
7201                ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
7202            ],
7203        );
7204        let out = tree.path("a.i");
7205        let code = run(&args(&[
7206            "-E",
7207            "-include",
7208            &tree.path("i.h"),
7209            "-imacros",
7210            &tree.path("m.h"),
7211            "-o",
7212            &out,
7213            &tree.path("a.c"),
7214        ]));
7215        assert_eq!(code, 0);
7216        let text = std::fs::read_to_string(&out).expect("the output should have been written");
7217        assert!(text.contains("saw_it"), "{text}");
7218        // And the text of the `-imacros` file is thrown away, which is the whole difference
7219        // between the two flags.
7220        assert!(!text.contains("macros_text"), "{text}");
7221    }
7222
7223    #[test]
7224    fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
7225        let tree = TempTree::new(
7226            "preinclude-deps",
7227            &[
7228                ("a.c", "int main(void) { return 0; }\n"),
7229                ("i.h", "int from_include;\n"),
7230                ("m.h", "#define M 1\n"),
7231            ],
7232        );
7233        let out = tree.path("dep.d");
7234        let code = run(&args(&[
7235            "-MM",
7236            "-MF",
7237            &out,
7238            "-include",
7239            &tree.path("i.h"),
7240            "-imacros",
7241            &tree.path("m.h"),
7242            "-o",
7243            &tree.path("a.i"),
7244            &tree.path("a.c"),
7245        ]));
7246        assert_eq!(code, 0);
7247        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
7248        assert!(text.contains("i.h"), "{text}");
7249        assert!(text.contains("m.h"), "{text}");
7250    }
7251
7252    #[test]
7253    fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
7254        // Including the directory of the source file, which is not on the path for these: the
7255        // command line was not written there, so a name in it is relative to where the compiler
7256        // was run rather than to where the source sits.
7257        let tree = TempTree::new(
7258            "preinclude-missing",
7259            &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
7260        );
7261        let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
7262        assert_eq!(code, 1);
7263    }
7264
7265    #[test]
7266    fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
7267        // The object a link goes through is in a temporary directory and is gone before `make`
7268        // reads any of this, so the rule that named it would be a rule for a file that is never
7269        // there. The target and the file are both the `-o`, which is the executable.
7270        let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
7271        assert_eq!(plan.output.as_deref(), Some("prog"));
7272        assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
7273        assert_eq!(
7274            deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
7275            Some("prog.d")
7276        );
7277    }
7278
7279    #[test]
7280    fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
7281        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
7282        assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
7283        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
7284        assert_eq!(plan.output, None);
7285    }
7286
7287    #[test]
7288    fn usage_fits_on_a_screen() {
7289        // Not a style preference. A help text that scrolls is one nobody reads, and this is
7290        // the cheapest way to keep it honest as flags accumulate. The number goes up only when
7291        // a family of flags arrives that has nowhere to share a line, which the two pass gates
7292        // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
7293        // the lines that family took. The four it went up by last are the flags a build system
7294        // passes without being asked to: how much to say, what machine to generate for, threads,
7295        // and the questions `configure` asks before it compiles anything. The one it went up by
7296        // last is the second line of `--emit`, whose kinds are a family that has now outgrown
7297        // one line and has nowhere else to go. The two it went up by last are the dependency
7298        // family, which is eight flags that share nothing with anything above them. The one it
7299        // went up by last is the four spellings of position independent code, which every
7300        // configure script writes and which could only have shared the link line, and that line
7301        // is already four characters short of the limit. The two it went up by last are the rest
7302        // of the include family, which is six more flags that change where a header is looked for
7303        // and two that name a header outright. The one it went up by last is the pair that keeps
7304        // the intermediate files and times the steps, which belong next to the two flags above
7305        // them that are also about watching a compilation rather than changing one. The two it
7306        // went up by last are the section flags and the visibility flag, which are what a build
7307        // that cares about the size of what it ships and about which names it exports writes, and
7308        // the second of them was already taken and only missing from here. The one it went up by
7309        // last is the stack protector, which is four spellings of one question and which every
7310        // distribution puts on every command line it issues, so a build that reads this list
7311        // looking for it and does not find it has to go and read the specification instead. The one
7312        // it went up by last is the profiler, which is two spellings of the request and two of
7313        // where the call goes, and which is about watching a program run rather than about what is
7314        // generated, so it shares its subject with nothing above it. The one it went up by last is
7315        // the room a function opens with for something to be written over it later, which takes an
7316        // argument of its own shape and is what a kernel build asks for, so it fits beside the
7317        // profiler and nothing else. The one it went up by last is what overflows rather than being
7318        // undefined, which is three spellings of two questions and which a kernel build and a great
7319        // deal of code written before the standard settled both pass. The one it went up by last is
7320        // the other answer to the first of those questions, which could not share the line because
7321        // what it asks for is the opposite of what the flags on that line ask for. The one it went
7322        // up by last is the split of the line that lists what this compiler does anyway into that
7323        // and what it assumes anyway, which are two different claims that were sharing a line until
7324        // the second of them got a second flag and the line stopped fitting. The one it went up by
7325        // last is the three flags that change the ABI rather than the code, which have to be given
7326        // to every file in a program or none of them and which therefore belong somewhere a person
7327        // reading this list will see them. The one it went up by last is the floating point group,
7328        // which is two lines rather than one because the first of them is a choice this compiler
7329        // records and the rest are claims about what it does anyway, and putting a real setting on
7330        // the same line as three flags that change nothing would be misleading about both. The one
7331        // it went up by last is the flag that says a write has to stay inside the member it names,
7332        // which is a setting rather than a claim and so cannot share the line above it, that being
7333        // the one that picks a tier. The two it went up by last are the prefix mapping family,
7334        // which is four flags whose whole job is to keep a build's output the same from two
7335        // different directories, and which a person chasing a reproducible build comes here
7336        // looking for by name. The one it went up by last is how the debug sections are compressed
7337        // and whether they go in a file of their own, which are two questions about the shape of
7338        // the debug output, where the line above them is about how much of it there is. The one it
7339        // went up by last is the `restrict` contract, which is a setting for the same reason the
7340        // flag that keeps a write inside its member is and which is the check a person who has been
7341        // bitten by a vectorizer comes here looking for. The one it went up by last is link time
7342        // optimization, which is a whole optimization rather than a flag and which says so on its
7343        // own line, because a build that passes it and reads this looking for what it got is
7344        // asking a question no other line here answers. The one it went up by last is the sysroot,
7345        // which is the question somebody asks when a cross build read a file nobody expected, and
7346        // which has no room on the line above it because the answers there are a path each and this
7347        // one is the root all of them are under. The one it went up by last is what is inside that
7348        // root and where each of it came from, which is a question about a whole tree rather than
7349        // about a path and which is long enough on its own that it could not have shared a line with
7350        // anything. The one it went up by last is the profile family, which splits down the middle
7351        // where no other family here does, so the line has to name the half that is taken and the
7352        // half that is refused or it would be read as taking both. The one it went up by last is
7353        // the sanitizers, which are what somebody reaching for a checked build writes first and
7354        // which belong beside the tier that is the nearest thing here to what they asked for. The
7355        // one it went up by last is the digest of that record, which is the same tree as one number
7356        // and could not share the line above it because that line prints a few hundred lines and
7357        // this one prints sixty four characters, and a reader who wants the short answer is looking
7358        // for it by name rather than reading the long one. The one it went up by last is the
7359        // sysroot fetch, which is the only command here that gets something from somewhere else and
7360        // is therefore the one a person wants to have read before they run it rather than after.
7361        // And the flag beside it that forbids every download, which earns its line by being what a
7362        // build in a sealed environment passes and by meaning something even though an ordinary
7363        // compile downloads nothing either way. The one it went up by last is the other fetch, the
7364        // one behind Microsoft's licence wall, which is a line rather than a paragraph because what
7365        // a person needs from here is that the command exists and that it will not do anything
7366        // until they have read a licence it prints for them. The one it went up by last is dlltool
7367        // mode, which is not a compiler flag at all but a second program behind the same binary,
7368        // and which a person building mingw-w64 with this compiler has to be able to find without
7369        // knowing it is there.
7370        assert!(USAGE.lines().count() < 74, "usage text has grown past one screen");
7371    }
7372}