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.11.19")]
30
31pub mod assemble;
32pub mod cache;
33pub mod compile;
34pub mod deps;
35pub mod fetch;
36mod glibc;
37pub mod install;
38pub mod library;
39pub mod link;
40mod map;
41pub mod msvc;
42pub mod phase;
43pub mod preprocess;
44pub mod schedule;
45mod shapes;
46pub mod trace;
47mod warnings;
48
49use std::fmt::Write as _;
50use std::io::Write as _;
51use std::path::PathBuf;
52
53use rucc_codegen::coverage::{self, Fired};
54use rucc_codegen::lowering::Lowerings;
55use rucc_codegen::pressure::Pressure;
56use rucc_pp::Dependency;
57use rucc_session::{
58    Compress, Control, Dumps, EmitKind, Hook, Math, Options, Pic, PrefixMap, Preinclude, Protector,
59    SaveTemps, Session, Std, Wrapping, runtime,
60};
61use rucc_sysroot::{Manifest, Sysroot};
62use rucc_target::{ObjectFormat, Triple};
63use rucc_tuple::TargetTuple;
64
65use crate::link::LinkOptions;
66
67pub use crate::assemble::assemble;
68pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
69pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan, Role};
70pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
71pub use crate::schedule::Jobs;
72
73/// The compiler's version, taken from the workspace manifest.
74pub const VERSION: &str = env!("CARGO_PKG_VERSION");
75
76/// What the command line asked for.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum Action {
79    /// Print usage and exit successfully.
80    Help,
81    /// Print the version and exit successfully.
82    Version,
83    /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
84    ///
85    /// A build system asks these before it compiles anything, and what it does with the answer
86    /// is paste it into a path or into another command line, so each one is a single line with
87    /// no decoration around it.
88    Print(String),
89    /// Print the resolved configuration and exit successfully.
90    PrintConfig(Box<Options>),
91    /// Print the passes the level will run and exit successfully.
92    PrintPipeline(Box<Options>),
93    /// Print the phase plan and the link line and exit successfully, which is `-###`.
94    PrintPlan {
95        /// The resolved options, which is what says what the link line is for.
96        opts: Box<Options>,
97        /// What to do to each input, and in what order.
98        plan: Box<Plan>,
99        /// What the command line said about linking.
100        link: Box<LinkOptions>,
101    },
102    /// `--fetch <tuple>`, which gets the sysroot this release pins for a target and installs it.
103    ///
104    /// The only action in this compiler that may run another program to move bytes onto the
105    /// machine, which is `spec/cross-compile/13-distribution.md` section 13.8's rule rather than a
106    /// property of how this happens to be written: a compilation has no branch that reaches it.
107    Fetch {
108        /// The artifact, from the table in [`rucc_sysroot::artifact`]. Resolved here rather than where the
109        /// work happens, so that a target nothing is pinned for is a refusal from the parser like
110        /// every other thing a command line can ask for and not have.
111        what: &'static rucc_sysroot::Pinned,
112        /// The target, which names the directory under the cache the tree is installed at and is
113        /// checked against the record inside the artifact.
114        target: TargetTuple,
115        /// Where the cache is, read where everything else that needs it reads it.
116        cache: PathBuf,
117    },
118    /// `--fetch-msvc-sdk <tuple>`, which gets what is behind Microsoft's licence wall.
119    ///
120    /// The other action that may run another program to move bytes onto the machine, and the only
121    /// one that asks a person to accept somebody else's licence first.
122    /// `spec/cross-compile/13-distribution.md` section 13.4 is why it is a command of its own
123    /// rather than something `--fetch` does when it recognises the target: no release pins an
124    /// artifact for these, and nothing about this may ever happen because a compile wanted it to.
125    FetchMsvcSdk {
126        /// The target, which says which architecture's CRT library package is wanted.
127        target: TargetTuple,
128        /// Whether `--accept-licence` was on the command line. Without it the licence and the list
129        /// are printed and nothing is downloaded, which is the whole of what the flag is for.
130        accepted: bool,
131        /// Where the cache is, read where everything else that needs it reads it.
132        cache: PathBuf,
133    },
134    /// Compile the given inputs.
135    Compile {
136        /// The resolved options.
137        opts: Box<Options>,
138        /// What to do to each input, and in what order.
139        plan: Box<Plan>,
140        /// What the command line said about linking.
141        link: Box<LinkOptions>,
142        /// How many translation units to compile at once.
143        jobs: Jobs,
144        /// Whether `-v` asked for the plan to be printed while it runs.
145        verbose: bool,
146        /// What is worth saying about the command line before anything is compiled, printed as
147        /// warnings and once for the whole run rather than once per file.
148        ///
149        /// These are not diagnostics. A diagnostic is about a piece of source and has a span to
150        /// point at, and these are about the way two flags were combined, so there is nothing to
151        /// point at and nowhere below the driver that knows both halves. `-w` does not reach them
152        /// for the same reason it does not reach a refusal from the parser.
153        notes: Vec<String>,
154    },
155}
156
157/// Why a command line was rejected.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct CliError {
160    /// The message, lowercase and without a trailing period, in the same shape as any other
161    /// diagnostic.
162    pub message: String,
163}
164
165impl std::fmt::Display for CliError {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        f.write_str(&self.message)
168    }
169}
170
171impl std::error::Error for CliError {}
172
173fn err(message: impl Into<String>) -> CliError {
174    CliError { message: message.into() }
175}
176
177/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
178///
179/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
180/// the only one that lets a directory whose name contains an `=` be the old half. It also means
181/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
182/// trap until you notice the alternative traps the far more common case.
183fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
184    let rest = &arg[flag.len()..];
185    PrefixMap::split(rest).ok_or_else(|| {
186        let flag = flag.trim_end_matches('=');
187        err(format!(
188            "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
189        ))
190    })
191}
192
193/// A question the command line asked instead of asking for a compilation.
194///
195/// These are answered after the loop rather than where they are read, because every one of them
196/// is about the target or about the library search and the last word on both is the end of the
197/// command line.
198enum Query {
199    /// `-dumpmachine`, the triple.
200    Machine,
201    /// `-dumpversion`, the major number of the GCC release this compiler claims to be.
202    Version,
203    /// `-dumpfullversion`, the same release in all three numbers.
204    FullVersion,
205    /// `-print-multiarch`, the directory name a distribution files this target under.
206    Multiarch,
207    /// `-print-search-dirs`, in the three lines GCC prints.
208    SearchDirs,
209    /// `-print-sysroot`, the root the headers and the libraries are read under.
210    Sysroot,
211    /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
212    SysrootProvenance,
213    /// `-print-sysroot-digest`, the one number that names all of it.
214    SysrootDigest,
215    /// `-print-file-name=<name>`, the full path of a library file.
216    FileName(String),
217    /// `-print-prog-name=<name>`, the full path of a program.
218    ProgName(String),
219    /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
220    Libgcc,
221}
222
223/// Usage text.
224///
225/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
226/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
227pub const USAGE: &str = "\
228rucc, an optimizing C compiler
229
230usage: rucc [options] file...
231
232options:
233  -c                     compile and assemble, do not link
234  -S                     compile only, emit assembly
235  -E                     preprocess only
236  -o <file>              write output to <file>, or to standard output for -
237  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
238  -I <dir>               add <dir> to the include search path
239  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
240  -I-, -iprefix <p>, -iwithprefix[before] <dir>   the older spellings of those
241  -include <file>, -imacros <file>    read <file> first, the second for its macros only
242  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
243  -P, -dM                with -E: leave out the markers, or dump the macros
244  -M -MM -MD -MMD        write a make rule for the source, the last two compile as well
245  -MF <file> -MT <t> -MQ <t> -MP   where the rule goes, what it builds, targets with no recipe
246  -std=<dialect>         c89 through c2y, and the gnu spellings
247  -fgnuc-version=<v>     the GCC release to claim, default 16.0.0
248  -x <lang>              treat later inputs as <lang>, or none to stop
249  -O<level>              optimize: 0, 1, 2, 3, s, z, fast
250  -fsafety=<tier>        check memory safety: off, detect, enforce, kernel
251  -f[no-]sanitize=<what>   the negative is taken, the positive is refused by name
252  -f[no-]safety-subobject   a write has to stay inside the member it names
253  -f[no-]safety-restrict    two restrict pointers of one block may not meet
254  -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
255  -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n>   stop a pass, or all of them, after n
256  -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>]   run a pass on some functions only
257  -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone   debug info, frame pointer, red zone
258  -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf   compress debug sections, one file not two
259  -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects   read, and not done yet
260  -fprofile-use[=<path>] -fprofile-dir=<dir>   read too, where -fprofile-generate is refused
261  -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
262  -ffunction-sections -fdata-sections   a section per function or variable, for --gc-sections
263  -fvisibility=<what>    default, hidden, internal or protected, when nothing in the source said
264  -l<name>, -L <dir>, -B <dir>   link a library, where to look for one, where our own tools are
265  -fPIC -fpic -fPIE -fpie, -fno-common, -pipe   what it does anyway
266  -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks   what it assumes anyway
267  -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s   how to link
268  -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name>   hand an argument to the linker, or pick one
269  -Werror -pedantic -pedantic-errors -w -W[no-]system-headers   how much to say, and how fatal
270  -m64 -march= -mtune= -mcpu= -mabi= -mcmodel=   what machine to generate for
271  -pg -p, -mfentry -mno-fentry   call a profiler on the way in, and where that call goes
272  -fpatchable-function-entry=<n>[,<m>]   room at the top of every function to patch later
273  -fwrapv, -fwrapv-pointer, -fno-strict-overflow, -ftrapv   overflow wraps, or stops the program
274  -f[no-]exceptions, -f[no-]non-call-exceptions   let an exception unwind through the code
275  -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums   change the ABI
276  -ffp-contract=<how>    fuse a multiply and an addition: fast, on or off
277  -f[no-]fast-math and each of its members, -f[no-]rounding-math, -fexcess-precision=<how>
278  -ffile-prefix-map=<old>=<new>   rewrite that front of every path we put in the output
279  -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map=   the same, one output each
280  -pthread               build for more than one thread, and link the library for it
281  -dumpmachine -dumpversion -print-multiarch -print-search-dirs   what this compiler is
282  -print-file-name=<name> -print-prog-name=<name>   where a file or a program is
283  -print-sysroot         the root the headers and the libraries are read under
284  -print-sysroot-provenance   every input under it, where it came from and its licence
285  -print-sysroot-digest   the sha256 of that record, which names the whole sysroot in one line
286  --fetch <tuple>        get the sysroot this release pins for <tuple> and install it in the cache
287  --fetch-msvc-sdk <tuple>   Microsoft's licence, then the SDK behind it with --accept-licence
288  --offline              never download anything, which a compilation never does anyway
289  -j[n]                  compile n translation units at once, default all
290  -v, -###               print each phase as it runs, or without running any
291  -save-temps[=cwd|obj], -fstack-usage, -time   keep the .i and .s, write a .su, time each step
292  --target=<triple>      generate code for <triple>, which a name like <triple>-rucc also does
293  --emit=<kind>          exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
294                         safety-summary, type-granules
295  --print-config, --print-pipeline    print the configuration or the pipeline, and exit
296  --version              print the version and exit
297  -h, --help             print this message and exit
298
299See spec/04-driver-and-cli.md for the full flag reference.
300";
301
302/// The argument of a flag that may be joined to it or may be the next word.
303///
304/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
305fn joined_or_next(
306    arg: &str,
307    at: usize,
308    args: &[String],
309    i: &mut usize,
310) -> Result<String, CliError> {
311    if arg.len() > at {
312        return Ok(arg[at..].to_owned());
313    }
314    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
315    *i += 1;
316    Ok(next.clone())
317}
318
319/// The smallest boundary a function is put on when the command line asked for no alignment at all.
320///
321/// Eight bytes, which is what gcc 16 gives `-fno-align-functions` on x86-64 and is a boundary every
322/// target this compiler has is happy with. It is not zero: a function still has to start somewhere
323/// an instruction may start, and the flag asks for the target's minimum rather than for none.
324const MIN_FUNC_ALIGN: u32 = 8;
325
326/// What `-falign-functions=N` asks for, as a power of two, or `None` for the target's own answer.
327///
328/// Zero and one both mean the default, which is gcc's reading of them, and everything else is
329/// rounded up to the next power of two, which is also gcc's: `-falign-functions=3` puts a function
330/// on a four byte boundary rather than being refused. Gives back `Err` shaped as an outer `None`
331/// only when the text is not a number, since that is the one thing gcc will not read either. A
332/// number larger than any alignment makes sense at is clamped rather than refused, for the same
333/// reason: this is a preference about speed and a build that wrote a silly one still deserves to
334/// compile.
335fn function_alignment(text: &str) -> Option<Option<u32>> {
336    // gcc takes `N:M:N2:M2`, where everything after the first number is about how far it is willing
337    // to go to reach the boundary. Only the boundary is answerable here, so the rest is read to
338    // check that it is numbers and then dropped.
339    let mut parts = text.split(':');
340    let first = parts.next()?;
341    if parts.any(|part| part.parse::<u64>().is_err()) {
342        return None;
343    }
344    let want: u64 = first.parse().ok()?;
345    if want <= 1 {
346        return Some(None);
347    }
348    let bytes = want.min(1 << 16).next_power_of_two();
349    Some(Some(u32::try_from(bytes).ok()?))
350}
351
352/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
353/// own.
354///
355/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
356/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
357/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
358/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
359/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
360/// because none of them is implemented.
361///
362/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
363/// those two spellings is read rather than by being on this list.
364const SANITIZERS: [&str; 34] = [
365    "address",
366    "kernel-address",
367    "hwaddress",
368    "kernel-hwaddress",
369    "pointer-compare",
370    "pointer-subtract",
371    "thread",
372    "leak",
373    "undefined",
374    "shift",
375    "shift-base",
376    "shift-exponent",
377    "integer-divide-by-zero",
378    "unreachable",
379    "vla-bound",
380    "null",
381    "return",
382    "signed-integer-overflow",
383    "bounds",
384    "bounds-strict",
385    "alignment",
386    "object-size",
387    "float-divide-by-zero",
388    "float-cast-overflow",
389    "nonnull-attribute",
390    "returns-nonnull-attribute",
391    "bool",
392    "enum",
393    "vptr",
394    "pointer-overflow",
395    "builtin",
396    "alias",
397    "restrict",
398    "memory",
399];
400
401/// The command line with every `@file` replaced by the words in the file, the way gcc does it.
402///
403/// Meson writes the link of a large target this way, so that a command line holding a thousand
404/// objects stays under the limit the system puts on one. Postgres's `postgres` executable is the
405/// one link in its tree that meson writes as `@postgres.rsp`, and before this the name went to
406/// the linker as it was. GNU ld reads response files itself, so it opened the file and found
407/// `-Wl,--as-needed` in it, which is a driver flag it has never heard of.
408///
409/// The rules are libiberty's `expandargv`, since that is what gcc and every other GNU tool read
410/// these files with. Words are split on white space, a single or a double quote keeps white
411/// space in a word until the matching quote, and a backslash makes the character after it an
412/// ordinary one, inside quotes as well as outside. A word the file gives that starts with `@` is
413/// read as a response file in turn. A name that cannot be opened is left on the command line as
414/// it was, which is what gcc does and which is how a file really called `@x.c` still reaches the
415/// loop, where it is refused as an unknown input rather than swallowed. The depth is capped so a
416/// file that names itself is an error and not a hang.
417fn response_files(args: &[String]) -> Result<Vec<String>, CliError> {
418    const DEEPEST: usize = 64;
419    fn expand(args: &[String], depth: usize, out: &mut Vec<String>) -> Result<(), CliError> {
420        for arg in args {
421            let Some(name) = arg.strip_prefix('@') else {
422                out.push(arg.clone());
423                continue;
424            };
425            let Ok(text) = std::fs::read_to_string(name) else {
426                out.push(arg.clone());
427                continue;
428            };
429            if depth == DEEPEST {
430                return Err(err(format!("response file '{name}' is nested too deeply")));
431            }
432            expand(&response_words(&text), depth + 1, out)?;
433        }
434        Ok(())
435    }
436    if !args.iter().any(|arg| arg.starts_with('@')) {
437        return Ok(args.to_vec());
438    }
439    let mut out = Vec::with_capacity(args.len());
440    expand(args, 0, &mut out)?;
441    Ok(out)
442}
443
444/// The words of one response file, split the way libiberty's `buildargv` splits them.
445fn response_words(text: &str) -> Vec<String> {
446    let mut words = Vec::new();
447    let mut word = String::new();
448    // Whether a word has begun, which is not the same as `word` having something in it: `''` is
449    // an empty word of its own and has to reach the command line as one.
450    let mut begun = false;
451    let mut quote: Option<char> = None;
452    let mut chars = text.chars();
453    while let Some(c) = chars.next() {
454        match c {
455            '\\' => {
456                if let Some(next) = chars.next() {
457                    word.push(next);
458                }
459                begun = true;
460            }
461            _ if quote == Some(c) => quote = None,
462            _ if quote.is_some() => word.push(c),
463            '\'' | '"' => {
464                quote = Some(c);
465                begun = true;
466            }
467            _ if c.is_whitespace() => {
468                if begun {
469                    words.push(std::mem::take(&mut word));
470                    begun = false;
471                }
472            }
473            _ => {
474                word.push(c);
475                begun = true;
476            }
477        }
478    }
479    if begun {
480        words.push(word);
481    }
482    words
483}
484
485/// The command line with every `-Wp,` this compiler understands spelled as its own flags.
486///
487/// The preprocessor is inside this compiler, so what a build hands it through `-Wp,` has to be
488/// read here. Kbuild is the reason: every object in the Linux kernel and in busybox is compiled
489/// with `-Wp,-MD,dir/.name.o.d`, which is cpp's spelling of `-MD -MF dir/.name.o.d`. cpp's `-MD`
490/// and `-MMD` take the file as their next word where the driver's do not, and the rest are the
491/// same flags in both. A `-Wp,` holding anything else is left as it was so the loop refuses it,
492/// because dropping part of what a build asked the preprocessor for would be the silent kind of
493/// wrong.
494fn preprocessor_args(args: &[String]) -> Vec<String> {
495    let mut out = Vec::with_capacity(args.len());
496    for arg in args {
497        let Some(list) = arg.strip_prefix("-Wp,") else {
498            out.push(arg.clone());
499            continue;
500        };
501        let words: Vec<&str> = list.split(',').collect();
502        let mut spelled = Vec::new();
503        let mut i = 0;
504        let understood = loop {
505            let Some(&word) = words.get(i) else {
506                break true;
507            };
508            i += 1;
509            match word {
510                "-MD" | "-MMD" | "-MF" | "-MT" | "-MQ" => {
511                    let Some(&value) = words.get(i) else {
512                        break false;
513                    };
514                    i += 1;
515                    if word == "-MD" || word == "-MMD" {
516                        spelled.extend([word.to_owned(), "-MF".to_owned()]);
517                    } else {
518                        spelled.push(word.to_owned());
519                    }
520                    spelled.push(value.to_owned());
521                }
522                "-MP" => spelled.push(word.to_owned()),
523                _ if word.len() > 2
524                    && (word.starts_with("-D")
525                        || word.starts_with("-U")
526                        || word.starts_with("-I")) =>
527                {
528                    spelled.push(word.to_owned());
529                }
530                _ => break false,
531            }
532        };
533        if understood {
534            out.extend(spelled);
535        } else {
536            out.push(arg.clone());
537        }
538    }
539    out
540}
541
542/// The extension a `-m` flag names and whether it turns it on, when it names one.
543///
544/// `-mno-` is the off form of every one of them, which is also how gcc spells it. A flag that is
545/// not an extension, `-mno-red-zone` say, is `None` and is left to the rest of the parser.
546fn isa_name(arg: &str) -> Option<(&str, rucc_target::Feature, bool)> {
547    let rest = arg.strip_prefix("-m")?;
548    let (name, on) = match rest.strip_prefix("no-") {
549        Some(name) => (name, false),
550        None => (rest, true),
551    };
552    let known =
553        if on { rucc_target::Feature::named(name) } else { rucc_target::Feature::named_off(name) };
554    known.map(|feature| (name, feature, on))
555}
556
557/// The extensions the machine running the compiler has, which is what `-march=native` means.
558///
559/// Asked of the processor with `cpuid`, through the standard library, and only when the compiler
560/// is running on an x86-64 at all. Anywhere else there is no processor to ask about an x86-64 one,
561/// and gcc on such a machine builds for the baseline, which is what this does. The list is the
562/// extensions whose names are stable in the standard library at this workspace's minimum Rust
563/// version, which covers everything [`rucc_target::Feature::honoured`] says yes to and a good deal
564/// that it does not.
565fn native_isa() -> rucc_target::Isa {
566    let base = rucc_target::Isa::baseline();
567    #[cfg(target_arch = "x86_64")]
568    {
569        let mut isa = rucc_target::Choices::new();
570        macro_rules! asked {
571            ($($detected:tt => $name:literal),* $(,)?) => {
572                $(if std::arch::is_x86_feature_detected!($detected) {
573                    isa.read($name).expect("a name gcc knows");
574                })*
575            };
576        }
577        asked! {
578            "sse3" => "sse3",
579            "ssse3" => "ssse3",
580            "sse4.1" => "sse4.1",
581            "sse4.2" => "sse4.2",
582            "sse4a" => "sse4a",
583            "popcnt" => "popcnt",
584            "avx" => "avx",
585            "avx2" => "avx2",
586            "fma" => "fma",
587            "f16c" => "f16c",
588            "bmi1" => "bmi",
589            "bmi2" => "bmi2",
590            "lzcnt" => "lzcnt",
591            "xsave" => "xsave",
592            "aes" => "aes",
593            "pclmulqdq" => "pclmul",
594            "sha" => "sha",
595            "cmpxchg16b" => "cx16",
596            "adx" => "adx",
597            "rdrand" => "rdrnd",
598            "rdseed" => "rdseed",
599        }
600        isa.over(base)
601    }
602    #[cfg(not(target_arch = "x86_64"))]
603    base
604}
605
606/// Parses a command line, without the program name.
607///
608/// # Errors
609///
610/// Returns the message to print when the arguments do not name a compilation this compiler
611/// can attempt.
612pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
613    let expanded = preprocessor_args(&response_files(args)?);
614    let args = expanded.as_slice();
615    let host = Triple::host()
616        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
617    let mut opts = Options::new(host);
618    // Where the compiler is running, which is what `DW_AT_comp_dir` is and what a debugger joins a
619    // relative file name onto. Asked here rather than where the debug sections are written, because
620    // this is the one layer that is allowed to look at the process it is in, and because a command
621    // line that compiles four files should give the same answer for all four.
622    opts.working_dir = std::env::current_dir().ok().map(|dir| dir.to_string_lossy().into_owned());
623    let mut inputs: Vec<Input> = Vec::new();
624    let mut print_config = false;
625    let mut print_pipeline = false;
626    let mut print_plan = false;
627    let mut verbose = false;
628    let mut jobs = Jobs::default();
629    let mut nostdinc = false;
630    let mut sysroot: Option<PathBuf> = None;
631    // What the command line is worth warning about, filled in after the loop rather than during it,
632    // because every question of this kind is about two flags and the last word on both of them is
633    // the end of the loop.
634    let mut notes: Vec<String> = Vec::new();
635    // The whole ten field target, kept beside the three field one because `--target=` can pin a
636    // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
637    // else today, and `None` is a command line that named no target, which is this machine.
638    let mut pinned: Option<TargetTuple> = None;
639    let mut min_version: Option<rucc_tuple::Version> = None;
640    let mut output = None;
641    let mut link = LinkOptions::default();
642    let mut query: Option<Query> = None;
643    // What `--fetch` named, and whether `--offline` forbade it. Both are weighed after the loop
644    // because either can be written after the other.
645    let mut fetch: Option<String> = None;
646    // The other fetch, kept apart from the one above because they are different commands with
647    // different rules, and weighed after the loop for the same reason that one is.
648    let mut fetch_msvc: Option<String> = None;
649    let mut accepted = false;
650    let mut offline = false;
651    let mut threads = false;
652    // Which sanitizers are still asked for by the end of the command line. Accumulated across the
653    // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
654    // build that asks for a check and then takes it back has asked for nothing. What happens to a
655    // set that is not empty is decided after the loop.
656    let mut sanitizers: Vec<&str> = Vec::new();
657    // The `-ffast-math` family in the order it was written, replayed after the loop on top of
658    // what `-Ofast` implies. gcc applies a level's defaults before any flag and the flags in order
659    // after that, so `-fno-fast-math -Ofast` is not fast math, and only a replay can say so.
660    let mut math_flags: Vec<&str> = Vec::new();
661    let mut ofast = false;
662    // `-mdaz-ftz` and `-mno-daz-ftz`, which decide the startup file directly and outrank the
663    // family on that one question.
664    let mut daz_ftz: Option<bool> = None;
665    // The instruction set extensions the `-m` flags named, in order, and the processor `-march`
666    // named last. Both are weighed after the loop, because a processor supplies only what no flag
667    // spoke for whichever order they came in, and because `--target=` may come after either and
668    // decide that neither means anything. See `rucc_target::isa`.
669    let mut isa = rucc_target::Choices::new();
670    let mut isa_flag: Option<&str> = None;
671    let mut march: Option<&str> = None;
672    // What `-fexceptions` and `-fno-exceptions` last said, if either was written. It is kept apart
673    // from the field because `-fnon-call-exceptions` turns exceptions on only when neither was,
674    // which is gcc's rule and is why `-fno-exceptions -fnon-call-exceptions` defines no
675    // `__EXCEPTIONS` whichever order the two come in.
676    let mut exceptions: Option<bool> = None;
677    // `-x` applies to inputs that come after it and stays in effect until the next one, which
678    // is why it is tracked across the loop rather than attached to a single argument.
679    let mut forced: Option<InputKind> = None;
680    // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
681    // the flags after it and not the ones before, so a command line may set it more than once.
682    // GCC's default is its own installed header directory with the last component taken off,
683    // which is a path a cross compiler's build system knows and passes; there is no equivalent
684    // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
685    // outright.
686    let mut iprefix = String::new();
687
688    let mut i = 0;
689    while i < args.len() {
690        let arg = args[i].as_str();
691        i += 1;
692        match arg {
693            "-h" | "--help" => return Ok(Action::Help),
694            "--version" => return Ok(Action::Version),
695            // The sysroot fetch, which is weighed after the loop rather than acted on here, because
696            // `--offline` written after it has to be able to forbid it. Both spellings, since a
697            // flag that takes a tuple gets written both ways and neither is a guess at what the
698            // other meant.
699            "--fetch" => {
700                let value = args
701                    .get(i)
702                    .ok_or_else(|| err("--fetch requires the target to get a sysroot for"))?;
703                i += 1;
704                fetch = Some(value.clone());
705            }
706            _ if arg.starts_with("--fetch=") => {
707                fetch = Some(arg["--fetch=".len()..].to_owned());
708            }
709            // The other fetch, which is section 13.4's. Same two spellings for the same reason,
710            // and weighed after the loop so that `--offline` and `--accept-licence` written after
711            // it are read whichever order somebody put them in.
712            "--fetch-msvc-sdk" => {
713                let value = args.get(i).ok_or_else(|| {
714                    err("--fetch-msvc-sdk requires the target to get the SDK for")
715                })?;
716                i += 1;
717                fetch_msvc = Some(value.clone());
718            }
719            _ if arg.starts_with("--fetch-msvc-sdk=") => {
720                fetch_msvc = Some(arg["--fetch-msvc-sdk=".len()..].to_owned());
721            }
722            // Both spellings of the word, because the compiler's own prose uses one of them and
723            // most of the people typing this will reach for the other, and being told that a flag
724            // is not a flag over the letter in the middle of it is a puzzle rather than a message.
725            "--accept-licence" | "--accept-license" => accepted = true,
726            // Accepted on any command line and only ever read by the fetch, because an ordinary
727            // compile downloads nothing with or without it. So this flag takes nothing away today,
728            // which is the property section 13.2 asks for rather than an omission: a build that
729            // passes it is saying what it expects of this compiler, and what it expects is already
730            // true.
731            "--offline" => offline = true,
732            "--print-config" => print_config = true,
733            "--print-pipeline" => print_pipeline = true,
734            "-###" => print_plan = true,
735            "-v" => verbose = true,
736            // The files a compilation goes through, kept rather than thrown away. The bare
737            // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
738            // gcc 16 does; `SaveTemps::Object` carries the measurement.
739            "-save-temps" => opts.save_temps = SaveTemps::Object,
740            _ if arg.starts_with("-save-temps=") => {
741                opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
742            }
743            // A `.su` beside every file compiled, one line per function saying how much stack it
744            // takes. Where the file goes is the plan's business, see `Job::stack_usage`.
745            "-fstack-usage" => opts.stack_usage = true,
746            "-fno-stack-usage" => opts.stack_usage = false,
747            // How long each step took. A misspelling of this is worth rejecting rather than
748            // ignoring, since a run that says nothing looks like a compilation that took no time.
749            "-time" => opts.time = true,
750            "-c" => opts.emit = EmitKind::Object,
751            "-S" => opts.emit = EmitKind::Asm,
752            "-E" => opts.emit = EmitKind::Preprocessed,
753            "-fsyntax-only" => opts.emit = EmitKind::SyntaxOnly,
754            "-g" => opts.debug_info = true,
755            // GCC's own levels of how much debug information to write. Zero is none and every
756            // other number is some, and this compiler has one amount, so the numbers above zero
757            // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
758            // debugger on the machine prefers, which is what we emit anyway.
759            "-g0" => opts.debug_info = false,
760            "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
761                opts.debug_info = true;
762            }
763            // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
764            // asks for another version is told rather than handed a file it cannot read.
765            "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
766            _ if arg.starts_with("-gdwarf-") => {
767                return Err(err(format!(
768                    "{arg}: this compiler writes DWARF 5 and no other version, see \
769                     spec/11-debug-info.md"
770                )));
771            }
772            // Whether the debug information goes in a file of its own beside the object. gcc
773            // writes that `.dwo` whether or not it found anything to put in it, which means a
774            // build system that declares the file as an output gets one and a make rule that
775            // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
776            // flag that changes nothing and refuses one that changes what is produced, and a file
777            // that does not appear is the plainest change of that kind there is. The negative
778            // spelling is taken, because putting it all in the object is what happens anyway.
779            "-gno-split-dwarf" => {}
780            "-gsplit-dwarf" => {
781                return Err(err(format!(
782                    "{arg}: this compiler writes no separate `.dwo` file, and a build that \
783                     expects one beside each object would wait for a file that never arrives, \
784                     see spec/11-debug-info.md"
785                )));
786            }
787            // How the debug sections are compressed. There are none yet, so every answer produces
788            // the same bytes and taking the flag promises nothing that is not kept. The value is
789            // still checked, because a typo in a distribution's flags is worth finding when the
790            // compiler reads it rather than when somebody later wonders why nothing got smaller.
791            // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
792            "-gz" => opts.compress = Compress::Zlib,
793            _ if arg.starts_with("-gz=") => {
794                let how = &arg["-gz=".len()..];
795                opts.compress = how.parse().map_err(|()| {
796                    err(format!(
797                        "`{how}` is not a way to compress debug sections, which is none, zlib, \
798                         zlib-gnu or zstd"
799                    ))
800                })?;
801            }
802            "-Werror" => opts.warnings_are_errors = true,
803            // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
804            // through rather than here, so that a warning `-w` dropped is not counted either.
805            "-w" => opts.warnings = false,
806            // Off by default, the way gcc has it off. A header that came with the machine is not
807            // one the person compiling can change, so a warning about it is noise, and under
808            // `-Werror` it is a build that stops on a line nobody in the project wrote. Somebody
809            // porting a header does want to hear all of it, which is what the flag is for.
810            "-Wsystem-headers" => opts.system_header_warnings = true,
811            "-Wno-system-headers" => opts.system_header_warnings = false,
812            "-pedantic-errors" => {
813                opts.pedantic = true;
814                opts.warnings_are_errors = true;
815            }
816            "-P" => opts.line_markers = false,
817            // The dependency family, which section 4.4 calls required because every build system
818            // that generates its own makefiles asks for it. The two that end in `D` write a file
819            // beside the object and let the compilation happen, and the two that do not write to
820            // standard output and stop after it. Nothing here turns the system headers back on
821            // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
822            // `-MM`: the flag asking for fewer of them is the one with something to say.
823            "-M" => {
824                opts.deps.emit = true;
825                opts.deps.instead_of_compiling = true;
826            }
827            "-MM" => {
828                opts.deps.emit = true;
829                opts.deps.instead_of_compiling = true;
830                opts.deps.system_headers = false;
831            }
832            "-MD" => opts.deps.emit = true,
833            "-MMD" => {
834                opts.deps.emit = true;
835                opts.deps.system_headers = false;
836            }
837            "-MP" => opts.deps.phony = true,
838            // These three take a word and only in the separated form, which is how GCC spells
839            // them and how every build system writes them.
840            "-MF" | "-MT" | "-MQ" => {
841                let value =
842                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
843                i += 1;
844                match arg {
845                    "-MF" => opts.deps.file = Some(value.clone()),
846                    // The whole of the difference between the two. `-MT` is for a build that has
847                    // already escaped what it is passing, and `-MQ` is for one that has a name
848                    // and wants it to arrive as that name.
849                    "-MT" => opts.deps.targets.push(value.clone()),
850                    _ => opts.deps.targets.push(deps::escaped(value)),
851                }
852            }
853            // The questions a build system asks before it compiles anything. Answered after the
854            // loop, because each one is about the target or the library search and the command
855            // line has not finished saying what those are.
856            "-dumpmachine" => query = Some(Query::Machine),
857            // Both answer with the GCC release in `__GNUC__` rather than our own version, because
858            // what asks is a build script deciding which GCC it is talking to, and `0.11` reads as
859            // a GCC too old to have anything. GCC 7 and later print only the major number for the
860            // first one, and that is the shape the scripts were written against.
861            "-dumpversion" => query = Some(Query::Version),
862            "-dumpfullversion" => query = Some(Query::FullVersion),
863            "-print-multiarch" => query = Some(Query::Multiarch),
864            "-print-search-dirs" => query = Some(Query::SearchDirs),
865            "-print-sysroot" => query = Some(Query::Sysroot),
866            // Both spellings, because this one is ours rather than GCC's and our own documents
867            // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
868            // two dashes like the other flags we invented, and document 12's table gives it one
869            // like the `-print-` family it sits in. A person who reads either and types what it
870            // says is right, so neither is refused.
871            "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
872                query = Some(Query::SysrootProvenance);
873            }
874            "-print-sysroot-digest" | "--print-sysroot-digest" => {
875                query = Some(Query::SysrootDigest);
876            }
877            "-print-libgcc-file-name" => query = Some(Query::Libgcc),
878            _ if arg.starts_with("-print-file-name=") => {
879                query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
880            }
881            _ if arg.starts_with("-print-prog-name=") => {
882                query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
883            }
884            // A program built to run in more than one thread. On every platform this compiler
885            // targets that is a macro the library's headers read and one more library on the
886            // link line, and the library is added after the loop so that it lands after the
887            // objects that refer to it.
888            "-pthread" | "-pthreads" => {
889                opts.defines.push("_REENTRANT".to_owned());
890                threads = true;
891            }
892            "-ansi" => {
893                opts.std = Std::C89;
894                opts.gnu_extensions = false;
895            }
896            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
897            // the spelling a build system that groups its warning flags tends to write.
898            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
899            // Both directions, because a build that needs this for one directory turns it back
900            // off for the next one rather than leaving it on for the whole tree.
901            "-fpermissive" => opts.permissive = true,
902            "-fno-permissive" => opts.permissive = false,
903            "-ffreestanding" => opts.hosted = false,
904            "-fhosted" => opts.hosted = true,
905            "-fno-builtin" => opts.builtins = false,
906            "-fbuiltin" => opts.builtins = true,
907            // The C89 dialects are under GNU's reading whatever this says, so turning it off
908            // there is turning off something the dialect asked for, which is accepted and does
909            // nothing. gcc refuses that command line, and there is nothing it could have meant.
910            "-fgnu89-inline" => opts.gnu89_inline = true,
911            "-fno-gnu89-inline" => opts.gnu89_inline = false,
912            // Both directions of each, because a build system that wants one of these usually
913            // writes it beside the flag that turns it back off for one directory.
914            "-fno-omit-frame-pointer" => opts.frame_pointer = Some(true),
915            "-fomit-frame-pointer" => opts.frame_pointer = Some(false),
916            // Both directions again, for the same reason, and a third answer for a command line
917            // that wrote neither: see `reorder_blocks` in `rucc_session`.
918            "-freorder-blocks" => opts.reorder_blocks = Some(true),
919            "-fno-reorder-blocks" => opts.reorder_blocks = Some(false),
920            // gcc's name for the scheduler that runs after the registers are handed out, which is
921            // the only one rucc has: see `schedule_insns` in `rucc_session`. gcc also takes
922            // `-fschedule-insns` for the pass before allocation, and taking that one here would be
923            // a flag that says a pass ran when none did.
924            "-fschedule-insns2" => opts.schedule_insns = Some(true),
925            "-fno-schedule-insns2" => opts.schedule_insns = Some(false),
926            // A call in tail position as a jump: see `sibling_calls` in `rucc_session`.
927            "-foptimize-sibling-calls" => opts.sibling_calls = Some(true),
928            "-fno-optimize-sibling-calls" => opts.sibling_calls = Some(false),
929            "-mno-red-zone" => opts.red_zone = false,
930            "-mred-zone" => opts.red_zone = true,
931            // Four flags rather than one with an argument, which is how gcc spells them and how
932            // every build line writes them. Last one wins, because a package build puts
933            // `-fstack-protector-strong` in its global flags and a directory that cannot have one
934            // turns it back off on the line after.
935            "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
936                opts.protector = Protector::None;
937            }
938            "-fstack-protector" => opts.protector = Protector::Buffers,
939            "-fstack-protector-strong" => opts.protector = Protector::Strong,
940            "-fstack-protector-all" => opts.protector = Protector::All,
941            // The other half of what a hardened build asks for, and it is a question about the
942            // frame rather than about the function, so it is a switch rather than a level.
943            "-fstack-clash-protection" => opts.stack_clash = true,
944            "-fno-stack-clash-protection" => opts.stack_clash = false,
945            // The third of them, and the one that is a question with an argument rather than a
946            // family of spellings, because what it asks about is which of the two edges of a
947            // control flow transfer is checked. Bare is both of them, which is what gcc does.
948            "-fcf-protection" => opts.control = Control::Full,
949            "-fno-cf-protection" => opts.control = Control::None,
950            // Two spellings of the same request, which is what gcc has as well. `-p` was the older
951            // profiler and `-pg` the one that also recorded who called whom, and on every platform
952            // this compiler targets there is now one hook and both ask for it.
953            "-pg" | "-p" => {
954                opts.profile = true;
955                link.profile = true;
956            }
957            // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
958            // say where the call goes and a command line that asked for no call has nowhere to put
959            // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
960            // directory is a build system that would otherwise fail on every other directory.
961            "-mfentry" => opts.hook = Hook::Early,
962            "-mno-fentry" => opts.hook = Hook::Late,
963            // GCC drops its own include directory along with the system ones, because its
964            // headers are half of a pair with the library's and half a pair is worse than
965            // none. A build that passes this is supplying the whole set itself.
966            "-nostdinc" => nostdinc = true,
967            "-o" => {
968                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
969                i += 1;
970            }
971            // What the files kept beside an output are named after, which is `-save-temps` and
972            // `-fstack-usage` so far. gcc takes each of the three in the separated form only, and
973            // its driver passes them to every compilation it runs, so a build that copied a
974            // command line out of gcc's `-v` has them. See `phase::aux_base` for what they do.
975            "-dumpbase" | "-dumpbase-ext" | "-dumpdir" => {
976                let value =
977                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?.clone();
978                i += 1;
979                match arg {
980                    "-dumpbase" => opts.dump_base = Some(value),
981                    "-dumpbase-ext" => opts.dump_base_ext = Some(value),
982                    _ => opts.dump_dir = Some(value),
983                }
984            }
985            // The flags that take a directory only in the separated form. GCC spells them
986            // this way and nothing writes `-iquotedir`, so accepting the joined form would
987            // mean guessing at a path that starts with the flag's own letters.
988            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
989            // two mean the same thing here: the configured directories are under there rather
990            // than under the root.
991            "-isysroot" => {
992                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
993                i += 1;
994                sysroot = Some(PathBuf::from(dir));
995            }
996            "-iquote" | "-isystem" | "-idirafter" => {
997                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
998                i += 1;
999                match arg {
1000                    "-iquote" => opts.search.push_quote(dir.clone()),
1001                    "-isystem" => opts.search.push_system(dir.clone()),
1002                    _ => opts.search.push_after(dir.clone()),
1003                }
1004            }
1005            "-iprefix" => {
1006                iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
1007                i += 1;
1008            }
1009            // Where GCC puts these is not where its manual says it puts them, and this is the
1010            // measured answer rather than the documented one: `-iwithprefix` lands in the
1011            // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
1012            // the `-I` slot. A cross build that uses them is relying on the behaviour, since
1013            // that is the compiler it was developed against.
1014            "-iwithprefix" | "-iwithprefixbefore" => {
1015                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1016                i += 1;
1017                let dir = format!("{iprefix}{dir}");
1018                if arg == "-iwithprefix" {
1019                    opts.search.push_system(dir);
1020                } else {
1021                    opts.search.push_bracket(dir);
1022                }
1023            }
1024            "-include" | "-imacros" => {
1025                let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1026                i += 1;
1027                opts.preincludes
1028                    .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
1029            }
1030            // The flag `-iquote` was introduced to replace, still passed by build systems old
1031            // enough to predate the replacement. It is not a directory: it says that every `-I`
1032            // so far is for quoted includes only, and that a quoted include stops looking next
1033            // to the file that wrote it.
1034            "-I-" => opts.search.split_quote_chain(),
1035            // `-x c` and `-xc`, both of which gcc takes. busybox and toybox probe the compiler
1036            // with the joined one.
1037            _ if arg.starts_with("-x") => {
1038                let lang = joined_or_next(arg, 2, args, &mut i)?;
1039                forced = if lang == "none" {
1040                    None
1041                } else {
1042                    Some(InputKind::from_x_arg(&lang).map_err(|e| err(format!("{e}")))?)
1043                };
1044            }
1045            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
1046            // translation units in one process rather than making the build system fork, and
1047            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
1048            // to exist and has to be spelled the way `make` spells it.
1049            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
1050            // and a build system may produce either, so both are read here rather than
1051            // being normalised by whatever generated the command line.
1052            _ if arg.starts_with("-D") => {
1053                let value = joined_or_next(arg, 2, args, &mut i)?;
1054                opts.defines.push(value);
1055            }
1056            _ if arg.starts_with("-U") => {
1057                let value = joined_or_next(arg, 2, args, &mut i)?;
1058                opts.undefines.push(value);
1059            }
1060            _ if arg.starts_with("-I") => {
1061                let dir = joined_or_next(arg, 2, args, &mut i)?;
1062                opts.search.push_bracket(dir);
1063            }
1064            _ if arg.starts_with("-std=") => {
1065                let name = &arg["-std=".len()..];
1066                let (std, gnu) = Std::from_flag(name)
1067                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
1068                opts.std = std;
1069                opts.gnu_extensions = gnu;
1070            }
1071            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
1072            // handed, so a differential run that does not set it is comparing two compilers
1073            // that believe they are different compilers.
1074            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
1075            // that we have not written yet are accepted and ignored, because a dump is a
1076            // debugging aid and a build that asks for one should still compile. A letter
1077            // outside the family falls through to the unknown option error, which is what
1078            // keeps `-dumpversion` from being read as a dump of nothing.
1079            _ if Dumps::is_family(arg) => {
1080                opts.dumps.add(&arg[2..]);
1081            }
1082            // One name at a time, which is what a build that means its own `memcpy` and the
1083            // library's everything else writes. The name is not checked against a list, because
1084            // the flag is about what the program means by a name and a program is allowed to mean
1085            // something by a name this compiler has never heard of.
1086            _ if arg.starts_with("-fno-builtin-") => {
1087                opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
1088            }
1089            _ if arg.starts_with("-fgnuc-version=") => {
1090                let v = &arg["-fgnuc-version=".len()..];
1091                opts.gnuc = v.parse().map_err(err)?;
1092            }
1093            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
1094            // than the unknown option one, because a build reaching for it is asking for a feature
1095            // and deserves to be told it is not coming rather than told the spelling is wrong.
1096            // The negative form is what this compiler does anyway, so it is taken and dropped.
1097            "-fnested-functions" => {
1098                return Err(err(
1099                    "nested functions are not supported: a call to one goes through a trampoline \
1100                     written on the stack, which no target that enforces an unexecutable stack \
1101                     allows",
1102                ));
1103            }
1104            "-fno-nested-functions" => {}
1105            // Which of the two links the output is for, which is a real difference and not a
1106            // description of what happens anyway. Everything here is position independent either
1107            // way, and what these decide is whether a name may be one another object defines or
1108            // replaces, because a link that produces an executable puts every name in the same
1109            // program and a link that produces a shared library does not.
1110            //
1111            // It matters that they are accepted at all, whatever they then do. Every autoconf and
1112            // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
1113            // be the `CC` of a project that has a configure script, whatever else it can do. That
1114            // is how this was found: building SQLite's test fixture stopped on it.
1115            "-fPIC" | "-fpic" => opts.pic = Pic::Library,
1116            // Not a synonym of the pair above, which is what they were treated as until #756. The
1117            // library is the expensive answer and gcc makes it the one that has to be asked for,
1118            // so this is also what nothing at all means.
1119            "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
1120            // A different question from the pair above, and the one every distribution build of a
1121            // shared library answers. `-fPIC` decides how an address is reached, and this decides
1122            // whether the optimizer may believe a body it can see, because an exported name is one
1123            // the dynamic linker may find another definition of first. On by default, which is
1124            // gcc's arrangement and is the honest answer, and off is a promise the build makes and
1125            // nothing checks.
1126            "-fsemantic-interposition" => opts.interposition = true,
1127            "-fno-semantic-interposition" => opts.interposition = false,
1128            // Two requests rather than one, and the same table answers both, so what decides is
1129            // whether either of them is standing. gcc arranges it the same way: the asynchronous
1130            // one is the default here and it implies the other, and a line that asks for a table
1131            // and against an asynchronous one gets a table.
1132            "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
1133            "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
1134            "-funwind-tables" => opts.unwind_tables = true,
1135            "-fno-unwind-tables" => opts.unwind_tables = false,
1136            // The other direction is a request, not a description, and it is one this compiler
1137            // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
1138            // option error. Answering it by carrying on would be answering a different question:
1139            // the code would still be position independent, which is correct everywhere an
1140            // ordinary program runs and is wrong in a kernel, where the flag is written precisely
1141            // because there is no loader to fill a global offset table in.
1142            "-fno-pic" | "-fno-pie" => {
1143                return Err(err(
1144                    "position dependent code is not supported: an address that may be in another \
1145                     object is loaded out of the global offset table, and nothing here emits the \
1146                     absolute form this asks for. Use -no-pie if what you meant was how to link",
1147                ));
1148            }
1149            // A section per function and a section per variable, which is what makes
1150            // `--gc-sections` able to drop anything: a linker can leave out a section nothing
1151            // reaches and cannot leave out half of one. Both directions are taken, and the off
1152            // one is the default rather than a refusal, since a build that writes it is asking
1153            // for what happens anyway.
1154            "-ffunction-sections" => opts.function_sections = true,
1155            "-fno-function-sections" => opts.function_sections = false,
1156            "-fdata-sections" => opts.data_sections = true,
1157            "-fno-data-sections" => opts.data_sections = false,
1158            // Another description of what this compiler does. A file scope declaration with no
1159            // initializer is written into `.bss` as an ordinary defined symbol, not offered to the
1160            // linker as a common one for it to merge, which is what `-fno-common` asks for and what
1161            // gcc has done by default since 10. Nothing in the front end produces `Linkage::Common`
1162            // at all.
1163            "-fno-common" => {}
1164            // What overflows rather than being undefined. Every one of these takes something away
1165            // from the optimizer rather than asking it to do anything, which is why the negative
1166            // spellings are the interesting ones and the positive spellings are the default.
1167            //
1168            // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
1169            // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
1170            // written here as the pair rather than kept as a third thing to test everywhere.
1171            //
1172            // `-ftrapv` is the exception and is the one that asks for something. It is the other
1173            // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
1174            // the other, which makes the last one on the command line the one that counts. That is
1175            // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
1176            // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
1177            // question is left alone by both, because neither has anything to say about it.
1178            "-fwrapv" => {
1179                opts.wrapping.signed = true;
1180                opts.wrapping.trap = false;
1181            }
1182            "-fno-wrapv" => opts.wrapping.signed = false,
1183            "-fwrapv-pointer" => opts.wrapping.pointer = true,
1184            "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
1185            "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
1186            // Which does not clear the checked one, because gcc does not: `-ftrapv
1187            // -fstrict-overflow` still emits the calls. It says what is assumed and not what
1188            // happens.
1189            "-fstrict-overflow" => {
1190                opts.wrapping.signed = false;
1191                opts.wrapping.pointer = false;
1192            }
1193            "-ftrapv" => {
1194                opts.wrapping.trap = true;
1195                opts.wrapping.signed = false;
1196            }
1197            "-fno-trapv" => opts.wrapping.trap = false,
1198            // The two flags that say what a plain `char` is, which is one question with two
1199            // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
1200            // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
1201            // answers and the last one written wins. Nothing is set until one of them is given,
1202            // because the target's own ABI is the answer otherwise and it is not the same answer
1203            // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
1204            "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
1205            "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
1206            // And the size of an enumeration, which is the other thing in this group that changes
1207            // the ABI rather than the code.
1208            "-fshort-enums" => opts.short_enums = true,
1209            "-fno-short-enums" => opts.short_enums = false,
1210            // And Microsoft's reading of an anonymous member, which changes the layout of every
1211            // record that writes a tag on one. Nothing is set until one of them is given, because
1212            // the target is the answer otherwise: gcc's mingw build has this on and its Linux
1213            // build has it off.
1214            "-fms-extensions" => opts.ms_extensions = Some(true),
1215            "-fno-ms-extensions" => opts.ms_extensions = Some(false),
1216            // And the request, which is the one that cannot be granted. It is a real difference and
1217            // not a preference: two files each writing `int g;` link under `-fcommon` and are a
1218            // duplicate definition without it, which is the whole reason the flag survives.
1219            "-fcommon" => {
1220                return Err(err(
1221                    "a tentative definition is written into .bss as its own symbol here, and \
1222                     nothing emits the common symbol this asks the linker to merge. Give the \
1223                     variable a definition in one file and declare it extern in the others",
1224                ));
1225            }
1226            // Both directions of this one are recorded, and what they decide is whether lowering
1227            // names the type each access goes through. Turning it off is the front end leaving the
1228            // name off rather than a pass being told to ignore one it can see, which is one
1229            // condition in one place, and it is the reading that survives link time optimization:
1230            // a unit built with the flag off keeps its own answer when its bodies end up in a
1231            // module beside bodies that were not.
1232            //
1233            // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
1234            // and is tested, and no pass at any level asks the alias analysis anything today, so
1235            // no program compiles differently for having passed this. The flag is wired anyway,
1236            // because the change that makes a pass ask is not the change anybody will remember to
1237            // wire it in, and a flag that is taken and dropped once the names mean something is
1238            // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
1239            // words.
1240            "-fstrict-aliasing" => opts.strict_aliasing = true,
1241            "-fno-strict-aliasing" => opts.strict_aliasing = false,
1242            // The same shape of answer for the same reason, and the flag the kernel writes beside
1243            // the one above it.
1244            //
1245            // Nothing here concludes that a pointer is not null from the fact that it was
1246            // dereferenced. There is no such conclusion to draw from, because no pass records one:
1247            // a load says where it read and nothing else, and a comparison against null is an
1248            // ordinary comparison of two values the optimizer has no fact about. So a function
1249            // that reads through a pointer and then tests it keeps the test, which is what the
1250            // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
1251            // to be asked for because it draws the conclusion by default.
1252            //
1253            // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
1254            // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
1255            // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
1256            "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
1257            // The floating point group, which goes the same way and for the same reason, and which
1258            // is worth writing out because the reason is easy to get backwards.
1259            //
1260            // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
1261            // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
1262            // changed and that an exception raised by an operation may be looked at, so an
1263            // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
1264            // whose exception the program does not get. Nothing here folds any floating point
1265            // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
1266            // that runs, at every level. So both of those describe what already happens.
1267            //
1268            // The permissive ones are the other half, and they are licences rather than requests
1269            // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
1270            // `-fno-trapping-math` says nothing looks at the exceptions, which together are
1271            // permission to fold. Not folding is the conservative side of that permission and is
1272            // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
1273            // speed and not correctness, which is the test section 4.1 puts a licence through.
1274            "-frounding-math" | "-fno-rounding-math" => {}
1275            // `-fno-trapping-math` is the one of the four that is kept, because there is one
1276            // conversion this compiler does not fold and gcc folds under it, and the two answers
1277            // differ. Converting a constant floating value to an integer type it does not fit in
1278            // is undefined behaviour rather than a value: left to the hardware it is one
1279            // instruction and the answer is the integer indefinite value, and folded it is the
1280            // nearest end of the integer's range. Both compilers leave it to the instruction by
1281            // default and gcc folds it under this flag, so a program built with it and compiled
1282            // without it gets a different number rather than a slower one. `-ftrapping-math` is
1283            // gcc's default, so a build spelling it out is asking for what it already has.
1284            //
1285            // The rest of the family goes with it, `-ffast-math` included, and all of them are
1286            // taken now. Each is a licence rather than a request and nothing here folds floating
1287            // point arithmetic, so the code does not change. What does change is the macros gcc
1288            // defines for each licence, which a header reads, and the startup file `-ffast-math`
1289            // links, which puts the hardware in flush to zero mode. Both are done after the loop,
1290            // because the family is a set of switches over the same fields and the last word on
1291            // each of them is the end of the command line.
1292            "-ftrapping-math"
1293            | "-fno-trapping-math"
1294            | "-ffast-math"
1295            | "-fno-fast-math"
1296            | "-funsafe-math-optimizations"
1297            | "-fno-unsafe-math-optimizations"
1298            | "-fmath-errno"
1299            | "-fno-math-errno"
1300            | "-ffinite-math-only"
1301            | "-fno-finite-math-only"
1302            | "-fsigned-zeros"
1303            | "-fno-signed-zeros"
1304            | "-freciprocal-math"
1305            | "-fno-reciprocal-math"
1306            | "-fassociative-math"
1307            | "-fno-associative-math" => math_flags.push(arg),
1308            // Whether the startup file that sets flush to zero is linked, asked directly. gcc
1309            // links it for a shared object too when this is written, which the family does not.
1310            "-mdaz-ftz" => daz_ftz = Some(true),
1311            "-mno-daz-ftz" => daz_ftz = Some(false),
1312            // About temporary files rather than about code. There is nothing between the phases of
1313            // one compilation here to write to a file in the first place.
1314            "-pipe" => {}
1315            // Preprocess the input, which a C compile always does. GCC has it for Fortran, and
1316            // meson writes it when it asks a compiler for its predefined macros.
1317            "-cpp" => {}
1318            // Nothing here writes colour, so all of these are the same answer, and it is the answer
1319            // that costs nothing: the diagnostics come out plain either way and no build depends on
1320            // an escape sequence being there. Taken rather than refused because cmake writes
1321            // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
1322            // makes this the second most common flag after `-fPIC` to stop a build over a question
1323            // about how the text looks.
1324            "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
1325            _ if arg.starts_with("-fdiagnostics-color=") => {}
1326            // The link flags. None of them changes the compilation, which is why they are
1327            // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
1328            // error: it is a thing said to a linker that is not going to run.
1329            "-static" => link.is_static = true,
1330            "-shared" => link.shared = true,
1331            "-r" => link.relocatable = true,
1332            "-pie" => link.pie = Some(true),
1333            "-no-pie" | "-nopie" => link.pie = Some(false),
1334            "-nostdlib" => link.no_stdlib = true,
1335            "-nostartfiles" => link.no_startfiles = true,
1336            "-nodefaultlibs" => link.no_defaultlibs = true,
1337            "-fno-builtins-lib" => link.no_builtins_lib = true,
1338            "-fbuiltins-lib" => link.no_builtins_lib = false,
1339            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
1340            "-s" => link.strip = true,
1341            // Into the ordered input list rather than a list of its own, because a great many of
1342            // the linker's options are a bracket around the files after them and an option that
1343            // lost its place among them says nothing. `--whole-archive` is the one that found this.
1344            "-Xlinker" => {
1345                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
1346                i += 1;
1347                inputs.push(Input::linker(next));
1348            }
1349            _ if arg.starts_with("-Wl,") => {
1350                // Commas separate arguments rather than being part of one, which is what makes
1351                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
1352                inputs.extend(arg["-Wl,".len()..].split(',').map(Input::linker));
1353            }
1354            _ if arg.starts_with("-fuse-ld=") => {
1355                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
1356            }
1357            _ if arg.starts_with("-l") && arg.len() > 2 => {
1358                inputs.push(Input::library(&arg[2..]));
1359            }
1360            "-l" => {
1361                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
1362                i += 1;
1363                inputs.push(Input::library(next));
1364            }
1365            _ if arg.starts_with("-L") => {
1366                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1367            }
1368            _ if arg.starts_with("-B") => {
1369                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1370            }
1371            _ if arg.starts_with("-j") => {
1372                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
1373            }
1374            _ if arg.starts_with("--sysroot=") => {
1375                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
1376            }
1377            _ if arg.starts_with("--target=") => {
1378                let t = &arg["--target=".len()..];
1379                // The same string again, as the model that has room for a libc version. A spelling
1380                // the three field parser took and this one does not is not an error, because the
1381                // one that decides what is compiled has already accepted it and the only thing
1382                // lost is a version nobody asked for.
1383                pinned = t.parse().ok();
1384                // The other way round is a deployment target the three field parser has no room
1385                // for, `aarch64-macos.13`, and the triple is the one the tuple narrows to.
1386                opts.target = match t.parse() {
1387                    Ok(triple) => triple,
1388                    Err(e) => {
1389                        pinned.and_then(Triple::from_tuple).ok_or_else(|| err(format!("{e}")))?
1390                    }
1391                };
1392            }
1393            _ if arg.starts_with("--emit=") => {
1394                let k = &arg["--emit=".len()..];
1395                opts.emit = k
1396                    .parse()
1397                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
1398            }
1399            // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
1400            // to write. `-Og` is GCC's level for a build somebody is going to step through, and
1401            // it is `-O1` with the transformations that move code around left out; this compiler
1402            // has no such level yet, so it is the nearest one and `--print-pipeline` says what
1403            // that came to rather than the flag pretending otherwise.
1404            "-O" | "-Og" => {
1405                opts.opt_level = rucc_session::OptLevel::O1;
1406                ofast = false;
1407            }
1408            // The union of `-O3` and `-ffast-math`. The second half is a default rather than a
1409            // flag, which is why it is remembered here and applied after the loop: a later level
1410            // takes it back, and so does a `-fno-fast-math` written on either side of it.
1411            "-Ofast" => {
1412                opts.opt_level = rucc_session::OptLevel::O3;
1413                ofast = true;
1414            }
1415            _ if arg.starts_with("-O") => {
1416                ofast = false;
1417                opts.opt_level = arg[2..]
1418                    .parse()
1419                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
1420            }
1421            // How far a multiply and an addition may be fused into one rounding. Before the
1422            // optimizer's `-f` family below for the reason the ones under it are, and kept rather
1423            // than dropped because it is the one flag in its group this compiler could act on: it
1424            // rides into the IR as an attribute on each function with a body, so the day the code
1425            // generator forms an `fma` it already knows which functions were given permission.
1426            // Nothing forms one today, under any value of this and under any `-march=`.
1427            _ if arg.starts_with("-ffp-contract=") => {
1428                let how = &arg["-ffp-contract=".len()..];
1429                opts.fp_contract = how.parse().map_err(|()| {
1430                    err(format!("`{how}` is not a contraction, which is fast, on or off"))
1431                })?;
1432            }
1433            // How much of an expression may be computed wider than it was written. The values are
1434            // gcc's and so is the refusal of anything else, and none of the three changes anything
1435            // here: an operation is computed in the type C says it is on every target this compiler
1436            // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
1437            // happens. `fast` and `16` are permission to be wider, which is a licence this takes
1438            // and does not use, the same way the two above are. The flag is worth taking because
1439            // glibc's headers and a good deal of configure output write it, and because the answer
1440            // it asks about is one this compiler can state rather than guess at: there is no x87
1441            // target here, which is the machine the whole question was invented for.
1442            // Whether a local and a spilled value that are never both wanted may be the same bytes
1443            // of the frame. gcc's three values, and two of them mean the same thing here: what rucc
1444            // shares is a local whose address provably never leaves the function, which is narrower
1445            // than `named_vars` and narrower still than `all`, so both of them get it. `none` is
1446            // the one that changes anything, and it is the flag a program that reads a local
1447            // through a pointer it kept past the end of the block writes.
1448            _ if arg.starts_with("-fstack-reuse=") => {
1449                let how = &arg["-fstack-reuse=".len()..];
1450                opts.stack_reuse = match how {
1451                    "all" | "named_vars" => Some(true),
1452                    "none" => Some(false),
1453                    _ => {
1454                        return Err(err(format!(
1455                            "`{how}` is not a stack reuse, which is all, named_vars or none"
1456                        )));
1457                    }
1458                };
1459            }
1460            _ if arg.starts_with("-fexcess-precision=") => {
1461                let how = &arg["-fexcess-precision=".len()..];
1462                if !matches!(how, "16" | "fast" | "standard") {
1463                    return Err(err(format!(
1464                        "`{how}` is not an excess precision, which is 16, fast or standard"
1465                    )));
1466                }
1467            }
1468            // Which front of a path is rewritten before it reaches the output, which is how a
1469            // build gets the same bytes out of two different directories. The four spellings are
1470            // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
1471            // once. Only the macro list does anything today, because `__FILE__` is the only place
1472            // a path reaches the output: there is no DWARF and no profile data yet, so the other
1473            // two are recorded for the work that will read them. The argument splits at the last
1474            // `=` rather than the first, which is gcc's rule and is what lets a directory with an
1475            // `=` in its name be the old half.
1476            _ if arg.starts_with("-fmacro-prefix-map=") => {
1477                let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1478                opts.prefix_map.macros.push(old, new);
1479            }
1480            _ if arg.starts_with("-fdebug-prefix-map=") => {
1481                let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1482                opts.prefix_map.debug.push(old, new);
1483            }
1484            _ if arg.starts_with("-fprofile-prefix-map=") => {
1485                let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1486                opts.prefix_map.profile.push(old, new);
1487            }
1488            _ if arg.starts_with("-ffile-prefix-map=") => {
1489                let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1490                opts.prefix_map.macros.push(old, new);
1491                opts.prefix_map.debug.push(old, new);
1492                opts.prefix_map.profile.push(old, new);
1493            }
1494            // A whole optimization rather than a flag, and the family is taken rather than
1495            // refused because of what ignoring it does. There is none of it here yet, so a build
1496            // that asks for it gets a program that is correct and slower than it could have been,
1497            // which is what section 4.1 means by a hint about speed and what every compilation at
1498            // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1499            // holds the bytecode and no machine code at all, and every object here holds the code,
1500            // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1501            // to this compiler gets objects that are more usable than the ones it asked for rather
1502            // than different ones. Every value is still checked against gcc's, because somebody
1503            // who wrote `-flto=thin` meant clang and had better hear about it here.
1504            "-flto" => opts.lto.requested = true,
1505            "-fno-lto" => opts.lto.requested = false,
1506            _ if arg.starts_with("-flto=") => {
1507                let how = &arg["-flto=".len()..];
1508                opts.lto.jobs = how.parse().map_err(|()| {
1509                    err(format!(
1510                        "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1511                         count above zero"
1512                    ))
1513                })?;
1514                opts.lto.requested = true;
1515            }
1516            _ if arg.starts_with("-flto-partition=") => {
1517                let how = &arg["-flto-partition=".len()..];
1518                opts.lto.partition = how.parse().map_err(|()| {
1519                    err(format!(
1520                        "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1521                         or none"
1522                    ))
1523                })?;
1524            }
1525            _ if arg.starts_with("-flto-compression-level=") => {
1526                let how = &arg["-flto-compression-level=".len()..];
1527                let level =
1528                    how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1529                        err(format!("`{how}` is not a compression level, 0 to 19"))
1530                    })?;
1531                opts.lto.compression = Some(level);
1532            }
1533            // Whether the object keeps its machine code as well as the bytecode. It always does
1534            // here, so the first of these describes what happens and the second asks for an object
1535            // with less in it, which is a smaller file and not a different program, so both are
1536            // taken.
1537            "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1538            // Whether the linker is handed a plugin that does the link time work. The design in
1539            // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1540            // plugin into anybody, so neither answer is a question it has to hold.
1541            "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1542            // Reading a profile back. Taken for the reason the family above it is: nothing here
1543            // reads one, so a build that asks gets the program it would have got anyway, and gcc
1544            // itself produces a byte for byte identical object from `-fprofile-use` when there are
1545            // no counts beside the file. The path is recorded for the pass that will read it. The
1546            // warning gcc prints when it looked and found nothing is deliberately not copied,
1547            // because nothing here looks, and a warning about a file that was never opened would
1548            // fire on the builds that have a perfectly good profile as well as on the ones that
1549            // do not.
1550            "-fprofile-use" => opts.profile_data.requested = true,
1551            "-fno-profile-use" => opts.profile_data.requested = false,
1552            _ if arg.starts_with("-fprofile-use=") => {
1553                opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1554                opts.profile_data.requested = true;
1555            }
1556            _ if arg.starts_with("-fprofile-dir=") => {
1557                opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1558            }
1559            "-fprofile-abs-path" => opts.profile_data.absolute = true,
1560            "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1561            "-fprofile-correction" => opts.profile_data.correction = true,
1562            "-fno-profile-correction" => opts.profile_data.correction = false,
1563            "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1564            "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1565            // Writing the counts rather than reading them, which is refused rather than taken and
1566            // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1567            // file a build declared as an output never appears: the instrumented program writes a
1568            // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1569            // two stage build that got neither would go on to optimize against no counts at all
1570            // and report coverage of nothing, with nothing along the way saying so. The objects
1571            // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1572            // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1573            // this is a flag that changes the output rather than a hint about speed.
1574            "-fprofile-arcs"
1575            | "--coverage"
1576            | "-fcondition-coverage"
1577            | "-fpath-coverage"
1578            | "-fprofile-generate" => {
1579                return Err(err(format!(
1580                    "{arg}: this compiler does not instrument for profiling, and a build that \
1581                     expects the counts a run of the instrumented program writes would optimize \
1582                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1583                )));
1584            }
1585            _ if arg.starts_with("-fprofile-generate=") => {
1586                return Err(err(format!(
1587                    "{arg}: this compiler does not instrument for profiling, and a build that \
1588                     expects the counts a run of the instrumented program writes would optimize \
1589                     against nothing on its second pass, see spec/04-driver-and-cli.md"
1590                )));
1591            }
1592            "-ftest-coverage" => {
1593                return Err(err(format!(
1594                    "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1595                     that expects one would wait for a file that never arrives, see \
1596                     spec/04-driver-and-cli.md"
1597                )));
1598            }
1599            // The rest of the family describes instrumentation that is refused above, so what is
1600            // left to do with them is check them and drop them. They are checked because a
1601            // misspelling in a distribution's flags is worth finding here rather than on the day
1602            // the instrumentation lands, and dropped because there is nothing for an answer about
1603            // how a counter is written to be an answer about.
1604            _ if arg.starts_with("-fprofile-update=") => {
1605                let how = &arg["-fprofile-update=".len()..];
1606                if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1607                    return Err(err(format!(
1608                        "`{how}` is not a profile update method, which is single, atomic or \
1609                         prefer-atomic"
1610                    )));
1611                }
1612            }
1613            _ if arg.starts_with("-fprofile-reproducible=") => {
1614                let how = &arg["-fprofile-reproducible=".len()..];
1615                if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1616                    return Err(err(format!(
1617                        "`{how}` is not a profile reproducibility method, which is serial, \
1618                         parallel-runs or multithreaded"
1619                    )));
1620                }
1621            }
1622            "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1623            "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1624            _ if arg.starts_with("-fprofile-filter-files=")
1625                || arg.starts_with("-fprofile-exclude-files=")
1626                || arg.starts_with("-fprofile-note=") => {}
1627            // What every name gets when nothing in the source said, which the attribute in the
1628            // source overrides rather than the other way round. Before the optimizer's `-f`
1629            // family below for the reason the tier below it is.
1630            _ if arg.starts_with("-fvisibility=") => {
1631                let seen = &arg["-fvisibility=".len()..];
1632                opts.visibility = seen.parse().map_err(|()| {
1633                    err(format!(
1634                        "`{seen}` is not a visibility, which is default, hidden, internal or \
1635                         protected"
1636                    ))
1637                })?;
1638            }
1639            // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1640            // family below for the reason the two above it are, and last of the three so that the
1641            // bare spelling and the negative one are matched exactly rather than by this.
1642            _ if arg.starts_with("-fcf-protection=") => {
1643                let edges = &arg["-fcf-protection=".len()..];
1644                opts.control = edges.parse().map_err(|()| {
1645                    err(format!(
1646                        "`{edges}` is not a control flow protection, which is full, branch, \
1647                         return, none or check"
1648                    ))
1649                })?;
1650            }
1651            // How much room every function opens with for something to be written over later.
1652            // Before the optimizer's `-f` family below for the reason the ones above it are.
1653            _ if arg.starts_with("-fpatchable-function-entry=") => {
1654                let room = &arg["-fpatchable-function-entry=".len()..];
1655                opts.patchable = room.parse().map_err(|()| {
1656                    err(format!(
1657                        "`{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"
1658                    ))
1659                })?;
1660            }
1661            // The memory safety monitor, from section 15.4 of
1662            // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1663            // because a pass that took the name `safety=detect` would otherwise be handed the
1664            // flag, and the tier is not a pass.
1665            _ if arg.starts_with("-fsafety=") => {
1666                let tier = &arg["-fsafety=".len()..];
1667                opts.safety = tier.parse().map_err(|()| {
1668                    err(format!(
1669                        "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1670                    ))
1671                })?;
1672            }
1673            // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1674            // than folded into the tier because it is a departure somebody who has read that
1675            // section makes, and the two defaults it describes are a property of what is being
1676            // built rather than of how much checking is wanted.
1677            _ if arg.starts_with("-fsafety-init=") => {
1678                let mode = &arg["-fsafety-init=".len()..];
1679                opts.padding = mode.parse().map_err(|()| {
1680                    err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1681                })?;
1682            }
1683            // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1684            // strict form of that section needs a member id the front end does not name yet and
1685            // accepting the spelling for it would be accepting a promise this build cannot keep.
1686            // Before `-fno-` is looked at below, for the reason the tier is.
1687            "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1688            "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1689            _ if arg.starts_with("-fsafety-subobject=") => {
1690                let form = &arg["-fsafety-subobject=".len()..];
1691                return Err(err(format!(
1692                    "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1693                     the strict form of section 9.4 is tamnd/rucc#967"
1694                )));
1695            }
1696            // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1697            // the one above has none: there is one form of this check and a spelling that suggested
1698            // otherwise would be promising something. Before `-fno-` is looked at below, the same
1699            // way.
1700            "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1701            "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1702            _ if arg.starts_with("-fsafety-restrict=") => {
1703                let form = &arg["-fsafety-restrict=".len()..];
1704                return Err(err(format!(
1705                    "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1706                )));
1707            }
1708            // Section 9.5's races, which take a value because the section gives them three modes
1709            // and the difference between two of them is which classes get reported rather than how
1710            // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1711            // reason the two above spell theirs out.
1712            _ if arg.starts_with("-fsafety-races=") => {
1713                let mode = &arg["-fsafety-races=".len()..];
1714                opts.races = mode.parse().map_err(|()| {
1715                    err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1716                })?;
1717            }
1718            "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1719            // The sanitizers of document 12, which are checks at run time rather than a way of
1720            // generating the same program. Each name is held to gcc 16's list, and what is still
1721            // asked for by the end of the line is answered after the loop, so that a command line
1722            // which turns one on and then off again is a command line that asked for nothing.
1723            //
1724            // Before the optimizer's `-f` family below, for the reason the tier above it is.
1725            _ if arg.starts_with("-fsanitize=") => {
1726                for one in arg["-fsanitize=".len()..].split(',') {
1727                    if one == "all" {
1728                        // gcc takes `all` only in the negative, because turning every check on at
1729                        // once includes checks that contradict each other.
1730                        return Err(err(
1731                            "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1732                        ));
1733                    }
1734                    if !SANITIZERS.contains(&one) {
1735                        return Err(err(format!(
1736                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1737                        )));
1738                    }
1739                    if !sanitizers.contains(&one) {
1740                        sanitizers.push(one);
1741                    }
1742                }
1743            }
1744            _ if arg.starts_with("-fno-sanitize=") => {
1745                for one in arg["-fno-sanitize=".len()..].split(',') {
1746                    if one == "all" {
1747                        sanitizers.clear();
1748                        continue;
1749                    }
1750                    if !SANITIZERS.contains(&one) {
1751                        return Err(err(format!(
1752                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1753                        )));
1754                    }
1755                    sanitizers.retain(|asked| *asked != one);
1756                }
1757            }
1758            // What a check does when it fires, and where the records about the checked objects go.
1759            // Each of them is an answer about the sanitizers refused after the loop, so there is
1760            // nothing left for them to change here. The names are still held to the list, because
1761            // a misspelling in a build's flags is worth finding when the compiler reads it.
1762            _ if arg.starts_with("-fsanitize-recover=")
1763                || arg.starts_with("-fno-sanitize-recover=")
1764                || arg.starts_with("-fsanitize-trap=")
1765                || arg.starts_with("-fno-sanitize-trap=") =>
1766            {
1767                // The guard above matched on a spelling that has an `=` in it, so the tail is
1768                // whatever follows the first one.
1769                let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1770                for one in how.split(',') {
1771                    if one != "all" && !SANITIZERS.contains(&one) {
1772                        return Err(err(format!(
1773                            "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1774                        )));
1775                    }
1776                }
1777            }
1778            "-fsanitize-undefined-trap-on-error"
1779            | "-fsanitize-address-use-after-scope"
1780            | "-fno-sanitize-address-use-after-scope" => {}
1781            _ if arg.starts_with("-fsanitize-sections=") => {}
1782            // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1783            // keeping. Refused rather than dropped, because a fuzzer whose calls into
1784            // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1785            // and there is no point in the campaign where that announces itself.
1786            _ if arg.starts_with("-fsanitize-coverage=") => {
1787                let how = &arg["-fsanitize-coverage=".len()..];
1788                for one in how.split(',') {
1789                    if !matches!(one, "trace-pc" | "trace-cmp") {
1790                        return Err(err(format!(
1791                            "`{one}` is not a coverage instrumentation, which is trace-pc or \
1792                             trace-cmp"
1793                        )));
1794                    }
1795                }
1796                return Err(err(format!(
1797                    "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1798                     with it would run without any feedback at all, see \
1799                     spec/04-driver-and-cli.md section 4.7"
1800                )));
1801            }
1802            // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1803            // after every `-f` the rest of the compiler answers to, so a pass can never take a
1804            // name that already means something else on the command line.
1805            _ if arg.starts_with("-fpass-fuel=") => {
1806                let (name, count) = arg["-fpass-fuel=".len()..]
1807                    .split_once('=')
1808                    .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1809                if rucc_opt::pass::find(name).is_none() {
1810                    return Err(err(format!(
1811                        "`{name}` is not a pass this compiler has, see --print-pipeline"
1812                    )));
1813                }
1814                let count: u32 = count
1815                    .parse()
1816                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1817                opts.pass_fuel.push((name.to_owned(), count));
1818            }
1819            _ if arg.starts_with("-fpass-fuel-global=") => {
1820                let count = &arg["-fpass-fuel-global=".len()..];
1821                let count: u32 = count
1822                    .parse()
1823                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1824                opts.pass_fuel_global = Some(count);
1825            }
1826            _ if arg.starts_with("-frucc-trace=") => {
1827                let path = &arg["-frucc-trace=".len()..];
1828                if path.is_empty() {
1829                    return Err(err("-frucc-trace= needs a file to write to"));
1830                }
1831                opts.trace = Some(path.to_owned());
1832            }
1833            // Everything from `-fopt-info` to the end of the argument, which is optional
1834            // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1835            // where the remarks are printed, because by then the compilation somebody wanted
1836            // to hear about is over.
1837            _ if arg == "-fopt-info"
1838                || arg.starts_with("-fopt-info=")
1839                || arg.starts_with("-fopt-info-") =>
1840            {
1841                let rest = &arg["-fopt-info".len()..];
1842                let (kinds, file) = match rest.split_once('=') {
1843                    Some((kinds, file)) => (kinds, Some(file)),
1844                    None => (rest, None),
1845                };
1846                let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1847                rucc_opt::Wants::none().add(kinds).map_err(err)?;
1848                opts.opt_info.push(kinds.to_owned());
1849                if let Some(file) = file {
1850                    if file.is_empty() {
1851                        return Err(err("-fopt-info= was given no file to write to"));
1852                    }
1853                    opts.opt_info_file = Some(file.to_owned());
1854                }
1855            }
1856            _ if arg.starts_with("-fdump-ir=") => {
1857                // Checked here rather than where the dumps are taken, because the compilation
1858                // that would have been dumped is over by then.
1859                let spec = &arg["-fdump-ir=".len()..];
1860                rucc_opt::Dumps::default().add(spec).map_err(err)?;
1861                opts.dump_ir.push(spec.to_owned());
1862            }
1863            // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1864            // otherwise take the flag away from the gate. Checked here rather than where the
1865            // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1866            // name that quietly gated nothing looks exactly like a pass that is not the guilty
1867            // one, and a bisection would carry on past the thing it was looking for.
1868            _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1869                let on = arg.starts_with("-fenable-");
1870                let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1871                rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1872                opts.pass_gates.push((on, spec.to_owned()));
1873            }
1874            // gcc's spelling for a pass this compiler has under a shorter name. It goes above the
1875            // two arms below rather than into the pile of gcc pass names further down, because the
1876            // pass is here: dropping the flag would leave a build that asked for unrolling without
1877            // it, and refusing it stops the build outright, which is what libtommath's makefile
1878            // ran into. `-funroll-all-loops` is deliberately not in here: gcc's is the one that
1879            // unrolls without a trip count, which is a different and usually worse thing.
1880            "-funroll-loops" => opts.passes.push(("unroll".to_owned(), true)),
1881            "-fno-unroll-loops" => opts.passes.push(("unroll".to_owned(), false)),
1882            // Here rather than through the two arms below, because what this names is not a
1883            // `rucc_opt::Pass`. Section 34.6's propagation is a module at a time and everything in
1884            // the pass list is one function at a time. `-fipa-cp-clone` is deliberately not here:
1885            // gcc turns that one on at `-O3` and it is in the list of what M4 does not build.
1886            "-fipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), true)),
1887            "-fno-ipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), false)),
1888            // The other half of the same section, here for the same reason, and `-fipa-sra` in gcc
1889            // is the aggregate splitting as well as the parameter removal. Asking for it gets the
1890            // half that is built.
1891            "-fipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), true)),
1892            "-fno-ipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), false)),
1893            // And the printf family fold, which is a module at a time for the same reason and so is
1894            // not a `rucc_opt::Pass` either. gcc has no flag of its own for this one, since
1895            // `-fno-builtin` already turns it off along with everything else the standard names
1896            // mean. This spelling is for taking one thing away during a bisection without taking
1897            // the rest of section 20.1 away with it.
1898            "-flibcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), true)),
1899            "-fno-libcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), false)),
1900            _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1901                opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1902            }
1903            _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1904                opts.passes.push((arg["-f".len()..].to_owned(), true));
1905            }
1906            // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1907            // program reduced from a miscompilation usually names the pass that miscompiled it on
1908            // its `dg-options` line, and they arrive from hand written build files for the same
1909            // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1910            // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1911            // for a compiler that does not exist here, and the program it is attached to is a
1912            // correctness test that passes either way. Turning on a pass we do not have costs
1913            // speed, turning off a pass we do not have costs nothing, and neither changes what the
1914            // program computes.
1915            //
1916            // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1917            // compiler has rather than landing here, and the day one of these names becomes a pass
1918            // here it stops being taken and dropped without anybody editing this list.
1919            //
1920            // Two of them are prefixes rather than names, which is the one place this file takes a
1921            // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1922            // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1923            // nothing else, and there is no member of either that changes the meaning of a program
1924            // that was already correct. The rest are written out one at a time, because they live
1925            // in the flat `-f` namespace where the neighbours do change meanings.
1926            _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1927            _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1928            "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1929            "-fmodulo-sched" | "-fno-modulo-sched" => {}
1930            "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1931            _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1932            }
1933            "-fearly-inlining" | "-fno-early-inlining" => {}
1934            // The one of the family that does reach the optimizer, since the step it names is built:
1935            // `-fno-inline` stops a function declared `inline` from being inlined and leaves
1936            // `always_inline` alone, which is what it does in gcc.
1937            "-finline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), true)),
1938            "-fno-inline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), false)),
1939            // The called once half of the same step, on its own, which leaves the `inline` hint and
1940            // `always_inline` as they are. tamnd/rucc#1966.
1941            "-finline-functions-called-once" => {
1942                opts.passes.push((rucc_opt::inline::ONCE.to_owned(), true));
1943            }
1944            "-fno-inline-functions-called-once" => {
1945                opts.passes.push((rucc_opt::inline::ONCE.to_owned(), false));
1946            }
1947            "-finline-functions"
1948            | "-fno-inline-functions"
1949            | "-finline-small-functions"
1950            | "-fno-inline-small-functions" => {}
1951            "-foptimize-strlen" | "-fno-optimize-strlen" => {}
1952            "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
1953            // Where a function starts, which is a thing this compiler already decides and so is a
1954            // request it can answer rather than one it has to drop. The bare form asks for the
1955            // target's default and the default here is the sixteen bytes gcc also gives, so it
1956            // says nothing; a number is a floor under every function that did not ask for more
1957            // itself; and the negative form asks for the smallest boundary the target has. gcc 16
1958            // rounds a number that is not a power of two up rather than refusing it, which is what
1959            // `=3` giving `.p2align 2` on x86-64 means, so this rounds too.
1960            "-falign-functions" => opts.align_functions = None,
1961            "-fno-align-functions" => opts.align_functions = Some(MIN_FUNC_ALIGN),
1962            _ if arg.starts_with("-falign-functions=") => {
1963                opts.align_functions = function_alignment(&arg["-falign-functions=".len()..])
1964                    .ok_or_else(|| {
1965                        err(format!("{arg}: the alignment has to be a number of bytes"))
1966                    })?;
1967            }
1968            // The head of every hot loop, which is padded when this is asked for so that a loop that
1969            // fits in a 64 byte line does not cross one. Both directions of the plain form are
1970            // answered. A number is taken and says nothing, because the boundary here is the
1971            // line's and a build that names another is asking for speed rather than for a
1972            // different program.
1973            "-falign-loops" => opts.align_loops = Some(true),
1974            "-fno-align-loops" => opts.align_loops = Some(false),
1975            // The other two of the family, which are about padding in front of any label and in
1976            // front of a label only a jump reaches. This compiler writes neither, and what they
1977            // ask for is speed: a label on a boundary computes what a label off one computes. So
1978            // they are taken and dropped for the reason `-march=` is, and the numbered form of
1979            // the loop flag with them.
1980            _ if arg.starts_with("-falign-labels")
1981                || arg.starts_with("-falign-loops=")
1982                || arg.starts_with("-falign-jumps")
1983                || arg.starts_with("-fno-align-labels")
1984                || arg.starts_with("-fno-align-jumps") => {}
1985            // The charset flags are not in that pile, because an encoding is a statement about
1986            // what the bytes of the source mean rather than about how fast the output is. The
1987            // preprocessor reads UTF-8 and has no converter, so the one name that describes what
1988            // already happens is taken and every other name is refused. Spelled without regard to
1989            // case and with both of the spellings iconv answers to, since a build writes whichever
1990            // one its author typed.
1991            _ if arg.starts_with("-finput-charset=") => {
1992                let name = &arg["-finput-charset=".len()..];
1993                if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
1994                    return Err(err(format!(
1995                        "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
1996                         converter, so a file in another encoding would be read as though it were \
1997                         UTF-8 rather than converted",
1998                    )));
1999                }
2000            }
2001            // What C has of exceptions, which is a `cleanup` handler an unwind has to run and the
2002            // `__EXCEPTIONS` that tells a header so. The walk is what turns down the handler it has
2003            // no landing pad for, so a unit with none of them is taken whole.
2004            "-fexceptions" => exceptions = Some(true),
2005            "-fno-exceptions" => exceptions = Some(false),
2006            "-fnon-call-exceptions" => opts.non_call_exceptions = true,
2007            "-fno-non-call-exceptions" => opts.non_call_exceptions = false,
2008            // Whether an instruction that could raise one may still be deleted when nothing uses
2009            // what it computes. Nothing here keeps a dead one, and neither does gcc in a C unit
2010            // with no handler around it, so both spellings describe the code as it is.
2011            "-fdelete-dead-exceptions" | "-fno-delete-dead-exceptions" => {}
2012            "-finstrument-functions" => opts.instrument_functions = true,
2013            "-fno-instrument-functions" => opts.instrument_functions = false,
2014            // The unstable options, spelled the way rustc spells them and carrying the same
2015            // promise, which is none: one of these may change or go away in any release. They are
2016            // measurements and debugging aids rather than things a build asks for, which is why
2017            // none of them is in the usage text and all of them are in section 4.11 of
2018            // `spec/04-driver-and-cli.md`.
2019            "-Zverify-each" => opts.verify_each = true,
2020            _ if arg.starts_with("-Zrule-coverage=") => {
2021                let file = &arg["-Zrule-coverage=".len()..];
2022                if file.is_empty() {
2023                    return Err(err("-Zrule-coverage= needs a file to write to"));
2024                }
2025                opts.rule_coverage = Some(file.to_owned());
2026            }
2027            _ if arg.starts_with("-Zcycle-accurate-model=") => {
2028                let value = &arg["-Zcycle-accurate-model=".len()..];
2029                opts.cycle_accurate_model = match value {
2030                    "yes" | "1" => Some(true),
2031                    "no" | "0" => Some(false),
2032                    _ => {
2033                        return Err(err("-Zcycle-accurate-model= takes yes or no"));
2034                    }
2035                };
2036            }
2037            _ if arg.starts_with("-Zswitch=") => {
2038                let shape = &arg["-Zswitch=".len()..];
2039                if rucc_codegen::switch::Force::named(shape).is_none() {
2040                    return Err(err("-Zswitch= takes table, tree or walk"));
2041                }
2042                opts.switch_shape = Some(shape.to_owned());
2043            }
2044            _ if arg.starts_with("-Zlowering=") => {
2045                let file = &arg["-Zlowering=".len()..];
2046                if file.is_empty() {
2047                    return Err(err("-Zlowering= needs a file to write to"));
2048                }
2049                opts.lowering_dump = Some(file.to_owned());
2050            }
2051            _ if arg.starts_with("-Zregister-pressure=") => {
2052                let file = &arg["-Zregister-pressure=".len()..];
2053                if file.is_empty() {
2054                    return Err(err("-Zregister-pressure= needs a file to write to"));
2055                }
2056                opts.register_pressure = Some(file.to_owned());
2057            }
2058            _ if arg.starts_with("-Z") => {
2059                return Err(err(format!(
2060                    "`{arg}` is not an unstable option this compiler has, see \
2061                     spec/04-driver-and-cli.md section 4.11 for the ones it does"
2062                )));
2063            }
2064            // The word size, which is a statement about the target and is taken as one. A build
2065            // that says the size the target already has is saying nothing, and one that says the
2066            // other size is asking for a target this compiler does not have, which it is told
2067            // rather than being given the wrong one.
2068            "-m64" | "-m32" | "-mx32" => {
2069                let want: u32 = match arg {
2070                    "-m64" => 64,
2071                    _ => 32,
2072                };
2073                let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
2074                if have != want {
2075                    return Err(err(format!(
2076                        "{arg} asks for a {want} bit target and {} is {have} bit, use \
2077                         --target= to name the one you mean",
2078                        opts.target
2079                    )));
2080                }
2081            }
2082            // One extension of the x86-64 instruction set, on or off, which is `-msse4.2` and its
2083            // relatives. Only the ones this compiler has the intrinsics for may be turned on for a
2084            // whole unit, because what turning one on does here is define the macro, and a macro
2085            // is a promise to a header that the names behind it exist. Turning one off is taken
2086            // for any name gcc knows, since nothing is promised by it, except for the baseline:
2087            // SSE2 is where the psABI passes a `double`, so a unit without it is a different
2088            // calling convention and not a smaller instruction set.
2089            _ if isa_name(arg).is_some() => {
2090                let Some((_, feature, on)) = isa_name(arg) else { continue };
2091                if on && !feature.honoured() {
2092                    return Err(err(format!(
2093                        "{arg}: this compiler has no intrinsics for {} yet, so it cannot build a \
2094                         whole unit for it",
2095                        feature.name()
2096                    )));
2097                }
2098                if !on && rucc_target::Isa::baseline().has(feature) {
2099                    return Err(err(format!(
2100                        "{arg}: {} is part of the x86-64 baseline and the psABI passes values in \
2101                         it, so a unit built without it would call and be called differently",
2102                        feature.name()
2103                    )));
2104                }
2105                isa.read(&arg["-m".len()..]).map_err(|_| err(format!("unknown option `{arg}`")))?;
2106                isa_flag.get_or_insert(arg);
2107            }
2108            // Which processor in the family to build for. What it decides is the extensions of
2109            // the instruction set the unit may assume, which is the macros, and only on x86-64;
2110            // see `rucc_target::isa`. A processor it has no list for is built for as the
2111            // baseline, which is a program that could have been faster rather than a program
2112            // that is wrong, and the same goes for every other target's processors. `-mtune=`
2113            // says what to schedule for and changes nothing a program can see.
2114            _ if arg.starts_with("-march=") => march = Some(&arg["-march=".len()..]),
2115            _ if arg.starts_with("-mtune=") || arg.starts_with("-mcpu=") => {}
2116            // The calling convention, which is not safe to ignore. Taken when it names the one
2117            // the target already uses and refused otherwise.
2118            _ if arg.starts_with("-mabi=") => {
2119                let want = &arg["-mabi=".len()..];
2120                let have = match opts.target.arch {
2121                    rucc_target::Arch::X86_64 => "sysv",
2122                    rucc_target::Arch::Aarch64 => "lp64",
2123                    rucc_target::Arch::Riscv64 => "lp64d",
2124                };
2125                if want != have {
2126                    return Err(err(format!(
2127                        "{arg}: {} uses the {have} convention and this compiler has no other",
2128                        opts.target
2129                    )));
2130                }
2131            }
2132            // How far apart the pieces of the program may be. The small model is what we emit and
2133            // it is every hosted program's default; the kernel model is a different one and a
2134            // build that asks for it and does not get it links and then does not run.
2135            "-mcmodel=small" => {}
2136            // clang's spellings of the deployment target, which it takes over a version in the
2137            // tuple. gcc on a Mac takes the first. A target that is not Apple ignores it, as
2138            // clang does, so a makefile that always passes it still builds for Linux.
2139            _ if arg.starts_with("-mmacosx-version-min=")
2140                || arg.starts_with("-mmacos-version-min=") =>
2141            {
2142                let text = &arg[arg.find('=').map_or(arg.len(), |i| i + 1)..];
2143                let version = rucc_tuple::Version::parse(text)
2144                    .ok_or_else(|| err(format!("`{text}` in `{arg}` is not a version")))?;
2145                min_version = Some(version);
2146            }
2147            _ if arg.starts_with("-mcmodel=") => {
2148                return Err(err(format!(
2149                    "{arg}: this compiler emits the small code model and no other, see \
2150                     spec/12-targets.md"
2151                )));
2152            }
2153            // GCC's own scripting language for how the driver builds a command line.
2154            // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
2155            // build reaching for it is told which flags do the same job.
2156            _ if arg.starts_with("-specs=") => {
2157                return Err(err(
2158                    "-specs= is not supported: the parts of it builds rely on are -B, -L, \
2159                     -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
2160                     section 4.4",
2161                ));
2162            }
2163            // Arguments meant for a separate assembler, which this compiler does not have: it is
2164            // inside it and does not read a command line. Refused rather than dropped, because
2165            // every one of these says something about the output and a build that asked for
2166            // `-Wa,--noexecstack` and was silently given an executable stack got the opposite of
2167            // what it asked for. The `-Wp,` ones this compiler understands were turned into its
2168            // own flags before the loop, so one that reaches here is one it does not.
2169            _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
2170                return Err(err(format!(
2171                    "`{arg}` is an argument for a separate assembler or preprocessor, and both \
2172                     are inside this compiler rather than programs it runs"
2173                )));
2174            }
2175            "-Xassembler" | "-Xpreprocessor" => {
2176                return Err(err(format!(
2177                    "{arg} hands an argument to a separate assembler or preprocessor, and both \
2178                     are inside this compiler rather than programs it runs"
2179                )));
2180            }
2181            // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
2182            // this one as a rule about build systems rather than about warnings: autoconf and
2183            // meson find out whether a warning flag exists by passing it and looking at the exit
2184            // status, so the answer has to be gcc's. A name gcc knows is accepted, and one it does
2185            // not is refused, the way gcc refuses clang's names. `-Wno-` of a name nobody knows is
2186            // accepted, because gcc accepts it too, but `-Werror=` and `-Wno-error=` of one are
2187            // not. None of them turns anything on yet, which #485 is about.
2188            _ if arg.starts_with("-W") => {
2189                let name = &arg["-W".len()..];
2190                let named = name.strip_prefix("error=").or_else(|| name.strip_prefix("no-error="));
2191                if let Some(named) = named {
2192                    if !warnings::known(named) {
2193                        return Err(err(format!("`{arg}`: no option `-W{named}`")));
2194                    }
2195                } else if !name.is_empty() && !name.starts_with("no-") && !warnings::known(name) {
2196                    return Err(err(format!("unknown option `{arg}`")));
2197                }
2198            }
2199            // Flags that name something this compiler does not do and would not do differently
2200            // if it did. `-fno-ident` is about a comment in the output that we do not write
2201            // either way, and the others are about a way of ordering the compilation that has
2202            // been GCC's only way for twenty years. Section 4.1 asks for the list to be short
2203            // and for adding to it to be deliberate, which is why it is written out here.
2204            "-fno-ident"
2205            | "-fident"
2206            | "-funit-at-a-time"
2207            | "-fno-unit-at-a-time"
2208            | "-shared-libgcc"
2209            | "-static-libgcc"
2210            | "-fpch-deps"
2211            | "-fno-pch-deps" => {}
2212            _ if arg.starts_with('-') && arg.len() > 1 => {
2213                // Silently ignoring an unknown flag is how a build ends up not doing what
2214                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
2215                // for the flags that change code generation, and the safe default until the
2216                // flag table is populated is to reject everything we do not know.
2217                return Err(err(format!("unknown option `{arg}`")));
2218            }
2219            _ => inputs.push(Input { path: arg.to_owned(), forced, role: Role::File }),
2220        }
2221    }
2222
2223    // The fetch, before anything that resolves a compilation, because `--fetch` does not describe
2224    // one. It is here rather than in the loop so that `--offline` can forbid it whichever order the
2225    // two were written in, and it is before the refusals below so that a command line asking for a
2226    // sysroot is not told about a sanitizer.
2227    if let Some(named) = fetch {
2228        if fetch_msvc.is_some() {
2229            return Err(err(
2230                "--fetch and --fetch-msvc-sdk are two different commands and this command line \
2231                 asked for both. --fetch gets a sysroot this release pins by URL and by hash, and \
2232                 --fetch-msvc-sdk gets what is behind Microsoft's licence wall, which no release \
2233                 pins and which nobody may republish. Run whichever one you meant",
2234            ));
2235        }
2236        return fetch_action(&named, offline, &inputs);
2237    }
2238    if let Some(named) = fetch_msvc {
2239        return fetch_msvc_action(&named, offline, accepted, &inputs);
2240    }
2241    if accepted {
2242        return Err(err(
2243            "--accept-licence says that Microsoft's Visual Studio Build Tools licence is accepted, \
2244             and nothing on this command line asked for anything that licence covers. \
2245             --fetch-msvc-sdk <tuple> is the command it belongs to, and an ordinary compile \
2246             downloads nothing with it or without it",
2247        ));
2248    }
2249
2250    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
2251    // order: a directory the user names outranks the compiler's own, and the compiler's own
2252    // outranks the library's. It is pushed after the loop rather than before it because
2253    // `SearchPath` appends within a group and the position is what the order is.
2254    // The same directory the headers were looked for under, because a sysroot is a statement
2255    // about a whole installation and not about half of one.
2256    // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
2257    // command line that turns a check on and off again has asked for nothing. What is left is
2258    // refused rather than dropped, and it is the one place in this parser where the reason is not
2259    // that the output would differ. A sanitizer is a promise that the program is watched while it
2260    // runs, so a build that asks for one and is quietly given a program with no checks in it does
2261    // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
2262    // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
2263    // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
2264    // options.
2265    if let Some(first) = sanitizers.first() {
2266        return Err(err(format!(
2267            "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
2268             asked for one and got none would run its tests unchecked, see \
2269             spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
2270             compiler does have"
2271        )));
2272    }
2273    // The fast math family, replayed in order on top of what `-Ofast` implies. The startup file is
2274    // gcc's spec rather than the fields: it is linked when `-Ofast`, `-ffast-math` or
2275    // `-funsafe-math-optimizations` is still in force at the end of the line, whatever a later
2276    // member took back, and `-mdaz-ftz` decides it outright.
2277    let mut math = Math::default();
2278    let mut trapping = if ofast { math.set_fast(true) } else { true };
2279    for flag in &math_flags {
2280        match *flag {
2281            "-ftrapping-math" => trapping = true,
2282            "-fno-trapping-math" => trapping = false,
2283            "-ffast-math" => trapping = math.set_fast(true),
2284            "-fno-fast-math" => trapping = math.set_fast(false),
2285            "-funsafe-math-optimizations" => trapping = math.set_unsafe(true),
2286            "-fno-unsafe-math-optimizations" => trapping = math.set_unsafe(false),
2287            "-fmath-errno" => math.errno = true,
2288            "-fno-math-errno" => math.errno = false,
2289            "-ffinite-math-only" => math.finite_only = true,
2290            "-fno-finite-math-only" => math.finite_only = false,
2291            "-fsigned-zeros" => math.signed_zeros = true,
2292            "-fno-signed-zeros" => math.signed_zeros = false,
2293            "-freciprocal-math" => math.reciprocal = true,
2294            "-fno-reciprocal-math" => math.reciprocal = false,
2295            "-fassociative-math" => math.associative = true,
2296            "-fno-associative-math" => math.associative = false,
2297            _ => unreachable!("{flag} is not in the family"),
2298        }
2299    }
2300    opts.trapping_math = trapping;
2301    opts.math = math;
2302    let last = |on: &str, off: &str| {
2303        math_flags.iter().rev().find(|f| **f == on || **f == off).is_some_and(|f| *f == on)
2304    };
2305    link.fast_math = ofast
2306        || last("-ffast-math", "-fno-fast-math")
2307        || last("-funsafe-math-optimizations", "-fno-unsafe-math-optimizations");
2308    link.daz_ftz = daz_ftz;
2309    // The extensions, now that the target is known. On x86-64 the processor supplies whatever no
2310    // flag said. Anywhere else there are none to have, and a flag naming one is gcc's unknown
2311    // option there too, so it is refused the same way it would have been had it not looked like
2312    // an x86 flag.
2313    match opts.target.arch {
2314        rucc_target::Arch::X86_64 => {
2315            let base = match march {
2316                Some("native") => native_isa(),
2317                Some(name) => {
2318                    rucc_target::Isa::level(name).unwrap_or_else(rucc_target::Isa::baseline)
2319                }
2320                None => rucc_target::Isa::baseline(),
2321            };
2322            opts.isa = isa.over(base);
2323        }
2324        rucc_target::Arch::Aarch64 | rucc_target::Arch::Riscv64 => {
2325            if let Some(flag) = isa_flag {
2326                return Err(err(format!("unknown option `{flag}`")));
2327            }
2328            opts.isa = rucc_target::Isa::NONE;
2329        }
2330    }
2331    opts.exceptions = exceptions.unwrap_or(opts.non_call_exceptions);
2332    link.sysroot = sysroot.clone();
2333    // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
2334    // inside the link line, because a link line that read the environment could only be tested on a
2335    // machine whose environment said the right thing, and the link line is the last thing that
2336    // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
2337    link.cache = Some(cache::dir());
2338    // And where a distribution's cross packages would have put a tree for the target, which is only
2339    // read when the target is not this machine and there is no sysroot of ours for it.
2340    link.usr = Some(PathBuf::from("/usr"));
2341    // And the ten field spelling of the target, because the release on it decides two things the
2342    // three field one cannot say: whether a target that is this architecture is still a cross
2343    // compile, and which directory under the cache it is against. After the loop because the last
2344    // `--target=` on the command line is the one that counts.
2345    link.pinned = pinned;
2346    // The deployment target, from the flag if there was one and from the tuple otherwise. Only an
2347    // Apple platform has one: anywhere else a version on the tuple is a libc or a preview number.
2348    if opts.target.os == rucc_target::Os::Darwin {
2349        opts.os_version = min_version.or_else(|| pinned.and_then(TargetTuple::os_version));
2350    }
2351    // After the loop rather than where `-pthread` was read, so that it lands after the objects
2352    // that refer to it. A static link takes the definitions it needs from a library when it
2353    // reaches it and not afterwards, so a library before the objects is a library that answers
2354    // nothing.
2355    if threads {
2356        inputs.push(Input::library("pthread"));
2357    }
2358    if let Some(query) = query {
2359        return Ok(Action::Print(answer(&query, &opts, &link)?));
2360    }
2361    // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
2362    // else the command line asked for. Read here rather than where the flag was, because a `-c`
2363    // written after it has to lose and the loop cannot know that until it has ended. The output
2364    // file is where the rule goes rather than where an object would have gone, and the last
2365    // phase being the preprocessor is what makes that true without a second rule for it.
2366    if opts.deps.instead_of_compiling {
2367        opts.emit = EmitKind::Preprocessed;
2368    }
2369    if !nostdinc {
2370        opts.search.push_system(runtime::DIR);
2371        // And the library's after ours, which is the other half of the same order. They go on
2372        // here rather than at the point `--target=` or `--sysroot=` was read because either
2373        // one changes the answer and the last word on both is the end of the loop.
2374        //
2375        // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
2376        // that the headers and the libraries come from the same place. A target that is this
2377        // machine reads this machine's headers, and a target that is not reads the ones in the
2378        // sysroot for it rather than the ones next door.
2379        let cross = link::cross_sysroot(opts.target, &link);
2380        let kernel = link::cross_kernel(opts.target, &link);
2381        let distro = link::distro_cross(opts.target, &link);
2382        // And the version of those headers, which only the bundled tree has an answer for. A host
2383        // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
2384        // and a second definition with a different value is a warning on every file, so the
2385        // condition is the same one that chose the directories.
2386        if cross.is_some() {
2387            let target = pinned.unwrap_or_else(|| opts.target.tuple());
2388            opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
2389                err(format!(
2390                    "{skew}; pin a release the tree has, or name a tree that has that one \
2391                     with --sysroot"
2392                ))
2393            })?;
2394        }
2395        let system = library::header_dirs(
2396            opts.target,
2397            sysroot.as_deref(),
2398            cross.as_ref(),
2399            kernel.as_ref(),
2400            distro.as_ref(),
2401        );
2402        // The two licence walls of `spec/cross-compile/13-distribution.md` section 13.4, which are
2403        // the only way step 3 comes back with nothing on a hosted target. Section 8.6 asks for the
2404        // answer to name the licence and the lawful ways to get what is behind it, rather than
2405        // leaving a person with an `#include` that failed as though a directory had gone missing.
2406        //
2407        // It is left on the search path instead of refused here, because a program that includes
2408        // none of the library needs none of the SDK and section 8.6 is explicit that targeting the
2409        // platform has to keep working. So the reason waits until an include has actually failed,
2410        // which is the only moment it helps and the only moment it is true.
2411        //
2412        // The condition is that step 3 found nothing at all, so an `SDKROOT`, an `INCLUDE` or a mac
2413        // with Xcode on it all pass through untouched, and `-nostdinc` never reaches this block. A
2414        // `--sysroot` or `-isysroot` passes through as well, even when the tree it names turns out to
2415        // be empty or absent: somebody who wrote a path has already answered the question this
2416        // message asks, and answering it again over the top of a mistyped directory would hide the
2417        // mistake behind a licence notice.
2418        if system.is_empty() && sysroot.is_none() {
2419            let tuple = pinned.unwrap_or_else(|| opts.target.tuple());
2420            if let Some(wall) = rucc_sysroot::Wall::of(tuple) {
2421                opts.search.explain_missing_system(wall.no_headers(&tuple.to_canonical_string()));
2422            }
2423        }
2424        // And whether the tree somebody named is the release they asked for, which is the one
2425        // question left once the directories are settled and the only place both halves of it are
2426        // known. Only for a named tree, because that is the case where the release in the target
2427        // stops deciding anything, and `crate::glibc` is where the rest of the reasoning is.
2428        if sysroot.is_some() {
2429            notes.extend(glibc::skew(opts.target, pinned, &system));
2430        }
2431        for dir in system {
2432            opts.search.push_system(dir);
2433        }
2434    }
2435    // Once, here, rather than as each directory is pushed. A `-I` that names a system
2436    // directory has to lose to the system entry and the system entry is added last, so the
2437    // question cannot be answered until the whole path is known.
2438    opts.search.remove_duplicates();
2439
2440    // The target has to be resolved before the configuration is printed, so this check comes
2441    // after the loop rather than at the point `--print-config` was seen.
2442    if print_config {
2443        return Ok(Action::PrintConfig(Box::new(opts)));
2444    }
2445    if print_pipeline {
2446        return Ok(Action::PrintPipeline(Box::new(opts)));
2447    }
2448    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
2449    if print_plan {
2450        return Ok(Action::PrintPlan {
2451            opts: Box::new(opts),
2452            plan: Box::new(plan),
2453            link: Box::new(link),
2454        });
2455    }
2456    Ok(Action::Compile {
2457        opts: Box::new(opts),
2458        plan: Box::new(plan),
2459        link: Box::new(link),
2460        jobs,
2461        verbose,
2462        notes,
2463    })
2464}
2465
2466/// What `--fetch <tuple>` asked for, or why it is not a thing that can be done.
2467///
2468/// The lookup happens here rather than at the point the bytes would move, so that a target this
2469/// release pins nothing for is a refusal from the parser and the only code that runs a downloader is
2470/// code that already knows what it is getting.
2471///
2472/// # Errors
2473///
2474/// [`CliError`] when `--offline` forbade it, when there are input files as well, when the tuple is
2475/// not a target this compiler knows, when its sysroot is behind one of section 13.4's licence walls,
2476/// and when this release pins no artifact for it.
2477fn fetch_action(named: &str, offline: bool, inputs: &[Input]) -> Result<Action, CliError> {
2478    // Not a precedence question. Section 13.2 says `--offline` forbids a fetch entirely, so a
2479    // command line that writes both has asked for two opposite things and the answer is to say so
2480    // rather than to pick one of them.
2481    if offline {
2482        return Err(err(
2483            "--fetch asks for a download and --offline forbids every download, so this command \
2484             line asks for two opposite things. Drop one of them: --offline is how a build says it \
2485             will not reach the network, and --fetch is one of the two things in this compiler \
2486             that reaches it",
2487        ));
2488    }
2489    if let Some(first) = inputs.first() {
2490        return Err(err(format!(
2491            "--fetch gets a sysroot and compiles nothing, so `{}` on the same command line is an \
2492             input that nothing would read",
2493            first.path
2494        )));
2495    }
2496    let target: TargetTuple = named
2497        .parse()
2498        .map_err(|why| err(format!("--fetch {named}: {why}, so there is no sysroot to get")))?;
2499    // The canonical spelling, because that is what a row is named by and what the directory under
2500    // the cache is called, and a person is free to write a tuple the long way round.
2501    let tuple = target.to_canonical_string();
2502    // Before the table is consulted, because a target behind a licence wall is not a row that has not
2503    // been written yet. Section 13.4 is that no release pins one of these ever, so the message says
2504    // the licence and the two lawful ways rather than naming the producer that will publish the rest.
2505    if let Some(wall) = rucc_sysroot::Wall::of(target) {
2506        return Err(err(format!("--fetch {tuple}: {}", wall.no_fetch(&tuple))));
2507    }
2508    let Some(what) = rucc_sysroot::pinned_for_target(target) else {
2509        return Err(err(unpinned(&tuple)));
2510    };
2511    Ok(Action::Fetch { what, target, cache: cache::dir() })
2512}
2513
2514/// What `--fetch-msvc-sdk <tuple>` asks for, weighed the same way the fetch above is.
2515///
2516/// The target is resolved here rather than where the work happens, so that a tuple this compiler
2517/// does not know and a target that is not behind Microsoft's wall are refusals from the parser like
2518/// every other thing a command line can ask for and not have. Whether the licence was accepted is
2519/// carried rather than acted on, because what it changes is what the command does and not whether
2520/// the command line made sense.
2521///
2522/// # Errors
2523///
2524/// [`CliError`] when `--offline` forbade it, when there are input files as well, and when the tuple
2525/// is not a target this compiler knows.
2526fn fetch_msvc_action(
2527    named: &str,
2528    offline: bool,
2529    accepted: bool,
2530    inputs: &[Input],
2531) -> Result<Action, CliError> {
2532    if offline {
2533        return Err(err(
2534            "--fetch-msvc-sdk asks for a download and --offline forbids every download, so this \
2535             command line asks for two opposite things. Drop one of them: --offline is how a build \
2536             says it will not reach the network",
2537        ));
2538    }
2539    if let Some(first) = inputs.first() {
2540        return Err(err(format!(
2541            "--fetch-msvc-sdk gets an SDK and compiles nothing, so `{}` on the same command line \
2542             is an input that nothing would read",
2543            first.path
2544        )));
2545    }
2546    let target: TargetTuple = named.parse().map_err(|why| {
2547        err(format!("--fetch-msvc-sdk {named}: {why}, so there is no SDK to get"))
2548    })?;
2549    Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir() })
2550}
2551
2552/// Why there is nothing to fetch for a target, which is a different sentence when the table is
2553/// empty.
2554///
2555/// A release that pins nothing and a release that pins eleven targets and not this one are two
2556/// situations, and a message that did not tell them apart would send somebody looking for a typo in
2557/// their tuple when the answer is that this work is not finished.
2558fn unpinned(tuple: &str) -> String {
2559    let pinned = rucc_sysroot::pinned_targets();
2560    if pinned.is_empty() {
2561        return format!(
2562            "this release pins no sysroot for {tuple}, and it pins none for any target yet. A \
2563             sysroot is built and published by the producer in tamnd/rucc-cross, per \
2564             spec/cross-compile/13-distribution.md section 13.8, and a release of this compiler \
2565             names one by URL and by hash afterwards. Until then, pass --sysroot=<dir> to compile \
2566             against a tree you have already"
2567        );
2568    }
2569    format!(
2570        "this release pins no sysroot for {tuple}. What it pins is {}. Pass --sysroot=<dir> to \
2571         compile against a tree you have already",
2572        pinned.join(", ")
2573    )
2574}
2575
2576/// Gets the artifact and installs it, saying what each step did.
2577///
2578/// The steps are section 13.8's and so are the messages: the transport is somebody else's program
2579/// and the check is ours, so a person reading this wants to know which downloader ran, that the
2580/// bytes matched, how many files the record named and where the tree ended up. A fetch of something
2581/// that is already there says that instead and moves nothing.
2582///
2583/// A Linux target is two artifacts, its own sysroot and the kernel header tree every Linux target
2584/// shares, and `kernel` is the second one when the target reads it. It is fetched after the sysroot
2585/// and by the same two steps, so a machine that has fetched one Linux target already has it and a
2586/// second target's fetch says so and moves nothing.
2587fn fetch_sysroot(
2588    what: &rucc_sysroot::Pinned,
2589    kernel: Option<&rucc_sysroot::Pinned>,
2590    target: TargetTuple,
2591    cache: &std::path::Path,
2592) -> i32 {
2593    let tuple = target.to_canonical_string();
2594    let say = |line: &str| println!("rucc: {tuple}: {line}");
2595    if let Err(why) = bring(what, cache, &say) {
2596        return complain(why);
2597    }
2598    let archive = what.archive_in(cache);
2599    match install::install(&archive, what.sha256, target, cache) {
2600        Ok(done) => report(&done, "sysroot", &say),
2601        Err(why) => return complain(why),
2602    }
2603    let Some(kernel) = kernel else { return 0 };
2604    if let Err(why) = bring(kernel, cache, &say) {
2605        return complain(why);
2606    }
2607    match install::install_kernel(&kernel.archive_in(cache), kernel.sha256, cache) {
2608        Ok(done) => {
2609            report(&done, "kernel header tree", &say);
2610            0
2611        }
2612        Err(why) => complain(why),
2613    }
2614}
2615
2616/// The download half of a fetch, for one artifact.
2617fn bring(
2618    what: &rucc_sysroot::Pinned,
2619    cache: &std::path::Path,
2620    say: &impl Fn(&str),
2621) -> Result<(), CliError> {
2622    let archive = what.archive_in(cache);
2623    match fetch::fetch(what.url, what.sha256, &archive)? {
2624        fetch::Fetched::AlreadyThere => {
2625            say(&format!("{} is already here and matches the hash", archive.display()));
2626        }
2627        fetch::Fetched::Downloaded(by) => {
2628            say(&format!("downloaded {} with {}", what.url, by.program()));
2629        }
2630    }
2631    Ok(())
2632}
2633
2634/// What an install did, in the words a person reading a fetch wants.
2635fn report(done: &install::Installed, what: &str, say: &impl Fn(&str)) {
2636    match &done.before {
2637        install::Before::Nothing => {
2638            say(&format!("{} files installed at {}", done.files, done.root.display()));
2639        }
2640        install::Before::TheSame => {
2641            say(&format!(
2642                "the same {what} is already at {}, so nothing moved",
2643                done.root.display()
2644            ));
2645        }
2646        install::Before::Different(was) => {
2647            say(&format!(
2648                "{} files installed at {}, over a tree whose record digested to {was}",
2649                done.files,
2650                done.root.display()
2651            ));
2652        }
2653    }
2654    say(&format!("the {what}'s record digests to {}", done.digest));
2655}
2656
2657/// What one of the `-dump` and `-print` flags prints.
2658///
2659/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
2660/// which is what makes the answer safe to paste into a link line whether or not the file is
2661/// there, and this does the same.
2662fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
2663    let found = |name: &str| {
2664        link::find_in_search(link, opts.target, name)
2665            .map_or_else(|| name.to_owned(), |path| path.display().to_string())
2666    };
2667    Ok(match query {
2668        Query::Machine => opts.target.to_string(),
2669        Query::Version => opts.gnuc.major.to_string(),
2670        Query::FullVersion => {
2671            format!("{}.{}.{}", opts.gnuc.major, opts.gnuc.minor, opts.gnuc.patch)
2672        }
2673        Query::Multiarch => link::multiarch(opts.target),
2674        // The three lines GCC prints, in its order and with its punctuation, because what reads
2675        // them is a script written against that shape. There is no installation directory to
2676        // report: this compiler is one binary that works wherever it is copied, and the headers
2677        // it ships are inside it, so `install` is where the binary is and nothing is under it.
2678        Query::SearchDirs => {
2679            let here = std::env::current_exe()
2680                .ok()
2681                .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
2682                .unwrap_or_default();
2683            let list = |dirs: &[PathBuf]| {
2684                dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
2685            };
2686            let libraries = link::search_dirs(link, opts.target);
2687            format!(
2688                "install: {}\nprograms: ={}\nlibraries: ={}",
2689                here.display(),
2690                list(&link.prefixes),
2691                list(&libraries)
2692            )
2693        }
2694        // The root the rest of the answers are under, which a build system asks for when it wants
2695        // to find a file itself rather than ask for one by name, and which is the first thing to
2696        // look at when a cross build read a header nobody expected. A native compile has no
2697        // sysroot and the answer is the empty line, which is what GCC prints when it was
2698        // configured without one. `--sysroot` wins over ours because it wins everywhere else.
2699        Query::Sysroot => {
2700            sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
2701        }
2702        // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
2703        // compiler's own code, what it is, where it was got, its hash, its licence and whether it
2704        // was bundled, generated or fetched. What is printed is the manifest the sysroot already
2705        // carries rather than a second format saying the same things, because the three uses 13.5
2706        // gives for this are a licence notice, a reproducibility check and a security audit, and all
2707        // three are somebody else parsing it. One format is one parser to write.
2708        // Read and rendered rather than copied out, so that what comes back is the format this
2709        // build understands. The last newline comes off because whatever prints an answer adds
2710        // one, the way it does for every other query here. Keeping it would put a blank line at
2711        // the end of the one answer that is a file somebody diffs against the file it came from.
2712        Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
2713            Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
2714            None => String::new(),
2715        },
2716        // Section 13.2 of the same document, which asks for the hash of a cache directory's
2717        // contents in the directory's name. A name cannot carry one, because the path has to be
2718        // computable before anything has been read, by the producer about to write the files and by
2719        // the compiler about to read them, and neither has the contents when it asks. So the number
2720        // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
2721        // which means `sha256sum` over the manifest answers the same thing.
2722        Query::SysrootDigest => match sysroot_manifest(opts, link)? {
2723            Some(manifest) => manifest.digest(),
2724            None => String::new(),
2725        },
2726        Query::FileName(name) => found(name),
2727        // The name GCC gives the library of routines a compiler's output calls that the C
2728        // library does not have. Ours is built in and there is no file, so the answer is the
2729        // name itself, which is what GCC prints when it cannot find one either.
2730        Query::Libgcc => found("libgcc.a"),
2731        // A program rather than a library: the linker and the archiver are the ones a build asks
2732        // about, and this compiler finds them on the path or under `-B` rather than shipping
2733        // them, so the name back is the honest answer unless a `-B` prefix holds one.
2734        Query::ProgName(name) => link
2735            .prefixes
2736            .iter()
2737            .map(|dir| dir.join(name))
2738            .find(|path| path.is_file())
2739            .map_or_else(|| name.clone(), |path| path.display().to_string()),
2740    })
2741}
2742
2743/// The root every sysroot answer is about.
2744///
2745/// One function rather than a copy in each, because the other flags exist to say what is inside the
2746/// tree this one names, and two answers that disagreed about which tree that is would be a
2747/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
2748/// else.
2749fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
2750    link.sysroot
2751        .clone()
2752        .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
2753}
2754
2755/// The record of the sysroot this command line reads, when there is one to read.
2756///
2757/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
2758/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
2759/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
2760/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
2761/// inputs in it because that one still has its header lines.
2762///
2763/// # Errors
2764///
2765/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
2766/// record we could not read on to whoever asked would make their parser the one that finds the
2767/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
2768/// output.
2769fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
2770    let Some(root) = sysroot_root(opts, link) else {
2771        return Ok(None);
2772    };
2773    let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
2774    match std::fs::read_to_string(&path) {
2775        Ok(text) => Manifest::parse(&text)
2776            .map(Some)
2777            .map_err(|why| err(format!("{}: {why}", path.display()))),
2778        Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
2779        Err(why) => Err(err(format!("{}: {why}", path.display()))),
2780    }
2781}
2782
2783/// Renders the passes this level will run, in order, with what each one does.
2784///
2785/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
2786/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
2787/// emerges from which flags happen to be set, and this is how that list is read.
2788#[must_use]
2789pub fn print_pipeline(opts: &Options) -> String {
2790    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
2791    settings.toggles.clone_from(&opts.passes);
2792    settings.global_fuel = opts.pass_fuel_global;
2793    for (on, spec) in &opts.pass_gates {
2794        // Every spelling was checked while the arguments were parsed, so there is nothing here
2795        // this can refuse, and a listing is not the place to report it if there were.
2796        let _ = settings.gates.add(*on, spec);
2797    }
2798    rucc_opt::pipeline::print(&settings)
2799}
2800
2801/// Renders the resolved configuration.
2802///
2803/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
2804/// this output is diffed across hosts in CI and a reordering would read as a change.
2805#[must_use]
2806pub fn print_config(opts: &Options) -> String {
2807    let sess = Session::new(opts.clone());
2808    let t = &sess.target;
2809    let mut out = String::new();
2810    let _ = writeln!(out, "version: {VERSION}");
2811    // The three field triple the driver was given rather than the ten field tuple it widens to,
2812    // because this output is what a build system reads to find out what it asked for. The tuple is
2813    // the compiler's model of the machine and this line is a receipt for a command line.
2814    let _ = writeln!(out, "target: {}", opts.target);
2815    let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
2816    let _ = writeln!(out, "os: {}", opts.target.os.as_str());
2817    let _ = writeln!(out, "env: {}", opts.target.env.as_str());
2818    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
2819    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
2820    let _ = writeln!(out, "long-width: {}", t.long_width);
2821    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
2822    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
2823    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
2824    let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
2825    // The register file as a count per class, which is enough to tell a target whose registers
2826    // are described from one whose are not without printing sixteen names nobody asked for.
2827    let regs: Vec<String> = t
2828        .regs
2829        .classes()
2830        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
2831        .collect();
2832    let _ = writeln!(
2833        out,
2834        "registers: {}",
2835        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
2836    );
2837    // What the schedule was chosen with, which is a sentence rather than a name on purpose: two
2838    // runs of a benchmark that disagree are usually two models and not two compilers.
2839    let _ = writeln!(out, "timing-model: {}", t.timing.map_or("none", |timing| timing.model));
2840    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
2841    let _ = writeln!(out, "safety: {}", sess.opts.safety);
2842    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
2843    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
2844    let _ = writeln!(out, "frame-pointer: {}", sess.opts.keeps_frame_pointer());
2845    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
2846    let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
2847    let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
2848    let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
2849    let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
2850    let _ = writeln!(out, "profile: {}", sess.opts.profile);
2851    let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
2852    // Last because it is the one key with more than one line under it, and the only one
2853    // whose value is a property of the machine rather than of the command line.
2854    for dir in sess.opts.search.dirs() {
2855        let system = if dir.is_system { " (system)" } else { "" };
2856        let _ = writeln!(out, "include: {}{system}", dir.path.display());
2857    }
2858    out
2859}
2860
2861/// The output name the make target is taken from, which is the `-o` argument or nothing.
2862///
2863/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
2864/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
2865/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
2866/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
2867/// `-S` on the argument does name what the rule builds, and it is used as written.
2868fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
2869    if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
2870}
2871
2872/// Writes to a path the command line named rather than one the plan derived, where `-` is
2873/// standard output.
2874fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
2875    if path == "-" {
2876        return write_out(&Output::Stdout, bytes);
2877    }
2878    write_out(&Output::File(path.to_owned()), bytes)
2879}
2880
2881/// Writes the make rule for one input, and reports whether it got there.
2882///
2883/// A rule with no file of its own goes where the compilation it replaced would have written,
2884/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
2885/// `$@`, and the same line with the `-o` left off puts it on standard output.
2886fn write_deps(
2887    opts: &Options,
2888    plan: &Plan,
2889    job: &Job,
2890    found: &[Dependency],
2891    stderr: &mut impl std::io::Write,
2892) -> bool {
2893    let targets = if opts.deps.targets.is_empty() {
2894        vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
2895    } else {
2896        opts.deps.targets.clone()
2897    };
2898    let rule = deps::rule(&opts.deps, &targets, &job.input, found);
2899    // The file, on the other hand, is named after the `-o` in every mode that still has one to
2900    // spend, which is every mode except the two that spend it on the rule.
2901    let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
2902        // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
2903        // named empty rather than absent, because a makefile that named it as a target of its
2904        // own is a makefile that will look for it.
2905        Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
2906            if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
2907        }),
2908        None => write_out(&job.output, rule.as_bytes()),
2909    };
2910    if let Err(e) = wrote {
2911        let _ = writeln!(stderr, "rucc: error: {e}");
2912        return false;
2913    }
2914    true
2915}
2916
2917/// Runs phase 4 over every input that has one, and writes what came out.
2918///
2919/// One input that fails does not stop the others. A build that reports every file it could
2920/// not preprocess in one run is worth more than one that stops at the first, and the exit
2921/// status is still a failure either way.
2922fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
2923    let fs = OsFileSystem::new();
2924    let mut stderr = std::io::stderr().lock();
2925    let mut failed = false;
2926    for job in &plan.jobs {
2927        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
2928            // An input that is already preprocessed, or an object file. GCC passes these
2929            // through untouched, and the plan has already said so in its notes.
2930            continue;
2931        }
2932        let started = std::time::Instant::now();
2933        let result = preprocess(opts, &job.input, &fs);
2934        if opts.time {
2935            say_time(&job.input, started.elapsed(), &mut stderr);
2936        }
2937        for message in &result.messages {
2938            let _ = writeln!(stderr, "{message}");
2939        }
2940        if result.failed() {
2941            failed = true;
2942            continue;
2943        }
2944        if opts.deps.emit {
2945            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2946            // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
2947            // to write. The other two asked for both and fall through to the text below.
2948            if opts.deps.instead_of_compiling {
2949                continue;
2950            }
2951        }
2952        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
2953            let _ = writeln!(stderr, "rucc: error: {e}");
2954            failed = true;
2955        }
2956    }
2957    i32::from(failed)
2958}
2959
2960/// Whether this job is a file of assembly that has to be assembled and that nothing here assembles.
2961///
2962/// The phases rather than the kind, because there are two kinds of assembly input and one of them
2963/// is preprocessed first, and because an object file also has no compile phase and is not this: it
2964/// has no phases at all and goes to the linker as it is. A `.s` on a `-c` line has exactly
2965/// [`Phase::Assemble`] left, and a `.S` has the preprocessor in front of it, and neither has
2966/// anything the front end can do.
2967fn needs_an_assembler(job: &Job) -> bool {
2968    job.phases.contains(&Phase::Assemble) && !job.phases.contains(&Phase::Compile)
2969}
2970
2971/// Whether the preprocessor runs over it on the way in, which is the whole difference between the
2972/// two kinds of assembly input.
2973fn assembly_wants_cpp(job: &Job) -> bool {
2974    job.phases.contains(&Phase::Preprocess)
2975}
2976
2977/// Runs the front end over every input that has a compile phase, and writes what came out.
2978///
2979/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
2980/// exit status is a failure either way. An input that is already assembly or an object has no
2981/// compile phase and is passed over here, which the plan has already said in its notes.
2982fn compile_all(opts: &Options, plan: &Plan) -> i32 {
2983    let fs = OsFileSystem::new();
2984    let mut stderr = std::io::stderr().lock();
2985    let mut failed = false;
2986    let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2987    failed |= !ok;
2988    let mut fired = Fired::new();
2989    let mut pressure = Pressure::new();
2990    let mut lowerings = Lowerings::new();
2991    for job in &plan.jobs {
2992        if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
2993            continue;
2994        }
2995        // An input of IR is read back rather than compiled, since the C it came from is not
2996        // here any more. A file of assembly does not go through the front end at all and is
2997        // read by the assembler instead. Everything after this is the same for all three, so
2998        // the paths meet again at the messages and the file the result is written to.
2999        let started = std::time::Instant::now();
3000        let result = if needs_an_assembler(job) {
3001            assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3002        } else if job.kind == InputKind::Ir {
3003            compile_ir(opts, &job.input, &fs)
3004        } else {
3005            compile(opts, &job.input, &fs)
3006        };
3007        if opts.time {
3008            say_time(&job.input, started.elapsed(), &mut stderr);
3009        }
3010        failed |= !write_trace(opts, job, started, &result, &mut stderr);
3011        fired.merge(&result.fired);
3012        pressure.merge(&result.pressure);
3013        lowerings.merge(&result.lowerings);
3014        failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3015        failed |= !remarks.write(&result.remarks, &mut stderr);
3016        for message in &result.messages {
3017            let _ = writeln!(stderr, "{message}");
3018        }
3019        // Before the failure below, because a compilation that stopped in the back end is exactly
3020        // the one whose preprocessed source somebody wants to look at.
3021        failed |= !write_temps(job, &result.temps, &mut stderr);
3022        // Before it as well, because gcc leaves an empty report for a file that did not compile
3023        // and a build that looks for one beside every object should find one.
3024        failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3025        if result.failed() {
3026            failed = true;
3027            continue;
3028        }
3029        // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
3030        // this is the one path where both files come out of the same run. An input of IR has no
3031        // dependencies to report and produces an empty list, which produces a rule naming only
3032        // itself, and that is the honest answer rather than a missing file.
3033        if opts.deps.emit {
3034            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3035        }
3036        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
3037            let _ = writeln!(stderr, "rucc: error: {e}");
3038            failed = true;
3039        }
3040    }
3041    failed |= !write_coverage(opts, &fired, &mut stderr);
3042    failed |= !write_pressure(opts, &pressure, &mut stderr);
3043    failed |= !write_lowering(opts, &lowerings, &mut stderr);
3044    i32::from(failed)
3045}
3046
3047/// A directory for the object files only the link step ever sees, removed when it goes away.
3048///
3049/// `-c` writes its object where the user can see it and linking does not, which is the whole of
3050/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
3051/// every other compiler. Removing them on drop rather than at the end of a function is so that a
3052/// link that failed leaves nothing behind either.
3053struct Scratch {
3054    /// Where the objects go.
3055    dir: PathBuf,
3056}
3057
3058impl Scratch {
3059    /// Makes one, under whatever the platform calls its temporary directory.
3060    ///
3061    /// The name carries the process id so that two compilers running at once do not share a
3062    /// directory, which they would otherwise do the moment two of them compiled a file of the
3063    /// same name.
3064    fn new() -> Result<Scratch, String> {
3065        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
3066        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
3067        Ok(Scratch { dir })
3068    }
3069}
3070
3071impl Drop for Scratch {
3072    fn drop(&mut self) {
3073        let _ = std::fs::remove_dir_all(&self.dir);
3074    }
3075}
3076
3077/// The link line the plan describes, for `-###`.
3078///
3079/// The names in it are the hints the plan carries rather than the temporaries a real compilation
3080/// would choose, because `-###` prints the line without having compiled anything and so has
3081/// nothing to point at. That also makes the printed line readable rather than naming a directory
3082/// that only exists while a compilation is running.
3083fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
3084    let linker = link::find(opts.target, link)?;
3085    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
3086    Ok(link::render(&linker, &args))
3087}
3088
3089/// Compiles everything, then links it.
3090///
3091/// The objects go in a directory that is removed afterwards, which is why this is not
3092/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
3093/// and does not say where, because where is a question that only has an answer once something is
3094/// running.
3095fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
3096    let Some(job) = &plan.link else {
3097        // Every path into here comes from a plan whose last phase is the link, and such a plan
3098        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
3099        let mut stderr = std::io::stderr().lock();
3100        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
3101        return 1;
3102    };
3103    // Before anything is compiled, because a linker that is not on the machine is worth knowing
3104    // about in the second it takes to look rather than after the compilation.
3105    // And before that, whether this link has a line at all and whether what it reads is on the
3106    // machine. Both are answerable now, and a target whose sysroot has not been built is worth
3107    // saying so about before the compilation rather than after it.
3108    if let Err(why) = link::preflight(opts.target, link) {
3109        return complain(why);
3110    }
3111    let linker = match link::find(opts.target, link) {
3112        Ok(linker) => linker,
3113        Err(why) => return complain(why),
3114    };
3115    // And whether the one that was found can do this link, which for one linker and one target is
3116    // a question only the linker itself can answer. Here rather than inside the search, because
3117    // what it does is refuse rather than move on to the next candidate: nothing else in the list
3118    // links a produced Windows sysroot either.
3119    if let Err(why) = link::suitable(opts.target, &linker) {
3120        return complain(why);
3121    }
3122    // The glibc stubs, which are the one part of a cross sysroot written here rather than fetched.
3123    // Before compiling for the same reason as the rest, and never for `-###`, which writes nothing.
3124    if let Err(why) = link::write_stubs(opts.target, link) {
3125        return complain(why);
3126    }
3127
3128    let scratch = match Scratch::new() {
3129        Ok(scratch) => scratch,
3130        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
3131    };
3132
3133    let fs = OsFileSystem::new();
3134    let mut failed = false;
3135    // One per job, in job order, which is what lets the link line below be rebuilt with the real
3136    // paths in it: every job contributes exactly one file to the line and does so in this order.
3137    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
3138    let mut fired = Fired::new();
3139    let mut pressure = Pressure::new();
3140    let mut lowerings = Lowerings::new();
3141    {
3142        let mut stderr = std::io::stderr().lock();
3143        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3144        failed |= !ok;
3145        for (at, job) in plan.jobs.iter().enumerate() {
3146            let out = match &job.output {
3147                Output::Temporary(hint) => {
3148                    // The index because two inputs in different directories can have the same
3149                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
3150                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
3151                }
3152                Output::File(path) => path.clone(),
3153                // A job feeding the linker never writes to standard output, since the plan gives
3154                // it a temporary. This is here so that the match is total rather than a panic.
3155                Output::Stdout => continue,
3156            };
3157            produced.push(out.clone());
3158            if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3159                continue;
3160            }
3161            let started = std::time::Instant::now();
3162            let result = if needs_an_assembler(job) {
3163                assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3164            } else if job.kind == InputKind::Ir {
3165                compile_ir(opts, &job.input, &fs)
3166            } else {
3167                compile(opts, &job.input, &fs)
3168            };
3169            if opts.time {
3170                say_time(&job.input, started.elapsed(), &mut stderr);
3171            }
3172            failed |= !write_trace(opts, job, started, &result, &mut stderr);
3173            fired.merge(&result.fired);
3174            pressure.merge(&result.pressure);
3175            lowerings.merge(&result.lowerings);
3176            failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3177            failed |= !remarks.write(&result.remarks, &mut stderr);
3178            for message in &result.messages {
3179                let _ = writeln!(stderr, "{message}");
3180            }
3181            failed |= !write_temps(job, &result.temps, &mut stderr);
3182            failed |= !write_stack_usage(job, &result.stack_usage, &mut stderr);
3183            if result.failed() {
3184                failed = true;
3185                continue;
3186            }
3187            // A `-MD` on a command line that links writes the rule next to the executable and
3188            // names the executable as its target, since that is the file this source builds
3189            // here. The object it went through is in a temporary directory and is gone by the
3190            // time `make` reads any of this.
3191            if opts.deps.emit {
3192                failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3193            }
3194            if !matches!(result.artifact, Artifact::Object { .. }) {
3195                // Worth saying rather than writing whatever it is and letting the linker read it.
3196                // An empty file is a valid empty linker script, so a link handed one gets as far
3197                // as reporting every symbol of this file undefined, which is a page of messages
3198                // about something that went wrong here.
3199                let _ = writeln!(
3200                    stderr,
3201                    "rucc: internal error: {}: no object file was produced for the link",
3202                    job.input
3203                );
3204                failed = true;
3205                continue;
3206            }
3207            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
3208                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
3209                failed = true;
3210            }
3211        }
3212        failed |= !write_coverage(opts, &fired, &mut stderr);
3213        failed |= !write_pressure(opts, &pressure, &mut stderr);
3214        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3215        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3216    }
3217    if failed {
3218        // Nothing is linked from a compilation that did not finish. A linker run over the objects
3219        // that did compile would report every function of the file that did not as undefined,
3220        // which is a page of messages about a mistake already reported once.
3221        return 1;
3222    }
3223
3224    // The items in command line order with the temporaries filled in. A library and a word for the
3225    // linker contribute no job and pass through, and every file item takes the next job's real
3226    // output, which is what keeps whatever was written between two objects between them here.
3227    let mut outputs = produced.into_iter();
3228    let mut items = Vec::with_capacity(job.inputs.len());
3229    for item in &job.inputs {
3230        match item {
3231            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
3232            link::Item::Linker(arg) => items.push(link::Item::Linker(arg.clone())),
3233            link::Item::File(_) => match outputs.next() {
3234                Some(path) => items.push(link::Item::File(path)),
3235                None => return complain("the plan asks the linker for a file nothing produced"),
3236            },
3237        }
3238    }
3239
3240    let args = match link::line(opts.target, link, &items, &job.output) {
3241        Ok(args) => args,
3242        Err(why) => return complain(why),
3243    };
3244    if verbose {
3245        let mut stderr = std::io::stderr().lock();
3246        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
3247    }
3248    let started = std::time::Instant::now();
3249    let ran = link::run(&linker, &args);
3250    if opts.time {
3251        // The one step of a compilation that really is another program, so this line is the same
3252        // measurement gcc's is and names the linker the way gcc names `collect2`.
3253        let mut stderr = std::io::stderr().lock();
3254        say_time(&linker.name, started.elapsed(), &mut stderr);
3255    }
3256    match ran {
3257        Ok(()) => 0,
3258        // The linker has already said what was wrong on its own error output, and repeating that
3259        // linking failed would only push its message further up the screen.
3260        Err(link::Error::Refused { .. }) => 1,
3261        Err(why) => complain(why),
3262    }
3263}
3264
3265/// Compiles everything and writes the objects into one static library.
3266///
3267/// No temporary directory and no second program. The objects never reach the file system at all:
3268/// they go from the compiler into the archive writer, which is both faster than writing a directory
3269/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
3270/// member's index entries are the names the object writer says it wrote, and the only thing that
3271/// knows those is the run that wrote it.
3272///
3273/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
3274/// person can find, and they are written there as well as put in the archive.
3275fn archive_all(opts: &Options, plan: &Plan) -> i32 {
3276    let Some(job) = &plan.archive else {
3277        // Every path into here comes from a plan whose last phase is the archive, and such a plan
3278        // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
3279        return complain("there is nothing to put in an archive");
3280    };
3281    // Before anything is compiled, because a format this has no container for is worth knowing
3282    // about in the second it takes to look rather than after the whole compilation.
3283    let flavour = match opts.target.os.object_format() {
3284        ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
3285        ObjectFormat::Coff => rucc_archive::Flavour::Coff,
3286        ObjectFormat::MachO => rucc_archive::Flavour::Bsd,
3287        // Wasm has no archives of its own at all.
3288        format @ ObjectFormat::Wasm => {
3289            return complain(format!(
3290                "there is no archive format for {} objects in this compiler yet",
3291                format.as_str()
3292            ));
3293        }
3294    };
3295
3296    let fs = OsFileSystem::new();
3297    let mut failed = false;
3298    let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
3299    let mut names = job.members.iter();
3300    let mut fired = Fired::new();
3301    let mut pressure = Pressure::new();
3302    let mut lowerings = Lowerings::new();
3303    {
3304        let mut stderr = std::io::stderr().lock();
3305        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3306        failed |= !ok;
3307        for plan_job in &plan.jobs {
3308            // What the plan called this member. The two lists are walked together rather than the
3309            // name being worked out again here, so that what `-###` printed and what goes in the
3310            // file cannot come apart.
3311            let Some(member) = names.next() else {
3312                return complain("the plan asks the archive for a member nothing produced");
3313            };
3314            if !plan_job.phases.contains(&Phase::Compile) && !needs_an_assembler(plan_job) {
3315                // Neither something to compile nor something to assemble, so there is nothing to
3316                // put in, and an archive quietly missing a member is worse than a message.
3317                let _ = writeln!(
3318                    &mut stderr,
3319                    "rucc: error: {}: this compiler makes an archive out of what it compiles, and \
3320                     there is nothing here for it to do",
3321                    plan_job.input
3322                );
3323                failed = true;
3324                continue;
3325            }
3326            let started = std::time::Instant::now();
3327            let result = if needs_an_assembler(plan_job) {
3328                assemble(opts, &plan_job.input, assembly_wants_cpp(plan_job), &fs)
3329            } else if plan_job.kind == InputKind::Ir {
3330                compile_ir(opts, &plan_job.input, &fs)
3331            } else {
3332                compile(opts, &plan_job.input, &fs)
3333            };
3334            if opts.time {
3335                say_time(&plan_job.input, started.elapsed(), &mut stderr);
3336            }
3337            failed |= !write_trace(opts, plan_job, started, &result, &mut stderr);
3338            fired.merge(&result.fired);
3339            pressure.merge(&result.pressure);
3340            lowerings.merge(&result.lowerings);
3341            failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
3342            failed |= !remarks.write(&result.remarks, &mut stderr);
3343            for message in &result.messages {
3344                let _ = writeln!(stderr, "{message}");
3345            }
3346            failed |= !write_temps(plan_job, &result.temps, &mut stderr);
3347            failed |= !write_stack_usage(plan_job, &result.stack_usage, &mut stderr);
3348            if result.failed() {
3349                failed = true;
3350                continue;
3351            }
3352            if opts.deps.emit {
3353                failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
3354            }
3355            let Artifact::Object { bytes, defines } = result.artifact else {
3356                let _ = writeln!(
3357                    stderr,
3358                    "rucc: internal error: {}: no object file was produced for the archive",
3359                    plan_job.input
3360                );
3361                failed = true;
3362                continue;
3363            };
3364            // Under `-save-temps` the plan gave the object a name a person can find, so it is
3365            // written there too. Otherwise it is only ever a member and never a file.
3366            if let Output::File(path) = &plan_job.output {
3367                if let Err(e) = std::fs::write(path, &bytes) {
3368                    let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3369                    failed = true;
3370                }
3371            }
3372            members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
3373        }
3374        failed |= !write_coverage(opts, &fired, &mut stderr);
3375        failed |= !write_pressure(opts, &pressure, &mut stderr);
3376        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3377        failed |= !write_lowering(opts, &lowerings, &mut stderr);
3378    }
3379    if failed {
3380        // Nothing is written from a compilation that did not finish, for the reason the link gives:
3381        // an archive missing the file that failed is one a link reports every name of as undefined,
3382        // which is a page of messages about a mistake already reported once.
3383        return 1;
3384    }
3385
3386    let bytes = match rucc_archive::write(flavour, &members) {
3387        Ok(bytes) => bytes,
3388        // Every one of these is a bug here rather than a program's mistake: the names came from the
3389        // object writer and the bodies came from this process.
3390        Err(why) => return complain(format!("the archive could not be written: {why}")),
3391    };
3392    match std::fs::write(&job.output, &bytes) {
3393        Ok(()) => 0,
3394        Err(e) => complain(format!("{}: {e}", job.output)),
3395    }
3396}
3397
3398/// Prints one driver level message and gives back the exit status that goes with it.
3399fn complain(why: impl std::fmt::Display) -> i32 {
3400    let mut stderr = std::io::stderr().lock();
3401    let _ = writeln!(stderr, "rucc: error: {why}");
3402    1
3403}
3404
3405/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
3406///
3407/// Once for the whole command line rather than once per input, because the question is which
3408/// lowering rules this run of the compiler reached and a file per input would leave the reader
3409/// unioning files to find out something one process already knew.
3410///
3411/// A file that could not be written is a failure and not a warning. What asks for this is a
3412/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
3413fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
3414    let Some(path) = &opts.rule_coverage else { return true };
3415    let Some(table) = coverage::table(opts.target.arch) else {
3416        let _ = writeln!(
3417            stderr,
3418            "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
3419             to report",
3420            opts.target
3421        );
3422        return false;
3423    };
3424    match std::fs::write(path, fired.listing(table)) {
3425        Ok(()) => true,
3426        Err(e) => {
3427            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3428            false
3429        }
3430    }
3431}
3432
3433/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
3434///
3435/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3436/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
3437/// rule table here, since every target this compiles for has an allocator, and a run that reached
3438/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
3439/// produced no code is still an answer and it is the honest one.
3440fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
3441    let Some(path) = &opts.register_pressure else { return true };
3442    match std::fs::write(path, pressure.listing()) {
3443        Ok(()) => true,
3444        Err(e) => {
3445            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3446            false
3447        }
3448    }
3449}
3450
3451/// Writes what `-Zlowering=FILE` asked for, and says whether it could.
3452///
3453/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3454/// not be written is a failure for the reason it gives too. A run that reached no back end writes
3455/// an empty listing rather than nothing, the way [`write_pressure`] does and for the same reason.
3456fn write_lowering(opts: &Options, lowerings: &Lowerings, stderr: &mut impl std::io::Write) -> bool {
3457    let Some(path) = &opts.lowering_dump else { return true };
3458    match std::fs::write(path, lowerings.listing()) {
3459        Ok(()) => true,
3460        Err(e) => {
3461            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3462            false
3463        }
3464    }
3465}
3466
3467/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
3468///
3469/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
3470/// A file rather than the diagnostic stream is what a harness wants: the corpus in
3471/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
3472/// a few thousand remarks mixed into that would bury it.
3473struct Remarks {
3474    /// The file, if there is one.
3475    file: Option<String>,
3476    /// Whether anything has been written to it yet, which decides between truncating and
3477    /// appending. One file holds the whole run rather than the last input in it.
3478    started: bool,
3479}
3480
3481impl Remarks {
3482    /// Prepares the destination, emptying the file if there is one.
3483    ///
3484    /// Emptied here rather than at the first remark, because a run where no pass had anything to
3485    /// say should leave an empty file and not yesterday's. An absent file and an empty one are
3486    /// different facts and something reading this will act on the difference.
3487    fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
3488        let mut ok = true;
3489        if let Some(path) = file {
3490            if let Err(e) = std::fs::write(path, "") {
3491                let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3492                ok = false;
3493            }
3494        }
3495        (Self { file: file.cloned(), started: false }, ok)
3496    }
3497
3498    /// Writes one input's remarks, and says whether that worked.
3499    ///
3500    /// A file that cannot be written is a failure and not a warning, for the reason
3501    /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
3502    /// where nothing happened.
3503    fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
3504        if text.is_empty() {
3505            return true;
3506        }
3507        let Some(path) = &self.file else {
3508            let _ = write!(stderr, "{text}");
3509            return true;
3510        };
3511        let opened = std::fs::OpenOptions::new()
3512            .write(true)
3513            .append(self.started)
3514            .truncate(!self.started)
3515            .create(true)
3516            .open(path);
3517        self.started = true;
3518        let result =
3519            opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
3520        if let Err(e) = result {
3521            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3522            return false;
3523        }
3524        true
3525    }
3526}
3527
3528/// Writes what `-fdump-ir=` asked to see, one file per dump.
3529///
3530/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
3531/// after a run is the passes in the order they ran, per input. They go in the working directory
3532/// rather than beside the output, because a dump is something a person asked for at a prompt and
3533/// the working directory is where that person is.
3534///
3535/// A file that could not be written is a failure and not a warning, for the reason
3536/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
3537/// quietly did not happen looks exactly like a pass that did not run.
3538fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
3539    let stem = std::path::Path::new(input)
3540        .file_name()
3541        .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
3542    let mut ok = true;
3543    for dump in dumps {
3544        let path = format!("{stem}.{}.ir", dump.name);
3545        if let Err(e) = std::fs::write(&path, &dump.text) {
3546            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3547            ok = false;
3548        }
3549    }
3550    ok
3551}
3552
3553/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
3554///
3555/// A file that could not be written is a failure rather than a warning, for the reason
3556/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
3557/// looks like a compilation that never went through that step.
3558fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
3559    let mut ok = true;
3560    let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
3561    for (path, text) in kept {
3562        // A step the compilation did not reach has nothing to keep, and a job that is not keeping
3563        // that step has nowhere to put it. Either way there is no file here.
3564        let (Some(path), Some(text)) = (path, text) else { continue };
3565        if let Err(e) = std::fs::write(&path, text) {
3566            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3567            ok = false;
3568        }
3569    }
3570    ok
3571}
3572
3573/// Writes the `.su` file `-fstack-usage` asked for, where the plan said it goes.
3574///
3575/// Written even when it is empty, because gcc writes an empty `.su` for a file with no functions,
3576/// for `-fsyntax-only` and for a file that did not compile, and a tool that looks for one beside
3577/// every object should find one.
3578fn write_stack_usage(job: &Job, text: &str, stderr: &mut impl std::io::Write) -> bool {
3579    let Some(path) = &job.stack_usage else { return true };
3580    if let Err(e) = std::fs::write(path, text) {
3581        let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3582        return false;
3583    }
3584    true
3585}
3586
3587/// Appends the file's line to the `-frucc-trace` file, when there is one.
3588///
3589/// Returns whether that went well, and says why on standard error when it did not.
3590fn write_trace(
3591    opts: &Options,
3592    job: &Job,
3593    started: std::time::Instant,
3594    result: &Compiled,
3595    stderr: &mut impl std::io::Write,
3596) -> bool {
3597    let Some(path) = &opts.trace else {
3598        return true;
3599    };
3600    let output = match &job.output {
3601        Output::Stdout => "-",
3602        Output::File(path) | Output::Temporary(path) => path,
3603    };
3604    let record = trace::Record {
3605        input: &job.input,
3606        output,
3607        ok: !result.failed(),
3608        total: started.elapsed(),
3609        timing: &result.timing,
3610    };
3611    match trace::append(path, &record) {
3612        Ok(()) => true,
3613        Err(e) => {
3614            let _ = writeln!(stderr, "rucc: error: {e}");
3615            false
3616        }
3617    }
3618}
3619
3620/// One line of `-time`, which is what a step was called and how long it took.
3621///
3622/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
3623/// no subprocess for anything but the link, so what is measured here is the wall clock of the
3624/// step and the second column is always zero. The shape of the line is kept because a person
3625/// reading it next to gcc's should not have to work out which column is which.
3626fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
3627    let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
3628}
3629
3630/// Writes one job's result where the plan said it goes.
3631///
3632/// # Errors
3633///
3634/// Returns the message to print, which names the file when there is one, because "permission
3635/// denied" on its own does not say which file was refused.
3636fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
3637    match output {
3638        Output::Stdout => {
3639            let mut stdout = std::io::stdout().lock();
3640            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
3641        }
3642        Output::File(path) | Output::Temporary(path) => {
3643            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
3644        }
3645    }
3646}
3647
3648/// The target a program name asks for, the way `aarch64-linux-gnu-gcc` is gcc for that target.
3649///
3650/// `program` is the path the compiler was started as. The name without its directory and without a
3651/// trailing `.exe` has to end in `-rucc`, and what comes before that has to be a target this
3652/// compiler knows, or there is no answer and the name means nothing. A link named `my-rucc` is
3653/// therefore just rucc and not an error.
3654pub fn target_from_program(program: &str) -> Option<String> {
3655    let name = program.rsplit(['/', '\\']).next()?;
3656    let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
3657    let triple = name.strip_suffix("-rucc")?;
3658    triple.parse::<Triple>().ok()?;
3659    Some(triple.to_owned())
3660}
3661
3662/// [`run`] for a compiler started as `program`, which is `argv[0]`.
3663///
3664/// A target taken from the name goes in front of `args`, so a `--target=` written on the command
3665/// line comes later and wins, which is what gcc and clang do with a prefixed name.
3666pub fn run_as(program: &str, args: &[String]) -> i32 {
3667    match target_from_program(program) {
3668        Some(triple) => {
3669            let mut all = Vec::with_capacity(args.len() + 1);
3670            all.push(format!("--target={triple}"));
3671            all.extend_from_slice(args);
3672            run(&all)
3673        }
3674        None => run(args),
3675    }
3676}
3677
3678/// What `--version` prints.
3679///
3680/// The first line is ours and is the one every harness we have reads. The second is for build
3681/// systems that decide what kind of compiler they have by reading this text. Meson takes the GNU
3682/// path only when it finds "Free Software Foundation" here, and otherwise stops with "Unknown
3683/// compiler" before it has asked a single question, which is how the whole of a meson build is
3684/// lost to one sentence. Past that point meson reads the version from `__GNUC__` and asks the
3685/// preprocessor everything else, so the line decides the path and nothing more. It says what is
3686/// true, that rucc speaks the dialect of GCC 16, and it does not claim to be GCC.
3687fn banner() -> String {
3688    format!(
3689        "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"
3690    )
3691}
3692
3693/// Runs the driver and returns the process exit code.
3694///
3695/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
3696/// is the one place in the compiler that is true.
3697pub fn run(args: &[String]) -> i32 {
3698    match parse_args(args) {
3699        Ok(Action::Help) => {
3700            print!("{USAGE}");
3701            0
3702        }
3703        Ok(Action::Version) => {
3704            print!("{}", banner());
3705            0
3706        }
3707        Ok(Action::Print(line)) => {
3708            println!("{line}");
3709            0
3710        }
3711        Ok(Action::PrintConfig(opts)) => {
3712            print!("{}", print_config(&opts));
3713            0
3714        }
3715        Ok(Action::PrintPipeline(opts)) => {
3716            print!("{}", print_pipeline(&opts));
3717            0
3718        }
3719        Ok(Action::PrintPlan { opts, plan, link }) => {
3720            print!("{}", plan.render());
3721            // The line as it would be typed, which is the half of `-###` that section 4.3 says
3722            // arrives with the link. It is printed even when the linker is not on this machine,
3723            // because what a build wants from `-###` is what the compiler would do.
3724            if let Some(job) = &plan.link {
3725                match link_line(&opts, &link, job) {
3726                    Ok(line) => println!("{line}"),
3727                    Err(why) => {
3728                        let mut stderr = std::io::stderr().lock();
3729                        let _ = writeln!(stderr, "rucc: error: {why}");
3730                        return 1;
3731                    }
3732                }
3733            }
3734            0
3735        }
3736        Ok(Action::Fetch { what, target, cache }) => {
3737            let kernel = rucc_sysroot::Kernel::for_target(&cache, target)
3738                .map(|_| &rucc_sysroot::KERNEL_HEADERS);
3739            fetch_sysroot(what, kernel, target, &cache)
3740        }
3741        Ok(Action::FetchMsvcSdk { target, accepted, cache }) => {
3742            msvc::fetch_msvc_sdk(target, accepted, &cache)
3743        }
3744        Ok(Action::Compile { opts, plan, link, jobs, verbose, notes }) => {
3745            {
3746                let mut stderr = std::io::stderr().lock();
3747                // Before the plan rather than after it, because a note is about the command line
3748                // and the plan is what the command line was read as, so the reader wants the two
3749                // in that order.
3750                for note in &notes {
3751                    let _ = writeln!(stderr, "rucc: warning: {note}");
3752                }
3753                if verbose {
3754                    let _ = write!(stderr, "{}", plan.render());
3755                    let _ = writeln!(stderr, "workers: {}", jobs.count());
3756                    // What `gcc -v` says about headers, because meson and cmake read it to find the
3757                    // system directories.
3758                    let _ = write!(stderr, "{}", opts.search.render_gcc());
3759                }
3760            }
3761            if opts.emit == EmitKind::Preprocessed {
3762                return preprocess_all(&opts, &plan);
3763            }
3764            if opts.emit == EmitKind::Archive {
3765                return archive_all(&opts, &plan);
3766            }
3767            if opts.emit != EmitKind::Executable {
3768                return compile_all(&opts, &plan);
3769            }
3770            link_all(&opts, &plan, &link, verbose)
3771        }
3772        Err(e) => {
3773            let mut stderr = std::io::stderr().lock();
3774            let _ = writeln!(stderr, "rucc: error: {e}");
3775            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
3776            1
3777        }
3778    }
3779}
3780
3781#[cfg(test)]
3782mod tests {
3783    use rucc_session::{
3784        Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
3785    };
3786
3787    use super::*;
3788
3789    fn args(s: &[&str]) -> Vec<String> {
3790        s.iter().map(|x| (*x).to_owned()).collect()
3791    }
3792
3793    /// A target to write down where the host would otherwise decide, for the tests whose answer
3794    /// would be a different one on a different machine.
3795    ///
3796    /// Most of the tests here never name a target, which is right, because most of what the driver
3797    /// does with a command line is the same wherever it runs and a test that pinned one would be
3798    /// saying so in every case for the sake of the two that need it. The two that need it are the
3799    /// ones whose answer comes off the target rather than off the command line: the name an object
3800    /// gets, which is `a.o` here and `a.obj` on Windows, and whether Microsoft's reading of a
3801    /// nameless member is on, which is off here and on there. Both are the compiler being right, and
3802    /// a test that leaves the target to the host is asking a question with two correct answers.
3803    const LINUX: &str = "--target=x86_64-unknown-linux-gnu";
3804
3805    #[test]
3806    fn a_response_file_is_split_the_way_libiberty_splits_one() {
3807        let words = response_words("-Wl,--as-needed  'a b' \"c d\"\ne\\ f '' \"it's\" g\\\\h\n");
3808        assert_eq!(words, ["-Wl,--as-needed", "a b", "c d", "e f", "", "it's", "g\\h"]);
3809        assert!(response_words(" \n\t").is_empty());
3810    }
3811
3812    #[test]
3813    fn a_response_file_on_the_command_line_is_read_in_its_place() {
3814        let dir = std::env::temp_dir().join(format!("rucc-rsp-{}", std::process::id()));
3815        std::fs::create_dir_all(&dir).unwrap();
3816        let inner = dir.join("inner.rsp");
3817        std::fs::write(&inner, "-lm\n").unwrap();
3818        let outer = dir.join("outer.rsp");
3819        std::fs::write(&outer, format!("-o 'my prog' -Wl,--as-needed @{}\n", inner.display()))
3820            .unwrap();
3821        let line = args(&["x.o", &format!("@{}", outer.display()), "@no-such-file"]);
3822        assert_eq!(
3823            response_files(&line).unwrap(),
3824            args(&["x.o", "-o", "my prog", "-Wl,--as-needed", "-lm", "@no-such-file"])
3825        );
3826        let itself = dir.join("itself.rsp");
3827        std::fs::write(&itself, format!("@{}", itself.display())).unwrap();
3828        let looped = response_files(&args(&[&format!("@{}", itself.display())]));
3829        assert!(looped.is_err(), "a file that names itself should be refused");
3830        std::fs::remove_dir_all(&dir).unwrap();
3831    }
3832
3833    #[test]
3834    fn help_and_version_win_over_everything_else() {
3835        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
3836        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
3837    }
3838
3839    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
3840        match parse_args(&args(s)).expect("expected a compilation") {
3841            Action::Compile { opts, plan, .. } => (opts, plan),
3842            other => panic!("expected a compilation, got {other:?}"),
3843        }
3844    }
3845
3846    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
3847        match parse_args(&args(s)).expect("expected a compilation") {
3848            Action::Compile { link, plan, .. } => (link, plan),
3849            other => panic!("expected a compilation, got {other:?}"),
3850        }
3851    }
3852
3853    fn notes(s: &[&str]) -> Vec<String> {
3854        match parse_args(&args(s)).expect("expected a compilation") {
3855            Action::Compile { notes, .. } => notes,
3856            other => panic!("expected a compilation, got {other:?}"),
3857        }
3858    }
3859
3860    /// The ordinary command line has nothing to say about itself, which is the property that makes
3861    /// a note worth reading when there is one.
3862    #[test]
3863    fn a_command_line_with_nothing_wrong_with_it_carries_no_notes() {
3864        assert_eq!(notes(&["-c", "a.c"]), Vec::<String>::new());
3865    }
3866
3867    /// A directory that is not there contributes nothing to the search path, so there is no tree to
3868    /// read a release out of and nothing to compare the pin against. Said as a test because this is
3869    /// the shape a hermetic machine takes: the probe reads the disk and every other machine has a
3870    /// different disk, so what can be asserted here is the silence.
3871    #[test]
3872    fn a_named_tree_that_is_not_on_the_machine_is_not_a_release_mismatch() {
3873        let said =
3874            notes(&["--target=x86_64-linux-gnu.2.28", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3875        assert_eq!(said, Vec::<String>::new());
3876    }
3877
3878    #[test]
3879    fn collects_inputs_and_flags() {
3880        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
3881        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
3882        assert_eq!(paths, vec!["a.c", "b.c"]);
3883        assert_eq!(opts.opt_level, OptLevel::O2);
3884        assert_eq!(opts.emit, EmitKind::Object);
3885        assert!(opts.debug_info);
3886    }
3887
3888    /// The unstable options, which are spelled apart from everything else on purpose: what is
3889    /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
3890    #[test]
3891    fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
3892        let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
3893        assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
3894
3895        let (plain, _) = compile(&["-c", "a.c"]);
3896        assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
3897
3898        assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
3899        let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
3900        assert!(unknown.message.contains("4.11"), "{}", unknown.message);
3901    }
3902
3903    /// The other measurement written to a file, which reads the same way and fails the same way.
3904    #[test]
3905    fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
3906        let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
3907        assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
3908
3909        let (plain, _) = compile(&["-c", "a.c"]);
3910        assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
3911
3912        assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
3913    }
3914
3915    /// The third one, which says what the pre-selection lowering group did.
3916    #[test]
3917    fn a_switch_shape_is_forced_by_name_and_only_by_one_it_has() {
3918        let (opts, _) = compile(&["-c", "-O2", "-Zswitch=walk", "a.c"]);
3919        assert_eq!(opts.switch_shape.as_deref(), Some("walk"));
3920        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3921        assert_eq!(plain.switch_shape, None, "nothing is forced unless it was asked for");
3922        assert!(parse_args(&args(&["-Zswitch=bit-test", "a.c"])).is_err(), "not a shape it forces");
3923    }
3924
3925    #[test]
3926    fn where_the_lowering_dump_goes_is_asked_for_the_same_way() {
3927        let (opts, _) = compile(&["-c", "-O2", "-Zlowering=/tmp/lowering.txt", "a.c"]);
3928        assert_eq!(opts.lowering_dump.as_deref(), Some("/tmp/lowering.txt"));
3929
3930        let (plain, _) = compile(&["-c", "a.c"]);
3931        assert_eq!(plain.lowering_dump, None, "nothing is dumped unless it was asked for");
3932
3933        assert!(parse_args(&args(&["-Zlowering=", "a.c"])).is_err(), "no file named");
3934    }
3935
3936    /// Scheduling, which has the three way answer every optimization flag has: on, off, and
3937    /// nothing said, which is whatever the optimization level asks for. The name is gcc's, and
3938    /// gcc's has a two in it because gcc has a scheduler before allocation and one after and this
3939    /// is the one after.
3940    #[test]
3941    fn scheduling_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
3942        let (on, _) = compile(&["-c", "-O0", "-fschedule-insns2", "a.c"]);
3943        assert_eq!(on.schedule_insns, Some(true));
3944
3945        let (off, _) = compile(&["-c", "-O2", "-fno-schedule-insns2", "a.c"]);
3946        assert_eq!(off.schedule_insns, Some(false));
3947
3948        let (quiet, _) = compile(&["-c", "-O2", "a.c"]);
3949        assert_eq!(quiet.schedule_insns, None, "nothing said, so the level decides");
3950        assert!(quiet.opt_level.schedules(), "and at this level the level says yes");
3951
3952        let (none, _) = compile(&["-c", "a.c"]);
3953        assert!(!none.opt_level.schedules(), "at no optimization it says no");
3954    }
3955
3956    /// Tail calls, which gcc spells as sibling calls and turns on at `-O2` and `-Os`.
3957    #[test]
3958    fn sibling_calls_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
3959        let (on, _) = compile(&["-c", "-O1", "-foptimize-sibling-calls", "a.c"]);
3960        assert_eq!(on.sibling_calls, Some(true));
3961
3962        let (off, _) = compile(&["-c", "-O2", "-fno-optimize-sibling-calls", "a.c"]);
3963        assert_eq!(off.sibling_calls, Some(false));
3964
3965        let (quiet, _) = compile(&["-c", "-Os", "a.c"]);
3966        assert_eq!(quiet.sibling_calls, None, "nothing said, so the level decides");
3967        assert!(quiet.opt_level.sibling_calls(), "and at this level the level says yes");
3968
3969        let (one, _) = compile(&["-c", "-O1", "a.c"]);
3970        assert!(!one.opt_level.sibling_calls(), "gcc leaves them off at -O1");
3971    }
3972
3973    /// Whether the timing model is worth holding an instruction back over, which is a `-Z` because
3974    /// it is a question about a target's description rather than about the program being compiled.
3975    #[test]
3976    fn whether_the_timing_model_is_cycle_accurate_can_be_overridden() {
3977        let (yes, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=yes", "a.c"]);
3978        assert_eq!(yes.cycle_accurate_model, Some(true));
3979
3980        let (no, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=no", "a.c"]);
3981        assert_eq!(no.cycle_accurate_model, Some(false));
3982
3983        let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3984        assert_eq!(plain.cycle_accurate_model, None, "the target's own answer stands");
3985
3986        let bad = parse_args(&args(&["-Zcycle-accurate-model=maybe", "a.c"]))
3987            .expect_err("it takes yes or no");
3988        assert!(bad.message.contains("yes or no"), "{}", bad.message);
3989    }
3990
3991    #[test]
3992    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
3993        let (opts, _) = compile(&["-O", "a.c"]);
3994        assert_eq!(opts.opt_level, OptLevel::O1);
3995    }
3996
3997    #[test]
3998    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
3999        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
4000        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4001        assert_eq!(plan.jobs[1].kind, InputKind::C);
4002        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4003    }
4004
4005    #[test]
4006    fn dash_x_can_be_joined_to_its_language() {
4007        let (_, plan) = compile(&["a.o", "-xc", "b.txt", "-xnone", "c.o"]);
4008        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
4009        assert_eq!(plan.jobs[1].kind, InputKind::C);
4010        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
4011    }
4012
4013    #[test]
4014    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
4015        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
4016            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
4017            other => panic!("expected a compilation, got {other:?}"),
4018        };
4019        assert_eq!(jobs.count(), 4);
4020
4021        let default = match parse_args(&args(&["a.c"])).unwrap() {
4022            Action::Compile { jobs, .. } => jobs,
4023            other => panic!("expected a compilation, got {other:?}"),
4024        };
4025        assert_eq!(default, Jobs::available());
4026        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
4027    }
4028
4029    #[test]
4030    fn triple_hash_prints_the_plan_and_runs_nothing() {
4031        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
4032        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
4033        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
4034    }
4035
4036    #[test]
4037    fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
4038        // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
4039        // this, and following the compiler is what makes a build that reads either of them find
4040        // the files where they are.
4041        assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
4042        assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
4043        assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
4044        assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
4045        // The last one on the line decides, the way it does for every other flag with an
4046        // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
4047        // nothing and said nothing looks exactly like one where the files were not produced.
4048        let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
4049        assert_eq!(opts.save_temps, SaveTemps::Cwd);
4050        let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
4051        assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
4052    }
4053
4054    #[test]
4055    fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
4056        let (opts, plan) = compile(&["-c", "-time", "a.c"]);
4057        let (plain, without) = compile(&["-c", "a.c"]);
4058        assert!(opts.time);
4059        assert!(!plain.time);
4060        // Against the same line without the flag rather than against a spelling of the object's
4061        // name, since what the object is called is the host's business and this is not about that.
4062        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4063    }
4064
4065    #[test]
4066    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
4067        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
4068        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
4069    }
4070
4071    /// What `--fetch` says for a target this release pins nothing for, which today is every target
4072    /// but the three windows-gnu ones, the four musl ones and the eight glibc ones.
4073    #[test]
4074    fn a_fetch_of_a_target_nothing_is_pinned_for_says_so_rather_than_reaching_the_network() {
4075        let e = parse_args(&args(&["--fetch", "x86_64-linux-gnux32"])).unwrap_err();
4076        assert!(e.message.contains("pins no sysroot for x86_64-linux-gnux32"), "{}", e.message);
4077        // And what it does pin, because a release with some rows in the table and a release with
4078        // none are two situations and the second sentence is what tells them apart.
4079        assert!(e.message.contains("x86_64-windows-gnu"), "{}", e.message);
4080        // The joined spelling is the same flag.
4081        let joined = parse_args(&args(&["--fetch=x86_64-linux-gnux32"])).unwrap_err();
4082        assert_eq!(joined, e);
4083    }
4084
4085    /// The two targets a release will never pin, which is a different answer from the one above.
4086    ///
4087    /// Section 13.4. A person who reads "this release pins no sysroot yet" waits for a release that
4088    /// does, and no release of this compiler can ship either of these, so the message names the
4089    /// licence that decides it and what to do instead.
4090    #[test]
4091    fn a_fetch_of_a_target_behind_a_licence_wall_says_so_rather_than_saying_not_yet() {
4092        let e = parse_args(&args(&["--fetch", "aarch64-macos"])).unwrap_err();
4093        assert!(e.message.contains("Xcode licence"), "{}", e.message);
4094        assert!(e.message.contains("there never will be"), "{}", e.message);
4095        assert!(!e.message.contains("tamnd/rucc-cross"), "{}", e.message);
4096
4097        let e = parse_args(&args(&["--fetch", "x86_64-windows-msvc"])).unwrap_err();
4098        assert!(e.message.contains("redistributed"), "{}", e.message);
4099        // The way out of this one is a target rather than a download, and it is the default already.
4100        assert!(e.message.contains("mingw-w64"), "{}", e.message);
4101        // And the mingw-w64 target next to it is ours to ship and published, so the same flag has
4102        // something to get rather than a licence to explain.
4103        let action = parse_args(&args(&["--fetch", "x86_64-windows-gnu"])).expect("it is pinned");
4104        let Action::Fetch { what, .. } = action else { panic!("{action:?}") };
4105        assert_eq!(what.tuple, "x86_64-windows-gnu");
4106    }
4107
4108    #[test]
4109    fn the_other_fetch_takes_a_target_behind_microsofts_wall_and_carries_the_acceptance() {
4110        // Both spellings of the flag, because a flag that takes a tuple gets written both ways.
4111        for line in [
4112            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc"],
4113            vec!["--fetch-msvc-sdk=x86_64-windows-msvc"],
4114        ] {
4115            let action = parse_args(&args(&line)).expect("that is a target behind the wall");
4116            let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4117                panic!("{action:?}")
4118            };
4119            assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
4120            // Nothing on the line accepted anything, so nothing did.
4121            assert!(!accepted);
4122        }
4123
4124        // And both spellings of the word, because the prose here uses one and most of the people
4125        // typing this will reach for the other.
4126        for word in ["--accept-licence", "--accept-license"] {
4127            let action = parse_args(&args(&["--fetch-msvc-sdk", "aarch64-windows-msvc", word]))
4128                .expect("that is a target behind the wall");
4129            let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4130                panic!("{action:?}")
4131            };
4132            assert_eq!(target.to_canonical_string(), "aarch64-windows-msvc");
4133            assert!(accepted, "{word} should have been read");
4134        }
4135    }
4136
4137    #[test]
4138    fn the_other_fetch_refuses_the_command_lines_that_do_not_mean_anything() {
4139        // A tuple is what it gets, so a flag with nothing after it is not a command.
4140        let e = parse_args(&args(&["--fetch-msvc-sdk"])).unwrap_err();
4141        assert!(e.message.contains("requires the target"), "{}", e.message);
4142        let e = parse_args(&args(&["--fetch-msvc-sdk", "not-a-target"])).unwrap_err();
4143        assert!(e.message.contains("there is no SDK to get"), "{}", e.message);
4144
4145        // `--offline` forbids every download and this one asks for one, whichever order they came
4146        // in, which is the same answer `--fetch` gives.
4147        for line in [
4148            vec!["--offline", "--fetch-msvc-sdk", "x86_64-windows-msvc"],
4149            vec!["--fetch-msvc-sdk", "x86_64-windows-msvc", "--offline"],
4150        ] {
4151            let e = parse_args(&args(&line)).unwrap_err();
4152            assert!(e.message.contains("two opposite things"), "{}", e.message);
4153        }
4154
4155        // It gets an SDK and compiles nothing, so a file on the same line would be read by nothing.
4156        let e = parse_args(&args(&["--fetch-msvc-sdk", "x86_64-windows-msvc", "a.c"])).unwrap_err();
4157        assert!(e.message.contains("compiles nothing"), "{}", e.message);
4158
4159        // The two fetches are two commands and a line that asked for both asked for neither.
4160        let e = parse_args(&args(&[
4161            "--fetch",
4162            "x86_64-windows-gnu",
4163            "--fetch-msvc-sdk",
4164            "x86_64-windows-msvc",
4165        ]))
4166        .unwrap_err();
4167        assert!(e.message.contains("two different commands"), "{}", e.message);
4168
4169        // And an acceptance with nothing to accept for is a command line that says something about
4170        // a licence no part of it goes near.
4171        let e = parse_args(&args(&["--accept-licence", "-c", "a.c"])).unwrap_err();
4172        assert!(e.message.contains("--fetch-msvc-sdk <tuple> is the command"), "{}", e.message);
4173    }
4174
4175    /// An Apple target on a machine with no SDK, which is section 8.6's other host.
4176    ///
4177    /// Not run on a mac, where the SDK this is about is installed and the compile is the ordinary one
4178    /// that uses it. What the reason says is asserted in `rucc_sysroot::wall` and where it is printed
4179    /// is asserted in `rucc-pp`, so what is left here is that the driver works it out and leaves it
4180    /// where the preprocessor will find it, and that neither way past the wall leaves one behind.
4181    #[test]
4182    fn an_apple_target_with_no_sdk_anywhere_carries_the_licence_rather_than_a_missing_directory() {
4183        if cfg!(target_os = "macos") || std::env::var_os("SDKROOT").is_some() {
4184            return;
4185        }
4186        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4187        let why = opts.search.missing_system().expect("the wall is the reason there are none");
4188        assert!(why.contains("aarch64-macos needs a macOS SDK"), "{why}");
4189        assert!(why.contains("Xcode licence"), "{why}");
4190        assert!(why.contains("-isysroot"), "{why}");
4191
4192        // A program that includes none of the library needs none of the SDK, which is what section
4193        // 8.6 means by being able to target the platform without one, so there is nothing to explain.
4194        let (opts, _) = compile(&["--target=aarch64-macos", "-nostdinc", "-c", "a.c"]);
4195        assert_eq!(opts.search.missing_system(), None);
4196        // And naming a path is the other way through, whether or not the path is there: a mistyped
4197        // directory is a mistake to report on its own terms rather than a licence to explain.
4198        let (opts, _) = compile(&["--target=aarch64-macos", "-isysroot", "/opt/sdk", "-c", "a.c"]);
4199        assert_eq!(opts.search.missing_system(), None);
4200    }
4201
4202    /// The same wall on the compile side of an MSVC target, where the way past it is a tuple.
4203    ///
4204    /// Not run on Windows, for the same reason the one above is not run on a mac: the wall stands in
4205    /// front of an SDK this machine does not have, and a Windows machine is the kind that does. The
4206    /// driver asks `vswhere` where Visual Studio is and takes the newest kit under it, so on a box
4207    /// with the build tools installed there are headers, no wall and nothing here to be about.
4208    /// `INCLUDE` is the other way a machine has one and is the other half of the guard, since a
4209    /// person can set that anywhere while Visual Studio is only found on the platform it runs on.
4210    #[test]
4211    fn an_msvc_target_with_no_sdk_named_says_which_environment_needs_nothing_installed() {
4212        if cfg!(target_os = "windows") || std::env::var_os("INCLUDE").is_some() {
4213            return;
4214        }
4215        let (opts, _) = compile(&["--target=x86_64-windows-msvc", "-c", "a.c"]);
4216        let why = opts.search.missing_system().expect("the wall is the reason there are none");
4217        assert!(why.contains("the Windows SDK and its universal CRT"), "{why}");
4218        assert!(why.contains("mingw-w64"), "{why}");
4219        // And the mingw-w64 target has its headers from us, so nothing is missing to explain.
4220        let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-c", "a.c"]);
4221        assert_eq!(opts.search.missing_system(), None);
4222    }
4223
4224    #[test]
4225    fn a_fetch_with_no_target_and_a_fetch_of_a_tuple_that_is_not_one_both_say_which() {
4226        let e = parse_args(&args(&["--fetch"])).unwrap_err();
4227        assert!(e.message.contains("--fetch requires"), "{}", e.message);
4228        let e = parse_args(&args(&["--fetch", "sparc64-solaris-gnu"])).unwrap_err();
4229        assert!(e.message.contains("--fetch sparc64-solaris-gnu"), "{}", e.message);
4230        assert!(e.message.contains("no sysroot to get"), "{}", e.message);
4231    }
4232
4233    /// Both flags on one line ask for opposite things, in either order.
4234    #[test]
4235    fn a_fetch_and_offline_together_is_a_refusal_whichever_way_round_they_are_written() {
4236        for line in [
4237            vec!["--offline", "--fetch", "x86_64-linux-musl"],
4238            vec!["--fetch", "x86_64-linux-musl", "--offline"],
4239        ] {
4240            let e = parse_args(&args(&line)).unwrap_err();
4241            assert!(e.message.contains("two opposite things"), "{}", e.message);
4242        }
4243    }
4244
4245    #[test]
4246    fn a_fetch_does_not_compile_anything_and_says_so_when_it_is_handed_a_file() {
4247        let e = parse_args(&args(&["--fetch", "x86_64-linux-musl", "a.c"])).unwrap_err();
4248        assert!(e.message.contains("compiles nothing"), "{}", e.message);
4249        assert!(e.message.contains("a.c"), "{}", e.message);
4250    }
4251
4252    /// `--offline` on its own is accepted and changes nothing, because an ordinary compile
4253    /// downloads nothing with or without it. A build that passes it everywhere is the case this is
4254    /// for, and it must not lose the compilation it was passed beside.
4255    #[test]
4256    fn offline_on_a_compilation_is_the_same_compilation() {
4257        let (opts, plan) = compile(&["-c", "--offline", "a.c"]);
4258        let (plain, without) = compile(&["-c", "a.c"]);
4259        assert_eq!(opts.target, plain.target);
4260        assert_eq!(plan.jobs.len(), without.jobs.len());
4261        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4262    }
4263
4264    #[test]
4265    fn a_deployment_target_comes_from_the_tuple_or_from_the_flag() {
4266        let version = |v: &str| rucc_tuple::Version::parse(v);
4267        let (opts, _) = compile(&["--target=aarch64-macos.13", "-c", "a.c"]);
4268        assert_eq!(opts.target, "aarch64-apple-darwin".parse().unwrap());
4269        assert_eq!(opts.os_version, version("13"));
4270        // The flag wins over the tuple, as it does under clang, and either spelling of it works.
4271        let (opts, _) =
4272            compile(&["--target=aarch64-macos.13", "-mmacosx-version-min=14.2", "-c", "a.c"]);
4273        assert_eq!(opts.os_version, version("14.2"));
4274        let (opts, _) = compile(&["--target=x86_64-macos", "-mmacos-version-min=12", "-c", "a.c"]);
4275        assert_eq!(opts.os_version, version("12"));
4276        // Nothing said leaves the platform's default to the target description.
4277        let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4278        assert_eq!(opts.os_version, None);
4279        // A Linux build that always passes the flag is not an Apple build because of it.
4280        let (opts, _) =
4281            compile(&["--target=aarch64-linux-gnu", "-mmacosx-version-min=13", "-c", "a.c"]);
4282        assert_eq!(opts.os_version, None);
4283        let e = parse_args(&args(&["-mmacosx-version-min=thirteen", "a.c"])).unwrap_err();
4284        assert!(e.message.contains("is not a version"), "{}", e.message);
4285    }
4286
4287    #[test]
4288    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
4289        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
4290        assert!(e.message.contains("unknown option"), "{}", e.message);
4291    }
4292
4293    /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
4294    /// one directory needs the older rules and the rest of the tree does not.
4295    #[test]
4296    fn permissive_reads_in_both_directions_and_the_last_one_wins() {
4297        let (opts, _) = compile(&["-c", "a.c"]);
4298        assert!(!opts.permissive, "off unless it is asked for");
4299
4300        let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
4301        assert!(opts.permissive);
4302
4303        let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
4304        assert!(!opts.permissive);
4305    }
4306
4307    #[test]
4308    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
4309        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
4310        assert!(e.message.contains("trampoline"), "{}", e.message);
4311        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
4312    }
4313
4314    #[test]
4315    fn the_flag_every_configure_script_writes_is_taken() {
4316        // All four spellings, because a build writes whichever one its macros picked and a
4317        // compiler that takes three of them is a compiler that fails on the fourth.
4318        for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
4319            let (opts, _) = compile(&["-c", flag, "a.c"]);
4320            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4321        }
4322    }
4323
4324    #[test]
4325    fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
4326        let (opts, _) = compile(&["-c", "a.c"]);
4327        assert!(opts.unwinds(), "the default is off");
4328        let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
4329        assert!(!opts.unwinds(), "the build was not taken at its word");
4330        let (opts, _) = compile(&[
4331            "-c",
4332            "-fno-asynchronous-unwind-tables",
4333            "-fasynchronous-unwind-tables",
4334            "a.c",
4335        ]);
4336        assert!(opts.unwinds(), "the last flag did not win");
4337        // The weaker request, which the same table answers, so a line that asks for a table and
4338        // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
4339        // build turns the asynchronous one off globally and a directory asks for a table back.
4340        let (opts, _) =
4341            compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
4342        assert!(opts.unwinds(), "the weaker request was dropped");
4343        let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
4344        assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
4345        let (opts, _) =
4346            compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
4347        assert!(!opts.unwinds(), "both were turned off and one stayed on");
4348    }
4349
4350    #[test]
4351    fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
4352        // Every one of these is on a real build line somewhere and every one of them was an
4353        // unknown option. What they have in common is that the answer rucc gives is the answer
4354        // they ask for, so there is nothing to implement and nothing to refuse.
4355        for flag in [
4356            "-fno-common",
4357            "-fstrict-aliasing",
4358            "-fno-strict-aliasing",
4359            "-fdelete-null-pointer-checks",
4360            "-fno-delete-null-pointer-checks",
4361            "-frounding-math",
4362            "-fno-rounding-math",
4363            "-fexcess-precision=standard",
4364            "-fexcess-precision=fast",
4365            "-fexcess-precision=16",
4366            "-pipe",
4367            "-cpp",
4368            "-fdiagnostics-color",
4369            "-fno-diagnostics-color",
4370            "-fdiagnostics-color=always",
4371            "-fdiagnostics-color=never",
4372            "-fdiagnostics-color=auto",
4373        ] {
4374            let (opts, _) = compile(&["-c", flag, "a.c"]);
4375            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4376        }
4377    }
4378
4379    #[test]
4380    fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
4381        let (opts, _) = compile(&["-c", "a.c"]);
4382        assert!(opts.trapping_math, "the default was not gcc's");
4383        let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
4384        assert!(!opts.trapping_math);
4385        let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
4386        assert!(opts.trapping_math, "spelling out the default turned it off");
4387        // The last one written wins, which is how a build line that inherits a flag from one
4388        // place and overrides it in another is read.
4389        let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
4390        assert!(opts.trapping_math);
4391    }
4392
4393    /// The flags a torture program writes on its own `dg-options` line, which is where most of
4394    /// these come from: a program reduced from a miscompilation names the pass that miscompiled
4395    /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
4396    /// tamnd/rucc#1019 is the list.
4397    #[test]
4398    fn no_inline_turns_off_the_inlining_of_a_function_declared_inline() {
4399        let (opts, _) = compile(&["-c", "-O2", "-fno-inline", "a.c"]);
4400        assert_eq!(opts.passes, [(rucc_opt::inline::NAME.to_owned(), false)]);
4401    }
4402
4403    #[test]
4404    fn inlining_a_function_called_once_is_turned_off_and_on_by_its_own_flag() {
4405        for level in ["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz", "-Og"] {
4406            let (opts, _) = compile(&["-c", level, "-fno-inline-functions-called-once", "a.c"]);
4407            assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), false)], "{level}");
4408            let (opts, _) = compile(&["-c", level, "-finline-functions-called-once", "a.c"]);
4409            assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), true)], "{level}");
4410        }
4411    }
4412
4413    #[test]
4414    fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
4415        for flag in [
4416            "-fno-tree-ccp",
4417            "-fno-tree-dominator-opts",
4418            "-fno-tree-vrp",
4419            "-fno-tree-bit-ccp",
4420            "-fno-tree-coalesce-vars",
4421            "-ftree-vectorize",
4422            "-ftree-loop-distribution",
4423            "-fipa-pta",
4424            "-fmodulo-sched",
4425            "-fno-vect-cost-model",
4426            "-fvect-cost-model=unlimited",
4427            "-fsimd-cost-model=cheap",
4428            "-fexpensive-optimizations",
4429            "-fno-early-inlining",
4430            "-finline-functions",
4431            "-foptimize-strlen",
4432            "-fno-ira-share-spill-slots",
4433        ] {
4434            let (opts, _) = compile(&["-c", flag, "a.c"]);
4435            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4436            assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
4437        }
4438    }
4439
4440    /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
4441    /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
4442    #[test]
4443    fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
4444        for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
4445            let (opts, _) = compile(&["-c", flag, "a.c"]);
4446            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4447        }
4448    }
4449
4450    /// A pass this compiler has keeps its flag, since the arms that read the registry are above
4451    /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
4452    /// is the program that writes it.
4453    #[test]
4454    fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
4455        let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
4456        assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
4457    }
4458
4459    /// gcc's name for the unroller reaches the unroller, in both directions. libtommath puts
4460    /// `-funroll-loops` in `CFLAGS` unconditionally, and before this it was an unknown option and
4461    /// the build stopped on its first file.
4462    #[test]
4463    fn the_gcc_spelling_of_the_unroller_turns_the_unroller_on_and_off() {
4464        let (opts, _) = compile(&["-c", "-funroll-loops", "a.c"]);
4465        assert_eq!(opts.passes, vec![("unroll".to_owned(), true)]);
4466        let (opts, _) = compile(&["-c", "-fno-unroll-loops", "a.c"]);
4467        assert_eq!(opts.passes, vec![("unroll".to_owned(), false)]);
4468    }
4469
4470    /// The three transformations that are a module at a time are named by a flag as well, even
4471    /// though none of them is a `rucc_opt::Pass` and so none is reached by the generic arms.
4472    ///
4473    /// A bisection over a miscompilation turns one thing off at a time, and a transformation with
4474    /// no spelling of its own cannot be the one turned off.
4475    #[test]
4476    fn the_transformations_that_are_not_passes_are_still_named_by_a_flag() {
4477        let (opts, _) = compile(&["-c", "-fno-ipa-cp", "-fipa-sra", "-fno-libcall", "a.c"]);
4478        assert_eq!(
4479            opts.passes,
4480            vec![
4481                (rucc_opt::ipcp::NAME.to_owned(), false),
4482                (rucc_opt::ipasra::NAME.to_owned(), true),
4483                (rucc_opt::libcall::NAME.to_owned(), false),
4484            ]
4485        );
4486        let (opts, _) = compile(&["-c", "-flibcall", "a.c"]);
4487        assert_eq!(opts.passes, vec![(rucc_opt::libcall::NAME.to_owned(), true)]);
4488    }
4489
4490    /// Where a function starts is a question this compiler answers, so the flag that asks about it
4491    /// is answered rather than dropped. femtolisp's Makefile writes the bare form on every compile
4492    /// of the project, and before this it was an unknown option and the build stopped on its first
4493    /// file. The numbers are gcc 16's, read off `-S` on x86-64: nothing and the bare form both
4494    /// give `.p2align 4`, `=32` gives 5, `=3` gives 2, and the negative form gives `.align 8`.
4495    #[test]
4496    fn the_alignment_of_a_function_is_a_request_this_compiler_can_answer() {
4497        let (opts, _) = compile(&["-c", "-falign-functions", "a.c"]);
4498        assert_eq!(opts.align_functions, None, "the bare form asks for the default");
4499
4500        let (opts, _) = compile(&["-c", "-falign-functions=32", "a.c"]);
4501        assert_eq!(opts.align_functions, Some(32));
4502
4503        let (opts, _) = compile(&["-c", "-falign-functions=3", "a.c"]);
4504        assert_eq!(opts.align_functions, Some(4), "rounded up rather than refused");
4505
4506        let (opts, _) = compile(&["-c", "-falign-functions=32:8", "a.c"]);
4507        assert_eq!(opts.align_functions, Some(32), "the boundary is the answerable half");
4508
4509        for flag in ["-falign-functions=0", "-falign-functions=1"] {
4510            let (opts, _) = compile(&["-c", flag, "a.c"]);
4511            assert_eq!(opts.align_functions, None, "{flag} means the default");
4512        }
4513
4514        let (opts, _) = compile(&["-c", "-fno-align-functions", "a.c"]);
4515        assert_eq!(opts.align_functions, Some(8), "the smallest boundary the target has");
4516
4517        // The last one on the line wins, which is how gcc reads a repeated flag.
4518        let (opts, _) = compile(&["-c", "-falign-functions=32", "-falign-functions", "a.c"]);
4519        assert_eq!(opts.align_functions, None);
4520
4521        let e = parse_args(&args(&["-c", "-falign-functions=big", "a.c"])).unwrap_err();
4522        assert!(e.message.contains("number of bytes"), "{}", e.message);
4523    }
4524
4525    /// The other three of the family are about padding inside a body, so none of them is about
4526    /// where a function starts. Every spelling of each, since a build writes whichever one its
4527    /// author typed.
4528    #[test]
4529    fn the_alignment_flags_about_the_inside_of_a_body_are_taken_and_say_nothing() {
4530        for flag in [
4531            "-falign-labels",
4532            "-falign-loops",
4533            "-falign-jumps",
4534            "-falign-loops=16",
4535            "-falign-labels=32",
4536            "-fno-align-loops",
4537            "-fno-align-labels",
4538            "-fno-align-jumps",
4539        ] {
4540            let (opts, _) = compile(&["-c", flag, "a.c"]);
4541            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4542            assert_eq!(opts.align_functions, None, "{flag} is not about where a function starts");
4543        }
4544    }
4545
4546    /// The loop flag in either direction is an answer, and a command line that wrote neither
4547    /// leaves the level to decide.
4548    #[test]
4549    fn the_loop_alignment_flag_is_answered_both_ways() {
4550        assert_eq!(compile(&["-c", "-O2", "a.c"]).0.align_loops, None);
4551        assert_eq!(compile(&["-c", "-O0", "-falign-loops", "a.c"]).0.align_loops, Some(true));
4552        assert_eq!(compile(&["-c", "-O2", "-fno-align-loops", "a.c"]).0.align_loops, Some(false));
4553        assert_eq!(compile(&["-c", "-falign-loops=32", "a.c"]).0.align_loops, None, "a number");
4554    }
4555
4556    /// The encoding of the source is not a question about speed, so the one name that describes
4557    /// what the preprocessor does is taken and every other name is refused.
4558    #[test]
4559    fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
4560        for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
4561            let (opts, _) = compile(&["-c", flag, "a.c"]);
4562            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4563        }
4564
4565        let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
4566        assert!(e.message.contains("latin1"), "{}", e.message);
4567        assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
4568    }
4569
4570    /// `-fnon-call-exceptions` turns exceptions on unless `-fexceptions` or `-fno-exceptions` was
4571    /// written, and the one written wins whichever side of it it is on, which is gcc 16's reading.
4572    #[test]
4573    fn exceptions_are_on_when_asked_for_and_non_call_ones_ask_unless_told_not_to() {
4574        let (opts, _) = compile(&["-c", "a.c"]);
4575        assert!(!opts.exceptions && !opts.non_call_exceptions, "gcc's default for C is off");
4576        let (opts, _) = compile(&["-c", "-fexceptions", "a.c"]);
4577        assert!(opts.exceptions && !opts.non_call_exceptions);
4578        let (opts, _) = compile(&["-c", "-fexceptions", "-fno-exceptions", "a.c"]);
4579        assert!(!opts.exceptions);
4580        let (opts, _) = compile(&["-c", "-fnon-call-exceptions", "a.c"]);
4581        assert!(opts.exceptions && opts.non_call_exceptions);
4582        for line in [
4583            ["-fno-exceptions", "-fnon-call-exceptions"],
4584            ["-fnon-call-exceptions", "-fno-exceptions"],
4585        ] {
4586            let (opts, _) = compile(&["-c", line[0], line[1], "a.c"]);
4587            assert!(!opts.exceptions && opts.non_call_exceptions, "{line:?}");
4588        }
4589        let (opts, _) =
4590            compile(&["-c", "-fnon-call-exceptions", "-fno-non-call-exceptions", "a.c"]);
4591        assert!(!opts.exceptions && !opts.non_call_exceptions);
4592        let (opts, _) = compile(&["-c", "-fno-delete-dead-exceptions", "a.c"]);
4593        assert_eq!(opts.emit, EmitKind::Object);
4594    }
4595
4596    /// `-ffast-math` used to be refused beside it and is the family it names now, with each
4597    /// member settable on its own and the last word on each winning, which is gcc's reading.
4598    #[test]
4599    fn fast_math_is_the_family_it_names_and_the_last_word_on_each_member_wins() {
4600        let both = |line: &[&str]| {
4601            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4602            let (link, _) = linking(&[line, &["a.c"]].concat());
4603            (opts, link)
4604        };
4605        let (opts, link) = both(&[]);
4606        assert_eq!(opts.math, Math::default());
4607        assert!(opts.trapping_math);
4608        assert!(!link.fast_math);
4609
4610        let (opts, link) = both(&["-ffast-math"]);
4611        assert!(opts.math.fast(opts.trapping_math), "{:?}", opts.math);
4612        assert!(!opts.trapping_math, "fast math turns trapping off");
4613        assert!(link.fast_math, "and it links the startup file");
4614
4615        // Taking one member back leaves the rest, and the whole is not fast math any more.
4616        let (opts, link) = both(&["-ffast-math", "-fno-finite-math-only"]);
4617        assert!(!opts.math.finite_only);
4618        assert!(!opts.math.errno && !opts.math.signed_zeros && opts.math.reciprocal);
4619        assert!(!opts.math.fast(opts.trapping_math));
4620        assert!(link.fast_math, "gcc's spec reads the flag and not the fields");
4621
4622        let (opts, _) = both(&["-ffast-math", "-ftrapping-math"]);
4623        assert!(opts.trapping_math);
4624        assert!(!opts.math.fast(opts.trapping_math));
4625        assert!(!opts.math.associative(opts.trapping_math));
4626
4627        let (opts, link) = both(&["-ffast-math", "-fno-fast-math"]);
4628        assert_eq!(opts.math, Math::default());
4629        assert!(opts.trapping_math);
4630        assert!(!link.fast_math);
4631
4632        // A member written alone is only that member.
4633        let (opts, link) = both(&["-fno-math-errno"]);
4634        assert_eq!(opts.math, Math { errno: false, ..Math::default() });
4635        assert!(opts.math.iec_559(opts.trapping_math), "errno is not an IEC 60559 question");
4636        assert!(!link.fast_math);
4637
4638        let (opts, link) = both(&["-funsafe-math-optimizations"]);
4639        assert!(opts.math.unsafe_math && opts.math.associative(opts.trapping_math));
4640        assert!(opts.math.errno && !opts.math.finite_only);
4641        assert!(link.fast_math);
4642    }
4643
4644    /// `-Ofast` is `-O3` with fast math as a default, which a later level and a
4645    /// `-fno-fast-math` on either side of it both take back.
4646    #[test]
4647    fn ofast_is_o3_with_fast_math_as_a_default_a_flag_can_take_back() {
4648        let both = |line: &[&str]| {
4649            let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4650            let (link, _) = linking(&[line, &["a.c"]].concat());
4651            (opts, link)
4652        };
4653        let (opts, link) = both(&["-Ofast"]);
4654        assert_eq!(opts.opt_level, OptLevel::O3);
4655        assert!(opts.math.fast(opts.trapping_math));
4656        assert!(link.fast_math);
4657
4658        for line in [&["-Ofast", "-O2"][..], &["-fno-fast-math", "-Ofast"]] {
4659            let (opts, _) = both(line);
4660            assert!(!opts.math.fast(opts.trapping_math), "{line:?}");
4661        }
4662
4663        let (_, link) = both(&["-Ofast", "-mno-daz-ftz"]);
4664        assert_eq!(link.daz_ftz, Some(false));
4665    }
4666
4667    /// `-finstrument-functions` used to be refused beside those two, and it is taken now that the
4668    /// hooks are called. The last of it and its negative is the one that counts, as with any pair.
4669    #[test]
4670    fn instrument_functions_is_taken_and_the_last_of_the_pair_wins() {
4671        let (opts, _) = compile(&["-c", "-finstrument-functions", "a.c"]);
4672        assert!(opts.instrument_functions);
4673        let (opts, _) =
4674            compile(&["-c", "-finstrument-functions", "-fno-instrument-functions", "a.c"]);
4675        assert!(!opts.instrument_functions);
4676    }
4677
4678    #[test]
4679    fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
4680        // The one of that family that is a request rather than a description, and it is a real
4681        // difference: two files each writing `int g;` link under it and do not without it.
4682        let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
4683        assert!(e.message.contains(".bss"), "{}", e.message);
4684        assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
4685    }
4686
4687    #[test]
4688    fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
4689        for flag in ["-fno-pic", "-fno-pie"] {
4690            let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
4691            assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
4692            // The one it may have meant, since the two are a letter apart and one of them is
4693            // about linking and is taken.
4694            assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
4695        }
4696    }
4697
4698    #[test]
4699    fn a_program_name_with_a_known_target_in_front_of_rucc_picks_that_target() {
4700        let t = |p: &str| target_from_program(p);
4701        assert_eq!(t("aarch64-linux-gnu-rucc").as_deref(), Some("aarch64-linux-gnu"));
4702        assert_eq!(t("/usr/bin/riscv64-linux-musl-rucc").as_deref(), Some("riscv64-linux-musl"));
4703        assert_eq!(t(r"C:\bin\x86_64-windows-gnu-rucc.exe").as_deref(), Some("x86_64-windows-gnu"));
4704        assert_eq!(t("rucc"), None);
4705        assert_eq!(t("/usr/local/bin/rucc"), None);
4706        assert_eq!(t("my-rucc"), None);
4707        assert_eq!(t("sparc64-linux-gnu-rucc"), None);
4708        assert_eq!(t("aarch64-linux-gnu-gcc"), None);
4709    }
4710
4711    #[test]
4712    fn an_unsupported_target_names_itself() {
4713        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
4714        assert!(e.message.contains("sparc64"), "{}", e.message);
4715    }
4716
4717    #[test]
4718    fn no_inputs_is_an_error_but_print_config_needs_none() {
4719        assert!(parse_args(&args(&[])).is_err());
4720        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
4721    }
4722
4723    #[test]
4724    fn print_config_reports_the_target_it_was_given_not_the_host() {
4725        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
4726        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
4727        let text = print_config(&opts);
4728        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
4729        assert!(text.contains("char-signed: false"), "{text}");
4730        assert!(text.contains("object-format: elf"), "{text}");
4731        assert!(text.contains("va-list: void-pointer"), "{text}");
4732        // RISC-V has a register file and this compiler has not written it down yet, and the
4733        // dump says which of those two it is rather than leaving the line out.
4734        assert!(text.contains("registers: none"), "{text}");
4735        assert!(text.contains("timing-model: none"), "{text}");
4736    }
4737
4738    /// The model the schedule was chosen with, which is a receipt anybody comparing two runs of a
4739    /// benchmark needs: two numbers that disagree are usually two models and not two compilers.
4740    #[test]
4741    fn print_config_names_the_model_the_schedule_was_chosen_with() {
4742        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4743        let text = print_config(&opts);
4744        let line = text.lines().find(|l| l.starts_with("timing-model:")).expect("the model");
4745        assert!(line.contains("Skylake"), "{line}");
4746        assert!(line.contains("published"), "a sentence saying where it came from: {line}");
4747    }
4748
4749    #[test]
4750    fn print_config_has_one_key_per_line_and_a_fixed_order() {
4751        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4752        let text = print_config(&opts);
4753        let keys: Vec<&str> =
4754            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
4755        assert_eq!(keys[0], "version");
4756        assert_eq!(keys[1], "target");
4757        assert_eq!(keys.len(), 26);
4758        assert!(text.ends_with('\n'));
4759    }
4760
4761    #[test]
4762    fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4763        let (opts, _) = compile(&["a.c"]);
4764        assert_eq!(opts.safety, rucc_session::Safety::Off);
4765
4766        for (flag, tier) in [
4767            ("-fsafety=detect", rucc_session::Safety::Detect),
4768            ("-fsafety=enforce", rucc_session::Safety::Enforce),
4769            ("-fsafety=kernel", rucc_session::Safety::Kernel),
4770            ("-fsafety=off", rucc_session::Safety::Off),
4771        ] {
4772            let (opts, _) = compile(&[flag, "a.c"]);
4773            assert_eq!(opts.safety, tier, "{flag}");
4774        }
4775
4776        // The last one wins, the way every other repeated flag on this command line does.
4777        let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
4778        assert_eq!(opts.safety, rucc_session::Safety::Off);
4779
4780        // A misspelled tier is refused rather than ignored. Silently compiling without the
4781        // monitor a build asked for is the one failure mode this feature cannot have.
4782        let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
4783        assert!(e.message.contains("is not a safety tier"), "{}", e.message);
4784        assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
4785    }
4786
4787    #[test]
4788    fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4789        // The default is the one section 9.3 of document 09 gives library code, which is that
4790        // padding does not participate, so a record filled a member at a time is not reported.
4791        let (opts, _) = compile(&["a.c"]);
4792        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4793
4794        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
4795        assert_eq!(opts.padding, rucc_session::Padding::Tracked);
4796
4797        let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
4798        assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4799
4800        // The tier is still a tier. A flag whose name starts the same way must not be eaten by
4801        // the one above it, which is the thing worth pinning about a pair of names like these.
4802        let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
4803        assert_eq!(opts.safety, rucc_session::Safety::Off);
4804
4805        let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
4806        assert!(e.message.contains("is not a padding mode"), "{}", e.message);
4807    }
4808
4809    #[test]
4810    fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
4811        // Off by default, because a store to allocated storage sets its effective type and C 6.5
4812        // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
4813        let (opts, _) = compile(&["a.c"]);
4814        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4815
4816        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
4817        assert_eq!(opts.subobject, rucc_session::Subobject::Members);
4818
4819        let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
4820        assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4821
4822        // It takes no value. The form that would take one is the strict reading of section 9.4,
4823        // which is not written yet, so say so rather than accept a spelling that does nothing.
4824        let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
4825        assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
4826    }
4827
4828    #[test]
4829    fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
4830        // Off by default, because the record a block keeps is the union of what each pointer
4831        // reached, so two pointers striding through one array without landing on the same byte are
4832        // reported and by the letter of the standard those are different objects. Row Y8 is a build
4833        // deciding it would rather know.
4834        let (opts, _) = compile(&["a.c"]);
4835        assert_eq!(opts.promise, rucc_session::Promise::Off);
4836
4837        let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
4838        assert_eq!(opts.promise, rucc_session::Promise::Blocks);
4839
4840        let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
4841        assert_eq!(opts.promise, rucc_session::Promise::Off);
4842
4843        // The tier is still a tier, which is the thing worth pinning about a pair of names where
4844        // one is the front of the other.
4845        let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
4846        assert_eq!(opts.safety, rucc_session::Safety::Off);
4847
4848        let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
4849        assert!(e.message.contains("takes no value"), "{}", e.message);
4850    }
4851
4852    #[test]
4853    fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
4854        // Three modes rather than a bare flag, because section 9.5 gives two answers that record
4855        // the same thing and report different classes, so a flag with no value could not say which
4856        // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
4857        // argument: this is the one plane where an edge nobody interposed costs a false report.
4858        let (opts, _) = compile(&["a.c"]);
4859        assert_eq!(opts.races, rucc_session::Races::Off);
4860
4861        let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
4862        assert_eq!(opts.races, rucc_session::Races::Metadata);
4863
4864        let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
4865        assert_eq!(opts.races, rucc_session::Races::Pointer);
4866
4867        // Last one wins, as it does for every other mode flag here.
4868        let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
4869        assert_eq!(opts.races, rucc_session::Races::Off);
4870
4871        let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
4872        assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
4873    }
4874
4875    #[test]
4876    fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
4877        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4878        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4879        let text = print_pipeline(&opts);
4880        assert!(text.starts_with("level: -O2\n"), "{text}");
4881        assert!(text.contains("fold"), "{text}");
4882
4883        let a = parse_args(&args(&["--print-pipeline"])).unwrap();
4884        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4885        // Two passes run at `-O0` and neither is an optimization. The first moves what
4886        // `__builtin_expect` said onto the branch and takes the instruction away, so that nothing
4887        // past the optimizer has to know the instruction exists. The second removes code nothing
4888        // reaches. See issue 359.
4889        assert!(print_pipeline(&opts).contains("1: expect,"), "{}", print_pipeline(&opts));
4890        assert!(print_pipeline(&opts).contains("2: simplify-cfg,"), "{}", print_pipeline(&opts));
4891
4892        let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
4893        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4894        // The second turns off and the first does not, because nothing below the optimizer lowers
4895        // what it removes, so `-fno-expect` is a compile that stops rather than one that runs.
4896        let text = print_pipeline(&opts);
4897        assert!(text.contains("1: expect,"), "{text}");
4898        assert!(!text.contains("simplify-cfg"), "{text}");
4899    }
4900
4901    #[test]
4902    fn print_pipeline_takes_the_toggles_into_account() {
4903        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
4904        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4905        let text = print_pipeline(&opts);
4906        // The one that was named is gone and the rest of the level is not, which is the whole
4907        // of what a toggle promises.
4908        assert!(!text.contains("fold"), "{text}");
4909        assert!(text.contains("dce"), "{text}");
4910
4911        // Every pass the compiler has, named off. Built from the registry rather than written
4912        // out, so a pass added later is turned off here too and this keeps testing the thing it
4913        // is about, which is that the toggles can empty a level down to the passes that are not
4914        // optional. Those are named, because a listing that is all of them is a level nobody
4915        // emptied and the assertion would pass while saying nothing.
4916        let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
4917        off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
4918        let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
4919        let a = parse_args(&args(&spelled)).unwrap();
4920        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4921        let text = print_pipeline(&opts);
4922        let left: Vec<&str> =
4923            rucc_opt::PASSES.iter().filter(|p| p.required()).map(|p| p.name()).collect();
4924        assert_eq!(left, vec!["expect", "constant-p"], "{text}");
4925        for (at, name) in left.iter().enumerate() {
4926            assert!(text.contains(&format!("{}: {name},", at + 1)), "{text}");
4927        }
4928        assert!(!text.contains("dce"), "{text}");
4929    }
4930
4931    #[test]
4932    fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
4933        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4934        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4935        assert!(!print_pipeline(&opts).contains("global fuel"));
4936
4937        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
4938        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4939        let text = print_pipeline(&opts);
4940        // Because the listing is the answer to what this compilation will do, and a run that
4941        // stops after four rewrites is not doing what the level says it does.
4942        assert!(text.contains("global fuel: 4"), "{text}");
4943    }
4944
4945    /// A pass is turned on and off by its own name, and the order the flags were given in is
4946    /// kept, because the last spelling of a name is the one that decides.
4947    #[test]
4948    fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
4949        let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
4950        assert_eq!(
4951            opts.passes,
4952            [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
4953        );
4954
4955        let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
4956        assert!(e.message.contains("unknown option"), "{}", e.message);
4957    }
4958
4959    #[test]
4960    fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
4961        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
4962        assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
4963
4964        let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
4965        assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
4966        let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
4967        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
4968        let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
4969        assert!(e.message.contains("not a number"), "{}", e.message);
4970    }
4971
4972    #[test]
4973    fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
4974        let (opts, _) = compile(&["-c", "-O2", "a.c"]);
4975        assert_eq!(opts.pass_fuel_global, None);
4976
4977        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
4978        assert_eq!(opts.pass_fuel_global, Some(12));
4979        // And it is not the per pass flag with a longer name, so neither spelling swallows the
4980        // other.
4981        assert!(opts.pass_fuel.is_empty());
4982
4983        let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
4984        assert!(e.message.contains("not a number"), "{}", e.message);
4985    }
4986
4987    #[test]
4988    fn the_trace_file_is_taken_from_the_flag_and_an_empty_one_is_refused() {
4989        let (opts, _) = compile(&["-c", "a.c"]);
4990        assert_eq!(opts.trace, None);
4991        let (opts, _) = compile(&["-c", "-frucc-trace=/tmp/compile.jsonl", "a.c"]);
4992        assert_eq!(opts.trace.as_deref(), Some("/tmp/compile.jsonl"));
4993        let e = parse_args(&args(&["-frucc-trace=", "a.c"])).unwrap_err();
4994        assert!(e.message.contains("needs a file"), "{}", e.message);
4995    }
4996
4997    #[test]
4998    fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
4999        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
5000        assert_eq!(
5001            opts.pass_gates,
5002            [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
5003            "the order is what decides, so it has to survive the parse"
5004        );
5005
5006        let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
5007        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
5008        let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
5009        assert!(e.message.contains("ends before it starts"), "{}", e.message);
5010        let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
5011        assert!(e.message.contains("is empty"), "{}", e.message);
5012    }
5013
5014    #[test]
5015    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
5016        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
5017        let text = print_pipeline(&opts);
5018        assert!(text.contains("fold, "), "{text}");
5019        assert!(text.contains("[off for main]"), "{text}");
5020    }
5021
5022    /// The spelling is checked while the arguments are read, because a dump that names a pass
5023    /// this compiler does not have is a typo, and a typo found after the compilation has run is
5024    /// found too late to be any use.
5025    #[test]
5026    fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
5027        let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
5028        assert_eq!(opts.dump_ir, ["all", "after-fold"]);
5029
5030        let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
5031        assert!(e.message.contains("nosuch"), "{}", e.message);
5032        assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
5033    }
5034
5035    /// Every spelling `-fopt-info` takes, and the one it does not.
5036    ///
5037    /// The keywords are checked here for the same reason a dump's pass name is: a person who
5038    /// misspelled one gets no output, and no output is also what a compilation where nothing
5039    /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
5040    #[test]
5041    fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
5042        let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
5043        assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
5044        assert_eq!(opts.opt_info_file, None, "and goes to standard error");
5045
5046        let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
5047        assert_eq!(opts.opt_info, ["missed-note"]);
5048
5049        // Two flags add up rather than the second replacing the first, and the file is the last
5050        // one that named a file, which is how GCC treats both.
5051        let (opts, _) =
5052            compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
5053        assert_eq!(opts.opt_info, ["missed", "all"]);
5054        assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
5055
5056        let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
5057        assert!(e.message.contains("vectorized"), "{}", e.message);
5058        assert!(e.message.contains("`missed`"), "{}", e.message);
5059        let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
5060        assert!(e.message.contains("no file"), "{}", e.message);
5061    }
5062
5063    #[test]
5064    fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
5065        let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
5066        assert!(opts.verify_each);
5067        assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
5068    }
5069
5070    #[test]
5071    fn dash_o_needs_an_argument() {
5072        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
5073        assert_eq!(e.message, "-o requires an argument");
5074    }
5075
5076    #[test]
5077    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
5078        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
5079        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
5080        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
5081    }
5082
5083    #[test]
5084    fn the_include_flags_land_on_the_chain_each_one_names() {
5085        // A sysroot with nothing under it, so that the library's own directories are the
5086        // same on every machine this test runs on, which is none of them.
5087        let (opts, _) = compile(&[
5088            "-Ii",
5089            "-iquote",
5090            "q",
5091            "-isystem",
5092            "sys",
5093            "-idirafter",
5094            "after",
5095            "--sysroot=/nowhere-at-all",
5096            "a.c",
5097        ]);
5098        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5099        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
5100        // which is where GCC puts its own: a directory the user named outranks ours.
5101        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
5102        assert!(!opts.search.dirs()[1].is_system);
5103        assert!(opts.search.dirs()[2].is_system);
5104    }
5105
5106    #[test]
5107    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
5108        // Which machine this runs on decides what is on the path, so the test is about the
5109        // order rather than about the names: ours is on it, the library's follow it, and
5110        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
5111        let (opts, _) = compile(&["a.c"]);
5112        let dirs = opts.search.dirs();
5113        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
5114        assert_eq!(ours, Some(0), "{dirs:?}");
5115        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
5116        let (bare, _) = compile(&["-nostdinc", "a.c"]);
5117        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
5118    }
5119
5120    #[test]
5121    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
5122        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
5123        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5124        assert_eq!(dirs, ["sys", runtime::DIR]);
5125    }
5126
5127    #[test]
5128    fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
5129        // The target is not the machine this test runs on wherever it runs, so the answer is the
5130        // same on all of them: the libc's two include directories for that target, the kernel's
5131        // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
5132        // program that builds on the build machine and is wrong everywhere else.
5133        let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
5134        let dirs: Vec<&std::path::Path> =
5135            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5136        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
5137        let kernel = cache::dir().join("kernel-headers");
5138        assert_eq!(dirs.len(), 5, "{dirs:?}");
5139        assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
5140        assert_eq!(dirs[1], root.join("include").join("riscv64"));
5141        assert_eq!(dirs[2], root.join("include").join("generic"));
5142        // The kernel's, which are beside the sysroots rather than inside one, because every target
5143        // that shares an architecture reads the same files.
5144        assert_eq!(dirs[3], kernel.join("riscv"));
5145        assert_eq!(dirs[4], kernel.join("generic"));
5146    }
5147
5148    #[test]
5149    fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
5150        // The other side of the same answer. Windows has its own system headers and no `linux/` at
5151        // all, so the list is the libc's own and the question never arises, which is the `None` that
5152        // `link::cross_kernel` returns rather than a directory nothing would be found in.
5153        //
5154        // The libc's own is one directory rather than two here, because mingw-w64 publishes a single
5155        // header tree for every architecture and `Sysroot::splits_by_arch` says so.
5156        let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
5157        let dirs: Vec<&std::path::Path> =
5158            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5159        assert_eq!(dirs.len(), 2, "{dirs:?}");
5160        assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
5161    }
5162
5163    #[test]
5164    fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
5165        // One tree serves every glibc release, so the release is what the target supplies, and the
5166        // condition is the same one that chose the directories. A host glibc and a tree somebody
5167        // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
5168        // different values is a warning on every compilation of every file.
5169        //
5170        // The architecture is chosen against this machine's rather than written down, because the
5171        // bundled tree is only in effect for a target that is not this machine. The first version of
5172        // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
5173        // Linux runner, so it passed here and failed there.
5174        //
5175        // Unless this machine has the distribution's cross packages for it and nothing fetched, and
5176        // then those are the headers and their own `features.h` says the release, as it does for a
5177        // tree somebody named.
5178        let gnu = format!("--target={}-linux-gnu", cross_arch());
5179        let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
5180        let (link, _) = linking(&[&gnu, "-c", "a.c"]);
5181        let distro = link::distro_cross(bundled.target, &link).is_some();
5182        assert_eq!(bundled.glibc_minor, if distro { None } else { Some(44) });
5183        let pin = format!("{gnu}.2.28");
5184        let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
5185        assert_eq!(pinned.glibc_minor, Some(28));
5186
5187        let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5188        assert_eq!(named.glibc_minor, None);
5189        let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
5190        assert_eq!(none.glibc_minor, None);
5191        let musl = format!("--target={}-linux-musl", cross_arch());
5192        let (musl, _) = compile(&[&musl, "-c", "a.c"]);
5193        assert_eq!(musl.glibc_minor, None);
5194
5195        // And this machine's own target gets nothing, whatever this machine is, because its headers
5196        // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
5197        // that is the case this test had backwards; on a mac it is true for the other reason, which
5198        // is that Darwin is not a glibc target at all.
5199        if let Some(host) = Triple::host() {
5200            let native = format!("--target={}", host.tuple());
5201            let (native, _) = compile(&[&native, "-c", "a.c"]);
5202            assert_eq!(native.glibc_minor, None);
5203        }
5204    }
5205
5206    #[test]
5207    fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
5208        // The end to end half of the answer in `link::cross_for`. A release named for this machine's
5209        // own target is a cross compile, so the headers are the bundled tree's and the macro says
5210        // what was asked for rather than what this machine has.
5211        //
5212        // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
5213        // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
5214        // where the case lives.
5215        let Some(host) = Triple::host() else { return };
5216        if host.env != rucc_target::Env::Gnu {
5217            return;
5218        }
5219        let pin = format!("--target={}.2.28", host.tuple());
5220        let (opts, _) = compile(&[&pin, "-c", "a.c"]);
5221        assert_eq!(opts.glibc_minor, Some(28));
5222        let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
5223        let dirs: Vec<&std::path::Path> =
5224            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5225        assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
5226        // And nothing of this machine's, which is the failure this was: a program compiled against
5227        // 2.44 declarations and told it was 2.28.
5228        assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
5229    }
5230
5231    /// An architecture that is not this machine's, out of the three the driver has targets for.
5232    ///
5233    /// A test about the bundled sysroot has to name a target that is not the host, because a target
5234    /// that is the host reads the host's own headers and libraries. Asking which machine this is
5235    /// beats picking a row and hoping, and it is two lines.
5236    fn cross_arch() -> &'static str {
5237        match Triple::host().map(|host| host.arch) {
5238            Some(rucc_target::Arch::X86_64) => "aarch64",
5239            _ => "x86_64",
5240        }
5241    }
5242
5243    #[test]
5244    fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
5245        // Both versions in the message, because the two things a person can do about it are pin a
5246        // release the tree has and name a sysroot that has the one they asked for, and neither is a
5247        // choice they can make without knowing which release the tree is.
5248        //
5249        // Not this machine's architecture, for the reason the test above gives: the refusal is about
5250        // the bundled tree, and the bundled tree is not what a target that is this machine reads.
5251        let target = format!("--target={}-linux-gnu.2.99", cross_arch());
5252        let message = refused(&[&target, "-c", "a.c"]);
5253        assert!(message.contains("asked for glibc 2.99"), "{message}");
5254        assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
5255        assert!(message.contains("--sysroot"), "{message}");
5256    }
5257
5258    #[test]
5259    fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
5260        // The tree somebody assembled beats the one we would build, on the headers as on the
5261        // libraries. It is empty here, which is why the list comes out short: the directories under
5262        // it are checked for rather than assumed, and a tree that is not there offers nothing.
5263        let (opts, _) =
5264            compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5265        let dirs: Vec<&std::path::Path> =
5266            opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5267        assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
5268    }
5269
5270    #[test]
5271    fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
5272        let (opts, _) =
5273            compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
5274        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5275        assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
5276        // An angled include sees only what came after the flag.
5277        assert_eq!(opts.search.start(IncludeForm::Angled), 2);
5278        assert!(!opts.search.searches_current_dir());
5279    }
5280
5281    #[test]
5282    fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
5283        let (opts, _) = compile(&[
5284            "-iprefix",
5285            "/tools/",
5286            "-iwithprefix",
5287            "late",
5288            "-iwithprefixbefore",
5289            "early",
5290            "-iprefix",
5291            "/other/",
5292            "-iwithprefix",
5293            "last",
5294            "-nostdinc",
5295            "a.c",
5296        ]);
5297        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5298        // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
5299        // puts them rather than where its manual says it does.
5300        assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
5301        assert!(!opts.search.dirs()[0].is_system);
5302        assert!(opts.search.dirs()[1].is_system);
5303    }
5304
5305    #[test]
5306    fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
5307        let (opts, _) =
5308            compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
5309        let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
5310        assert_eq!(names, ["one.h", "two.h", "3.h"]);
5311        assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
5312    }
5313
5314    #[test]
5315    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
5316        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
5317        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5318        assert_eq!(dirs, ["i"]);
5319    }
5320
5321    #[test]
5322    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
5323        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
5324        assert_eq!(opts.std, Std::C11);
5325        assert!(opts.gnu_extensions);
5326
5327        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
5328        assert_eq!(opts.std, Std::C99);
5329        assert!(!opts.gnu_extensions);
5330
5331        let (opts, _) = compile(&["-ansi", "a.c"]);
5332        assert_eq!(opts.std, Std::C89);
5333        assert!(!opts.gnu_extensions);
5334
5335        let (opts, _) = compile(&["-std=gnu2y", "a.c"]);
5336        assert_eq!(opts.std, Std::C2y);
5337        assert!(opts.gnu_extensions);
5338
5339        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
5340        assert!(e.message.contains("unknown dialect"), "{}", e.message);
5341    }
5342
5343    #[test]
5344    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
5345        let (opts, _) = compile(&["-dM", "a.c"]);
5346        assert!(opts.dumps.macros);
5347
5348        // Packed, the way GCC takes them, and a letter in the family we have not written yet
5349        // is accepted and does nothing rather than failing a build.
5350        let (opts, _) = compile(&["-dDM", "a.c"]);
5351        assert!(opts.dumps.macros);
5352        let (opts, _) = compile(&["-dD", "a.c"]);
5353        assert!(!opts.dumps.macros);
5354
5355        let (opts, _) = compile(&["a.c"]);
5356        assert!(!opts.dumps.any());
5357
5358        // `-dumpversion` is a different flag that happens to start the same way, and it is read
5359        // as itself rather than as a dump of nothing.
5360        assert_eq!(printed(&["-dumpversion", "a.c"]), "16");
5361    }
5362
5363    #[test]
5364    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
5365        let (opts, _) = compile(&["a.c"]);
5366        assert_eq!(
5367            opts.gnuc,
5368            GnucVersion { major: 16, minor: 0, patch: 0 },
5369            "the release this compiler is written against, and the earliest one of that series"
5370        );
5371
5372        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
5373        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
5374
5375        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
5376        // patchlevel and a harness that pastes that back has to be understood.
5377        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
5378        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
5379
5380        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
5381        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
5382
5383        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
5384        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
5385
5386        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
5387        assert!(e.message.contains("more than three"), "{}", e.message);
5388    }
5389
5390    #[test]
5391    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
5392        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
5393        assert!(opts.pedantic);
5394        assert_eq!(opts.std, Std::C17);
5395
5396        // The `-W` family's name for it, which is what a build that groups its warning flags
5397        // tends to write.
5398        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
5399        assert!(opts.pedantic);
5400
5401        let (opts, _) = compile(&["-std=c17", "a.c"]);
5402        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
5403    }
5404
5405    #[test]
5406    fn dash_p_and_dash_ffreestanding_reach_the_options() {
5407        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
5408        assert!(!opts.line_markers);
5409        assert!(!opts.hosted);
5410        assert_eq!(opts.emit, EmitKind::Preprocessed);
5411    }
5412
5413    /// The two ways a build says it means its own function by a name the C library also has.
5414    ///
5415    /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
5416    /// build writes when it means its own `memcpy` and the library's everything else. The name is
5417    /// kept as it was written and not checked against anything, because a program is allowed to
5418    /// mean something by a name this compiler has never heard of.
5419    #[test]
5420    fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
5421        let (opts, _) = compile(&["-c", "a.c"]);
5422        assert!(opts.builtins, "a library name means the library function by default");
5423        assert!(opts.no_builtin.is_empty());
5424
5425        let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
5426        assert!(!opts.builtins);
5427
5428        let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
5429        assert!(opts.builtins, "the last mention decides");
5430
5431        let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
5432        assert!(opts.builtins, "one name is not the family");
5433        assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
5434    }
5435
5436    /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
5437    /// and which was refused as an unknown option until now.
5438    ///
5439    /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
5440    /// the address across a component boundary, and nothing derives anything from that promise
5441    /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
5442    /// over a distinction this compiler does not make.
5443    #[test]
5444    fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
5445        let (opts, _) = compile(&["-c", "a.c"]);
5446        assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
5447
5448        for (written, wanted) in [
5449            ("default", Visibility::Default),
5450            ("hidden", Visibility::Hidden),
5451            ("internal", Visibility::Hidden),
5452            ("protected", Visibility::Protected),
5453        ] {
5454            let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
5455            assert_eq!(opts.visibility, wanted, "{written}");
5456        }
5457
5458        // The last mention decides, which is what every other flag of this shape does and what a
5459        // build that turns something off for one directory relies on.
5460        let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
5461        assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
5462
5463        // A spelling gcc does not take is refused rather than read as the default, because a
5464        // build that meant hidden and got exported is a library with the wrong interface and
5465        // nothing said about it anywhere.
5466        let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
5467        assert!(failed.to_string().contains("is not a visibility"), "{failed}");
5468    }
5469
5470    /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
5471    /// described, and the values are gcc 16's three.
5472    #[test]
5473    fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
5474        let (opts, _) = compile(&["-c", "a.c"]);
5475        assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
5476
5477        for (written, wanted) in
5478            [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
5479        {
5480            let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
5481            assert_eq!(opts.fp_contract, wanted, "{written}");
5482        }
5483
5484        let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
5485        assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
5486
5487        // Refused rather than read as one of the three, because a build that asked for no fusing
5488        // and was given the default would be one whose numbers change and whose command line says
5489        // they should not. gcc refuses the same spellings and names the same three in its message.
5490        for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
5491            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5492            assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
5493        }
5494
5495        // And the other one that takes a value, which is taken and kept nowhere: every operation
5496        // here is computed in the type it was written in, so `standard` is what happens and the
5497        // other two are permission to do something this does not do.
5498        let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
5499        assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
5500    }
5501
5502    /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
5503    /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
5504    /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
5505    #[test]
5506    fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
5507        let (opts, _) = compile(&["-c", "a.c"]);
5508        assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
5509        assert!(opts.prefix_map.debug.is_empty(), "nor here");
5510        assert!(opts.prefix_map.profile.is_empty(), "nor here");
5511
5512        let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
5513        assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
5514        assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
5515
5516        let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
5517        assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
5518        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5519
5520        let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
5521        assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
5522        assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5523
5524        let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
5525        for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
5526            assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
5527        }
5528
5529        // Every mention is kept and the last one that matches wins, unlike the flags above whose
5530        // last mention replaces the earlier ones. A build writes one of these per source root and
5531        // expects all of them to be in force, which is the whole point of a list.
5532        let (opts, _) =
5533            compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
5534        assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
5535        assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
5536
5537        // An argument with no `=` is refused rather than ignored, because a build whose paths were
5538        // meant to be rewritten and were not is one that ships the build directory's name and says
5539        // nothing about it. gcc refuses the same thing.
5540        for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
5541            let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5542            assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
5543        }
5544    }
5545
5546    /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
5547    /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
5548    /// one. A kernel and an embedded image are both linked that way.
5549    ///
5550    /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
5551    /// the other is a build that measured something: splitting the code is nearly free at link time
5552    /// and splitting the data can defeat the linker's ordering of what is next to what.
5553    #[test]
5554    fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
5555        let (opts, _) = compile(&["-c", "a.c"]);
5556        assert!(!opts.function_sections, "one text section unless something says otherwise");
5557        assert!(!opts.data_sections);
5558
5559        let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
5560        assert!(opts.function_sections);
5561        assert!(!opts.data_sections, "one flag is not the other");
5562
5563        let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
5564        assert!(opts.data_sections);
5565        assert!(!opts.function_sections);
5566
5567        // Both directions taken, and the off one is what happens anyway rather than a refusal,
5568        // since a build that writes it is asking for the default.
5569        let (opts, _) = compile(&[
5570            "-c",
5571            "-ffunction-sections",
5572            "-fno-function-sections",
5573            "-fdata-sections",
5574            "-fno-data-sections",
5575            "a.c",
5576        ]);
5577        assert!(!opts.function_sections, "the last mention decides");
5578        assert!(!opts.data_sections, "the last mention decides");
5579    }
5580
5581    /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
5582    /// line, since the dialect asks for GNU's reading further in rather than through this.
5583    #[test]
5584    fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
5585        let (opts, _) = compile(&["-c", "a.c"]);
5586        assert!(!opts.gnu89_inline, "C's reading of inline by default");
5587
5588        let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
5589        assert!(opts.gnu89_inline);
5590
5591        let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
5592        assert!(!opts.gnu89_inline, "the last mention decides");
5593
5594        // The C89 dialects are under GNU's reading whether this was written or not, so the flag
5595        // stays off there and the dialect is what the checker and the macro set both ask. That is
5596        // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
5597        // dialect already has. gcc refuses that command line, which is measured in the issue.
5598        let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
5599        assert!(!opts.gnu89_inline);
5600    }
5601
5602    /// Both spellings of both frame flags, since a build that wants one usually writes the
5603    /// other beside it for the one file that has to be compiled the ordinary way.
5604    #[test]
5605    fn the_two_frame_flags_are_read_in_both_directions() {
5606        let (opts, _) = compile(&["-c", "a.c"]);
5607        assert_eq!(opts.frame_pointer, None, "nothing said, so the level decides");
5608        assert!(opts.keeps_frame_pointer(), "and at -O0 gcc keeps one, so this does too");
5609        let (opts, _) = compile(&["-c", "-O1", "a.c"]);
5610        assert!(!opts.keeps_frame_pointer(), "gcc omits it above -O0 and so does this");
5611        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
5612
5613        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
5614        assert_eq!(opts.frame_pointer, Some(true));
5615        assert!(!opts.red_zone);
5616
5617        let (opts, _) = compile(&[
5618            "-c",
5619            "-fno-omit-frame-pointer",
5620            "-fomit-frame-pointer",
5621            "-mno-red-zone",
5622            "-mred-zone",
5623            "a.c",
5624        ]);
5625        assert_eq!(opts.frame_pointer, Some(false), "the last one wins, as it does in gcc");
5626        assert!(!opts.keeps_frame_pointer(), "and it wins over the level too");
5627        assert!(opts.red_zone);
5628    }
5629
5630    /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
5631    /// spelled three ways because a build that turns one off writes whichever it turned on.
5632    #[test]
5633    fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
5634        let (opts, _) = compile(&["-c", "a.c"]);
5635        assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
5636
5637        for (flag, want) in [
5638            ("-fstack-protector", Protector::Buffers),
5639            ("-fstack-protector-strong", Protector::Strong),
5640            ("-fstack-protector-all", Protector::All),
5641        ] {
5642            let (opts, _) = compile(&["-c", flag, "a.c"]);
5643            assert_eq!(opts.protector, want, "{flag}");
5644        }
5645
5646        // What a package build does: the strong one in the global flags and one directory that
5647        // cannot have a protector turning it off on the line after.
5648        for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
5649            let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
5650            assert_eq!(opts.protector, Protector::None, "{off}");
5651        }
5652        let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
5653        assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
5654    }
5655
5656    /// A switch rather than a level, because how a frame is taken is one question and which
5657    /// functions get a canary is another, and gcc spells it that way for the same reason.
5658    #[test]
5659    fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
5660        let (opts, _) = compile(&["-c", "a.c"]);
5661        assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
5662
5663        let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
5664        assert!(opts.stack_clash);
5665
5666        // The same shape a package build uses for the protector: on in the global flags and off
5667        // for the one directory that cannot have it.
5668        let (opts, _) =
5669            compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
5670        assert!(!opts.stack_clash);
5671        let (opts, _) =
5672            compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
5673        assert!(opts.stack_clash, "the last one wins either way round");
5674
5675        // The two are independent, since one is about the frame and the other about the function.
5676        let (opts, _) =
5677            compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
5678        assert!(opts.stack_clash);
5679        assert_eq!(opts.protector, Protector::Strong);
5680    }
5681
5682    /// One flag with an argument rather than a family of spellings, because what it asks about is
5683    /// which of the two edges of a control flow transfer is checked and the two are not separate
5684    /// questions to the hardware.
5685    #[test]
5686    fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
5687        let (opts, _) = compile(&["-c", "a.c"]);
5688        assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
5689
5690        for (arg, want) in [
5691            ("-fcf-protection", Control::Full),
5692            ("-fcf-protection=full", Control::Full),
5693            ("-fcf-protection=branch", Control::Branch),
5694            ("-fcf-protection=return", Control::Return),
5695            ("-fcf-protection=none", Control::None),
5696            ("-fcf-protection=check", Control::Check),
5697        ] {
5698            let (opts, _) = compile(&["-c", arg, "a.c"]);
5699            assert_eq!(opts.control, want, "{arg}");
5700        }
5701
5702        // The shape a package build uses: on in the global flags and off for the one directory
5703        // that cannot have it, whichever of the two spellings of off it reaches for.
5704        let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
5705        assert_eq!(opts.control, Control::None);
5706        let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
5707        assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
5708    }
5709
5710    /// The profiler is asked for by two spellings, and where its hook goes by two more.
5711    ///
5712    /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
5713    /// asks for no call, which is what gcc does with it, and a build system that sets it globally
5714    /// and asks for the profile per directory needs that to be true rather than an error.
5715    ///
5716    /// The link is asserted alongside, because the flag changes it too and a build that compiled
5717    /// with it and linked without it is a program that calls the hook everywhere and never writes a
5718    /// profile.
5719    #[test]
5720    fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
5721        let (opts, _) = compile(&["-c", "a.c"]);
5722        assert!(!opts.profile);
5723        assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
5724
5725        for arg in ["-pg", "-p"] {
5726            let (opts, _) = compile(&["-c", arg, "a.c"]);
5727            assert!(opts.profile, "{arg}");
5728            let (link, _) = linking(&[arg, "a.c"]);
5729            assert!(link.profile, "{arg} changes the link as well");
5730        }
5731
5732        for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
5733            let (opts, _) = compile(&["-c", arg, "a.c"]);
5734            assert_eq!(opts.hook, want, "{arg}");
5735            assert!(!opts.profile, "{arg} asks for no call of its own");
5736        }
5737
5738        let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
5739        assert_eq!(opts.hook, Hook::Late, "the last one wins");
5740        assert!(opts.profile);
5741    }
5742
5743    /// How much room a patcher is promised, which is one number or two.
5744    ///
5745    /// A command line that did not ask is asserted alongside, because the flag has to be written to
5746    /// mean anything and a build that reserved room nobody asked for would grow every function in
5747    /// it for nothing.
5748    #[test]
5749    fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
5750        let (opts, _) = compile(&["-c", "a.c"]);
5751        assert_eq!(opts.patchable, Patchable::default());
5752        assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
5753
5754        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
5755        assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
5756
5757        let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
5758        assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
5759        assert_eq!(opts.patchable.after(), 2);
5760
5761        // The last one wins, which is what every other flag of this shape does and what a build
5762        // that adds one to a command line it did not write is relying on.
5763        let (opts, _) = compile(&[
5764            "-c",
5765            "-fpatchable-function-entry=5,3",
5766            "-fpatchable-function-entry=2",
5767            "a.c",
5768        ]);
5769        assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
5770    }
5771
5772    /// And a request nothing could satisfy is refused rather than rounded into one that can be.
5773    #[test]
5774    fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
5775        for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
5776            let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
5777            assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
5778        }
5779    }
5780
5781    /// What wraps rather than being undefined, which is two questions and three flags.
5782    ///
5783    /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
5784    /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
5785    /// only what it asked for.
5786    #[test]
5787    fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
5788        let (opts, _) = compile(&["-c", "a.c"]);
5789        assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
5790
5791        let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
5792        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5793
5794        let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
5795        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
5796
5797        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
5798        assert_eq!(opts.wrapping, Wrapping::ALL);
5799
5800        // And the last one wins, in both directions. A build that turns one of these on globally
5801        // and off for one directory is relying on that, and so is one that writes the pair and
5802        // then takes half of it back.
5803        let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
5804        assert_eq!(opts.wrapping, Wrapping::NONE);
5805
5806        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
5807        assert_eq!(opts.wrapping, Wrapping::NONE);
5808
5809        let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
5810        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5811    }
5812
5813    /// And the other answer to the signed question cannot be held at the same time as the first.
5814    ///
5815    /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
5816    /// resolves it by letting the last one win rather than by reporting anything. That was measured
5817    /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
5818    /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
5819    #[test]
5820    fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
5821        let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
5822        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5823
5824        let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
5825        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5826
5827        let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
5828        assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5829
5830        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
5831        assert_eq!(opts.wrapping, Wrapping::ALL);
5832
5833        let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
5834        assert_eq!(opts.wrapping, Wrapping::NONE);
5835
5836        // And the flag that says what may be assumed says nothing about what happens, so it leaves
5837        // this alone where it takes the wrapping away. gcc does the same.
5838        let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
5839        assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5840    }
5841
5842    /// What a plain `char` is, which is four spellings of two answers and nothing by default.
5843    ///
5844    /// Nothing is the target's own answer and has to stay distinct from both of the others, since
5845    /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
5846    /// The negative spellings are the other flag rather than a way of asking for the default, which
5847    /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
5848    /// `-fno-unsigned-char` does not.
5849    #[test]
5850    fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
5851        let (opts, _) = compile(&["-c", "a.c"]);
5852        assert_eq!(opts.char_signed, None);
5853
5854        for flag in ["-fsigned-char", "-fno-unsigned-char"] {
5855            let (opts, _) = compile(&["-c", flag, "a.c"]);
5856            assert_eq!(opts.char_signed, Some(true), "{flag}");
5857        }
5858
5859        for flag in ["-funsigned-char", "-fno-signed-char"] {
5860            let (opts, _) = compile(&["-c", flag, "a.c"]);
5861            assert_eq!(opts.char_signed, Some(false), "{flag}");
5862        }
5863
5864        // And the last one wins, which is what a build that sets one globally and the other for a
5865        // directory relies on.
5866        let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
5867        assert_eq!(opts.char_signed, Some(true));
5868
5869        // And what is asked for reaches the target, because that is what every other part of the
5870        // compiler asks. The triple is one whose own answer is the opposite, so a session that
5871        // ignored the flag would still read as signed here.
5872        let (opts, _) =
5873            compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
5874        assert!(Session::new(*opts).target.char_is_signed);
5875        let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
5876        assert!(!Session::new(*opts).target.char_is_signed);
5877    }
5878
5879    /// And the size of an enumeration, which is one question with two spellings.
5880    #[test]
5881    fn the_smallest_enumeration_is_asked_for_and_taken_back() {
5882        let (opts, _) = compile(&["-c", "a.c"]);
5883        assert!(!opts.short_enums);
5884
5885        let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
5886        assert!(opts.short_enums);
5887
5888        let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
5889        assert!(!opts.short_enums);
5890
5891        let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
5892        assert!(opts.short_enums);
5893    }
5894
5895    /// And Microsoft's reading of an anonymous member, which the target answers where the command
5896    /// line said nothing. gcc's mingw build has it on and its Linux build has it off, so a header
5897    /// that closes a nameless union with a macro that expands to nothing is read the way the
5898    /// compiler that platform ships would read it.
5899    #[test]
5900    fn the_microsoft_reading_of_a_member_follows_the_target_until_it_is_asked_for() {
5901        // Named rather than left to the host, since the answer this asks for is the one a target
5902        // that is not Windows gives and on a Windows machine the host is not one of those.
5903        let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
5904        assert!(!Session::new(*opts).ms_extensions());
5905
5906        let (opts, _) = compile(&["-c", "--target=x86_64-pc-windows-gnu", "a.c"]);
5907        assert!(Session::new(*opts).ms_extensions());
5908
5909        let (opts, _) = compile(&["-c", "-fms-extensions", "a.c"]);
5910        assert!(Session::new(*opts).ms_extensions());
5911
5912        let (opts, _) =
5913            compile(&["-c", "--target=x86_64-pc-windows-gnu", "-fno-ms-extensions", "a.c"]);
5914        assert!(!Session::new(*opts).ms_extensions());
5915    }
5916
5917    /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
5918    ///
5919    /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
5920    /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
5921    /// family would report it as an unknown pass. Neither is the news the build wants.
5922    #[test]
5923    fn a_control_flow_protection_nothing_means_is_refused() {
5924        let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
5925        assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
5926        assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
5927    }
5928
5929    #[test]
5930    fn the_link_flags_are_collected_apart_from_the_compilation() {
5931        let (link, _) = linking(&[
5932            "-static",
5933            "-nostartfiles",
5934            "-rdynamic",
5935            "-s",
5936            "-fuse-ld=mold",
5937            "-L/opt/lib",
5938            "-B",
5939            "/opt/tools",
5940            "a.c",
5941        ]);
5942        assert!(link.is_static);
5943        assert!(link.no_startfiles);
5944        assert!(link.export_dynamic);
5945        assert!(link.strip);
5946        assert_eq!(link.use_ld.as_deref(), Some("mold"));
5947        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
5948        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
5949    }
5950
5951    #[test]
5952    fn a_comma_in_dash_wl_separates_two_arguments() {
5953        // The target is written down because the name of the object is derived from it, and `a.o`
5954        // on a Linux host is `a.obj` on a Windows one. What is under test is the splitting of the
5955        // argument, which has nothing to do with either.
5956        let (_, plan) = linking(&[LINUX, "-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
5957        let link = plan.link.expect("expected a link step");
5958        assert_eq!(
5959            link.inputs,
5960            vec![
5961                link::Item::Linker("-rpath".into()),
5962                link::Item::Linker("/opt/lib".into()),
5963                link::Item::Linker("--as-needed".into()),
5964                link::Item::File("a.o".into()),
5965            ]
5966        );
5967    }
5968
5969    #[test]
5970    fn a_word_for_the_linker_keeps_its_place_among_the_files_too() {
5971        // What libtool writes around a set of convenience archives, and what #1279 was. Both words
5972        // are about the files between them, so the pair collected out of the line and appended to
5973        // the end is two options that bracket nothing and an archive that went in empty.
5974        let (_, plan) = linking(&[
5975            "--target=x86_64-unknown-linux-gnu",
5976            "a.c",
5977            "-Wl,--whole-archive",
5978            "libaesni.a",
5979            "-Wl,--no-whole-archive",
5980            "-lm",
5981        ]);
5982        let link = plan.link.expect("expected a link step");
5983        assert_eq!(
5984            link.inputs,
5985            vec![
5986                link::Item::File("a.o".into()),
5987                link::Item::Linker("--whole-archive".into()),
5988                link::Item::File("libaesni.a".into()),
5989                link::Item::Linker("--no-whole-archive".into()),
5990                link::Item::Library("m".into()),
5991            ]
5992        );
5993        // And it is not a job, because there is nothing to compile in a word for the linker.
5994        assert_eq!(plan.jobs.len(), 2);
5995    }
5996
5997    #[test]
5998    fn a_word_for_the_linker_on_a_dash_c_line_is_dropped_without_a_word() {
5999        // GCC says nothing about one either. `-Wl,` on a compile line is what a build system
6000        // writes when one variable holds the flags for both, and a note here would be a note on
6001        // every compile of every autotools project.
6002        let (_, plan) = linking(&["-c", "-Wl,--as-needed", "a.c"]);
6003        assert!(plan.link.is_none());
6004        assert!(plan.notes.is_empty(), "{:?}", plan.notes);
6005        assert_eq!(plan.jobs.len(), 1);
6006    }
6007
6008    #[test]
6009    fn a_library_keeps_its_place_between_the_objects() {
6010        // Link order is semantic: `-lm` written between two files resolves for the one before
6011        // it and not for the one after, so a library cannot be collected into a list of its own.
6012        // The target is named because the suffix of an object is the target's and this asserts
6013        // on the names: the same command line on a Windows host plans two `.obj` files.
6014        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
6015        let link = plan.link.expect("expected a link step");
6016        assert_eq!(
6017            link.inputs,
6018            vec![
6019                link::Item::File("a.o".into()),
6020                link::Item::Library("m".into()),
6021                link::Item::File("b.o".into()),
6022            ]
6023        );
6024        // And it is not a job, because there is nothing to compile in a library.
6025        assert_eq!(plan.jobs.len(), 2);
6026    }
6027
6028    #[test]
6029    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
6030        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
6031        assert!(plan.link.is_none());
6032        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
6033    }
6034
6035    #[test]
6036    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
6037        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
6038        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
6039    }
6040
6041    fn printed(s: &[&str]) -> String {
6042        match parse_args(&args(s)).expect("expected an answer") {
6043            Action::Print(line) => line,
6044            other => panic!("expected an answer, got {other:?}"),
6045        }
6046    }
6047
6048    fn refused(s: &[&str]) -> String {
6049        parse_args(&args(s)).expect_err("expected a refusal").message
6050    }
6051
6052    #[test]
6053    fn a_warning_flag_gcc_knows_is_taken_even_though_nothing_reads_it() {
6054        // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
6055        // out whether a warning flag exists by passing it and looking at the exit status, so a
6056        // compiler that refuses one gcc knows fails a script written for gcc.
6057        let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
6058        assert!(!opts.warnings_are_errors);
6059        assert!(opts.warnings);
6060        // The two spellings that do mean something are still read.
6061        let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
6062        assert!(opts.warnings_are_errors);
6063        let (opts, _) = compile(&["-w", "-c", "a.c"]);
6064        assert!(!opts.warnings);
6065        // Off without being asked, the way gcc has it off, and both spellings are read.
6066        let (opts, _) = compile(&["-c", "a.c"]);
6067        assert!(!opts.system_header_warnings);
6068        let (opts, _) = compile(&["-Wsystem-headers", "-c", "a.c"]);
6069        assert!(opts.system_header_warnings);
6070        let (opts, _) = compile(&["-Wsystem-headers", "-Wno-system-headers", "-c", "a.c"]);
6071        assert!(!opts.system_header_warnings);
6072        let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
6073        assert!(opts.pedantic && opts.warnings_are_errors);
6074    }
6075
6076    #[test]
6077    fn a_warning_flag_gcc_refuses_is_refused_here_too() {
6078        // Postgres's meson build probes these, and with rucc taking them it ended up passing four
6079        // clang warnings that the gcc build had dropped.
6080        for flag in ["-Wcast-function-type-strict", "-Wunused-command-line-argument"] {
6081            assert_eq!(refused(&[flag, "-c", "a.c"]), format!("unknown option `{flag}`"));
6082        }
6083        assert_eq!(
6084            refused(&["-Werror=unguarded-availability-new", "-c", "a.c"]),
6085            "`-Werror=unguarded-availability-new`: no option `-Wunguarded-availability-new`"
6086        );
6087        assert!(refused(&["-Wno-error=nonsense", "-c", "a.c"]).contains("no option `-Wnonsense`"));
6088        // gcc takes `-Wno-` of a name it does not know, and says nothing unless something else
6089        // is said, and it takes C++ and Fortran names on a C compile.
6090        for flag in
6091            ["-Wno-cast-function-type-strict", "-Werror=format", "-Wformat=2", "-Wabi-tag", "-W"]
6092        {
6093            compile(&[flag, "-c", "a.c"]);
6094        }
6095    }
6096
6097    #[test]
6098    fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
6099        // Every one of these says something about the output, so the wrong answer is silence.
6100        assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
6101        assert!(refused(&["-Wp,-C", "-c", "a.c"]).contains("separate assembler"));
6102        assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
6103        assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
6104        assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
6105        // The word size the target does not have, which is a target this compiler was not asked
6106        // for rather than a flag it does not know.
6107        let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
6108        assert!(no32.contains("32 bit target"), "{no32}");
6109    }
6110
6111    /// `-gz` and the two spellings of the split, which are the two questions about the shape of
6112    /// the debug output rather than about how much of it there is.
6113    ///
6114    /// Both answers here are about what happens when there is debug information to shape, and
6115    /// there is none yet, so what is being asserted is that the flags are read and remembered
6116    /// rather than that anything changed in the output. That is the whole of what taking them
6117    /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
6118    /// it comes to find out what the command line said.
6119    #[test]
6120    fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
6121        let (opts, _) = compile(&["-c", "a.c"]);
6122        assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
6123
6124        // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
6125        // which describes the flag without ever saying which algorithm it picks.
6126        assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
6127        for (spelling, want) in [
6128            ("none", Compress::None),
6129            ("zlib", Compress::Zlib),
6130            ("zlib-gnu", Compress::ZlibGnu),
6131            ("zstd", Compress::Zstd),
6132        ] {
6133            let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
6134            assert_eq!(opts.compress, want, "{spelling}");
6135        }
6136
6137        // A value nothing here has heard of is refused rather than rounded to the nearest one,
6138        // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
6139        // reader may not understand and would have no way of finding out.
6140        for bad in ["-gz=gzip", "-gz="] {
6141            let failed = refused(&[bad, "-c", "a.c"]);
6142            assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
6143        }
6144
6145        // The split is refused in the direction that would have written a file and taken in the
6146        // direction that describes what happens. A build system that names the `.dwo` as an
6147        // output has to hear about it now rather than at the point the file is missing.
6148        let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
6149        assert!(opts.debug_info, "the negative spelling says nothing about how much");
6150        let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
6151        assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
6152    }
6153
6154    /// The `-flto` family, which is the whole of an optimization this compiler does not do.
6155    ///
6156    /// Taken rather than refused because ignoring it gives a correct program that is slower than
6157    /// it could have been, which is section 4.1's hint about speed. The values are still held to
6158    /// gcc's, so a command line written for clang is told rather than quietly taken.
6159    #[test]
6160    fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
6161        let (opts, _) = compile(&["-c", "a.c"]);
6162        assert!(!opts.lto.requested, "nothing asks unless the command line does");
6163
6164        let (opts, _) = compile(&["-flto", "-c", "a.c"]);
6165        assert!(opts.lto.requested);
6166        assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
6167
6168        // The last of the two directions wins, the same as every other pair of `-f` spellings.
6169        assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
6170        assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
6171
6172        // A count is a count, and asking for one implies asking for the optimization.
6173        for (spelling, want) in [
6174            ("auto", LtoJobs::Auto),
6175            ("jobserver", LtoJobs::Jobserver),
6176            ("1", LtoJobs::One),
6177            ("8", LtoJobs::Count(8)),
6178        ] {
6179            let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
6180            assert_eq!(opts.lto.jobs, want, "{spelling}");
6181            assert!(opts.lto.requested, "{spelling} asks for it too");
6182        }
6183
6184        // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
6185        // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
6186        // different compiler and gets told so here rather than getting a serial link.
6187        for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
6188            let failed = refused(&[bad, "-c", "a.c"]);
6189            assert!(failed.contains("link time jobs"), "{bad}: {failed}");
6190        }
6191
6192        // How the program is cut up before the work is spread over it.
6193        assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
6194        for (spelling, want) in [
6195            ("balanced", Partition::Balanced),
6196            ("1to1", Partition::OneToOne),
6197            ("one", Partition::One),
6198            ("max", Partition::Max),
6199            ("none", Partition::None),
6200        ] {
6201            let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
6202            assert_eq!(opts.lto.partition, want, "{spelling}");
6203        }
6204        assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
6205
6206        // And how hard the bytecode is compressed on its way into the object, which is zstd's
6207        // range of levels and is the range gcc checks an argument against.
6208        assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
6209        assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
6210        let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
6211        assert_eq!(opts.lto.compression, Some(19));
6212        for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
6213            let failed = refused(&[bad, "-c", "a.c"]);
6214            assert!(failed.contains("compression level"), "{bad}: {failed}");
6215        }
6216
6217        // The two pairs that describe an arrangement rather than ask for one. Every object here
6218        // holds its machine code, so the fat spelling is what already happens and the other is a
6219        // smaller file rather than a different program, and the plugin pair is about a tool the
6220        // design in `spec/09-optimizer.md` never loads.
6221        for taken in [
6222            "-ffat-lto-objects",
6223            "-fno-fat-lto-objects",
6224            "-fuse-linker-plugin",
6225            "-fno-use-linker-plugin",
6226        ] {
6227            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6228            assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
6229        }
6230    }
6231
6232    /// The profile family, which is the only one here that splits down the middle.
6233    ///
6234    /// Reading a profile is taken and writing one is refused, and the line between them is the one
6235    /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
6236    /// slower than it could have been, and ignoring a request to write them means a file the build
6237    /// declared as an output never appears.
6238    #[test]
6239    fn reading_a_profile_is_taken_and_writing_one_is_refused() {
6240        let (opts, _) = compile(&["-c", "a.c"]);
6241        assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
6242        assert_eq!(opts.profile_data.path, None);
6243
6244        let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
6245        assert!(opts.profile_data.requested);
6246        assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
6247
6248        let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
6249        assert!(opts.profile_data.requested, "naming a path asks for it too");
6250        assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
6251
6252        // The last of the two directions wins, the same as every other pair of `-f` spellings.
6253        assert!(
6254            !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
6255        );
6256        assert!(
6257            compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
6258        );
6259
6260        // The rest of the reading half, which is where the files are and three answers about what
6261        // to make of what is in them.
6262        let (opts, _) = compile(&[
6263            "-fprofile-dir=/build/profiles",
6264            "-fprofile-abs-path",
6265            "-fprofile-correction",
6266            "-fprofile-partial-training",
6267            "-c",
6268            "a.c",
6269        ]);
6270        assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
6271        assert!(opts.profile_data.absolute);
6272        assert!(opts.profile_data.correction);
6273        assert!(opts.profile_data.partial_training);
6274
6275        // Writing one, which is refused by name. The first four instrument the program and the
6276        // last writes a file beside the object, and a build that got neither and no message would
6277        // go on to optimize against counts that were never gathered.
6278        for writing in [
6279            "-fprofile-generate",
6280            "-fprofile-generate=/build/profiles",
6281            "-fprofile-arcs",
6282            "--coverage",
6283            "-fcondition-coverage",
6284            "-fpath-coverage",
6285        ] {
6286            let failed = refused(&[writing, "-c", "a.c"]);
6287            assert!(failed.contains("instrument"), "{writing}: {failed}");
6288        }
6289        assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
6290
6291        // The negative spellings of the refused half are what already happens, so they are taken.
6292        for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
6293            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6294            assert!(!opts.profile_data.requested, "{taken} asks for nothing");
6295        }
6296
6297        // And the flags that describe the instrumentation that is refused above, which are checked
6298        // and dropped. Checked because a typo is worth finding here rather than on the day the
6299        // instrumentation lands.
6300        for taken in [
6301            "-fprofile-update=single",
6302            "-fprofile-update=atomic",
6303            "-fprofile-update=prefer-atomic",
6304            "-fprofile-reproducible=serial",
6305            "-fprofile-reproducible=parallel-runs",
6306            "-fprofile-reproducible=multithreaded",
6307            "-fprofile-values",
6308            "-fno-profile-values",
6309            "-fprofile-info-section",
6310            "-fprofile-filter-files=a.c",
6311            "-fprofile-exclude-files=b.c",
6312            "-fprofile-note=a.gcno",
6313        ] {
6314            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6315            assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
6316        }
6317        assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
6318        assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
6319    }
6320
6321    /// The sanitizers, which are refused by name and are the one family refused for a reason that
6322    /// is not about the bytes.
6323    ///
6324    /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
6325    /// for one and was quietly given a program with no checks in it gets a test suite that passes
6326    /// for the wrong reason rather than a slower program.
6327    #[test]
6328    fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
6329        for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
6330            let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
6331            assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
6332            assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
6333        }
6334
6335        // A list is every name in it, and the first one still standing is the one named.
6336        let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
6337        assert!(failed.contains("address"), "{failed}");
6338
6339        // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
6340        // with a typo in it has a different problem from somebody who wrote a real one.
6341        for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
6342            let failed = refused(&[bad, "-c", "a.c"]);
6343            assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
6344        }
6345
6346        // gcc takes `all` only in the negative, and so does this.
6347        assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
6348
6349        // Asking and then taking it back is asking for nothing, which is why the answer waits for
6350        // the end of the line. A build whose shared flags turn a check on and whose rule for one
6351        // file turns it off again compiles that file here.
6352        for pair in [
6353            ["-fsanitize=address", "-fno-sanitize=address"],
6354            ["-fsanitize=address,undefined", "-fno-sanitize=all"],
6355            ["-fsanitize=undefined", "-fno-sanitize=undefined"],
6356        ] {
6357            let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
6358            assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
6359        }
6360        // And the other order still asks, because the last word is the one that counts.
6361        assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
6362
6363        // What a check does when it fires is an answer about checks that are refused, so there is
6364        // nothing left for it to change and it is taken.
6365        for taken in [
6366            "-fsanitize-recover=undefined",
6367            "-fno-sanitize-recover=all",
6368            "-fsanitize-trap=undefined",
6369            "-fno-sanitize-trap=all",
6370            "-fsanitize-undefined-trap-on-error",
6371            "-fsanitize-address-use-after-scope",
6372            "-fno-sanitize-address-use-after-scope",
6373            "-fsanitize-sections=.data",
6374        ] {
6375            let (opts, _) = compile(&[taken, "-c", "a.c"]);
6376            assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
6377        }
6378        assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
6379
6380        // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
6381        // feedback runs blind and never says so.
6382        let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
6383        assert!(failed.contains("feedback"), "{failed}");
6384        let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
6385        assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
6386    }
6387
6388    #[test]
6389    fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
6390        assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6391        assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6392        assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
6393    }
6394
6395    #[test]
6396    fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
6397        let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
6398        let (opts, _) =
6399            compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
6400        assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
6401        let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
6402        assert!(wrong.contains("sysv convention"), "{wrong}");
6403    }
6404
6405    /// Whether a unit built with that command line has the extension called `name`.
6406    fn has(line: &[&str], name: &str) -> bool {
6407        let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6408        let (opts, _) = compile(&[&x86[..], line].concat());
6409        opts.isa.has(rucc_target::Feature::named(name).expect("a feature"))
6410    }
6411
6412    #[test]
6413    fn the_sse_flags_and_the_processor_levels_name_extensions() {
6414        // tamnd/rucc#2003. Every one of these was an unknown option before, and Postgres's
6415        // configure probe for the CRC-32C intrinsics is compiled with the first.
6416        assert!(has(&["-msse4.2"], "sse4.2") && has(&["-msse4.2"], "crc32"));
6417        assert!(has(&["-msse4.2"], "ssse3") && has(&["-msse4.2"], "popcnt"));
6418        assert!(!has(&[], "sse3") && !has(&[], "popcnt"));
6419        assert!(has(&["-mssse3"], "sse3") && !has(&["-mssse3"], "sse4.1"));
6420        assert!(has(&["-msse4"], "sse4.2") && !has(&["-msse4", "-mno-sse4"], "sse4.1"));
6421        assert!(has(&["-mpopcnt"], "popcnt") && !has(&["-mpopcnt"], "sse3"));
6422        assert!(has(&["-mcrc32"], "crc32"));
6423        assert!(has(&["-mxsave"], "xsave") && !has(&["-mxsave", "-mno-xsave"], "xsave"));
6424        assert!(!has(&["-msse4.2", "-mno-popcnt"], "popcnt"));
6425        // A processor supplies what no flag spoke for, whichever order they came in.
6426        assert!(has(&["-march=x86-64-v2"], "sse4.2"));
6427        assert!(!has(&["-march=x86-64-v2", "-mno-sse4.2"], "sse4.2"));
6428        assert!(!has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.2"));
6429        assert!(has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.1"));
6430        assert!(!has(&["-march=x86-64-v2", "-march=x86-64"], "sse3"));
6431        // One it has no list for is the baseline, as it was when all of them were.
6432        assert!(!has(&["-march=pentium-m"], "sse3"));
6433        assert!(has(&["-march=x86-64-v3"], "avx2"));
6434        // Turning off what is never on is nothing, and the flag is still gcc's.
6435        assert!(!has(&["-mno-avx512f"], "avx512f"));
6436    }
6437
6438    #[test]
6439    fn an_extension_this_compiler_cannot_provide_for_a_whole_unit_is_refused() {
6440        let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6441        let said = refused(&[&x86[..], &["-mavx2"]].concat());
6442        assert!(said.contains("no intrinsics for avx2"), "{said}");
6443        let said = refused(&[&x86[..], &["-mno-sse2"]].concat());
6444        assert!(said.contains("baseline"), "{said}");
6445        assert!(refused(&[&x86[..], &["-msse5"]].concat()).contains("unknown option"));
6446        // No other target has these, whichever side of the target the flag was written on.
6447        let said = refused(&["-msse4.2", "--target=aarch64-linux-gnu", "-c", "a.c"]);
6448        assert!(said.contains("unknown option `-msse4.2`"), "{said}");
6449        let (opts, _) = compile(&["--target=aarch64-linux-gnu", "-march=armv8-a+crc", "-c", "a.c"]);
6450        assert_eq!(opts.isa, rucc_target::Isa::NONE);
6451    }
6452
6453    #[test]
6454    fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
6455        let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
6456        assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
6457        // After the input, because a static link takes what it needs from a library when it
6458        // reaches it and not afterwards.
6459        let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
6460        assert_eq!(names, vec!["a.c"]);
6461    }
6462
6463    #[test]
6464    fn the_version_banner_keeps_our_first_line_and_takes_meson_down_the_gnu_path() {
6465        let text = banner();
6466        let mut lines = text.lines();
6467        // Every harness we have reads the first line and nothing else.
6468        assert_eq!(lines.next(), Some(format!("rucc {VERSION}").as_str()));
6469        // The words meson looks for, in `mesonbuild/compilers/detect.py`.
6470        assert!(text.contains("Free Software Foundation"), "{text}");
6471        // GCC's own banner has three lines and so does this one, and the claim is the dialect.
6472        assert!(lines.next().is_some_and(|l| l.contains("GCC 16")), "{text}");
6473        assert!(lines.next().is_some() && lines.next().is_none(), "{text}");
6474    }
6475
6476    #[test]
6477    fn the_questions_a_build_system_asks_before_it_compiles_anything() {
6478        let target = "--target=x86_64-unknown-linux-gnu";
6479        assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
6480        assert_eq!(printed(&[target, "-dumpversion"]), "16");
6481        assert_eq!(printed(&[target, "-dumpfullversion"]), "16.0.0");
6482        // They follow the release claimed, since that is the one `__GNUC__` says.
6483        assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpversion"]), "15");
6484        assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpfullversion"]), "15.2.0");
6485        assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
6486        // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
6487        // answer safe to paste into a link line whether or not the file is there.
6488        assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
6489        assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
6490        let dirs = printed(&[target, "-print-search-dirs"]);
6491        assert!(dirs.starts_with("install: "), "{dirs}");
6492        assert!(dirs.contains("\nlibraries: ="), "{dirs}");
6493    }
6494
6495    #[test]
6496    fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
6497        // A tree the user named is the answer whatever the target is, because it is the answer to
6498        // every other question too.
6499        assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
6500
6501        // A target that is no machine this suite runs on is read under the cache, and the answer is
6502        // the root rather than one of the directories under it, since what asks is looking for a
6503        // file of its own.
6504        let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
6505        assert_eq!(
6506            printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
6507            root.display().to_string()
6508        );
6509
6510        // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
6511        // was configured without one rather than a `/` that would be a claim about the filesystem.
6512        let host = Triple::host().expect("a host this compiler knows");
6513        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot"]), "");
6514    }
6515
6516    #[test]
6517    fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
6518        // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
6519        // is the record that already has them, so the flag prints that rather than a second format.
6520        let manifest = "rucc sysroot manifest 3\n\
6521                        target\tx86_64-linux-musl\n\
6522                        kernel\t6.12\n\
6523                        include/generic/stdio.h\tmusl-1.2.5\t\
6524                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6525                        0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
6526                        bundled\n\
6527                        lib/libc.so\tmusl-1.2.5\t\
6528                        https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6529                        1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
6530                        generated\n";
6531        let tree = TempTree::new("provenance", &[("manifest", manifest)]);
6532        let sysroot = format!("--sysroot={}", tree.0.display());
6533        // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
6534        // the flag parses the record and renders it again rather than picking fields out of it. That
6535        // is the reason it prints a manifest and not a format of its own.
6536        //
6537        // The answer is the file without its last newline, because whatever prints it adds one. The
6538        // file is what somebody diffs the output against, so the two have to be the same bytes.
6539        assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
6540
6541        // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
6542        // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
6543        // tell it from a manifest with no inputs because that one still has its two header lines.
6544        let bare = TempTree::new("provenance-bare", &[]);
6545        assert_eq!(
6546            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
6547            ""
6548        );
6549
6550        // And a compile for this machine has no sysroot at all, which is the same empty answer
6551        // `-print-sysroot` gives for it.
6552        let host = Triple::host().expect("a host this compiler knows");
6553        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
6554
6555        // And the other spelling, which section 13.5 is the document that writes.
6556        assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
6557
6558        // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
6559        // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
6560        // the bytes it is over are the bytes of the file. The number here is that hash of the
6561        // fixture above, computed by `sha256sum` rather than by this compiler.
6562        assert_eq!(
6563            printed(&[&sysroot, "-print-sysroot-digest"]),
6564            "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
6565        );
6566        assert_eq!(
6567            printed(&[&sysroot, "--print-sysroot-digest"]),
6568            printed(&[&sysroot, "-print-sysroot-digest"])
6569        );
6570
6571        // And the two empty answers are empty here too, because a digest of nothing would read as a
6572        // claim about a sysroot rather than as the absence of one.
6573        assert_eq!(
6574            printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
6575            ""
6576        );
6577        assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
6578    }
6579
6580    #[test]
6581    fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
6582        // Passing a file we could not parse to whoever asked would make their parser the one that
6583        // finds the problem, and the three uses section 13.5 gives for this are all somebody else
6584        // parsing it.
6585        let tree = TempTree::new(
6586            "provenance-bad",
6587            &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
6588        );
6589        let message =
6590            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
6591        assert!(message.contains("manifest"), "{message}");
6592        assert!(message.contains("1 fields where an input has six"), "{message}");
6593
6594        // The digest is refused for the same file and for a stronger reason: a hash of bytes this
6595        // build cannot read would be a number that names a record nobody can act on.
6596        let digest =
6597            refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
6598        assert_eq!(digest, message);
6599    }
6600
6601    #[test]
6602    fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
6603        let (opts, _) = compile(&["-M", "a.c"]);
6604        assert!(opts.deps.emit && opts.deps.instead_of_compiling);
6605        assert!(opts.deps.system_headers, "plain -M lists them");
6606        assert_eq!(opts.emit, EmitKind::Preprocessed);
6607
6608        // Even where a later flag asked for something else, because the family is a mode and
6609        // the mode is what the run is for.
6610        let (opts, _) = compile(&["-M", "-c", "a.c"]);
6611        assert_eq!(opts.emit, EmitKind::Preprocessed);
6612
6613        let (opts, _) = compile(&["-MM", "a.c"]);
6614        assert!(!opts.deps.system_headers);
6615    }
6616
6617    #[test]
6618    fn the_two_that_end_in_d_leave_the_compilation_alone() {
6619        let (opts, _) = compile(&["-MD", "-c", "a.c"]);
6620        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6621        assert!(opts.deps.system_headers);
6622        assert_eq!(opts.emit, EmitKind::Object);
6623
6624        let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
6625        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6626        assert!(!opts.deps.system_headers);
6627    }
6628
6629    #[test]
6630    fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
6631        // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
6632        // the answer, because the other one never asked the question.
6633        let (opts, _) = compile(&["-MM", "-M", "a.c"]);
6634        assert!(!opts.deps.system_headers);
6635        let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
6636        assert!(!opts.deps.system_headers);
6637        let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
6638        assert!(!opts.deps.system_headers);
6639    }
6640
6641    #[test]
6642    fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
6643        let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
6644        assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
6645    }
6646
6647    #[test]
6648    fn the_rest_of_the_family_is_a_file_and_a_switch() {
6649        let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
6650        assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
6651        assert!(opts.deps.phony);
6652
6653        for flag in ["-MF", "-MT", "-MQ"] {
6654            let e = parse_args(&args(&[flag])).unwrap_err();
6655            assert!(e.message.contains("requires an argument"), "{}", e.message);
6656        }
6657    }
6658
6659    /// Kbuild's spelling, which is how busybox and the kernel ask for every dependency file.
6660    #[test]
6661    fn a_dependency_file_asked_for_through_the_preprocessor_is_written_where_it_said() {
6662        let (opts, _) = compile(&["-Wp,-MD,applets/.applets.o.d", "-c", "a.c"]);
6663        assert!(opts.deps.emit);
6664        assert!(opts.deps.system_headers);
6665        assert_eq!(opts.deps.file.as_deref(), Some("applets/.applets.o.d"));
6666
6667        let (opts, _) = compile(&["-Wp,-MMD,x.d,-MP,-MT,x.o", "-c", "a.c"]);
6668        assert!(!opts.deps.system_headers);
6669        assert!(opts.deps.phony);
6670        assert_eq!(opts.deps.file.as_deref(), Some("x.d"));
6671        assert_eq!(opts.deps.targets, vec!["x.o".to_owned()]);
6672    }
6673
6674    #[test]
6675    fn a_preprocessor_flag_this_compiler_does_not_read_is_still_refused_whole() {
6676        assert!(refused(&["-Wp,-MD", "-c", "a.c"]).contains("separate assembler"));
6677        assert!(refused(&["-Wp,-MD,x.d,-C", "-c", "a.c"]).contains("-Wp,-MD,x.d,-C"));
6678    }
6679
6680    /// A directory of sources for one test, removed when the test is done with it.
6681    struct TempTree(PathBuf);
6682
6683    impl Drop for TempTree {
6684        fn drop(&mut self) {
6685            let _ = std::fs::remove_dir_all(&self.0);
6686        }
6687    }
6688
6689    impl TempTree {
6690        fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
6691            let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
6692            let _ = std::fs::remove_dir_all(&dir);
6693            std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
6694            for (path, text) in files {
6695                let at = dir.join(path);
6696                if let Some(parent) = at.parent() {
6697                    std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
6698                }
6699                std::fs::write(&at, text).expect("writing a temporary file should work");
6700            }
6701            TempTree(dir)
6702        }
6703
6704        fn path(&self, name: &str) -> String {
6705            self.0.join(name).to_string_lossy().into_owned()
6706        }
6707    }
6708
6709    #[test]
6710    fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
6711        // End to end, because the list comes from the preprocessor and the format comes from
6712        // somewhere else, and a test of either half on its own would pass with the two of them
6713        // wired up backwards.
6714        let tree = TempTree::new(
6715            "found",
6716            &[
6717                ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
6718                ("one.h", "#define X 0\n"),
6719                ("two.h", "#include \"one.h\"\n"),
6720            ],
6721        );
6722        let out = tree.path("dep.d");
6723        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6724        assert_eq!(code, 0);
6725
6726        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6727        let names: Vec<&str> = text.split_whitespace().collect();
6728        // The target, the source, and each header once however many times it was reached.
6729        assert_eq!(names.first(), Some(&"a.o:"), "{text}");
6730        assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
6731        assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
6732        // And the `-o` went to the file the rule replaced, which is left empty rather than
6733        // absent because a makefile that named it as a target will look for it.
6734        assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
6735    }
6736
6737    #[test]
6738    fn syntax_only_checks_the_file_and_writes_nothing() {
6739        // What meson's `has_header_symbol` probe does: compile with `-fsyntax-only` and read the
6740        // exit status. A good file passes and leaves no output behind, a bad one fails.
6741        let tree = TempTree::new(
6742            "syntax-only",
6743            &[
6744                ("good.c", "int f(int x) { return x + 1; }\n"),
6745                ("bad.c", "int f(void) { return y; }\n"),
6746            ],
6747        );
6748        let (opts, _) = compile(&["-fsyntax-only", "a.c"]);
6749        assert_eq!(opts.emit, EmitKind::SyntaxOnly);
6750
6751        let out = tree.path("good.o");
6752        assert_eq!(run(&args(&["-fsyntax-only", "-o", &out, &tree.path("good.c")])), 0);
6753        assert!(!std::path::Path::new(&out).exists(), "-fsyntax-only wrote {out}");
6754        assert!(!std::path::Path::new(&tree.path("good.s")).exists());
6755        assert_ne!(run(&args(&["-fsyntax-only", &tree.path("bad.c")])), 0);
6756    }
6757
6758    /// Where `-fstack-usage` puts each job's report, one entry per job, for a command line.
6759    fn stack_usage_files(line: &[&str]) -> Vec<Option<String>> {
6760        let mut words = vec![LINUX, "-fstack-usage"];
6761        words.extend_from_slice(line);
6762        let (_, plan) = compile(&words);
6763        plan.jobs.iter().map(|job| job.stack_usage.clone()).collect()
6764    }
6765
6766    #[test]
6767    fn a_stack_usage_file_is_named_the_way_gcc_names_it() {
6768        // Every row was run through gcc 16 with the same command line, and the name is the one it
6769        // wrote. `rpg frames` finds gcc's file and this compiler's by the same rule, so a name that
6770        // differs is a function that goes missing from the comparison.
6771        let cases: &[(&[&str], &[Option<&str>])] = &[
6772            (&["-c", "sub/a.c"], &[Some("a.su")]),
6773            (&["-c", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.su")]),
6774            (&["-c", "sub/a.c", "b.c"], &[Some("a.su"), Some("b.su")]),
6775            (&["-S", "sub/a.c", "-o", "out/y.s"], &[Some("out/y.su")]),
6776            (&["-S", "sub/a.c", "-o", "-"], &[Some("a.su")]),
6777            (&["-E", "sub/a.c", "-o", "out/z.i"], &[None]),
6778            (&["-fsyntax-only", "sub/a.c"], &[Some("a.su")]),
6779            (&["-fsyntax-only", "sub/a.c", "-o", "out/x.o"], &[Some("out/x.o-a.su")]),
6780            (&["sub/a.c"], &[Some("a.su")]),
6781            (&["sub/a.c", "-lm"], &[Some("a.su")]),
6782            (&["sub/a.c", "b.c"], &[Some("a-a.su"), Some("a-b.su")]),
6783            (&["sub/a.c", "b.o"], &[Some("a-a.su"), None]),
6784            (&["sub/a.c", "-o", "out/prog"], &[Some("out/prog-a.su")]),
6785            (&["sub/a.c", "-o", "out/lib.so"], &[Some("out/lib.so-a.su")]),
6786            (&["sub/a.c", "-o", "out/prog.exe"], &[Some("out/prog-a.su")]),
6787            (&["sub/a.c", "-o", "out/prog", "-dumpbase", "zz"], &[Some("out/zz-a.su")]),
6788            (&["sub/a.c", "-o", "out/prog", "-dumpdir", "dd-"], &[Some("dd-a.su")]),
6789            (
6790                &["sub/a.c", "b.c", "-dumpdir", "dd/", "-dumpbase", "zz"],
6791                &[Some("dd/zz-a.su"), Some("dd/zz-b.su")],
6792            ),
6793            (&["-c", "sub/a.c", "-dumpbase", "foo", "-o", "out/w.o"], &[Some("out/foo.su")]),
6794            (&["-c", "sub/a.c", "-dumpdir", "dd/", "-dumpbase", "sub/zz"], &[Some("sub/zz.su")]),
6795            (&["-c", "sub/a.c", "-dumpbase", "zz.c", "-dumpbase-ext", ".c"], &[Some("zz.su")]),
6796            (&["-c", "sub/a.c", "-dumpdir", "pre", "-o", "out/x.o"], &[Some("prex.su")]),
6797            (&["-c", "sub/a.c", "-save-temps=cwd", "-o", "out/x.o"], &[Some("x.su")]),
6798        ];
6799        for (line, want) in cases {
6800            let want: Vec<Option<String>> = want.iter().map(|w| w.map(str::to_owned)).collect();
6801            assert_eq!(stack_usage_files(line), want, "{line:?}");
6802        }
6803        // Nothing at all without the flag.
6804        let (_, plan) = compile(&[LINUX, "-c", "sub/a.c"]);
6805        assert_eq!(plan.jobs[0].stack_usage, None);
6806    }
6807
6808    #[test]
6809    fn a_stack_usage_file_has_a_line_per_function_where_gcc_would_put_it() {
6810        let tree = TempTree::new(
6811            "stack-usage",
6812            &[
6813                ("inc/h.h", "static inline int twice(int x) { return x * 2; }\n"),
6814                (
6815                    "a.c",
6816                    "#include \"inc/h.h\"\n\
6817                     static int helper(int);\n\
6818                     int grows(int n) { char v[n]; v[0] = (char)n; return v[n - 1] + twice(n); }\n\
6819                     static int\n\
6820                     helper(int x)\n\
6821                     {\n\
6822                     return x + 1;\n\
6823                     }\n\
6824                     int calls(int x) { return helper(x) + grows(x); }\n",
6825                ),
6826            ],
6827        );
6828        let (source, object) = (tree.path("a.c"), tree.path("a.o"));
6829        assert_eq!(run(&args(&["-O0", "-fstack-usage", "-c", &source, "-o", &object])), 0);
6830        let text = std::fs::read_to_string(tree.path("a.su")).expect("a.su should be written");
6831
6832        let line = |function: &str| {
6833            let suffix = format!(":{function}");
6834            let line =
6835                text.lines().find(|line| line.split('\t').next().unwrap().ends_with(&suffix));
6836            line.unwrap_or_else(|| panic!("no line for {function} in\n{text}"))
6837        };
6838        let expect = |function: &str, at: String, qualifier: &str| {
6839            let fields: Vec<&str> = line(function).split('\t').collect();
6840            assert_eq!(fields.len(), 3, "{text}");
6841            assert_eq!(fields[0], format!("{at}:{function}"), "{text}");
6842            let bytes: u32 = fields[1].parse().expect("the bytes should be a number");
6843            assert!(bytes >= 8 && bytes % 8 == 0, "{function} takes {bytes} bytes");
6844            assert_eq!(fields[2], qualifier, "{text}");
6845        };
6846        // A variable length array makes the frame grow while the function runs.
6847        expect("grows", format!("{source}:3:5"), "dynamic");
6848        // The definition rather than the declaration above it, and the line the name is on
6849        // rather than the one the type is on.
6850        expect("helper", format!("{source}:5:1"), "static");
6851        expect("calls", format!("{source}:9:5"), "static");
6852        // A function from a header is reported against the header.
6853        expect("twice", format!("{}:1:19", tree.path("inc/h.h")), "static");
6854        assert_eq!(text.lines().count(), 4, "{text}");
6855    }
6856
6857    #[test]
6858    fn a_stack_usage_file_is_empty_when_there_is_nothing_to_report_and_absent_under_dash_e() {
6859        let tree = TempTree::new(
6860            "stack-usage-empty",
6861            &[
6862                ("good.c", "int f(int x) { return x + 1; }\n"),
6863                ("bad.c", "int f(void) { return y; }\n"),
6864            ],
6865        );
6866        let good = tree.path("good.c");
6867        // gcc writes an empty file for a check that compiles nothing and for a file that failed,
6868        // and a build that looks for one beside every object finds one.
6869        assert_eq!(
6870            run(&args(&["-fstack-usage", "-fsyntax-only", &good, "-o", &tree.path("x")])),
6871            0
6872        );
6873        assert_eq!(std::fs::read_to_string(tree.path("x-good.su")).unwrap(), "");
6874        let bad = tree.path("bad.c");
6875        assert_ne!(run(&args(&["-fstack-usage", "-c", &bad, "-o", &tree.path("bad.o")])), 0);
6876        assert_eq!(std::fs::read_to_string(tree.path("bad.su")).unwrap(), "");
6877        // And none under `-E`, which never reaches a function.
6878        assert_eq!(run(&args(&["-fstack-usage", "-E", &good, "-o", &tree.path("e.i")])), 0);
6879        assert!(!std::path::Path::new(&tree.path("e.su")).exists());
6880    }
6881
6882    #[test]
6883    fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
6884        // The multiple-include optimization means the second reach never opens the file. It is
6885        // still a file this translation unit was built from, so it is still in the rule.
6886        let tree = TempTree::new(
6887            "guarded",
6888            &[
6889                ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
6890                ("g.h", "#ifndef G\n#define G\n#endif\n"),
6891            ],
6892        );
6893        let out = tree.path("dep.d");
6894        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6895        assert_eq!(code, 0);
6896        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6897        assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
6898    }
6899
6900    #[test]
6901    fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
6902        // Measured against GCC rather than read: the two flags the other way round produce the
6903        // same output byte for byte, so the command line order between the two families does not
6904        // decide anything and the order within one does. The `-include` file here can only see
6905        // the definition if the `-imacros` file that was written after it ran first.
6906        let tree = TempTree::new(
6907            "preinclude",
6908            &[
6909                ("a.c", "int main(void) { return 0; }\n"),
6910                ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
6911                ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
6912            ],
6913        );
6914        let out = tree.path("a.i");
6915        let code = run(&args(&[
6916            "-E",
6917            "-include",
6918            &tree.path("i.h"),
6919            "-imacros",
6920            &tree.path("m.h"),
6921            "-o",
6922            &out,
6923            &tree.path("a.c"),
6924        ]));
6925        assert_eq!(code, 0);
6926        let text = std::fs::read_to_string(&out).expect("the output should have been written");
6927        assert!(text.contains("saw_it"), "{text}");
6928        // And the text of the `-imacros` file is thrown away, which is the whole difference
6929        // between the two flags.
6930        assert!(!text.contains("macros_text"), "{text}");
6931    }
6932
6933    #[test]
6934    fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
6935        let tree = TempTree::new(
6936            "preinclude-deps",
6937            &[
6938                ("a.c", "int main(void) { return 0; }\n"),
6939                ("i.h", "int from_include;\n"),
6940                ("m.h", "#define M 1\n"),
6941            ],
6942        );
6943        let out = tree.path("dep.d");
6944        let code = run(&args(&[
6945            "-MM",
6946            "-MF",
6947            &out,
6948            "-include",
6949            &tree.path("i.h"),
6950            "-imacros",
6951            &tree.path("m.h"),
6952            "-o",
6953            &tree.path("a.i"),
6954            &tree.path("a.c"),
6955        ]));
6956        assert_eq!(code, 0);
6957        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6958        assert!(text.contains("i.h"), "{text}");
6959        assert!(text.contains("m.h"), "{text}");
6960    }
6961
6962    #[test]
6963    fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
6964        // Including the directory of the source file, which is not on the path for these: the
6965        // command line was not written there, so a name in it is relative to where the compiler
6966        // was run rather than to where the source sits.
6967        let tree = TempTree::new(
6968            "preinclude-missing",
6969            &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
6970        );
6971        let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
6972        assert_eq!(code, 1);
6973    }
6974
6975    #[test]
6976    fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
6977        // The object a link goes through is in a temporary directory and is gone before `make`
6978        // reads any of this, so the rule that named it would be a rule for a file that is never
6979        // there. The target and the file are both the `-o`, which is the executable.
6980        let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
6981        assert_eq!(plan.output.as_deref(), Some("prog"));
6982        assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
6983        assert_eq!(
6984            deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
6985            Some("prog.d")
6986        );
6987    }
6988
6989    #[test]
6990    fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
6991        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
6992        assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
6993        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
6994        assert_eq!(plan.output, None);
6995    }
6996
6997    #[test]
6998    fn usage_fits_on_a_screen() {
6999        // Not a style preference. A help text that scrolls is one nobody reads, and this is
7000        // the cheapest way to keep it honest as flags accumulate. The number goes up only when
7001        // a family of flags arrives that has nowhere to share a line, which the two pass gates
7002        // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
7003        // the lines that family took. The four it went up by last are the flags a build system
7004        // passes without being asked to: how much to say, what machine to generate for, threads,
7005        // and the questions `configure` asks before it compiles anything. The one it went up by
7006        // last is the second line of `--emit`, whose kinds are a family that has now outgrown
7007        // one line and has nowhere else to go. The two it went up by last are the dependency
7008        // family, which is eight flags that share nothing with anything above them. The one it
7009        // went up by last is the four spellings of position independent code, which every
7010        // configure script writes and which could only have shared the link line, and that line
7011        // is already four characters short of the limit. The two it went up by last are the rest
7012        // of the include family, which is six more flags that change where a header is looked for
7013        // and two that name a header outright. The one it went up by last is the pair that keeps
7014        // the intermediate files and times the steps, which belong next to the two flags above
7015        // them that are also about watching a compilation rather than changing one. The two it
7016        // went up by last are the section flags and the visibility flag, which are what a build
7017        // that cares about the size of what it ships and about which names it exports writes, and
7018        // the second of them was already taken and only missing from here. The one it went up by
7019        // last is the stack protector, which is four spellings of one question and which every
7020        // distribution puts on every command line it issues, so a build that reads this list
7021        // looking for it and does not find it has to go and read the specification instead. The one
7022        // it went up by last is the profiler, which is two spellings of the request and two of
7023        // where the call goes, and which is about watching a program run rather than about what is
7024        // generated, so it shares its subject with nothing above it. The one it went up by last is
7025        // the room a function opens with for something to be written over it later, which takes an
7026        // argument of its own shape and is what a kernel build asks for, so it fits beside the
7027        // profiler and nothing else. The one it went up by last is what overflows rather than being
7028        // undefined, which is three spellings of two questions and which a kernel build and a great
7029        // deal of code written before the standard settled both pass. The one it went up by last is
7030        // the other answer to the first of those questions, which could not share the line because
7031        // what it asks for is the opposite of what the flags on that line ask for. The one it went
7032        // up by last is the split of the line that lists what this compiler does anyway into that
7033        // and what it assumes anyway, which are two different claims that were sharing a line until
7034        // the second of them got a second flag and the line stopped fitting. The one it went up by
7035        // last is the three flags that change the ABI rather than the code, which have to be given
7036        // to every file in a program or none of them and which therefore belong somewhere a person
7037        // reading this list will see them. The one it went up by last is the floating point group,
7038        // which is two lines rather than one because the first of them is a choice this compiler
7039        // records and the rest are claims about what it does anyway, and putting a real setting on
7040        // the same line as three flags that change nothing would be misleading about both. The one
7041        // it went up by last is the flag that says a write has to stay inside the member it names,
7042        // which is a setting rather than a claim and so cannot share the line above it, that being
7043        // the one that picks a tier. The two it went up by last are the prefix mapping family,
7044        // which is four flags whose whole job is to keep a build's output the same from two
7045        // different directories, and which a person chasing a reproducible build comes here
7046        // looking for by name. The one it went up by last is how the debug sections are compressed
7047        // and whether they go in a file of their own, which are two questions about the shape of
7048        // the debug output, where the line above them is about how much of it there is. The one it
7049        // went up by last is the `restrict` contract, which is a setting for the same reason the
7050        // flag that keeps a write inside its member is and which is the check a person who has been
7051        // bitten by a vectorizer comes here looking for. The one it went up by last is link time
7052        // optimization, which is a whole optimization rather than a flag and which says so on its
7053        // own line, because a build that passes it and reads this looking for what it got is
7054        // asking a question no other line here answers. The one it went up by last is the sysroot,
7055        // which is the question somebody asks when a cross build read a file nobody expected, and
7056        // which has no room on the line above it because the answers there are a path each and this
7057        // one is the root all of them are under. The one it went up by last is what is inside that
7058        // root and where each of it came from, which is a question about a whole tree rather than
7059        // about a path and which is long enough on its own that it could not have shared a line with
7060        // anything. The one it went up by last is the profile family, which splits down the middle
7061        // where no other family here does, so the line has to name the half that is taken and the
7062        // half that is refused or it would be read as taking both. The one it went up by last is
7063        // the sanitizers, which are what somebody reaching for a checked build writes first and
7064        // which belong beside the tier that is the nearest thing here to what they asked for. The
7065        // one it went up by last is the digest of that record, which is the same tree as one number
7066        // and could not share the line above it because that line prints a few hundred lines and
7067        // this one prints sixty four characters, and a reader who wants the short answer is looking
7068        // for it by name rather than reading the long one. The one it went up by last is the
7069        // sysroot fetch, which is the only command here that gets something from somewhere else and
7070        // is therefore the one a person wants to have read before they run it rather than after.
7071        // And the flag beside it that forbids every download, which earns its line by being what a
7072        // build in a sealed environment passes and by meaning something even though an ordinary
7073        // compile downloads nothing either way. The one it went up by last is the other fetch, the
7074        // one behind Microsoft's licence wall, which is a line rather than a paragraph because what
7075        // a person needs from here is that the command exists and that it will not do anything
7076        // until they have read a licence it prints for them.
7077        assert!(USAGE.lines().count() < 73, "usage text has grown past one screen");
7078    }
7079}