1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.2.17")]
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, runtime};
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
46pub const VERSION: &str = env!("CARGO_PKG_VERSION");
48
49#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum Action {
52 Help,
54 Version,
56 PrintConfig(Box<Options>),
58 PrintPlan(Box<Plan>),
60 Compile {
62 opts: Box<Options>,
64 plan: Box<Plan>,
66 jobs: Jobs,
68 verbose: bool,
70 },
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct CliError {
76 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
93pub 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 chains, -nostdinc drops ours
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
129fn 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
146pub 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 nostdinc = false;
162 let mut output = None;
163 let mut forced: Option<InputKind> = None;
166
167 let mut i = 0;
168 while i < args.len() {
169 let arg = args[i].as_str();
170 i += 1;
171 match arg {
172 "-h" | "--help" => return Ok(Action::Help),
173 "--version" => return Ok(Action::Version),
174 "--print-config" => print_config = true,
175 "-###" => print_plan = true,
176 "-v" => verbose = true,
177 "-c" => opts.emit = EmitKind::Object,
178 "-S" => opts.emit = EmitKind::Asm,
179 "-E" => opts.emit = EmitKind::Preprocessed,
180 "-g" => opts.debug_info = true,
181 "-Werror" => opts.warnings_are_errors = true,
182 "-P" => opts.line_markers = false,
183 "-ansi" => {
184 opts.std = Std::C89;
185 opts.gnu_extensions = false;
186 }
187 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
190 "-ffreestanding" => opts.hosted = false,
191 "-fhosted" => opts.hosted = true,
192 "-nostdinc" => nostdinc = true,
196 "-o" => {
197 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
198 i += 1;
199 }
200 "-iquote" | "-isystem" | "-idirafter" => {
204 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
205 i += 1;
206 match arg {
207 "-iquote" => opts.search.push_quote(dir.clone()),
208 "-isystem" => opts.search.push_system(dir.clone()),
209 _ => opts.search.push_after(dir.clone()),
210 }
211 }
212 "-x" => {
213 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
214 i += 1;
215 forced = if lang == "none" {
216 None
217 } else {
218 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
219 };
220 }
221 _ if arg.starts_with("-D") => {
229 let value = joined_or_next(arg, 2, args, &mut i)?;
230 opts.defines.push(value);
231 }
232 _ if arg.starts_with("-U") => {
233 let value = joined_or_next(arg, 2, args, &mut i)?;
234 opts.undefines.push(value);
235 }
236 _ if arg.starts_with("-I") => {
237 let dir = joined_or_next(arg, 2, args, &mut i)?;
238 opts.search.push_bracket(dir);
239 }
240 _ if arg.starts_with("-std=") => {
241 let name = &arg["-std=".len()..];
242 let (std, gnu) = Std::from_flag(name)
243 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
244 opts.std = std;
245 opts.gnu_extensions = gnu;
246 }
247 _ if Dumps::is_family(arg) => {
256 opts.dumps.add(&arg[2..]);
257 }
258 _ if arg.starts_with("-fgnuc-version=") => {
259 let v = &arg["-fgnuc-version=".len()..];
260 opts.gnuc = v.parse().map_err(err)?;
261 }
262 _ if arg.starts_with("-j") => {
263 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
264 }
265 _ if arg.starts_with("--target=") => {
266 let t = &arg["--target=".len()..];
267 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
268 }
269 _ if arg.starts_with("--emit=") => {
270 let k = &arg["--emit=".len()..];
271 opts.emit = k
272 .parse()
273 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
274 }
275 _ if arg.starts_with("-O") => {
276 opts.opt_level = arg[2..]
277 .parse()
278 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
279 }
280 _ if arg.starts_with('-') && arg.len() > 1 => {
281 return Err(err(format!("unknown option `{arg}`")));
286 }
287 _ => inputs.push(Input { path: arg.to_owned(), forced }),
288 }
289 }
290
291 if !nostdinc {
296 opts.search.push_system(runtime::DIR);
297 }
298
299 if print_config {
302 return Ok(Action::PrintConfig(Box::new(opts)));
303 }
304 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
305 if print_plan {
306 return Ok(Action::PrintPlan(Box::new(plan)));
307 }
308 Ok(Action::Compile { opts: Box::new(opts), plan: Box::new(plan), jobs, verbose })
309}
310
311#[must_use]
316pub fn print_config(opts: &Options) -> String {
317 let sess = Session::new(opts.clone());
318 let t = &sess.target;
319 let mut out = String::new();
320 let _ = writeln!(out, "version: {VERSION}");
321 let _ = writeln!(out, "target: {}", t.triple);
322 let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
323 let _ = writeln!(out, "os: {}", t.triple.os.as_str());
324 let _ = writeln!(out, "env: {}", t.triple.env.as_str());
325 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
326 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
327 let _ = writeln!(out, "long-width: {}", t.long_width);
328 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
329 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
330 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
331 let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
332 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
333 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
334 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
335 out
336}
337
338fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
344 let fs = OsFileSystem::new();
345 let mut stderr = std::io::stderr().lock();
346 let mut failed = false;
347 for job in &plan.jobs {
348 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
349 continue;
352 }
353 let result = preprocess(opts, &job.input, &fs);
354 for message in &result.messages {
355 let _ = writeln!(stderr, "{message}");
356 }
357 if result.failed() {
358 failed = true;
359 continue;
360 }
361 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
362 let _ = writeln!(stderr, "rucc: error: {e}");
363 failed = true;
364 }
365 }
366 i32::from(failed)
367}
368
369fn compile_all(opts: &Options, plan: &Plan) -> i32 {
375 let fs = OsFileSystem::new();
376 let mut stderr = std::io::stderr().lock();
377 let mut failed = false;
378 for job in &plan.jobs {
379 if !job.phases.contains(&Phase::Compile) {
380 continue;
381 }
382 let result = if job.kind == InputKind::Ir {
386 compile_ir(opts, &job.input, &fs)
387 } else {
388 compile(opts, &job.input, &fs)
389 };
390 for message in &result.messages {
391 let _ = writeln!(stderr, "{message}");
392 }
393 if result.failed() {
394 failed = true;
395 continue;
396 }
397 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
398 let _ = writeln!(stderr, "rucc: error: {e}");
399 failed = true;
400 }
401 }
402 i32::from(failed)
403}
404
405fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
412 match output {
413 Output::Stdout => {
414 let mut stdout = std::io::stdout().lock();
415 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
416 }
417 Output::File(path) | Output::Temporary(path) => {
418 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
419 }
420 }
421}
422
423pub fn run(args: &[String]) -> i32 {
428 match parse_args(args) {
429 Ok(Action::Help) => {
430 print!("{USAGE}");
431 0
432 }
433 Ok(Action::Version) => {
434 println!("rucc {VERSION}");
435 0
436 }
437 Ok(Action::PrintConfig(opts)) => {
438 print!("{}", print_config(&opts));
439 0
440 }
441 Ok(Action::PrintPlan(plan)) => {
442 print!("{}", plan.render());
443 0
444 }
445 Ok(Action::Compile { opts, plan, jobs, verbose }) => {
446 {
447 let mut stderr = std::io::stderr().lock();
448 if verbose {
449 let _ = write!(stderr, "{}", plan.render());
450 let _ = writeln!(stderr, "workers: {}", jobs.count());
451 }
452 }
453 if opts.emit == EmitKind::Preprocessed {
454 return preprocess_all(&opts, &plan);
455 }
456 if matches!(opts.emit, EmitKind::Tast | EmitKind::Ir) {
457 return compile_all(&opts, &plan);
458 }
459 let mut stderr = std::io::stderr().lock();
460 let _ = writeln!(
464 stderr,
465 "rucc: error: running the {} phase is not implemented yet; \
466 use -E for preprocessed output, and see spec/17-milestones.md for the rest",
467 opts.emit.as_str()
468 );
469 1
470 }
471 Err(e) => {
472 let mut stderr = std::io::stderr().lock();
473 let _ = writeln!(stderr, "rucc: error: {e}");
474 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
475 1
476 }
477 }
478}
479
480#[cfg(test)]
481mod tests {
482 use rucc_session::{GnucVersion, OptLevel};
483
484 use super::*;
485
486 fn args(s: &[&str]) -> Vec<String> {
487 s.iter().map(|x| (*x).to_owned()).collect()
488 }
489
490 #[test]
491 fn help_and_version_win_over_everything_else() {
492 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
493 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
494 }
495
496 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
497 match parse_args(&args(s)).expect("expected a compilation") {
498 Action::Compile { opts, plan, .. } => (opts, plan),
499 other => panic!("expected a compilation, got {other:?}"),
500 }
501 }
502
503 #[test]
504 fn collects_inputs_and_flags() {
505 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
506 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
507 assert_eq!(paths, vec!["a.c", "b.c"]);
508 assert_eq!(opts.opt_level, OptLevel::O2);
509 assert_eq!(opts.emit, EmitKind::Object);
510 assert!(opts.debug_info);
511 }
512
513 #[test]
514 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
515 let (opts, _) = compile(&["-O", "a.c"]);
516 assert_eq!(opts.opt_level, OptLevel::O1);
517 }
518
519 #[test]
520 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
521 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
522 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
523 assert_eq!(plan.jobs[1].kind, InputKind::C);
524 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
525 }
526
527 #[test]
528 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
529 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
530 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
531 other => panic!("expected a compilation, got {other:?}"),
532 };
533 assert_eq!(jobs.count(), 4);
534
535 let default = match parse_args(&args(&["a.c"])).unwrap() {
536 Action::Compile { jobs, .. } => jobs,
537 other => panic!("expected a compilation, got {other:?}"),
538 };
539 assert_eq!(default, Jobs::available());
540 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
541 }
542
543 #[test]
544 fn triple_hash_prints_the_plan_and_runs_nothing() {
545 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
546 let Action::PrintPlan(plan) = a else { panic!("expected a plan dump") };
547 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
548 }
549
550 #[test]
551 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
552 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
553 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
554 }
555
556 #[test]
557 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
558 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
559 assert!(e.message.contains("unknown option"), "{}", e.message);
560 }
561
562 #[test]
563 fn an_unsupported_target_names_itself() {
564 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
565 assert!(e.message.contains("sparc64"), "{}", e.message);
566 }
567
568 #[test]
569 fn no_inputs_is_an_error_but_print_config_needs_none() {
570 assert!(parse_args(&args(&[])).is_err());
571 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
572 }
573
574 #[test]
575 fn print_config_reports_the_target_it_was_given_not_the_host() {
576 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
577 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
578 let text = print_config(&opts);
579 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
580 assert!(text.contains("char-signed: false"), "{text}");
581 assert!(text.contains("object-format: elf"), "{text}");
582 assert!(text.contains("va-list: void-pointer"), "{text}");
583 }
584
585 #[test]
586 fn print_config_has_one_key_per_line_and_a_fixed_order() {
587 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
588 let text = print_config(&opts);
589 let keys: Vec<&str> =
590 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
591 assert_eq!(keys[0], "version");
592 assert_eq!(keys[1], "target");
593 assert_eq!(keys.len(), 15);
594 assert!(text.ends_with('\n'));
595 }
596
597 #[test]
598 fn dash_o_needs_an_argument() {
599 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
600 assert_eq!(e.message, "-o requires an argument");
601 }
602
603 #[test]
604 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
605 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
606 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
607 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
608 }
609
610 #[test]
611 fn the_include_flags_land_on_the_chain_each_one_names() {
612 let (opts, _) =
613 compile(&["-Ii", "-iquote", "q", "-isystem", "sys", "-idirafter", "after", "a.c"]);
614 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
615 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
618 assert!(!opts.search.dirs()[1].is_system);
619 assert!(opts.search.dirs()[2].is_system);
620 }
621
622 #[test]
623 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
624 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
625 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
626 assert_eq!(dirs, ["i"]);
627 }
628
629 #[test]
630 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
631 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
632 assert_eq!(opts.std, Std::C11);
633 assert!(opts.gnu_extensions);
634
635 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
636 assert_eq!(opts.std, Std::C99);
637 assert!(!opts.gnu_extensions);
638
639 let (opts, _) = compile(&["-ansi", "a.c"]);
640 assert_eq!(opts.std, Std::C89);
641 assert!(!opts.gnu_extensions);
642
643 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
644 assert!(e.message.contains("unknown dialect"), "{}", e.message);
645 }
646
647 #[test]
648 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
649 let (opts, _) = compile(&["-dM", "a.c"]);
650 assert!(opts.dumps.macros);
651
652 let (opts, _) = compile(&["-dDM", "a.c"]);
655 assert!(opts.dumps.macros);
656 let (opts, _) = compile(&["-dD", "a.c"]);
657 assert!(!opts.dumps.macros);
658
659 let (opts, _) = compile(&["a.c"]);
660 assert!(!opts.dumps.any());
661
662 let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
665 assert!(e.message.contains("unknown option"), "{}", e.message);
666 }
667
668 #[test]
669 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
670 let (opts, _) = compile(&["a.c"]);
671 assert_eq!(
672 opts.gnuc,
673 GnucVersion { major: 4, minor: 2, patch: 1 },
674 "conservative by default"
675 );
676
677 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
678 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
679
680 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
683 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
684
685 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
686 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
687
688 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
689 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
690
691 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
692 assert!(e.message.contains("more than three"), "{}", e.message);
693 }
694
695 #[test]
696 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
697 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
698 assert!(opts.pedantic);
699 assert_eq!(opts.std, Std::C17);
700
701 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
704 assert!(opts.pedantic);
705
706 let (opts, _) = compile(&["-std=c17", "a.c"]);
707 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
708 }
709
710 #[test]
711 fn dash_p_and_dash_ffreestanding_reach_the_options() {
712 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
713 assert!(!opts.line_markers);
714 assert!(!opts.hosted);
715 assert_eq!(opts.emit, EmitKind::Preprocessed);
716 }
717
718 #[test]
719 fn usage_fits_on_a_screen() {
720 assert!(USAGE.lines().count() < 30, "usage text has grown past one screen");
723 }
724}