1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.3.1")]
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
48pub const VERSION: &str = env!("CARGO_PKG_VERSION");
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Action {
54 Help,
56 Version,
58 PrintConfig(Box<Options>),
60 PrintPlan(Box<Plan>),
62 Compile {
64 opts: Box<Options>,
66 plan: Box<Plan>,
68 jobs: Jobs,
70 verbose: bool,
72 },
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct CliError {
78 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
95pub 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 emit debug information
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
131fn 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
148pub 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 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 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
193 "-ffreestanding" => opts.hosted = false,
194 "-fhosted" => opts.hosted = true,
195 "-nostdinc" => nostdinc = true,
199 "-o" => {
200 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
201 i += 1;
202 }
203 "-isysroot" => {
210 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
211 i += 1;
212 sysroot = Some(PathBuf::from(dir));
213 }
214 "-iquote" | "-isystem" | "-idirafter" => {
215 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
216 i += 1;
217 match arg {
218 "-iquote" => opts.search.push_quote(dir.clone()),
219 "-isystem" => opts.search.push_system(dir.clone()),
220 _ => opts.search.push_after(dir.clone()),
221 }
222 }
223 "-x" => {
224 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
225 i += 1;
226 forced = if lang == "none" {
227 None
228 } else {
229 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
230 };
231 }
232 _ if arg.starts_with("-D") => {
240 let value = joined_or_next(arg, 2, args, &mut i)?;
241 opts.defines.push(value);
242 }
243 _ if arg.starts_with("-U") => {
244 let value = joined_or_next(arg, 2, args, &mut i)?;
245 opts.undefines.push(value);
246 }
247 _ if arg.starts_with("-I") => {
248 let dir = joined_or_next(arg, 2, args, &mut i)?;
249 opts.search.push_bracket(dir);
250 }
251 _ if arg.starts_with("-std=") => {
252 let name = &arg["-std=".len()..];
253 let (std, gnu) = Std::from_flag(name)
254 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
255 opts.std = std;
256 opts.gnu_extensions = gnu;
257 }
258 _ if Dumps::is_family(arg) => {
267 opts.dumps.add(&arg[2..]);
268 }
269 _ if arg.starts_with("-fgnuc-version=") => {
270 let v = &arg["-fgnuc-version=".len()..];
271 opts.gnuc = v.parse().map_err(err)?;
272 }
273 "-fnested-functions" => {
278 return Err(err(
279 "nested functions are not supported: a call to one goes through a trampoline \
280 written on the stack, which no target that enforces an unexecutable stack \
281 allows",
282 ));
283 }
284 "-fno-nested-functions" => {}
285 _ if arg.starts_with("-j") => {
286 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
287 }
288 _ if arg.starts_with("--sysroot=") => {
289 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
290 }
291 _ if arg.starts_with("--target=") => {
292 let t = &arg["--target=".len()..];
293 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
294 }
295 _ if arg.starts_with("--emit=") => {
296 let k = &arg["--emit=".len()..];
297 opts.emit = k
298 .parse()
299 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
300 }
301 _ if arg.starts_with("-O") => {
302 opts.opt_level = arg[2..]
303 .parse()
304 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
305 }
306 _ if arg.starts_with('-') && arg.len() > 1 => {
307 return Err(err(format!("unknown option `{arg}`")));
312 }
313 _ => inputs.push(Input { path: arg.to_owned(), forced }),
314 }
315 }
316
317 if !nostdinc {
322 opts.search.push_system(runtime::DIR);
323 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
327 opts.search.push_system(dir);
328 }
329 }
330 opts.search.remove_duplicates();
334
335 if print_config {
338 return Ok(Action::PrintConfig(Box::new(opts)));
339 }
340 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
341 if print_plan {
342 return Ok(Action::PrintPlan(Box::new(plan)));
343 }
344 Ok(Action::Compile { opts: Box::new(opts), plan: Box::new(plan), jobs, verbose })
345}
346
347#[must_use]
352pub fn print_config(opts: &Options) -> String {
353 let sess = Session::new(opts.clone());
354 let t = &sess.target;
355 let mut out = String::new();
356 let _ = writeln!(out, "version: {VERSION}");
357 let _ = writeln!(out, "target: {}", t.triple);
358 let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
359 let _ = writeln!(out, "os: {}", t.triple.os.as_str());
360 let _ = writeln!(out, "env: {}", t.triple.env.as_str());
361 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
362 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
363 let _ = writeln!(out, "long-width: {}", t.long_width);
364 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
365 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
366 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
367 let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
368 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
369 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
370 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
371 for dir in sess.opts.search.dirs() {
374 let system = if dir.is_system { " (system)" } else { "" };
375 let _ = writeln!(out, "include: {}{system}", dir.path.display());
376 }
377 out
378}
379
380fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
386 let fs = OsFileSystem::new();
387 let mut stderr = std::io::stderr().lock();
388 let mut failed = false;
389 for job in &plan.jobs {
390 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
391 continue;
394 }
395 let result = preprocess(opts, &job.input, &fs);
396 for message in &result.messages {
397 let _ = writeln!(stderr, "{message}");
398 }
399 if result.failed() {
400 failed = true;
401 continue;
402 }
403 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
404 let _ = writeln!(stderr, "rucc: error: {e}");
405 failed = true;
406 }
407 }
408 i32::from(failed)
409}
410
411fn compile_all(opts: &Options, plan: &Plan) -> i32 {
417 let fs = OsFileSystem::new();
418 let mut stderr = std::io::stderr().lock();
419 let mut failed = false;
420 for job in &plan.jobs {
421 if !job.phases.contains(&Phase::Compile) {
422 continue;
423 }
424 let result = if job.kind == InputKind::Ir {
428 compile_ir(opts, &job.input, &fs)
429 } else {
430 compile(opts, &job.input, &fs)
431 };
432 for message in &result.messages {
433 let _ = writeln!(stderr, "{message}");
434 }
435 if result.failed() {
436 failed = true;
437 continue;
438 }
439 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
440 let _ = writeln!(stderr, "rucc: error: {e}");
441 failed = true;
442 }
443 }
444 i32::from(failed)
445}
446
447fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
454 match output {
455 Output::Stdout => {
456 let mut stdout = std::io::stdout().lock();
457 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
458 }
459 Output::File(path) | Output::Temporary(path) => {
460 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
461 }
462 }
463}
464
465pub fn run(args: &[String]) -> i32 {
470 match parse_args(args) {
471 Ok(Action::Help) => {
472 print!("{USAGE}");
473 0
474 }
475 Ok(Action::Version) => {
476 println!("rucc {VERSION}");
477 0
478 }
479 Ok(Action::PrintConfig(opts)) => {
480 print!("{}", print_config(&opts));
481 0
482 }
483 Ok(Action::PrintPlan(plan)) => {
484 print!("{}", plan.render());
485 0
486 }
487 Ok(Action::Compile { opts, plan, jobs, verbose }) => {
488 {
489 let mut stderr = std::io::stderr().lock();
490 if verbose {
491 let _ = write!(stderr, "{}", plan.render());
492 let _ = writeln!(stderr, "workers: {}", jobs.count());
493 }
494 }
495 if opts.emit == EmitKind::Preprocessed {
496 return preprocess_all(&opts, &plan);
497 }
498 if matches!(opts.emit, EmitKind::Tast | EmitKind::Ir) {
499 return compile_all(&opts, &plan);
500 }
501 let mut stderr = std::io::stderr().lock();
502 let _ = writeln!(
506 stderr,
507 "rucc: error: running the {} phase is not implemented yet; \
508 use -E for preprocessed output, and see spec/17-milestones.md for the rest",
509 opts.emit.as_str()
510 );
511 1
512 }
513 Err(e) => {
514 let mut stderr = std::io::stderr().lock();
515 let _ = writeln!(stderr, "rucc: error: {e}");
516 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
517 1
518 }
519 }
520}
521
522#[cfg(test)]
523mod tests {
524 use rucc_session::{GnucVersion, OptLevel};
525
526 use super::*;
527
528 fn args(s: &[&str]) -> Vec<String> {
529 s.iter().map(|x| (*x).to_owned()).collect()
530 }
531
532 #[test]
533 fn help_and_version_win_over_everything_else() {
534 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
535 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
536 }
537
538 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
539 match parse_args(&args(s)).expect("expected a compilation") {
540 Action::Compile { opts, plan, .. } => (opts, plan),
541 other => panic!("expected a compilation, got {other:?}"),
542 }
543 }
544
545 #[test]
546 fn collects_inputs_and_flags() {
547 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
548 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
549 assert_eq!(paths, vec!["a.c", "b.c"]);
550 assert_eq!(opts.opt_level, OptLevel::O2);
551 assert_eq!(opts.emit, EmitKind::Object);
552 assert!(opts.debug_info);
553 }
554
555 #[test]
556 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
557 let (opts, _) = compile(&["-O", "a.c"]);
558 assert_eq!(opts.opt_level, OptLevel::O1);
559 }
560
561 #[test]
562 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
563 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
564 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
565 assert_eq!(plan.jobs[1].kind, InputKind::C);
566 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
567 }
568
569 #[test]
570 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
571 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
572 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
573 other => panic!("expected a compilation, got {other:?}"),
574 };
575 assert_eq!(jobs.count(), 4);
576
577 let default = match parse_args(&args(&["a.c"])).unwrap() {
578 Action::Compile { jobs, .. } => jobs,
579 other => panic!("expected a compilation, got {other:?}"),
580 };
581 assert_eq!(default, Jobs::available());
582 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
583 }
584
585 #[test]
586 fn triple_hash_prints_the_plan_and_runs_nothing() {
587 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
588 let Action::PrintPlan(plan) = a else { panic!("expected a plan dump") };
589 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
590 }
591
592 #[test]
593 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
594 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
595 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
596 }
597
598 #[test]
599 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
600 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
601 assert!(e.message.contains("unknown option"), "{}", e.message);
602 }
603
604 #[test]
605 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
606 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
607 assert!(e.message.contains("trampoline"), "{}", e.message);
608 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
609 }
610
611 #[test]
612 fn an_unsupported_target_names_itself() {
613 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
614 assert!(e.message.contains("sparc64"), "{}", e.message);
615 }
616
617 #[test]
618 fn no_inputs_is_an_error_but_print_config_needs_none() {
619 assert!(parse_args(&args(&[])).is_err());
620 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
621 }
622
623 #[test]
624 fn print_config_reports_the_target_it_was_given_not_the_host() {
625 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
626 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
627 let text = print_config(&opts);
628 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
629 assert!(text.contains("char-signed: false"), "{text}");
630 assert!(text.contains("object-format: elf"), "{text}");
631 assert!(text.contains("va-list: void-pointer"), "{text}");
632 }
633
634 #[test]
635 fn print_config_has_one_key_per_line_and_a_fixed_order() {
636 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
637 let text = print_config(&opts);
638 let keys: Vec<&str> =
639 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
640 assert_eq!(keys[0], "version");
641 assert_eq!(keys[1], "target");
642 assert_eq!(keys.len(), 15);
643 assert!(text.ends_with('\n'));
644 }
645
646 #[test]
647 fn dash_o_needs_an_argument() {
648 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
649 assert_eq!(e.message, "-o requires an argument");
650 }
651
652 #[test]
653 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
654 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
655 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
656 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
657 }
658
659 #[test]
660 fn the_include_flags_land_on_the_chain_each_one_names() {
661 let (opts, _) = compile(&[
664 "-Ii",
665 "-iquote",
666 "q",
667 "-isystem",
668 "sys",
669 "-idirafter",
670 "after",
671 "--sysroot=/nowhere-at-all",
672 "a.c",
673 ]);
674 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
675 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
678 assert!(!opts.search.dirs()[1].is_system);
679 assert!(opts.search.dirs()[2].is_system);
680 }
681
682 #[test]
683 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
684 let (opts, _) = compile(&["a.c"]);
688 let dirs = opts.search.dirs();
689 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
690 assert_eq!(ours, Some(0), "{dirs:?}");
691 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
692 let (bare, _) = compile(&["-nostdinc", "a.c"]);
693 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
694 }
695
696 #[test]
697 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
698 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
699 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
700 assert_eq!(dirs, ["sys", runtime::DIR]);
701 }
702
703 #[test]
704 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
705 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
706 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
707 assert_eq!(dirs, ["i"]);
708 }
709
710 #[test]
711 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
712 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
713 assert_eq!(opts.std, Std::C11);
714 assert!(opts.gnu_extensions);
715
716 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
717 assert_eq!(opts.std, Std::C99);
718 assert!(!opts.gnu_extensions);
719
720 let (opts, _) = compile(&["-ansi", "a.c"]);
721 assert_eq!(opts.std, Std::C89);
722 assert!(!opts.gnu_extensions);
723
724 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
725 assert!(e.message.contains("unknown dialect"), "{}", e.message);
726 }
727
728 #[test]
729 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
730 let (opts, _) = compile(&["-dM", "a.c"]);
731 assert!(opts.dumps.macros);
732
733 let (opts, _) = compile(&["-dDM", "a.c"]);
736 assert!(opts.dumps.macros);
737 let (opts, _) = compile(&["-dD", "a.c"]);
738 assert!(!opts.dumps.macros);
739
740 let (opts, _) = compile(&["a.c"]);
741 assert!(!opts.dumps.any());
742
743 let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
746 assert!(e.message.contains("unknown option"), "{}", e.message);
747 }
748
749 #[test]
750 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
751 let (opts, _) = compile(&["a.c"]);
752 assert_eq!(
753 opts.gnuc,
754 GnucVersion { major: 7, minor: 0, patch: 0 },
755 "the lowest claim a modern glibc gives its own declarations to"
756 );
757
758 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
759 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
760
761 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
764 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
765
766 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
767 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
768
769 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
770 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
771
772 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
773 assert!(e.message.contains("more than three"), "{}", e.message);
774 }
775
776 #[test]
777 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
778 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
779 assert!(opts.pedantic);
780 assert_eq!(opts.std, Std::C17);
781
782 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
785 assert!(opts.pedantic);
786
787 let (opts, _) = compile(&["-std=c17", "a.c"]);
788 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
789 }
790
791 #[test]
792 fn dash_p_and_dash_ffreestanding_reach_the_options() {
793 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
794 assert!(!opts.line_markers);
795 assert!(!opts.hosted);
796 assert_eq!(opts.emit, EmitKind::Preprocessed);
797 }
798
799 #[test]
800 fn usage_fits_on_a_screen() {
801 assert!(USAGE.lines().count() < 30, "usage text has grown past one screen");
804 }
805}