Skip to main content

rucc_driver/
lib.rs

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