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