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`, `-iquote`, `-isystem`, `-idirafter`, `--sysroot=`, `-isysroot`, `-P`, `-std=`,
21//! `-fgnuc-version=`, `-ansi`, `-ffreestanding`, `-fno-builtin`, `-fno-builtin-<name>`,
22//! `-fgnu89-inline`, `-pedantic` and `-Werror`.
23//! The phases after them still say they are not implemented.
24//!
25//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
26//! explicitly unstable and will change without a major version bump.
27
28#![doc(html_root_url = "https://docs.rs/rucc-driver/0.9.2")]
29
30pub mod compile;
31pub mod library;
32pub mod link;
33mod map;
34pub mod phase;
35pub mod preprocess;
36pub mod schedule;
37
38use std::fmt::Write as _;
39use std::io::Write as _;
40use std::path::PathBuf;
41
42use rucc_codegen::coverage::{self, Fired};
43use rucc_session::{Dumps, EmitKind, Options, Session, Std, runtime};
44use rucc_target::Triple;
45
46use crate::link::LinkOptions;
47
48pub use crate::compile::{Artifact, Compiled, compile, compile_ir};
49pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
50pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
51pub use crate::schedule::Jobs;
52
53/// The compiler's version, taken from the workspace manifest.
54pub const VERSION: &str = env!("CARGO_PKG_VERSION");
55
56/// What the command line asked for.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Action {
59    /// Print usage and exit successfully.
60    Help,
61    /// Print the version and exit successfully.
62    Version,
63    /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
64    ///
65    /// A build system asks these before it compiles anything, and what it does with the answer
66    /// is paste it into a path or into another command line, so each one is a single line with
67    /// no decoration around it.
68    Print(String),
69    /// Print the resolved configuration and exit successfully.
70    PrintConfig(Box<Options>),
71    /// Print the passes the level will run and exit successfully.
72    PrintPipeline(Box<Options>),
73    /// Print the phase plan and the link line and exit successfully, which is `-###`.
74    PrintPlan {
75        /// The resolved options, which is what says what the link line is for.
76        opts: Box<Options>,
77        /// What to do to each input, and in what order.
78        plan: Box<Plan>,
79        /// What the command line said about linking.
80        link: Box<LinkOptions>,
81    },
82    /// Compile the given inputs.
83    Compile {
84        /// The resolved options.
85        opts: Box<Options>,
86        /// What to do to each input, and in what order.
87        plan: Box<Plan>,
88        /// What the command line said about linking.
89        link: Box<LinkOptions>,
90        /// How many translation units to compile at once.
91        jobs: Jobs,
92        /// Whether `-v` asked for the plan to be printed while it runs.
93        verbose: bool,
94    },
95}
96
97/// Why a command line was rejected.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct CliError {
100    /// The message, lowercase and without a trailing period, in the same shape as any other
101    /// diagnostic.
102    pub message: String,
103}
104
105impl std::fmt::Display for CliError {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        f.write_str(&self.message)
108    }
109}
110
111impl std::error::Error for CliError {}
112
113fn err(message: impl Into<String>) -> CliError {
114    CliError { message: message.into() }
115}
116
117/// A question the command line asked instead of asking for a compilation.
118///
119/// These are answered after the loop rather than where they are read, because every one of them
120/// is about the target or about the library search and the last word on both is the end of the
121/// command line.
122enum Query {
123    /// `-dumpmachine`, the triple.
124    Machine,
125    /// `-dumpversion` and `-dumpfullversion`, which are the same three numbers here.
126    Version,
127    /// `-print-multiarch`, the directory name a distribution files this target under.
128    Multiarch,
129    /// `-print-search-dirs`, in the three lines GCC prints.
130    SearchDirs,
131    /// `-print-file-name=<name>`, the full path of a library file.
132    FileName(String),
133    /// `-print-prog-name=<name>`, the full path of a program.
134    ProgName(String),
135    /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
136    Libgcc,
137}
138
139/// Usage text.
140///
141/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
142/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
143pub const USAGE: &str = "\
144rucc, an optimizing C compiler
145
146usage: rucc [options] file...
147
148options:
149  -c                     compile and assemble, do not link
150  -S                     compile only, emit assembly
151  -E                     preprocess only
152  -o <file>              write output to <file>, or to standard output for -
153  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
154  -I <dir>               add <dir> to the include search path
155  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
156  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
157  -P, -dM                with -E: leave out the markers, or dump the macros
158  -std=<dialect>         c89 through c23, and the gnu spellings
159  -fgnuc-version=<v>     the GCC release to claim, default 7.0.0
160  -x <lang>              treat later inputs as <lang>, or none to stop
161  -O<level>              optimize: 0, 1, 2, 3, s, z
162  -fsafety=<tier>        check memory safety: off, detect, enforce, kernel
163  -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
164  -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n>   stop a pass, or all of them, after n
165  -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>]   run a pass on some functions only
166  -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone   debug info, frame pointer, red zone
167  -l<name>, -L <dir>, -B <dir>   link a library, where to look for one, where our own tools are
168  -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s   how to link
169  -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name>   hand an argument to the linker, or pick one
170  -Werror -pedantic -pedantic-errors -w   how much to say, and whether it is fatal
171  -m64 -march= -mtune= -mcpu= -mabi= -mcmodel=   what machine to generate for
172  -pthread               build for more than one thread, and link the library for it
173  -dumpmachine -dumpversion -print-multiarch -print-search-dirs   what this compiler is
174  -print-file-name=<name> -print-prog-name=<name>   where a file or a program is
175  -j[n]                  compile n translation units at once, default all
176  -v, -###               print each phase as it runs, or without running any
177  --target=<triple>      generate code for <triple>
178  --emit=<kind>          exe, obj, asm, preprocessed, tast, ir, mir-final,
179                         safety-summary, type-granules
180  --print-config, --print-pipeline    print the configuration or the pipeline, and exit
181  --version              print the version and exit
182  -h, --help             print this message and exit
183
184See spec/04-driver-and-cli.md for the full flag reference.
185";
186
187/// The argument of a flag that may be joined to it or may be the next word.
188///
189/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
190fn joined_or_next(
191    arg: &str,
192    at: usize,
193    args: &[String],
194    i: &mut usize,
195) -> Result<String, CliError> {
196    if arg.len() > at {
197        return Ok(arg[at..].to_owned());
198    }
199    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
200    *i += 1;
201    Ok(next.clone())
202}
203
204/// Parses a command line, without the program name.
205///
206/// # Errors
207///
208/// Returns the message to print when the arguments do not name a compilation this compiler
209/// can attempt.
210pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
211    let host = Triple::host()
212        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
213    let mut opts = Options::new(host);
214    let mut inputs: Vec<Input> = Vec::new();
215    let mut print_config = false;
216    let mut print_pipeline = false;
217    let mut print_plan = false;
218    let mut verbose = false;
219    let mut jobs = Jobs::default();
220    let mut nostdinc = false;
221    let mut sysroot: Option<PathBuf> = None;
222    let mut output = None;
223    let mut link = LinkOptions::default();
224    let mut query: Option<Query> = None;
225    let mut threads = false;
226    // `-x` applies to inputs that come after it and stays in effect until the next one, which
227    // is why it is tracked across the loop rather than attached to a single argument.
228    let mut forced: Option<InputKind> = None;
229
230    let mut i = 0;
231    while i < args.len() {
232        let arg = args[i].as_str();
233        i += 1;
234        match arg {
235            "-h" | "--help" => return Ok(Action::Help),
236            "--version" => return Ok(Action::Version),
237            "--print-config" => print_config = true,
238            "--print-pipeline" => print_pipeline = true,
239            "-###" => print_plan = true,
240            "-v" => verbose = true,
241            "-c" => opts.emit = EmitKind::Object,
242            "-S" => opts.emit = EmitKind::Asm,
243            "-E" => opts.emit = EmitKind::Preprocessed,
244            "-g" => opts.debug_info = true,
245            // GCC's own levels of how much debug information to write. Zero is none and every
246            // other number is some, and this compiler has one amount, so the numbers above zero
247            // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
248            // debugger on the machine prefers, which is what we emit anyway.
249            "-g0" => opts.debug_info = false,
250            "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
251                opts.debug_info = true;
252            }
253            // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
254            // asks for another version is told rather than handed a file it cannot read.
255            "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
256            _ if arg.starts_with("-gdwarf-") => {
257                return Err(err(format!(
258                    "{arg}: this compiler writes DWARF 5 and no other version, see \
259                     spec/11-debug-info.md"
260                )));
261            }
262            "-Werror" => opts.warnings_are_errors = true,
263            // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
264            // through rather than here, so that a warning `-w` dropped is not counted either.
265            "-w" => opts.warnings = false,
266            "-pedantic-errors" => {
267                opts.pedantic = true;
268                opts.warnings_are_errors = true;
269            }
270            "-P" => opts.line_markers = false,
271            // The questions a build system asks before it compiles anything. Answered after the
272            // loop, because each one is about the target or the library search and the command
273            // line has not finished saying what those are.
274            "-dumpmachine" => query = Some(Query::Machine),
275            "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
276            "-print-multiarch" => query = Some(Query::Multiarch),
277            "-print-search-dirs" => query = Some(Query::SearchDirs),
278            "-print-libgcc-file-name" => query = Some(Query::Libgcc),
279            _ if arg.starts_with("-print-file-name=") => {
280                query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
281            }
282            _ if arg.starts_with("-print-prog-name=") => {
283                query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
284            }
285            // A program built to run in more than one thread. On every platform this compiler
286            // targets that is a macro the library's headers read and one more library on the
287            // link line, and the library is added after the loop so that it lands after the
288            // objects that refer to it.
289            "-pthread" | "-pthreads" => {
290                opts.defines.push("_REENTRANT".to_owned());
291                threads = true;
292            }
293            "-ansi" => {
294                opts.std = Std::C89;
295                opts.gnu_extensions = false;
296            }
297            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
298            // the spelling a build system that groups its warning flags tends to write.
299            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
300            // Both directions, because a build that needs this for one directory turns it back
301            // off for the next one rather than leaving it on for the whole tree.
302            "-fpermissive" => opts.permissive = true,
303            "-fno-permissive" => opts.permissive = false,
304            "-ffreestanding" => opts.hosted = false,
305            "-fhosted" => opts.hosted = true,
306            "-fno-builtin" => opts.builtins = false,
307            "-fbuiltin" => opts.builtins = true,
308            // The C89 dialects are under GNU's reading whatever this says, so turning it off
309            // there is turning off something the dialect asked for, which is accepted and does
310            // nothing. gcc refuses that command line, and there is nothing it could have meant.
311            "-fgnu89-inline" => opts.gnu89_inline = true,
312            "-fno-gnu89-inline" => opts.gnu89_inline = false,
313            // Both directions of each, because a build system that wants one of these usually
314            // writes it beside the flag that turns it back off for one directory.
315            "-fno-omit-frame-pointer" => opts.frame_pointer = true,
316            "-fomit-frame-pointer" => opts.frame_pointer = false,
317            "-mno-red-zone" => opts.red_zone = false,
318            "-mred-zone" => opts.red_zone = true,
319            // GCC drops its own include directory along with the system ones, because its
320            // headers are half of a pair with the library's and half a pair is worse than
321            // none. A build that passes this is supplying the whole set itself.
322            "-nostdinc" => nostdinc = true,
323            "-o" => {
324                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
325                i += 1;
326            }
327            // The flags that take a directory only in the separated form. GCC spells them
328            // this way and nothing writes `-iquotedir`, so accepting the joined form would
329            // mean guessing at a path that starts with the flag's own letters.
330            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
331            // two mean the same thing here: the configured directories are under there rather
332            // than under the root.
333            "-isysroot" => {
334                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
335                i += 1;
336                sysroot = Some(PathBuf::from(dir));
337            }
338            "-iquote" | "-isystem" | "-idirafter" => {
339                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
340                i += 1;
341                match arg {
342                    "-iquote" => opts.search.push_quote(dir.clone()),
343                    "-isystem" => opts.search.push_system(dir.clone()),
344                    _ => opts.search.push_after(dir.clone()),
345                }
346            }
347            "-x" => {
348                let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
349                i += 1;
350                forced = if lang == "none" {
351                    None
352                } else {
353                    Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
354                };
355            }
356            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
357            // translation units in one process rather than making the build system fork, and
358            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
359            // to exist and has to be spelled the way `make` spells it.
360            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
361            // and a build system may produce either, so both are read here rather than
362            // being normalised by whatever generated the command line.
363            _ if arg.starts_with("-D") => {
364                let value = joined_or_next(arg, 2, args, &mut i)?;
365                opts.defines.push(value);
366            }
367            _ if arg.starts_with("-U") => {
368                let value = joined_or_next(arg, 2, args, &mut i)?;
369                opts.undefines.push(value);
370            }
371            _ if arg.starts_with("-I") => {
372                let dir = joined_or_next(arg, 2, args, &mut i)?;
373                opts.search.push_bracket(dir);
374            }
375            _ if arg.starts_with("-std=") => {
376                let name = &arg["-std=".len()..];
377                let (std, gnu) = Std::from_flag(name)
378                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
379                opts.std = std;
380                opts.gnu_extensions = gnu;
381            }
382            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
383            // handed, so a differential run that does not set it is comparing two compilers
384            // that believe they are different compilers.
385            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
386            // that we have not written yet are accepted and ignored, because a dump is a
387            // debugging aid and a build that asks for one should still compile. A letter
388            // outside the family falls through to the unknown option error, which is what
389            // keeps `-dumpversion` from being read as a dump of nothing.
390            _ if Dumps::is_family(arg) => {
391                opts.dumps.add(&arg[2..]);
392            }
393            // One name at a time, which is what a build that means its own `memcpy` and the
394            // library's everything else writes. The name is not checked against a list, because
395            // the flag is about what the program means by a name and a program is allowed to mean
396            // something by a name this compiler has never heard of.
397            _ if arg.starts_with("-fno-builtin-") => {
398                opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
399            }
400            _ if arg.starts_with("-fgnuc-version=") => {
401                let v = &arg["-fgnuc-version=".len()..];
402                opts.gnuc = v.parse().map_err(err)?;
403            }
404            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
405            // than the unknown option one, because a build reaching for it is asking for a feature
406            // and deserves to be told it is not coming rather than told the spelling is wrong.
407            // The negative form is what this compiler does anyway, so it is taken and dropped.
408            "-fnested-functions" => {
409                return Err(err(
410                    "nested functions are not supported: a call to one goes through a trampoline \
411                     written on the stack, which no target that enforces an unexecutable stack \
412                     allows",
413                ));
414            }
415            "-fno-nested-functions" => {}
416            // The link flags. None of them changes the compilation, which is why they are
417            // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
418            // error: it is a thing said to a linker that is not going to run.
419            "-static" => link.is_static = true,
420            "-shared" => link.shared = true,
421            "-pie" => link.pie = Some(true),
422            "-no-pie" | "-nopie" => link.pie = Some(false),
423            "-nostdlib" => link.no_stdlib = true,
424            "-nostartfiles" => link.no_startfiles = true,
425            "-nodefaultlibs" => link.no_defaultlibs = true,
426            "-fno-builtins-lib" => link.no_builtins_lib = true,
427            "-fbuiltins-lib" => link.no_builtins_lib = false,
428            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
429            "-s" => link.strip = true,
430            "-Xlinker" => {
431                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
432                i += 1;
433                link.passthrough.push(next.clone());
434            }
435            _ if arg.starts_with("-Wl,") => {
436                // Commas separate arguments rather than being part of one, which is what makes
437                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
438                link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
439            }
440            _ if arg.starts_with("-fuse-ld=") => {
441                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
442            }
443            _ if arg.starts_with("-l") && arg.len() > 2 => {
444                inputs.push(Input::library(&arg[2..]));
445            }
446            "-l" => {
447                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
448                i += 1;
449                inputs.push(Input::library(next));
450            }
451            _ if arg.starts_with("-L") => {
452                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
453            }
454            _ if arg.starts_with("-B") => {
455                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
456            }
457            _ if arg.starts_with("-j") => {
458                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
459            }
460            _ if arg.starts_with("--sysroot=") => {
461                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
462            }
463            _ if arg.starts_with("--target=") => {
464                let t = &arg["--target=".len()..];
465                opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
466            }
467            _ if arg.starts_with("--emit=") => {
468                let k = &arg["--emit=".len()..];
469                opts.emit = k
470                    .parse()
471                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
472            }
473            // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
474            // to write. `-Og` is GCC's level for a build somebody is going to step through, and
475            // it is `-O1` with the transformations that move code around left out; this compiler
476            // has no such level yet, so it is the nearest one and `--print-pipeline` says what
477            // that came to rather than the flag pretending otherwise.
478            "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
479            // The union of `-O3` and `-ffast-math`, and the second half of that changes what
480            // floating point arithmetic means. Refused rather than taken as `-O3`, because a
481            // build that asks for fast math and is quietly given ordinary arithmetic gets a
482            // slower program than it asked for and a build that is given fast math it did not
483            // ask for gets a wrong one.
484            "-Ofast" => {
485                return Err(err(
486                    "-Ofast is -O3 with fast math, and fast math is not implemented, see \
487                     spec/04-driver-and-cli.md section 4.6",
488                ));
489            }
490            _ if arg.starts_with("-O") => {
491                opts.opt_level = arg[2..]
492                    .parse()
493                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
494            }
495            // The memory safety monitor, from section 15.4 of
496            // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
497            // because a pass that took the name `safety=detect` would otherwise be handed the
498            // flag, and the tier is not a pass.
499            _ if arg.starts_with("-fsafety=") => {
500                let tier = &arg["-fsafety=".len()..];
501                opts.safety = tier.parse().map_err(|()| {
502                    err(format!(
503                        "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
504                    ))
505                })?;
506            }
507            // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
508            // after every `-f` the rest of the compiler answers to, so a pass can never take a
509            // name that already means something else on the command line.
510            _ if arg.starts_with("-fpass-fuel=") => {
511                let (name, count) = arg["-fpass-fuel=".len()..]
512                    .split_once('=')
513                    .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
514                if rucc_opt::pass::find(name).is_none() {
515                    return Err(err(format!(
516                        "`{name}` is not a pass this compiler has, see --print-pipeline"
517                    )));
518                }
519                let count: u32 = count
520                    .parse()
521                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
522                opts.pass_fuel.push((name.to_owned(), count));
523            }
524            _ if arg.starts_with("-fpass-fuel-global=") => {
525                let count = &arg["-fpass-fuel-global=".len()..];
526                let count: u32 = count
527                    .parse()
528                    .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
529                opts.pass_fuel_global = Some(count);
530            }
531            // Everything from `-fopt-info` to the end of the argument, which is optional
532            // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
533            // where the remarks are printed, because by then the compilation somebody wanted
534            // to hear about is over.
535            _ if arg == "-fopt-info"
536                || arg.starts_with("-fopt-info=")
537                || arg.starts_with("-fopt-info-") =>
538            {
539                let rest = &arg["-fopt-info".len()..];
540                let (kinds, file) = match rest.split_once('=') {
541                    Some((kinds, file)) => (kinds, Some(file)),
542                    None => (rest, None),
543                };
544                let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
545                rucc_opt::Wants::none().add(kinds).map_err(err)?;
546                opts.opt_info.push(kinds.to_owned());
547                if let Some(file) = file {
548                    if file.is_empty() {
549                        return Err(err("-fopt-info= was given no file to write to"));
550                    }
551                    opts.opt_info_file = Some(file.to_owned());
552                }
553            }
554            _ if arg.starts_with("-fdump-ir=") => {
555                // Checked here rather than where the dumps are taken, because the compilation
556                // that would have been dumped is over by then.
557                let spec = &arg["-fdump-ir=".len()..];
558                rucc_opt::Dumps::default().add(spec).map_err(err)?;
559                opts.dump_ir.push(spec.to_owned());
560            }
561            // Before the bare `-f<pass>` below, because a pass called `enable-something` would
562            // otherwise take the flag away from the gate. Checked here rather than where the
563            // pipeline reads it, for the reason that applies to all of these: a misspelled pass
564            // name that quietly gated nothing looks exactly like a pass that is not the guilty
565            // one, and a bisection would carry on past the thing it was looking for.
566            _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
567                let on = arg.starts_with("-fenable-");
568                let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
569                rucc_opt::Gates::default().add(on, spec).map_err(err)?;
570                opts.pass_gates.push((on, spec.to_owned()));
571            }
572            _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
573                opts.passes.push((arg["-fno-".len()..].to_owned(), false));
574            }
575            _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
576                opts.passes.push((arg["-f".len()..].to_owned(), true));
577            }
578            // The unstable options, spelled the way rustc spells them and carrying the same
579            // promise, which is none: one of these may change or go away in any release. They are
580            // measurements and debugging aids rather than things a build asks for, which is why
581            // none of them is in the usage text and all of them are in section 4.11 of
582            // `spec/04-driver-and-cli.md`.
583            "-Zverify-each" => opts.verify_each = true,
584            _ if arg.starts_with("-Zrule-coverage=") => {
585                let file = &arg["-Zrule-coverage=".len()..];
586                if file.is_empty() {
587                    return Err(err("-Zrule-coverage= needs a file to write to"));
588                }
589                opts.rule_coverage = Some(file.to_owned());
590            }
591            _ if arg.starts_with("-Z") => {
592                return Err(err(format!(
593                    "`{arg}` is not an unstable option this compiler has, see \
594                     spec/04-driver-and-cli.md section 4.11 for the ones it does"
595                )));
596            }
597            // The word size, which is a statement about the target and is taken as one. A build
598            // that says the size the target already has is saying nothing, and one that says the
599            // other size is asking for a target this compiler does not have, which it is told
600            // rather than being given the wrong one.
601            "-m64" | "-m32" | "-mx32" => {
602                let want: u32 = match arg {
603                    "-m64" => 64,
604                    _ => 32,
605                };
606                let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
607                if have != want {
608                    return Err(err(format!(
609                        "{arg} asks for a {want} bit target and {} is {have} bit, use \
610                         --target= to name the one you mean",
611                        opts.target
612                    )));
613                }
614            }
615            // Which processor in the family to generate for. This compiler emits the base
616            // instruction set of the architecture and nothing above it, so a program built with
617            // any of these runs on the machine that was named; it is a program that could have
618            // been faster rather than a program that is wrong, which is what makes these safe to
619            // take and ignore where a flag that changed the meaning of the code would not be.
620            _ if arg.starts_with("-march=")
621                || arg.starts_with("-mtune=")
622                || arg.starts_with("-mcpu=") => {}
623            // The calling convention, which is not safe to ignore. Taken when it names the one
624            // the target already uses and refused otherwise.
625            _ if arg.starts_with("-mabi=") => {
626                let want = &arg["-mabi=".len()..];
627                let have = match opts.target.arch {
628                    rucc_target::Arch::X86_64 => "sysv",
629                    rucc_target::Arch::Aarch64 => "lp64",
630                    rucc_target::Arch::Riscv64 => "lp64d",
631                };
632                if want != have {
633                    return Err(err(format!(
634                        "{arg}: {} uses the {have} convention and this compiler has no other",
635                        opts.target
636                    )));
637                }
638            }
639            // How far apart the pieces of the program may be. The small model is what we emit and
640            // it is every hosted program's default; the kernel model is a different one and a
641            // build that asks for it and does not get it links and then does not run.
642            "-mcmodel=small" => {}
643            _ if arg.starts_with("-mcmodel=") => {
644                return Err(err(format!(
645                    "{arg}: this compiler emits the small code model and no other, see \
646                     spec/12-targets.md"
647                )));
648            }
649            // GCC's own scripting language for how the driver builds a command line.
650            // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
651            // build reaching for it is told which flags do the same job.
652            _ if arg.starts_with("-specs=") => {
653                return Err(err(
654                    "-specs= is not supported: the parts of it builds rely on are -B, -L, \
655                     -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
656                     section 4.4",
657                ));
658            }
659            // Arguments meant for a separate assembler or preprocessor, which this compiler does
660            // not have: both are inside it and neither reads a command line. Refused rather than
661            // dropped, because every one of these says something about the output and a build
662            // that asked for `-Wa,--noexecstack` and was silently given an executable stack got
663            // the opposite of what it asked for.
664            _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
665                return Err(err(format!(
666                    "`{arg}` is an argument for a separate assembler or preprocessor, and both \
667                     are inside this compiler rather than programs it runs"
668                )));
669            }
670            "-Xassembler" | "-Xpreprocessor" => {
671                return Err(err(format!(
672                    "{arg} hands an argument to a separate assembler or preprocessor, and both \
673                     are inside this compiler rather than programs it runs"
674                )));
675            }
676            // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
677            // this one as a rule about build systems rather than about warnings: autoconf finds
678            // out whether a warning flag exists by passing it and looking at the exit status, so
679            // a compiler that refuses one it has not heard of fails a configure script written
680            // for a GCC newer than itself. The names are not checked against a list because this
681            // compiler has no warning groups for a list to be of, which #485 is about.
682            _ if arg.starts_with("-W") => {}
683            // Flags that name something this compiler does not do and would not do differently
684            // if it did. `-fno-ident` is about a comment in the output that we do not write
685            // either way, and the others are about a way of ordering the compilation that has
686            // been GCC's only way for twenty years. Section 4.1 asks for the list to be short
687            // and for adding to it to be deliberate, which is why it is written out here.
688            "-fno-ident"
689            | "-fident"
690            | "-funit-at-a-time"
691            | "-fno-unit-at-a-time"
692            | "-shared-libgcc"
693            | "-static-libgcc" => {}
694            _ if arg.starts_with('-') && arg.len() > 1 => {
695                // Silently ignoring an unknown flag is how a build ends up not doing what
696                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
697                // for the flags that change code generation, and the safe default until the
698                // flag table is populated is to reject everything we do not know.
699                return Err(err(format!("unknown option `{arg}`")));
700            }
701            _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
702        }
703    }
704
705    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
706    // order: a directory the user names outranks the compiler's own, and the compiler's own
707    // outranks the library's. It is pushed after the loop rather than before it because
708    // `SearchPath` appends within a group and the position is what the order is.
709    // The same directory the headers were looked for under, because a sysroot is a statement
710    // about a whole installation and not about half of one.
711    link.sysroot = sysroot.clone();
712    // After the loop rather than where `-pthread` was read, so that it lands after the objects
713    // that refer to it. A static link takes the definitions it needs from a library when it
714    // reaches it and not afterwards, so a library before the objects is a library that answers
715    // nothing.
716    if threads {
717        inputs.push(Input::library("pthread"));
718    }
719    if let Some(query) = query {
720        return Ok(Action::Print(answer(&query, &opts, &link)));
721    }
722    if !nostdinc {
723        opts.search.push_system(runtime::DIR);
724        // And the library's after ours, which is the other half of the same order. They go on
725        // here rather than at the point `--target=` or `--sysroot=` was read because either
726        // one changes the answer and the last word on both is the end of the loop.
727        for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
728            opts.search.push_system(dir);
729        }
730    }
731    // Once, here, rather than as each directory is pushed. A `-I` that names a system
732    // directory has to lose to the system entry and the system entry is added last, so the
733    // question cannot be answered until the whole path is known.
734    opts.search.remove_duplicates();
735
736    // The target has to be resolved before the configuration is printed, so this check comes
737    // after the loop rather than at the point `--print-config` was seen.
738    if print_config {
739        return Ok(Action::PrintConfig(Box::new(opts)));
740    }
741    if print_pipeline {
742        return Ok(Action::PrintPipeline(Box::new(opts)));
743    }
744    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
745    if print_plan {
746        return Ok(Action::PrintPlan {
747            opts: Box::new(opts),
748            plan: Box::new(plan),
749            link: Box::new(link),
750        });
751    }
752    Ok(Action::Compile {
753        opts: Box::new(opts),
754        plan: Box::new(plan),
755        link: Box::new(link),
756        jobs,
757        verbose,
758    })
759}
760
761/// What one of the `-dump` and `-print` flags prints.
762///
763/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
764/// which is what makes the answer safe to paste into a link line whether or not the file is
765/// there, and this does the same.
766fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
767    let found = |name: &str| {
768        link::find_in_search(link, opts.target, name)
769            .map_or_else(|| name.to_owned(), |path| path.display().to_string())
770    };
771    match query {
772        Query::Machine => opts.target.to_string(),
773        Query::Version => VERSION.to_owned(),
774        Query::Multiarch => link::multiarch(opts.target),
775        // The three lines GCC prints, in its order and with its punctuation, because what reads
776        // them is a script written against that shape. There is no installation directory to
777        // report: this compiler is one binary that works wherever it is copied, and the headers
778        // it ships are inside it, so `install` is where the binary is and nothing is under it.
779        Query::SearchDirs => {
780            let here = std::env::current_exe()
781                .ok()
782                .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
783                .unwrap_or_default();
784            let list = |dirs: &[PathBuf]| {
785                dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
786            };
787            let libraries = link::search_dirs(link, opts.target);
788            format!(
789                "install: {}\nprograms: ={}\nlibraries: ={}",
790                here.display(),
791                list(&link.prefixes),
792                list(&libraries)
793            )
794        }
795        Query::FileName(name) => found(name),
796        // The name GCC gives the library of routines a compiler's output calls that the C
797        // library does not have. Ours is built in and there is no file, so the answer is the
798        // name itself, which is what GCC prints when it cannot find one either.
799        Query::Libgcc => found("libgcc.a"),
800        // A program rather than a library: the linker and the archiver are the ones a build asks
801        // about, and this compiler finds them on the path or under `-B` rather than shipping
802        // them, so the name back is the honest answer unless a `-B` prefix holds one.
803        Query::ProgName(name) => link
804            .prefixes
805            .iter()
806            .map(|dir| dir.join(name))
807            .find(|path| path.is_file())
808            .map_or_else(|| name.clone(), |path| path.display().to_string()),
809    }
810}
811
812/// Renders the passes this level will run, in order, with what each one does.
813///
814/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
815/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
816/// emerges from which flags happen to be set, and this is how that list is read.
817#[must_use]
818pub fn print_pipeline(opts: &Options) -> String {
819    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
820    settings.toggles.clone_from(&opts.passes);
821    settings.global_fuel = opts.pass_fuel_global;
822    for (on, spec) in &opts.pass_gates {
823        // Every spelling was checked while the arguments were parsed, so there is nothing here
824        // this can refuse, and a listing is not the place to report it if there were.
825        let _ = settings.gates.add(*on, spec);
826    }
827    rucc_opt::pipeline::print(&settings)
828}
829
830/// Renders the resolved configuration.
831///
832/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
833/// this output is diffed across hosts in CI and a reordering would read as a change.
834#[must_use]
835pub fn print_config(opts: &Options) -> String {
836    let sess = Session::new(opts.clone());
837    let t = &sess.target;
838    let mut out = String::new();
839    let _ = writeln!(out, "version: {VERSION}");
840    // The three field triple the driver was given rather than the ten field tuple it widens to,
841    // because this output is what a build system reads to find out what it asked for. The tuple is
842    // the compiler's model of the machine and this line is a receipt for a command line.
843    let _ = writeln!(out, "target: {}", opts.target);
844    let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
845    let _ = writeln!(out, "os: {}", opts.target.os.as_str());
846    let _ = writeln!(out, "env: {}", opts.target.env.as_str());
847    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
848    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
849    let _ = writeln!(out, "long-width: {}", t.long_width);
850    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
851    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
852    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
853    let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
854    // The register file as a count per class, which is enough to tell a target whose registers
855    // are described from one whose are not without printing sixteen names nobody asked for.
856    let regs: Vec<String> = t
857        .regs
858        .classes()
859        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
860        .collect();
861    let _ = writeln!(
862        out,
863        "registers: {}",
864        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
865    );
866    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
867    let _ = writeln!(out, "safety: {}", sess.opts.safety);
868    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
869    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
870    let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
871    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
872    // Last because it is the one key with more than one line under it, and the only one
873    // whose value is a property of the machine rather than of the command line.
874    for dir in sess.opts.search.dirs() {
875        let system = if dir.is_system { " (system)" } else { "" };
876        let _ = writeln!(out, "include: {}{system}", dir.path.display());
877    }
878    out
879}
880
881/// Runs phase 4 over every input that has one, and writes what came out.
882///
883/// One input that fails does not stop the others. A build that reports every file it could
884/// not preprocess in one run is worth more than one that stops at the first, and the exit
885/// status is still a failure either way.
886fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
887    let fs = OsFileSystem::new();
888    let mut stderr = std::io::stderr().lock();
889    let mut failed = false;
890    for job in &plan.jobs {
891        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
892            // An input that is already preprocessed, or an object file. GCC passes these
893            // through untouched, and the plan has already said so in its notes.
894            continue;
895        }
896        let result = preprocess(opts, &job.input, &fs);
897        for message in &result.messages {
898            let _ = writeln!(stderr, "{message}");
899        }
900        if result.failed() {
901            failed = true;
902            continue;
903        }
904        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
905            let _ = writeln!(stderr, "rucc: error: {e}");
906            failed = true;
907        }
908    }
909    i32::from(failed)
910}
911
912/// Runs the front end over every input that has a compile phase, and writes what came out.
913///
914/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
915/// exit status is a failure either way. An input that is already assembly or an object has no
916/// compile phase and is passed over here, which the plan has already said in its notes.
917fn compile_all(opts: &Options, plan: &Plan) -> i32 {
918    let fs = OsFileSystem::new();
919    let mut stderr = std::io::stderr().lock();
920    let mut failed = false;
921    let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
922    failed |= !ok;
923    let mut fired = Fired::new();
924    for job in &plan.jobs {
925        if !job.phases.contains(&Phase::Compile) {
926            continue;
927        }
928        // An input of IR is read back rather than compiled, since the C it came from is not
929        // here any more. Everything after this is the same, so the two paths meet again at the
930        // messages and the file the result is written to.
931        let result = if job.kind == InputKind::Ir {
932            compile_ir(opts, &job.input, &fs)
933        } else {
934            compile(opts, &job.input, &fs)
935        };
936        fired.merge(&result.fired);
937        failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
938        failed |= !remarks.write(&result.remarks, &mut stderr);
939        for message in &result.messages {
940            let _ = writeln!(stderr, "{message}");
941        }
942        if result.failed() {
943            failed = true;
944            continue;
945        }
946        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
947            let _ = writeln!(stderr, "rucc: error: {e}");
948            failed = true;
949        }
950    }
951    failed |= !write_coverage(opts, &fired, &mut stderr);
952    i32::from(failed)
953}
954
955/// A directory for the object files only the link step ever sees, removed when it goes away.
956///
957/// `-c` writes its object where the user can see it and linking does not, which is the whole of
958/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
959/// every other compiler. Removing them on drop rather than at the end of a function is so that a
960/// link that failed leaves nothing behind either.
961struct Scratch {
962    /// Where the objects go.
963    dir: PathBuf,
964}
965
966impl Scratch {
967    /// Makes one, under whatever the platform calls its temporary directory.
968    ///
969    /// The name carries the process id so that two compilers running at once do not share a
970    /// directory, which they would otherwise do the moment two of them compiled a file of the
971    /// same name.
972    fn new() -> Result<Scratch, String> {
973        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
974        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
975        Ok(Scratch { dir })
976    }
977}
978
979impl Drop for Scratch {
980    fn drop(&mut self) {
981        let _ = std::fs::remove_dir_all(&self.dir);
982    }
983}
984
985/// The link line the plan describes, for `-###`.
986///
987/// The names in it are the hints the plan carries rather than the temporaries a real compilation
988/// would choose, because `-###` prints the line without having compiled anything and so has
989/// nothing to point at. That also makes the printed line readable rather than naming a directory
990/// that only exists while a compilation is running.
991fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
992    let linker = link::find(opts.target, link)?;
993    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
994    Ok(link::render(&linker, &args))
995}
996
997/// Compiles everything, then links it.
998///
999/// The objects go in a directory that is removed afterwards, which is why this is not
1000/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
1001/// and does not say where, because where is a question that only has an answer once something is
1002/// running.
1003fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1004    let Some(job) = &plan.link else {
1005        // Every path into here comes from a plan whose last phase is the link, and such a plan
1006        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
1007        let mut stderr = std::io::stderr().lock();
1008        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1009        return 1;
1010    };
1011    // Before anything is compiled, because a linker that is not on the machine is worth knowing
1012    // about in the second it takes to look rather than after the compilation.
1013    let linker = match link::find(opts.target, link) {
1014        Ok(linker) => linker,
1015        Err(why) => return complain(why),
1016    };
1017
1018    let scratch = match Scratch::new() {
1019        Ok(scratch) => scratch,
1020        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1021    };
1022
1023    let fs = OsFileSystem::new();
1024    let mut failed = false;
1025    // One per job, in job order, which is what lets the link line below be rebuilt with the real
1026    // paths in it: every job contributes exactly one file to the line and does so in this order.
1027    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1028    let mut fired = Fired::new();
1029    {
1030        let mut stderr = std::io::stderr().lock();
1031        let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1032        failed |= !ok;
1033        for (at, job) in plan.jobs.iter().enumerate() {
1034            let out = match &job.output {
1035                Output::Temporary(hint) => {
1036                    // The index because two inputs in different directories can have the same
1037                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
1038                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1039                }
1040                Output::File(path) => path.clone(),
1041                // A job feeding the linker never writes to standard output, since the plan gives
1042                // it a temporary. This is here so that the match is total rather than a panic.
1043                Output::Stdout => continue,
1044            };
1045            produced.push(out.clone());
1046            if !job.phases.contains(&Phase::Compile) {
1047                continue;
1048            }
1049            let result = if job.kind == InputKind::Ir {
1050                compile_ir(opts, &job.input, &fs)
1051            } else {
1052                compile(opts, &job.input, &fs)
1053            };
1054            fired.merge(&result.fired);
1055            failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1056            failed |= !remarks.write(&result.remarks, &mut stderr);
1057            for message in &result.messages {
1058                let _ = writeln!(stderr, "{message}");
1059            }
1060            if result.failed() {
1061                failed = true;
1062                continue;
1063            }
1064            if !matches!(result.artifact, Artifact::Object(_)) {
1065                // Worth saying rather than writing whatever it is and letting the linker read it.
1066                // An empty file is a valid empty linker script, so a link handed one gets as far
1067                // as reporting every symbol of this file undefined, which is a page of messages
1068                // about something that went wrong here.
1069                let _ = writeln!(
1070                    stderr,
1071                    "rucc: internal error: {}: no object file was produced for the link",
1072                    job.input
1073                );
1074                failed = true;
1075                continue;
1076            }
1077            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1078                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1079                failed = true;
1080            }
1081        }
1082        failed |= !write_coverage(opts, &fired, &mut stderr);
1083    }
1084    if failed {
1085        // Nothing is linked from a compilation that did not finish. A linker run over the objects
1086        // that did compile would report every function of the file that did not as undefined,
1087        // which is a page of messages about a mistake already reported once.
1088        return 1;
1089    }
1090
1091    // The items in command line order with the temporaries filled in. A library contributes no
1092    // job and passes through, and every file item takes the next job's real output, which is
1093    // what keeps a library that was written between two objects between them here.
1094    let mut outputs = produced.into_iter();
1095    let mut items = Vec::with_capacity(job.inputs.len());
1096    for item in &job.inputs {
1097        match item {
1098            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1099            link::Item::File(_) => match outputs.next() {
1100                Some(path) => items.push(link::Item::File(path)),
1101                None => return complain("the plan asks the linker for a file nothing produced"),
1102            },
1103        }
1104    }
1105
1106    let args = match link::line(opts.target, link, &items, &job.output) {
1107        Ok(args) => args,
1108        Err(why) => return complain(why),
1109    };
1110    if verbose {
1111        let mut stderr = std::io::stderr().lock();
1112        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1113    }
1114    match link::run(&linker, &args) {
1115        Ok(()) => 0,
1116        // The linker has already said what was wrong on its own error output, and repeating that
1117        // linking failed would only push its message further up the screen.
1118        Err(link::Error::Refused { .. }) => 1,
1119        Err(why) => complain(why),
1120    }
1121}
1122
1123/// Prints one driver level message and gives back the exit status that goes with it.
1124fn complain(why: impl std::fmt::Display) -> i32 {
1125    let mut stderr = std::io::stderr().lock();
1126    let _ = writeln!(stderr, "rucc: error: {why}");
1127    1
1128}
1129
1130/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
1131///
1132/// Once for the whole command line rather than once per input, because the question is which
1133/// lowering rules this run of the compiler reached and a file per input would leave the reader
1134/// unioning files to find out something one process already knew.
1135///
1136/// A file that could not be written is a failure and not a warning. What asks for this is a
1137/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
1138fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1139    let Some(path) = &opts.rule_coverage else { return true };
1140    let Some(table) = coverage::table(opts.target.arch) else {
1141        let _ = writeln!(
1142            stderr,
1143            "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1144             to report",
1145            opts.target
1146        );
1147        return false;
1148    };
1149    match std::fs::write(path, fired.listing(table)) {
1150        Ok(()) => true,
1151        Err(e) => {
1152            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1153            false
1154        }
1155    }
1156}
1157
1158/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
1159///
1160/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
1161/// A file rather than the diagnostic stream is what a harness wants: the corpus in
1162/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
1163/// a few thousand remarks mixed into that would bury it.
1164struct Remarks {
1165    /// The file, if there is one.
1166    file: Option<String>,
1167    /// Whether anything has been written to it yet, which decides between truncating and
1168    /// appending. One file holds the whole run rather than the last input in it.
1169    started: bool,
1170}
1171
1172impl Remarks {
1173    /// Prepares the destination, emptying the file if there is one.
1174    ///
1175    /// Emptied here rather than at the first remark, because a run where no pass had anything to
1176    /// say should leave an empty file and not yesterday's. An absent file and an empty one are
1177    /// different facts and something reading this will act on the difference.
1178    fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1179        let mut ok = true;
1180        if let Some(path) = file {
1181            if let Err(e) = std::fs::write(path, "") {
1182                let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1183                ok = false;
1184            }
1185        }
1186        (Self { file: file.cloned(), started: false }, ok)
1187    }
1188
1189    /// Writes one input's remarks, and says whether that worked.
1190    ///
1191    /// A file that cannot be written is a failure and not a warning, for the reason
1192    /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
1193    /// where nothing happened.
1194    fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1195        if text.is_empty() {
1196            return true;
1197        }
1198        let Some(path) = &self.file else {
1199            let _ = write!(stderr, "{text}");
1200            return true;
1201        };
1202        let opened = std::fs::OpenOptions::new()
1203            .write(true)
1204            .append(self.started)
1205            .truncate(!self.started)
1206            .create(true)
1207            .open(path);
1208        self.started = true;
1209        let result =
1210            opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1211        if let Err(e) = result {
1212            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1213            return false;
1214        }
1215        true
1216    }
1217}
1218
1219/// Writes what `-fdump-ir=` asked to see, one file per dump.
1220///
1221/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
1222/// after a run is the passes in the order they ran, per input. They go in the working directory
1223/// rather than beside the output, because a dump is something a person asked for at a prompt and
1224/// the working directory is where that person is.
1225///
1226/// A file that could not be written is a failure and not a warning, for the reason
1227/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
1228/// quietly did not happen looks exactly like a pass that did not run.
1229fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1230    let stem = std::path::Path::new(input)
1231        .file_name()
1232        .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1233    let mut ok = true;
1234    for dump in dumps {
1235        let path = format!("{stem}.{}.ir", dump.name);
1236        if let Err(e) = std::fs::write(&path, &dump.text) {
1237            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1238            ok = false;
1239        }
1240    }
1241    ok
1242}
1243
1244/// Writes one job's result where the plan said it goes.
1245///
1246/// # Errors
1247///
1248/// Returns the message to print, which names the file when there is one, because "permission
1249/// denied" on its own does not say which file was refused.
1250fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1251    match output {
1252        Output::Stdout => {
1253            let mut stdout = std::io::stdout().lock();
1254            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1255        }
1256        Output::File(path) | Output::Temporary(path) => {
1257            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1258        }
1259    }
1260}
1261
1262/// Runs the driver and returns the process exit code.
1263///
1264/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
1265/// is the one place in the compiler that is true.
1266pub fn run(args: &[String]) -> i32 {
1267    match parse_args(args) {
1268        Ok(Action::Help) => {
1269            print!("{USAGE}");
1270            0
1271        }
1272        Ok(Action::Version) => {
1273            println!("rucc {VERSION}");
1274            0
1275        }
1276        Ok(Action::Print(line)) => {
1277            println!("{line}");
1278            0
1279        }
1280        Ok(Action::PrintConfig(opts)) => {
1281            print!("{}", print_config(&opts));
1282            0
1283        }
1284        Ok(Action::PrintPipeline(opts)) => {
1285            print!("{}", print_pipeline(&opts));
1286            0
1287        }
1288        Ok(Action::PrintPlan { opts, plan, link }) => {
1289            print!("{}", plan.render());
1290            // The line as it would be typed, which is the half of `-###` that section 4.3 says
1291            // arrives with the link. It is printed even when the linker is not on this machine,
1292            // because what a build wants from `-###` is what the compiler would do.
1293            if let Some(job) = &plan.link {
1294                match link_line(&opts, &link, job) {
1295                    Ok(line) => println!("{line}"),
1296                    Err(why) => {
1297                        let mut stderr = std::io::stderr().lock();
1298                        let _ = writeln!(stderr, "rucc: error: {why}");
1299                        return 1;
1300                    }
1301                }
1302            }
1303            0
1304        }
1305        Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1306            {
1307                let mut stderr = std::io::stderr().lock();
1308                if verbose {
1309                    let _ = write!(stderr, "{}", plan.render());
1310                    let _ = writeln!(stderr, "workers: {}", jobs.count());
1311                }
1312            }
1313            if opts.emit == EmitKind::Preprocessed {
1314                return preprocess_all(&opts, &plan);
1315            }
1316            if opts.emit != EmitKind::Executable {
1317                return compile_all(&opts, &plan);
1318            }
1319            link_all(&opts, &plan, &link, verbose)
1320        }
1321        Err(e) => {
1322            let mut stderr = std::io::stderr().lock();
1323            let _ = writeln!(stderr, "rucc: error: {e}");
1324            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1325            1
1326        }
1327    }
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332    use rucc_session::{GnucVersion, OptLevel};
1333
1334    use super::*;
1335
1336    fn args(s: &[&str]) -> Vec<String> {
1337        s.iter().map(|x| (*x).to_owned()).collect()
1338    }
1339
1340    #[test]
1341    fn help_and_version_win_over_everything_else() {
1342        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1343        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1344    }
1345
1346    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1347        match parse_args(&args(s)).expect("expected a compilation") {
1348            Action::Compile { opts, plan, .. } => (opts, plan),
1349            other => panic!("expected a compilation, got {other:?}"),
1350        }
1351    }
1352
1353    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1354        match parse_args(&args(s)).expect("expected a compilation") {
1355            Action::Compile { link, plan, .. } => (link, plan),
1356            other => panic!("expected a compilation, got {other:?}"),
1357        }
1358    }
1359
1360    #[test]
1361    fn collects_inputs_and_flags() {
1362        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1363        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1364        assert_eq!(paths, vec!["a.c", "b.c"]);
1365        assert_eq!(opts.opt_level, OptLevel::O2);
1366        assert_eq!(opts.emit, EmitKind::Object);
1367        assert!(opts.debug_info);
1368    }
1369
1370    /// The unstable options, which are spelled apart from everything else on purpose: what is
1371    /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
1372    #[test]
1373    fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1374        let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1375        assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1376
1377        let (plain, _) = compile(&["-c", "a.c"]);
1378        assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1379
1380        assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1381        let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1382        assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1383    }
1384
1385    #[test]
1386    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1387        let (opts, _) = compile(&["-O", "a.c"]);
1388        assert_eq!(opts.opt_level, OptLevel::O1);
1389    }
1390
1391    #[test]
1392    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1393        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1394        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1395        assert_eq!(plan.jobs[1].kind, InputKind::C);
1396        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1397    }
1398
1399    #[test]
1400    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1401        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1402            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1403            other => panic!("expected a compilation, got {other:?}"),
1404        };
1405        assert_eq!(jobs.count(), 4);
1406
1407        let default = match parse_args(&args(&["a.c"])).unwrap() {
1408            Action::Compile { jobs, .. } => jobs,
1409            other => panic!("expected a compilation, got {other:?}"),
1410        };
1411        assert_eq!(default, Jobs::available());
1412        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1413    }
1414
1415    #[test]
1416    fn triple_hash_prints_the_plan_and_runs_nothing() {
1417        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1418        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1419        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1420    }
1421
1422    #[test]
1423    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1424        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1425        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1426    }
1427
1428    #[test]
1429    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1430        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1431        assert!(e.message.contains("unknown option"), "{}", e.message);
1432    }
1433
1434    /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
1435    /// one directory needs the older rules and the rest of the tree does not.
1436    #[test]
1437    fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1438        let (opts, _) = compile(&["-c", "a.c"]);
1439        assert!(!opts.permissive, "off unless it is asked for");
1440
1441        let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1442        assert!(opts.permissive);
1443
1444        let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1445        assert!(!opts.permissive);
1446    }
1447
1448    #[test]
1449    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1450        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1451        assert!(e.message.contains("trampoline"), "{}", e.message);
1452        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1453    }
1454
1455    #[test]
1456    fn an_unsupported_target_names_itself() {
1457        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1458        assert!(e.message.contains("sparc64"), "{}", e.message);
1459    }
1460
1461    #[test]
1462    fn no_inputs_is_an_error_but_print_config_needs_none() {
1463        assert!(parse_args(&args(&[])).is_err());
1464        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1465    }
1466
1467    #[test]
1468    fn print_config_reports_the_target_it_was_given_not_the_host() {
1469        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1470        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1471        let text = print_config(&opts);
1472        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1473        assert!(text.contains("char-signed: false"), "{text}");
1474        assert!(text.contains("object-format: elf"), "{text}");
1475        assert!(text.contains("va-list: void-pointer"), "{text}");
1476        // RISC-V has a register file and this compiler has not written it down yet, and the
1477        // dump says which of those two it is rather than leaving the line out.
1478        assert!(text.contains("registers: none"), "{text}");
1479    }
1480
1481    #[test]
1482    fn print_config_has_one_key_per_line_and_a_fixed_order() {
1483        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1484        let text = print_config(&opts);
1485        let keys: Vec<&str> =
1486            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1487        assert_eq!(keys[0], "version");
1488        assert_eq!(keys[1], "target");
1489        assert_eq!(keys.len(), 19);
1490        assert!(text.ends_with('\n'));
1491    }
1492
1493    #[test]
1494    fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
1495        let (opts, _) = compile(&["a.c"]);
1496        assert_eq!(opts.safety, rucc_session::Safety::Off);
1497
1498        for (flag, tier) in [
1499            ("-fsafety=detect", rucc_session::Safety::Detect),
1500            ("-fsafety=enforce", rucc_session::Safety::Enforce),
1501            ("-fsafety=kernel", rucc_session::Safety::Kernel),
1502            ("-fsafety=off", rucc_session::Safety::Off),
1503        ] {
1504            let (opts, _) = compile(&[flag, "a.c"]);
1505            assert_eq!(opts.safety, tier, "{flag}");
1506        }
1507
1508        // The last one wins, the way every other repeated flag on this command line does.
1509        let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
1510        assert_eq!(opts.safety, rucc_session::Safety::Off);
1511
1512        // A misspelled tier is refused rather than ignored. Silently compiling without the
1513        // monitor a build asked for is the one failure mode this feature cannot have.
1514        let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
1515        assert!(e.message.contains("is not a safety tier"), "{}", e.message);
1516        assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
1517    }
1518
1519    #[test]
1520    fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
1521        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1522        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1523        let text = print_pipeline(&opts);
1524        assert!(text.starts_with("level: -O2\n"), "{text}");
1525        assert!(text.contains("fold"), "{text}");
1526
1527        let a = parse_args(&args(&["--print-pipeline"])).unwrap();
1528        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1529        // One pass runs at `-O0` and it is the one that removes code nothing reaches, which is
1530        // not an optimization. See issue 359.
1531        assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
1532
1533        let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
1534        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1535        // And with that one turned off there is nothing left, which the dump says rather than
1536        // printing an empty list.
1537        assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1538    }
1539
1540    #[test]
1541    fn print_pipeline_takes_the_toggles_into_account() {
1542        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
1543        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1544        let text = print_pipeline(&opts);
1545        // The one that was named is gone and the rest of the level is not, which is the whole
1546        // of what a toggle promises.
1547        assert!(!text.contains("fold"), "{text}");
1548        assert!(text.contains("dce"), "{text}");
1549
1550        // Every pass the compiler has, named off. Built from the registry rather than written
1551        // out, so a pass added later is turned off here too and this keeps testing the thing it
1552        // is about, which is that the toggles can empty a level.
1553        let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
1554        off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
1555        let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
1556        let a = parse_args(&args(&spelled)).unwrap();
1557        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1558        assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1559    }
1560
1561    #[test]
1562    fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
1563        let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1564        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1565        assert!(!print_pipeline(&opts).contains("global fuel"));
1566
1567        let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
1568        let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1569        let text = print_pipeline(&opts);
1570        // Because the listing is the answer to what this compilation will do, and a run that
1571        // stops after four rewrites is not doing what the level says it does.
1572        assert!(text.contains("global fuel: 4"), "{text}");
1573    }
1574
1575    /// A pass is turned on and off by its own name, and the order the flags were given in is
1576    /// kept, because the last spelling of a name is the one that decides.
1577    #[test]
1578    fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
1579        let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
1580        assert_eq!(
1581            opts.passes,
1582            [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
1583        );
1584
1585        let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
1586        assert!(e.message.contains("unknown option"), "{}", e.message);
1587    }
1588
1589    #[test]
1590    fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
1591        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
1592        assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
1593
1594        let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
1595        assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
1596        let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
1597        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
1598        let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
1599        assert!(e.message.contains("not a number"), "{}", e.message);
1600    }
1601
1602    #[test]
1603    fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
1604        let (opts, _) = compile(&["-c", "-O2", "a.c"]);
1605        assert_eq!(opts.pass_fuel_global, None);
1606
1607        let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
1608        assert_eq!(opts.pass_fuel_global, Some(12));
1609        // And it is not the per pass flag with a longer name, so neither spelling swallows the
1610        // other.
1611        assert!(opts.pass_fuel.is_empty());
1612
1613        let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
1614        assert!(e.message.contains("not a number"), "{}", e.message);
1615    }
1616
1617    #[test]
1618    fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
1619        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
1620        assert_eq!(
1621            opts.pass_gates,
1622            [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
1623            "the order is what decides, so it has to survive the parse"
1624        );
1625
1626        let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
1627        assert!(e.message.contains("--print-pipeline"), "{}", e.message);
1628        let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
1629        assert!(e.message.contains("ends before it starts"), "{}", e.message);
1630        let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
1631        assert!(e.message.contains("is empty"), "{}", e.message);
1632    }
1633
1634    #[test]
1635    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
1636        let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
1637        let text = print_pipeline(&opts);
1638        assert!(text.contains("fold, "), "{text}");
1639        assert!(text.contains("[off for main]"), "{text}");
1640    }
1641
1642    /// The spelling is checked while the arguments are read, because a dump that names a pass
1643    /// this compiler does not have is a typo, and a typo found after the compilation has run is
1644    /// found too late to be any use.
1645    #[test]
1646    fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
1647        let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
1648        assert_eq!(opts.dump_ir, ["all", "after-fold"]);
1649
1650        let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
1651        assert!(e.message.contains("nosuch"), "{}", e.message);
1652        assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
1653    }
1654
1655    /// Every spelling `-fopt-info` takes, and the one it does not.
1656    ///
1657    /// The keywords are checked here for the same reason a dump's pass name is: a person who
1658    /// misspelled one gets no output, and no output is also what a compilation where nothing
1659    /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
1660    #[test]
1661    fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
1662        let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
1663        assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
1664        assert_eq!(opts.opt_info_file, None, "and goes to standard error");
1665
1666        let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
1667        assert_eq!(opts.opt_info, ["missed-note"]);
1668
1669        // Two flags add up rather than the second replacing the first, and the file is the last
1670        // one that named a file, which is how GCC treats both.
1671        let (opts, _) =
1672            compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
1673        assert_eq!(opts.opt_info, ["missed", "all"]);
1674        assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
1675
1676        let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
1677        assert!(e.message.contains("vectorized"), "{}", e.message);
1678        assert!(e.message.contains("`missed`"), "{}", e.message);
1679        let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
1680        assert!(e.message.contains("no file"), "{}", e.message);
1681    }
1682
1683    #[test]
1684    fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
1685        let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
1686        assert!(opts.verify_each);
1687        assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
1688    }
1689
1690    #[test]
1691    fn dash_o_needs_an_argument() {
1692        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
1693        assert_eq!(e.message, "-o requires an argument");
1694    }
1695
1696    #[test]
1697    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
1698        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
1699        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
1700        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
1701    }
1702
1703    #[test]
1704    fn the_include_flags_land_on_the_chain_each_one_names() {
1705        // A sysroot with nothing under it, so that the library's own directories are the
1706        // same on every machine this test runs on, which is none of them.
1707        let (opts, _) = compile(&[
1708            "-Ii",
1709            "-iquote",
1710            "q",
1711            "-isystem",
1712            "sys",
1713            "-idirafter",
1714            "after",
1715            "--sysroot=/nowhere-at-all",
1716            "a.c",
1717        ]);
1718        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1719        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
1720        // which is where GCC puts its own: a directory the user named outranks ours.
1721        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
1722        assert!(!opts.search.dirs()[1].is_system);
1723        assert!(opts.search.dirs()[2].is_system);
1724    }
1725
1726    #[test]
1727    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
1728        // Which machine this runs on decides what is on the path, so the test is about the
1729        // order rather than about the names: ours is on it, the library's follow it, and
1730        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
1731        let (opts, _) = compile(&["a.c"]);
1732        let dirs = opts.search.dirs();
1733        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
1734        assert_eq!(ours, Some(0), "{dirs:?}");
1735        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
1736        let (bare, _) = compile(&["-nostdinc", "a.c"]);
1737        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
1738    }
1739
1740    #[test]
1741    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
1742        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
1743        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1744        assert_eq!(dirs, ["sys", runtime::DIR]);
1745    }
1746
1747    #[test]
1748    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
1749        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
1750        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1751        assert_eq!(dirs, ["i"]);
1752    }
1753
1754    #[test]
1755    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
1756        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
1757        assert_eq!(opts.std, Std::C11);
1758        assert!(opts.gnu_extensions);
1759
1760        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
1761        assert_eq!(opts.std, Std::C99);
1762        assert!(!opts.gnu_extensions);
1763
1764        let (opts, _) = compile(&["-ansi", "a.c"]);
1765        assert_eq!(opts.std, Std::C89);
1766        assert!(!opts.gnu_extensions);
1767
1768        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
1769        assert!(e.message.contains("unknown dialect"), "{}", e.message);
1770    }
1771
1772    #[test]
1773    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
1774        let (opts, _) = compile(&["-dM", "a.c"]);
1775        assert!(opts.dumps.macros);
1776
1777        // Packed, the way GCC takes them, and a letter in the family we have not written yet
1778        // is accepted and does nothing rather than failing a build.
1779        let (opts, _) = compile(&["-dDM", "a.c"]);
1780        assert!(opts.dumps.macros);
1781        let (opts, _) = compile(&["-dD", "a.c"]);
1782        assert!(!opts.dumps.macros);
1783
1784        let (opts, _) = compile(&["a.c"]);
1785        assert!(!opts.dumps.any());
1786
1787        // `-dumpversion` is a different flag that happens to start the same way, and it is read
1788        // as itself rather than as a dump of nothing.
1789        assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
1790    }
1791
1792    #[test]
1793    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
1794        let (opts, _) = compile(&["a.c"]);
1795        assert_eq!(
1796            opts.gnuc,
1797            GnucVersion { major: 7, minor: 0, patch: 0 },
1798            "the lowest claim a modern glibc gives its own declarations to"
1799        );
1800
1801        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
1802        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
1803
1804        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
1805        // patchlevel and a harness that pastes that back has to be understood.
1806        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
1807        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
1808
1809        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
1810        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
1811
1812        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
1813        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
1814
1815        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
1816        assert!(e.message.contains("more than three"), "{}", e.message);
1817    }
1818
1819    #[test]
1820    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
1821        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
1822        assert!(opts.pedantic);
1823        assert_eq!(opts.std, Std::C17);
1824
1825        // The `-W` family's name for it, which is what a build that groups its warning flags
1826        // tends to write.
1827        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
1828        assert!(opts.pedantic);
1829
1830        let (opts, _) = compile(&["-std=c17", "a.c"]);
1831        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
1832    }
1833
1834    #[test]
1835    fn dash_p_and_dash_ffreestanding_reach_the_options() {
1836        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
1837        assert!(!opts.line_markers);
1838        assert!(!opts.hosted);
1839        assert_eq!(opts.emit, EmitKind::Preprocessed);
1840    }
1841
1842    /// The two ways a build says it means its own function by a name the C library also has.
1843    ///
1844    /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
1845    /// build writes when it means its own `memcpy` and the library's everything else. The name is
1846    /// kept as it was written and not checked against anything, because a program is allowed to
1847    /// mean something by a name this compiler has never heard of.
1848    #[test]
1849    fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
1850        let (opts, _) = compile(&["-c", "a.c"]);
1851        assert!(opts.builtins, "a library name means the library function by default");
1852        assert!(opts.no_builtin.is_empty());
1853
1854        let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
1855        assert!(!opts.builtins);
1856
1857        let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
1858        assert!(opts.builtins, "the last mention decides");
1859
1860        let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
1861        assert!(opts.builtins, "one name is not the family");
1862        assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
1863    }
1864
1865    /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
1866    /// line, since the dialect asks for GNU's reading further in rather than through this.
1867    #[test]
1868    fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
1869        let (opts, _) = compile(&["-c", "a.c"]);
1870        assert!(!opts.gnu89_inline, "C's reading of inline by default");
1871
1872        let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
1873        assert!(opts.gnu89_inline);
1874
1875        let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
1876        assert!(!opts.gnu89_inline, "the last mention decides");
1877
1878        // The C89 dialects are under GNU's reading whether this was written or not, so the flag
1879        // stays off there and the dialect is what the checker and the macro set both ask. That is
1880        // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
1881        // dialect already has. gcc refuses that command line, which is measured in the issue.
1882        let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
1883        assert!(!opts.gnu89_inline);
1884    }
1885
1886    /// Both spellings of both frame flags, since a build that wants one usually writes the
1887    /// other beside it for the one file that has to be compiled the ordinary way.
1888    #[test]
1889    fn the_two_frame_flags_are_read_in_both_directions() {
1890        let (opts, _) = compile(&["-c", "a.c"]);
1891        assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
1892        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
1893
1894        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
1895        assert!(opts.frame_pointer);
1896        assert!(!opts.red_zone);
1897
1898        let (opts, _) = compile(&[
1899            "-c",
1900            "-fno-omit-frame-pointer",
1901            "-fomit-frame-pointer",
1902            "-mno-red-zone",
1903            "-mred-zone",
1904            "a.c",
1905        ]);
1906        assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
1907        assert!(opts.red_zone);
1908    }
1909
1910    #[test]
1911    fn the_link_flags_are_collected_apart_from_the_compilation() {
1912        let (link, _) = linking(&[
1913            "-static",
1914            "-nostartfiles",
1915            "-rdynamic",
1916            "-s",
1917            "-fuse-ld=mold",
1918            "-L/opt/lib",
1919            "-B",
1920            "/opt/tools",
1921            "a.c",
1922        ]);
1923        assert!(link.is_static);
1924        assert!(link.no_startfiles);
1925        assert!(link.export_dynamic);
1926        assert!(link.strip);
1927        assert_eq!(link.use_ld.as_deref(), Some("mold"));
1928        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
1929        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
1930    }
1931
1932    #[test]
1933    fn a_comma_in_dash_wl_separates_two_arguments() {
1934        let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
1935        assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
1936    }
1937
1938    #[test]
1939    fn a_library_keeps_its_place_between_the_objects() {
1940        // Link order is semantic: `-lm` written between two files resolves for the one before
1941        // it and not for the one after, so a library cannot be collected into a list of its own.
1942        // The target is named because the suffix of an object is the target's and this asserts
1943        // on the names: the same command line on a Windows host plans two `.obj` files.
1944        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
1945        let link = plan.link.expect("expected a link step");
1946        assert_eq!(
1947            link.inputs,
1948            vec![
1949                link::Item::File("a.o".into()),
1950                link::Item::Library("m".into()),
1951                link::Item::File("b.o".into()),
1952            ]
1953        );
1954        // And it is not a job, because there is nothing to compile in a library.
1955        assert_eq!(plan.jobs.len(), 2);
1956    }
1957
1958    #[test]
1959    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1960        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
1961        assert!(plan.link.is_none());
1962        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
1963    }
1964
1965    #[test]
1966    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
1967        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
1968        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
1969    }
1970
1971    fn printed(s: &[&str]) -> String {
1972        match parse_args(&args(s)).expect("expected an answer") {
1973            Action::Print(line) => line,
1974            other => panic!("expected an answer, got {other:?}"),
1975        }
1976    }
1977
1978    fn refused(s: &[&str]) -> String {
1979        parse_args(&args(s)).expect_err("expected a refusal").message
1980    }
1981
1982    #[test]
1983    fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
1984        // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
1985        // out whether a warning flag exists by passing it and looking at the exit status, so a
1986        // compiler that refuses one it does not know fails a script written for a newer GCC.
1987        let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
1988        assert!(!opts.warnings_are_errors);
1989        assert!(opts.warnings);
1990        // The two spellings that do mean something are still read.
1991        let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
1992        assert!(opts.warnings_are_errors);
1993        let (opts, _) = compile(&["-w", "-c", "a.c"]);
1994        assert!(!opts.warnings);
1995        let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
1996        assert!(opts.pedantic && opts.warnings_are_errors);
1997    }
1998
1999    #[test]
2000    fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2001        // Every one of these says something about the output, so the wrong answer is silence.
2002        assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2003        assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2004        assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2005        assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2006        assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2007        assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2008        // The word size the target does not have, which is a target this compiler was not asked
2009        // for rather than a flag it does not know.
2010        let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2011        assert!(no32.contains("32 bit target"), "{no32}");
2012    }
2013
2014    #[test]
2015    fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2016        assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2017        assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2018        assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2019    }
2020
2021    #[test]
2022    fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2023        let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2024        let (opts, _) =
2025            compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2026        assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2027        let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2028        assert!(wrong.contains("sysv convention"), "{wrong}");
2029    }
2030
2031    #[test]
2032    fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2033        let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2034        assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2035        // After the input, because a static link takes what it needs from a library when it
2036        // reaches it and not afterwards.
2037        let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2038        assert_eq!(names, vec!["a.c"]);
2039    }
2040
2041    #[test]
2042    fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2043        let target = "--target=x86_64-unknown-linux-gnu";
2044        assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2045        assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2046        assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2047        assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2048        // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
2049        // answer safe to paste into a link line whether or not the file is there.
2050        assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2051        assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2052        let dirs = printed(&[target, "-print-search-dirs"]);
2053        assert!(dirs.starts_with("install: "), "{dirs}");
2054        assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2055    }
2056
2057    #[test]
2058    fn usage_fits_on_a_screen() {
2059        // Not a style preference. A help text that scrolls is one nobody reads, and this is
2060        // the cheapest way to keep it honest as flags accumulate. The number goes up only when
2061        // a family of flags arrives that has nowhere to share a line, which the two pass gates
2062        // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
2063        // the lines that family took. The four it went up by last are the flags a build system
2064        // passes without being asked to: how much to say, what machine to generate for, threads,
2065        // and the questions `configure` asks before it compiles anything. The one it went up by
2066        // last is the second line of `--emit`, whose kinds are a family that has now outgrown
2067        // one line and has nowhere else to go.
2068        assert!(USAGE.lines().count() < 42, "usage text has grown past one screen");
2069    }
2070}