1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.2.12")]
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};
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 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
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 output = None;
162 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 "-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 "-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 _ 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 _ 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 return Err(err(format!("unknown option `{arg}`")));
281 }
282 _ => inputs.push(Input { path: arg.to_owned(), forced }),
283 }
284 }
285
286 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#[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, "opt-level: {}", sess.opts.opt_level);
319 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
320 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
321 out
322}
323
324fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
330 let fs = OsFileSystem::new();
331 let mut stderr = std::io::stderr().lock();
332 let mut failed = false;
333 for job in &plan.jobs {
334 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
335 continue;
338 }
339 let result = preprocess(opts, &job.input, &fs);
340 for message in &result.messages {
341 let _ = writeln!(stderr, "{message}");
342 }
343 if result.failed() {
344 failed = true;
345 continue;
346 }
347 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
348 let _ = writeln!(stderr, "rucc: error: {e}");
349 failed = true;
350 }
351 }
352 i32::from(failed)
353}
354
355fn compile_all(opts: &Options, plan: &Plan) -> i32 {
361 let fs = OsFileSystem::new();
362 let mut stderr = std::io::stderr().lock();
363 let mut failed = false;
364 for job in &plan.jobs {
365 if !job.phases.contains(&Phase::Compile) {
366 continue;
367 }
368 let result = compile(opts, &job.input, &fs);
369 for message in &result.messages {
370 let _ = writeln!(stderr, "{message}");
371 }
372 if result.failed() {
373 failed = true;
374 continue;
375 }
376 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
377 let _ = writeln!(stderr, "rucc: error: {e}");
378 failed = true;
379 }
380 }
381 i32::from(failed)
382}
383
384fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
391 match output {
392 Output::Stdout => {
393 let mut stdout = std::io::stdout().lock();
394 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
395 }
396 Output::File(path) | Output::Temporary(path) => {
397 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
398 }
399 }
400}
401
402pub fn run(args: &[String]) -> i32 {
407 match parse_args(args) {
408 Ok(Action::Help) => {
409 print!("{USAGE}");
410 0
411 }
412 Ok(Action::Version) => {
413 println!("rucc {VERSION}");
414 0
415 }
416 Ok(Action::PrintConfig(opts)) => {
417 print!("{}", print_config(&opts));
418 0
419 }
420 Ok(Action::PrintPlan(plan)) => {
421 print!("{}", plan.render());
422 0
423 }
424 Ok(Action::Compile { opts, plan, jobs, verbose }) => {
425 {
426 let mut stderr = std::io::stderr().lock();
427 if verbose {
428 let _ = write!(stderr, "{}", plan.render());
429 let _ = writeln!(stderr, "workers: {}", jobs.count());
430 }
431 }
432 if opts.emit == EmitKind::Preprocessed {
433 return preprocess_all(&opts, &plan);
434 }
435 if opts.emit == EmitKind::Tast {
436 return compile_all(&opts, &plan);
437 }
438 let mut stderr = std::io::stderr().lock();
439 let _ = writeln!(
443 stderr,
444 "rucc: error: running the {} phase is not implemented yet; \
445 use -E for preprocessed output, and see spec/17-milestones.md for the rest",
446 opts.emit.as_str()
447 );
448 1
449 }
450 Err(e) => {
451 let mut stderr = std::io::stderr().lock();
452 let _ = writeln!(stderr, "rucc: error: {e}");
453 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
454 1
455 }
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 use rucc_session::{GnucVersion, OptLevel};
462
463 use super::*;
464
465 fn args(s: &[&str]) -> Vec<String> {
466 s.iter().map(|x| (*x).to_owned()).collect()
467 }
468
469 #[test]
470 fn help_and_version_win_over_everything_else() {
471 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
472 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
473 }
474
475 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
476 match parse_args(&args(s)).expect("expected a compilation") {
477 Action::Compile { opts, plan, .. } => (opts, plan),
478 other => panic!("expected a compilation, got {other:?}"),
479 }
480 }
481
482 #[test]
483 fn collects_inputs_and_flags() {
484 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
485 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
486 assert_eq!(paths, vec!["a.c", "b.c"]);
487 assert_eq!(opts.opt_level, OptLevel::O2);
488 assert_eq!(opts.emit, EmitKind::Object);
489 assert!(opts.debug_info);
490 }
491
492 #[test]
493 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
494 let (opts, _) = compile(&["-O", "a.c"]);
495 assert_eq!(opts.opt_level, OptLevel::O1);
496 }
497
498 #[test]
499 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
500 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
501 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
502 assert_eq!(plan.jobs[1].kind, InputKind::C);
503 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
504 }
505
506 #[test]
507 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
508 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
509 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
510 other => panic!("expected a compilation, got {other:?}"),
511 };
512 assert_eq!(jobs.count(), 4);
513
514 let default = match parse_args(&args(&["a.c"])).unwrap() {
515 Action::Compile { jobs, .. } => jobs,
516 other => panic!("expected a compilation, got {other:?}"),
517 };
518 assert_eq!(default, Jobs::available());
519 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
520 }
521
522 #[test]
523 fn triple_hash_prints_the_plan_and_runs_nothing() {
524 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
525 let Action::PrintPlan(plan) = a else { panic!("expected a plan dump") };
526 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
527 }
528
529 #[test]
530 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
531 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
532 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
533 }
534
535 #[test]
536 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
537 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
538 assert!(e.message.contains("unknown option"), "{}", e.message);
539 }
540
541 #[test]
542 fn an_unsupported_target_names_itself() {
543 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
544 assert!(e.message.contains("sparc64"), "{}", e.message);
545 }
546
547 #[test]
548 fn no_inputs_is_an_error_but_print_config_needs_none() {
549 assert!(parse_args(&args(&[])).is_err());
550 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
551 }
552
553 #[test]
554 fn print_config_reports_the_target_it_was_given_not_the_host() {
555 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
556 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
557 let text = print_config(&opts);
558 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
559 assert!(text.contains("char-signed: false"), "{text}");
560 assert!(text.contains("object-format: elf"), "{text}");
561 }
562
563 #[test]
564 fn print_config_has_one_key_per_line_and_a_fixed_order() {
565 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
566 let text = print_config(&opts);
567 let keys: Vec<&str> =
568 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
569 assert_eq!(keys[0], "version");
570 assert_eq!(keys[1], "target");
571 assert_eq!(keys.len(), 14);
572 assert!(text.ends_with('\n'));
573 }
574
575 #[test]
576 fn dash_o_needs_an_argument() {
577 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
578 assert_eq!(e.message, "-o requires an argument");
579 }
580
581 #[test]
582 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
583 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
584 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
585 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
586 }
587
588 #[test]
589 fn the_include_flags_land_on_the_chain_each_one_names() {
590 let (opts, _) =
591 compile(&["-Ii", "-iquote", "q", "-isystem", "sys", "-idirafter", "after", "a.c"]);
592 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
593 assert_eq!(dirs, ["q", "i", "sys", "after"]);
594 assert!(!opts.search.dirs()[1].is_system);
595 assert!(opts.search.dirs()[2].is_system);
596 }
597
598 #[test]
599 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
600 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
601 assert_eq!(opts.std, Std::C11);
602 assert!(opts.gnu_extensions);
603
604 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
605 assert_eq!(opts.std, Std::C99);
606 assert!(!opts.gnu_extensions);
607
608 let (opts, _) = compile(&["-ansi", "a.c"]);
609 assert_eq!(opts.std, Std::C89);
610 assert!(!opts.gnu_extensions);
611
612 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
613 assert!(e.message.contains("unknown dialect"), "{}", e.message);
614 }
615
616 #[test]
617 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
618 let (opts, _) = compile(&["-dM", "a.c"]);
619 assert!(opts.dumps.macros);
620
621 let (opts, _) = compile(&["-dDM", "a.c"]);
624 assert!(opts.dumps.macros);
625 let (opts, _) = compile(&["-dD", "a.c"]);
626 assert!(!opts.dumps.macros);
627
628 let (opts, _) = compile(&["a.c"]);
629 assert!(!opts.dumps.any());
630
631 let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
634 assert!(e.message.contains("unknown option"), "{}", e.message);
635 }
636
637 #[test]
638 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
639 let (opts, _) = compile(&["a.c"]);
640 assert_eq!(
641 opts.gnuc,
642 GnucVersion { major: 4, minor: 2, patch: 1 },
643 "conservative by default"
644 );
645
646 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
647 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
648
649 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
652 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
653
654 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
655 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
656
657 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
658 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
659
660 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
661 assert!(e.message.contains("more than three"), "{}", e.message);
662 }
663
664 #[test]
665 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
666 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
667 assert!(opts.pedantic);
668 assert_eq!(opts.std, Std::C17);
669
670 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
673 assert!(opts.pedantic);
674
675 let (opts, _) = compile(&["-std=c17", "a.c"]);
676 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
677 }
678
679 #[test]
680 fn dash_p_and_dash_ffreestanding_reach_the_options() {
681 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
682 assert!(!opts.line_markers);
683 assert!(!opts.hosted);
684 assert_eq!(opts.emit, EmitKind::Preprocessed);
685 }
686
687 #[test]
688 fn usage_fits_on_a_screen() {
689 assert!(USAGE.lines().count() < 30, "usage text has grown past one screen");
692 }
693}