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.5")]
28
29pub mod compile;
30pub mod library;
31mod map;
32pub mod phase;
33pub mod preprocess;
34pub mod schedule;
35
36use std::fmt::Write as _;
37use std::io::Write as _;
38use std::path::PathBuf;
39
40use rucc_session::{Dumps, EmitKind, Options, Session, Std, runtime};
41use rucc_target::Triple;
42
43pub use crate::compile::{Compiled, compile, compile_ir};
44pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
45pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
46pub use crate::schedule::Jobs;
47
48/// The compiler's version, taken from the workspace manifest.
49pub const VERSION: &str = env!("CARGO_PKG_VERSION");
50
51/// What the command line asked for.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Action {
54    /// Print usage and exit successfully.
55    Help,
56    /// Print the version and exit successfully.
57    Version,
58    /// Print the resolved configuration and exit successfully.
59    PrintConfig(Box<Options>),
60    /// Print the phase plan and exit successfully, which is what `-###` asks for.
61    PrintPlan(Box<Plan>),
62    /// Compile the given inputs.
63    Compile {
64        /// The resolved options.
65        opts: Box<Options>,
66        /// What to do to each input, and in what order.
67        plan: Box<Plan>,
68        /// How many translation units to compile at once.
69        jobs: Jobs,
70        /// Whether `-v` asked for the plan to be printed while it runs.
71        verbose: bool,
72    },
73}
74
75/// Why a command line was rejected.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct CliError {
78    /// The message, lowercase and without a trailing period, in the same shape as any other
79    /// diagnostic.
80    pub message: String,
81}
82
83impl std::fmt::Display for CliError {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.write_str(&self.message)
86    }
87}
88
89impl std::error::Error for CliError {}
90
91fn err(message: impl Into<String>) -> CliError {
92    CliError { message: message.into() }
93}
94
95/// Usage text.
96///
97/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
98/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
99pub const USAGE: &str = "\
100rucc, an optimizing C compiler
101
102usage: rucc [options] file...
103
104options:
105  -c                     compile and assemble, do not link
106  -S                     compile only, emit assembly
107  -E                     preprocess only
108  -o <file>              write output to <file>, or to standard output for -
109  -D <name>[=<value>], -U <name>      define a macro, or undefine one after every -D
110  -I <dir>               add <dir> to the include search path
111  -iquote -isystem -idirafter <dir>   the other chains, -nostdinc drops ours
112  --sysroot=<dir>        look for the library's headers under <dir>, -isysroot too
113  -P, -dM                with -E: leave out the markers, or dump the macros
114  -std=<dialect>         c89 through c23, and the gnu spellings
115  -fgnuc-version=<v>     the GCC release to claim, default 7.0.0
116  -x <lang>              treat later inputs as <lang>, or none to stop
117  -O<level>              optimize: 0, 1, 2, 3, s, z
118  -g, -fno-omit-frame-pointer, -mno-red-zone   debug info, keep a frame pointer, no red zone
119  -Werror -pedantic      warnings are errors, diagnose what the standard forbids
120  -j[n]                  compile n translation units at once, default all
121  -v, -###               print each phase as it runs, or without running any
122  --target=<triple>      generate code for <triple>
123  --emit=<kind>          exe, obj, asm, preprocessed, tast, ir, mir-final
124  --print-config         print the resolved configuration and exit
125  --version              print the version and exit
126  -h, --help             print this message and exit
127
128See spec/04-driver-and-cli.md for the full flag reference.
129";
130
131/// The argument of a flag that may be joined to it or may be the next word.
132///
133/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
134fn joined_or_next(
135    arg: &str,
136    at: usize,
137    args: &[String],
138    i: &mut usize,
139) -> Result<String, CliError> {
140    if arg.len() > at {
141        return Ok(arg[at..].to_owned());
142    }
143    let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
144    *i += 1;
145    Ok(next.clone())
146}
147
148/// Parses a command line, without the program name.
149///
150/// # Errors
151///
152/// Returns the message to print when the arguments do not name a compilation this compiler
153/// can attempt.
154pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
155    let host = Triple::host()
156        .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
157    let mut opts = Options::new(host);
158    let mut inputs: Vec<Input> = Vec::new();
159    let mut print_config = false;
160    let mut print_plan = false;
161    let mut verbose = false;
162    let mut jobs = Jobs::default();
163    let mut nostdinc = false;
164    let mut sysroot: Option<PathBuf> = None;
165    let mut output = None;
166    // `-x` applies to inputs that come after it and stays in effect until the next one, which
167    // is why it is tracked across the loop rather than attached to a single argument.
168    let mut forced: Option<InputKind> = None;
169
170    let mut i = 0;
171    while i < args.len() {
172        let arg = args[i].as_str();
173        i += 1;
174        match arg {
175            "-h" | "--help" => return Ok(Action::Help),
176            "--version" => return Ok(Action::Version),
177            "--print-config" => print_config = true,
178            "-###" => print_plan = true,
179            "-v" => verbose = true,
180            "-c" => opts.emit = EmitKind::Object,
181            "-S" => opts.emit = EmitKind::Asm,
182            "-E" => opts.emit = EmitKind::Preprocessed,
183            "-g" => opts.debug_info = true,
184            "-Werror" => opts.warnings_are_errors = true,
185            "-P" => opts.line_markers = false,
186            "-ansi" => {
187                opts.std = Std::C89;
188                opts.gnu_extensions = false;
189            }
190            // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
191            // the spelling a build system that groups its warning flags tends to write.
192            "-pedantic" | "-Wpedantic" => opts.pedantic = true,
193            "-ffreestanding" => opts.hosted = false,
194            "-fhosted" => opts.hosted = true,
195            // Both directions of each, because a build system that wants one of these usually
196            // writes it beside the flag that turns it back off for one directory.
197            "-fno-omit-frame-pointer" => opts.frame_pointer = true,
198            "-fomit-frame-pointer" => opts.frame_pointer = false,
199            "-mno-red-zone" => opts.red_zone = false,
200            "-mred-zone" => opts.red_zone = true,
201            // GCC drops its own include directory along with the system ones, because its
202            // headers are half of a pair with the library's and half a pair is worse than
203            // none. A build that passes this is supplying the whole set itself.
204            "-nostdinc" => nostdinc = true,
205            "-o" => {
206                output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
207                i += 1;
208            }
209            // The flags that take a directory only in the separated form. GCC spells them
210            // this way and nothing writes `-iquotedir`, so accepting the joined form would
211            // mean guessing at a path that starts with the flag's own letters.
212            // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
213            // two mean the same thing here: the configured directories are under there rather
214            // than under the root.
215            "-isysroot" => {
216                let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
217                i += 1;
218                sysroot = Some(PathBuf::from(dir));
219            }
220            "-iquote" | "-isystem" | "-idirafter" => {
221                let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
222                i += 1;
223                match arg {
224                    "-iquote" => opts.search.push_quote(dir.clone()),
225                    "-isystem" => opts.search.push_system(dir.clone()),
226                    _ => opts.search.push_after(dir.clone()),
227                }
228            }
229            "-x" => {
230                let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
231                i += 1;
232                forced = if lang == "none" {
233                    None
234                } else {
235                    Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
236                };
237            }
238            // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
239            // translation units in one process rather than making the build system fork, and
240            // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
241            // to exist and has to be spelled the way `make` spells it.
242            // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
243            // and a build system may produce either, so both are read here rather than
244            // being normalised by whatever generated the command line.
245            _ if arg.starts_with("-D") => {
246                let value = joined_or_next(arg, 2, args, &mut i)?;
247                opts.defines.push(value);
248            }
249            _ if arg.starts_with("-U") => {
250                let value = joined_or_next(arg, 2, args, &mut i)?;
251                opts.undefines.push(value);
252            }
253            _ if arg.starts_with("-I") => {
254                let dir = joined_or_next(arg, 2, args, &mut i)?;
255                opts.search.push_bracket(dir);
256            }
257            _ if arg.starts_with("-std=") => {
258                let name = &arg["-std=".len()..];
259                let (std, gnu) = Std::from_flag(name)
260                    .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
261                opts.std = std;
262                opts.gnu_extensions = gnu;
263            }
264            // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
265            // handed, so a differential run that does not set it is comparing two compilers
266            // that believe they are different compilers.
267            // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
268            // that we have not written yet are accepted and ignored, because a dump is a
269            // debugging aid and a build that asks for one should still compile. A letter
270            // outside the family falls through to the unknown option error, which is what
271            // keeps `-dumpversion` from being read as a dump of nothing.
272            _ if Dumps::is_family(arg) => {
273                opts.dumps.add(&arg[2..]);
274            }
275            _ if arg.starts_with("-fgnuc-version=") => {
276                let v = &arg["-fgnuc-version=".len()..];
277                opts.gnuc = v.parse().map_err(err)?;
278            }
279            // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
280            // than the unknown option one, because a build reaching for it is asking for a feature
281            // and deserves to be told it is not coming rather than told the spelling is wrong.
282            // The negative form is what this compiler does anyway, so it is taken and dropped.
283            "-fnested-functions" => {
284                return Err(err(
285                    "nested functions are not supported: a call to one goes through a trampoline \
286                     written on the stack, which no target that enforces an unexecutable stack \
287                     allows",
288                ));
289            }
290            "-fno-nested-functions" => {}
291            _ if arg.starts_with("-j") => {
292                jobs = Jobs::parse(&arg[2..]).map_err(err)?;
293            }
294            _ if arg.starts_with("--sysroot=") => {
295                sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
296            }
297            _ if arg.starts_with("--target=") => {
298                let t = &arg["--target=".len()..];
299                opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
300            }
301            _ if arg.starts_with("--emit=") => {
302                let k = &arg["--emit=".len()..];
303                opts.emit = k
304                    .parse()
305                    .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
306            }
307            _ if arg.starts_with("-O") => {
308                opts.opt_level = arg[2..]
309                    .parse()
310                    .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
311            }
312            _ if arg.starts_with('-') && arg.len() > 1 => {
313                // Silently ignoring an unknown flag is how a build ends up not doing what
314                // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
315                // for the flags that change code generation, and the safe default until the
316                // flag table is populated is to reject everything we do not know.
317                return Err(err(format!("unknown option `{arg}`")));
318            }
319            _ => inputs.push(Input { path: arg.to_owned(), forced }),
320        }
321    }
322
323    // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
324    // order: a directory the user names outranks the compiler's own, and the compiler's own
325    // outranks the library's. It is pushed after the loop rather than before it because
326    // `SearchPath` appends within a group and the position is what the order is.
327    if !nostdinc {
328        opts.search.push_system(runtime::DIR);
329        // And the library's after ours, which is the other half of the same order. They go on
330        // here rather than at the point `--target=` or `--sysroot=` was read because either
331        // one changes the answer and the last word on both is the end of the loop.
332        for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
333            opts.search.push_system(dir);
334        }
335    }
336    // Once, here, rather than as each directory is pushed. A `-I` that names a system
337    // directory has to lose to the system entry and the system entry is added last, so the
338    // question cannot be answered until the whole path is known.
339    opts.search.remove_duplicates();
340
341    // The target has to be resolved before the configuration is printed, so this check comes
342    // after the loop rather than at the point `--print-config` was seen.
343    if print_config {
344        return Ok(Action::PrintConfig(Box::new(opts)));
345    }
346    let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
347    if print_plan {
348        return Ok(Action::PrintPlan(Box::new(plan)));
349    }
350    Ok(Action::Compile { opts: Box::new(opts), plan: Box::new(plan), jobs, verbose })
351}
352
353/// Renders the resolved configuration.
354///
355/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
356/// this output is diffed across hosts in CI and a reordering would read as a change.
357#[must_use]
358pub fn print_config(opts: &Options) -> String {
359    let sess = Session::new(opts.clone());
360    let t = &sess.target;
361    let mut out = String::new();
362    let _ = writeln!(out, "version: {VERSION}");
363    let _ = writeln!(out, "target: {}", t.triple);
364    let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
365    let _ = writeln!(out, "os: {}", t.triple.os.as_str());
366    let _ = writeln!(out, "env: {}", t.triple.env.as_str());
367    let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
368    let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
369    let _ = writeln!(out, "long-width: {}", t.long_width);
370    let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
371    let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
372    let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
373    let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
374    // The register file as a count per class, which is enough to tell a target whose registers
375    // are described from one whose are not without printing sixteen names nobody asked for.
376    let regs: Vec<String> = t
377        .regs
378        .classes()
379        .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
380        .collect();
381    let _ = writeln!(
382        out,
383        "registers: {}",
384        if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
385    );
386    let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
387    let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
388    let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
389    let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
390    let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
391    // Last because it is the one key with more than one line under it, and the only one
392    // whose value is a property of the machine rather than of the command line.
393    for dir in sess.opts.search.dirs() {
394        let system = if dir.is_system { " (system)" } else { "" };
395        let _ = writeln!(out, "include: {}{system}", dir.path.display());
396    }
397    out
398}
399
400/// Runs phase 4 over every input that has one, and writes what came out.
401///
402/// One input that fails does not stop the others. A build that reports every file it could
403/// not preprocess in one run is worth more than one that stops at the first, and the exit
404/// status is still a failure either way.
405fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
406    let fs = OsFileSystem::new();
407    let mut stderr = std::io::stderr().lock();
408    let mut failed = false;
409    for job in &plan.jobs {
410        if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
411            // An input that is already preprocessed, or an object file. GCC passes these
412            // through untouched, and the plan has already said so in its notes.
413            continue;
414        }
415        let result = preprocess(opts, &job.input, &fs);
416        for message in &result.messages {
417            let _ = writeln!(stderr, "{message}");
418        }
419        if result.failed() {
420            failed = true;
421            continue;
422        }
423        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
424            let _ = writeln!(stderr, "rucc: error: {e}");
425            failed = true;
426        }
427    }
428    i32::from(failed)
429}
430
431/// Runs the front end over every input that has a compile phase, and writes what came out.
432///
433/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
434/// exit status is a failure either way. An input that is already assembly or an object has no
435/// compile phase and is passed over here, which the plan has already said in its notes.
436fn compile_all(opts: &Options, plan: &Plan) -> i32 {
437    let fs = OsFileSystem::new();
438    let mut stderr = std::io::stderr().lock();
439    let mut failed = false;
440    for job in &plan.jobs {
441        if !job.phases.contains(&Phase::Compile) {
442            continue;
443        }
444        // An input of IR is read back rather than compiled, since the C it came from is not
445        // here any more. Everything after this is the same, so the two paths meet again at the
446        // messages and the file the result is written to.
447        let result = if job.kind == InputKind::Ir {
448            compile_ir(opts, &job.input, &fs)
449        } else {
450            compile(opts, &job.input, &fs)
451        };
452        for message in &result.messages {
453            let _ = writeln!(stderr, "{message}");
454        }
455        if result.failed() {
456            failed = true;
457            continue;
458        }
459        if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
460            let _ = writeln!(stderr, "rucc: error: {e}");
461            failed = true;
462        }
463    }
464    i32::from(failed)
465}
466
467/// Writes one job's result where the plan said it goes.
468///
469/// # Errors
470///
471/// Returns the message to print, which names the file when there is one, because "permission
472/// denied" on its own does not say which file was refused.
473fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
474    match output {
475        Output::Stdout => {
476            let mut stdout = std::io::stdout().lock();
477            stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
478        }
479        Output::File(path) | Output::Temporary(path) => {
480            std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
481        }
482    }
483}
484
485/// Runs the driver and returns the process exit code.
486///
487/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
488/// is the one place in the compiler that is true.
489pub fn run(args: &[String]) -> i32 {
490    match parse_args(args) {
491        Ok(Action::Help) => {
492            print!("{USAGE}");
493            0
494        }
495        Ok(Action::Version) => {
496            println!("rucc {VERSION}");
497            0
498        }
499        Ok(Action::PrintConfig(opts)) => {
500            print!("{}", print_config(&opts));
501            0
502        }
503        Ok(Action::PrintPlan(plan)) => {
504            print!("{}", plan.render());
505            0
506        }
507        Ok(Action::Compile { opts, plan, jobs, verbose }) => {
508            {
509                let mut stderr = std::io::stderr().lock();
510                if verbose {
511                    let _ = write!(stderr, "{}", plan.render());
512                    let _ = writeln!(stderr, "workers: {}", jobs.count());
513                }
514            }
515            if opts.emit == EmitKind::Preprocessed {
516                return preprocess_all(&opts, &plan);
517            }
518            if matches!(
519                opts.emit,
520                EmitKind::Tast | EmitKind::Ir | EmitKind::MirFinal | EmitKind::Asm
521            ) {
522                return compile_all(&opts, &plan);
523            }
524            let mut stderr = std::io::stderr().lock();
525            // An object and an executable are the rest of M3 in spec/17-milestones.md. The plan
526            // above is real and can be inspected with `-###`. Saying so is better than a panic,
527            // and better than pretending to have produced an object.
528            let _ = writeln!(
529                stderr,
530                "rucc: error: running the {} phase is not implemented yet; \
531                 use -E for preprocessed output, and see spec/17-milestones.md for the rest",
532                opts.emit.as_str()
533            );
534            1
535        }
536        Err(e) => {
537            let mut stderr = std::io::stderr().lock();
538            let _ = writeln!(stderr, "rucc: error: {e}");
539            let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
540            1
541        }
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use rucc_session::{GnucVersion, OptLevel};
548
549    use super::*;
550
551    fn args(s: &[&str]) -> Vec<String> {
552        s.iter().map(|x| (*x).to_owned()).collect()
553    }
554
555    #[test]
556    fn help_and_version_win_over_everything_else() {
557        assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
558        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
559    }
560
561    fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
562        match parse_args(&args(s)).expect("expected a compilation") {
563            Action::Compile { opts, plan, .. } => (opts, plan),
564            other => panic!("expected a compilation, got {other:?}"),
565        }
566    }
567
568    #[test]
569    fn collects_inputs_and_flags() {
570        let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
571        let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
572        assert_eq!(paths, vec!["a.c", "b.c"]);
573        assert_eq!(opts.opt_level, OptLevel::O2);
574        assert_eq!(opts.emit, EmitKind::Object);
575        assert!(opts.debug_info);
576    }
577
578    #[test]
579    fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
580        let (opts, _) = compile(&["-O", "a.c"]);
581        assert_eq!(opts.opt_level, OptLevel::O1);
582    }
583
584    #[test]
585    fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
586        let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
587        assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
588        assert_eq!(plan.jobs[1].kind, InputKind::C);
589        assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
590    }
591
592    #[test]
593    fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
594        let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
595            Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
596            other => panic!("expected a compilation, got {other:?}"),
597        };
598        assert_eq!(jobs.count(), 4);
599
600        let default = match parse_args(&args(&["a.c"])).unwrap() {
601            Action::Compile { jobs, .. } => jobs,
602            other => panic!("expected a compilation, got {other:?}"),
603        };
604        assert_eq!(default, Jobs::available());
605        assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
606    }
607
608    #[test]
609    fn triple_hash_prints_the_plan_and_runs_nothing() {
610        let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
611        let Action::PrintPlan(plan) = a else { panic!("expected a plan dump") };
612        assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
613    }
614
615    #[test]
616    fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
617        let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
618        assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
619    }
620
621    #[test]
622    fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
623        let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
624        assert!(e.message.contains("unknown option"), "{}", e.message);
625    }
626
627    #[test]
628    fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
629        let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
630        assert!(e.message.contains("trampoline"), "{}", e.message);
631        assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
632    }
633
634    #[test]
635    fn an_unsupported_target_names_itself() {
636        let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
637        assert!(e.message.contains("sparc64"), "{}", e.message);
638    }
639
640    #[test]
641    fn no_inputs_is_an_error_but_print_config_needs_none() {
642        assert!(parse_args(&args(&[])).is_err());
643        assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
644    }
645
646    #[test]
647    fn print_config_reports_the_target_it_was_given_not_the_host() {
648        let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
649        let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
650        let text = print_config(&opts);
651        assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
652        assert!(text.contains("char-signed: false"), "{text}");
653        assert!(text.contains("object-format: elf"), "{text}");
654        assert!(text.contains("va-list: void-pointer"), "{text}");
655        // RISC-V has a register file and this compiler has not written it down yet, and the
656        // dump says which of those two it is rather than leaving the line out.
657        assert!(text.contains("registers: none"), "{text}");
658    }
659
660    #[test]
661    fn print_config_has_one_key_per_line_and_a_fixed_order() {
662        let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
663        let text = print_config(&opts);
664        let keys: Vec<&str> =
665            text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
666        assert_eq!(keys[0], "version");
667        assert_eq!(keys[1], "target");
668        assert_eq!(keys.len(), 18);
669        assert!(text.ends_with('\n'));
670    }
671
672    #[test]
673    fn dash_o_needs_an_argument() {
674        let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
675        assert_eq!(e.message, "-o requires an argument");
676    }
677
678    #[test]
679    fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
680        let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
681        assert_eq!(opts.defines, ["FOO=1", "BAR"]);
682        assert_eq!(opts.undefines, ["BAZ", "QUX"]);
683    }
684
685    #[test]
686    fn the_include_flags_land_on_the_chain_each_one_names() {
687        // A sysroot with nothing under it, so that the library's own directories are the
688        // same on every machine this test runs on, which is none of them.
689        let (opts, _) = compile(&[
690            "-Ii",
691            "-iquote",
692            "q",
693            "-isystem",
694            "sys",
695            "-idirafter",
696            "after",
697            "--sysroot=/nowhere-at-all",
698            "a.c",
699        ]);
700        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
701        // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
702        // which is where GCC puts its own: a directory the user named outranks ours.
703        assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
704        assert!(!opts.search.dirs()[1].is_system);
705        assert!(opts.search.dirs()[2].is_system);
706    }
707
708    #[test]
709    fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
710        // Which machine this runs on decides what is on the path, so the test is about the
711        // order rather than about the names: ours is on it, the library's follow it, and
712        // `-nostdinc` is the one flag that takes both halves of the pair off at once.
713        let (opts, _) = compile(&["a.c"]);
714        let dirs = opts.search.dirs();
715        let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
716        assert_eq!(ours, Some(0), "{dirs:?}");
717        assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
718        let (bare, _) = compile(&["-nostdinc", "a.c"]);
719        assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
720    }
721
722    #[test]
723    fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
724        let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
725        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
726        assert_eq!(dirs, ["sys", runtime::DIR]);
727    }
728
729    #[test]
730    fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
731        let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
732        let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
733        assert_eq!(dirs, ["i"]);
734    }
735
736    #[test]
737    fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
738        let (opts, _) = compile(&["-std=gnu11", "a.c"]);
739        assert_eq!(opts.std, Std::C11);
740        assert!(opts.gnu_extensions);
741
742        let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
743        assert_eq!(opts.std, Std::C99);
744        assert!(!opts.gnu_extensions);
745
746        let (opts, _) = compile(&["-ansi", "a.c"]);
747        assert_eq!(opts.std, Std::C89);
748        assert!(!opts.gnu_extensions);
749
750        let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
751        assert!(e.message.contains("unknown dialect"), "{}", e.message);
752    }
753
754    #[test]
755    fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
756        let (opts, _) = compile(&["-dM", "a.c"]);
757        assert!(opts.dumps.macros);
758
759        // Packed, the way GCC takes them, and a letter in the family we have not written yet
760        // is accepted and does nothing rather than failing a build.
761        let (opts, _) = compile(&["-dDM", "a.c"]);
762        assert!(opts.dumps.macros);
763        let (opts, _) = compile(&["-dD", "a.c"]);
764        assert!(!opts.dumps.macros);
765
766        let (opts, _) = compile(&["a.c"]);
767        assert!(!opts.dumps.any());
768
769        // `-dumpversion` is a different flag that happens to start the same way. We have not
770        // written it, and saying so beats reading it as a dump of nothing.
771        let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
772        assert!(e.message.contains("unknown option"), "{}", e.message);
773    }
774
775    #[test]
776    fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
777        let (opts, _) = compile(&["a.c"]);
778        assert_eq!(
779            opts.gnuc,
780            GnucVersion { major: 7, minor: 0, patch: 0 },
781            "the lowest claim a modern glibc gives its own declarations to"
782        );
783
784        let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
785        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
786
787        // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
788        // patchlevel and a harness that pastes that back has to be understood.
789        let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
790        assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
791
792        let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
793        assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
794
795        let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
796        assert!(e.message.contains("minor that is not a number"), "{}", e.message);
797
798        let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
799        assert!(e.message.contains("more than three"), "{}", e.message);
800    }
801
802    #[test]
803    fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
804        let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
805        assert!(opts.pedantic);
806        assert_eq!(opts.std, Std::C17);
807
808        // The `-W` family's name for it, which is what a build that groups its warning flags
809        // tends to write.
810        let (opts, _) = compile(&["-Wpedantic", "a.c"]);
811        assert!(opts.pedantic);
812
813        let (opts, _) = compile(&["-std=c17", "a.c"]);
814        assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
815    }
816
817    #[test]
818    fn dash_p_and_dash_ffreestanding_reach_the_options() {
819        let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
820        assert!(!opts.line_markers);
821        assert!(!opts.hosted);
822        assert_eq!(opts.emit, EmitKind::Preprocessed);
823    }
824
825    /// Both spellings of both frame flags, since a build that wants one usually writes the
826    /// other beside it for the one file that has to be compiled the ordinary way.
827    #[test]
828    fn the_two_frame_flags_are_read_in_both_directions() {
829        let (opts, _) = compile(&["-c", "a.c"]);
830        assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
831        assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
832
833        let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
834        assert!(opts.frame_pointer);
835        assert!(!opts.red_zone);
836
837        let (opts, _) = compile(&[
838            "-c",
839            "-fno-omit-frame-pointer",
840            "-fomit-frame-pointer",
841            "-mno-red-zone",
842            "-mred-zone",
843            "a.c",
844        ]);
845        assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
846        assert!(opts.red_zone);
847    }
848
849    #[test]
850    fn usage_fits_on_a_screen() {
851        // Not a style preference. A help text that scrolls is one nobody reads, and this is
852        // the cheapest way to keep it honest as flags accumulate.
853        assert!(USAGE.lines().count() < 30, "usage text has grown past one screen");
854    }
855}