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.7")]
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            "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
318            "-s" => link.strip = true,
319            "-Xlinker" => {
320                let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
321                i += 1;
322                link.passthrough.push(next.clone());
323            }
324            _ if arg.starts_with("-Wl,") => {
325                // Commas separate arguments rather than being part of one, which is what makes
326                // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
327                link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
328            }
329            _ if arg.starts_with("-fuse-ld=") => {
330                link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
331            }
332            _ if arg.starts_with("-l") && arg.len() > 2 => {
333                inputs.push(Input::library(&arg[2..]));
334            }
335            "-l" => {
336                let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
337                i += 1;
338                inputs.push(Input::library(next));
339            }
340            _ if arg.starts_with("-L") => {
341                link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
342            }
343            _ if arg.starts_with("-B") => {
344                link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
345            }
346            _ if arg.starts_with("-j") => {
347                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
348            }
349            _ if arg.starts_with("--sysroot=") => {
350                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
351            }
352            _ if arg.starts_with("--target=") => {
353                let t = &arg["--target=".len()..];
354                opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
355            }
356            _ if arg.starts_with("--emit=") => {
357                let k = &arg["--emit=".len()..];
358                opts.emit = k
359                    .parse()
360                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
361            }
362            _ if arg.starts_with("-O") => {
363                opts.opt_level = arg[2..]
364                    .parse()
365                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
366            }
367            _ if arg.starts_with('-') && arg.len() > 1 => {
368                // Silently ignoring an unknown flag is how a build ends up not doing what
369                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
370                // for the flags that change code generation, and the safe default until the
371                // flag table is populated is to reject everything we do not know.
372                return Err(err(format!("unknown option `{arg}`")));
373            }
374            _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
375        }
376    }
377
378    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
379    // order: a directory the user names outranks the compiler's own, and the compiler's own
380    // outranks the library's. It is pushed after the loop rather than before it because
381    // `SearchPath` appends within a group and the position is what the order is.
382    // The same directory the headers were looked for under, because a sysroot is a statement
383    // about a whole installation and not about half of one.
384    link.sysroot = sysroot.clone();
385    if !nostdinc {
386        opts.search.push_system(runtime::DIR);
387        // And the library's after ours, which is the other half of the same order. They go on
388        // here rather than at the point `--target=` or `--sysroot=` was read because either
389        // one changes the answer and the last word on both is the end of the loop.
390        for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
391            opts.search.push_system(dir);
392        }
393    }
394    // Once, here, rather than as each directory is pushed. A `-I` that names a system
395    // directory has to lose to the system entry and the system entry is added last, so the
396    // question cannot be answered until the whole path is known.
397    opts.search.remove_duplicates();
398
399    // The target has to be resolved before the configuration is printed, so this check comes
400    // after the loop rather than at the point `--print-config` was seen.
401    if print_config {
402        return Ok(Action::PrintConfig(Box::new(opts)));
403    }
404    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
405    if print_plan {
406        return Ok(Action::PrintPlan {
407            opts: Box::new(opts),
408            plan: Box::new(plan),
409            link: Box::new(link),
410        });
411    }
412    Ok(Action::Compile {
413        opts: Box::new(opts),
414        plan: Box::new(plan),
415        link: Box::new(link),
416        jobs,
417        verbose,
418    })
419}
420
421/// Renders the resolved configuration.
422///
423/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
424/// this output is diffed across hosts in CI and a reordering would read as a change.
425#[must_use]
426pub fn print_config(opts: &Options) -> String {
427    let sess = Session::new(opts.clone());
428    let t = &sess.target;
429    let mut out = String::new();
430    let _ = writeln!(out, "version: {VERSION}");
431    let _ = writeln!(out, "target: {}", t.triple);
432    let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
433    let _ = writeln!(out, "os: {}", t.triple.os.as_str());
434    let _ = writeln!(out, "env: {}", t.triple.env.as_str());
435    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
436    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
437    let _ = writeln!(out, "long-width: {}", t.long_width);
438    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
439    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
440    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
441    let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
442    // The register file as a count per class, which is enough to tell a target whose registers
443    // are described from one whose are not without printing sixteen names nobody asked for.
444    let regs: Vec<String> = t
445        .regs
446        .classes()
447        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
448        .collect();
449    let _ = writeln!(
450        out,
451        "registers: {}",
452        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
453    );
454    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
455    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
456    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
457    let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
458    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
459    // Last because it is the one key with more than one line under it, and the only one
460    // whose value is a property of the machine rather than of the command line.
461    for dir in sess.opts.search.dirs() {
462        let system = if dir.is_system { " (system)" } else { "" };
463        let _ = writeln!(out, "include: {}{system}", dir.path.display());
464    }
465    out
466}
467
468/// Runs phase 4 over every input that has one, and writes what came out.
469///
470/// One input that fails does not stop the others. A build that reports every file it could
471/// not preprocess in one run is worth more than one that stops at the first, and the exit
472/// status is still a failure either way.
473fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
474    let fs = OsFileSystem::new();
475    let mut stderr = std::io::stderr().lock();
476    let mut failed = false;
477    for job in &plan.jobs {
478        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
479            // An input that is already preprocessed, or an object file. GCC passes these
480            // through untouched, and the plan has already said so in its notes.
481            continue;
482        }
483        let result = preprocess(opts, &job.input, &fs);
484        for message in &result.messages {
485            let _ = writeln!(stderr, "{message}");
486        }
487        if result.failed() {
488            failed = true;
489            continue;
490        }
491        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
492            let _ = writeln!(stderr, "rucc: error: {e}");
493            failed = true;
494        }
495    }
496    i32::from(failed)
497}
498
499/// Runs the front end over every input that has a compile phase, and writes what came out.
500///
501/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
502/// exit status is a failure either way. An input that is already assembly or an object has no
503/// compile phase and is passed over here, which the plan has already said in its notes.
504fn compile_all(opts: &Options, plan: &Plan) -> i32 {
505    let fs = OsFileSystem::new();
506    let mut stderr = std::io::stderr().lock();
507    let mut failed = false;
508    for job in &plan.jobs {
509        if !job.phases.contains(&Phase::Compile) {
510            continue;
511        }
512        // An input of IR is read back rather than compiled, since the C it came from is not
513        // here any more. Everything after this is the same, so the two paths meet again at the
514        // messages and the file the result is written to.
515        let result = if job.kind == InputKind::Ir {
516            compile_ir(opts, &job.input, &fs)
517        } else {
518            compile(opts, &job.input, &fs)
519        };
520        for message in &result.messages {
521            let _ = writeln!(stderr, "{message}");
522        }
523        if result.failed() {
524            failed = true;
525            continue;
526        }
527        if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
528            let _ = writeln!(stderr, "rucc: error: {e}");
529            failed = true;
530        }
531    }
532    i32::from(failed)
533}
534
535/// A directory for the object files only the link step ever sees, removed when it goes away.
536///
537/// `-c` writes its object where the user can see it and linking does not, which is the whole of
538/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
539/// every other compiler. Removing them on drop rather than at the end of a function is so that a
540/// link that failed leaves nothing behind either.
541struct Scratch {
542    /// Where the objects go.
543    dir: PathBuf,
544}
545
546impl Scratch {
547    /// Makes one, under whatever the platform calls its temporary directory.
548    ///
549    /// The name carries the process id so that two compilers running at once do not share a
550    /// directory, which they would otherwise do the moment two of them compiled a file of the
551    /// same name.
552    fn new() -> Result<Scratch, String> {
553        let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
554        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
555        Ok(Scratch { dir })
556    }
557}
558
559impl Drop for Scratch {
560    fn drop(&mut self) {
561        let _ = std::fs::remove_dir_all(&self.dir);
562    }
563}
564
565/// The link line the plan describes, for `-###`.
566///
567/// The names in it are the hints the plan carries rather than the temporaries a real compilation
568/// would choose, because `-###` prints the line without having compiled anything and so has
569/// nothing to point at. That also makes the printed line readable rather than naming a directory
570/// that only exists while a compilation is running.
571fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
572    let linker = link::find(opts.target, link)?;
573    let args = link::line(opts.target, link, &job.inputs, &job.output)?;
574    Ok(link::render(&linker, &args))
575}
576
577/// Compiles everything, then links it.
578///
579/// The objects go in a directory that is removed afterwards, which is why this is not
580/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
581/// and does not say where, because where is a question that only has an answer once something is
582/// running.
583fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
584    let Some(job) = &plan.link else {
585        // Every path into here comes from a plan whose last phase is the link, and such a plan
586        // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
587        let mut stderr = std::io::stderr().lock();
588        let _ = writeln!(stderr, "rucc: error: there is nothing to link");
589        return 1;
590    };
591    // Before anything is compiled, because a linker that is not on the machine is worth knowing
592    // about in the second it takes to look rather than after the compilation.
593    let linker = match link::find(opts.target, link) {
594        Ok(linker) => linker,
595        Err(why) => return complain(why),
596    };
597
598    let scratch = match Scratch::new() {
599        Ok(scratch) => scratch,
600        Err(why) => return complain(format!("could not make a place for the object files: {why}")),
601    };
602
603    let fs = OsFileSystem::new();
604    let mut failed = false;
605    // One per job, in job order, which is what lets the link line below be rebuilt with the real
606    // paths in it: every job contributes exactly one file to the line and does so in this order.
607    let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
608    {
609        let mut stderr = std::io::stderr().lock();
610        for (at, job) in plan.jobs.iter().enumerate() {
611            let out = match &job.output {
612                Output::Temporary(hint) => {
613                    // The index because two inputs in different directories can have the same
614                    // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
615                    scratch.dir.join(format!("{at}-{hint}")).display().to_string()
616                }
617                Output::File(path) => path.clone(),
618                // A job feeding the linker never writes to standard output, since the plan gives
619                // it a temporary. This is here so that the match is total rather than a panic.
620                Output::Stdout => continue,
621            };
622            produced.push(out.clone());
623            if !job.phases.contains(&Phase::Compile) {
624                continue;
625            }
626            let result = if job.kind == InputKind::Ir {
627                compile_ir(opts, &job.input, &fs)
628            } else {
629                compile(opts, &job.input, &fs)
630            };
631            for message in &result.messages {
632                let _ = writeln!(stderr, "{message}");
633            }
634            if result.failed() {
635                failed = true;
636                continue;
637            }
638            if !matches!(result.artifact, Artifact::Object(_)) {
639                // Worth saying rather than writing whatever it is and letting the linker read it.
640                // An empty file is a valid empty linker script, so a link handed one gets as far
641                // as reporting every symbol of this file undefined, which is a page of messages
642                // about something that went wrong here.
643                let _ = writeln!(
644                    stderr,
645                    "rucc: internal error: {}: no object file was produced for the link",
646                    job.input
647                );
648                failed = true;
649                continue;
650            }
651            if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
652                let _ = writeln!(stderr, "rucc: error: {out}: {e}");
653                failed = true;
654            }
655        }
656    }
657    if failed {
658        // Nothing is linked from a compilation that did not finish. A linker run over the objects
659        // that did compile would report every function of the file that did not as undefined,
660        // which is a page of messages about a mistake already reported once.
661        return 1;
662    }
663
664    // The items in command line order with the temporaries filled in. A library contributes no
665    // job and passes through, and every file item takes the next job's real output, which is
666    // what keeps a library that was written between two objects between them here.
667    let mut outputs = produced.into_iter();
668    let mut items = Vec::with_capacity(job.inputs.len());
669    for item in &job.inputs {
670        match item {
671            link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
672            link::Item::File(_) => match outputs.next() {
673                Some(path) => items.push(link::Item::File(path)),
674                None => return complain("the plan asks the linker for a file nothing produced"),
675            },
676        }
677    }
678
679    let args = match link::line(opts.target, link, &items, &job.output) {
680        Ok(args) => args,
681        Err(why) => return complain(why),
682    };
683    if verbose {
684        let mut stderr = std::io::stderr().lock();
685        let _ = writeln!(stderr, "{}", link::render(&linker, &args));
686    }
687    match link::run(&linker, &args) {
688        Ok(()) => 0,
689        // The linker has already said what was wrong on its own error output, and repeating that
690        // linking failed would only push its message further up the screen.
691        Err(link::Error::Refused { .. }) => 1,
692        Err(why) => complain(why),
693    }
694}
695
696/// Prints one driver level message and gives back the exit status that goes with it.
697fn complain(why: impl std::fmt::Display) -> i32 {
698    let mut stderr = std::io::stderr().lock();
699    let _ = writeln!(stderr, "rucc: error: {why}");
700    1
701}
702
703/// Writes one job's result where the plan said it goes.
704///
705/// # Errors
706///
707/// Returns the message to print, which names the file when there is one, because "permission
708/// denied" on its own does not say which file was refused.
709fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
710    match output {
711        Output::Stdout => {
712            let mut stdout = std::io::stdout().lock();
713            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
714        }
715        Output::File(path) | Output::Temporary(path) => {
716            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
717        }
718    }
719}
720
721/// Runs the driver and returns the process exit code.
722///
723/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
724/// is the one place in the compiler that is true.
725pub fn run(args: &[String]) -> i32 {
726    match parse_args(args) {
727        Ok(Action::Help) => {
728            print!("{USAGE}");
729            0
730        }
731        Ok(Action::Version) => {
732            println!("rucc {VERSION}");
733            0
734        }
735        Ok(Action::PrintConfig(opts)) => {
736            print!("{}", print_config(&opts));
737            0
738        }
739        Ok(Action::PrintPlan { opts, plan, link }) => {
740            print!("{}", plan.render());
741            // The line as it would be typed, which is the half of `-###` that section 4.3 says
742            // arrives with the link. It is printed even when the linker is not on this machine,
743            // because what a build wants from `-###` is what the compiler would do.
744            if let Some(job) = &plan.link {
745                match link_line(&opts, &link, job) {
746                    Ok(line) => println!("{line}"),
747                    Err(why) => {
748                        let mut stderr = std::io::stderr().lock();
749                        let _ = writeln!(stderr, "rucc: error: {why}");
750                        return 1;
751                    }
752                }
753            }
754            0
755        }
756        Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
757            {
758                let mut stderr = std::io::stderr().lock();
759                if verbose {
760                    let _ = write!(stderr, "{}", plan.render());
761                    let _ = writeln!(stderr, "workers: {}", jobs.count());
762                }
763            }
764            if opts.emit == EmitKind::Preprocessed {
765                return preprocess_all(&opts, &plan);
766            }
767            if opts.emit != EmitKind::Executable {
768                return compile_all(&opts, &plan);
769            }
770            link_all(&opts, &plan, &link, verbose)
771        }
772        Err(e) => {
773            let mut stderr = std::io::stderr().lock();
774            let _ = writeln!(stderr, "rucc: error: {e}");
775            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
776            1
777        }
778    }
779}
780
781#[cfg(test)]
782mod tests {
783    use rucc_session::{GnucVersion, OptLevel};
784
785    use super::*;
786
787    fn args(s: &[&str]) -> Vec<String> {
788        s.iter().map(|x| (*x).to_owned()).collect()
789    }
790
791    #[test]
792    fn help_and_version_win_over_everything_else() {
793        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
794        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
795    }
796
797    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
798        match parse_args(&args(s)).expect("expected a compilation") {
799            Action::Compile { opts, plan, .. } => (opts, plan),
800            other => panic!("expected a compilation, got {other:?}"),
801        }
802    }
803
804    fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
805        match parse_args(&args(s)).expect("expected a compilation") {
806            Action::Compile { link, plan, .. } => (link, plan),
807            other => panic!("expected a compilation, got {other:?}"),
808        }
809    }
810
811    #[test]
812    fn collects_inputs_and_flags() {
813        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
814        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
815        assert_eq!(paths, vec!["a.c", "b.c"]);
816        assert_eq!(opts.opt_level, OptLevel::O2);
817        assert_eq!(opts.emit, EmitKind::Object);
818        assert!(opts.debug_info);
819    }
820
821    #[test]
822    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
823        let (opts, _) = compile(&["-O", "a.c"]);
824        assert_eq!(opts.opt_level, OptLevel::O1);
825    }
826
827    #[test]
828    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
829        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
830        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
831        assert_eq!(plan.jobs[1].kind, InputKind::C);
832        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
833    }
834
835    #[test]
836    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
837        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
838            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
839            other => panic!("expected a compilation, got {other:?}"),
840        };
841        assert_eq!(jobs.count(), 4);
842
843        let default = match parse_args(&args(&["a.c"])).unwrap() {
844            Action::Compile { jobs, .. } => jobs,
845            other => panic!("expected a compilation, got {other:?}"),
846        };
847        assert_eq!(default, Jobs::available());
848        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
849    }
850
851    #[test]
852    fn triple_hash_prints_the_plan_and_runs_nothing() {
853        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
854        let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
855        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
856    }
857
858    #[test]
859    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
860        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
861        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
862    }
863
864    #[test]
865    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
866        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
867        assert!(e.message.contains("unknown option"), "{}", e.message);
868    }
869
870    #[test]
871    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
872        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
873        assert!(e.message.contains("trampoline"), "{}", e.message);
874        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
875    }
876
877    #[test]
878    fn an_unsupported_target_names_itself() {
879        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
880        assert!(e.message.contains("sparc64"), "{}", e.message);
881    }
882
883    #[test]
884    fn no_inputs_is_an_error_but_print_config_needs_none() {
885        assert!(parse_args(&args(&[])).is_err());
886        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
887    }
888
889    #[test]
890    fn print_config_reports_the_target_it_was_given_not_the_host() {
891        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
892        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
893        let text = print_config(&opts);
894        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
895        assert!(text.contains("char-signed: false"), "{text}");
896        assert!(text.contains("object-format: elf"), "{text}");
897        assert!(text.contains("va-list: void-pointer"), "{text}");
898        // RISC-V has a register file and this compiler has not written it down yet, and the
899        // dump says which of those two it is rather than leaving the line out.
900        assert!(text.contains("registers: none"), "{text}");
901    }
902
903    #[test]
904    fn print_config_has_one_key_per_line_and_a_fixed_order() {
905        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
906        let text = print_config(&opts);
907        let keys: Vec<&str> =
908            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
909        assert_eq!(keys[0], "version");
910        assert_eq!(keys[1], "target");
911        assert_eq!(keys.len(), 18);
912        assert!(text.ends_with('\n'));
913    }
914
915    #[test]
916    fn dash_o_needs_an_argument() {
917        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
918        assert_eq!(e.message, "-o requires an argument");
919    }
920
921    #[test]
922    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
923        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
924        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
925        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
926    }
927
928    #[test]
929    fn the_include_flags_land_on_the_chain_each_one_names() {
930        // A sysroot with nothing under it, so that the library's own directories are the
931        // same on every machine this test runs on, which is none of them.
932        let (opts, _) = compile(&[
933            "-Ii",
934            "-iquote",
935            "q",
936            "-isystem",
937            "sys",
938            "-idirafter",
939            "after",
940            "--sysroot=/nowhere-at-all",
941            "a.c",
942        ]);
943        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
944        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
945        // which is where GCC puts its own: a directory the user named outranks ours.
946        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
947        assert!(!opts.search.dirs()[1].is_system);
948        assert!(opts.search.dirs()[2].is_system);
949    }
950
951    #[test]
952    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
953        // Which machine this runs on decides what is on the path, so the test is about the
954        // order rather than about the names: ours is on it, the library's follow it, and
955        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
956        let (opts, _) = compile(&["a.c"]);
957        let dirs = opts.search.dirs();
958        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
959        assert_eq!(ours, Some(0), "{dirs:?}");
960        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
961        let (bare, _) = compile(&["-nostdinc", "a.c"]);
962        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
963    }
964
965    #[test]
966    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
967        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
968        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
969        assert_eq!(dirs, ["sys", runtime::DIR]);
970    }
971
972    #[test]
973    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
974        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
975        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
976        assert_eq!(dirs, ["i"]);
977    }
978
979    #[test]
980    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
981        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
982        assert_eq!(opts.std, Std::C11);
983        assert!(opts.gnu_extensions);
984
985        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
986        assert_eq!(opts.std, Std::C99);
987        assert!(!opts.gnu_extensions);
988
989        let (opts, _) = compile(&["-ansi", "a.c"]);
990        assert_eq!(opts.std, Std::C89);
991        assert!(!opts.gnu_extensions);
992
993        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
994        assert!(e.message.contains("unknown dialect"), "{}", e.message);
995    }
996
997    #[test]
998    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
999        let (opts, _) = compile(&["-dM", "a.c"]);
1000        assert!(opts.dumps.macros);
1001
1002        // Packed, the way GCC takes them, and a letter in the family we have not written yet
1003        // is accepted and does nothing rather than failing a build.
1004        let (opts, _) = compile(&["-dDM", "a.c"]);
1005        assert!(opts.dumps.macros);
1006        let (opts, _) = compile(&["-dD", "a.c"]);
1007        assert!(!opts.dumps.macros);
1008
1009        let (opts, _) = compile(&["a.c"]);
1010        assert!(!opts.dumps.any());
1011
1012        // `-dumpversion` is a different flag that happens to start the same way. We have not
1013        // written it, and saying so beats reading it as a dump of nothing.
1014        let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
1015        assert!(e.message.contains("unknown option"), "{}", e.message);
1016    }
1017
1018    #[test]
1019    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
1020        let (opts, _) = compile(&["a.c"]);
1021        assert_eq!(
1022            opts.gnuc,
1023            GnucVersion { major: 7, minor: 0, patch: 0 },
1024            "the lowest claim a modern glibc gives its own declarations to"
1025        );
1026
1027        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
1028        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
1029
1030        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
1031        // patchlevel and a harness that pastes that back has to be understood.
1032        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
1033        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
1034
1035        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
1036        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
1037
1038        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
1039        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
1040
1041        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
1042        assert!(e.message.contains("more than three"), "{}", e.message);
1043    }
1044
1045    #[test]
1046    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
1047        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
1048        assert!(opts.pedantic);
1049        assert_eq!(opts.std, Std::C17);
1050
1051        // The `-W` family's name for it, which is what a build that groups its warning flags
1052        // tends to write.
1053        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
1054        assert!(opts.pedantic);
1055
1056        let (opts, _) = compile(&["-std=c17", "a.c"]);
1057        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
1058    }
1059
1060    #[test]
1061    fn dash_p_and_dash_ffreestanding_reach_the_options() {
1062        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
1063        assert!(!opts.line_markers);
1064        assert!(!opts.hosted);
1065        assert_eq!(opts.emit, EmitKind::Preprocessed);
1066    }
1067
1068    /// Both spellings of both frame flags, since a build that wants one usually writes the
1069    /// other beside it for the one file that has to be compiled the ordinary way.
1070    #[test]
1071    fn the_two_frame_flags_are_read_in_both_directions() {
1072        let (opts, _) = compile(&["-c", "a.c"]);
1073        assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
1074        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
1075
1076        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
1077        assert!(opts.frame_pointer);
1078        assert!(!opts.red_zone);
1079
1080        let (opts, _) = compile(&[
1081            "-c",
1082            "-fno-omit-frame-pointer",
1083            "-fomit-frame-pointer",
1084            "-mno-red-zone",
1085            "-mred-zone",
1086            "a.c",
1087        ]);
1088        assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
1089        assert!(opts.red_zone);
1090    }
1091
1092    #[test]
1093    fn the_link_flags_are_collected_apart_from_the_compilation() {
1094        let (link, _) = linking(&[
1095            "-static",
1096            "-nostartfiles",
1097            "-rdynamic",
1098            "-s",
1099            "-fuse-ld=mold",
1100            "-L/opt/lib",
1101            "-B",
1102            "/opt/tools",
1103            "a.c",
1104        ]);
1105        assert!(link.is_static);
1106        assert!(link.no_startfiles);
1107        assert!(link.export_dynamic);
1108        assert!(link.strip);
1109        assert_eq!(link.use_ld.as_deref(), Some("mold"));
1110        assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
1111        assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
1112    }
1113
1114    #[test]
1115    fn a_comma_in_dash_wl_separates_two_arguments() {
1116        let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
1117        assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
1118    }
1119
1120    #[test]
1121    fn a_library_keeps_its_place_between_the_objects() {
1122        // Link order is semantic: `-lm` written between two files resolves for the one before
1123        // it and not for the one after, so a library cannot be collected into a list of its own.
1124        // The target is named because the suffix of an object is the target's and this asserts
1125        // on the names: the same command line on a Windows host plans two `.obj` files.
1126        let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
1127        let link = plan.link.expect("expected a link step");
1128        assert_eq!(
1129            link.inputs,
1130            vec![
1131                link::Item::File("a.o".into()),
1132                link::Item::Library("m".into()),
1133                link::Item::File("b.o".into()),
1134            ]
1135        );
1136        // And it is not a job, because there is nothing to compile in a library.
1137        assert_eq!(plan.jobs.len(), 2);
1138    }
1139
1140    #[test]
1141    fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1142        let (_, plan) = linking(&["-c", "-lm", "a.c"]);
1143        assert!(plan.link.is_none());
1144        assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
1145    }
1146
1147    #[test]
1148    fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
1149        let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
1150        assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
1151    }
1152
1153    #[test]
1154    fn usage_fits_on_a_screen() {
1155        // Not a style preference. A help text that scrolls is one nobody reads, and this is
1156        // the cheapest way to keep it honest as flags accumulate.
1157        assert!(USAGE.lines().count() < 34, "usage text has grown past one screen");
1158    }
1159}