1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.5")]
30
31pub mod compile;
32pub mod deps;
33pub mod library;
34pub mod link;
35mod map;
36pub mod phase;
37pub mod preprocess;
38pub mod schedule;
39
40use std::fmt::Write as _;
41use std::io::Write as _;
42use std::path::PathBuf;
43
44use rucc_codegen::coverage::{self, Fired};
45use rucc_pp::Dependency;
46use rucc_session::{Dumps, EmitKind, Options, Pic, Preinclude, SaveTemps, Session, Std, runtime};
47use rucc_target::Triple;
48
49use crate::link::LinkOptions;
50
51pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
52pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
53pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
54pub use crate::schedule::Jobs;
55
56pub const VERSION: &str = env!("CARGO_PKG_VERSION");
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum Action {
62 Help,
64 Version,
66 Print(String),
72 PrintConfig(Box<Options>),
74 PrintPipeline(Box<Options>),
76 PrintPlan {
78 opts: Box<Options>,
80 plan: Box<Plan>,
82 link: Box<LinkOptions>,
84 },
85 Compile {
87 opts: Box<Options>,
89 plan: Box<Plan>,
91 link: Box<LinkOptions>,
93 jobs: Jobs,
95 verbose: bool,
97 },
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct CliError {
103 pub message: String,
106}
107
108impl std::fmt::Display for CliError {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 f.write_str(&self.message)
111 }
112}
113
114impl std::error::Error for CliError {}
115
116fn err(message: impl Into<String>) -> CliError {
117 CliError { message: message.into() }
118}
119
120enum Query {
126 Machine,
128 Version,
130 Multiarch,
132 SearchDirs,
134 FileName(String),
136 ProgName(String),
138 Libgcc,
140}
141
142pub const USAGE: &str = "\
147rucc, an optimizing C compiler
148
149usage: rucc [options] file...
150
151options:
152 -c compile and assemble, do not link
153 -S compile only, emit assembly
154 -E preprocess only
155 -o <file> write output to <file>, or to standard output for -
156 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
157 -I <dir> add <dir> to the include search path
158 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
159 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
160 -include <file>, -imacros <file> read <file> first, the second for its macros only
161 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
162 -P, -dM with -E: leave out the markers, or dump the macros
163 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
164 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
165 -std=<dialect> c89 through c23, and the gnu spellings
166 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
167 -x <lang> treat later inputs as <lang>, or none to stop
168 -O<level> optimize: 0, 1, 2, 3, s, z
169 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
170 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
171 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
172 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
173 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
174 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
175 -fPIC -fpic -fPIE -fpie, -fno-common, -f[no-]strict-aliasing, -pipe what it does anyway
176 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
177 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
178 -Werror -pedantic -pedantic-errors -w how much to say, and whether it is fatal
179 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
180 -pthread build for more than one thread, and link the library for it
181 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
182 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
183 -j[n] compile n translation units at once, default all
184 -v, -### print each phase as it runs, or without running any
185 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
186 --target=<triple> generate code for <triple>
187 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
188 safety-summary, type-granules
189 --print-config, --print-pipeline print the configuration or the pipeline, and exit
190 --version print the version and exit
191 -h, --help print this message and exit
192
193See spec/04-driver-and-cli.md for the full flag reference.
194";
195
196fn joined_or_next(
200 arg: &str,
201 at: usize,
202 args: &[String],
203 i: &mut usize,
204) -> Result<String, CliError> {
205 if arg.len() > at {
206 return Ok(arg[at..].to_owned());
207 }
208 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
209 *i += 1;
210 Ok(next.clone())
211}
212
213pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
220 let host = Triple::host()
221 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
222 let mut opts = Options::new(host);
223 let mut inputs: Vec<Input> = Vec::new();
224 let mut print_config = false;
225 let mut print_pipeline = false;
226 let mut print_plan = false;
227 let mut verbose = false;
228 let mut jobs = Jobs::default();
229 let mut nostdinc = false;
230 let mut sysroot: Option<PathBuf> = None;
231 let mut output = None;
232 let mut link = LinkOptions::default();
233 let mut query: Option<Query> = None;
234 let mut threads = false;
235 let mut forced: Option<InputKind> = None;
238 let mut iprefix = String::new();
245
246 let mut i = 0;
247 while i < args.len() {
248 let arg = args[i].as_str();
249 i += 1;
250 match arg {
251 "-h" | "--help" => return Ok(Action::Help),
252 "--version" => return Ok(Action::Version),
253 "--print-config" => print_config = true,
254 "--print-pipeline" => print_pipeline = true,
255 "-###" => print_plan = true,
256 "-v" => verbose = true,
257 "-save-temps" => opts.save_temps = SaveTemps::Object,
261 _ if arg.starts_with("-save-temps=") => {
262 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
263 }
264 "-time" => opts.time = true,
267 "-c" => opts.emit = EmitKind::Object,
268 "-S" => opts.emit = EmitKind::Asm,
269 "-E" => opts.emit = EmitKind::Preprocessed,
270 "-g" => opts.debug_info = true,
271 "-g0" => opts.debug_info = false,
276 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
277 opts.debug_info = true;
278 }
279 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
282 _ if arg.starts_with("-gdwarf-") => {
283 return Err(err(format!(
284 "{arg}: this compiler writes DWARF 5 and no other version, see \
285 spec/11-debug-info.md"
286 )));
287 }
288 "-Werror" => opts.warnings_are_errors = true,
289 "-w" => opts.warnings = false,
292 "-pedantic-errors" => {
293 opts.pedantic = true;
294 opts.warnings_are_errors = true;
295 }
296 "-P" => opts.line_markers = false,
297 "-M" => {
304 opts.deps.emit = true;
305 opts.deps.instead_of_compiling = true;
306 }
307 "-MM" => {
308 opts.deps.emit = true;
309 opts.deps.instead_of_compiling = true;
310 opts.deps.system_headers = false;
311 }
312 "-MD" => opts.deps.emit = true,
313 "-MMD" => {
314 opts.deps.emit = true;
315 opts.deps.system_headers = false;
316 }
317 "-MP" => opts.deps.phony = true,
318 "-MF" | "-MT" | "-MQ" => {
321 let value =
322 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
323 i += 1;
324 match arg {
325 "-MF" => opts.deps.file = Some(value.clone()),
326 "-MT" => opts.deps.targets.push(value.clone()),
330 _ => opts.deps.targets.push(deps::escaped(value)),
331 }
332 }
333 "-dumpmachine" => query = Some(Query::Machine),
337 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
338 "-print-multiarch" => query = Some(Query::Multiarch),
339 "-print-search-dirs" => query = Some(Query::SearchDirs),
340 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
341 _ if arg.starts_with("-print-file-name=") => {
342 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
343 }
344 _ if arg.starts_with("-print-prog-name=") => {
345 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
346 }
347 "-pthread" | "-pthreads" => {
352 opts.defines.push("_REENTRANT".to_owned());
353 threads = true;
354 }
355 "-ansi" => {
356 opts.std = Std::C89;
357 opts.gnu_extensions = false;
358 }
359 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
362 "-fpermissive" => opts.permissive = true,
365 "-fno-permissive" => opts.permissive = false,
366 "-ffreestanding" => opts.hosted = false,
367 "-fhosted" => opts.hosted = true,
368 "-fno-builtin" => opts.builtins = false,
369 "-fbuiltin" => opts.builtins = true,
370 "-fgnu89-inline" => opts.gnu89_inline = true,
374 "-fno-gnu89-inline" => opts.gnu89_inline = false,
375 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
378 "-fomit-frame-pointer" => opts.frame_pointer = false,
379 "-mno-red-zone" => opts.red_zone = false,
380 "-mred-zone" => opts.red_zone = true,
381 "-nostdinc" => nostdinc = true,
385 "-o" => {
386 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
387 i += 1;
388 }
389 "-isysroot" => {
396 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
397 i += 1;
398 sysroot = Some(PathBuf::from(dir));
399 }
400 "-iquote" | "-isystem" | "-idirafter" => {
401 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
402 i += 1;
403 match arg {
404 "-iquote" => opts.search.push_quote(dir.clone()),
405 "-isystem" => opts.search.push_system(dir.clone()),
406 _ => opts.search.push_after(dir.clone()),
407 }
408 }
409 "-iprefix" => {
410 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
411 i += 1;
412 }
413 "-iwithprefix" | "-iwithprefixbefore" => {
419 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
420 i += 1;
421 let dir = format!("{iprefix}{dir}");
422 if arg == "-iwithprefix" {
423 opts.search.push_system(dir);
424 } else {
425 opts.search.push_bracket(dir);
426 }
427 }
428 "-include" | "-imacros" => {
429 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
430 i += 1;
431 opts.preincludes
432 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
433 }
434 "-I-" => opts.search.split_quote_chain(),
439 "-x" => {
440 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
441 i += 1;
442 forced = if lang == "none" {
443 None
444 } else {
445 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
446 };
447 }
448 _ if arg.starts_with("-D") => {
456 let value = joined_or_next(arg, 2, args, &mut i)?;
457 opts.defines.push(value);
458 }
459 _ if arg.starts_with("-U") => {
460 let value = joined_or_next(arg, 2, args, &mut i)?;
461 opts.undefines.push(value);
462 }
463 _ if arg.starts_with("-I") => {
464 let dir = joined_or_next(arg, 2, args, &mut i)?;
465 opts.search.push_bracket(dir);
466 }
467 _ if arg.starts_with("-std=") => {
468 let name = &arg["-std=".len()..];
469 let (std, gnu) = Std::from_flag(name)
470 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
471 opts.std = std;
472 opts.gnu_extensions = gnu;
473 }
474 _ if Dumps::is_family(arg) => {
483 opts.dumps.add(&arg[2..]);
484 }
485 _ if arg.starts_with("-fno-builtin-") => {
490 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
491 }
492 _ if arg.starts_with("-fgnuc-version=") => {
493 let v = &arg["-fgnuc-version=".len()..];
494 opts.gnuc = v.parse().map_err(err)?;
495 }
496 "-fnested-functions" => {
501 return Err(err(
502 "nested functions are not supported: a call to one goes through a trampoline \
503 written on the stack, which no target that enforces an unexecutable stack \
504 allows",
505 ));
506 }
507 "-fno-nested-functions" => {}
508 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
519 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
523 "-fsemantic-interposition" => opts.interposition = true,
530 "-fno-semantic-interposition" => opts.interposition = false,
531 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
536 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
537 "-funwind-tables" => opts.unwind_tables = true,
538 "-fno-unwind-tables" => opts.unwind_tables = false,
539 "-fno-pic" | "-fno-pie" => {
546 return Err(err(
547 "position dependent code is not supported: an address that may be in another \
548 object is loaded out of the global offset table, and nothing here emits the \
549 absolute form this asks for. Use -no-pie if what you meant was how to link",
550 ));
551 }
552 "-fno-common" => {}
558 "-fcommon" => {
562 return Err(err(
563 "a tentative definition is written into .bss as its own symbol here, and \
564 nothing emits the common symbol this asks the linker to merge. Give the \
565 variable a definition in one file and declare it extern in the others",
566 ));
567 }
568 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
582 "-pipe" => {}
585 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
592 _ if arg.starts_with("-fdiagnostics-color=") => {}
593 "-static" => link.is_static = true,
597 "-shared" => link.shared = true,
598 "-pie" => link.pie = Some(true),
599 "-no-pie" | "-nopie" => link.pie = Some(false),
600 "-nostdlib" => link.no_stdlib = true,
601 "-nostartfiles" => link.no_startfiles = true,
602 "-nodefaultlibs" => link.no_defaultlibs = true,
603 "-fno-builtins-lib" => link.no_builtins_lib = true,
604 "-fbuiltins-lib" => link.no_builtins_lib = false,
605 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
606 "-s" => link.strip = true,
607 "-Xlinker" => {
608 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
609 i += 1;
610 link.passthrough.push(next.clone());
611 }
612 _ if arg.starts_with("-Wl,") => {
613 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
616 }
617 _ if arg.starts_with("-fuse-ld=") => {
618 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
619 }
620 _ if arg.starts_with("-l") && arg.len() > 2 => {
621 inputs.push(Input::library(&arg[2..]));
622 }
623 "-l" => {
624 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
625 i += 1;
626 inputs.push(Input::library(next));
627 }
628 _ if arg.starts_with("-L") => {
629 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
630 }
631 _ if arg.starts_with("-B") => {
632 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
633 }
634 _ if arg.starts_with("-j") => {
635 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
636 }
637 _ if arg.starts_with("--sysroot=") => {
638 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
639 }
640 _ if arg.starts_with("--target=") => {
641 let t = &arg["--target=".len()..];
642 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
643 }
644 _ if arg.starts_with("--emit=") => {
645 let k = &arg["--emit=".len()..];
646 opts.emit = k
647 .parse()
648 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
649 }
650 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
656 "-Ofast" => {
662 return Err(err(
663 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
664 spec/04-driver-and-cli.md section 4.6",
665 ));
666 }
667 _ if arg.starts_with("-O") => {
668 opts.opt_level = arg[2..]
669 .parse()
670 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
671 }
672 _ if arg.starts_with("-fvisibility=") => {
676 let seen = &arg["-fvisibility=".len()..];
677 opts.visibility = seen.parse().map_err(|()| {
678 err(format!(
679 "`{seen}` is not a visibility, which is default, hidden, internal or \
680 protected"
681 ))
682 })?;
683 }
684 _ if arg.starts_with("-fsafety=") => {
689 let tier = &arg["-fsafety=".len()..];
690 opts.safety = tier.parse().map_err(|()| {
691 err(format!(
692 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
693 ))
694 })?;
695 }
696 _ if arg.starts_with("-fpass-fuel=") => {
700 let (name, count) = arg["-fpass-fuel=".len()..]
701 .split_once('=')
702 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
703 if rucc_opt::pass::find(name).is_none() {
704 return Err(err(format!(
705 "`{name}` is not a pass this compiler has, see --print-pipeline"
706 )));
707 }
708 let count: u32 = count
709 .parse()
710 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
711 opts.pass_fuel.push((name.to_owned(), count));
712 }
713 _ if arg.starts_with("-fpass-fuel-global=") => {
714 let count = &arg["-fpass-fuel-global=".len()..];
715 let count: u32 = count
716 .parse()
717 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
718 opts.pass_fuel_global = Some(count);
719 }
720 _ if arg == "-fopt-info"
725 || arg.starts_with("-fopt-info=")
726 || arg.starts_with("-fopt-info-") =>
727 {
728 let rest = &arg["-fopt-info".len()..];
729 let (kinds, file) = match rest.split_once('=') {
730 Some((kinds, file)) => (kinds, Some(file)),
731 None => (rest, None),
732 };
733 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
734 rucc_opt::Wants::none().add(kinds).map_err(err)?;
735 opts.opt_info.push(kinds.to_owned());
736 if let Some(file) = file {
737 if file.is_empty() {
738 return Err(err("-fopt-info= was given no file to write to"));
739 }
740 opts.opt_info_file = Some(file.to_owned());
741 }
742 }
743 _ if arg.starts_with("-fdump-ir=") => {
744 let spec = &arg["-fdump-ir=".len()..];
747 rucc_opt::Dumps::default().add(spec).map_err(err)?;
748 opts.dump_ir.push(spec.to_owned());
749 }
750 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
756 let on = arg.starts_with("-fenable-");
757 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
758 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
759 opts.pass_gates.push((on, spec.to_owned()));
760 }
761 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
762 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
763 }
764 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
765 opts.passes.push((arg["-f".len()..].to_owned(), true));
766 }
767 "-Zverify-each" => opts.verify_each = true,
773 _ if arg.starts_with("-Zrule-coverage=") => {
774 let file = &arg["-Zrule-coverage=".len()..];
775 if file.is_empty() {
776 return Err(err("-Zrule-coverage= needs a file to write to"));
777 }
778 opts.rule_coverage = Some(file.to_owned());
779 }
780 _ if arg.starts_with("-Z") => {
781 return Err(err(format!(
782 "`{arg}` is not an unstable option this compiler has, see \
783 spec/04-driver-and-cli.md section 4.11 for the ones it does"
784 )));
785 }
786 "-m64" | "-m32" | "-mx32" => {
791 let want: u32 = match arg {
792 "-m64" => 64,
793 _ => 32,
794 };
795 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
796 if have != want {
797 return Err(err(format!(
798 "{arg} asks for a {want} bit target and {} is {have} bit, use \
799 --target= to name the one you mean",
800 opts.target
801 )));
802 }
803 }
804 _ if arg.starts_with("-march=")
810 || arg.starts_with("-mtune=")
811 || arg.starts_with("-mcpu=") => {}
812 _ if arg.starts_with("-mabi=") => {
815 let want = &arg["-mabi=".len()..];
816 let have = match opts.target.arch {
817 rucc_target::Arch::X86_64 => "sysv",
818 rucc_target::Arch::Aarch64 => "lp64",
819 rucc_target::Arch::Riscv64 => "lp64d",
820 };
821 if want != have {
822 return Err(err(format!(
823 "{arg}: {} uses the {have} convention and this compiler has no other",
824 opts.target
825 )));
826 }
827 }
828 "-mcmodel=small" => {}
832 _ if arg.starts_with("-mcmodel=") => {
833 return Err(err(format!(
834 "{arg}: this compiler emits the small code model and no other, see \
835 spec/12-targets.md"
836 )));
837 }
838 _ if arg.starts_with("-specs=") => {
842 return Err(err(
843 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
844 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
845 section 4.4",
846 ));
847 }
848 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
854 return Err(err(format!(
855 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
856 are inside this compiler rather than programs it runs"
857 )));
858 }
859 "-Xassembler" | "-Xpreprocessor" => {
860 return Err(err(format!(
861 "{arg} hands an argument to a separate assembler or preprocessor, and both \
862 are inside this compiler rather than programs it runs"
863 )));
864 }
865 _ if arg.starts_with("-W") => {}
872 "-fno-ident"
878 | "-fident"
879 | "-funit-at-a-time"
880 | "-fno-unit-at-a-time"
881 | "-shared-libgcc"
882 | "-static-libgcc" => {}
883 _ if arg.starts_with('-') && arg.len() > 1 => {
884 return Err(err(format!("unknown option `{arg}`")));
889 }
890 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
891 }
892 }
893
894 link.sysroot = sysroot.clone();
901 if threads {
906 inputs.push(Input::library("pthread"));
907 }
908 if let Some(query) = query {
909 return Ok(Action::Print(answer(&query, &opts, &link)));
910 }
911 if opts.deps.instead_of_compiling {
917 opts.emit = EmitKind::Preprocessed;
918 }
919 if !nostdinc {
920 opts.search.push_system(runtime::DIR);
921 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
925 opts.search.push_system(dir);
926 }
927 }
928 opts.search.remove_duplicates();
932
933 if print_config {
936 return Ok(Action::PrintConfig(Box::new(opts)));
937 }
938 if print_pipeline {
939 return Ok(Action::PrintPipeline(Box::new(opts)));
940 }
941 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
942 if print_plan {
943 return Ok(Action::PrintPlan {
944 opts: Box::new(opts),
945 plan: Box::new(plan),
946 link: Box::new(link),
947 });
948 }
949 Ok(Action::Compile {
950 opts: Box::new(opts),
951 plan: Box::new(plan),
952 link: Box::new(link),
953 jobs,
954 verbose,
955 })
956}
957
958fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
964 let found = |name: &str| {
965 link::find_in_search(link, opts.target, name)
966 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
967 };
968 match query {
969 Query::Machine => opts.target.to_string(),
970 Query::Version => VERSION.to_owned(),
971 Query::Multiarch => link::multiarch(opts.target),
972 Query::SearchDirs => {
977 let here = std::env::current_exe()
978 .ok()
979 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
980 .unwrap_or_default();
981 let list = |dirs: &[PathBuf]| {
982 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
983 };
984 let libraries = link::search_dirs(link, opts.target);
985 format!(
986 "install: {}\nprograms: ={}\nlibraries: ={}",
987 here.display(),
988 list(&link.prefixes),
989 list(&libraries)
990 )
991 }
992 Query::FileName(name) => found(name),
993 Query::Libgcc => found("libgcc.a"),
997 Query::ProgName(name) => link
1001 .prefixes
1002 .iter()
1003 .map(|dir| dir.join(name))
1004 .find(|path| path.is_file())
1005 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1006 }
1007}
1008
1009#[must_use]
1015pub fn print_pipeline(opts: &Options) -> String {
1016 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1017 settings.toggles.clone_from(&opts.passes);
1018 settings.global_fuel = opts.pass_fuel_global;
1019 for (on, spec) in &opts.pass_gates {
1020 let _ = settings.gates.add(*on, spec);
1023 }
1024 rucc_opt::pipeline::print(&settings)
1025}
1026
1027#[must_use]
1032pub fn print_config(opts: &Options) -> String {
1033 let sess = Session::new(opts.clone());
1034 let t = &sess.target;
1035 let mut out = String::new();
1036 let _ = writeln!(out, "version: {VERSION}");
1037 let _ = writeln!(out, "target: {}", opts.target);
1041 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1042 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1043 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1044 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1045 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1046 let _ = writeln!(out, "long-width: {}", t.long_width);
1047 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1048 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1049 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1050 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1051 let regs: Vec<String> = t
1054 .regs
1055 .classes()
1056 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1057 .collect();
1058 let _ = writeln!(
1059 out,
1060 "registers: {}",
1061 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1062 );
1063 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1064 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1065 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1066 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1067 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1068 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1069 for dir in sess.opts.search.dirs() {
1072 let system = if dir.is_system { " (system)" } else { "" };
1073 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1074 }
1075 out
1076}
1077
1078fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1086 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1087}
1088
1089fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1092 if path == "-" {
1093 return write_out(&Output::Stdout, bytes);
1094 }
1095 write_out(&Output::File(path.to_owned()), bytes)
1096}
1097
1098fn write_deps(
1104 opts: &Options,
1105 plan: &Plan,
1106 job: &Job,
1107 found: &[Dependency],
1108 stderr: &mut impl std::io::Write,
1109) -> bool {
1110 let targets = if opts.deps.targets.is_empty() {
1111 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1112 } else {
1113 opts.deps.targets.clone()
1114 };
1115 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1116 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1119 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1123 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1124 }),
1125 None => write_out(&job.output, rule.as_bytes()),
1126 };
1127 if let Err(e) = wrote {
1128 let _ = writeln!(stderr, "rucc: error: {e}");
1129 return false;
1130 }
1131 true
1132}
1133
1134fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1140 let fs = OsFileSystem::new();
1141 let mut stderr = std::io::stderr().lock();
1142 let mut failed = false;
1143 for job in &plan.jobs {
1144 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1145 continue;
1148 }
1149 let started = std::time::Instant::now();
1150 let result = preprocess(opts, &job.input, &fs);
1151 if opts.time {
1152 say_time(&job.input, started.elapsed(), &mut stderr);
1153 }
1154 for message in &result.messages {
1155 let _ = writeln!(stderr, "{message}");
1156 }
1157 if result.failed() {
1158 failed = true;
1159 continue;
1160 }
1161 if opts.deps.emit {
1162 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1163 if opts.deps.instead_of_compiling {
1166 continue;
1167 }
1168 }
1169 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1170 let _ = writeln!(stderr, "rucc: error: {e}");
1171 failed = true;
1172 }
1173 }
1174 i32::from(failed)
1175}
1176
1177fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1183 let fs = OsFileSystem::new();
1184 let mut stderr = std::io::stderr().lock();
1185 let mut failed = false;
1186 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1187 failed |= !ok;
1188 let mut fired = Fired::new();
1189 for job in &plan.jobs {
1190 if !job.phases.contains(&Phase::Compile) {
1191 continue;
1192 }
1193 let started = std::time::Instant::now();
1197 let result = if job.kind == InputKind::Ir {
1198 compile_ir(opts, &job.input, &fs)
1199 } else {
1200 compile(opts, &job.input, &fs)
1201 };
1202 if opts.time {
1203 say_time(&job.input, started.elapsed(), &mut stderr);
1204 }
1205 fired.merge(&result.fired);
1206 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1207 failed |= !remarks.write(&result.remarks, &mut stderr);
1208 for message in &result.messages {
1209 let _ = writeln!(stderr, "{message}");
1210 }
1211 failed |= !write_temps(job, &result.temps, &mut stderr);
1214 if result.failed() {
1215 failed = true;
1216 continue;
1217 }
1218 if opts.deps.emit {
1223 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1224 }
1225 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1226 let _ = writeln!(stderr, "rucc: error: {e}");
1227 failed = true;
1228 }
1229 }
1230 failed |= !write_coverage(opts, &fired, &mut stderr);
1231 i32::from(failed)
1232}
1233
1234struct Scratch {
1241 dir: PathBuf,
1243}
1244
1245impl Scratch {
1246 fn new() -> Result<Scratch, String> {
1252 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1253 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1254 Ok(Scratch { dir })
1255 }
1256}
1257
1258impl Drop for Scratch {
1259 fn drop(&mut self) {
1260 let _ = std::fs::remove_dir_all(&self.dir);
1261 }
1262}
1263
1264fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1271 let linker = link::find(opts.target, link)?;
1272 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1273 Ok(link::render(&linker, &args))
1274}
1275
1276fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1283 let Some(job) = &plan.link else {
1284 let mut stderr = std::io::stderr().lock();
1287 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1288 return 1;
1289 };
1290 let linker = match link::find(opts.target, link) {
1293 Ok(linker) => linker,
1294 Err(why) => return complain(why),
1295 };
1296
1297 let scratch = match Scratch::new() {
1298 Ok(scratch) => scratch,
1299 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1300 };
1301
1302 let fs = OsFileSystem::new();
1303 let mut failed = false;
1304 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1307 let mut fired = Fired::new();
1308 {
1309 let mut stderr = std::io::stderr().lock();
1310 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1311 failed |= !ok;
1312 for (at, job) in plan.jobs.iter().enumerate() {
1313 let out = match &job.output {
1314 Output::Temporary(hint) => {
1315 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1318 }
1319 Output::File(path) => path.clone(),
1320 Output::Stdout => continue,
1323 };
1324 produced.push(out.clone());
1325 if !job.phases.contains(&Phase::Compile) {
1326 continue;
1327 }
1328 let started = std::time::Instant::now();
1329 let result = if job.kind == InputKind::Ir {
1330 compile_ir(opts, &job.input, &fs)
1331 } else {
1332 compile(opts, &job.input, &fs)
1333 };
1334 if opts.time {
1335 say_time(&job.input, started.elapsed(), &mut stderr);
1336 }
1337 fired.merge(&result.fired);
1338 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1339 failed |= !remarks.write(&result.remarks, &mut stderr);
1340 for message in &result.messages {
1341 let _ = writeln!(stderr, "{message}");
1342 }
1343 failed |= !write_temps(job, &result.temps, &mut stderr);
1344 if result.failed() {
1345 failed = true;
1346 continue;
1347 }
1348 if opts.deps.emit {
1353 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1354 }
1355 if !matches!(result.artifact, Artifact::Object(_)) {
1356 let _ = writeln!(
1361 stderr,
1362 "rucc: internal error: {}: no object file was produced for the link",
1363 job.input
1364 );
1365 failed = true;
1366 continue;
1367 }
1368 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1369 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1370 failed = true;
1371 }
1372 }
1373 failed |= !write_coverage(opts, &fired, &mut stderr);
1374 }
1375 if failed {
1376 return 1;
1380 }
1381
1382 let mut outputs = produced.into_iter();
1386 let mut items = Vec::with_capacity(job.inputs.len());
1387 for item in &job.inputs {
1388 match item {
1389 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1390 link::Item::File(_) => match outputs.next() {
1391 Some(path) => items.push(link::Item::File(path)),
1392 None => return complain("the plan asks the linker for a file nothing produced"),
1393 },
1394 }
1395 }
1396
1397 let args = match link::line(opts.target, link, &items, &job.output) {
1398 Ok(args) => args,
1399 Err(why) => return complain(why),
1400 };
1401 if verbose {
1402 let mut stderr = std::io::stderr().lock();
1403 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1404 }
1405 let started = std::time::Instant::now();
1406 let ran = link::run(&linker, &args);
1407 if opts.time {
1408 let mut stderr = std::io::stderr().lock();
1411 say_time(&linker.name, started.elapsed(), &mut stderr);
1412 }
1413 match ran {
1414 Ok(()) => 0,
1415 Err(link::Error::Refused { .. }) => 1,
1418 Err(why) => complain(why),
1419 }
1420}
1421
1422fn complain(why: impl std::fmt::Display) -> i32 {
1424 let mut stderr = std::io::stderr().lock();
1425 let _ = writeln!(stderr, "rucc: error: {why}");
1426 1
1427}
1428
1429fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1438 let Some(path) = &opts.rule_coverage else { return true };
1439 let Some(table) = coverage::table(opts.target.arch) else {
1440 let _ = writeln!(
1441 stderr,
1442 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1443 to report",
1444 opts.target
1445 );
1446 return false;
1447 };
1448 match std::fs::write(path, fired.listing(table)) {
1449 Ok(()) => true,
1450 Err(e) => {
1451 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1452 false
1453 }
1454 }
1455}
1456
1457struct Remarks {
1464 file: Option<String>,
1466 started: bool,
1469}
1470
1471impl Remarks {
1472 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1478 let mut ok = true;
1479 if let Some(path) = file {
1480 if let Err(e) = std::fs::write(path, "") {
1481 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1482 ok = false;
1483 }
1484 }
1485 (Self { file: file.cloned(), started: false }, ok)
1486 }
1487
1488 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1494 if text.is_empty() {
1495 return true;
1496 }
1497 let Some(path) = &self.file else {
1498 let _ = write!(stderr, "{text}");
1499 return true;
1500 };
1501 let opened = std::fs::OpenOptions::new()
1502 .write(true)
1503 .append(self.started)
1504 .truncate(!self.started)
1505 .create(true)
1506 .open(path);
1507 self.started = true;
1508 let result =
1509 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1510 if let Err(e) = result {
1511 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1512 return false;
1513 }
1514 true
1515 }
1516}
1517
1518fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1529 let stem = std::path::Path::new(input)
1530 .file_name()
1531 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1532 let mut ok = true;
1533 for dump in dumps {
1534 let path = format!("{stem}.{}.ir", dump.name);
1535 if let Err(e) = std::fs::write(&path, &dump.text) {
1536 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1537 ok = false;
1538 }
1539 }
1540 ok
1541}
1542
1543fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1549 let mut ok = true;
1550 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1551 for (path, text) in kept {
1552 let (Some(path), Some(text)) = (path, text) else { continue };
1555 if let Err(e) = std::fs::write(&path, text) {
1556 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1557 ok = false;
1558 }
1559 }
1560 ok
1561}
1562
1563fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1570 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1571}
1572
1573fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1580 match output {
1581 Output::Stdout => {
1582 let mut stdout = std::io::stdout().lock();
1583 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1584 }
1585 Output::File(path) | Output::Temporary(path) => {
1586 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1587 }
1588 }
1589}
1590
1591pub fn run(args: &[String]) -> i32 {
1596 match parse_args(args) {
1597 Ok(Action::Help) => {
1598 print!("{USAGE}");
1599 0
1600 }
1601 Ok(Action::Version) => {
1602 println!("rucc {VERSION}");
1603 0
1604 }
1605 Ok(Action::Print(line)) => {
1606 println!("{line}");
1607 0
1608 }
1609 Ok(Action::PrintConfig(opts)) => {
1610 print!("{}", print_config(&opts));
1611 0
1612 }
1613 Ok(Action::PrintPipeline(opts)) => {
1614 print!("{}", print_pipeline(&opts));
1615 0
1616 }
1617 Ok(Action::PrintPlan { opts, plan, link }) => {
1618 print!("{}", plan.render());
1619 if let Some(job) = &plan.link {
1623 match link_line(&opts, &link, job) {
1624 Ok(line) => println!("{line}"),
1625 Err(why) => {
1626 let mut stderr = std::io::stderr().lock();
1627 let _ = writeln!(stderr, "rucc: error: {why}");
1628 return 1;
1629 }
1630 }
1631 }
1632 0
1633 }
1634 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1635 {
1636 let mut stderr = std::io::stderr().lock();
1637 if verbose {
1638 let _ = write!(stderr, "{}", plan.render());
1639 let _ = writeln!(stderr, "workers: {}", jobs.count());
1640 }
1641 }
1642 if opts.emit == EmitKind::Preprocessed {
1643 return preprocess_all(&opts, &plan);
1644 }
1645 if opts.emit != EmitKind::Executable {
1646 return compile_all(&opts, &plan);
1647 }
1648 link_all(&opts, &plan, &link, verbose)
1649 }
1650 Err(e) => {
1651 let mut stderr = std::io::stderr().lock();
1652 let _ = writeln!(stderr, "rucc: error: {e}");
1653 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1654 1
1655 }
1656 }
1657}
1658
1659#[cfg(test)]
1660mod tests {
1661 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1662
1663 use super::*;
1664
1665 fn args(s: &[&str]) -> Vec<String> {
1666 s.iter().map(|x| (*x).to_owned()).collect()
1667 }
1668
1669 #[test]
1670 fn help_and_version_win_over_everything_else() {
1671 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1672 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1673 }
1674
1675 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1676 match parse_args(&args(s)).expect("expected a compilation") {
1677 Action::Compile { opts, plan, .. } => (opts, plan),
1678 other => panic!("expected a compilation, got {other:?}"),
1679 }
1680 }
1681
1682 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1683 match parse_args(&args(s)).expect("expected a compilation") {
1684 Action::Compile { link, plan, .. } => (link, plan),
1685 other => panic!("expected a compilation, got {other:?}"),
1686 }
1687 }
1688
1689 #[test]
1690 fn collects_inputs_and_flags() {
1691 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1692 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1693 assert_eq!(paths, vec!["a.c", "b.c"]);
1694 assert_eq!(opts.opt_level, OptLevel::O2);
1695 assert_eq!(opts.emit, EmitKind::Object);
1696 assert!(opts.debug_info);
1697 }
1698
1699 #[test]
1702 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1703 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1704 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1705
1706 let (plain, _) = compile(&["-c", "a.c"]);
1707 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1708
1709 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1710 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1711 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1712 }
1713
1714 #[test]
1715 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1716 let (opts, _) = compile(&["-O", "a.c"]);
1717 assert_eq!(opts.opt_level, OptLevel::O1);
1718 }
1719
1720 #[test]
1721 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1722 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1723 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1724 assert_eq!(plan.jobs[1].kind, InputKind::C);
1725 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1726 }
1727
1728 #[test]
1729 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1730 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1731 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1732 other => panic!("expected a compilation, got {other:?}"),
1733 };
1734 assert_eq!(jobs.count(), 4);
1735
1736 let default = match parse_args(&args(&["a.c"])).unwrap() {
1737 Action::Compile { jobs, .. } => jobs,
1738 other => panic!("expected a compilation, got {other:?}"),
1739 };
1740 assert_eq!(default, Jobs::available());
1741 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1742 }
1743
1744 #[test]
1745 fn triple_hash_prints_the_plan_and_runs_nothing() {
1746 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1747 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1748 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1749 }
1750
1751 #[test]
1752 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1753 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1757 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1758 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1759 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1760 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1764 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1765 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1766 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1767 }
1768
1769 #[test]
1770 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1771 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1772 let (plain, without) = compile(&["-c", "a.c"]);
1773 assert!(opts.time);
1774 assert!(!plain.time);
1775 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1778 }
1779
1780 #[test]
1781 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1782 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1783 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1784 }
1785
1786 #[test]
1787 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1788 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1789 assert!(e.message.contains("unknown option"), "{}", e.message);
1790 }
1791
1792 #[test]
1795 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1796 let (opts, _) = compile(&["-c", "a.c"]);
1797 assert!(!opts.permissive, "off unless it is asked for");
1798
1799 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1800 assert!(opts.permissive);
1801
1802 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1803 assert!(!opts.permissive);
1804 }
1805
1806 #[test]
1807 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1808 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1809 assert!(e.message.contains("trampoline"), "{}", e.message);
1810 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1811 }
1812
1813 #[test]
1814 fn the_flag_every_configure_script_writes_is_taken() {
1815 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1818 let (opts, _) = compile(&["-c", flag, "a.c"]);
1819 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1820 }
1821 }
1822
1823 #[test]
1824 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1825 let (opts, _) = compile(&["-c", "a.c"]);
1826 assert!(opts.unwinds(), "the default is off");
1827 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1828 assert!(!opts.unwinds(), "the build was not taken at its word");
1829 let (opts, _) = compile(&[
1830 "-c",
1831 "-fno-asynchronous-unwind-tables",
1832 "-fasynchronous-unwind-tables",
1833 "a.c",
1834 ]);
1835 assert!(opts.unwinds(), "the last flag did not win");
1836 let (opts, _) =
1840 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1841 assert!(opts.unwinds(), "the weaker request was dropped");
1842 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
1843 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
1844 let (opts, _) =
1845 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
1846 assert!(!opts.unwinds(), "both were turned off and one stayed on");
1847 }
1848
1849 #[test]
1850 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1851 for flag in [
1855 "-fno-common",
1856 "-fstrict-aliasing",
1857 "-fno-strict-aliasing",
1858 "-pipe",
1859 "-fdiagnostics-color",
1860 "-fno-diagnostics-color",
1861 "-fdiagnostics-color=always",
1862 "-fdiagnostics-color=never",
1863 "-fdiagnostics-color=auto",
1864 ] {
1865 let (opts, _) = compile(&["-c", flag, "a.c"]);
1866 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1867 }
1868 }
1869
1870 #[test]
1871 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1872 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1875 assert!(e.message.contains(".bss"), "{}", e.message);
1876 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1877 }
1878
1879 #[test]
1880 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1881 for flag in ["-fno-pic", "-fno-pie"] {
1882 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1883 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1884 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1887 }
1888 }
1889
1890 #[test]
1891 fn an_unsupported_target_names_itself() {
1892 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1893 assert!(e.message.contains("sparc64"), "{}", e.message);
1894 }
1895
1896 #[test]
1897 fn no_inputs_is_an_error_but_print_config_needs_none() {
1898 assert!(parse_args(&args(&[])).is_err());
1899 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1900 }
1901
1902 #[test]
1903 fn print_config_reports_the_target_it_was_given_not_the_host() {
1904 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1905 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1906 let text = print_config(&opts);
1907 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1908 assert!(text.contains("char-signed: false"), "{text}");
1909 assert!(text.contains("object-format: elf"), "{text}");
1910 assert!(text.contains("va-list: void-pointer"), "{text}");
1911 assert!(text.contains("registers: none"), "{text}");
1914 }
1915
1916 #[test]
1917 fn print_config_has_one_key_per_line_and_a_fixed_order() {
1918 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1919 let text = print_config(&opts);
1920 let keys: Vec<&str> =
1921 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1922 assert_eq!(keys[0], "version");
1923 assert_eq!(keys[1], "target");
1924 assert_eq!(keys.len(), 19);
1925 assert!(text.ends_with('\n'));
1926 }
1927
1928 #[test]
1929 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
1930 let (opts, _) = compile(&["a.c"]);
1931 assert_eq!(opts.safety, rucc_session::Safety::Off);
1932
1933 for (flag, tier) in [
1934 ("-fsafety=detect", rucc_session::Safety::Detect),
1935 ("-fsafety=enforce", rucc_session::Safety::Enforce),
1936 ("-fsafety=kernel", rucc_session::Safety::Kernel),
1937 ("-fsafety=off", rucc_session::Safety::Off),
1938 ] {
1939 let (opts, _) = compile(&[flag, "a.c"]);
1940 assert_eq!(opts.safety, tier, "{flag}");
1941 }
1942
1943 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
1945 assert_eq!(opts.safety, rucc_session::Safety::Off);
1946
1947 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
1950 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
1951 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
1952 }
1953
1954 #[test]
1955 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
1956 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1957 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1958 let text = print_pipeline(&opts);
1959 assert!(text.starts_with("level: -O2\n"), "{text}");
1960 assert!(text.contains("fold"), "{text}");
1961
1962 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
1963 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1964 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
1967
1968 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
1969 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1970 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1973 }
1974
1975 #[test]
1976 fn print_pipeline_takes_the_toggles_into_account() {
1977 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
1978 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1979 let text = print_pipeline(&opts);
1980 assert!(!text.contains("fold"), "{text}");
1983 assert!(text.contains("dce"), "{text}");
1984
1985 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
1989 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
1990 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
1991 let a = parse_args(&args(&spelled)).unwrap();
1992 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1993 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1994 }
1995
1996 #[test]
1997 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
1998 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1999 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2000 assert!(!print_pipeline(&opts).contains("global fuel"));
2001
2002 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2003 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2004 let text = print_pipeline(&opts);
2005 assert!(text.contains("global fuel: 4"), "{text}");
2008 }
2009
2010 #[test]
2013 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2014 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2015 assert_eq!(
2016 opts.passes,
2017 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2018 );
2019
2020 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2021 assert!(e.message.contains("unknown option"), "{}", e.message);
2022 }
2023
2024 #[test]
2025 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2026 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2027 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2028
2029 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2030 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2031 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2032 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2033 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2034 assert!(e.message.contains("not a number"), "{}", e.message);
2035 }
2036
2037 #[test]
2038 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2039 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2040 assert_eq!(opts.pass_fuel_global, None);
2041
2042 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2043 assert_eq!(opts.pass_fuel_global, Some(12));
2044 assert!(opts.pass_fuel.is_empty());
2047
2048 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2049 assert!(e.message.contains("not a number"), "{}", e.message);
2050 }
2051
2052 #[test]
2053 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2054 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2055 assert_eq!(
2056 opts.pass_gates,
2057 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2058 "the order is what decides, so it has to survive the parse"
2059 );
2060
2061 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2062 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2063 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2064 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2065 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2066 assert!(e.message.contains("is empty"), "{}", e.message);
2067 }
2068
2069 #[test]
2070 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2071 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2072 let text = print_pipeline(&opts);
2073 assert!(text.contains("fold, "), "{text}");
2074 assert!(text.contains("[off for main]"), "{text}");
2075 }
2076
2077 #[test]
2081 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2082 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2083 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2084
2085 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2086 assert!(e.message.contains("nosuch"), "{}", e.message);
2087 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2088 }
2089
2090 #[test]
2096 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2097 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2098 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2099 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2100
2101 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2102 assert_eq!(opts.opt_info, ["missed-note"]);
2103
2104 let (opts, _) =
2107 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2108 assert_eq!(opts.opt_info, ["missed", "all"]);
2109 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2110
2111 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2112 assert!(e.message.contains("vectorized"), "{}", e.message);
2113 assert!(e.message.contains("`missed`"), "{}", e.message);
2114 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2115 assert!(e.message.contains("no file"), "{}", e.message);
2116 }
2117
2118 #[test]
2119 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2120 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2121 assert!(opts.verify_each);
2122 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2123 }
2124
2125 #[test]
2126 fn dash_o_needs_an_argument() {
2127 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2128 assert_eq!(e.message, "-o requires an argument");
2129 }
2130
2131 #[test]
2132 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2133 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2134 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2135 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2136 }
2137
2138 #[test]
2139 fn the_include_flags_land_on_the_chain_each_one_names() {
2140 let (opts, _) = compile(&[
2143 "-Ii",
2144 "-iquote",
2145 "q",
2146 "-isystem",
2147 "sys",
2148 "-idirafter",
2149 "after",
2150 "--sysroot=/nowhere-at-all",
2151 "a.c",
2152 ]);
2153 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2154 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2157 assert!(!opts.search.dirs()[1].is_system);
2158 assert!(opts.search.dirs()[2].is_system);
2159 }
2160
2161 #[test]
2162 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2163 let (opts, _) = compile(&["a.c"]);
2167 let dirs = opts.search.dirs();
2168 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2169 assert_eq!(ours, Some(0), "{dirs:?}");
2170 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2171 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2172 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2173 }
2174
2175 #[test]
2176 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2177 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2178 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2179 assert_eq!(dirs, ["sys", runtime::DIR]);
2180 }
2181
2182 #[test]
2183 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2184 let (opts, _) =
2185 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2186 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2187 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2188 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2190 assert!(!opts.search.searches_current_dir());
2191 }
2192
2193 #[test]
2194 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2195 let (opts, _) = compile(&[
2196 "-iprefix",
2197 "/tools/",
2198 "-iwithprefix",
2199 "late",
2200 "-iwithprefixbefore",
2201 "early",
2202 "-iprefix",
2203 "/other/",
2204 "-iwithprefix",
2205 "last",
2206 "-nostdinc",
2207 "a.c",
2208 ]);
2209 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2210 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2213 assert!(!opts.search.dirs()[0].is_system);
2214 assert!(opts.search.dirs()[1].is_system);
2215 }
2216
2217 #[test]
2218 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2219 let (opts, _) =
2220 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2221 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2222 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2223 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2224 }
2225
2226 #[test]
2227 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2228 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2229 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2230 assert_eq!(dirs, ["i"]);
2231 }
2232
2233 #[test]
2234 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2235 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2236 assert_eq!(opts.std, Std::C11);
2237 assert!(opts.gnu_extensions);
2238
2239 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2240 assert_eq!(opts.std, Std::C99);
2241 assert!(!opts.gnu_extensions);
2242
2243 let (opts, _) = compile(&["-ansi", "a.c"]);
2244 assert_eq!(opts.std, Std::C89);
2245 assert!(!opts.gnu_extensions);
2246
2247 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2248 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2249 }
2250
2251 #[test]
2252 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2253 let (opts, _) = compile(&["-dM", "a.c"]);
2254 assert!(opts.dumps.macros);
2255
2256 let (opts, _) = compile(&["-dDM", "a.c"]);
2259 assert!(opts.dumps.macros);
2260 let (opts, _) = compile(&["-dD", "a.c"]);
2261 assert!(!opts.dumps.macros);
2262
2263 let (opts, _) = compile(&["a.c"]);
2264 assert!(!opts.dumps.any());
2265
2266 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2269 }
2270
2271 #[test]
2272 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2273 let (opts, _) = compile(&["a.c"]);
2274 assert_eq!(
2275 opts.gnuc,
2276 GnucVersion { major: 7, minor: 0, patch: 0 },
2277 "the lowest claim a modern glibc gives its own declarations to"
2278 );
2279
2280 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2281 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2282
2283 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2286 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2287
2288 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2289 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2290
2291 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2292 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2293
2294 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2295 assert!(e.message.contains("more than three"), "{}", e.message);
2296 }
2297
2298 #[test]
2299 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2300 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2301 assert!(opts.pedantic);
2302 assert_eq!(opts.std, Std::C17);
2303
2304 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2307 assert!(opts.pedantic);
2308
2309 let (opts, _) = compile(&["-std=c17", "a.c"]);
2310 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2311 }
2312
2313 #[test]
2314 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2315 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2316 assert!(!opts.line_markers);
2317 assert!(!opts.hosted);
2318 assert_eq!(opts.emit, EmitKind::Preprocessed);
2319 }
2320
2321 #[test]
2328 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2329 let (opts, _) = compile(&["-c", "a.c"]);
2330 assert!(opts.builtins, "a library name means the library function by default");
2331 assert!(opts.no_builtin.is_empty());
2332
2333 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2334 assert!(!opts.builtins);
2335
2336 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2337 assert!(opts.builtins, "the last mention decides");
2338
2339 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2340 assert!(opts.builtins, "one name is not the family");
2341 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2342 }
2343
2344 #[test]
2352 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2353 let (opts, _) = compile(&["-c", "a.c"]);
2354 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2355
2356 for (written, wanted) in [
2357 ("default", Visibility::Default),
2358 ("hidden", Visibility::Hidden),
2359 ("internal", Visibility::Hidden),
2360 ("protected", Visibility::Protected),
2361 ] {
2362 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2363 assert_eq!(opts.visibility, wanted, "{written}");
2364 }
2365
2366 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2369 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2370
2371 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2375 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2376 }
2377
2378 #[test]
2381 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2382 let (opts, _) = compile(&["-c", "a.c"]);
2383 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2384
2385 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2386 assert!(opts.gnu89_inline);
2387
2388 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2389 assert!(!opts.gnu89_inline, "the last mention decides");
2390
2391 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2396 assert!(!opts.gnu89_inline);
2397 }
2398
2399 #[test]
2402 fn the_two_frame_flags_are_read_in_both_directions() {
2403 let (opts, _) = compile(&["-c", "a.c"]);
2404 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2405 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2406
2407 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2408 assert!(opts.frame_pointer);
2409 assert!(!opts.red_zone);
2410
2411 let (opts, _) = compile(&[
2412 "-c",
2413 "-fno-omit-frame-pointer",
2414 "-fomit-frame-pointer",
2415 "-mno-red-zone",
2416 "-mred-zone",
2417 "a.c",
2418 ]);
2419 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2420 assert!(opts.red_zone);
2421 }
2422
2423 #[test]
2424 fn the_link_flags_are_collected_apart_from_the_compilation() {
2425 let (link, _) = linking(&[
2426 "-static",
2427 "-nostartfiles",
2428 "-rdynamic",
2429 "-s",
2430 "-fuse-ld=mold",
2431 "-L/opt/lib",
2432 "-B",
2433 "/opt/tools",
2434 "a.c",
2435 ]);
2436 assert!(link.is_static);
2437 assert!(link.no_startfiles);
2438 assert!(link.export_dynamic);
2439 assert!(link.strip);
2440 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2441 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2442 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2443 }
2444
2445 #[test]
2446 fn a_comma_in_dash_wl_separates_two_arguments() {
2447 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2448 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2449 }
2450
2451 #[test]
2452 fn a_library_keeps_its_place_between_the_objects() {
2453 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2458 let link = plan.link.expect("expected a link step");
2459 assert_eq!(
2460 link.inputs,
2461 vec![
2462 link::Item::File("a.o".into()),
2463 link::Item::Library("m".into()),
2464 link::Item::File("b.o".into()),
2465 ]
2466 );
2467 assert_eq!(plan.jobs.len(), 2);
2469 }
2470
2471 #[test]
2472 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2473 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2474 assert!(plan.link.is_none());
2475 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2476 }
2477
2478 #[test]
2479 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2480 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2481 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2482 }
2483
2484 fn printed(s: &[&str]) -> String {
2485 match parse_args(&args(s)).expect("expected an answer") {
2486 Action::Print(line) => line,
2487 other => panic!("expected an answer, got {other:?}"),
2488 }
2489 }
2490
2491 fn refused(s: &[&str]) -> String {
2492 parse_args(&args(s)).expect_err("expected a refusal").message
2493 }
2494
2495 #[test]
2496 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2497 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2501 assert!(!opts.warnings_are_errors);
2502 assert!(opts.warnings);
2503 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2505 assert!(opts.warnings_are_errors);
2506 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2507 assert!(!opts.warnings);
2508 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2509 assert!(opts.pedantic && opts.warnings_are_errors);
2510 }
2511
2512 #[test]
2513 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2514 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2516 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2517 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2518 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2519 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2520 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2521 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2524 assert!(no32.contains("32 bit target"), "{no32}");
2525 }
2526
2527 #[test]
2528 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2529 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2530 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2531 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2532 }
2533
2534 #[test]
2535 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2536 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2537 let (opts, _) =
2538 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2539 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2540 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2541 assert!(wrong.contains("sysv convention"), "{wrong}");
2542 }
2543
2544 #[test]
2545 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2546 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2547 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2548 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2551 assert_eq!(names, vec!["a.c"]);
2552 }
2553
2554 #[test]
2555 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2556 let target = "--target=x86_64-unknown-linux-gnu";
2557 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2558 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2559 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2560 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2561 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2564 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2565 let dirs = printed(&[target, "-print-search-dirs"]);
2566 assert!(dirs.starts_with("install: "), "{dirs}");
2567 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2568 }
2569
2570 #[test]
2571 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2572 let (opts, _) = compile(&["-M", "a.c"]);
2573 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2574 assert!(opts.deps.system_headers, "plain -M lists them");
2575 assert_eq!(opts.emit, EmitKind::Preprocessed);
2576
2577 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2580 assert_eq!(opts.emit, EmitKind::Preprocessed);
2581
2582 let (opts, _) = compile(&["-MM", "a.c"]);
2583 assert!(!opts.deps.system_headers);
2584 }
2585
2586 #[test]
2587 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2588 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2589 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2590 assert!(opts.deps.system_headers);
2591 assert_eq!(opts.emit, EmitKind::Object);
2592
2593 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2594 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2595 assert!(!opts.deps.system_headers);
2596 }
2597
2598 #[test]
2599 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2600 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2603 assert!(!opts.deps.system_headers);
2604 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2605 assert!(!opts.deps.system_headers);
2606 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2607 assert!(!opts.deps.system_headers);
2608 }
2609
2610 #[test]
2611 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2612 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2613 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2614 }
2615
2616 #[test]
2617 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2618 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2619 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2620 assert!(opts.deps.phony);
2621
2622 for flag in ["-MF", "-MT", "-MQ"] {
2623 let e = parse_args(&args(&[flag])).unwrap_err();
2624 assert!(e.message.contains("requires an argument"), "{}", e.message);
2625 }
2626 }
2627
2628 struct TempTree(PathBuf);
2630
2631 impl Drop for TempTree {
2632 fn drop(&mut self) {
2633 let _ = std::fs::remove_dir_all(&self.0);
2634 }
2635 }
2636
2637 impl TempTree {
2638 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2639 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2640 let _ = std::fs::remove_dir_all(&dir);
2641 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2642 for (path, text) in files {
2643 let at = dir.join(path);
2644 if let Some(parent) = at.parent() {
2645 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2646 }
2647 std::fs::write(&at, text).expect("writing a temporary file should work");
2648 }
2649 TempTree(dir)
2650 }
2651
2652 fn path(&self, name: &str) -> String {
2653 self.0.join(name).to_string_lossy().into_owned()
2654 }
2655 }
2656
2657 #[test]
2658 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2659 let tree = TempTree::new(
2663 "found",
2664 &[
2665 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2666 ("one.h", "#define X 0\n"),
2667 ("two.h", "#include \"one.h\"\n"),
2668 ],
2669 );
2670 let out = tree.path("dep.d");
2671 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2672 assert_eq!(code, 0);
2673
2674 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2675 let names: Vec<&str> = text.split_whitespace().collect();
2676 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2678 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2679 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2680 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2683 }
2684
2685 #[test]
2686 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2687 let tree = TempTree::new(
2690 "guarded",
2691 &[
2692 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2693 ("g.h", "#ifndef G\n#define G\n#endif\n"),
2694 ],
2695 );
2696 let out = tree.path("dep.d");
2697 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2698 assert_eq!(code, 0);
2699 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2700 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2701 }
2702
2703 #[test]
2704 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2705 let tree = TempTree::new(
2710 "preinclude",
2711 &[
2712 ("a.c", "int main(void) { return 0; }\n"),
2713 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2714 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2715 ],
2716 );
2717 let out = tree.path("a.i");
2718 let code = run(&args(&[
2719 "-E",
2720 "-include",
2721 &tree.path("i.h"),
2722 "-imacros",
2723 &tree.path("m.h"),
2724 "-o",
2725 &out,
2726 &tree.path("a.c"),
2727 ]));
2728 assert_eq!(code, 0);
2729 let text = std::fs::read_to_string(&out).expect("the output should have been written");
2730 assert!(text.contains("saw_it"), "{text}");
2731 assert!(!text.contains("macros_text"), "{text}");
2734 }
2735
2736 #[test]
2737 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
2738 let tree = TempTree::new(
2739 "preinclude-deps",
2740 &[
2741 ("a.c", "int main(void) { return 0; }\n"),
2742 ("i.h", "int from_include;\n"),
2743 ("m.h", "#define M 1\n"),
2744 ],
2745 );
2746 let out = tree.path("dep.d");
2747 let code = run(&args(&[
2748 "-MM",
2749 "-MF",
2750 &out,
2751 "-include",
2752 &tree.path("i.h"),
2753 "-imacros",
2754 &tree.path("m.h"),
2755 "-o",
2756 &tree.path("a.i"),
2757 &tree.path("a.c"),
2758 ]));
2759 assert_eq!(code, 0);
2760 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2761 assert!(text.contains("i.h"), "{text}");
2762 assert!(text.contains("m.h"), "{text}");
2763 }
2764
2765 #[test]
2766 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
2767 let tree = TempTree::new(
2771 "preinclude-missing",
2772 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
2773 );
2774 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
2775 assert_eq!(code, 1);
2776 }
2777
2778 #[test]
2779 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
2780 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
2784 assert_eq!(plan.output.as_deref(), Some("prog"));
2785 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
2786 assert_eq!(
2787 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
2788 Some("prog.d")
2789 );
2790 }
2791
2792 #[test]
2793 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
2794 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
2795 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
2796 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
2797 assert_eq!(plan.output, None);
2798 }
2799
2800 #[test]
2801 fn usage_fits_on_a_screen() {
2802 assert!(USAGE.lines().count() < 48, "usage text has grown past one screen");
2820 }
2821}