Skip to main content

rucc_driver/
lib.rs

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