1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.7.3")]
29
30pub mod compile;
31pub mod library;
32pub mod link;
33mod map;
34pub mod phase;
35pub mod preprocess;
36pub mod schedule;
37
38use std::fmt::Write as _;
39use std::io::Write as _;
40use std::path::PathBuf;
41
42use rucc_codegen::coverage::{self, Fired};
43use rucc_session::{Dumps, EmitKind, Options, Session, Std, runtime};
44use rucc_target::Triple;
45
46use crate::link::LinkOptions;
47
48pub use crate::compile::{Artifact, Compiled, compile, compile_ir};
49pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
50pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
51pub use crate::schedule::Jobs;
52
53pub const VERSION: &str = env!("CARGO_PKG_VERSION");
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Action {
59 Help,
61 Version,
63 Print(String),
69 PrintConfig(Box<Options>),
71 PrintPipeline(Box<Options>),
73 PrintPlan {
75 opts: Box<Options>,
77 plan: Box<Plan>,
79 link: Box<LinkOptions>,
81 },
82 Compile {
84 opts: Box<Options>,
86 plan: Box<Plan>,
88 link: Box<LinkOptions>,
90 jobs: Jobs,
92 verbose: bool,
94 },
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct CliError {
100 pub message: String,
103}
104
105impl std::fmt::Display for CliError {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.write_str(&self.message)
108 }
109}
110
111impl std::error::Error for CliError {}
112
113fn err(message: impl Into<String>) -> CliError {
114 CliError { message: message.into() }
115}
116
117enum Query {
123 Machine,
125 Version,
127 Multiarch,
129 SearchDirs,
131 FileName(String),
133 ProgName(String),
135 Libgcc,
137}
138
139pub const USAGE: &str = "\
144rucc, an optimizing C compiler
145
146usage: rucc [options] file...
147
148options:
149 -c compile and assemble, do not link
150 -S compile only, emit assembly
151 -E preprocess only
152 -o <file> write output to <file>, or to standard output for -
153 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
154 -I <dir> add <dir> to the include search path
155 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
156 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
157 -P, -dM with -E: leave out the markers, or dump the macros
158 -std=<dialect> c89 through c23, and the gnu spellings
159 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
160 -x <lang> treat later inputs as <lang>, or none to stop
161 -O<level> optimize: 0, 1, 2, 3, s, z
162 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
163 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
164 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
165 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
166 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
167 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
168 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
169 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
170 -Werror -pedantic -pedantic-errors -w how much to say, and whether it is fatal
171 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
172 -pthread build for more than one thread, and link the library for it
173 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
174 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
175 -j[n] compile n translation units at once, default all
176 -v, -### print each phase as it runs, or without running any
177 --target=<triple> generate code for <triple>
178 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
179 safety-summary, type-granules
180 --print-config, --print-pipeline print the configuration or the pipeline, and exit
181 --version print the version and exit
182 -h, --help print this message and exit
183
184See spec/04-driver-and-cli.md for the full flag reference.
185";
186
187fn joined_or_next(
191 arg: &str,
192 at: usize,
193 args: &[String],
194 i: &mut usize,
195) -> Result<String, CliError> {
196 if arg.len() > at {
197 return Ok(arg[at..].to_owned());
198 }
199 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
200 *i += 1;
201 Ok(next.clone())
202}
203
204pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
211 let host = Triple::host()
212 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
213 let mut opts = Options::new(host);
214 let mut inputs: Vec<Input> = Vec::new();
215 let mut print_config = false;
216 let mut print_pipeline = false;
217 let mut print_plan = false;
218 let mut verbose = false;
219 let mut jobs = Jobs::default();
220 let mut nostdinc = false;
221 let mut sysroot: Option<PathBuf> = None;
222 let mut output = None;
223 let mut link = LinkOptions::default();
224 let mut query: Option<Query> = None;
225 let mut threads = false;
226 let mut forced: Option<InputKind> = None;
229
230 let mut i = 0;
231 while i < args.len() {
232 let arg = args[i].as_str();
233 i += 1;
234 match arg {
235 "-h" | "--help" => return Ok(Action::Help),
236 "--version" => return Ok(Action::Version),
237 "--print-config" => print_config = true,
238 "--print-pipeline" => print_pipeline = true,
239 "-###" => print_plan = true,
240 "-v" => verbose = true,
241 "-c" => opts.emit = EmitKind::Object,
242 "-S" => opts.emit = EmitKind::Asm,
243 "-E" => opts.emit = EmitKind::Preprocessed,
244 "-g" => opts.debug_info = true,
245 "-g0" => opts.debug_info = false,
250 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
251 opts.debug_info = true;
252 }
253 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
256 _ if arg.starts_with("-gdwarf-") => {
257 return Err(err(format!(
258 "{arg}: this compiler writes DWARF 5 and no other version, see \
259 spec/11-debug-info.md"
260 )));
261 }
262 "-Werror" => opts.warnings_are_errors = true,
263 "-w" => opts.warnings = false,
266 "-pedantic-errors" => {
267 opts.pedantic = true;
268 opts.warnings_are_errors = true;
269 }
270 "-P" => opts.line_markers = false,
271 "-dumpmachine" => query = Some(Query::Machine),
275 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
276 "-print-multiarch" => query = Some(Query::Multiarch),
277 "-print-search-dirs" => query = Some(Query::SearchDirs),
278 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
279 _ if arg.starts_with("-print-file-name=") => {
280 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
281 }
282 _ if arg.starts_with("-print-prog-name=") => {
283 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
284 }
285 "-pthread" | "-pthreads" => {
290 opts.defines.push("_REENTRANT".to_owned());
291 threads = true;
292 }
293 "-ansi" => {
294 opts.std = Std::C89;
295 opts.gnu_extensions = false;
296 }
297 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
300 "-ffreestanding" => opts.hosted = false,
301 "-fhosted" => opts.hosted = true,
302 "-fno-builtin" => opts.builtins = false,
303 "-fbuiltin" => opts.builtins = true,
304 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
307 "-fomit-frame-pointer" => opts.frame_pointer = false,
308 "-mno-red-zone" => opts.red_zone = false,
309 "-mred-zone" => opts.red_zone = true,
310 "-nostdinc" => nostdinc = true,
314 "-o" => {
315 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
316 i += 1;
317 }
318 "-isysroot" => {
325 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
326 i += 1;
327 sysroot = Some(PathBuf::from(dir));
328 }
329 "-iquote" | "-isystem" | "-idirafter" => {
330 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
331 i += 1;
332 match arg {
333 "-iquote" => opts.search.push_quote(dir.clone()),
334 "-isystem" => opts.search.push_system(dir.clone()),
335 _ => opts.search.push_after(dir.clone()),
336 }
337 }
338 "-x" => {
339 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
340 i += 1;
341 forced = if lang == "none" {
342 None
343 } else {
344 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
345 };
346 }
347 _ if arg.starts_with("-D") => {
355 let value = joined_or_next(arg, 2, args, &mut i)?;
356 opts.defines.push(value);
357 }
358 _ if arg.starts_with("-U") => {
359 let value = joined_or_next(arg, 2, args, &mut i)?;
360 opts.undefines.push(value);
361 }
362 _ if arg.starts_with("-I") => {
363 let dir = joined_or_next(arg, 2, args, &mut i)?;
364 opts.search.push_bracket(dir);
365 }
366 _ if arg.starts_with("-std=") => {
367 let name = &arg["-std=".len()..];
368 let (std, gnu) = Std::from_flag(name)
369 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
370 opts.std = std;
371 opts.gnu_extensions = gnu;
372 }
373 _ if Dumps::is_family(arg) => {
382 opts.dumps.add(&arg[2..]);
383 }
384 _ if arg.starts_with("-fno-builtin-") => {
389 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
390 }
391 _ if arg.starts_with("-fgnuc-version=") => {
392 let v = &arg["-fgnuc-version=".len()..];
393 opts.gnuc = v.parse().map_err(err)?;
394 }
395 "-fnested-functions" => {
400 return Err(err(
401 "nested functions are not supported: a call to one goes through a trampoline \
402 written on the stack, which no target that enforces an unexecutable stack \
403 allows",
404 ));
405 }
406 "-fno-nested-functions" => {}
407 "-static" => link.is_static = true,
411 "-shared" => link.shared = true,
412 "-pie" => link.pie = Some(true),
413 "-no-pie" | "-nopie" => link.pie = Some(false),
414 "-nostdlib" => link.no_stdlib = true,
415 "-nostartfiles" => link.no_startfiles = true,
416 "-nodefaultlibs" => link.no_defaultlibs = true,
417 "-fno-builtins-lib" => link.no_builtins_lib = true,
418 "-fbuiltins-lib" => link.no_builtins_lib = false,
419 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
420 "-s" => link.strip = true,
421 "-Xlinker" => {
422 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
423 i += 1;
424 link.passthrough.push(next.clone());
425 }
426 _ if arg.starts_with("-Wl,") => {
427 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
430 }
431 _ if arg.starts_with("-fuse-ld=") => {
432 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
433 }
434 _ if arg.starts_with("-l") && arg.len() > 2 => {
435 inputs.push(Input::library(&arg[2..]));
436 }
437 "-l" => {
438 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
439 i += 1;
440 inputs.push(Input::library(next));
441 }
442 _ if arg.starts_with("-L") => {
443 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
444 }
445 _ if arg.starts_with("-B") => {
446 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
447 }
448 _ if arg.starts_with("-j") => {
449 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
450 }
451 _ if arg.starts_with("--sysroot=") => {
452 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
453 }
454 _ if arg.starts_with("--target=") => {
455 let t = &arg["--target=".len()..];
456 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
457 }
458 _ if arg.starts_with("--emit=") => {
459 let k = &arg["--emit=".len()..];
460 opts.emit = k
461 .parse()
462 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
463 }
464 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
470 "-Ofast" => {
476 return Err(err(
477 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
478 spec/04-driver-and-cli.md section 4.6",
479 ));
480 }
481 _ if arg.starts_with("-O") => {
482 opts.opt_level = arg[2..]
483 .parse()
484 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
485 }
486 _ if arg.starts_with("-fsafety=") => {
491 let tier = &arg["-fsafety=".len()..];
492 opts.safety = tier.parse().map_err(|()| {
493 err(format!(
494 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
495 ))
496 })?;
497 }
498 _ if arg.starts_with("-fpass-fuel=") => {
502 let (name, count) = arg["-fpass-fuel=".len()..]
503 .split_once('=')
504 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
505 if rucc_opt::pass::find(name).is_none() {
506 return Err(err(format!(
507 "`{name}` is not a pass this compiler has, see --print-pipeline"
508 )));
509 }
510 let count: u32 = count
511 .parse()
512 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
513 opts.pass_fuel.push((name.to_owned(), count));
514 }
515 _ if arg.starts_with("-fpass-fuel-global=") => {
516 let count = &arg["-fpass-fuel-global=".len()..];
517 let count: u32 = count
518 .parse()
519 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
520 opts.pass_fuel_global = Some(count);
521 }
522 _ if arg == "-fopt-info"
527 || arg.starts_with("-fopt-info=")
528 || arg.starts_with("-fopt-info-") =>
529 {
530 let rest = &arg["-fopt-info".len()..];
531 let (kinds, file) = match rest.split_once('=') {
532 Some((kinds, file)) => (kinds, Some(file)),
533 None => (rest, None),
534 };
535 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
536 rucc_opt::Wants::none().add(kinds).map_err(err)?;
537 opts.opt_info.push(kinds.to_owned());
538 if let Some(file) = file {
539 if file.is_empty() {
540 return Err(err("-fopt-info= was given no file to write to"));
541 }
542 opts.opt_info_file = Some(file.to_owned());
543 }
544 }
545 _ if arg.starts_with("-fdump-ir=") => {
546 let spec = &arg["-fdump-ir=".len()..];
549 rucc_opt::Dumps::default().add(spec).map_err(err)?;
550 opts.dump_ir.push(spec.to_owned());
551 }
552 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
558 let on = arg.starts_with("-fenable-");
559 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
560 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
561 opts.pass_gates.push((on, spec.to_owned()));
562 }
563 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
564 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
565 }
566 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
567 opts.passes.push((arg["-f".len()..].to_owned(), true));
568 }
569 "-Zverify-each" => opts.verify_each = true,
575 _ if arg.starts_with("-Zrule-coverage=") => {
576 let file = &arg["-Zrule-coverage=".len()..];
577 if file.is_empty() {
578 return Err(err("-Zrule-coverage= needs a file to write to"));
579 }
580 opts.rule_coverage = Some(file.to_owned());
581 }
582 _ if arg.starts_with("-Z") => {
583 return Err(err(format!(
584 "`{arg}` is not an unstable option this compiler has, see \
585 spec/04-driver-and-cli.md section 4.11 for the ones it does"
586 )));
587 }
588 "-m64" | "-m32" | "-mx32" => {
593 let want: u32 = match arg {
594 "-m64" => 64,
595 _ => 32,
596 };
597 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
598 if have != want {
599 return Err(err(format!(
600 "{arg} asks for a {want} bit target and {} is {have} bit, use \
601 --target= to name the one you mean",
602 opts.target
603 )));
604 }
605 }
606 _ if arg.starts_with("-march=")
612 || arg.starts_with("-mtune=")
613 || arg.starts_with("-mcpu=") => {}
614 _ if arg.starts_with("-mabi=") => {
617 let want = &arg["-mabi=".len()..];
618 let have = match opts.target.arch {
619 rucc_target::Arch::X86_64 => "sysv",
620 rucc_target::Arch::Aarch64 => "lp64",
621 rucc_target::Arch::Riscv64 => "lp64d",
622 };
623 if want != have {
624 return Err(err(format!(
625 "{arg}: {} uses the {have} convention and this compiler has no other",
626 opts.target
627 )));
628 }
629 }
630 "-mcmodel=small" => {}
634 _ if arg.starts_with("-mcmodel=") => {
635 return Err(err(format!(
636 "{arg}: this compiler emits the small code model and no other, see \
637 spec/12-targets.md"
638 )));
639 }
640 _ if arg.starts_with("-specs=") => {
644 return Err(err(
645 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
646 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
647 section 4.4",
648 ));
649 }
650 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
656 return Err(err(format!(
657 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
658 are inside this compiler rather than programs it runs"
659 )));
660 }
661 "-Xassembler" | "-Xpreprocessor" => {
662 return Err(err(format!(
663 "{arg} hands an argument to a separate assembler or preprocessor, and both \
664 are inside this compiler rather than programs it runs"
665 )));
666 }
667 _ if arg.starts_with("-W") => {}
674 "-fno-ident"
680 | "-fident"
681 | "-funit-at-a-time"
682 | "-fno-unit-at-a-time"
683 | "-shared-libgcc"
684 | "-static-libgcc" => {}
685 _ if arg.starts_with('-') && arg.len() > 1 => {
686 return Err(err(format!("unknown option `{arg}`")));
691 }
692 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
693 }
694 }
695
696 link.sysroot = sysroot.clone();
703 if threads {
708 inputs.push(Input::library("pthread"));
709 }
710 if let Some(query) = query {
711 return Ok(Action::Print(answer(&query, &opts, &link)));
712 }
713 if !nostdinc {
714 opts.search.push_system(runtime::DIR);
715 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
719 opts.search.push_system(dir);
720 }
721 }
722 opts.search.remove_duplicates();
726
727 if print_config {
730 return Ok(Action::PrintConfig(Box::new(opts)));
731 }
732 if print_pipeline {
733 return Ok(Action::PrintPipeline(Box::new(opts)));
734 }
735 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
736 if print_plan {
737 return Ok(Action::PrintPlan {
738 opts: Box::new(opts),
739 plan: Box::new(plan),
740 link: Box::new(link),
741 });
742 }
743 Ok(Action::Compile {
744 opts: Box::new(opts),
745 plan: Box::new(plan),
746 link: Box::new(link),
747 jobs,
748 verbose,
749 })
750}
751
752fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
758 let found = |name: &str| {
759 link::find_in_search(link, opts.target, name)
760 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
761 };
762 match query {
763 Query::Machine => opts.target.to_string(),
764 Query::Version => VERSION.to_owned(),
765 Query::Multiarch => link::multiarch(opts.target),
766 Query::SearchDirs => {
771 let here = std::env::current_exe()
772 .ok()
773 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
774 .unwrap_or_default();
775 let list = |dirs: &[PathBuf]| {
776 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
777 };
778 let libraries = link::search_dirs(link, opts.target);
779 format!(
780 "install: {}\nprograms: ={}\nlibraries: ={}",
781 here.display(),
782 list(&link.prefixes),
783 list(&libraries)
784 )
785 }
786 Query::FileName(name) => found(name),
787 Query::Libgcc => found("libgcc.a"),
791 Query::ProgName(name) => link
795 .prefixes
796 .iter()
797 .map(|dir| dir.join(name))
798 .find(|path| path.is_file())
799 .map_or_else(|| name.clone(), |path| path.display().to_string()),
800 }
801}
802
803#[must_use]
809pub fn print_pipeline(opts: &Options) -> String {
810 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
811 settings.toggles.clone_from(&opts.passes);
812 settings.global_fuel = opts.pass_fuel_global;
813 for (on, spec) in &opts.pass_gates {
814 let _ = settings.gates.add(*on, spec);
817 }
818 rucc_opt::pipeline::print(&settings)
819}
820
821#[must_use]
826pub fn print_config(opts: &Options) -> String {
827 let sess = Session::new(opts.clone());
828 let t = &sess.target;
829 let mut out = String::new();
830 let _ = writeln!(out, "version: {VERSION}");
831 let _ = writeln!(out, "target: {}", t.triple);
832 let _ = writeln!(out, "arch: {}", t.triple.arch.as_str());
833 let _ = writeln!(out, "os: {}", t.triple.os.as_str());
834 let _ = writeln!(out, "env: {}", t.triple.env.as_str());
835 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
836 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
837 let _ = writeln!(out, "long-width: {}", t.long_width);
838 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
839 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
840 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
841 let _ = writeln!(out, "va-list: {}", t.va_list.as_str());
842 let regs: Vec<String> = t
845 .regs
846 .classes()
847 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
848 .collect();
849 let _ = writeln!(
850 out,
851 "registers: {}",
852 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
853 );
854 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
855 let _ = writeln!(out, "safety: {}", sess.opts.safety);
856 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
857 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
858 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
859 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
860 for dir in sess.opts.search.dirs() {
863 let system = if dir.is_system { " (system)" } else { "" };
864 let _ = writeln!(out, "include: {}{system}", dir.path.display());
865 }
866 out
867}
868
869fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
875 let fs = OsFileSystem::new();
876 let mut stderr = std::io::stderr().lock();
877 let mut failed = false;
878 for job in &plan.jobs {
879 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
880 continue;
883 }
884 let result = preprocess(opts, &job.input, &fs);
885 for message in &result.messages {
886 let _ = writeln!(stderr, "{message}");
887 }
888 if result.failed() {
889 failed = true;
890 continue;
891 }
892 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
893 let _ = writeln!(stderr, "rucc: error: {e}");
894 failed = true;
895 }
896 }
897 i32::from(failed)
898}
899
900fn compile_all(opts: &Options, plan: &Plan) -> i32 {
906 let fs = OsFileSystem::new();
907 let mut stderr = std::io::stderr().lock();
908 let mut failed = false;
909 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
910 failed |= !ok;
911 let mut fired = Fired::new();
912 for job in &plan.jobs {
913 if !job.phases.contains(&Phase::Compile) {
914 continue;
915 }
916 let result = if job.kind == InputKind::Ir {
920 compile_ir(opts, &job.input, &fs)
921 } else {
922 compile(opts, &job.input, &fs)
923 };
924 fired.merge(&result.fired);
925 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
926 failed |= !remarks.write(&result.remarks, &mut stderr);
927 for message in &result.messages {
928 let _ = writeln!(stderr, "{message}");
929 }
930 if result.failed() {
931 failed = true;
932 continue;
933 }
934 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
935 let _ = writeln!(stderr, "rucc: error: {e}");
936 failed = true;
937 }
938 }
939 failed |= !write_coverage(opts, &fired, &mut stderr);
940 i32::from(failed)
941}
942
943struct Scratch {
950 dir: PathBuf,
952}
953
954impl Scratch {
955 fn new() -> Result<Scratch, String> {
961 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
962 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
963 Ok(Scratch { dir })
964 }
965}
966
967impl Drop for Scratch {
968 fn drop(&mut self) {
969 let _ = std::fs::remove_dir_all(&self.dir);
970 }
971}
972
973fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
980 let linker = link::find(opts.target, link)?;
981 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
982 Ok(link::render(&linker, &args))
983}
984
985fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
992 let Some(job) = &plan.link else {
993 let mut stderr = std::io::stderr().lock();
996 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
997 return 1;
998 };
999 let linker = match link::find(opts.target, link) {
1002 Ok(linker) => linker,
1003 Err(why) => return complain(why),
1004 };
1005
1006 let scratch = match Scratch::new() {
1007 Ok(scratch) => scratch,
1008 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1009 };
1010
1011 let fs = OsFileSystem::new();
1012 let mut failed = false;
1013 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1016 let mut fired = Fired::new();
1017 {
1018 let mut stderr = std::io::stderr().lock();
1019 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1020 failed |= !ok;
1021 for (at, job) in plan.jobs.iter().enumerate() {
1022 let out = match &job.output {
1023 Output::Temporary(hint) => {
1024 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1027 }
1028 Output::File(path) => path.clone(),
1029 Output::Stdout => continue,
1032 };
1033 produced.push(out.clone());
1034 if !job.phases.contains(&Phase::Compile) {
1035 continue;
1036 }
1037 let result = if job.kind == InputKind::Ir {
1038 compile_ir(opts, &job.input, &fs)
1039 } else {
1040 compile(opts, &job.input, &fs)
1041 };
1042 fired.merge(&result.fired);
1043 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1044 failed |= !remarks.write(&result.remarks, &mut stderr);
1045 for message in &result.messages {
1046 let _ = writeln!(stderr, "{message}");
1047 }
1048 if result.failed() {
1049 failed = true;
1050 continue;
1051 }
1052 if !matches!(result.artifact, Artifact::Object(_)) {
1053 let _ = writeln!(
1058 stderr,
1059 "rucc: internal error: {}: no object file was produced for the link",
1060 job.input
1061 );
1062 failed = true;
1063 continue;
1064 }
1065 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1066 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1067 failed = true;
1068 }
1069 }
1070 failed |= !write_coverage(opts, &fired, &mut stderr);
1071 }
1072 if failed {
1073 return 1;
1077 }
1078
1079 let mut outputs = produced.into_iter();
1083 let mut items = Vec::with_capacity(job.inputs.len());
1084 for item in &job.inputs {
1085 match item {
1086 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1087 link::Item::File(_) => match outputs.next() {
1088 Some(path) => items.push(link::Item::File(path)),
1089 None => return complain("the plan asks the linker for a file nothing produced"),
1090 },
1091 }
1092 }
1093
1094 let args = match link::line(opts.target, link, &items, &job.output) {
1095 Ok(args) => args,
1096 Err(why) => return complain(why),
1097 };
1098 if verbose {
1099 let mut stderr = std::io::stderr().lock();
1100 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1101 }
1102 match link::run(&linker, &args) {
1103 Ok(()) => 0,
1104 Err(link::Error::Refused { .. }) => 1,
1107 Err(why) => complain(why),
1108 }
1109}
1110
1111fn complain(why: impl std::fmt::Display) -> i32 {
1113 let mut stderr = std::io::stderr().lock();
1114 let _ = writeln!(stderr, "rucc: error: {why}");
1115 1
1116}
1117
1118fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1127 let Some(path) = &opts.rule_coverage else { return true };
1128 let Some(table) = coverage::table(opts.target.arch) else {
1129 let _ = writeln!(
1130 stderr,
1131 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1132 to report",
1133 opts.target
1134 );
1135 return false;
1136 };
1137 match std::fs::write(path, fired.listing(table)) {
1138 Ok(()) => true,
1139 Err(e) => {
1140 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1141 false
1142 }
1143 }
1144}
1145
1146struct Remarks {
1153 file: Option<String>,
1155 started: bool,
1158}
1159
1160impl Remarks {
1161 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1167 let mut ok = true;
1168 if let Some(path) = file {
1169 if let Err(e) = std::fs::write(path, "") {
1170 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1171 ok = false;
1172 }
1173 }
1174 (Self { file: file.cloned(), started: false }, ok)
1175 }
1176
1177 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1183 if text.is_empty() {
1184 return true;
1185 }
1186 let Some(path) = &self.file else {
1187 let _ = write!(stderr, "{text}");
1188 return true;
1189 };
1190 let opened = std::fs::OpenOptions::new()
1191 .write(true)
1192 .append(self.started)
1193 .truncate(!self.started)
1194 .create(true)
1195 .open(path);
1196 self.started = true;
1197 let result =
1198 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1199 if let Err(e) = result {
1200 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1201 return false;
1202 }
1203 true
1204 }
1205}
1206
1207fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1218 let stem = std::path::Path::new(input)
1219 .file_name()
1220 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1221 let mut ok = true;
1222 for dump in dumps {
1223 let path = format!("{stem}.{}.ir", dump.name);
1224 if let Err(e) = std::fs::write(&path, &dump.text) {
1225 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1226 ok = false;
1227 }
1228 }
1229 ok
1230}
1231
1232fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1239 match output {
1240 Output::Stdout => {
1241 let mut stdout = std::io::stdout().lock();
1242 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1243 }
1244 Output::File(path) | Output::Temporary(path) => {
1245 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1246 }
1247 }
1248}
1249
1250pub fn run(args: &[String]) -> i32 {
1255 match parse_args(args) {
1256 Ok(Action::Help) => {
1257 print!("{USAGE}");
1258 0
1259 }
1260 Ok(Action::Version) => {
1261 println!("rucc {VERSION}");
1262 0
1263 }
1264 Ok(Action::Print(line)) => {
1265 println!("{line}");
1266 0
1267 }
1268 Ok(Action::PrintConfig(opts)) => {
1269 print!("{}", print_config(&opts));
1270 0
1271 }
1272 Ok(Action::PrintPipeline(opts)) => {
1273 print!("{}", print_pipeline(&opts));
1274 0
1275 }
1276 Ok(Action::PrintPlan { opts, plan, link }) => {
1277 print!("{}", plan.render());
1278 if let Some(job) = &plan.link {
1282 match link_line(&opts, &link, job) {
1283 Ok(line) => println!("{line}"),
1284 Err(why) => {
1285 let mut stderr = std::io::stderr().lock();
1286 let _ = writeln!(stderr, "rucc: error: {why}");
1287 return 1;
1288 }
1289 }
1290 }
1291 0
1292 }
1293 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1294 {
1295 let mut stderr = std::io::stderr().lock();
1296 if verbose {
1297 let _ = write!(stderr, "{}", plan.render());
1298 let _ = writeln!(stderr, "workers: {}", jobs.count());
1299 }
1300 }
1301 if opts.emit == EmitKind::Preprocessed {
1302 return preprocess_all(&opts, &plan);
1303 }
1304 if opts.emit != EmitKind::Executable {
1305 return compile_all(&opts, &plan);
1306 }
1307 link_all(&opts, &plan, &link, verbose)
1308 }
1309 Err(e) => {
1310 let mut stderr = std::io::stderr().lock();
1311 let _ = writeln!(stderr, "rucc: error: {e}");
1312 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1313 1
1314 }
1315 }
1316}
1317
1318#[cfg(test)]
1319mod tests {
1320 use rucc_session::{GnucVersion, OptLevel};
1321
1322 use super::*;
1323
1324 fn args(s: &[&str]) -> Vec<String> {
1325 s.iter().map(|x| (*x).to_owned()).collect()
1326 }
1327
1328 #[test]
1329 fn help_and_version_win_over_everything_else() {
1330 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1331 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1332 }
1333
1334 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1335 match parse_args(&args(s)).expect("expected a compilation") {
1336 Action::Compile { opts, plan, .. } => (opts, plan),
1337 other => panic!("expected a compilation, got {other:?}"),
1338 }
1339 }
1340
1341 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1342 match parse_args(&args(s)).expect("expected a compilation") {
1343 Action::Compile { link, plan, .. } => (link, plan),
1344 other => panic!("expected a compilation, got {other:?}"),
1345 }
1346 }
1347
1348 #[test]
1349 fn collects_inputs_and_flags() {
1350 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1351 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1352 assert_eq!(paths, vec!["a.c", "b.c"]);
1353 assert_eq!(opts.opt_level, OptLevel::O2);
1354 assert_eq!(opts.emit, EmitKind::Object);
1355 assert!(opts.debug_info);
1356 }
1357
1358 #[test]
1361 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1362 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1363 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1364
1365 let (plain, _) = compile(&["-c", "a.c"]);
1366 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1367
1368 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1369 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1370 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1371 }
1372
1373 #[test]
1374 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1375 let (opts, _) = compile(&["-O", "a.c"]);
1376 assert_eq!(opts.opt_level, OptLevel::O1);
1377 }
1378
1379 #[test]
1380 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1381 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1382 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1383 assert_eq!(plan.jobs[1].kind, InputKind::C);
1384 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1385 }
1386
1387 #[test]
1388 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1389 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1390 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1391 other => panic!("expected a compilation, got {other:?}"),
1392 };
1393 assert_eq!(jobs.count(), 4);
1394
1395 let default = match parse_args(&args(&["a.c"])).unwrap() {
1396 Action::Compile { jobs, .. } => jobs,
1397 other => panic!("expected a compilation, got {other:?}"),
1398 };
1399 assert_eq!(default, Jobs::available());
1400 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1401 }
1402
1403 #[test]
1404 fn triple_hash_prints_the_plan_and_runs_nothing() {
1405 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1406 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1407 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1408 }
1409
1410 #[test]
1411 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1412 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1413 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1414 }
1415
1416 #[test]
1417 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1418 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1419 assert!(e.message.contains("unknown option"), "{}", e.message);
1420 }
1421
1422 #[test]
1423 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1424 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1425 assert!(e.message.contains("trampoline"), "{}", e.message);
1426 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1427 }
1428
1429 #[test]
1430 fn an_unsupported_target_names_itself() {
1431 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1432 assert!(e.message.contains("sparc64"), "{}", e.message);
1433 }
1434
1435 #[test]
1436 fn no_inputs_is_an_error_but_print_config_needs_none() {
1437 assert!(parse_args(&args(&[])).is_err());
1438 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1439 }
1440
1441 #[test]
1442 fn print_config_reports_the_target_it_was_given_not_the_host() {
1443 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1444 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1445 let text = print_config(&opts);
1446 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1447 assert!(text.contains("char-signed: false"), "{text}");
1448 assert!(text.contains("object-format: elf"), "{text}");
1449 assert!(text.contains("va-list: void-pointer"), "{text}");
1450 assert!(text.contains("registers: none"), "{text}");
1453 }
1454
1455 #[test]
1456 fn print_config_has_one_key_per_line_and_a_fixed_order() {
1457 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1458 let text = print_config(&opts);
1459 let keys: Vec<&str> =
1460 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1461 assert_eq!(keys[0], "version");
1462 assert_eq!(keys[1], "target");
1463 assert_eq!(keys.len(), 19);
1464 assert!(text.ends_with('\n'));
1465 }
1466
1467 #[test]
1468 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
1469 let (opts, _) = compile(&["a.c"]);
1470 assert_eq!(opts.safety, rucc_session::Safety::Off);
1471
1472 for (flag, tier) in [
1473 ("-fsafety=detect", rucc_session::Safety::Detect),
1474 ("-fsafety=enforce", rucc_session::Safety::Enforce),
1475 ("-fsafety=kernel", rucc_session::Safety::Kernel),
1476 ("-fsafety=off", rucc_session::Safety::Off),
1477 ] {
1478 let (opts, _) = compile(&[flag, "a.c"]);
1479 assert_eq!(opts.safety, tier, "{flag}");
1480 }
1481
1482 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
1484 assert_eq!(opts.safety, rucc_session::Safety::Off);
1485
1486 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
1489 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
1490 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
1491 }
1492
1493 #[test]
1494 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
1495 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1496 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1497 let text = print_pipeline(&opts);
1498 assert!(text.starts_with("level: -O2\n"), "{text}");
1499 assert!(text.contains("fold"), "{text}");
1500
1501 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
1502 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1503 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
1506
1507 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
1508 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1509 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1512 }
1513
1514 #[test]
1515 fn print_pipeline_takes_the_toggles_into_account() {
1516 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
1517 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1518 let text = print_pipeline(&opts);
1519 assert!(!text.contains("fold"), "{text}");
1522 assert!(text.contains("dce"), "{text}");
1523
1524 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
1528 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
1529 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
1530 let a = parse_args(&args(&spelled)).unwrap();
1531 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1532 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1533 }
1534
1535 #[test]
1536 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
1537 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1538 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1539 assert!(!print_pipeline(&opts).contains("global fuel"));
1540
1541 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
1542 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1543 let text = print_pipeline(&opts);
1544 assert!(text.contains("global fuel: 4"), "{text}");
1547 }
1548
1549 #[test]
1552 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
1553 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
1554 assert_eq!(
1555 opts.passes,
1556 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
1557 );
1558
1559 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
1560 assert!(e.message.contains("unknown option"), "{}", e.message);
1561 }
1562
1563 #[test]
1564 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
1565 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
1566 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
1567
1568 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
1569 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
1570 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
1571 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
1572 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
1573 assert!(e.message.contains("not a number"), "{}", e.message);
1574 }
1575
1576 #[test]
1577 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
1578 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
1579 assert_eq!(opts.pass_fuel_global, None);
1580
1581 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
1582 assert_eq!(opts.pass_fuel_global, Some(12));
1583 assert!(opts.pass_fuel.is_empty());
1586
1587 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
1588 assert!(e.message.contains("not a number"), "{}", e.message);
1589 }
1590
1591 #[test]
1592 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
1593 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
1594 assert_eq!(
1595 opts.pass_gates,
1596 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
1597 "the order is what decides, so it has to survive the parse"
1598 );
1599
1600 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
1601 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
1602 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
1603 assert!(e.message.contains("ends before it starts"), "{}", e.message);
1604 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
1605 assert!(e.message.contains("is empty"), "{}", e.message);
1606 }
1607
1608 #[test]
1609 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
1610 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
1611 let text = print_pipeline(&opts);
1612 assert!(text.contains("fold, "), "{text}");
1613 assert!(text.contains("[off for main]"), "{text}");
1614 }
1615
1616 #[test]
1620 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
1621 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
1622 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
1623
1624 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
1625 assert!(e.message.contains("nosuch"), "{}", e.message);
1626 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
1627 }
1628
1629 #[test]
1635 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
1636 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
1637 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
1638 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
1639
1640 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
1641 assert_eq!(opts.opt_info, ["missed-note"]);
1642
1643 let (opts, _) =
1646 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
1647 assert_eq!(opts.opt_info, ["missed", "all"]);
1648 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
1649
1650 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
1651 assert!(e.message.contains("vectorized"), "{}", e.message);
1652 assert!(e.message.contains("`missed`"), "{}", e.message);
1653 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
1654 assert!(e.message.contains("no file"), "{}", e.message);
1655 }
1656
1657 #[test]
1658 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
1659 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
1660 assert!(opts.verify_each);
1661 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
1662 }
1663
1664 #[test]
1665 fn dash_o_needs_an_argument() {
1666 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
1667 assert_eq!(e.message, "-o requires an argument");
1668 }
1669
1670 #[test]
1671 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
1672 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
1673 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
1674 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
1675 }
1676
1677 #[test]
1678 fn the_include_flags_land_on_the_chain_each_one_names() {
1679 let (opts, _) = compile(&[
1682 "-Ii",
1683 "-iquote",
1684 "q",
1685 "-isystem",
1686 "sys",
1687 "-idirafter",
1688 "after",
1689 "--sysroot=/nowhere-at-all",
1690 "a.c",
1691 ]);
1692 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1693 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
1696 assert!(!opts.search.dirs()[1].is_system);
1697 assert!(opts.search.dirs()[2].is_system);
1698 }
1699
1700 #[test]
1701 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
1702 let (opts, _) = compile(&["a.c"]);
1706 let dirs = opts.search.dirs();
1707 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
1708 assert_eq!(ours, Some(0), "{dirs:?}");
1709 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
1710 let (bare, _) = compile(&["-nostdinc", "a.c"]);
1711 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
1712 }
1713
1714 #[test]
1715 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
1716 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
1717 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1718 assert_eq!(dirs, ["sys", runtime::DIR]);
1719 }
1720
1721 #[test]
1722 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
1723 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
1724 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
1725 assert_eq!(dirs, ["i"]);
1726 }
1727
1728 #[test]
1729 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
1730 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
1731 assert_eq!(opts.std, Std::C11);
1732 assert!(opts.gnu_extensions);
1733
1734 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
1735 assert_eq!(opts.std, Std::C99);
1736 assert!(!opts.gnu_extensions);
1737
1738 let (opts, _) = compile(&["-ansi", "a.c"]);
1739 assert_eq!(opts.std, Std::C89);
1740 assert!(!opts.gnu_extensions);
1741
1742 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
1743 assert!(e.message.contains("unknown dialect"), "{}", e.message);
1744 }
1745
1746 #[test]
1747 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
1748 let (opts, _) = compile(&["-dM", "a.c"]);
1749 assert!(opts.dumps.macros);
1750
1751 let (opts, _) = compile(&["-dDM", "a.c"]);
1754 assert!(opts.dumps.macros);
1755 let (opts, _) = compile(&["-dD", "a.c"]);
1756 assert!(!opts.dumps.macros);
1757
1758 let (opts, _) = compile(&["a.c"]);
1759 assert!(!opts.dumps.any());
1760
1761 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
1764 }
1765
1766 #[test]
1767 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
1768 let (opts, _) = compile(&["a.c"]);
1769 assert_eq!(
1770 opts.gnuc,
1771 GnucVersion { major: 7, minor: 0, patch: 0 },
1772 "the lowest claim a modern glibc gives its own declarations to"
1773 );
1774
1775 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
1776 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
1777
1778 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
1781 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
1782
1783 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
1784 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
1785
1786 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
1787 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
1788
1789 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
1790 assert!(e.message.contains("more than three"), "{}", e.message);
1791 }
1792
1793 #[test]
1794 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
1795 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
1796 assert!(opts.pedantic);
1797 assert_eq!(opts.std, Std::C17);
1798
1799 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
1802 assert!(opts.pedantic);
1803
1804 let (opts, _) = compile(&["-std=c17", "a.c"]);
1805 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
1806 }
1807
1808 #[test]
1809 fn dash_p_and_dash_ffreestanding_reach_the_options() {
1810 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
1811 assert!(!opts.line_markers);
1812 assert!(!opts.hosted);
1813 assert_eq!(opts.emit, EmitKind::Preprocessed);
1814 }
1815
1816 #[test]
1823 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
1824 let (opts, _) = compile(&["-c", "a.c"]);
1825 assert!(opts.builtins, "a library name means the library function by default");
1826 assert!(opts.no_builtin.is_empty());
1827
1828 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
1829 assert!(!opts.builtins);
1830
1831 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
1832 assert!(opts.builtins, "the last mention decides");
1833
1834 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
1835 assert!(opts.builtins, "one name is not the family");
1836 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
1837 }
1838
1839 #[test]
1842 fn the_two_frame_flags_are_read_in_both_directions() {
1843 let (opts, _) = compile(&["-c", "a.c"]);
1844 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
1845 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
1846
1847 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
1848 assert!(opts.frame_pointer);
1849 assert!(!opts.red_zone);
1850
1851 let (opts, _) = compile(&[
1852 "-c",
1853 "-fno-omit-frame-pointer",
1854 "-fomit-frame-pointer",
1855 "-mno-red-zone",
1856 "-mred-zone",
1857 "a.c",
1858 ]);
1859 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
1860 assert!(opts.red_zone);
1861 }
1862
1863 #[test]
1864 fn the_link_flags_are_collected_apart_from_the_compilation() {
1865 let (link, _) = linking(&[
1866 "-static",
1867 "-nostartfiles",
1868 "-rdynamic",
1869 "-s",
1870 "-fuse-ld=mold",
1871 "-L/opt/lib",
1872 "-B",
1873 "/opt/tools",
1874 "a.c",
1875 ]);
1876 assert!(link.is_static);
1877 assert!(link.no_startfiles);
1878 assert!(link.export_dynamic);
1879 assert!(link.strip);
1880 assert_eq!(link.use_ld.as_deref(), Some("mold"));
1881 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
1882 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
1883 }
1884
1885 #[test]
1886 fn a_comma_in_dash_wl_separates_two_arguments() {
1887 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
1888 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
1889 }
1890
1891 #[test]
1892 fn a_library_keeps_its_place_between_the_objects() {
1893 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
1898 let link = plan.link.expect("expected a link step");
1899 assert_eq!(
1900 link.inputs,
1901 vec![
1902 link::Item::File("a.o".into()),
1903 link::Item::Library("m".into()),
1904 link::Item::File("b.o".into()),
1905 ]
1906 );
1907 assert_eq!(plan.jobs.len(), 2);
1909 }
1910
1911 #[test]
1912 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1913 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
1914 assert!(plan.link.is_none());
1915 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
1916 }
1917
1918 #[test]
1919 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
1920 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
1921 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
1922 }
1923
1924 fn printed(s: &[&str]) -> String {
1925 match parse_args(&args(s)).expect("expected an answer") {
1926 Action::Print(line) => line,
1927 other => panic!("expected an answer, got {other:?}"),
1928 }
1929 }
1930
1931 fn refused(s: &[&str]) -> String {
1932 parse_args(&args(s)).expect_err("expected a refusal").message
1933 }
1934
1935 #[test]
1936 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
1937 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
1941 assert!(!opts.warnings_are_errors);
1942 assert!(opts.warnings);
1943 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
1945 assert!(opts.warnings_are_errors);
1946 let (opts, _) = compile(&["-w", "-c", "a.c"]);
1947 assert!(!opts.warnings);
1948 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
1949 assert!(opts.pedantic && opts.warnings_are_errors);
1950 }
1951
1952 #[test]
1953 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
1954 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
1956 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
1957 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
1958 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
1959 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
1960 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
1961 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
1964 assert!(no32.contains("32 bit target"), "{no32}");
1965 }
1966
1967 #[test]
1968 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
1969 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
1970 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
1971 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
1972 }
1973
1974 #[test]
1975 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
1976 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
1977 let (opts, _) =
1978 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
1979 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
1980 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
1981 assert!(wrong.contains("sysv convention"), "{wrong}");
1982 }
1983
1984 #[test]
1985 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
1986 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
1987 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
1988 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1991 assert_eq!(names, vec!["a.c"]);
1992 }
1993
1994 #[test]
1995 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
1996 let target = "--target=x86_64-unknown-linux-gnu";
1997 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
1998 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
1999 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2000 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2001 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2004 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2005 let dirs = printed(&[target, "-print-search-dirs"]);
2006 assert!(dirs.starts_with("install: "), "{dirs}");
2007 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2008 }
2009
2010 #[test]
2011 fn usage_fits_on_a_screen() {
2012 assert!(USAGE.lines().count() < 42, "usage text has grown past one screen");
2022 }
2023}