1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.2.6")]
27
28mod map;
29pub mod phase;
30pub mod preprocess;
31pub mod schedule;
32
33use std::fmt::Write as _;
34use std::io::Write as _;
35
36use rucc_session::{Dumps, EmitKind, Options, Session, Std};
37use rucc_target::Triple;
38
39pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
40pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
41pub use crate::schedule::Jobs;
42
43pub const VERSION: &str = env!("CARGO_PKG_VERSION");
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum Action {
49 Help,
51 Version,
53 PrintConfig(Box<Options>),
55 PrintPlan(Box<Plan>),
57 Compile {
59 opts: Box<Options>,
61 plan: Box<Plan>,
63 jobs: Jobs,
65 verbose: bool,
67 },
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct CliError {
73 pub message: String,
76}
77
78impl std::fmt::Display for CliError {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 f.write_str(&self.message)
81 }
82}
83
84impl std::error::Error for CliError {}
85
86fn err(message: impl Into<String>) -> CliError {
87 CliError { message: message.into() }
88}
89
90pub const USAGE: &str = "\
95rucc, an optimizing C compiler
96
97usage: rucc [options] file...
98
99options:
100 -c compile and assemble, do not link
101 -S compile only, emit assembly
102 -E preprocess only
103 -o <file> write output to <file>
104 -D <name>[=<value>] define a macro, value 1 if none is given
105 -U <name> undefine a macro, after every -D
106 -I <dir> add <dir> to the include search path
107 -iquote -isystem -idirafter <dir> the other search chains
108 -P, -dM with -E: leave out the markers, or dump the macros
109 -std=<dialect> c89 through c23, and the gnu spellings
110 -fgnuc-version=<v> the GCC release to claim, default 4.2.1
111 -x <lang> treat later inputs as <lang>, or none to stop
112 -O<level> optimize: 0, 1, 2, 3, s, z
113 -g emit debug information
114 -Werror treat warnings as errors
115 -j[n] compile n translation units at once, default all
116 -v, -### print each phase as it runs, or without running any
117 --target=<triple> generate code for <triple>
118 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final
119 --print-config print the resolved configuration and exit
120 --version print the version and exit
121 -h, --help print this message and exit
122
123See spec/04-driver-and-cli.md for the full flag reference.
124";
125
126fn joined_or_next(
130 arg: &str,
131 at: usize,
132 args: &[String],
133 i: &mut usize,
134) -> Result<String, CliError> {
135 if arg.len() > at {
136 return Ok(arg[at..].to_owned());
137 }
138 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
139 *i += 1;
140 Ok(next.clone())
141}
142
143pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
150 let host = Triple::host()
151 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
152 let mut opts = Options::new(host);
153 let mut inputs: Vec<Input> = Vec::new();
154 let mut print_config = false;
155 let mut print_plan = false;
156 let mut verbose = false;
157 let mut jobs = Jobs::default();
158 let mut output = None;
159 let mut forced: Option<InputKind> = None;
162
163 let mut i = 0;
164 while i < args.len() {
165 let arg = args[i].as_str();
166 i += 1;
167 match arg {
168 "-h" | "--help" => return Ok(Action::Help),
169 "--version" => return Ok(Action::Version),
170 "--print-config" => print_config = true,
171 "-###" => print_plan = true,
172 "-v" => verbose = true,
173 "-c" => opts.emit = EmitKind::Object,
174 "-S" => opts.emit = EmitKind::Asm,
175 "-E" => opts.emit = EmitKind::Preprocessed,
176 "-g" => opts.debug_info = true,
177 "-Werror" => opts.warnings_are_errors = true,
178 "-P" => opts.line_markers = false,
179 "-ansi" => {
180 opts.std = Std::C89;
181 opts.gnu_extensions = false;
182 }
183 "-ffreestanding" => opts.hosted = false,
184 "-fhosted" => opts.hosted = true,
185 "-o" => {
186 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
187 i += 1;
188 }
189 "-iquote" | "-isystem" | "-idirafter" => {
193 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
194 i += 1;
195 match arg {
196 "-iquote" => opts.search.push_quote(dir.clone()),
197 "-isystem" => opts.search.push_system(dir.clone()),
198 _ => opts.search.push_after(dir.clone()),
199 }
200 }
201 "-x" => {
202 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
203 i += 1;
204 forced = if lang == "none" {
205 None
206 } else {
207 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
208 };
209 }
210 _ if arg.starts_with("-D") => {
218 let value = joined_or_next(arg, 2, args, &mut i)?;
219 opts.defines.push(value);
220 }
221 _ if arg.starts_with("-U") => {
222 let value = joined_or_next(arg, 2, args, &mut i)?;
223 opts.undefines.push(value);
224 }
225 _ if arg.starts_with("-I") => {
226 let dir = joined_or_next(arg, 2, args, &mut i)?;
227 opts.search.push_bracket(dir);
228 }
229 _ if arg.starts_with("-std=") => {
230 let name = &arg["-std=".len()..];
231 let (std, gnu) = Std::from_flag(name)
232 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
233 opts.std = std;
234 opts.gnu_extensions = gnu;
235 }
236 _ if Dumps::is_family(arg) => {
245 opts.dumps.add(&arg[2..]);
246 }
247 _ if arg.starts_with("-fgnuc-version=") => {
248 let v = &arg["-fgnuc-version=".len()..];
249 opts.gnuc = v.parse().map_err(err)?;
250 }
251 _ if arg.starts_with("-j") => {
252 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
253 }
254 _ if arg.starts_with("--target=") => {
255 let t = &arg["--target=".len()..];
256 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
257 }
258 _ if arg.starts_with("--emit=") => {
259 let k = &arg["--emit=".len()..];
260 opts.emit = k
261 .parse()
262 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
263 }
264 _ if arg.starts_with("-O") => {
265 opts.opt_level = arg[2..]
266 .parse()
267 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
268 }
269 _ if arg.starts_with('-') && arg.len() > 1 => {
270 return Err(err(format!("unknown option `{arg}`")));
275 }
276 _ => inputs.push(Input { path: arg.to_owned(), forced }),
277 }
278 }
279
280 if print_config {
283 return Ok(Action::PrintConfig(Box::new(opts)));
284 }
285 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
286 if print_plan {
287 return Ok(Action::PrintPlan(Box::new(plan)));
288 }
289 Ok(Action::Compile { opts: Box::new(opts), plan: Box::new(plan), jobs, verbose })
290}
291
292#[must_use]
297pub fn print_config(opts: &Options) -> String {
298 let sess = Session::new(opts.clone());
299 let t = &sess.target;
300 let mut out = String::new();
301 let _ = writeln!(out, "version: {VERSION}");
302 let _ = writeln!(out, "target: {}", t.triple);
303 let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
304 let _ = writeln!(out, "os: {}", t.triple.os.as_str());
305 let _ = writeln!(out, "env: {}", t.triple.env.as_str());
306 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
307 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
308 let _ = writeln!(out, "long-width: {}", t.long_width);
309 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
310 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
311 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
312 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
313 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
314 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
315 out
316}
317
318fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
324 let fs = OsFileSystem::new();
325 let mut stderr = std::io::stderr().lock();
326 let mut failed = false;
327 for job in &plan.jobs {
328 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
329 continue;
332 }
333 let result = preprocess(opts, &job.input, &fs);
334 for message in &result.messages {
335 let _ = writeln!(stderr, "{message}");
336 }
337 if result.failed() {
338 failed = true;
339 continue;
340 }
341 match &job.output {
342 Output::Stdout => {
343 let mut stdout = std::io::stdout().lock();
344 if let Err(e) = stdout.write_all(result.text.as_bytes()) {
345 let _ = writeln!(stderr, "rucc: error: writing to standard output: {e}");
346 failed = true;
347 }
348 }
349 Output::File(path) | Output::Temporary(path) => {
350 if let Err(e) = std::fs::write(path, result.text.as_bytes()) {
351 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
352 failed = true;
353 }
354 }
355 }
356 }
357 i32::from(failed)
358}
359
360pub fn run(args: &[String]) -> i32 {
365 match parse_args(args) {
366 Ok(Action::Help) => {
367 print!("{USAGE}");
368 0
369 }
370 Ok(Action::Version) => {
371 println!("rucc {VERSION}");
372 0
373 }
374 Ok(Action::PrintConfig(opts)) => {
375 print!("{}", print_config(&opts));
376 0
377 }
378 Ok(Action::PrintPlan(plan)) => {
379 print!("{}", plan.render());
380 0
381 }
382 Ok(Action::Compile { opts, plan, jobs, verbose }) => {
383 {
384 let mut stderr = std::io::stderr().lock();
385 if verbose {
386 let _ = write!(stderr, "{}", plan.render());
387 let _ = writeln!(stderr, "workers: {}", jobs.count());
388 }
389 }
390 if opts.emit == EmitKind::Preprocessed {
391 return preprocess_all(&opts, &plan);
392 }
393 let mut stderr = std::io::stderr().lock();
394 let _ = writeln!(
398 stderr,
399 "rucc: error: running the {} phase is not implemented yet; \
400 use -E for preprocessed output, and see spec/17-milestones.md for the rest",
401 opts.emit.as_str()
402 );
403 1
404 }
405 Err(e) => {
406 let mut stderr = std::io::stderr().lock();
407 let _ = writeln!(stderr, "rucc: error: {e}");
408 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
409 1
410 }
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use rucc_session::{GnucVersion, OptLevel};
417
418 use super::*;
419
420 fn args(s: &[&str]) -> Vec<String> {
421 s.iter().map(|x| (*x).to_owned()).collect()
422 }
423
424 #[test]
425 fn help_and_version_win_over_everything_else() {
426 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
427 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
428 }
429
430 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
431 match parse_args(&args(s)).expect("expected a compilation") {
432 Action::Compile { opts, plan, .. } => (opts, plan),
433 other => panic!("expected a compilation, got {other:?}"),
434 }
435 }
436
437 #[test]
438 fn collects_inputs_and_flags() {
439 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
440 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
441 assert_eq!(paths, vec!["a.c", "b.c"]);
442 assert_eq!(opts.opt_level, OptLevel::O2);
443 assert_eq!(opts.emit, EmitKind::Object);
444 assert!(opts.debug_info);
445 }
446
447 #[test]
448 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
449 let (opts, _) = compile(&["-O", "a.c"]);
450 assert_eq!(opts.opt_level, OptLevel::O1);
451 }
452
453 #[test]
454 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
455 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
456 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
457 assert_eq!(plan.jobs[1].kind, InputKind::C);
458 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
459 }
460
461 #[test]
462 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
463 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
464 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
465 other => panic!("expected a compilation, got {other:?}"),
466 };
467 assert_eq!(jobs.count(), 4);
468
469 let default = match parse_args(&args(&["a.c"])).unwrap() {
470 Action::Compile { jobs, .. } => jobs,
471 other => panic!("expected a compilation, got {other:?}"),
472 };
473 assert_eq!(default, Jobs::available());
474 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
475 }
476
477 #[test]
478 fn triple_hash_prints_the_plan_and_runs_nothing() {
479 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
480 let Action::PrintPlan(plan) = a else { panic!("expected a plan dump") };
481 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
482 }
483
484 #[test]
485 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
486 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
487 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
488 }
489
490 #[test]
491 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
492 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
493 assert!(e.message.contains("unknown option"), "{}", e.message);
494 }
495
496 #[test]
497 fn an_unsupported_target_names_itself() {
498 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
499 assert!(e.message.contains("sparc64"), "{}", e.message);
500 }
501
502 #[test]
503 fn no_inputs_is_an_error_but_print_config_needs_none() {
504 assert!(parse_args(&args(&[])).is_err());
505 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
506 }
507
508 #[test]
509 fn print_config_reports_the_target_it_was_given_not_the_host() {
510 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
511 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
512 let text = print_config(&opts);
513 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
514 assert!(text.contains("char-signed: false"), "{text}");
515 assert!(text.contains("object-format: elf"), "{text}");
516 }
517
518 #[test]
519 fn print_config_has_one_key_per_line_and_a_fixed_order() {
520 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
521 let text = print_config(&opts);
522 let keys: Vec<&str> =
523 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
524 assert_eq!(keys[0], "version");
525 assert_eq!(keys[1], "target");
526 assert_eq!(keys.len(), 14);
527 assert!(text.ends_with('\n'));
528 }
529
530 #[test]
531 fn dash_o_needs_an_argument() {
532 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
533 assert_eq!(e.message, "-o requires an argument");
534 }
535
536 #[test]
537 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
538 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
539 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
540 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
541 }
542
543 #[test]
544 fn the_include_flags_land_on_the_chain_each_one_names() {
545 let (opts, _) =
546 compile(&["-Ii", "-iquote", "q", "-isystem", "sys", "-idirafter", "after", "a.c"]);
547 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
548 assert_eq!(dirs, ["q", "i", "sys", "after"]);
549 assert!(!opts.search.dirs()[1].is_system);
550 assert!(opts.search.dirs()[2].is_system);
551 }
552
553 #[test]
554 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
555 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
556 assert_eq!(opts.std, Std::C11);
557 assert!(opts.gnu_extensions);
558
559 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
560 assert_eq!(opts.std, Std::C99);
561 assert!(!opts.gnu_extensions);
562
563 let (opts, _) = compile(&["-ansi", "a.c"]);
564 assert_eq!(opts.std, Std::C89);
565 assert!(!opts.gnu_extensions);
566
567 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
568 assert!(e.message.contains("unknown dialect"), "{}", e.message);
569 }
570
571 #[test]
572 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
573 let (opts, _) = compile(&["-dM", "a.c"]);
574 assert!(opts.dumps.macros);
575
576 let (opts, _) = compile(&["-dDM", "a.c"]);
579 assert!(opts.dumps.macros);
580 let (opts, _) = compile(&["-dD", "a.c"]);
581 assert!(!opts.dumps.macros);
582
583 let (opts, _) = compile(&["a.c"]);
584 assert!(!opts.dumps.any());
585
586 let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
589 assert!(e.message.contains("unknown option"), "{}", e.message);
590 }
591
592 #[test]
593 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
594 let (opts, _) = compile(&["a.c"]);
595 assert_eq!(
596 opts.gnuc,
597 GnucVersion { major: 4, minor: 2, patch: 1 },
598 "conservative by default"
599 );
600
601 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
602 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
603
604 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
607 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
608
609 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
610 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
611
612 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
613 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
614
615 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
616 assert!(e.message.contains("more than three"), "{}", e.message);
617 }
618
619 #[test]
620 fn dash_p_and_dash_ffreestanding_reach_the_options() {
621 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
622 assert!(!opts.line_markers);
623 assert!(!opts.hosted);
624 assert_eq!(opts.emit, EmitKind::Preprocessed);
625 }
626
627 #[test]
628 fn usage_fits_on_a_screen() {
629 assert!(USAGE.lines().count() < 30, "usage text has grown past one screen");
632 }
633}