1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.3.9")]
28
29pub mod compile;
30pub mod library;
31pub mod link;
32mod map;
33pub mod phase;
34pub mod preprocess;
35pub mod schedule;
36
37use std::fmt::Write as _;
38use std::io::Write as _;
39use std::path::PathBuf;
40
41use rucc_session::{Dumps, EmitKind, Options, Session, Std, runtime};
42use rucc_target::Triple;
43
44use crate::link::LinkOptions;
45
46pub use crate::compile::{Artifact, Compiled, compile, compile_ir};
47pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
48pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
49pub use crate::schedule::Jobs;
50
51pub const VERSION: &str = env!("CARGO_PKG_VERSION");
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum Action {
57 Help,
59 Version,
61 PrintConfig(Box<Options>),
63 PrintPlan {
65 opts: Box<Options>,
67 plan: Box<Plan>,
69 link: Box<LinkOptions>,
71 },
72 Compile {
74 opts: Box<Options>,
76 plan: Box<Plan>,
78 link: Box<LinkOptions>,
80 jobs: Jobs,
82 verbose: bool,
84 },
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct CliError {
90 pub message: String,
93}
94
95impl std::fmt::Display for CliError {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 f.write_str(&self.message)
98 }
99}
100
101impl std::error::Error for CliError {}
102
103fn err(message: impl Into<String>) -> CliError {
104 CliError { message: message.into() }
105}
106
107pub const USAGE: &str = "\
112rucc, an optimizing C compiler
113
114usage: rucc [options] file...
115
116options:
117 -c compile and assemble, do not link
118 -S compile only, emit assembly
119 -E preprocess only
120 -o <file> write output to <file>, or to standard output for -
121 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
122 -I <dir> add <dir> to the include search path
123 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
124 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
125 -P, -dM with -E: leave out the markers, or dump the macros
126 -std=<dialect> c89 through c23, and the gnu spellings
127 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
128 -x <lang> treat later inputs as <lang>, or none to stop
129 -O<level> optimize: 0, 1, 2, 3, s, z
130 -g, -fno-omit-frame-pointer, -mno-red-zone debug info, keep a frame pointer, no red zone
131 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
132 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
133 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
134 -Werror -pedantic warnings are errors, diagnose what the standard forbids
135 -j[n] compile n translation units at once, default all
136 -v, -### print each phase as it runs, or without running any
137 --target=<triple> generate code for <triple>
138 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final
139 --print-config print the resolved configuration and exit
140 --version print the version and exit
141 -h, --help print this message and exit
142
143See spec/04-driver-and-cli.md for the full flag reference.
144";
145
146fn joined_or_next(
150 arg: &str,
151 at: usize,
152 args: &[String],
153 i: &mut usize,
154) -> Result<String, CliError> {
155 if arg.len() > at {
156 return Ok(arg[at..].to_owned());
157 }
158 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
159 *i += 1;
160 Ok(next.clone())
161}
162
163pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
170 let host = Triple::host()
171 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
172 let mut opts = Options::new(host);
173 let mut inputs: Vec<Input> = Vec::new();
174 let mut print_config = false;
175 let mut print_plan = false;
176 let mut verbose = false;
177 let mut jobs = Jobs::default();
178 let mut nostdinc = false;
179 let mut sysroot: Option<PathBuf> = None;
180 let mut output = None;
181 let mut link = LinkOptions::default();
182 let mut forced: Option<InputKind> = None;
185
186 let mut i = 0;
187 while i < args.len() {
188 let arg = args[i].as_str();
189 i += 1;
190 match arg {
191 "-h" | "--help" => return Ok(Action::Help),
192 "--version" => return Ok(Action::Version),
193 "--print-config" => print_config = true,
194 "-###" => print_plan = true,
195 "-v" => verbose = true,
196 "-c" => opts.emit = EmitKind::Object,
197 "-S" => opts.emit = EmitKind::Asm,
198 "-E" => opts.emit = EmitKind::Preprocessed,
199 "-g" => opts.debug_info = true,
200 "-Werror" => opts.warnings_are_errors = true,
201 "-P" => opts.line_markers = false,
202 "-ansi" => {
203 opts.std = Std::C89;
204 opts.gnu_extensions = false;
205 }
206 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
209 "-ffreestanding" => opts.hosted = false,
210 "-fhosted" => opts.hosted = true,
211 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
214 "-fomit-frame-pointer" => opts.frame_pointer = false,
215 "-mno-red-zone" => opts.red_zone = false,
216 "-mred-zone" => opts.red_zone = true,
217 "-nostdinc" => nostdinc = true,
221 "-o" => {
222 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
223 i += 1;
224 }
225 "-isysroot" => {
232 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
233 i += 1;
234 sysroot = Some(PathBuf::from(dir));
235 }
236 "-iquote" | "-isystem" | "-idirafter" => {
237 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
238 i += 1;
239 match arg {
240 "-iquote" => opts.search.push_quote(dir.clone()),
241 "-isystem" => opts.search.push_system(dir.clone()),
242 _ => opts.search.push_after(dir.clone()),
243 }
244 }
245 "-x" => {
246 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
247 i += 1;
248 forced = if lang == "none" {
249 None
250 } else {
251 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
252 };
253 }
254 _ if arg.starts_with("-D") => {
262 let value = joined_or_next(arg, 2, args, &mut i)?;
263 opts.defines.push(value);
264 }
265 _ if arg.starts_with("-U") => {
266 let value = joined_or_next(arg, 2, args, &mut i)?;
267 opts.undefines.push(value);
268 }
269 _ if arg.starts_with("-I") => {
270 let dir = joined_or_next(arg, 2, args, &mut i)?;
271 opts.search.push_bracket(dir);
272 }
273 _ if arg.starts_with("-std=") => {
274 let name = &arg["-std=".len()..];
275 let (std, gnu) = Std::from_flag(name)
276 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
277 opts.std = std;
278 opts.gnu_extensions = gnu;
279 }
280 _ if Dumps::is_family(arg) => {
289 opts.dumps.add(&arg[2..]);
290 }
291 _ if arg.starts_with("-fgnuc-version=") => {
292 let v = &arg["-fgnuc-version=".len()..];
293 opts.gnuc = v.parse().map_err(err)?;
294 }
295 "-fnested-functions" => {
300 return Err(err(
301 "nested functions are not supported: a call to one goes through a trampoline \
302 written on the stack, which no target that enforces an unexecutable stack \
303 allows",
304 ));
305 }
306 "-fno-nested-functions" => {}
307 "-static" => link.is_static = true,
311 "-shared" => link.shared = true,
312 "-pie" => link.pie = Some(true),
313 "-no-pie" | "-nopie" => link.pie = Some(false),
314 "-nostdlib" => link.no_stdlib = true,
315 "-nostartfiles" => link.no_startfiles = true,
316 "-nodefaultlibs" => link.no_defaultlibs = true,
317 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
318 "-s" => link.strip = true,
319 "-Xlinker" => {
320 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
321 i += 1;
322 link.passthrough.push(next.clone());
323 }
324 _ if arg.starts_with("-Wl,") => {
325 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
328 }
329 _ if arg.starts_with("-fuse-ld=") => {
330 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
331 }
332 _ if arg.starts_with("-l") && arg.len() > 2 => {
333 inputs.push(Input::library(&arg[2..]));
334 }
335 "-l" => {
336 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
337 i += 1;
338 inputs.push(Input::library(next));
339 }
340 _ if arg.starts_with("-L") => {
341 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
342 }
343 _ if arg.starts_with("-B") => {
344 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
345 }
346 _ if arg.starts_with("-j") => {
347 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
348 }
349 _ if arg.starts_with("--sysroot=") => {
350 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
351 }
352 _ if arg.starts_with("--target=") => {
353 let t = &arg["--target=".len()..];
354 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
355 }
356 _ if arg.starts_with("--emit=") => {
357 let k = &arg["--emit=".len()..];
358 opts.emit = k
359 .parse()
360 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
361 }
362 _ if arg.starts_with("-O") => {
363 opts.opt_level = arg[2..]
364 .parse()
365 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
366 }
367 _ if arg.starts_with('-') && arg.len() > 1 => {
368 return Err(err(format!("unknown option `{arg}`")));
373 }
374 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
375 }
376 }
377
378 link.sysroot = sysroot.clone();
385 if !nostdinc {
386 opts.search.push_system(runtime::DIR);
387 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
391 opts.search.push_system(dir);
392 }
393 }
394 opts.search.remove_duplicates();
398
399 if print_config {
402 return Ok(Action::PrintConfig(Box::new(opts)));
403 }
404 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
405 if print_plan {
406 return Ok(Action::PrintPlan {
407 opts: Box::new(opts),
408 plan: Box::new(plan),
409 link: Box::new(link),
410 });
411 }
412 Ok(Action::Compile {
413 opts: Box::new(opts),
414 plan: Box::new(plan),
415 link: Box::new(link),
416 jobs,
417 verbose,
418 })
419}
420
421#[must_use]
426pub fn print_config(opts: &Options) -> String {
427 let sess = Session::new(opts.clone());
428 let t = &sess.target;
429 let mut out = String::new();
430 let _ = writeln!(out, "version: {VERSION}");
431 let _ = writeln!(out, "target: {}", t.triple);
432 let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
433 let _ = writeln!(out, "os: {}", t.triple.os.as_str());
434 let _ = writeln!(out, "env: {}", t.triple.env.as_str());
435 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
436 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
437 let _ = writeln!(out, "long-width: {}", t.long_width);
438 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
439 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
440 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
441 let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
442 let regs: Vec<String> = t
445 .regs
446 .classes()
447 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
448 .collect();
449 let _ = writeln!(
450 out,
451 "registers: {}",
452 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
453 );
454 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
455 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
456 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
457 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
458 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
459 for dir in sess.opts.search.dirs() {
462 let system = if dir.is_system { " (system)" } else { "" };
463 let _ = writeln!(out, "include: {}{system}", dir.path.display());
464 }
465 out
466}
467
468fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
474 let fs = OsFileSystem::new();
475 let mut stderr = std::io::stderr().lock();
476 let mut failed = false;
477 for job in &plan.jobs {
478 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
479 continue;
482 }
483 let result = preprocess(opts, &job.input, &fs);
484 for message in &result.messages {
485 let _ = writeln!(stderr, "{message}");
486 }
487 if result.failed() {
488 failed = true;
489 continue;
490 }
491 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
492 let _ = writeln!(stderr, "rucc: error: {e}");
493 failed = true;
494 }
495 }
496 i32::from(failed)
497}
498
499fn compile_all(opts: &Options, plan: &Plan) -> i32 {
505 let fs = OsFileSystem::new();
506 let mut stderr = std::io::stderr().lock();
507 let mut failed = false;
508 for job in &plan.jobs {
509 if !job.phases.contains(&Phase::Compile) {
510 continue;
511 }
512 let result = if job.kind == InputKind::Ir {
516 compile_ir(opts, &job.input, &fs)
517 } else {
518 compile(opts, &job.input, &fs)
519 };
520 for message in &result.messages {
521 let _ = writeln!(stderr, "{message}");
522 }
523 if result.failed() {
524 failed = true;
525 continue;
526 }
527 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
528 let _ = writeln!(stderr, "rucc: error: {e}");
529 failed = true;
530 }
531 }
532 i32::from(failed)
533}
534
535struct Scratch {
542 dir: PathBuf,
544}
545
546impl Scratch {
547 fn new() -> Result<Scratch, String> {
553 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
554 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
555 Ok(Scratch { dir })
556 }
557}
558
559impl Drop for Scratch {
560 fn drop(&mut self) {
561 let _ = std::fs::remove_dir_all(&self.dir);
562 }
563}
564
565fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
572 let linker = link::find(opts.target, link)?;
573 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
574 Ok(link::render(&linker, &args))
575}
576
577fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
584 let Some(job) = &plan.link else {
585 let mut stderr = std::io::stderr().lock();
588 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
589 return 1;
590 };
591 let linker = match link::find(opts.target, link) {
594 Ok(linker) => linker,
595 Err(why) => return complain(why),
596 };
597
598 let scratch = match Scratch::new() {
599 Ok(scratch) => scratch,
600 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
601 };
602
603 let fs = OsFileSystem::new();
604 let mut failed = false;
605 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
608 {
609 let mut stderr = std::io::stderr().lock();
610 for (at, job) in plan.jobs.iter().enumerate() {
611 let out = match &job.output {
612 Output::Temporary(hint) => {
613 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
616 }
617 Output::File(path) => path.clone(),
618 Output::Stdout => continue,
621 };
622 produced.push(out.clone());
623 if !job.phases.contains(&Phase::Compile) {
624 continue;
625 }
626 let result = if job.kind == InputKind::Ir {
627 compile_ir(opts, &job.input, &fs)
628 } else {
629 compile(opts, &job.input, &fs)
630 };
631 for message in &result.messages {
632 let _ = writeln!(stderr, "{message}");
633 }
634 if result.failed() {
635 failed = true;
636 continue;
637 }
638 if !matches!(result.artifact, Artifact::Object(_)) {
639 let _ = writeln!(
644 stderr,
645 "rucc: internal error: {}: no object file was produced for the link",
646 job.input
647 );
648 failed = true;
649 continue;
650 }
651 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
652 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
653 failed = true;
654 }
655 }
656 }
657 if failed {
658 return 1;
662 }
663
664 let mut outputs = produced.into_iter();
668 let mut items = Vec::with_capacity(job.inputs.len());
669 for item in &job.inputs {
670 match item {
671 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
672 link::Item::File(_) => match outputs.next() {
673 Some(path) => items.push(link::Item::File(path)),
674 None => return complain("the plan asks the linker for a file nothing produced"),
675 },
676 }
677 }
678
679 let args = match link::line(opts.target, link, &items, &job.output) {
680 Ok(args) => args,
681 Err(why) => return complain(why),
682 };
683 if verbose {
684 let mut stderr = std::io::stderr().lock();
685 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
686 }
687 match link::run(&linker, &args) {
688 Ok(()) => 0,
689 Err(link::Error::Refused { .. }) => 1,
692 Err(why) => complain(why),
693 }
694}
695
696fn complain(why: impl std::fmt::Display) -> i32 {
698 let mut stderr = std::io::stderr().lock();
699 let _ = writeln!(stderr, "rucc: error: {why}");
700 1
701}
702
703fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
710 match output {
711 Output::Stdout => {
712 let mut stdout = std::io::stdout().lock();
713 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
714 }
715 Output::File(path) | Output::Temporary(path) => {
716 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
717 }
718 }
719}
720
721pub fn run(args: &[String]) -> i32 {
726 match parse_args(args) {
727 Ok(Action::Help) => {
728 print!("{USAGE}");
729 0
730 }
731 Ok(Action::Version) => {
732 println!("rucc {VERSION}");
733 0
734 }
735 Ok(Action::PrintConfig(opts)) => {
736 print!("{}", print_config(&opts));
737 0
738 }
739 Ok(Action::PrintPlan { opts, plan, link }) => {
740 print!("{}", plan.render());
741 if let Some(job) = &plan.link {
745 match link_line(&opts, &link, job) {
746 Ok(line) => println!("{line}"),
747 Err(why) => {
748 let mut stderr = std::io::stderr().lock();
749 let _ = writeln!(stderr, "rucc: error: {why}");
750 return 1;
751 }
752 }
753 }
754 0
755 }
756 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
757 {
758 let mut stderr = std::io::stderr().lock();
759 if verbose {
760 let _ = write!(stderr, "{}", plan.render());
761 let _ = writeln!(stderr, "workers: {}", jobs.count());
762 }
763 }
764 if opts.emit == EmitKind::Preprocessed {
765 return preprocess_all(&opts, &plan);
766 }
767 if opts.emit != EmitKind::Executable {
768 return compile_all(&opts, &plan);
769 }
770 link_all(&opts, &plan, &link, verbose)
771 }
772 Err(e) => {
773 let mut stderr = std::io::stderr().lock();
774 let _ = writeln!(stderr, "rucc: error: {e}");
775 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
776 1
777 }
778 }
779}
780
781#[cfg(test)]
782mod tests {
783 use rucc_session::{GnucVersion, OptLevel};
784
785 use super::*;
786
787 fn args(s: &[&str]) -> Vec<String> {
788 s.iter().map(|x| (*x).to_owned()).collect()
789 }
790
791 #[test]
792 fn help_and_version_win_over_everything_else() {
793 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
794 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
795 }
796
797 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
798 match parse_args(&args(s)).expect("expected a compilation") {
799 Action::Compile { opts, plan, .. } => (opts, plan),
800 other => panic!("expected a compilation, got {other:?}"),
801 }
802 }
803
804 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
805 match parse_args(&args(s)).expect("expected a compilation") {
806 Action::Compile { link, plan, .. } => (link, plan),
807 other => panic!("expected a compilation, got {other:?}"),
808 }
809 }
810
811 #[test]
812 fn collects_inputs_and_flags() {
813 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
814 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
815 assert_eq!(paths, vec!["a.c", "b.c"]);
816 assert_eq!(opts.opt_level, OptLevel::O2);
817 assert_eq!(opts.emit, EmitKind::Object);
818 assert!(opts.debug_info);
819 }
820
821 #[test]
822 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
823 let (opts, _) = compile(&["-O", "a.c"]);
824 assert_eq!(opts.opt_level, OptLevel::O1);
825 }
826
827 #[test]
828 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
829 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
830 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
831 assert_eq!(plan.jobs[1].kind, InputKind::C);
832 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
833 }
834
835 #[test]
836 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
837 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
838 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
839 other => panic!("expected a compilation, got {other:?}"),
840 };
841 assert_eq!(jobs.count(), 4);
842
843 let default = match parse_args(&args(&["a.c"])).unwrap() {
844 Action::Compile { jobs, .. } => jobs,
845 other => panic!("expected a compilation, got {other:?}"),
846 };
847 assert_eq!(default, Jobs::available());
848 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
849 }
850
851 #[test]
852 fn triple_hash_prints_the_plan_and_runs_nothing() {
853 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
854 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
855 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
856 }
857
858 #[test]
859 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
860 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
861 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
862 }
863
864 #[test]
865 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
866 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
867 assert!(e.message.contains("unknown option"), "{}", e.message);
868 }
869
870 #[test]
871 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
872 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
873 assert!(e.message.contains("trampoline"), "{}", e.message);
874 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
875 }
876
877 #[test]
878 fn an_unsupported_target_names_itself() {
879 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
880 assert!(e.message.contains("sparc64"), "{}", e.message);
881 }
882
883 #[test]
884 fn no_inputs_is_an_error_but_print_config_needs_none() {
885 assert!(parse_args(&args(&[])).is_err());
886 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
887 }
888
889 #[test]
890 fn print_config_reports_the_target_it_was_given_not_the_host() {
891 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
892 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
893 let text = print_config(&opts);
894 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
895 assert!(text.contains("char-signed: false"), "{text}");
896 assert!(text.contains("object-format: elf"), "{text}");
897 assert!(text.contains("va-list: void-pointer"), "{text}");
898 assert!(text.contains("registers: none"), "{text}");
901 }
902
903 #[test]
904 fn print_config_has_one_key_per_line_and_a_fixed_order() {
905 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
906 let text = print_config(&opts);
907 let keys: Vec<&str> =
908 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
909 assert_eq!(keys[0], "version");
910 assert_eq!(keys[1], "target");
911 assert_eq!(keys.len(), 18);
912 assert!(text.ends_with('\n'));
913 }
914
915 #[test]
916 fn dash_o_needs_an_argument() {
917 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
918 assert_eq!(e.message, "-o requires an argument");
919 }
920
921 #[test]
922 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
923 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
924 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
925 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
926 }
927
928 #[test]
929 fn the_include_flags_land_on_the_chain_each_one_names() {
930 let (opts, _) = compile(&[
933 "-Ii",
934 "-iquote",
935 "q",
936 "-isystem",
937 "sys",
938 "-idirafter",
939 "after",
940 "--sysroot=/nowhere-at-all",
941 "a.c",
942 ]);
943 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
944 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
947 assert!(!opts.search.dirs()[1].is_system);
948 assert!(opts.search.dirs()[2].is_system);
949 }
950
951 #[test]
952 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
953 let (opts, _) = compile(&["a.c"]);
957 let dirs = opts.search.dirs();
958 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
959 assert_eq!(ours, Some(0), "{dirs:?}");
960 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
961 let (bare, _) = compile(&["-nostdinc", "a.c"]);
962 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
963 }
964
965 #[test]
966 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
967 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
968 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
969 assert_eq!(dirs, ["sys", runtime::DIR]);
970 }
971
972 #[test]
973 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
974 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
975 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
976 assert_eq!(dirs, ["i"]);
977 }
978
979 #[test]
980 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
981 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
982 assert_eq!(opts.std, Std::C11);
983 assert!(opts.gnu_extensions);
984
985 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
986 assert_eq!(opts.std, Std::C99);
987 assert!(!opts.gnu_extensions);
988
989 let (opts, _) = compile(&["-ansi", "a.c"]);
990 assert_eq!(opts.std, Std::C89);
991 assert!(!opts.gnu_extensions);
992
993 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
994 assert!(e.message.contains("unknown dialect"), "{}", e.message);
995 }
996
997 #[test]
998 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
999 let (opts, _) = compile(&["-dM", "a.c"]);
1000 assert!(opts.dumps.macros);
1001
1002 let (opts, _) = compile(&["-dDM", "a.c"]);
1005 assert!(opts.dumps.macros);
1006 let (opts, _) = compile(&["-dD", "a.c"]);
1007 assert!(!opts.dumps.macros);
1008
1009 let (opts, _) = compile(&["a.c"]);
1010 assert!(!opts.dumps.any());
1011
1012 let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
1015 assert!(e.message.contains("unknown option"), "{}", e.message);
1016 }
1017
1018 #[test]
1019 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
1020 let (opts, _) = compile(&["a.c"]);
1021 assert_eq!(
1022 opts.gnuc,
1023 GnucVersion { major: 7, minor: 0, patch: 0 },
1024 "the lowest claim a modern glibc gives its own declarations to"
1025 );
1026
1027 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
1028 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
1029
1030 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
1033 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
1034
1035 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
1036 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
1037
1038 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
1039 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
1040
1041 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
1042 assert!(e.message.contains("more than three"), "{}", e.message);
1043 }
1044
1045 #[test]
1046 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
1047 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
1048 assert!(opts.pedantic);
1049 assert_eq!(opts.std, Std::C17);
1050
1051 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
1054 assert!(opts.pedantic);
1055
1056 let (opts, _) = compile(&["-std=c17", "a.c"]);
1057 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
1058 }
1059
1060 #[test]
1061 fn dash_p_and_dash_ffreestanding_reach_the_options() {
1062 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
1063 assert!(!opts.line_markers);
1064 assert!(!opts.hosted);
1065 assert_eq!(opts.emit, EmitKind::Preprocessed);
1066 }
1067
1068 #[test]
1071 fn the_two_frame_flags_are_read_in_both_directions() {
1072 let (opts, _) = compile(&["-c", "a.c"]);
1073 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
1074 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
1075
1076 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
1077 assert!(opts.frame_pointer);
1078 assert!(!opts.red_zone);
1079
1080 let (opts, _) = compile(&[
1081 "-c",
1082 "-fno-omit-frame-pointer",
1083 "-fomit-frame-pointer",
1084 "-mno-red-zone",
1085 "-mred-zone",
1086 "a.c",
1087 ]);
1088 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
1089 assert!(opts.red_zone);
1090 }
1091
1092 #[test]
1093 fn the_link_flags_are_collected_apart_from_the_compilation() {
1094 let (link, _) = linking(&[
1095 "-static",
1096 "-nostartfiles",
1097 "-rdynamic",
1098 "-s",
1099 "-fuse-ld=mold",
1100 "-L/opt/lib",
1101 "-B",
1102 "/opt/tools",
1103 "a.c",
1104 ]);
1105 assert!(link.is_static);
1106 assert!(link.no_startfiles);
1107 assert!(link.export_dynamic);
1108 assert!(link.strip);
1109 assert_eq!(link.use_ld.as_deref(), Some("mold"));
1110 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
1111 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
1112 }
1113
1114 #[test]
1115 fn a_comma_in_dash_wl_separates_two_arguments() {
1116 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
1117 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
1118 }
1119
1120 #[test]
1121 fn a_library_keeps_its_place_between_the_objects() {
1122 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
1127 let link = plan.link.expect("expected a link step");
1128 assert_eq!(
1129 link.inputs,
1130 vec![
1131 link::Item::File("a.o".into()),
1132 link::Item::Library("m".into()),
1133 link::Item::File("b.o".into()),
1134 ]
1135 );
1136 assert_eq!(plan.jobs.len(), 2);
1138 }
1139
1140 #[test]
1141 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1142 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
1143 assert!(plan.link.is_none());
1144 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
1145 }
1146
1147 #[test]
1148 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
1149 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
1150 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
1151 }
1152
1153 #[test]
1154 fn usage_fits_on_a_screen() {
1155 assert!(USAGE.lines().count() < 34, "usage text has grown past one screen");
1158 }
1159}