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 12, see `spec/18-package-layout.md`.
5//!
6//! This is the only crate that is allowed to know the process exists. It reads the command
7//! line, touches the file system, spawns the linker and writes to the terminal, and it hands
8//! everything below it a [`Session`]. The binary crate is a `main` that calls
9//! [`run`] and nothing else, so that the whole driver is reachable from a test.
10//!
11//! # Status
12//!
13//! `--help`, `--version` and `--print-config` are real, which is the `M0` exit criterion in
14//! `spec/17-milestones.md`. The phase graph is real and `-###` prints it, and the scheduler
15//! that will run it is real and tested.
16//!
17//! Two phases run. `-E` reads the file, runs phase 4 over it and writes the result, to `-o` or
18//! to standard output. `--emit=tast` carries on through phase 7, the parse and the checking,
19//! and writes the typed tree. The flags those two read are real with them, which is `-D`, `-U`,
20//! `-I`, `-iquote`, `-isystem`, `-idirafter`, `--sysroot=`, `-isysroot`, `-P`, `-std=`,
21//! `-fgnuc-version=`, `-ansi`, `-ffreestanding`, `-pedantic` and `-Werror`.
22//! The phases after them still say they are not implemented.
23//!
24//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
25//! explicitly unstable and will change without a major version bump.
26
27#![doc(html_root_url = "https://docs.rs/rucc-driver/0.3.14")]
28
29pub mod compile;
30pub mod library;
31pub mod link;
32mod map;
33pub mod phase;
34pub mod preprocess;
35pub mod schedule;
36
37use std::fmt::Write as _;
38use std::io::Write as _;
39use std::path::PathBuf;
40
41use rucc_codegen::coverage::{self, Fired};
42use rucc_session::{Dumps, EmitKind, Options, Session, Std, runtime};
43use rucc_target::Triple;
44
45use crate::link::LinkOptions;
46
47pub use crate::compile::{Artifact, Compiled, compile, compile_ir};
48pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
49pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
50pub use crate::schedule::Jobs;
51
52/// The compiler's version, taken from the workspace manifest.
53pub const VERSION: &str = env!("CARGO_PKG_VERSION");
54
55/// What the command line asked for.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum Action {
58    /// Print usage and exit successfully.
59    Help,
60    /// Print the version and exit successfully.
61    Version,
62    /// Print the resolved configuration and exit successfully.
63    PrintConfig(Box<Options>),
64    /// Print the phase plan and the link line and exit successfully, which is `-###`.
65    PrintPlan {
66        /// The resolved options, which is what says what the link line is for.
67        opts: Box<Options>,
68        /// What to do to each input, and in what order.
69        plan: Box<Plan>,
70        /// What the command line said about linking.
71        link: Box<LinkOptions>,
72    },
73    /// Compile the given inputs.
74    Compile {
75        /// The resolved options.
76        opts: Box<Options>,
77        /// What to do to each input, and in what order.
78        plan: Box<Plan>,
79        /// What the command line said about linking.
80        link: Box<LinkOptions>,
81        /// How many translation units to compile at once.
82        jobs: Jobs,
83        /// Whether `-v` asked for the plan to be printed while it runs.
84        verbose: bool,
85    },
86}
87
88/// Why a command line was rejected.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct CliError {
91    /// The message, lowercase and without a trailing period, in the same shape as any other
92    /// diagnostic.
93    pub message: String,
94}
95
96impl std::fmt::Display for CliError {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.write_str(&self.message)
99    }
100}
101
102impl std::error::Error for CliError {}
103
104fn err(message: impl Into<String>) -> CliError {
105    CliError { message: message.into() }
106}
107
108/// Usage text.
109///
110/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
111/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
112pub const USAGE: &str = "\
113rucc, an optimizing C compiler
114
115usage: rucc [options] file...
116
117options:
118  -c                     compile and assemble, do not link
119  -S                     compile only, emit assembly
120  -E                     preprocess only
121  -o <file>              write output to <file>, or to standard output for -
122  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
123  -I <dir>               add <dir> to the include search path
124  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
125  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
126  -P, -dM                with -E: leave out the markers, or dump the macros
127  -std=<dialect>         c89 through c23, and the gnu spellings
128  -fgnuc-version=<v>     the GCC release to claim, default 7.0.0
129  -x <lang>              treat later inputs as <lang>, or none to stop
130  -O<level>              optimize: 0, 1, 2, 3, s, z
131  -g, -fno-omit-frame-pointer, -mno-red-zone   debug info, keep a frame pointer, no red zone
132  -l<name>, -L <dir>, -B <dir>   link a library, where to look for one, where our own tools are
133  -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s   how to link
134  -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name>   hand an argument to the linker, or pick one
135  -Werror -pedantic      warnings are errors, diagnose what the standard forbids
136  -j[n]                  compile n translation units at once, default all
137  -v, -###               print each phase as it runs, or without running any
138  --target=<triple>      generate code for <triple>
139  --emit=<kind>          exe, obj, asm, preprocessed, tast, ir, mir-final
140  --print-config         print the resolved configuration and exit
141  --version              print the version and exit
142  -h, --help             print this message and exit
143
144See spec/04-driver-and-cli.md for the full flag reference.
145";
146
147/// The argument of a flag that may be joined to it or may be the next word.
148///
149/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
150fn joined_or_next(
151    arg: &str,
152    at: usize,
153    args: &[String],
154    i: &mut usize,
155) -> Result<String, CliError> {
156    if arg.len() > at {
157        return Ok(arg[at..].to_owned());
158    }
159    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
160    *i += 1;
161    Ok(next.clone())
162}
163
164/// Parses a command line, without the program name.
165///
166/// # Errors
167///
168/// Returns the message to print when the arguments do not name a compilation this compiler
169/// can attempt.
170pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
171    let host = Triple::host()
172        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
173    let mut opts = Options::new(host);
174    let mut inputs: Vec<Input> = Vec::new();
175    let mut print_config = false;
176    let mut print_plan = false;
177    let mut verbose = false;
178    let mut jobs = Jobs::default();
179    let mut nostdinc = false;
180    let mut sysroot: Option<PathBuf> = None;
181    let mut output = None;
182    let mut link = LinkOptions::default();
183    // `-x` applies to inputs that come after it and stays in effect until the next one, which
184    // is why it is tracked across the loop rather than attached to a single argument.
185    let mut forced: Option<InputKind> = None;
186
187    let mut i = 0;
188    while i < args.len() {
189        let arg = args[i].as_str();
190        i += 1;
191        match arg {
192            "-h" | "--help" => return Ok(Action::Help),
193            "--version" => return Ok(Action::Version),
194            "--print-config" => print_config = true,
195            "-###" => print_plan = true,
196            "-v" => verbose = true,
197            "-c" => opts.emit = EmitKind::Object,
198            "-S" => opts.emit = EmitKind::Asm,
199            "-E" => opts.emit = EmitKind::Preprocessed,
200            "-g" => opts.debug_info = true,
201            "-Werror" => opts.warnings_are_errors = true,
202            "-P" => opts.line_markers = false,
203            "-ansi" => {
204                opts.std = Std::C89;
205                opts.gnu_extensions = false;
206            }
207            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
208            // the spelling a build system that groups its warning flags tends to write.
209            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
210            "-ffreestanding" => opts.hosted = false,
211            "-fhosted" => opts.hosted = true,
212            // Both directions of each, because a build system that wants one of these usually
213            // writes it beside the flag that turns it back off for one directory.
214            "-fno-omit-frame-pointer" => opts.frame_pointer = true,
215            "-fomit-frame-pointer" => opts.frame_pointer = false,
216            "-mno-red-zone" => opts.red_zone = false,
217            "-mred-zone" => opts.red_zone = true,
218            // GCC drops its own include directory along with the system ones, because its
219            // headers are half of a pair with the library's and half a pair is worse than
220            // none. A build that passes this is supplying the whole set itself.
221            "-nostdinc" => nostdinc = true,
222            "-o" => {
223                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
224                i += 1;
225            }
226            // The flags that take a directory only in the separated form. GCC spells them
227            // this way and nothing writes `-iquotedir`, so accepting the joined form would
228            // mean guessing at a path that starts with the flag's own letters.
229            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
230            // two mean the same thing here: the configured directories are under there rather
231            // than under the root.
232            "-isysroot" => {
233                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
234                i += 1;
235                sysroot = Some(PathBuf::from(dir));
236            }
237            "-iquote" | "-isystem" | "-idirafter" => {
238                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
239                i += 1;
240                match arg {
241                    "-iquote" => opts.search.push_quote(dir.clone()),
242                    "-isystem" => opts.search.push_system(dir.clone()),
243                    _ => opts.search.push_after(dir.clone()),
244                }
245            }
246            "-x" => {
247                let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
248                i += 1;
249                forced = if lang == "none" {
250                    None
251                } else {
252                    Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
253                };
254            }
255            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
256            // translation units in one process rather than making the build system fork, and
257            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
258            // to exist and has to be spelled the way `make` spells it.
259            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
260            // and a build system may produce either, so both are read here rather than
261            // being normalised by whatever generated the command line.
262            _ if arg.starts_with("-D") => {
263                let value = joined_or_next(arg, 2, args, &mut i)?;
264                opts.defines.push(value);
265            }
266            _ if arg.starts_with("-U") => {
267                let value = joined_or_next(arg, 2, args, &mut i)?;
268                opts.undefines.push(value);
269            }
270            _ if arg.starts_with("-I") => {
271                let dir = joined_or_next(arg, 2, args, &mut i)?;
272                opts.search.push_bracket(dir);
273            }
274            _ if arg.starts_with("-std=") => {
275                let name = &arg["-std=".len()..];
276                let (std, gnu) = Std::from_flag(name)
277                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
278                opts.std = std;
279                opts.gnu_extensions = gnu;
280            }
281            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
282            // handed, so a differential run that does not set it is comparing two compilers
283            // that believe they are different compilers.
284            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
285            // that we have not written yet are accepted and ignored, because a dump is a
286            // debugging aid and a build that asks for one should still compile. A letter
287            // outside the family falls through to the unknown option error, which is what
288            // keeps `-dumpversion` from being read as a dump of nothing.
289            _ if Dumps::is_family(arg) => {
290                opts.dumps.add(&arg[2..]);
291            }
292            _ if arg.starts_with("-fgnuc-version=") => {
293                let v = &arg["-fgnuc-version=".len()..];
294                opts.gnuc = v.parse().map_err(err)?;
295            }
296            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
297            // than the unknown option one, because a build reaching for it is asking for a feature
298            // and deserves to be told it is not coming rather than told the spelling is wrong.
299            // The negative form is what this compiler does anyway, so it is taken and dropped.
300            "-fnested-functions" => {
301                return Err(err(
302                    "nested functions are not supported: a call to one goes through a trampoline \
303                     written on the stack, which no target that enforces an unexecutable stack \
304                     allows",
305                ));
306            }
307            "-fno-nested-functions" => {}
308            // The link flags. None of them changes the compilation, which is why they are
309            // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
310            // error: it is a thing said to a linker that is not going to run.
311            "-static" => link.is_static = true,
312            "-shared" => link.shared = true,
313            "-pie" => link.pie = Some(true),
314            "-no-pie" | "-nopie" => link.pie = Some(false),
315            "-nostdlib" => link.no_stdlib = true,
316            "-nostartfiles" => link.no_startfiles = true,
317            "-nodefaultlibs" => link.no_defaultlibs = true,
318            "-fno-builtins-lib" => link.no_builtins_lib = true,
319            "-fbuiltins-lib" => link.no_builtins_lib = false,
320            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
321            "-s" => link.strip = true,
322            "-Xlinker" => {
323                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
324                i += 1;
325                link.passthrough.push(next.clone());
326            }
327            _ if arg.starts_with("-Wl,") => {
328                // Commas separate arguments rather than being part of one, which is what makes
329                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
330                link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
331            }
332            _ if arg.starts_with("-fuse-ld=") => {
333                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
334            }
335            _ if arg.starts_with("-l") && arg.len() > 2 => {
336                inputs.push(Input::library(&arg[2..]));
337            }
338            "-l" => {
339                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
340                i += 1;
341                inputs.push(Input::library(next));
342            }
343            _ if arg.starts_with("-L") => {
344                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
345            }
346            _ if arg.starts_with("-B") => {
347                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
348            }
349            _ if arg.starts_with("-j") => {
350                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
351            }
352            _ if arg.starts_with("--sysroot=") => {
353                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
354            }
355            _ if arg.starts_with("--target=") => {
356                let t = &arg["--target=".len()..];
357                opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
358            }
359            _ if arg.starts_with("--emit=") => {
360                let k = &arg["--emit=".len()..];
361                opts.emit = k
362                    .parse()
363                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
364            }
365            _ if arg.starts_with("-O") => {
366                opts.opt_level = arg[2..]
367                    .parse()
368                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
369            }
370            // The unstable options, spelled the way rustc spells them and carrying the same
371            // promise, which is none: one of these may change or go away in any release. They are
372            // measurements and debugging aids rather than things a build asks for, which is why
373            // none of them is in the usage text and all of them are in section 4.11 of
374            // `spec/04-driver-and-cli.md`.
375            _ if arg.starts_with("-Zrule-coverage=") => {
376                let file = &arg["-Zrule-coverage=".len()..];
377                if file.is_empty() {
378                    return Err(err("-Zrule-coverage= needs a file to write to"));
379                }
380                opts.rule_coverage = Some(file.to_owned());
381            }
382            _ if arg.starts_with("-Z") => {
383                return Err(err(format!(
384                    "`{arg}` is not an unstable option this compiler has, see \
385                     spec/04-driver-and-cli.md section 4.11 for the ones it does"
386                )));
387            }
388            _ if arg.starts_with('-') && arg.len() > 1 => {
389                // Silently ignoring an unknown flag is how a build ends up not doing what
390                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
391                // for the flags that change code generation, and the safe default until the
392                // flag table is populated is to reject everything we do not know.
393                return Err(err(format!("unknown option `{arg}`")));
394            }
395            _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
396        }
397    }
398
399    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
400    // order: a directory the user names outranks the compiler's own, and the compiler's own
401    // outranks the library's. It is pushed after the loop rather than before it because
402    // `SearchPath` appends within a group and the position is what the order is.
403    // The same directory the headers were looked for under, because a sysroot is a statement
404    // about a whole installation and not about half of one.
405    link.sysroot = sysroot.clone();
406    if !nostdinc {
407        opts.search.push_system(runtime::DIR);
408        // And the library's after ours, which is the other half of the same order. They go on
409        // here rather than at the point `--target=` or `--sysroot=` was read because either
410        // one changes the answer and the last word on both is the end of the loop.
411        for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
412            opts.search.push_system(dir);
413        }
414    }
415    // Once, here, rather than as each directory is pushed. A `-I` that names a system
416    // directory has to lose to the system entry and the system entry is added last, so the
417    // question cannot be answered until the whole path is known.
418    opts.search.remove_duplicates();
419
420    // The target has to be resolved before the configuration is printed, so this check comes
421    // after the loop rather than at the point `--print-config` was seen.
422    if print_config {
423        return Ok(Action::PrintConfig(Box::new(opts)));
424    }
425    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
426    if print_plan {
427        return Ok(Action::PrintPlan {
428            opts: Box::new(opts),
429            plan: Box::new(plan),
430            link: Box::new(link),
431        });
432    }
433    Ok(Action::Compile {
434        opts: Box::new(opts),
435        plan: Box::new(plan),
436        link: Box::new(link),
437        jobs,
438        verbose,
439    })
440}
441
442/// Renders the resolved configuration.
443///
444/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
445/// this output is diffed across hosts in CI and a reordering would read as a change.
446#[must_use]
447pub fn print_config(opts: &Options) -> String {
448    let sess = Session::new(opts.clone());
449    let t = &sess.target;
450    let mut out = String::new();
451    let _ = writeln!(out, "version: {VERSION}");
452    let _ = writeln!(out, "target: {}", t.triple);
453    let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
454    let _ = writeln!(out, "os: {}", t.triple.os.as_str());
455    let _ = writeln!(out, "env: {}", t.triple.env.as_str());
456    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
457    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
458    let _ = writeln!(out, "long-width: {}", t.long_width);
459    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
460    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
461    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
462    let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
463    // The register file as a count per class, which is enough to tell a target whose registers
464    // are described from one whose are not without printing sixteen names nobody asked for.
465    let regs: Vec<String> = t
466        .regs
467        .classes()
468        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
469        .collect();
470    let _ = writeln!(
471        out,
472        "registers: {}",
473        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
474    );
475    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
476    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
477    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
478    let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
479    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
480    // Last because it is the one key with more than one line under it, and the only one
481    // whose value is a property of the machine rather than of the command line.
482    for dir in sess.opts.search.dirs() {
483        let system = if dir.is_system { " (system)" } else { "" };
484        let _ = writeln!(out, "include: {}{system}", dir.path.display());
485    }
486    out
487}
488
489/// Runs phase 4 over every input that has one, and writes what came out.
490///
491/// One input that fails does not stop the others. A build that reports every file it could
492/// not preprocess in one run is worth more than one that stops at the first, and the exit
493/// status is still a failure either way.
494fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
495    let fs = OsFileSystem::new();
496    let mut stderr = std::io::stderr().lock();
497    let mut failed = false;
498    for job in &plan.jobs {
499        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
500            // An input that is already preprocessed, or an object file. GCC passes these
501            // through untouched, and the plan has already said so in its notes.
502            continue;
503        }
504        let result = preprocess(opts, &job.input, &fs);
505        for message in &result.messages {
506            let _ = writeln!(stderr, "{message}");
507        }
508        if result.failed() {
509            failed = true;
510            continue;
511        }
512        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
513            let _ = writeln!(stderr, "rucc: error: {e}");
514            failed = true;
515        }
516    }
517    i32::from(failed)
518}
519
520/// Runs the front end over every input that has a compile phase, and writes what came out.
521///
522/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
523/// exit status is a failure either way. An input that is already assembly or an object has no
524/// compile phase and is passed over here, which the plan has already said in its notes.
525fn compile_all(opts: &Options, plan: &Plan) -> i32 {
526    let fs = OsFileSystem::new();
527    let mut stderr = std::io::stderr().lock();
528    let mut failed = false;
529    let mut fired = Fired::new();
530    for job in &plan.jobs {
531        if !job.phases.contains(&Phase::Compile) {
532            continue;
533        }
534        // An input of IR is read back rather than compiled, since the C it came from is not
535        // here any more. Everything after this is the same, so the two paths meet again at the
536        // messages and the file the result is written to.
537        let result = if job.kind == InputKind::Ir {
538            compile_ir(opts, &job.input, &fs)
539        } else {
540            compile(opts, &job.input, &fs)
541        };
542        fired.merge(&result.fired);
543        for message in &result.messages {
544            let _ = writeln!(stderr, "{message}");
545        }
546        if result.failed() {
547            failed = true;
548            continue;
549        }
550        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
551            let _ = writeln!(stderr, "rucc: error: {e}");
552            failed = true;
553        }
554    }
555    failed |= !write_coverage(opts, &fired, &mut stderr);
556    i32::from(failed)
557}
558
559/// A directory for the object files only the link step ever sees, removed when it goes away.
560///
561/// `-c` writes its object where the user can see it and linking does not, which is the whole of
562/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
563/// every other compiler. Removing them on drop rather than at the end of a function is so that a
564/// link that failed leaves nothing behind either.
565struct Scratch {
566    /// Where the objects go.
567    dir: PathBuf,
568}
569
570impl Scratch {
571    /// Makes one, under whatever the platform calls its temporary directory.
572    ///
573    /// The name carries the process id so that two compilers running at once do not share a
574    /// directory, which they would otherwise do the moment two of them compiled a file of the
575    /// same name.
576    fn new() -> Result<Scratch, String> {
577        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
578        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
579        Ok(Scratch { dir })
580    }
581}
582
583impl Drop for Scratch {
584    fn drop(&mut self) {
585        let _ = std::fs::remove_dir_all(&self.dir);
586    }
587}
588
589/// The link line the plan describes, for `-###`.
590///
591/// The names in it are the hints the plan carries rather than the temporaries a real compilation
592/// would choose, because `-###` prints the line without having compiled anything and so has
593/// nothing to point at. That also makes the printed line readable rather than naming a directory
594/// that only exists while a compilation is running.
595fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
596    let linker = link::find(opts.target, link)?;
597    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
598    Ok(link::render(&linker, &args))
599}
600
601/// Compiles everything, then links it.
602///
603/// The objects go in a directory that is removed afterwards, which is why this is not
604/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
605/// and does not say where, because where is a question that only has an answer once something is
606/// running.
607fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
608    let Some(job) = &plan.link else {
609        // Every path into here comes from a plan whose last phase is the link, and such a plan
610        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
611        let mut stderr = std::io::stderr().lock();
612        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
613        return 1;
614    };
615    // Before anything is compiled, because a linker that is not on the machine is worth knowing
616    // about in the second it takes to look rather than after the compilation.
617    let linker = match link::find(opts.target, link) {
618        Ok(linker) => linker,
619        Err(why) => return complain(why),
620    };
621
622    let scratch = match Scratch::new() {
623        Ok(scratch) => scratch,
624        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
625    };
626
627    let fs = OsFileSystem::new();
628    let mut failed = false;
629    // One per job, in job order, which is what lets the link line below be rebuilt with the real
630    // paths in it: every job contributes exactly one file to the line and does so in this order.
631    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
632    let mut fired = Fired::new();
633    {
634        let mut stderr = std::io::stderr().lock();
635        for (at, job) in plan.jobs.iter().enumerate() {
636            let out = match &job.output {
637                Output::Temporary(hint) => {
638                    // The index because two inputs in different directories can have the same
639                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
640                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
641                }
642                Output::File(path) => path.clone(),
643                // A job feeding the linker never writes to standard output, since the plan gives
644                // it a temporary. This is here so that the match is total rather than a panic.
645                Output::Stdout => continue,
646            };
647            produced.push(out.clone());
648            if !job.phases.contains(&Phase::Compile) {
649                continue;
650            }
651            let result = if job.kind == InputKind::Ir {
652                compile_ir(opts, &job.input, &fs)
653            } else {
654                compile(opts, &job.input, &fs)
655            };
656            fired.merge(&result.fired);
657            for message in &result.messages {
658                let _ = writeln!(stderr, "{message}");
659            }
660            if result.failed() {
661                failed = true;
662                continue;
663            }
664            if !matches!(result.artifact, Artifact::Object(_)) {
665                // Worth saying rather than writing whatever it is and letting the linker read it.
666                // An empty file is a valid empty linker script, so a link handed one gets as far
667                // as reporting every symbol of this file undefined, which is a page of messages
668                // about something that went wrong here.
669                let _ = writeln!(
670                    stderr,
671                    "rucc: internal error: {}: no object file was produced for the link",
672                    job.input
673                );
674                failed = true;
675                continue;
676            }
677            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
678                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
679                failed = true;
680            }
681        }
682        failed |= !write_coverage(opts, &fired, &mut stderr);
683    }
684    if failed {
685        // Nothing is linked from a compilation that did not finish. A linker run over the objects
686        // that did compile would report every function of the file that did not as undefined,
687        // which is a page of messages about a mistake already reported once.
688        return 1;
689    }
690
691    // The items in command line order with the temporaries filled in. A library contributes no
692    // job and passes through, and every file item takes the next job's real output, which is
693    // what keeps a library that was written between two objects between them here.
694    let mut outputs = produced.into_iter();
695    let mut items = Vec::with_capacity(job.inputs.len());
696    for item in &job.inputs {
697        match item {
698            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
699            link::Item::File(_) => match outputs.next() {
700                Some(path) => items.push(link::Item::File(path)),
701                None => return complain("the plan asks the linker for a file nothing produced"),
702            },
703        }
704    }
705
706    let args = match link::line(opts.target, link, &items, &job.output) {
707        Ok(args) => args,
708        Err(why) => return complain(why),
709    };
710    if verbose {
711        let mut stderr = std::io::stderr().lock();
712        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
713    }
714    match link::run(&linker, &args) {
715        Ok(()) => 0,
716        // The linker has already said what was wrong on its own error output, and repeating that
717        // linking failed would only push its message further up the screen.
718        Err(link::Error::Refused { .. }) => 1,
719        Err(why) => complain(why),
720    }
721}
722
723/// Prints one driver level message and gives back the exit status that goes with it.
724fn complain(why: impl std::fmt::Display) -> i32 {
725    let mut stderr = std::io::stderr().lock();
726    let _ = writeln!(stderr, "rucc: error: {why}");
727    1
728}
729
730/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
731///
732/// Once for the whole command line rather than once per input, because the question is which
733/// lowering rules this run of the compiler reached and a file per input would leave the reader
734/// unioning files to find out something one process already knew.
735///
736/// A file that could not be written is a failure and not a warning. What asks for this is a
737/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
738fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
739    let Some(path) = &opts.rule_coverage else { return true };
740    let Some(table) = coverage::table(opts.target.arch) else {
741        let _ = writeln!(
742            stderr,
743            "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
744             to report",
745            opts.target
746        );
747        return false;
748    };
749    match std::fs::write(path, fired.listing(table)) {
750        Ok(()) => true,
751        Err(e) => {
752            let _ = writeln!(stderr, "rucc: error: {path}: {e}");
753            false
754        }
755    }
756}
757
758/// Writes one job's result where the plan said it goes.
759///
760/// # Errors
761///
762/// Returns the message to print, which names the file when there is one, because "permission
763/// denied" on its own does not say which file was refused.
764fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
765    match output {
766        Output::Stdout => {
767            let mut stdout = std::io::stdout().lock();
768            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
769        }
770        Output::File(path) | Output::Temporary(path) => {
771            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
772        }
773    }
774}
775
776/// Runs the driver and returns the process exit code.
777///
778/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
779/// is the one place in the compiler that is true.
780pub fn run(args: &[String]) -> i32 {
781    match parse_args(args) {
782        Ok(Action::Help) => {
783            print!("{USAGE}");
784            0
785        }
786        Ok(Action::Version) => {
787            println!("rucc {VERSION}");
788            0
789        }
790        Ok(Action::PrintConfig(opts)) => {
791            print!("{}", print_config(&opts));
792            0
793        }
794        Ok(Action::PrintPlan { opts, plan, link }) => {
795            print!("{}", plan.render());
796            // The line as it would be typed, which is the half of `-###` that section 4.3 says
797            // arrives with the link. It is printed even when the linker is not on this machine,
798            // because what a build wants from `-###` is what the compiler would do.
799            if let Some(job) = &plan.link {
800                match link_line(&opts, &link, job) {
801                    Ok(line) => println!("{line}"),
802                    Err(why) => {
803                        let mut stderr = std::io::stderr().lock();
804                        let _ = writeln!(stderr, "rucc: error: {why}");
805                        return 1;
806                    }
807                }
808            }
809            0
810        }
811        Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
812            {
813                let mut stderr = std::io::stderr().lock();
814                if verbose {
815                    let _ = write!(stderr, "{}", plan.render());
816                    let _ = writeln!(stderr, "workers: {}", jobs.count());
817                }
818            }
819            if opts.emit == EmitKind::Preprocessed {
820                return preprocess_all(&opts, &plan);
821            }
822            if opts.emit != EmitKind::Executable {
823                return compile_all(&opts, &plan);
824            }
825            link_all(&opts, &plan, &link, verbose)
826        }
827        Err(e) => {
828            let mut stderr = std::io::stderr().lock();
829            let _ = writeln!(stderr, "rucc: error: {e}");
830            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
831            1
832        }
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use rucc_session::{GnucVersion, OptLevel};
839
840    use super::*;
841
842    fn args(s: &[&str]) -> Vec<String> {
843        s.iter().map(|x| (*x).to_owned()).collect()
844    }
845
846    #[test]
847    fn help_and_version_win_over_everything_else() {
848        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
849        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
850    }
851
852    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
853        match parse_args(&args(s)).expect("expected a compilation") {
854            Action::Compile { opts, plan, .. } => (opts, plan),
855            other => panic!("expected a compilation, got {other:?}"),
856        }
857    }
858
859    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
860        match parse_args(&args(s)).expect("expected a compilation") {
861            Action::Compile { link, plan, .. } => (link, plan),
862            other => panic!("expected a compilation, got {other:?}"),
863        }
864    }
865
866    #[test]
867    fn collects_inputs_and_flags() {
868        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
869        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
870        assert_eq!(paths, vec!["a.c", "b.c"]);
871        assert_eq!(opts.opt_level, OptLevel::O2);
872        assert_eq!(opts.emit, EmitKind::Object);
873        assert!(opts.debug_info);
874    }
875
876    /// The unstable options, which are spelled apart from everything else on purpose: what is
877    /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
878    #[test]
879    fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
880        let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
881        assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
882
883        let (plain, _) = compile(&["-c", "a.c"]);
884        assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
885
886        assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
887        let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
888        assert!(unknown.message.contains("4.11"), "{}", unknown.message);
889    }
890
891    #[test]
892    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
893        let (opts, _) = compile(&["-O", "a.c"]);
894        assert_eq!(opts.opt_level, OptLevel::O1);
895    }
896
897    #[test]
898    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
899        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
900        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
901        assert_eq!(plan.jobs[1].kind, InputKind::C);
902        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
903    }
904
905    #[test]
906    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
907        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
908            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
909            other => panic!("expected a compilation, got {other:?}"),
910        };
911        assert_eq!(jobs.count(), 4);
912
913        let default = match parse_args(&args(&["a.c"])).unwrap() {
914            Action::Compile { jobs, .. } => jobs,
915            other => panic!("expected a compilation, got {other:?}"),
916        };
917        assert_eq!(default, Jobs::available());
918        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
919    }
920
921    #[test]
922    fn triple_hash_prints_the_plan_and_runs_nothing() {
923        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
924        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
925        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
926    }
927
928    #[test]
929    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
930        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
931        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
932    }
933
934    #[test]
935    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
936        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
937        assert!(e.message.contains("unknown option"), "{}", e.message);
938    }
939
940    #[test]
941    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
942        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
943        assert!(e.message.contains("trampoline"), "{}", e.message);
944        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
945    }
946
947    #[test]
948    fn an_unsupported_target_names_itself() {
949        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
950        assert!(e.message.contains("sparc64"), "{}", e.message);
951    }
952
953    #[test]
954    fn no_inputs_is_an_error_but_print_config_needs_none() {
955        assert!(parse_args(&args(&[])).is_err());
956        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
957    }
958
959    #[test]
960    fn print_config_reports_the_target_it_was_given_not_the_host() {
961        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
962        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
963        let text = print_config(&opts);
964        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
965        assert!(text.contains("char-signed: false"), "{text}");
966        assert!(text.contains("object-format: elf"), "{text}");
967        assert!(text.contains("va-list: void-pointer"), "{text}");
968        // RISC-V has a register file and this compiler has not written it down yet, and the
969        // dump says which of those two it is rather than leaving the line out.
970        assert!(text.contains("registers: none"), "{text}");
971    }
972
973    #[test]
974    fn print_config_has_one_key_per_line_and_a_fixed_order() {
975        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
976        let text = print_config(&opts);
977        let keys: Vec<&str> =
978            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
979        assert_eq!(keys[0], "version");
980        assert_eq!(keys[1], "target");
981        assert_eq!(keys.len(), 18);
982        assert!(text.ends_with('\n'));
983    }
984
985    #[test]
986    fn dash_o_needs_an_argument() {
987        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
988        assert_eq!(e.message, "-o requires an argument");
989    }
990
991    #[test]
992    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
993        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
994        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
995        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
996    }
997
998    #[test]
999    fn the_include_flags_land_on_the_chain_each_one_names() {
1000        // A sysroot with nothing under it, so that the library's own directories are the
1001        // same on every machine this test runs on, which is none of them.
1002        let (opts, _) = compile(&[
1003            "-Ii",
1004            "-iquote",
1005            "q",
1006            "-isystem",
1007            "sys",
1008            "-idirafter",
1009            "after",
1010            "--sysroot=/nowhere-at-all",
1011            "a.c",
1012        ]);
1013        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1014        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
1015        // which is where GCC puts its own: a directory the user named outranks ours.
1016        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
1017        assert!(!opts.search.dirs()[1].is_system);
1018        assert!(opts.search.dirs()[2].is_system);
1019    }
1020
1021    #[test]
1022    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
1023        // Which machine this runs on decides what is on the path, so the test is about the
1024        // order rather than about the names: ours is on it, the library's follow it, and
1025        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
1026        let (opts, _) = compile(&["a.c"]);
1027        let dirs = opts.search.dirs();
1028        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
1029        assert_eq!(ours, Some(0), "{dirs:?}");
1030        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
1031        let (bare, _) = compile(&["-nostdinc", "a.c"]);
1032        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
1033    }
1034
1035    #[test]
1036    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
1037        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
1038        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1039        assert_eq!(dirs, ["sys", runtime::DIR]);
1040    }
1041
1042    #[test]
1043    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
1044        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
1045        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1046        assert_eq!(dirs, ["i"]);
1047    }
1048
1049    #[test]
1050    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
1051        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
1052        assert_eq!(opts.std, Std::C11);
1053        assert!(opts.gnu_extensions);
1054
1055        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
1056        assert_eq!(opts.std, Std::C99);
1057        assert!(!opts.gnu_extensions);
1058
1059        let (opts, _) = compile(&["-ansi", "a.c"]);
1060        assert_eq!(opts.std, Std::C89);
1061        assert!(!opts.gnu_extensions);
1062
1063        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
1064        assert!(e.message.contains("unknown dialect"), "{}", e.message);
1065    }
1066
1067    #[test]
1068    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
1069        let (opts, _) = compile(&["-dM", "a.c"]);
1070        assert!(opts.dumps.macros);
1071
1072        // Packed, the way GCC takes them, and a letter in the family we have not written yet
1073        // is accepted and does nothing rather than failing a build.
1074        let (opts, _) = compile(&["-dDM", "a.c"]);
1075        assert!(opts.dumps.macros);
1076        let (opts, _) = compile(&["-dD", "a.c"]);
1077        assert!(!opts.dumps.macros);
1078
1079        let (opts, _) = compile(&["a.c"]);
1080        assert!(!opts.dumps.any());
1081
1082        // `-dumpversion` is a different flag that happens to start the same way. We have not
1083        // written it, and saying so beats reading it as a dump of nothing.
1084        let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
1085        assert!(e.message.contains("unknown option"), "{}", e.message);
1086    }
1087
1088    #[test]
1089    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
1090        let (opts, _) = compile(&["a.c"]);
1091        assert_eq!(
1092            opts.gnuc,
1093            GnucVersion { major: 7, minor: 0, patch: 0 },
1094            "the lowest claim a modern glibc gives its own declarations to"
1095        );
1096
1097        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
1098        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
1099
1100        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
1101        // patchlevel and a harness that pastes that back has to be understood.
1102        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
1103        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
1104
1105        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
1106        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
1107
1108        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
1109        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
1110
1111        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
1112        assert!(e.message.contains("more than three"), "{}", e.message);
1113    }
1114
1115    #[test]
1116    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
1117        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
1118        assert!(opts.pedantic);
1119        assert_eq!(opts.std, Std::C17);
1120
1121        // The `-W` family's name for it, which is what a build that groups its warning flags
1122        // tends to write.
1123        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
1124        assert!(opts.pedantic);
1125
1126        let (opts, _) = compile(&["-std=c17", "a.c"]);
1127        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
1128    }
1129
1130    #[test]
1131    fn dash_p_and_dash_ffreestanding_reach_the_options() {
1132        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
1133        assert!(!opts.line_markers);
1134        assert!(!opts.hosted);
1135        assert_eq!(opts.emit, EmitKind::Preprocessed);
1136    }
1137
1138    /// Both spellings of both frame flags, since a build that wants one usually writes the
1139    /// other beside it for the one file that has to be compiled the ordinary way.
1140    #[test]
1141    fn the_two_frame_flags_are_read_in_both_directions() {
1142        let (opts, _) = compile(&["-c", "a.c"]);
1143        assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
1144        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
1145
1146        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
1147        assert!(opts.frame_pointer);
1148        assert!(!opts.red_zone);
1149
1150        let (opts, _) = compile(&[
1151            "-c",
1152            "-fno-omit-frame-pointer",
1153            "-fomit-frame-pointer",
1154            "-mno-red-zone",
1155            "-mred-zone",
1156            "a.c",
1157        ]);
1158        assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
1159        assert!(opts.red_zone);
1160    }
1161
1162    #[test]
1163    fn the_link_flags_are_collected_apart_from_the_compilation() {
1164        let (link, _) = linking(&[
1165            "-static",
1166            "-nostartfiles",
1167            "-rdynamic",
1168            "-s",
1169            "-fuse-ld=mold",
1170            "-L/opt/lib",
1171            "-B",
1172            "/opt/tools",
1173            "a.c",
1174        ]);
1175        assert!(link.is_static);
1176        assert!(link.no_startfiles);
1177        assert!(link.export_dynamic);
1178        assert!(link.strip);
1179        assert_eq!(link.use_ld.as_deref(), Some("mold"));
1180        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
1181        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
1182    }
1183
1184    #[test]
1185    fn a_comma_in_dash_wl_separates_two_arguments() {
1186        let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
1187        assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
1188    }
1189
1190    #[test]
1191    fn a_library_keeps_its_place_between_the_objects() {
1192        // Link order is semantic: `-lm` written between two files resolves for the one before
1193        // it and not for the one after, so a library cannot be collected into a list of its own.
1194        // The target is named because the suffix of an object is the target's and this asserts
1195        // on the names: the same command line on a Windows host plans two `.obj` files.
1196        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
1197        let link = plan.link.expect("expected a link step");
1198        assert_eq!(
1199            link.inputs,
1200            vec![
1201                link::Item::File("a.o".into()),
1202                link::Item::Library("m".into()),
1203                link::Item::File("b.o".into()),
1204            ]
1205        );
1206        // And it is not a job, because there is nothing to compile in a library.
1207        assert_eq!(plan.jobs.len(), 2);
1208    }
1209
1210    #[test]
1211    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1212        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
1213        assert!(plan.link.is_none());
1214        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
1215    }
1216
1217    #[test]
1218    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
1219        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
1220        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
1221    }
1222
1223    #[test]
1224    fn usage_fits_on_a_screen() {
1225        // Not a style preference. A help text that scrolls is one nobody reads, and this is
1226        // the cheapest way to keep it honest as flags accumulate.
1227        assert!(USAGE.lines().count() < 34, "usage text has grown past one screen");
1228    }
1229}