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.3")]
30
31pub mod compile;
32pub mod deps;
33pub mod library;
34pub mod link;
35mod map;
36pub mod phase;
37pub mod preprocess;
38pub mod schedule;
39
40use std::fmt::Write as _;
41use std::io::Write as _;
42use std::path::PathBuf;
43
44use rucc_codegen::coverage::{self, Fired};
45use rucc_pp::Dependency;
46use rucc_session::{Dumps, EmitKind, Options, Preinclude, SaveTemps, Session, Std, runtime};
47use rucc_target::Triple;
48
49use crate::link::LinkOptions;
50
51pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
52pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
53pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
54pub use crate::schedule::Jobs;
55
56/// The compiler's version, taken from the workspace manifest.
57pub const VERSION: &str = env!("CARGO_PKG_VERSION");
58
59/// What the command line asked for.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum Action {
62    /// Print usage and exit successfully.
63    Help,
64    /// Print the version and exit successfully.
65    Version,
66    /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
67    ///
68    /// A build system asks these before it compiles anything, and what it does with the answer
69    /// is paste it into a path or into another command line, so each one is a single line with
70    /// no decoration around it.
71    Print(String),
72    /// Print the resolved configuration and exit successfully.
73    PrintConfig(Box<Options>),
74    /// Print the passes the level will run and exit successfully.
75    PrintPipeline(Box<Options>),
76    /// Print the phase plan and the link line and exit successfully, which is `-###`.
77    PrintPlan {
78        /// The resolved options, which is what says what the link line is for.
79        opts: Box<Options>,
80        /// What to do to each input, and in what order.
81        plan: Box<Plan>,
82        /// What the command line said about linking.
83        link: Box<LinkOptions>,
84    },
85    /// Compile the given inputs.
86    Compile {
87        /// The resolved options.
88        opts: Box<Options>,
89        /// What to do to each input, and in what order.
90        plan: Box<Plan>,
91        /// What the command line said about linking.
92        link: Box<LinkOptions>,
93        /// How many translation units to compile at once.
94        jobs: Jobs,
95        /// Whether `-v` asked for the plan to be printed while it runs.
96        verbose: bool,
97    },
98}
99
100/// Why a command line was rejected.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct CliError {
103    /// The message, lowercase and without a trailing period, in the same shape as any other
104    /// diagnostic.
105    pub message: String,
106}
107
108impl std::fmt::Display for CliError {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.write_str(&self.message)
111    }
112}
113
114impl std::error::Error for CliError {}
115
116fn err(message: impl Into<String>) -> CliError {
117    CliError { message: message.into() }
118}
119
120/// A question the command line asked instead of asking for a compilation.
121///
122/// These are answered after the loop rather than where they are read, because every one of them
123/// is about the target or about the library search and the last word on both is the end of the
124/// command line.
125enum Query {
126    /// `-dumpmachine`, the triple.
127    Machine,
128    /// `-dumpversion` and `-dumpfullversion`, which are the same three numbers here.
129    Version,
130    /// `-print-multiarch`, the directory name a distribution files this target under.
131    Multiarch,
132    /// `-print-search-dirs`, in the three lines GCC prints.
133    SearchDirs,
134    /// `-print-file-name=<name>`, the full path of a library file.
135    FileName(String),
136    /// `-print-prog-name=<name>`, the full path of a program.
137    ProgName(String),
138    /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
139    Libgcc,
140}
141
142/// Usage text.
143///
144/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
145/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
146pub const USAGE: &str = "\
147rucc, an optimizing C compiler
148
149usage: rucc [options] file...
150
151options:
152  -c                     compile and assemble, do not link
153  -S                     compile only, emit assembly
154  -E                     preprocess only
155  -o <file>              write output to <file>, or to standard output for -
156  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
157  -I <dir>               add <dir> to the include search path
158  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
159  -I-, -iprefix <p>, -iwithprefix[before] <dir>   the older spellings of those
160  -include <file>, -imacros <file>    read <file> first, the second for its macros only
161  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
162  -P, -dM                with -E: leave out the markers, or dump the macros
163  -M -MM -MD -MMD        write a make rule for the source, the last two compile as well
164  -MF <file> -MT <t> -MQ <t> -MP   where the rule goes, what it builds, targets with no recipe
165  -std=<dialect>         c89 through c23, and the gnu spellings
166  -fgnuc-version=<v>     the GCC release to claim, default 7.0.0
167  -x <lang>              treat later inputs as <lang>, or none to stop
168  -O<level>              optimize: 0, 1, 2, 3, s, z
169  -fsafety=<tier>        check memory safety: off, detect, enforce, kernel
170  -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
171  -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n>   stop a pass, or all of them, after n
172  -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>]   run a pass on some functions only
173  -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone   debug info, frame pointer, red zone
174  -l<name>, -L <dir>, -B <dir>   link a library, where to look for one, where our own tools are
175  -fPIC -fpic -fPIE -fpie, -fno-common, -f[no-]strict-aliasing, -pipe   what it does anyway
176  -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s   how to link
177  -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name>   hand an argument to the linker, or pick one
178  -Werror -pedantic -pedantic-errors -w   how much to say, and whether it is fatal
179  -m64 -march= -mtune= -mcpu= -mabi= -mcmodel=   what machine to generate for
180  -pthread               build for more than one thread, and link the library for it
181  -dumpmachine -dumpversion -print-multiarch -print-search-dirs   what this compiler is
182  -print-file-name=<name> -print-prog-name=<name>   where a file or a program is
183  -j[n]                  compile n translation units at once, default all
184  -v, -###               print each phase as it runs, or without running any
185  -save-temps[=cwd|obj], -time   keep the .i and the .s, say how long each step took
186  --target=<triple>      generate code for <triple>
187  --emit=<kind>          exe, obj, asm, preprocessed, tast, ir, mir-final,
188                         safety-summary, type-granules
189  --print-config, --print-pipeline    print the configuration or the pipeline, and exit
190  --version              print the version and exit
191  -h, --help             print this message and exit
192
193See spec/04-driver-and-cli.md for the full flag reference.
194";
195
196/// The argument of a flag that may be joined to it or may be the next word.
197///
198/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
199fn joined_or_next(
200    arg: &str,
201    at: usize,
202    args: &[String],
203    i: &mut usize,
204) -> Result<String, CliError> {
205    if arg.len() > at {
206        return Ok(arg[at..].to_owned());
207    }
208    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
209    *i += 1;
210    Ok(next.clone())
211}
212
213/// Parses a command line, without the program name.
214///
215/// # Errors
216///
217/// Returns the message to print when the arguments do not name a compilation this compiler
218/// can attempt.
219pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
220    let host = Triple::host()
221        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
222    let mut opts = Options::new(host);
223    let mut inputs: Vec<Input> = Vec::new();
224    let mut print_config = false;
225    let mut print_pipeline = false;
226    let mut print_plan = false;
227    let mut verbose = false;
228    let mut jobs = Jobs::default();
229    let mut nostdinc = false;
230    let mut sysroot: Option<PathBuf> = None;
231    let mut output = None;
232    let mut link = LinkOptions::default();
233    let mut query: Option<Query> = None;
234    let mut threads = false;
235    // `-x` applies to inputs that come after it and stays in effect until the next one, which
236    // is why it is tracked across the loop rather than attached to a single argument.
237    let mut forced: Option<InputKind> = None;
238    // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
239    // the flags after it and not the ones before, so a command line may set it more than once.
240    // GCC's default is its own installed header directory with the last component taken off,
241    // which is a path a cross compiler's build system knows and passes; there is no equivalent
242    // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
243    // outright.
244    let mut iprefix = String::new();
245
246    let mut i = 0;
247    while i < args.len() {
248        let arg = args[i].as_str();
249        i += 1;
250        match arg {
251            "-h" | "--help" => return Ok(Action::Help),
252            "--version" => return Ok(Action::Version),
253            "--print-config" => print_config = true,
254            "--print-pipeline" => print_pipeline = true,
255            "-###" => print_plan = true,
256            "-v" => verbose = true,
257            // The files a compilation goes through, kept rather than thrown away. The bare
258            // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
259            // gcc 16 does; `SaveTemps::Object` carries the measurement.
260            "-save-temps" => opts.save_temps = SaveTemps::Object,
261            _ if arg.starts_with("-save-temps=") => {
262                opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
263            }
264            // How long each step took. A misspelling of this is worth rejecting rather than
265            // ignoring, since a run that says nothing looks like a compilation that took no time.
266            "-time" => opts.time = true,
267            "-c" => opts.emit = EmitKind::Object,
268            "-S" => opts.emit = EmitKind::Asm,
269            "-E" => opts.emit = EmitKind::Preprocessed,
270            "-g" => opts.debug_info = true,
271            // GCC's own levels of how much debug information to write. Zero is none and every
272            // other number is some, and this compiler has one amount, so the numbers above zero
273            // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
274            // debugger on the machine prefers, which is what we emit anyway.
275            "-g0" => opts.debug_info = false,
276            "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
277                opts.debug_info = true;
278            }
279            // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
280            // asks for another version is told rather than handed a file it cannot read.
281            "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
282            _ if arg.starts_with("-gdwarf-") => {
283                return Err(err(format!(
284                    "{arg}: this compiler writes DWARF 5 and no other version, see \
285                     spec/11-debug-info.md"
286                )));
287            }
288            "-Werror" => opts.warnings_are_errors = true,
289            // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
290            // through rather than here, so that a warning `-w` dropped is not counted either.
291            "-w" => opts.warnings = false,
292            "-pedantic-errors" => {
293                opts.pedantic = true;
294                opts.warnings_are_errors = true;
295            }
296            "-P" => opts.line_markers = false,
297            // The dependency family, which section 4.4 calls required because every build system
298            // that generates its own makefiles asks for it. The two that end in `D` write a file
299            // beside the object and let the compilation happen, and the two that do not write to
300            // standard output and stop after it. Nothing here turns the system headers back on
301            // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
302            // `-MM`: the flag asking for fewer of them is the one with something to say.
303            "-M" => {
304                opts.deps.emit = true;
305                opts.deps.instead_of_compiling = true;
306            }
307            "-MM" => {
308                opts.deps.emit = true;
309                opts.deps.instead_of_compiling = true;
310                opts.deps.system_headers = false;
311            }
312            "-MD" => opts.deps.emit = true,
313            "-MMD" => {
314                opts.deps.emit = true;
315                opts.deps.system_headers = false;
316            }
317            "-MP" => opts.deps.phony = true,
318            // These three take a word and only in the separated form, which is how GCC spells
319            // them and how every build system writes them.
320            "-MF" | "-MT" | "-MQ" => {
321                let value =
322                    args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
323                i += 1;
324                match arg {
325                    "-MF" => opts.deps.file = Some(value.clone()),
326                    // The whole of the difference between the two. `-MT` is for a build that has
327                    // already escaped what it is passing, and `-MQ` is for one that has a name
328                    // and wants it to arrive as that name.
329                    "-MT" => opts.deps.targets.push(value.clone()),
330                    _ => opts.deps.targets.push(deps::escaped(value)),
331                }
332            }
333            // The questions a build system asks before it compiles anything. Answered after the
334            // loop, because each one is about the target or the library search and the command
335            // line has not finished saying what those are.
336            "-dumpmachine" => query = Some(Query::Machine),
337            "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
338            "-print-multiarch" => query = Some(Query::Multiarch),
339            "-print-search-dirs" => query = Some(Query::SearchDirs),
340            "-print-libgcc-file-name" => query = Some(Query::Libgcc),
341            _ if arg.starts_with("-print-file-name=") => {
342                query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
343            }
344            _ if arg.starts_with("-print-prog-name=") => {
345                query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
346            }
347            // A program built to run in more than one thread. On every platform this compiler
348            // targets that is a macro the library's headers read and one more library on the
349            // link line, and the library is added after the loop so that it lands after the
350            // objects that refer to it.
351            "-pthread" | "-pthreads" => {
352                opts.defines.push("_REENTRANT".to_owned());
353                threads = true;
354            }
355            "-ansi" => {
356                opts.std = Std::C89;
357                opts.gnu_extensions = false;
358            }
359            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
360            // the spelling a build system that groups its warning flags tends to write.
361            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
362            // Both directions, because a build that needs this for one directory turns it back
363            // off for the next one rather than leaving it on for the whole tree.
364            "-fpermissive" => opts.permissive = true,
365            "-fno-permissive" => opts.permissive = false,
366            "-ffreestanding" => opts.hosted = false,
367            "-fhosted" => opts.hosted = true,
368            "-fno-builtin" => opts.builtins = false,
369            "-fbuiltin" => opts.builtins = true,
370            // The C89 dialects are under GNU's reading whatever this says, so turning it off
371            // there is turning off something the dialect asked for, which is accepted and does
372            // nothing. gcc refuses that command line, and there is nothing it could have meant.
373            "-fgnu89-inline" => opts.gnu89_inline = true,
374            "-fno-gnu89-inline" => opts.gnu89_inline = false,
375            // Both directions of each, because a build system that wants one of these usually
376            // writes it beside the flag that turns it back off for one directory.
377            "-fno-omit-frame-pointer" => opts.frame_pointer = true,
378            "-fomit-frame-pointer" => opts.frame_pointer = false,
379            "-mno-red-zone" => opts.red_zone = false,
380            "-mred-zone" => opts.red_zone = true,
381            // GCC drops its own include directory along with the system ones, because its
382            // headers are half of a pair with the library's and half a pair is worse than
383            // none. A build that passes this is supplying the whole set itself.
384            "-nostdinc" => nostdinc = true,
385            "-o" => {
386                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
387                i += 1;
388            }
389            // The flags that take a directory only in the separated form. GCC spells them
390            // this way and nothing writes `-iquotedir`, so accepting the joined form would
391            // mean guessing at a path that starts with the flag's own letters.
392            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
393            // two mean the same thing here: the configured directories are under there rather
394            // than under the root.
395            "-isysroot" => {
396                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
397                i += 1;
398                sysroot = Some(PathBuf::from(dir));
399            }
400            "-iquote" | "-isystem" | "-idirafter" => {
401                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
402                i += 1;
403                match arg {
404                    "-iquote" => opts.search.push_quote(dir.clone()),
405                    "-isystem" => opts.search.push_system(dir.clone()),
406                    _ => opts.search.push_after(dir.clone()),
407                }
408            }
409            "-iprefix" => {
410                iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
411                i += 1;
412            }
413            // Where GCC puts these is not where its manual says it puts them, and this is the
414            // measured answer rather than the documented one: `-iwithprefix` lands in the
415            // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
416            // the `-I` slot. A cross build that uses them is relying on the behaviour, since
417            // that is the compiler it was developed against.
418            "-iwithprefix" | "-iwithprefixbefore" => {
419                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
420                i += 1;
421                let dir = format!("{iprefix}{dir}");
422                if arg == "-iwithprefix" {
423                    opts.search.push_system(dir);
424                } else {
425                    opts.search.push_bracket(dir);
426                }
427            }
428            "-include" | "-imacros" => {
429                let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
430                i += 1;
431                opts.preincludes
432                    .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
433            }
434            // The flag `-iquote` was introduced to replace, still passed by build systems old
435            // enough to predate the replacement. It is not a directory: it says that every `-I`
436            // so far is for quoted includes only, and that a quoted include stops looking next
437            // to the file that wrote it.
438            "-I-" => opts.search.split_quote_chain(),
439            "-x" => {
440                let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
441                i += 1;
442                forced = if lang == "none" {
443                    None
444                } else {
445                    Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
446                };
447            }
448            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
449            // translation units in one process rather than making the build system fork, and
450            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
451            // to exist and has to be spelled the way `make` spells it.
452            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
453            // and a build system may produce either, so both are read here rather than
454            // being normalised by whatever generated the command line.
455            _ if arg.starts_with("-D") => {
456                let value = joined_or_next(arg, 2, args, &mut i)?;
457                opts.defines.push(value);
458            }
459            _ if arg.starts_with("-U") => {
460                let value = joined_or_next(arg, 2, args, &mut i)?;
461                opts.undefines.push(value);
462            }
463            _ if arg.starts_with("-I") => {
464                let dir = joined_or_next(arg, 2, args, &mut i)?;
465                opts.search.push_bracket(dir);
466            }
467            _ if arg.starts_with("-std=") => {
468                let name = &arg["-std=".len()..];
469                let (std, gnu) = Std::from_flag(name)
470                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
471                opts.std = std;
472                opts.gnu_extensions = gnu;
473            }
474            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
475            // handed, so a differential run that does not set it is comparing two compilers
476            // that believe they are different compilers.
477            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
478            // that we have not written yet are accepted and ignored, because a dump is a
479            // debugging aid and a build that asks for one should still compile. A letter
480            // outside the family falls through to the unknown option error, which is what
481            // keeps `-dumpversion` from being read as a dump of nothing.
482            _ if Dumps::is_family(arg) => {
483                opts.dumps.add(&arg[2..]);
484            }
485            // One name at a time, which is what a build that means its own `memcpy` and the
486            // library's everything else writes. The name is not checked against a list, because
487            // the flag is about what the program means by a name and a program is allowed to mean
488            // something by a name this compiler has never heard of.
489            _ if arg.starts_with("-fno-builtin-") => {
490                opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
491            }
492            _ if arg.starts_with("-fgnuc-version=") => {
493                let v = &arg["-fgnuc-version=".len()..];
494                opts.gnuc = v.parse().map_err(err)?;
495            }
496            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
497            // than the unknown option one, because a build reaching for it is asking for a feature
498            // and deserves to be told it is not coming rather than told the spelling is wrong.
499            // The negative form is what this compiler does anyway, so it is taken and dropped.
500            "-fnested-functions" => {
501                return Err(err(
502                    "nested functions are not supported: a call to one goes through a trampoline \
503                     written on the stack, which no target that enforces an unexecutable stack \
504                     allows",
505                ));
506            }
507            "-fno-nested-functions" => {}
508            // What this compiler already does, so the flag asks for nothing and is taken and
509            // dropped. An address that may turn out to be in a shared library is loaded out of the
510            // global offset table rather than worked out from where the instruction is, which is
511            // what makes the output usable in a shared library and in a position independent
512            // executable, and `__PIC__` has said so since predefines were written.
513            //
514            // It matters that this is accepted rather than merely harmless. Every autoconf and
515            // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
516            // be the `CC` of a project that has a configure script, whatever else it can do. That
517            // is how this was found: building SQLite's test fixture stopped on it.
518            "-fPIC" | "-fpic" | "-fPIE" | "-fpie" => {}
519            // The other direction is a request, not a description, and it is one this compiler
520            // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
521            // option error. Answering it by carrying on would be answering a different question:
522            // the code would still be position independent, which is correct everywhere an
523            // ordinary program runs and is wrong in a kernel, where the flag is written precisely
524            // because there is no loader to fill a global offset table in.
525            "-fno-pic" | "-fno-pie" => {
526                return Err(err(
527                    "position dependent code is not supported: an address that may be in another \
528                     object is loaded out of the global offset table, and nothing here emits the \
529                     absolute form this asks for. Use -no-pie if what you meant was how to link",
530                ));
531            }
532            // Another description of what this compiler does. A file scope declaration with no
533            // initializer is written into `.bss` as an ordinary defined symbol, not offered to the
534            // linker as a common one for it to merge, which is what `-fno-common` asks for and what
535            // gcc has done by default since 10. Nothing in the front end produces `Linkage::Common`
536            // at all.
537            "-fno-common" => {}
538            // And the request, which is the one that cannot be granted. It is a real difference and
539            // not a preference: two files each writing `int g;` link under `-fcommon` and are a
540            // duplicate definition without it, which is the whole reason the flag survives.
541            "-fcommon" => {
542                return Err(err(
543                    "a tentative definition is written into .bss as its own symbol here, and \
544                     nothing emits the common symbol this asks the linker to merge. Give the \
545                     variable a definition in one file and declare it extern in the others",
546                ));
547            }
548            // Both directions of this one are taken, which is the exception to the rule above, and
549            // the reason is which way being wrong costs something.
550            //
551            // Nothing here derives anything from the type an object is accessed through. The IR has
552            // somewhere to put a type based aliasing node and lowering fills it with nothing on
553            // every access, so no pass has one to read and the alias analysis falls back to what it
554            // can see. That makes `-fno-strict-aliasing` a description, the way `-fPIC` is.
555            //
556            // `-fstrict-aliasing` is a request to assume more than that, and this compiler assumes
557            // less. Answering a request for a weaker guarantee by giving a stronger one is safe in
558            // a way the `-fno-pic` case is not: every program that is correct under the assumption
559            // is correct without it, only slower. And `-O2` implies it, so a build that spells it
560            // out is a build that would stop on a compiler that refused it, for no gain at all.
561            "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
562            // About temporary files rather than about code. There is nothing between the phases of
563            // one compilation here to write to a file in the first place.
564            "-pipe" => {}
565            // Nothing here writes colour, so all of these are the same answer, and it is the answer
566            // that costs nothing: the diagnostics come out plain either way and no build depends on
567            // an escape sequence being there. Taken rather than refused because cmake writes
568            // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
569            // makes this the second most common flag after `-fPIC` to stop a build over a question
570            // about how the text looks.
571            "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
572            _ if arg.starts_with("-fdiagnostics-color=") => {}
573            // The link flags. None of them changes the compilation, which is why they are
574            // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
575            // error: it is a thing said to a linker that is not going to run.
576            "-static" => link.is_static = true,
577            "-shared" => link.shared = true,
578            "-pie" => link.pie = Some(true),
579            "-no-pie" | "-nopie" => link.pie = Some(false),
580            "-nostdlib" => link.no_stdlib = true,
581            "-nostartfiles" => link.no_startfiles = true,
582            "-nodefaultlibs" => link.no_defaultlibs = true,
583            "-fno-builtins-lib" => link.no_builtins_lib = true,
584            "-fbuiltins-lib" => link.no_builtins_lib = false,
585            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
586            "-s" => link.strip = true,
587            "-Xlinker" => {
588                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
589                i += 1;
590                link.passthrough.push(next.clone());
591            }
592            _ if arg.starts_with("-Wl,") => {
593                // Commas separate arguments rather than being part of one, which is what makes
594                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
595                link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
596            }
597            _ if arg.starts_with("-fuse-ld=") => {
598                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
599            }
600            _ if arg.starts_with("-l") && arg.len() > 2 => {
601                inputs.push(Input::library(&arg[2..]));
602            }
603            "-l" => {
604                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
605                i += 1;
606                inputs.push(Input::library(next));
607            }
608            _ if arg.starts_with("-L") => {
609                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
610            }
611            _ if arg.starts_with("-B") => {
612                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
613            }
614            _ if arg.starts_with("-j") => {
615                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
616            }
617            _ if arg.starts_with("--sysroot=") => {
618                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
619            }
620            _ if arg.starts_with("--target=") => {
621                let t = &arg["--target=".len()..];
622                opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
623            }
624            _ if arg.starts_with("--emit=") => {
625                let k = &arg["--emit=".len()..];
626                opts.emit = k
627                    .parse()
628                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
629            }
630            // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
631            // to write. `-Og` is GCC's level for a build somebody is going to step through, and
632            // it is `-O1` with the transformations that move code around left out; this compiler
633            // has no such level yet, so it is the nearest one and `--print-pipeline` says what
634            // that came to rather than the flag pretending otherwise.
635            "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
636            // The union of `-O3` and `-ffast-math`, and the second half of that changes what
637            // floating point arithmetic means. Refused rather than taken as `-O3`, because a
638            // build that asks for fast math and is quietly given ordinary arithmetic gets a
639            // slower program than it asked for and a build that is given fast math it did not
640            // ask for gets a wrong one.
641            "-Ofast" => {
642                return Err(err(
643                    "-Ofast is -O3 with fast math, and fast math is not implemented, see \
644                     spec/04-driver-and-cli.md section 4.6",
645                ));
646            }
647            _ if arg.starts_with("-O") => {
648                opts.opt_level = arg[2..]
649                    .parse()
650                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
651            }
652            // What every name gets when nothing in the source said, which the attribute in the
653            // source overrides rather than the other way round. Before the optimizer's `-f`
654            // family below for the reason the tier below it is.
655            _ if arg.starts_with("-fvisibility=") => {
656                let seen = &arg["-fvisibility=".len()..];
657                opts.visibility = seen.parse().map_err(|()| {
658                    err(format!(
659                        "`{seen}` is not a visibility, which is default, hidden, internal or \
660                         protected"
661                    ))
662                })?;
663            }
664            // The memory safety monitor, from section 15.4 of
665            // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
666            // because a pass that took the name `safety=detect` would otherwise be handed the
667            // flag, and the tier is not a pass.
668            _ if arg.starts_with("-fsafety=") => {
669                let tier = &arg["-fsafety=".len()..];
670                opts.safety = tier.parse().map_err(|()| {
671                    err(format!(
672                        "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
673                    ))
674                })?;
675            }
676            // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
677            // after every `-f` the rest of the compiler answers to, so a pass can never take a
678            // name that already means something else on the command line.
679            _ if arg.starts_with("-fpass-fuel=") => {
680                let (name, count) = arg["-fpass-fuel=".len()..]
681                    .split_once('=')
682                    .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
683                if rucc_opt::pass::find(name).is_none() {
684                    return Err(err(format!(
685                        "`{name}` is not a pass this compiler has, see --print-pipeline"
686                    )));
687                }
688                let count: u32 = count
689                    .parse()
690                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
691                opts.pass_fuel.push((name.to_owned(), count));
692            }
693            _ if arg.starts_with("-fpass-fuel-global=") => {
694                let count = &arg["-fpass-fuel-global=".len()..];
695                let count: u32 = count
696                    .parse()
697                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
698                opts.pass_fuel_global = Some(count);
699            }
700            // Everything from `-fopt-info` to the end of the argument, which is optional
701            // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
702            // where the remarks are printed, because by then the compilation somebody wanted
703            // to hear about is over.
704            _ if arg == "-fopt-info"
705                || arg.starts_with("-fopt-info=")
706                || arg.starts_with("-fopt-info-") =>
707            {
708                let rest = &arg["-fopt-info".len()..];
709                let (kinds, file) = match rest.split_once('=') {
710                    Some((kinds, file)) => (kinds, Some(file)),
711                    None => (rest, None),
712                };
713                let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
714                rucc_opt::Wants::none().add(kinds).map_err(err)?;
715                opts.opt_info.push(kinds.to_owned());
716                if let Some(file) = file {
717                    if file.is_empty() {
718                        return Err(err("-fopt-info= was given no file to write to"));
719                    }
720                    opts.opt_info_file = Some(file.to_owned());
721                }
722            }
723            _ if arg.starts_with("-fdump-ir=") => {
724                // Checked here rather than where the dumps are taken, because the compilation
725                // that would have been dumped is over by then.
726                let spec = &arg["-fdump-ir=".len()..];
727                rucc_opt::Dumps::default().add(spec).map_err(err)?;
728                opts.dump_ir.push(spec.to_owned());
729            }
730            // Before the bare `-f<pass>` below, because a pass called `enable-something` would
731            // otherwise take the flag away from the gate. Checked here rather than where the
732            // pipeline reads it, for the reason that applies to all of these: a misspelled pass
733            // name that quietly gated nothing looks exactly like a pass that is not the guilty
734            // one, and a bisection would carry on past the thing it was looking for.
735            _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
736                let on = arg.starts_with("-fenable-");
737                let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
738                rucc_opt::Gates::default().add(on, spec).map_err(err)?;
739                opts.pass_gates.push((on, spec.to_owned()));
740            }
741            _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
742                opts.passes.push((arg["-fno-".len()..].to_owned(), false));
743            }
744            _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
745                opts.passes.push((arg["-f".len()..].to_owned(), true));
746            }
747            // The unstable options, spelled the way rustc spells them and carrying the same
748            // promise, which is none: one of these may change or go away in any release. They are
749            // measurements and debugging aids rather than things a build asks for, which is why
750            // none of them is in the usage text and all of them are in section 4.11 of
751            // `spec/04-driver-and-cli.md`.
752            "-Zverify-each" => opts.verify_each = true,
753            _ if arg.starts_with("-Zrule-coverage=") => {
754                let file = &arg["-Zrule-coverage=".len()..];
755                if file.is_empty() {
756                    return Err(err("-Zrule-coverage= needs a file to write to"));
757                }
758                opts.rule_coverage = Some(file.to_owned());
759            }
760            _ if arg.starts_with("-Z") => {
761                return Err(err(format!(
762                    "`{arg}` is not an unstable option this compiler has, see \
763                     spec/04-driver-and-cli.md section 4.11 for the ones it does"
764                )));
765            }
766            // The word size, which is a statement about the target and is taken as one. A build
767            // that says the size the target already has is saying nothing, and one that says the
768            // other size is asking for a target this compiler does not have, which it is told
769            // rather than being given the wrong one.
770            "-m64" | "-m32" | "-mx32" => {
771                let want: u32 = match arg {
772                    "-m64" => 64,
773                    _ => 32,
774                };
775                let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
776                if have != want {
777                    return Err(err(format!(
778                        "{arg} asks for a {want} bit target and {} is {have} bit, use \
779                         --target= to name the one you mean",
780                        opts.target
781                    )));
782                }
783            }
784            // Which processor in the family to generate for. This compiler emits the base
785            // instruction set of the architecture and nothing above it, so a program built with
786            // any of these runs on the machine that was named; it is a program that could have
787            // been faster rather than a program that is wrong, which is what makes these safe to
788            // take and ignore where a flag that changed the meaning of the code would not be.
789            _ if arg.starts_with("-march=")
790                || arg.starts_with("-mtune=")
791                || arg.starts_with("-mcpu=") => {}
792            // The calling convention, which is not safe to ignore. Taken when it names the one
793            // the target already uses and refused otherwise.
794            _ if arg.starts_with("-mabi=") => {
795                let want = &arg["-mabi=".len()..];
796                let have = match opts.target.arch {
797                    rucc_target::Arch::X86_64 => "sysv",
798                    rucc_target::Arch::Aarch64 => "lp64",
799                    rucc_target::Arch::Riscv64 => "lp64d",
800                };
801                if want != have {
802                    return Err(err(format!(
803                        "{arg}: {} uses the {have} convention and this compiler has no other",
804                        opts.target
805                    )));
806                }
807            }
808            // How far apart the pieces of the program may be. The small model is what we emit and
809            // it is every hosted program's default; the kernel model is a different one and a
810            // build that asks for it and does not get it links and then does not run.
811            "-mcmodel=small" => {}
812            _ if arg.starts_with("-mcmodel=") => {
813                return Err(err(format!(
814                    "{arg}: this compiler emits the small code model and no other, see \
815                     spec/12-targets.md"
816                )));
817            }
818            // GCC's own scripting language for how the driver builds a command line.
819            // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
820            // build reaching for it is told which flags do the same job.
821            _ if arg.starts_with("-specs=") => {
822                return Err(err(
823                    "-specs= is not supported: the parts of it builds rely on are -B, -L, \
824                     -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
825                     section 4.4",
826                ));
827            }
828            // Arguments meant for a separate assembler or preprocessor, which this compiler does
829            // not have: both are inside it and neither reads a command line. Refused rather than
830            // dropped, because every one of these says something about the output and a build
831            // that asked for `-Wa,--noexecstack` and was silently given an executable stack got
832            // the opposite of what it asked for.
833            _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
834                return Err(err(format!(
835                    "`{arg}` is an argument for a separate assembler or preprocessor, and both \
836                     are inside this compiler rather than programs it runs"
837                )));
838            }
839            "-Xassembler" | "-Xpreprocessor" => {
840                return Err(err(format!(
841                    "{arg} hands an argument to a separate assembler or preprocessor, and both \
842                     are inside this compiler rather than programs it runs"
843                )));
844            }
845            // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
846            // this one as a rule about build systems rather than about warnings: autoconf finds
847            // out whether a warning flag exists by passing it and looking at the exit status, so
848            // a compiler that refuses one it has not heard of fails a configure script written
849            // for a GCC newer than itself. The names are not checked against a list because this
850            // compiler has no warning groups for a list to be of, which #485 is about.
851            _ if arg.starts_with("-W") => {}
852            // Flags that name something this compiler does not do and would not do differently
853            // if it did. `-fno-ident` is about a comment in the output that we do not write
854            // either way, and the others are about a way of ordering the compilation that has
855            // been GCC's only way for twenty years. Section 4.1 asks for the list to be short
856            // and for adding to it to be deliberate, which is why it is written out here.
857            "-fno-ident"
858            | "-fident"
859            | "-funit-at-a-time"
860            | "-fno-unit-at-a-time"
861            | "-shared-libgcc"
862            | "-static-libgcc" => {}
863            _ if arg.starts_with('-') && arg.len() > 1 => {
864                // Silently ignoring an unknown flag is how a build ends up not doing what
865                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
866                // for the flags that change code generation, and the safe default until the
867                // flag table is populated is to reject everything we do not know.
868                return Err(err(format!("unknown option `{arg}`")));
869            }
870            _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
871        }
872    }
873
874    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
875    // order: a directory the user names outranks the compiler's own, and the compiler's own
876    // outranks the library's. It is pushed after the loop rather than before it because
877    // `SearchPath` appends within a group and the position is what the order is.
878    // The same directory the headers were looked for under, because a sysroot is a statement
879    // about a whole installation and not about half of one.
880    link.sysroot = sysroot.clone();
881    // After the loop rather than where `-pthread` was read, so that it lands after the objects
882    // that refer to it. A static link takes the definitions it needs from a library when it
883    // reaches it and not afterwards, so a library before the objects is a library that answers
884    // nothing.
885    if threads {
886        inputs.push(Input::library("pthread"));
887    }
888    if let Some(query) = query {
889        return Ok(Action::Print(answer(&query, &opts, &link)));
890    }
891    // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
892    // else the command line asked for. Read here rather than where the flag was, because a `-c`
893    // written after it has to lose and the loop cannot know that until it has ended. The output
894    // file is where the rule goes rather than where an object would have gone, and the last
895    // phase being the preprocessor is what makes that true without a second rule for it.
896    if opts.deps.instead_of_compiling {
897        opts.emit = EmitKind::Preprocessed;
898    }
899    if !nostdinc {
900        opts.search.push_system(runtime::DIR);
901        // And the library's after ours, which is the other half of the same order. They go on
902        // here rather than at the point `--target=` or `--sysroot=` was read because either
903        // one changes the answer and the last word on both is the end of the loop.
904        for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
905            opts.search.push_system(dir);
906        }
907    }
908    // Once, here, rather than as each directory is pushed. A `-I` that names a system
909    // directory has to lose to the system entry and the system entry is added last, so the
910    // question cannot be answered until the whole path is known.
911    opts.search.remove_duplicates();
912
913    // The target has to be resolved before the configuration is printed, so this check comes
914    // after the loop rather than at the point `--print-config` was seen.
915    if print_config {
916        return Ok(Action::PrintConfig(Box::new(opts)));
917    }
918    if print_pipeline {
919        return Ok(Action::PrintPipeline(Box::new(opts)));
920    }
921    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
922    if print_plan {
923        return Ok(Action::PrintPlan {
924            opts: Box::new(opts),
925            plan: Box::new(plan),
926            link: Box::new(link),
927        });
928    }
929    Ok(Action::Compile {
930        opts: Box::new(opts),
931        plan: Box::new(plan),
932        link: Box::new(link),
933        jobs,
934        verbose,
935    })
936}
937
938/// What one of the `-dump` and `-print` flags prints.
939///
940/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
941/// which is what makes the answer safe to paste into a link line whether or not the file is
942/// there, and this does the same.
943fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
944    let found = |name: &str| {
945        link::find_in_search(link, opts.target, name)
946            .map_or_else(|| name.to_owned(), |path| path.display().to_string())
947    };
948    match query {
949        Query::Machine => opts.target.to_string(),
950        Query::Version => VERSION.to_owned(),
951        Query::Multiarch => link::multiarch(opts.target),
952        // The three lines GCC prints, in its order and with its punctuation, because what reads
953        // them is a script written against that shape. There is no installation directory to
954        // report: this compiler is one binary that works wherever it is copied, and the headers
955        // it ships are inside it, so `install` is where the binary is and nothing is under it.
956        Query::SearchDirs => {
957            let here = std::env::current_exe()
958                .ok()
959                .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
960                .unwrap_or_default();
961            let list = |dirs: &[PathBuf]| {
962                dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
963            };
964            let libraries = link::search_dirs(link, opts.target);
965            format!(
966                "install: {}\nprograms: ={}\nlibraries: ={}",
967                here.display(),
968                list(&link.prefixes),
969                list(&libraries)
970            )
971        }
972        Query::FileName(name) => found(name),
973        // The name GCC gives the library of routines a compiler's output calls that the C
974        // library does not have. Ours is built in and there is no file, so the answer is the
975        // name itself, which is what GCC prints when it cannot find one either.
976        Query::Libgcc => found("libgcc.a"),
977        // A program rather than a library: the linker and the archiver are the ones a build asks
978        // about, and this compiler finds them on the path or under `-B` rather than shipping
979        // them, so the name back is the honest answer unless a `-B` prefix holds one.
980        Query::ProgName(name) => link
981            .prefixes
982            .iter()
983            .map(|dir| dir.join(name))
984            .find(|path| path.is_file())
985            .map_or_else(|| name.clone(), |path| path.display().to_string()),
986    }
987}
988
989/// Renders the passes this level will run, in order, with what each one does.
990///
991/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
992/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
993/// emerges from which flags happen to be set, and this is how that list is read.
994#[must_use]
995pub fn print_pipeline(opts: &Options) -> String {
996    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
997    settings.toggles.clone_from(&opts.passes);
998    settings.global_fuel = opts.pass_fuel_global;
999    for (on, spec) in &opts.pass_gates {
1000        // Every spelling was checked while the arguments were parsed, so there is nothing here
1001        // this can refuse, and a listing is not the place to report it if there were.
1002        let _ = settings.gates.add(*on, spec);
1003    }
1004    rucc_opt::pipeline::print(&settings)
1005}
1006
1007/// Renders the resolved configuration.
1008///
1009/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
1010/// this output is diffed across hosts in CI and a reordering would read as a change.
1011#[must_use]
1012pub fn print_config(opts: &Options) -> String {
1013    let sess = Session::new(opts.clone());
1014    let t = &sess.target;
1015    let mut out = String::new();
1016    let _ = writeln!(out, "version: {VERSION}");
1017    // The three field triple the driver was given rather than the ten field tuple it widens to,
1018    // because this output is what a build system reads to find out what it asked for. The tuple is
1019    // the compiler's model of the machine and this line is a receipt for a command line.
1020    let _ = writeln!(out, "target: {}", opts.target);
1021    let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1022    let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1023    let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1024    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1025    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1026    let _ = writeln!(out, "long-width: {}", t.long_width);
1027    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1028    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1029    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1030    let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1031    // The register file as a count per class, which is enough to tell a target whose registers
1032    // are described from one whose are not without printing sixteen names nobody asked for.
1033    let regs: Vec<String> = t
1034        .regs
1035        .classes()
1036        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1037        .collect();
1038    let _ = writeln!(
1039        out,
1040        "registers: {}",
1041        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1042    );
1043    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1044    let _ = writeln!(out, "safety: {}", sess.opts.safety);
1045    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1046    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1047    let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1048    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1049    // Last because it is the one key with more than one line under it, and the only one
1050    // whose value is a property of the machine rather than of the command line.
1051    for dir in sess.opts.search.dirs() {
1052        let system = if dir.is_system { " (system)" } else { "" };
1053        let _ = writeln!(out, "include: {}{system}", dir.path.display());
1054    }
1055    out
1056}
1057
1058/// The output name the make target is taken from, which is the `-o` argument or nothing.
1059///
1060/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
1061/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
1062/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
1063/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
1064/// `-S` on the argument does name what the rule builds, and it is used as written.
1065fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1066    if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1067}
1068
1069/// Writes to a path the command line named rather than one the plan derived, where `-` is
1070/// standard output.
1071fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1072    if path == "-" {
1073        return write_out(&Output::Stdout, bytes);
1074    }
1075    write_out(&Output::File(path.to_owned()), bytes)
1076}
1077
1078/// Writes the make rule for one input, and reports whether it got there.
1079///
1080/// A rule with no file of its own goes where the compilation it replaced would have written,
1081/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
1082/// `$@`, and the same line with the `-o` left off puts it on standard output.
1083fn write_deps(
1084    opts: &Options,
1085    plan: &Plan,
1086    job: &Job,
1087    found: &[Dependency],
1088    stderr: &mut impl std::io::Write,
1089) -> bool {
1090    let targets = if opts.deps.targets.is_empty() {
1091        vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1092    } else {
1093        opts.deps.targets.clone()
1094    };
1095    let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1096    // The file, on the other hand, is named after the `-o` in every mode that still has one to
1097    // spend, which is every mode except the two that spend it on the rule.
1098    let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1099        // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
1100        // named empty rather than absent, because a makefile that named it as a target of its
1101        // own is a makefile that will look for it.
1102        Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1103            if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1104        }),
1105        None => write_out(&job.output, rule.as_bytes()),
1106    };
1107    if let Err(e) = wrote {
1108        let _ = writeln!(stderr, "rucc: error: {e}");
1109        return false;
1110    }
1111    true
1112}
1113
1114/// Runs phase 4 over every input that has one, and writes what came out.
1115///
1116/// One input that fails does not stop the others. A build that reports every file it could
1117/// not preprocess in one run is worth more than one that stops at the first, and the exit
1118/// status is still a failure either way.
1119fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1120    let fs = OsFileSystem::new();
1121    let mut stderr = std::io::stderr().lock();
1122    let mut failed = false;
1123    for job in &plan.jobs {
1124        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1125            // An input that is already preprocessed, or an object file. GCC passes these
1126            // through untouched, and the plan has already said so in its notes.
1127            continue;
1128        }
1129        let started = std::time::Instant::now();
1130        let result = preprocess(opts, &job.input, &fs);
1131        if opts.time {
1132            say_time(&job.input, started.elapsed(), &mut stderr);
1133        }
1134        for message in &result.messages {
1135            let _ = writeln!(stderr, "{message}");
1136        }
1137        if result.failed() {
1138            failed = true;
1139            continue;
1140        }
1141        if opts.deps.emit {
1142            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1143            // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
1144            // to write. The other two asked for both and fall through to the text below.
1145            if opts.deps.instead_of_compiling {
1146                continue;
1147            }
1148        }
1149        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1150            let _ = writeln!(stderr, "rucc: error: {e}");
1151            failed = true;
1152        }
1153    }
1154    i32::from(failed)
1155}
1156
1157/// Runs the front end over every input that has a compile phase, and writes what came out.
1158///
1159/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
1160/// exit status is a failure either way. An input that is already assembly or an object has no
1161/// compile phase and is passed over here, which the plan has already said in its notes.
1162fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1163    let fs = OsFileSystem::new();
1164    let mut stderr = std::io::stderr().lock();
1165    let mut failed = false;
1166    let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1167    failed |= !ok;
1168    let mut fired = Fired::new();
1169    for job in &plan.jobs {
1170        if !job.phases.contains(&Phase::Compile) {
1171            continue;
1172        }
1173        // An input of IR is read back rather than compiled, since the C it came from is not
1174        // here any more. Everything after this is the same, so the two paths meet again at the
1175        // messages and the file the result is written to.
1176        let started = std::time::Instant::now();
1177        let result = if job.kind == InputKind::Ir {
1178            compile_ir(opts, &job.input, &fs)
1179        } else {
1180            compile(opts, &job.input, &fs)
1181        };
1182        if opts.time {
1183            say_time(&job.input, started.elapsed(), &mut stderr);
1184        }
1185        fired.merge(&result.fired);
1186        failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1187        failed |= !remarks.write(&result.remarks, &mut stderr);
1188        for message in &result.messages {
1189            let _ = writeln!(stderr, "{message}");
1190        }
1191        // Before the failure below, because a compilation that stopped in the back end is exactly
1192        // the one whose preprocessed source somebody wants to look at.
1193        failed |= !write_temps(job, &result.temps, &mut stderr);
1194        if result.failed() {
1195            failed = true;
1196            continue;
1197        }
1198        // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
1199        // this is the one path where both files come out of the same run. An input of IR has no
1200        // dependencies to report and produces an empty list, which produces a rule naming only
1201        // itself, and that is the honest answer rather than a missing file.
1202        if opts.deps.emit {
1203            failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1204        }
1205        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1206            let _ = writeln!(stderr, "rucc: error: {e}");
1207            failed = true;
1208        }
1209    }
1210    failed |= !write_coverage(opts, &fired, &mut stderr);
1211    i32::from(failed)
1212}
1213
1214/// A directory for the object files only the link step ever sees, removed when it goes away.
1215///
1216/// `-c` writes its object where the user can see it and linking does not, which is the whole of
1217/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
1218/// every other compiler. Removing them on drop rather than at the end of a function is so that a
1219/// link that failed leaves nothing behind either.
1220struct Scratch {
1221    /// Where the objects go.
1222    dir: PathBuf,
1223}
1224
1225impl Scratch {
1226    /// Makes one, under whatever the platform calls its temporary directory.
1227    ///
1228    /// The name carries the process id so that two compilers running at once do not share a
1229    /// directory, which they would otherwise do the moment two of them compiled a file of the
1230    /// same name.
1231    fn new() -> Result<Scratch, String> {
1232        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1233        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1234        Ok(Scratch { dir })
1235    }
1236}
1237
1238impl Drop for Scratch {
1239    fn drop(&mut self) {
1240        let _ = std::fs::remove_dir_all(&self.dir);
1241    }
1242}
1243
1244/// The link line the plan describes, for `-###`.
1245///
1246/// The names in it are the hints the plan carries rather than the temporaries a real compilation
1247/// would choose, because `-###` prints the line without having compiled anything and so has
1248/// nothing to point at. That also makes the printed line readable rather than naming a directory
1249/// that only exists while a compilation is running.
1250fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1251    let linker = link::find(opts.target, link)?;
1252    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1253    Ok(link::render(&linker, &args))
1254}
1255
1256/// Compiles everything, then links it.
1257///
1258/// The objects go in a directory that is removed afterwards, which is why this is not
1259/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
1260/// and does not say where, because where is a question that only has an answer once something is
1261/// running.
1262fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1263    let Some(job) = &plan.link else {
1264        // Every path into here comes from a plan whose last phase is the link, and such a plan
1265        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
1266        let mut stderr = std::io::stderr().lock();
1267        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1268        return 1;
1269    };
1270    // Before anything is compiled, because a linker that is not on the machine is worth knowing
1271    // about in the second it takes to look rather than after the compilation.
1272    let linker = match link::find(opts.target, link) {
1273        Ok(linker) => linker,
1274        Err(why) => return complain(why),
1275    };
1276
1277    let scratch = match Scratch::new() {
1278        Ok(scratch) => scratch,
1279        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1280    };
1281
1282    let fs = OsFileSystem::new();
1283    let mut failed = false;
1284    // One per job, in job order, which is what lets the link line below be rebuilt with the real
1285    // paths in it: every job contributes exactly one file to the line and does so in this order.
1286    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1287    let mut fired = Fired::new();
1288    {
1289        let mut stderr = std::io::stderr().lock();
1290        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1291        failed |= !ok;
1292        for (at, job) in plan.jobs.iter().enumerate() {
1293            let out = match &job.output {
1294                Output::Temporary(hint) => {
1295                    // The index because two inputs in different directories can have the same
1296                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
1297                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1298                }
1299                Output::File(path) => path.clone(),
1300                // A job feeding the linker never writes to standard output, since the plan gives
1301                // it a temporary. This is here so that the match is total rather than a panic.
1302                Output::Stdout => continue,
1303            };
1304            produced.push(out.clone());
1305            if !job.phases.contains(&Phase::Compile) {
1306                continue;
1307            }
1308            let started = std::time::Instant::now();
1309            let result = if job.kind == InputKind::Ir {
1310                compile_ir(opts, &job.input, &fs)
1311            } else {
1312                compile(opts, &job.input, &fs)
1313            };
1314            if opts.time {
1315                say_time(&job.input, started.elapsed(), &mut stderr);
1316            }
1317            fired.merge(&result.fired);
1318            failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1319            failed |= !remarks.write(&result.remarks, &mut stderr);
1320            for message in &result.messages {
1321                let _ = writeln!(stderr, "{message}");
1322            }
1323            failed |= !write_temps(job, &result.temps, &mut stderr);
1324            if result.failed() {
1325                failed = true;
1326                continue;
1327            }
1328            // A `-MD` on a command line that links writes the rule next to the executable and
1329            // names the executable as its target, since that is the file this source builds
1330            // here. The object it went through is in a temporary directory and is gone by the
1331            // time `make` reads any of this.
1332            if opts.deps.emit {
1333                failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1334            }
1335            if !matches!(result.artifact, Artifact::Object(_)) {
1336                // Worth saying rather than writing whatever it is and letting the linker read it.
1337                // An empty file is a valid empty linker script, so a link handed one gets as far
1338                // as reporting every symbol of this file undefined, which is a page of messages
1339                // about something that went wrong here.
1340                let _ = writeln!(
1341                    stderr,
1342                    "rucc: internal error: {}: no object file was produced for the link",
1343                    job.input
1344                );
1345                failed = true;
1346                continue;
1347            }
1348            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1349                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1350                failed = true;
1351            }
1352        }
1353        failed |= !write_coverage(opts, &fired, &mut stderr);
1354    }
1355    if failed {
1356        // Nothing is linked from a compilation that did not finish. A linker run over the objects
1357        // that did compile would report every function of the file that did not as undefined,
1358        // which is a page of messages about a mistake already reported once.
1359        return 1;
1360    }
1361
1362    // The items in command line order with the temporaries filled in. A library contributes no
1363    // job and passes through, and every file item takes the next job's real output, which is
1364    // what keeps a library that was written between two objects between them here.
1365    let mut outputs = produced.into_iter();
1366    let mut items = Vec::with_capacity(job.inputs.len());
1367    for item in &job.inputs {
1368        match item {
1369            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1370            link::Item::File(_) => match outputs.next() {
1371                Some(path) => items.push(link::Item::File(path)),
1372                None => return complain("the plan asks the linker for a file nothing produced"),
1373            },
1374        }
1375    }
1376
1377    let args = match link::line(opts.target, link, &items, &job.output) {
1378        Ok(args) => args,
1379        Err(why) => return complain(why),
1380    };
1381    if verbose {
1382        let mut stderr = std::io::stderr().lock();
1383        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1384    }
1385    let started = std::time::Instant::now();
1386    let ran = link::run(&linker, &args);
1387    if opts.time {
1388        // The one step of a compilation that really is another program, so this line is the same
1389        // measurement gcc's is and names the linker the way gcc names `collect2`.
1390        let mut stderr = std::io::stderr().lock();
1391        say_time(&linker.name, started.elapsed(), &mut stderr);
1392    }
1393    match ran {
1394        Ok(()) => 0,
1395        // The linker has already said what was wrong on its own error output, and repeating that
1396        // linking failed would only push its message further up the screen.
1397        Err(link::Error::Refused { .. }) => 1,
1398        Err(why) => complain(why),
1399    }
1400}
1401
1402/// Prints one driver level message and gives back the exit status that goes with it.
1403fn complain(why: impl std::fmt::Display) -> i32 {
1404    let mut stderr = std::io::stderr().lock();
1405    let _ = writeln!(stderr, "rucc: error: {why}");
1406    1
1407}
1408
1409/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
1410///
1411/// Once for the whole command line rather than once per input, because the question is which
1412/// lowering rules this run of the compiler reached and a file per input would leave the reader
1413/// unioning files to find out something one process already knew.
1414///
1415/// A file that could not be written is a failure and not a warning. What asks for this is a
1416/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
1417fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1418    let Some(path) = &opts.rule_coverage else { return true };
1419    let Some(table) = coverage::table(opts.target.arch) else {
1420        let _ = writeln!(
1421            stderr,
1422            "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1423             to report",
1424            opts.target
1425        );
1426        return false;
1427    };
1428    match std::fs::write(path, fired.listing(table)) {
1429        Ok(()) => true,
1430        Err(e) => {
1431            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1432            false
1433        }
1434    }
1435}
1436
1437/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
1438///
1439/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
1440/// A file rather than the diagnostic stream is what a harness wants: the corpus in
1441/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
1442/// a few thousand remarks mixed into that would bury it.
1443struct Remarks {
1444    /// The file, if there is one.
1445    file: Option<String>,
1446    /// Whether anything has been written to it yet, which decides between truncating and
1447    /// appending. One file holds the whole run rather than the last input in it.
1448    started: bool,
1449}
1450
1451impl Remarks {
1452    /// Prepares the destination, emptying the file if there is one.
1453    ///
1454    /// Emptied here rather than at the first remark, because a run where no pass had anything to
1455    /// say should leave an empty file and not yesterday's. An absent file and an empty one are
1456    /// different facts and something reading this will act on the difference.
1457    fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1458        let mut ok = true;
1459        if let Some(path) = file {
1460            if let Err(e) = std::fs::write(path, "") {
1461                let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1462                ok = false;
1463            }
1464        }
1465        (Self { file: file.cloned(), started: false }, ok)
1466    }
1467
1468    /// Writes one input's remarks, and says whether that worked.
1469    ///
1470    /// A file that cannot be written is a failure and not a warning, for the reason
1471    /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
1472    /// where nothing happened.
1473    fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1474        if text.is_empty() {
1475            return true;
1476        }
1477        let Some(path) = &self.file else {
1478            let _ = write!(stderr, "{text}");
1479            return true;
1480        };
1481        let opened = std::fs::OpenOptions::new()
1482            .write(true)
1483            .append(self.started)
1484            .truncate(!self.started)
1485            .create(true)
1486            .open(path);
1487        self.started = true;
1488        let result =
1489            opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1490        if let Err(e) = result {
1491            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1492            return false;
1493        }
1494        true
1495    }
1496}
1497
1498/// Writes what `-fdump-ir=` asked to see, one file per dump.
1499///
1500/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
1501/// after a run is the passes in the order they ran, per input. They go in the working directory
1502/// rather than beside the output, because a dump is something a person asked for at a prompt and
1503/// the working directory is where that person is.
1504///
1505/// A file that could not be written is a failure and not a warning, for the reason
1506/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
1507/// quietly did not happen looks exactly like a pass that did not run.
1508fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1509    let stem = std::path::Path::new(input)
1510        .file_name()
1511        .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1512    let mut ok = true;
1513    for dump in dumps {
1514        let path = format!("{stem}.{}.ir", dump.name);
1515        if let Err(e) = std::fs::write(&path, &dump.text) {
1516            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1517            ok = false;
1518        }
1519    }
1520    ok
1521}
1522
1523/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
1524///
1525/// A file that could not be written is a failure rather than a warning, for the reason
1526/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
1527/// looks like a compilation that never went through that step.
1528fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1529    let mut ok = true;
1530    let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1531    for (path, text) in kept {
1532        // A step the compilation did not reach has nothing to keep, and a job that is not keeping
1533        // that step has nowhere to put it. Either way there is no file here.
1534        let (Some(path), Some(text)) = (path, text) else { continue };
1535        if let Err(e) = std::fs::write(&path, text) {
1536            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1537            ok = false;
1538        }
1539    }
1540    ok
1541}
1542
1543/// One line of `-time`, which is what a step was called and how long it took.
1544///
1545/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
1546/// no subprocess for anything but the link, so what is measured here is the wall clock of the
1547/// step and the second column is always zero. The shape of the line is kept because a person
1548/// reading it next to gcc's should not have to work out which column is which.
1549fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1550    let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1551}
1552
1553/// Writes one job's result where the plan said it goes.
1554///
1555/// # Errors
1556///
1557/// Returns the message to print, which names the file when there is one, because "permission
1558/// denied" on its own does not say which file was refused.
1559fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1560    match output {
1561        Output::Stdout => {
1562            let mut stdout = std::io::stdout().lock();
1563            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1564        }
1565        Output::File(path) | Output::Temporary(path) => {
1566            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1567        }
1568    }
1569}
1570
1571/// Runs the driver and returns the process exit code.
1572///
1573/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
1574/// is the one place in the compiler that is true.
1575pub fn run(args: &[String]) -> i32 {
1576    match parse_args(args) {
1577        Ok(Action::Help) => {
1578            print!("{USAGE}");
1579            0
1580        }
1581        Ok(Action::Version) => {
1582            println!("rucc {VERSION}");
1583            0
1584        }
1585        Ok(Action::Print(line)) => {
1586            println!("{line}");
1587            0
1588        }
1589        Ok(Action::PrintConfig(opts)) => {
1590            print!("{}", print_config(&opts));
1591            0
1592        }
1593        Ok(Action::PrintPipeline(opts)) => {
1594            print!("{}", print_pipeline(&opts));
1595            0
1596        }
1597        Ok(Action::PrintPlan { opts, plan, link }) => {
1598            print!("{}", plan.render());
1599            // The line as it would be typed, which is the half of `-###` that section 4.3 says
1600            // arrives with the link. It is printed even when the linker is not on this machine,
1601            // because what a build wants from `-###` is what the compiler would do.
1602            if let Some(job) = &plan.link {
1603                match link_line(&opts, &link, job) {
1604                    Ok(line) => println!("{line}"),
1605                    Err(why) => {
1606                        let mut stderr = std::io::stderr().lock();
1607                        let _ = writeln!(stderr, "rucc: error: {why}");
1608                        return 1;
1609                    }
1610                }
1611            }
1612            0
1613        }
1614        Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1615            {
1616                let mut stderr = std::io::stderr().lock();
1617                if verbose {
1618                    let _ = write!(stderr, "{}", plan.render());
1619                    let _ = writeln!(stderr, "workers: {}", jobs.count());
1620                }
1621            }
1622            if opts.emit == EmitKind::Preprocessed {
1623                return preprocess_all(&opts, &plan);
1624            }
1625            if opts.emit != EmitKind::Executable {
1626                return compile_all(&opts, &plan);
1627            }
1628            link_all(&opts, &plan, &link, verbose)
1629        }
1630        Err(e) => {
1631            let mut stderr = std::io::stderr().lock();
1632            let _ = writeln!(stderr, "rucc: error: {e}");
1633            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1634            1
1635        }
1636    }
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641    use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1642
1643    use super::*;
1644
1645    fn args(s: &[&str]) -> Vec<String> {
1646        s.iter().map(|x| (*x).to_owned()).collect()
1647    }
1648
1649    #[test]
1650    fn help_and_version_win_over_everything_else() {
1651        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1652        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1653    }
1654
1655    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1656        match parse_args(&args(s)).expect("expected a compilation") {
1657            Action::Compile { opts, plan, .. } => (opts, plan),
1658            other => panic!("expected a compilation, got {other:?}"),
1659        }
1660    }
1661
1662    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1663        match parse_args(&args(s)).expect("expected a compilation") {
1664            Action::Compile { link, plan, .. } => (link, plan),
1665            other => panic!("expected a compilation, got {other:?}"),
1666        }
1667    }
1668
1669    #[test]
1670    fn collects_inputs_and_flags() {
1671        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1672        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1673        assert_eq!(paths, vec!["a.c", "b.c"]);
1674        assert_eq!(opts.opt_level, OptLevel::O2);
1675        assert_eq!(opts.emit, EmitKind::Object);
1676        assert!(opts.debug_info);
1677    }
1678
1679    /// The unstable options, which are spelled apart from everything else on purpose: what is
1680    /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
1681    #[test]
1682    fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1683        let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1684        assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1685
1686        let (plain, _) = compile(&["-c", "a.c"]);
1687        assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1688
1689        assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1690        let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1691        assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1692    }
1693
1694    #[test]
1695    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1696        let (opts, _) = compile(&["-O", "a.c"]);
1697        assert_eq!(opts.opt_level, OptLevel::O1);
1698    }
1699
1700    #[test]
1701    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1702        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1703        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1704        assert_eq!(plan.jobs[1].kind, InputKind::C);
1705        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1706    }
1707
1708    #[test]
1709    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1710        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1711            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1712            other => panic!("expected a compilation, got {other:?}"),
1713        };
1714        assert_eq!(jobs.count(), 4);
1715
1716        let default = match parse_args(&args(&["a.c"])).unwrap() {
1717            Action::Compile { jobs, .. } => jobs,
1718            other => panic!("expected a compilation, got {other:?}"),
1719        };
1720        assert_eq!(default, Jobs::available());
1721        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1722    }
1723
1724    #[test]
1725    fn triple_hash_prints_the_plan_and_runs_nothing() {
1726        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1727        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1728        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1729    }
1730
1731    #[test]
1732    fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1733        // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
1734        // this, and following the compiler is what makes a build that reads either of them find
1735        // the files where they are.
1736        assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1737        assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1738        assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1739        assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1740        // The last one on the line decides, the way it does for every other flag with an
1741        // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
1742        // nothing and said nothing looks exactly like one where the files were not produced.
1743        let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1744        assert_eq!(opts.save_temps, SaveTemps::Cwd);
1745        let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1746        assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1747    }
1748
1749    #[test]
1750    fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1751        let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1752        let (plain, without) = compile(&["-c", "a.c"]);
1753        assert!(opts.time);
1754        assert!(!plain.time);
1755        // Against the same line without the flag rather than against a spelling of the object's
1756        // name, since what the object is called is the host's business and this is not about that.
1757        assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1758    }
1759
1760    #[test]
1761    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1762        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1763        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1764    }
1765
1766    #[test]
1767    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1768        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1769        assert!(e.message.contains("unknown option"), "{}", e.message);
1770    }
1771
1772    /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
1773    /// one directory needs the older rules and the rest of the tree does not.
1774    #[test]
1775    fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1776        let (opts, _) = compile(&["-c", "a.c"]);
1777        assert!(!opts.permissive, "off unless it is asked for");
1778
1779        let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1780        assert!(opts.permissive);
1781
1782        let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1783        assert!(!opts.permissive);
1784    }
1785
1786    #[test]
1787    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1788        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1789        assert!(e.message.contains("trampoline"), "{}", e.message);
1790        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1791    }
1792
1793    #[test]
1794    fn the_flag_every_configure_script_writes_is_taken() {
1795        // All four spellings, because a build writes whichever one its macros picked and a
1796        // compiler that takes three of them is a compiler that fails on the fourth.
1797        for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1798            let (opts, _) = compile(&["-c", flag, "a.c"]);
1799            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1800        }
1801    }
1802
1803    #[test]
1804    fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1805        // Every one of these is on a real build line somewhere and every one of them was an
1806        // unknown option. What they have in common is that the answer rucc gives is the answer
1807        // they ask for, so there is nothing to implement and nothing to refuse.
1808        for flag in [
1809            "-fno-common",
1810            "-fstrict-aliasing",
1811            "-fno-strict-aliasing",
1812            "-pipe",
1813            "-fdiagnostics-color",
1814            "-fno-diagnostics-color",
1815            "-fdiagnostics-color=always",
1816            "-fdiagnostics-color=never",
1817            "-fdiagnostics-color=auto",
1818        ] {
1819            let (opts, _) = compile(&["-c", flag, "a.c"]);
1820            assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1821        }
1822    }
1823
1824    #[test]
1825    fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1826        // The one of that family that is a request rather than a description, and it is a real
1827        // difference: two files each writing `int g;` link under it and do not without it.
1828        let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1829        assert!(e.message.contains(".bss"), "{}", e.message);
1830        assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1831    }
1832
1833    #[test]
1834    fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1835        for flag in ["-fno-pic", "-fno-pie"] {
1836            let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1837            assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1838            // The one it may have meant, since the two are a letter apart and one of them is
1839            // about linking and is taken.
1840            assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1841        }
1842    }
1843
1844    #[test]
1845    fn an_unsupported_target_names_itself() {
1846        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1847        assert!(e.message.contains("sparc64"), "{}", e.message);
1848    }
1849
1850    #[test]
1851    fn no_inputs_is_an_error_but_print_config_needs_none() {
1852        assert!(parse_args(&args(&[])).is_err());
1853        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1854    }
1855
1856    #[test]
1857    fn print_config_reports_the_target_it_was_given_not_the_host() {
1858        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1859        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1860        let text = print_config(&opts);
1861        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1862        assert!(text.contains("char-signed: false"), "{text}");
1863        assert!(text.contains("object-format: elf"), "{text}");
1864        assert!(text.contains("va-list: void-pointer"), "{text}");
1865        // RISC-V has a register file and this compiler has not written it down yet, and the
1866        // dump says which of those two it is rather than leaving the line out.
1867        assert!(text.contains("registers: none"), "{text}");
1868    }
1869
1870    #[test]
1871    fn print_config_has_one_key_per_line_and_a_fixed_order() {
1872        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1873        let text = print_config(&opts);
1874        let keys: Vec<&str> =
1875            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1876        assert_eq!(keys[0], "version");
1877        assert_eq!(keys[1], "target");
1878        assert_eq!(keys.len(), 19);
1879        assert!(text.ends_with('\n'));
1880    }
1881
1882    #[test]
1883    fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
1884        let (opts, _) = compile(&["a.c"]);
1885        assert_eq!(opts.safety, rucc_session::Safety::Off);
1886
1887        for (flag, tier) in [
1888            ("-fsafety=detect", rucc_session::Safety::Detect),
1889            ("-fsafety=enforce", rucc_session::Safety::Enforce),
1890            ("-fsafety=kernel", rucc_session::Safety::Kernel),
1891            ("-fsafety=off", rucc_session::Safety::Off),
1892        ] {
1893            let (opts, _) = compile(&[flag, "a.c"]);
1894            assert_eq!(opts.safety, tier, "{flag}");
1895        }
1896
1897        // The last one wins, the way every other repeated flag on this command line does.
1898        let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
1899        assert_eq!(opts.safety, rucc_session::Safety::Off);
1900
1901        // A misspelled tier is refused rather than ignored. Silently compiling without the
1902        // monitor a build asked for is the one failure mode this feature cannot have.
1903        let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
1904        assert!(e.message.contains("is not a safety tier"), "{}", e.message);
1905        assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
1906    }
1907
1908    #[test]
1909    fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
1910        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1911        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1912        let text = print_pipeline(&opts);
1913        assert!(text.starts_with("level: -O2\n"), "{text}");
1914        assert!(text.contains("fold"), "{text}");
1915
1916        let a = parse_args(&args(&["--print-pipeline"])).unwrap();
1917        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1918        // One pass runs at `-O0` and it is the one that removes code nothing reaches, which is
1919        // not an optimization. See issue 359.
1920        assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
1921
1922        let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
1923        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1924        // And with that one turned off there is nothing left, which the dump says rather than
1925        // printing an empty list.
1926        assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1927    }
1928
1929    #[test]
1930    fn print_pipeline_takes_the_toggles_into_account() {
1931        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
1932        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1933        let text = print_pipeline(&opts);
1934        // The one that was named is gone and the rest of the level is not, which is the whole
1935        // of what a toggle promises.
1936        assert!(!text.contains("fold"), "{text}");
1937        assert!(text.contains("dce"), "{text}");
1938
1939        // Every pass the compiler has, named off. Built from the registry rather than written
1940        // out, so a pass added later is turned off here too and this keeps testing the thing it
1941        // is about, which is that the toggles can empty a level.
1942        let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
1943        off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
1944        let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
1945        let a = parse_args(&args(&spelled)).unwrap();
1946        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1947        assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1948    }
1949
1950    #[test]
1951    fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
1952        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1953        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1954        assert!(!print_pipeline(&opts).contains("global fuel"));
1955
1956        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
1957        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1958        let text = print_pipeline(&opts);
1959        // Because the listing is the answer to what this compilation will do, and a run that
1960        // stops after four rewrites is not doing what the level says it does.
1961        assert!(text.contains("global fuel: 4"), "{text}");
1962    }
1963
1964    /// A pass is turned on and off by its own name, and the order the flags were given in is
1965    /// kept, because the last spelling of a name is the one that decides.
1966    #[test]
1967    fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
1968        let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
1969        assert_eq!(
1970            opts.passes,
1971            [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
1972        );
1973
1974        let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
1975        assert!(e.message.contains("unknown option"), "{}", e.message);
1976    }
1977
1978    #[test]
1979    fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
1980        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
1981        assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
1982
1983        let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
1984        assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
1985        let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
1986        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
1987        let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
1988        assert!(e.message.contains("not a number"), "{}", e.message);
1989    }
1990
1991    #[test]
1992    fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
1993        let (opts, _) = compile(&["-c", "-O2", "a.c"]);
1994        assert_eq!(opts.pass_fuel_global, None);
1995
1996        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
1997        assert_eq!(opts.pass_fuel_global, Some(12));
1998        // And it is not the per pass flag with a longer name, so neither spelling swallows the
1999        // other.
2000        assert!(opts.pass_fuel.is_empty());
2001
2002        let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2003        assert!(e.message.contains("not a number"), "{}", e.message);
2004    }
2005
2006    #[test]
2007    fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2008        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2009        assert_eq!(
2010            opts.pass_gates,
2011            [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2012            "the order is what decides, so it has to survive the parse"
2013        );
2014
2015        let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2016        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2017        let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2018        assert!(e.message.contains("ends before it starts"), "{}", e.message);
2019        let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2020        assert!(e.message.contains("is empty"), "{}", e.message);
2021    }
2022
2023    #[test]
2024    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2025        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2026        let text = print_pipeline(&opts);
2027        assert!(text.contains("fold, "), "{text}");
2028        assert!(text.contains("[off for main]"), "{text}");
2029    }
2030
2031    /// The spelling is checked while the arguments are read, because a dump that names a pass
2032    /// this compiler does not have is a typo, and a typo found after the compilation has run is
2033    /// found too late to be any use.
2034    #[test]
2035    fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2036        let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2037        assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2038
2039        let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2040        assert!(e.message.contains("nosuch"), "{}", e.message);
2041        assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2042    }
2043
2044    /// Every spelling `-fopt-info` takes, and the one it does not.
2045    ///
2046    /// The keywords are checked here for the same reason a dump's pass name is: a person who
2047    /// misspelled one gets no output, and no output is also what a compilation where nothing
2048    /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
2049    #[test]
2050    fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2051        let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2052        assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2053        assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2054
2055        let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2056        assert_eq!(opts.opt_info, ["missed-note"]);
2057
2058        // Two flags add up rather than the second replacing the first, and the file is the last
2059        // one that named a file, which is how GCC treats both.
2060        let (opts, _) =
2061            compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2062        assert_eq!(opts.opt_info, ["missed", "all"]);
2063        assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2064
2065        let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2066        assert!(e.message.contains("vectorized"), "{}", e.message);
2067        assert!(e.message.contains("`missed`"), "{}", e.message);
2068        let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2069        assert!(e.message.contains("no file"), "{}", e.message);
2070    }
2071
2072    #[test]
2073    fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2074        let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2075        assert!(opts.verify_each);
2076        assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2077    }
2078
2079    #[test]
2080    fn dash_o_needs_an_argument() {
2081        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2082        assert_eq!(e.message, "-o requires an argument");
2083    }
2084
2085    #[test]
2086    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2087        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2088        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2089        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2090    }
2091
2092    #[test]
2093    fn the_include_flags_land_on_the_chain_each_one_names() {
2094        // A sysroot with nothing under it, so that the library's own directories are the
2095        // same on every machine this test runs on, which is none of them.
2096        let (opts, _) = compile(&[
2097            "-Ii",
2098            "-iquote",
2099            "q",
2100            "-isystem",
2101            "sys",
2102            "-idirafter",
2103            "after",
2104            "--sysroot=/nowhere-at-all",
2105            "a.c",
2106        ]);
2107        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2108        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
2109        // which is where GCC puts its own: a directory the user named outranks ours.
2110        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2111        assert!(!opts.search.dirs()[1].is_system);
2112        assert!(opts.search.dirs()[2].is_system);
2113    }
2114
2115    #[test]
2116    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2117        // Which machine this runs on decides what is on the path, so the test is about the
2118        // order rather than about the names: ours is on it, the library's follow it, and
2119        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
2120        let (opts, _) = compile(&["a.c"]);
2121        let dirs = opts.search.dirs();
2122        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2123        assert_eq!(ours, Some(0), "{dirs:?}");
2124        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2125        let (bare, _) = compile(&["-nostdinc", "a.c"]);
2126        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2127    }
2128
2129    #[test]
2130    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2131        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2132        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2133        assert_eq!(dirs, ["sys", runtime::DIR]);
2134    }
2135
2136    #[test]
2137    fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2138        let (opts, _) =
2139            compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2140        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2141        assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2142        // An angled include sees only what came after the flag.
2143        assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2144        assert!(!opts.search.searches_current_dir());
2145    }
2146
2147    #[test]
2148    fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2149        let (opts, _) = compile(&[
2150            "-iprefix",
2151            "/tools/",
2152            "-iwithprefix",
2153            "late",
2154            "-iwithprefixbefore",
2155            "early",
2156            "-iprefix",
2157            "/other/",
2158            "-iwithprefix",
2159            "last",
2160            "-nostdinc",
2161            "a.c",
2162        ]);
2163        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2164        // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
2165        // puts them rather than where its manual says it does.
2166        assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2167        assert!(!opts.search.dirs()[0].is_system);
2168        assert!(opts.search.dirs()[1].is_system);
2169    }
2170
2171    #[test]
2172    fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2173        let (opts, _) =
2174            compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2175        let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2176        assert_eq!(names, ["one.h", "two.h", "3.h"]);
2177        assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2178    }
2179
2180    #[test]
2181    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2182        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2183        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2184        assert_eq!(dirs, ["i"]);
2185    }
2186
2187    #[test]
2188    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2189        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2190        assert_eq!(opts.std, Std::C11);
2191        assert!(opts.gnu_extensions);
2192
2193        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2194        assert_eq!(opts.std, Std::C99);
2195        assert!(!opts.gnu_extensions);
2196
2197        let (opts, _) = compile(&["-ansi", "a.c"]);
2198        assert_eq!(opts.std, Std::C89);
2199        assert!(!opts.gnu_extensions);
2200
2201        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2202        assert!(e.message.contains("unknown dialect"), "{}", e.message);
2203    }
2204
2205    #[test]
2206    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2207        let (opts, _) = compile(&["-dM", "a.c"]);
2208        assert!(opts.dumps.macros);
2209
2210        // Packed, the way GCC takes them, and a letter in the family we have not written yet
2211        // is accepted and does nothing rather than failing a build.
2212        let (opts, _) = compile(&["-dDM", "a.c"]);
2213        assert!(opts.dumps.macros);
2214        let (opts, _) = compile(&["-dD", "a.c"]);
2215        assert!(!opts.dumps.macros);
2216
2217        let (opts, _) = compile(&["a.c"]);
2218        assert!(!opts.dumps.any());
2219
2220        // `-dumpversion` is a different flag that happens to start the same way, and it is read
2221        // as itself rather than as a dump of nothing.
2222        assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2223    }
2224
2225    #[test]
2226    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2227        let (opts, _) = compile(&["a.c"]);
2228        assert_eq!(
2229            opts.gnuc,
2230            GnucVersion { major: 7, minor: 0, patch: 0 },
2231            "the lowest claim a modern glibc gives its own declarations to"
2232        );
2233
2234        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2235        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2236
2237        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
2238        // patchlevel and a harness that pastes that back has to be understood.
2239        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2240        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2241
2242        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2243        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2244
2245        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2246        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2247
2248        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2249        assert!(e.message.contains("more than three"), "{}", e.message);
2250    }
2251
2252    #[test]
2253    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2254        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2255        assert!(opts.pedantic);
2256        assert_eq!(opts.std, Std::C17);
2257
2258        // The `-W` family's name for it, which is what a build that groups its warning flags
2259        // tends to write.
2260        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2261        assert!(opts.pedantic);
2262
2263        let (opts, _) = compile(&["-std=c17", "a.c"]);
2264        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2265    }
2266
2267    #[test]
2268    fn dash_p_and_dash_ffreestanding_reach_the_options() {
2269        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2270        assert!(!opts.line_markers);
2271        assert!(!opts.hosted);
2272        assert_eq!(opts.emit, EmitKind::Preprocessed);
2273    }
2274
2275    /// The two ways a build says it means its own function by a name the C library also has.
2276    ///
2277    /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
2278    /// build writes when it means its own `memcpy` and the library's everything else. The name is
2279    /// kept as it was written and not checked against anything, because a program is allowed to
2280    /// mean something by a name this compiler has never heard of.
2281    #[test]
2282    fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2283        let (opts, _) = compile(&["-c", "a.c"]);
2284        assert!(opts.builtins, "a library name means the library function by default");
2285        assert!(opts.no_builtin.is_empty());
2286
2287        let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2288        assert!(!opts.builtins);
2289
2290        let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2291        assert!(opts.builtins, "the last mention decides");
2292
2293        let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2294        assert!(opts.builtins, "one name is not the family");
2295        assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2296    }
2297
2298    /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
2299    /// and which was refused as an unknown option until now.
2300    ///
2301    /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
2302    /// the address across a component boundary, and nothing derives anything from that promise
2303    /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
2304    /// over a distinction this compiler does not make.
2305    #[test]
2306    fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2307        let (opts, _) = compile(&["-c", "a.c"]);
2308        assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2309
2310        for (written, wanted) in [
2311            ("default", Visibility::Default),
2312            ("hidden", Visibility::Hidden),
2313            ("internal", Visibility::Hidden),
2314            ("protected", Visibility::Protected),
2315        ] {
2316            let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2317            assert_eq!(opts.visibility, wanted, "{written}");
2318        }
2319
2320        // The last mention decides, which is what every other flag of this shape does and what a
2321        // build that turns something off for one directory relies on.
2322        let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2323        assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2324
2325        // A spelling gcc does not take is refused rather than read as the default, because a
2326        // build that meant hidden and got exported is a library with the wrong interface and
2327        // nothing said about it anywhere.
2328        let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2329        assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2330    }
2331
2332    /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
2333    /// line, since the dialect asks for GNU's reading further in rather than through this.
2334    #[test]
2335    fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2336        let (opts, _) = compile(&["-c", "a.c"]);
2337        assert!(!opts.gnu89_inline, "C's reading of inline by default");
2338
2339        let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2340        assert!(opts.gnu89_inline);
2341
2342        let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2343        assert!(!opts.gnu89_inline, "the last mention decides");
2344
2345        // The C89 dialects are under GNU's reading whether this was written or not, so the flag
2346        // stays off there and the dialect is what the checker and the macro set both ask. That is
2347        // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
2348        // dialect already has. gcc refuses that command line, which is measured in the issue.
2349        let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2350        assert!(!opts.gnu89_inline);
2351    }
2352
2353    /// Both spellings of both frame flags, since a build that wants one usually writes the
2354    /// other beside it for the one file that has to be compiled the ordinary way.
2355    #[test]
2356    fn the_two_frame_flags_are_read_in_both_directions() {
2357        let (opts, _) = compile(&["-c", "a.c"]);
2358        assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2359        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2360
2361        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2362        assert!(opts.frame_pointer);
2363        assert!(!opts.red_zone);
2364
2365        let (opts, _) = compile(&[
2366            "-c",
2367            "-fno-omit-frame-pointer",
2368            "-fomit-frame-pointer",
2369            "-mno-red-zone",
2370            "-mred-zone",
2371            "a.c",
2372        ]);
2373        assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2374        assert!(opts.red_zone);
2375    }
2376
2377    #[test]
2378    fn the_link_flags_are_collected_apart_from_the_compilation() {
2379        let (link, _) = linking(&[
2380            "-static",
2381            "-nostartfiles",
2382            "-rdynamic",
2383            "-s",
2384            "-fuse-ld=mold",
2385            "-L/opt/lib",
2386            "-B",
2387            "/opt/tools",
2388            "a.c",
2389        ]);
2390        assert!(link.is_static);
2391        assert!(link.no_startfiles);
2392        assert!(link.export_dynamic);
2393        assert!(link.strip);
2394        assert_eq!(link.use_ld.as_deref(), Some("mold"));
2395        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2396        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2397    }
2398
2399    #[test]
2400    fn a_comma_in_dash_wl_separates_two_arguments() {
2401        let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2402        assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2403    }
2404
2405    #[test]
2406    fn a_library_keeps_its_place_between_the_objects() {
2407        // Link order is semantic: `-lm` written between two files resolves for the one before
2408        // it and not for the one after, so a library cannot be collected into a list of its own.
2409        // The target is named because the suffix of an object is the target's and this asserts
2410        // on the names: the same command line on a Windows host plans two `.obj` files.
2411        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2412        let link = plan.link.expect("expected a link step");
2413        assert_eq!(
2414            link.inputs,
2415            vec![
2416                link::Item::File("a.o".into()),
2417                link::Item::Library("m".into()),
2418                link::Item::File("b.o".into()),
2419            ]
2420        );
2421        // And it is not a job, because there is nothing to compile in a library.
2422        assert_eq!(plan.jobs.len(), 2);
2423    }
2424
2425    #[test]
2426    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2427        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2428        assert!(plan.link.is_none());
2429        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2430    }
2431
2432    #[test]
2433    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2434        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2435        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2436    }
2437
2438    fn printed(s: &[&str]) -> String {
2439        match parse_args(&args(s)).expect("expected an answer") {
2440            Action::Print(line) => line,
2441            other => panic!("expected an answer, got {other:?}"),
2442        }
2443    }
2444
2445    fn refused(s: &[&str]) -> String {
2446        parse_args(&args(s)).expect_err("expected a refusal").message
2447    }
2448
2449    #[test]
2450    fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2451        // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
2452        // out whether a warning flag exists by passing it and looking at the exit status, so a
2453        // compiler that refuses one it does not know fails a script written for a newer GCC.
2454        let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2455        assert!(!opts.warnings_are_errors);
2456        assert!(opts.warnings);
2457        // The two spellings that do mean something are still read.
2458        let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2459        assert!(opts.warnings_are_errors);
2460        let (opts, _) = compile(&["-w", "-c", "a.c"]);
2461        assert!(!opts.warnings);
2462        let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2463        assert!(opts.pedantic && opts.warnings_are_errors);
2464    }
2465
2466    #[test]
2467    fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2468        // Every one of these says something about the output, so the wrong answer is silence.
2469        assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2470        assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2471        assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2472        assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2473        assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2474        assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2475        // The word size the target does not have, which is a target this compiler was not asked
2476        // for rather than a flag it does not know.
2477        let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2478        assert!(no32.contains("32 bit target"), "{no32}");
2479    }
2480
2481    #[test]
2482    fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2483        assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2484        assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2485        assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2486    }
2487
2488    #[test]
2489    fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2490        let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2491        let (opts, _) =
2492            compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2493        assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2494        let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2495        assert!(wrong.contains("sysv convention"), "{wrong}");
2496    }
2497
2498    #[test]
2499    fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2500        let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2501        assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2502        // After the input, because a static link takes what it needs from a library when it
2503        // reaches it and not afterwards.
2504        let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2505        assert_eq!(names, vec!["a.c"]);
2506    }
2507
2508    #[test]
2509    fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2510        let target = "--target=x86_64-unknown-linux-gnu";
2511        assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2512        assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2513        assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2514        assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2515        // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
2516        // answer safe to paste into a link line whether or not the file is there.
2517        assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2518        assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2519        let dirs = printed(&[target, "-print-search-dirs"]);
2520        assert!(dirs.starts_with("install: "), "{dirs}");
2521        assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2522    }
2523
2524    #[test]
2525    fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2526        let (opts, _) = compile(&["-M", "a.c"]);
2527        assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2528        assert!(opts.deps.system_headers, "plain -M lists them");
2529        assert_eq!(opts.emit, EmitKind::Preprocessed);
2530
2531        // Even where a later flag asked for something else, because the family is a mode and
2532        // the mode is what the run is for.
2533        let (opts, _) = compile(&["-M", "-c", "a.c"]);
2534        assert_eq!(opts.emit, EmitKind::Preprocessed);
2535
2536        let (opts, _) = compile(&["-MM", "a.c"]);
2537        assert!(!opts.deps.system_headers);
2538    }
2539
2540    #[test]
2541    fn the_two_that_end_in_d_leave_the_compilation_alone() {
2542        let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2543        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2544        assert!(opts.deps.system_headers);
2545        assert_eq!(opts.emit, EmitKind::Object);
2546
2547        let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2548        assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2549        assert!(!opts.deps.system_headers);
2550    }
2551
2552    #[test]
2553    fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2554        // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
2555        // the answer, because the other one never asked the question.
2556        let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2557        assert!(!opts.deps.system_headers);
2558        let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2559        assert!(!opts.deps.system_headers);
2560        let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2561        assert!(!opts.deps.system_headers);
2562    }
2563
2564    #[test]
2565    fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2566        let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2567        assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2568    }
2569
2570    #[test]
2571    fn the_rest_of_the_family_is_a_file_and_a_switch() {
2572        let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2573        assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2574        assert!(opts.deps.phony);
2575
2576        for flag in ["-MF", "-MT", "-MQ"] {
2577            let e = parse_args(&args(&[flag])).unwrap_err();
2578            assert!(e.message.contains("requires an argument"), "{}", e.message);
2579        }
2580    }
2581
2582    /// A directory of sources for one test, removed when the test is done with it.
2583    struct TempTree(PathBuf);
2584
2585    impl Drop for TempTree {
2586        fn drop(&mut self) {
2587            let _ = std::fs::remove_dir_all(&self.0);
2588        }
2589    }
2590
2591    impl TempTree {
2592        fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2593            let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2594            let _ = std::fs::remove_dir_all(&dir);
2595            std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2596            for (path, text) in files {
2597                let at = dir.join(path);
2598                if let Some(parent) = at.parent() {
2599                    std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2600                }
2601                std::fs::write(&at, text).expect("writing a temporary file should work");
2602            }
2603            TempTree(dir)
2604        }
2605
2606        fn path(&self, name: &str) -> String {
2607            self.0.join(name).to_string_lossy().into_owned()
2608        }
2609    }
2610
2611    #[test]
2612    fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2613        // End to end, because the list comes from the preprocessor and the format comes from
2614        // somewhere else, and a test of either half on its own would pass with the two of them
2615        // wired up backwards.
2616        let tree = TempTree::new(
2617            "found",
2618            &[
2619                ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2620                ("one.h", "#define X 0\n"),
2621                ("two.h", "#include \"one.h\"\n"),
2622            ],
2623        );
2624        let out = tree.path("dep.d");
2625        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2626        assert_eq!(code, 0);
2627
2628        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2629        let names: Vec<&str> = text.split_whitespace().collect();
2630        // The target, the source, and each header once however many times it was reached.
2631        assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2632        assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2633        assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2634        // And the `-o` went to the file the rule replaced, which is left empty rather than
2635        // absent because a makefile that named it as a target will look for it.
2636        assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2637    }
2638
2639    #[test]
2640    fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2641        // The multiple-include optimization means the second reach never opens the file. It is
2642        // still a file this translation unit was built from, so it is still in the rule.
2643        let tree = TempTree::new(
2644            "guarded",
2645            &[
2646                ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2647                ("g.h", "#ifndef G\n#define G\n#endif\n"),
2648            ],
2649        );
2650        let out = tree.path("dep.d");
2651        let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2652        assert_eq!(code, 0);
2653        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2654        assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2655    }
2656
2657    #[test]
2658    fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2659        // Measured against GCC rather than read: the two flags the other way round produce the
2660        // same output byte for byte, so the command line order between the two families does not
2661        // decide anything and the order within one does. The `-include` file here can only see
2662        // the definition if the `-imacros` file that was written after it ran first.
2663        let tree = TempTree::new(
2664            "preinclude",
2665            &[
2666                ("a.c", "int main(void) { return 0; }\n"),
2667                ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2668                ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2669            ],
2670        );
2671        let out = tree.path("a.i");
2672        let code = run(&args(&[
2673            "-E",
2674            "-include",
2675            &tree.path("i.h"),
2676            "-imacros",
2677            &tree.path("m.h"),
2678            "-o",
2679            &out,
2680            &tree.path("a.c"),
2681        ]));
2682        assert_eq!(code, 0);
2683        let text = std::fs::read_to_string(&out).expect("the output should have been written");
2684        assert!(text.contains("saw_it"), "{text}");
2685        // And the text of the `-imacros` file is thrown away, which is the whole difference
2686        // between the two flags.
2687        assert!(!text.contains("macros_text"), "{text}");
2688    }
2689
2690    #[test]
2691    fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
2692        let tree = TempTree::new(
2693            "preinclude-deps",
2694            &[
2695                ("a.c", "int main(void) { return 0; }\n"),
2696                ("i.h", "int from_include;\n"),
2697                ("m.h", "#define M 1\n"),
2698            ],
2699        );
2700        let out = tree.path("dep.d");
2701        let code = run(&args(&[
2702            "-MM",
2703            "-MF",
2704            &out,
2705            "-include",
2706            &tree.path("i.h"),
2707            "-imacros",
2708            &tree.path("m.h"),
2709            "-o",
2710            &tree.path("a.i"),
2711            &tree.path("a.c"),
2712        ]));
2713        assert_eq!(code, 0);
2714        let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2715        assert!(text.contains("i.h"), "{text}");
2716        assert!(text.contains("m.h"), "{text}");
2717    }
2718
2719    #[test]
2720    fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
2721        // Including the directory of the source file, which is not on the path for these: the
2722        // command line was not written there, so a name in it is relative to where the compiler
2723        // was run rather than to where the source sits.
2724        let tree = TempTree::new(
2725            "preinclude-missing",
2726            &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
2727        );
2728        let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
2729        assert_eq!(code, 1);
2730    }
2731
2732    #[test]
2733    fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
2734        // The object a link goes through is in a temporary directory and is gone before `make`
2735        // reads any of this, so the rule that named it would be a rule for a file that is never
2736        // there. The target and the file are both the `-o`, which is the executable.
2737        let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
2738        assert_eq!(plan.output.as_deref(), Some("prog"));
2739        assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
2740        assert_eq!(
2741            deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
2742            Some("prog.d")
2743        );
2744    }
2745
2746    #[test]
2747    fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
2748        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
2749        assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
2750        let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
2751        assert_eq!(plan.output, None);
2752    }
2753
2754    #[test]
2755    fn usage_fits_on_a_screen() {
2756        // Not a style preference. A help text that scrolls is one nobody reads, and this is
2757        // the cheapest way to keep it honest as flags accumulate. The number goes up only when
2758        // a family of flags arrives that has nowhere to share a line, which the two pass gates
2759        // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
2760        // the lines that family took. The four it went up by last are the flags a build system
2761        // passes without being asked to: how much to say, what machine to generate for, threads,
2762        // and the questions `configure` asks before it compiles anything. The one it went up by
2763        // last is the second line of `--emit`, whose kinds are a family that has now outgrown
2764        // one line and has nowhere else to go. The two it went up by last are the dependency
2765        // family, which is eight flags that share nothing with anything above them. The one it
2766        // went up by last is the four spellings of position independent code, which every
2767        // configure script writes and which could only have shared the link line, and that line
2768        // is already four characters short of the limit. The two it went up by last are the rest
2769        // of the include family, which is six more flags that change where a header is looked for
2770        // and two that name a header outright. The one it went up by last is the pair that keeps
2771        // the intermediate files and times the steps, which belong next to the two flags above
2772        // them that are also about watching a compilation rather than changing one.
2773        assert!(USAGE.lines().count() < 48, "usage text has grown past one screen");
2774    }
2775}