1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.3.12")]
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 "-fno-builtins-lib" => link.no_builtins_lib = true,
318 "-fbuiltins-lib" => link.no_builtins_lib = false,
319 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
320 "-s" => link.strip = true,
321 "-Xlinker" => {
322 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
323 i += 1;
324 link.passthrough.push(next.clone());
325 }
326 _ if arg.starts_with("-Wl,") => {
327 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
330 }
331 _ if arg.starts_with("-fuse-ld=") => {
332 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
333 }
334 _ if arg.starts_with("-l") && arg.len() > 2 => {
335 inputs.push(Input::library(&arg[2..]));
336 }
337 "-l" => {
338 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
339 i += 1;
340 inputs.push(Input::library(next));
341 }
342 _ if arg.starts_with("-L") => {
343 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
344 }
345 _ if arg.starts_with("-B") => {
346 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
347 }
348 _ if arg.starts_with("-j") => {
349 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
350 }
351 _ if arg.starts_with("--sysroot=") => {
352 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
353 }
354 _ if arg.starts_with("--target=") => {
355 let t = &arg["--target=".len()..];
356 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
357 }
358 _ if arg.starts_with("--emit=") => {
359 let k = &arg["--emit=".len()..];
360 opts.emit = k
361 .parse()
362 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
363 }
364 _ if arg.starts_with("-O") => {
365 opts.opt_level = arg[2..]
366 .parse()
367 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
368 }
369 _ if arg.starts_with('-') && arg.len() > 1 => {
370 return Err(err(format!("unknown option `{arg}`")));
375 }
376 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
377 }
378 }
379
380 link.sysroot = sysroot.clone();
387 if !nostdinc {
388 opts.search.push_system(runtime::DIR);
389 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
393 opts.search.push_system(dir);
394 }
395 }
396 opts.search.remove_duplicates();
400
401 if print_config {
404 return Ok(Action::PrintConfig(Box::new(opts)));
405 }
406 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
407 if print_plan {
408 return Ok(Action::PrintPlan {
409 opts: Box::new(opts),
410 plan: Box::new(plan),
411 link: Box::new(link),
412 });
413 }
414 Ok(Action::Compile {
415 opts: Box::new(opts),
416 plan: Box::new(plan),
417 link: Box::new(link),
418 jobs,
419 verbose,
420 })
421}
422
423#[must_use]
428pub fn print_config(opts: &Options) -> String {
429 let sess = Session::new(opts.clone());
430 let t = &sess.target;
431 let mut out = String::new();
432 let _ = writeln!(out, "version: {VERSION}");
433 let _ = writeln!(out, "target: {}", t.triple);
434 let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
435 let _ = writeln!(out, "os: {}", t.triple.os.as_str());
436 let _ = writeln!(out, "env: {}", t.triple.env.as_str());
437 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
438 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
439 let _ = writeln!(out, "long-width: {}", t.long_width);
440 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
441 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
442 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
443 let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
444 let regs: Vec<String> = t
447 .regs
448 .classes()
449 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
450 .collect();
451 let _ = writeln!(
452 out,
453 "registers: {}",
454 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
455 );
456 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
457 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
458 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
459 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
460 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
461 for dir in sess.opts.search.dirs() {
464 let system = if dir.is_system { " (system)" } else { "" };
465 let _ = writeln!(out, "include: {}{system}", dir.path.display());
466 }
467 out
468}
469
470fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
476 let fs = OsFileSystem::new();
477 let mut stderr = std::io::stderr().lock();
478 let mut failed = false;
479 for job in &plan.jobs {
480 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
481 continue;
484 }
485 let result = preprocess(opts, &job.input, &fs);
486 for message in &result.messages {
487 let _ = writeln!(stderr, "{message}");
488 }
489 if result.failed() {
490 failed = true;
491 continue;
492 }
493 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
494 let _ = writeln!(stderr, "rucc: error: {e}");
495 failed = true;
496 }
497 }
498 i32::from(failed)
499}
500
501fn compile_all(opts: &Options, plan: &Plan) -> i32 {
507 let fs = OsFileSystem::new();
508 let mut stderr = std::io::stderr().lock();
509 let mut failed = false;
510 for job in &plan.jobs {
511 if !job.phases.contains(&Phase::Compile) {
512 continue;
513 }
514 let result = if job.kind == InputKind::Ir {
518 compile_ir(opts, &job.input, &fs)
519 } else {
520 compile(opts, &job.input, &fs)
521 };
522 for message in &result.messages {
523 let _ = writeln!(stderr, "{message}");
524 }
525 if result.failed() {
526 failed = true;
527 continue;
528 }
529 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
530 let _ = writeln!(stderr, "rucc: error: {e}");
531 failed = true;
532 }
533 }
534 i32::from(failed)
535}
536
537struct Scratch {
544 dir: PathBuf,
546}
547
548impl Scratch {
549 fn new() -> Result<Scratch, String> {
555 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
556 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
557 Ok(Scratch { dir })
558 }
559}
560
561impl Drop for Scratch {
562 fn drop(&mut self) {
563 let _ = std::fs::remove_dir_all(&self.dir);
564 }
565}
566
567fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
574 let linker = link::find(opts.target, link)?;
575 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
576 Ok(link::render(&linker, &args))
577}
578
579fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
586 let Some(job) = &plan.link else {
587 let mut stderr = std::io::stderr().lock();
590 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
591 return 1;
592 };
593 let linker = match link::find(opts.target, link) {
596 Ok(linker) => linker,
597 Err(why) => return complain(why),
598 };
599
600 let scratch = match Scratch::new() {
601 Ok(scratch) => scratch,
602 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
603 };
604
605 let fs = OsFileSystem::new();
606 let mut failed = false;
607 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
610 {
611 let mut stderr = std::io::stderr().lock();
612 for (at, job) in plan.jobs.iter().enumerate() {
613 let out = match &job.output {
614 Output::Temporary(hint) => {
615 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
618 }
619 Output::File(path) => path.clone(),
620 Output::Stdout => continue,
623 };
624 produced.push(out.clone());
625 if !job.phases.contains(&Phase::Compile) {
626 continue;
627 }
628 let result = if job.kind == InputKind::Ir {
629 compile_ir(opts, &job.input, &fs)
630 } else {
631 compile(opts, &job.input, &fs)
632 };
633 for message in &result.messages {
634 let _ = writeln!(stderr, "{message}");
635 }
636 if result.failed() {
637 failed = true;
638 continue;
639 }
640 if !matches!(result.artifact, Artifact::Object(_)) {
641 let _ = writeln!(
646 stderr,
647 "rucc: internal error: {}: no object file was produced for the link",
648 job.input
649 );
650 failed = true;
651 continue;
652 }
653 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
654 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
655 failed = true;
656 }
657 }
658 }
659 if failed {
660 return 1;
664 }
665
666 let mut outputs = produced.into_iter();
670 let mut items = Vec::with_capacity(job.inputs.len());
671 for item in &job.inputs {
672 match item {
673 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
674 link::Item::File(_) => match outputs.next() {
675 Some(path) => items.push(link::Item::File(path)),
676 None => return complain("the plan asks the linker for a file nothing produced"),
677 },
678 }
679 }
680
681 let args = match link::line(opts.target, link, &items, &job.output) {
682 Ok(args) => args,
683 Err(why) => return complain(why),
684 };
685 if verbose {
686 let mut stderr = std::io::stderr().lock();
687 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
688 }
689 match link::run(&linker, &args) {
690 Ok(()) => 0,
691 Err(link::Error::Refused { .. }) => 1,
694 Err(why) => complain(why),
695 }
696}
697
698fn complain(why: impl std::fmt::Display) -> i32 {
700 let mut stderr = std::io::stderr().lock();
701 let _ = writeln!(stderr, "rucc: error: {why}");
702 1
703}
704
705fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
712 match output {
713 Output::Stdout => {
714 let mut stdout = std::io::stdout().lock();
715 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
716 }
717 Output::File(path) | Output::Temporary(path) => {
718 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
719 }
720 }
721}
722
723pub fn run(args: &[String]) -> i32 {
728 match parse_args(args) {
729 Ok(Action::Help) => {
730 print!("{USAGE}");
731 0
732 }
733 Ok(Action::Version) => {
734 println!("rucc {VERSION}");
735 0
736 }
737 Ok(Action::PrintConfig(opts)) => {
738 print!("{}", print_config(&opts));
739 0
740 }
741 Ok(Action::PrintPlan { opts, plan, link }) => {
742 print!("{}", plan.render());
743 if let Some(job) = &plan.link {
747 match link_line(&opts, &link, job) {
748 Ok(line) => println!("{line}"),
749 Err(why) => {
750 let mut stderr = std::io::stderr().lock();
751 let _ = writeln!(stderr, "rucc: error: {why}");
752 return 1;
753 }
754 }
755 }
756 0
757 }
758 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
759 {
760 let mut stderr = std::io::stderr().lock();
761 if verbose {
762 let _ = write!(stderr, "{}", plan.render());
763 let _ = writeln!(stderr, "workers: {}", jobs.count());
764 }
765 }
766 if opts.emit == EmitKind::Preprocessed {
767 return preprocess_all(&opts, &plan);
768 }
769 if opts.emit != EmitKind::Executable {
770 return compile_all(&opts, &plan);
771 }
772 link_all(&opts, &plan, &link, verbose)
773 }
774 Err(e) => {
775 let mut stderr = std::io::stderr().lock();
776 let _ = writeln!(stderr, "rucc: error: {e}");
777 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
778 1
779 }
780 }
781}
782
783#[cfg(test)]
784mod tests {
785 use rucc_session::{GnucVersion, OptLevel};
786
787 use super::*;
788
789 fn args(s: &[&str]) -> Vec<String> {
790 s.iter().map(|x| (*x).to_owned()).collect()
791 }
792
793 #[test]
794 fn help_and_version_win_over_everything_else() {
795 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
796 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
797 }
798
799 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
800 match parse_args(&args(s)).expect("expected a compilation") {
801 Action::Compile { opts, plan, .. } => (opts, plan),
802 other => panic!("expected a compilation, got {other:?}"),
803 }
804 }
805
806 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
807 match parse_args(&args(s)).expect("expected a compilation") {
808 Action::Compile { link, plan, .. } => (link, plan),
809 other => panic!("expected a compilation, got {other:?}"),
810 }
811 }
812
813 #[test]
814 fn collects_inputs_and_flags() {
815 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
816 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
817 assert_eq!(paths, vec!["a.c", "b.c"]);
818 assert_eq!(opts.opt_level, OptLevel::O2);
819 assert_eq!(opts.emit, EmitKind::Object);
820 assert!(opts.debug_info);
821 }
822
823 #[test]
824 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
825 let (opts, _) = compile(&["-O", "a.c"]);
826 assert_eq!(opts.opt_level, OptLevel::O1);
827 }
828
829 #[test]
830 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
831 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
832 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
833 assert_eq!(plan.jobs[1].kind, InputKind::C);
834 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
835 }
836
837 #[test]
838 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
839 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
840 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
841 other => panic!("expected a compilation, got {other:?}"),
842 };
843 assert_eq!(jobs.count(), 4);
844
845 let default = match parse_args(&args(&["a.c"])).unwrap() {
846 Action::Compile { jobs, .. } => jobs,
847 other => panic!("expected a compilation, got {other:?}"),
848 };
849 assert_eq!(default, Jobs::available());
850 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
851 }
852
853 #[test]
854 fn triple_hash_prints_the_plan_and_runs_nothing() {
855 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
856 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
857 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
858 }
859
860 #[test]
861 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
862 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
863 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
864 }
865
866 #[test]
867 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
868 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
869 assert!(e.message.contains("unknown option"), "{}", e.message);
870 }
871
872 #[test]
873 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
874 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
875 assert!(e.message.contains("trampoline"), "{}", e.message);
876 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
877 }
878
879 #[test]
880 fn an_unsupported_target_names_itself() {
881 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
882 assert!(e.message.contains("sparc64"), "{}", e.message);
883 }
884
885 #[test]
886 fn no_inputs_is_an_error_but_print_config_needs_none() {
887 assert!(parse_args(&args(&[])).is_err());
888 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
889 }
890
891 #[test]
892 fn print_config_reports_the_target_it_was_given_not_the_host() {
893 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
894 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
895 let text = print_config(&opts);
896 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
897 assert!(text.contains("char-signed: false"), "{text}");
898 assert!(text.contains("object-format: elf"), "{text}");
899 assert!(text.contains("va-list: void-pointer"), "{text}");
900 assert!(text.contains("registers: none"), "{text}");
903 }
904
905 #[test]
906 fn print_config_has_one_key_per_line_and_a_fixed_order() {
907 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
908 let text = print_config(&opts);
909 let keys: Vec<&str> =
910 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
911 assert_eq!(keys[0], "version");
912 assert_eq!(keys[1], "target");
913 assert_eq!(keys.len(), 18);
914 assert!(text.ends_with('\n'));
915 }
916
917 #[test]
918 fn dash_o_needs_an_argument() {
919 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
920 assert_eq!(e.message, "-o requires an argument");
921 }
922
923 #[test]
924 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
925 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
926 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
927 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
928 }
929
930 #[test]
931 fn the_include_flags_land_on_the_chain_each_one_names() {
932 let (opts, _) = compile(&[
935 "-Ii",
936 "-iquote",
937 "q",
938 "-isystem",
939 "sys",
940 "-idirafter",
941 "after",
942 "--sysroot=/nowhere-at-all",
943 "a.c",
944 ]);
945 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
946 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
949 assert!(!opts.search.dirs()[1].is_system);
950 assert!(opts.search.dirs()[2].is_system);
951 }
952
953 #[test]
954 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
955 let (opts, _) = compile(&["a.c"]);
959 let dirs = opts.search.dirs();
960 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
961 assert_eq!(ours, Some(0), "{dirs:?}");
962 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
963 let (bare, _) = compile(&["-nostdinc", "a.c"]);
964 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
965 }
966
967 #[test]
968 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
969 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
970 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
971 assert_eq!(dirs, ["sys", runtime::DIR]);
972 }
973
974 #[test]
975 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
976 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
977 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
978 assert_eq!(dirs, ["i"]);
979 }
980
981 #[test]
982 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
983 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
984 assert_eq!(opts.std, Std::C11);
985 assert!(opts.gnu_extensions);
986
987 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
988 assert_eq!(opts.std, Std::C99);
989 assert!(!opts.gnu_extensions);
990
991 let (opts, _) = compile(&["-ansi", "a.c"]);
992 assert_eq!(opts.std, Std::C89);
993 assert!(!opts.gnu_extensions);
994
995 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
996 assert!(e.message.contains("unknown dialect"), "{}", e.message);
997 }
998
999 #[test]
1000 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
1001 let (opts, _) = compile(&["-dM", "a.c"]);
1002 assert!(opts.dumps.macros);
1003
1004 let (opts, _) = compile(&["-dDM", "a.c"]);
1007 assert!(opts.dumps.macros);
1008 let (opts, _) = compile(&["-dD", "a.c"]);
1009 assert!(!opts.dumps.macros);
1010
1011 let (opts, _) = compile(&["a.c"]);
1012 assert!(!opts.dumps.any());
1013
1014 let e = parse_args(&args(&["-dumpversion", "a.c"])).unwrap_err();
1017 assert!(e.message.contains("unknown option"), "{}", e.message);
1018 }
1019
1020 #[test]
1021 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
1022 let (opts, _) = compile(&["a.c"]);
1023 assert_eq!(
1024 opts.gnuc,
1025 GnucVersion { major: 7, minor: 0, patch: 0 },
1026 "the lowest claim a modern glibc gives its own declarations to"
1027 );
1028
1029 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
1030 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
1031
1032 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
1035 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
1036
1037 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
1038 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
1039
1040 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
1041 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
1042
1043 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
1044 assert!(e.message.contains("more than three"), "{}", e.message);
1045 }
1046
1047 #[test]
1048 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
1049 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
1050 assert!(opts.pedantic);
1051 assert_eq!(opts.std, Std::C17);
1052
1053 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
1056 assert!(opts.pedantic);
1057
1058 let (opts, _) = compile(&["-std=c17", "a.c"]);
1059 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
1060 }
1061
1062 #[test]
1063 fn dash_p_and_dash_ffreestanding_reach_the_options() {
1064 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
1065 assert!(!opts.line_markers);
1066 assert!(!opts.hosted);
1067 assert_eq!(opts.emit, EmitKind::Preprocessed);
1068 }
1069
1070 #[test]
1073 fn the_two_frame_flags_are_read_in_both_directions() {
1074 let (opts, _) = compile(&["-c", "a.c"]);
1075 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
1076 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
1077
1078 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
1079 assert!(opts.frame_pointer);
1080 assert!(!opts.red_zone);
1081
1082 let (opts, _) = compile(&[
1083 "-c",
1084 "-fno-omit-frame-pointer",
1085 "-fomit-frame-pointer",
1086 "-mno-red-zone",
1087 "-mred-zone",
1088 "a.c",
1089 ]);
1090 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
1091 assert!(opts.red_zone);
1092 }
1093
1094 #[test]
1095 fn the_link_flags_are_collected_apart_from_the_compilation() {
1096 let (link, _) = linking(&[
1097 "-static",
1098 "-nostartfiles",
1099 "-rdynamic",
1100 "-s",
1101 "-fuse-ld=mold",
1102 "-L/opt/lib",
1103 "-B",
1104 "/opt/tools",
1105 "a.c",
1106 ]);
1107 assert!(link.is_static);
1108 assert!(link.no_startfiles);
1109 assert!(link.export_dynamic);
1110 assert!(link.strip);
1111 assert_eq!(link.use_ld.as_deref(), Some("mold"));
1112 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
1113 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
1114 }
1115
1116 #[test]
1117 fn a_comma_in_dash_wl_separates_two_arguments() {
1118 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
1119 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
1120 }
1121
1122 #[test]
1123 fn a_library_keeps_its_place_between_the_objects() {
1124 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
1129 let link = plan.link.expect("expected a link step");
1130 assert_eq!(
1131 link.inputs,
1132 vec![
1133 link::Item::File("a.o".into()),
1134 link::Item::Library("m".into()),
1135 link::Item::File("b.o".into()),
1136 ]
1137 );
1138 assert_eq!(plan.jobs.len(), 2);
1140 }
1141
1142 #[test]
1143 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1144 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
1145 assert!(plan.link.is_none());
1146 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
1147 }
1148
1149 #[test]
1150 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
1151 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
1152 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
1153 }
1154
1155 #[test]
1156 fn usage_fits_on_a_screen() {
1157 assert!(USAGE.lines().count() < 34, "usage text has grown past one screen");
1160 }
1161}