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