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