1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.4")]
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 "-fno-pic" | "-fno-pie" => {
538 return Err(err(
539 "position dependent code is not supported: an address that may be in another \
540 object is loaded out of the global offset table, and nothing here emits the \
541 absolute form this asks for. Use -no-pie if what you meant was how to link",
542 ));
543 }
544 "-fno-common" => {}
550 "-fcommon" => {
554 return Err(err(
555 "a tentative definition is written into .bss as its own symbol here, and \
556 nothing emits the common symbol this asks the linker to merge. Give the \
557 variable a definition in one file and declare it extern in the others",
558 ));
559 }
560 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
574 "-pipe" => {}
577 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
584 _ if arg.starts_with("-fdiagnostics-color=") => {}
585 "-static" => link.is_static = true,
589 "-shared" => link.shared = true,
590 "-pie" => link.pie = Some(true),
591 "-no-pie" | "-nopie" => link.pie = Some(false),
592 "-nostdlib" => link.no_stdlib = true,
593 "-nostartfiles" => link.no_startfiles = true,
594 "-nodefaultlibs" => link.no_defaultlibs = true,
595 "-fno-builtins-lib" => link.no_builtins_lib = true,
596 "-fbuiltins-lib" => link.no_builtins_lib = false,
597 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
598 "-s" => link.strip = true,
599 "-Xlinker" => {
600 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
601 i += 1;
602 link.passthrough.push(next.clone());
603 }
604 _ if arg.starts_with("-Wl,") => {
605 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
608 }
609 _ if arg.starts_with("-fuse-ld=") => {
610 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
611 }
612 _ if arg.starts_with("-l") && arg.len() > 2 => {
613 inputs.push(Input::library(&arg[2..]));
614 }
615 "-l" => {
616 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
617 i += 1;
618 inputs.push(Input::library(next));
619 }
620 _ if arg.starts_with("-L") => {
621 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
622 }
623 _ if arg.starts_with("-B") => {
624 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
625 }
626 _ if arg.starts_with("-j") => {
627 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
628 }
629 _ if arg.starts_with("--sysroot=") => {
630 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
631 }
632 _ if arg.starts_with("--target=") => {
633 let t = &arg["--target=".len()..];
634 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
635 }
636 _ if arg.starts_with("--emit=") => {
637 let k = &arg["--emit=".len()..];
638 opts.emit = k
639 .parse()
640 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
641 }
642 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
648 "-Ofast" => {
654 return Err(err(
655 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
656 spec/04-driver-and-cli.md section 4.6",
657 ));
658 }
659 _ if arg.starts_with("-O") => {
660 opts.opt_level = arg[2..]
661 .parse()
662 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
663 }
664 _ if arg.starts_with("-fvisibility=") => {
668 let seen = &arg["-fvisibility=".len()..];
669 opts.visibility = seen.parse().map_err(|()| {
670 err(format!(
671 "`{seen}` is not a visibility, which is default, hidden, internal or \
672 protected"
673 ))
674 })?;
675 }
676 _ if arg.starts_with("-fsafety=") => {
681 let tier = &arg["-fsafety=".len()..];
682 opts.safety = tier.parse().map_err(|()| {
683 err(format!(
684 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
685 ))
686 })?;
687 }
688 _ if arg.starts_with("-fpass-fuel=") => {
692 let (name, count) = arg["-fpass-fuel=".len()..]
693 .split_once('=')
694 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
695 if rucc_opt::pass::find(name).is_none() {
696 return Err(err(format!(
697 "`{name}` is not a pass this compiler has, see --print-pipeline"
698 )));
699 }
700 let count: u32 = count
701 .parse()
702 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
703 opts.pass_fuel.push((name.to_owned(), count));
704 }
705 _ if arg.starts_with("-fpass-fuel-global=") => {
706 let count = &arg["-fpass-fuel-global=".len()..];
707 let count: u32 = count
708 .parse()
709 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
710 opts.pass_fuel_global = Some(count);
711 }
712 _ if arg == "-fopt-info"
717 || arg.starts_with("-fopt-info=")
718 || arg.starts_with("-fopt-info-") =>
719 {
720 let rest = &arg["-fopt-info".len()..];
721 let (kinds, file) = match rest.split_once('=') {
722 Some((kinds, file)) => (kinds, Some(file)),
723 None => (rest, None),
724 };
725 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
726 rucc_opt::Wants::none().add(kinds).map_err(err)?;
727 opts.opt_info.push(kinds.to_owned());
728 if let Some(file) = file {
729 if file.is_empty() {
730 return Err(err("-fopt-info= was given no file to write to"));
731 }
732 opts.opt_info_file = Some(file.to_owned());
733 }
734 }
735 _ if arg.starts_with("-fdump-ir=") => {
736 let spec = &arg["-fdump-ir=".len()..];
739 rucc_opt::Dumps::default().add(spec).map_err(err)?;
740 opts.dump_ir.push(spec.to_owned());
741 }
742 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
748 let on = arg.starts_with("-fenable-");
749 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
750 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
751 opts.pass_gates.push((on, spec.to_owned()));
752 }
753 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
754 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
755 }
756 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
757 opts.passes.push((arg["-f".len()..].to_owned(), true));
758 }
759 "-Zverify-each" => opts.verify_each = true,
765 _ if arg.starts_with("-Zrule-coverage=") => {
766 let file = &arg["-Zrule-coverage=".len()..];
767 if file.is_empty() {
768 return Err(err("-Zrule-coverage= needs a file to write to"));
769 }
770 opts.rule_coverage = Some(file.to_owned());
771 }
772 _ if arg.starts_with("-Z") => {
773 return Err(err(format!(
774 "`{arg}` is not an unstable option this compiler has, see \
775 spec/04-driver-and-cli.md section 4.11 for the ones it does"
776 )));
777 }
778 "-m64" | "-m32" | "-mx32" => {
783 let want: u32 = match arg {
784 "-m64" => 64,
785 _ => 32,
786 };
787 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
788 if have != want {
789 return Err(err(format!(
790 "{arg} asks for a {want} bit target and {} is {have} bit, use \
791 --target= to name the one you mean",
792 opts.target
793 )));
794 }
795 }
796 _ if arg.starts_with("-march=")
802 || arg.starts_with("-mtune=")
803 || arg.starts_with("-mcpu=") => {}
804 _ if arg.starts_with("-mabi=") => {
807 let want = &arg["-mabi=".len()..];
808 let have = match opts.target.arch {
809 rucc_target::Arch::X86_64 => "sysv",
810 rucc_target::Arch::Aarch64 => "lp64",
811 rucc_target::Arch::Riscv64 => "lp64d",
812 };
813 if want != have {
814 return Err(err(format!(
815 "{arg}: {} uses the {have} convention and this compiler has no other",
816 opts.target
817 )));
818 }
819 }
820 "-mcmodel=small" => {}
824 _ if arg.starts_with("-mcmodel=") => {
825 return Err(err(format!(
826 "{arg}: this compiler emits the small code model and no other, see \
827 spec/12-targets.md"
828 )));
829 }
830 _ if arg.starts_with("-specs=") => {
834 return Err(err(
835 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
836 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
837 section 4.4",
838 ));
839 }
840 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
846 return Err(err(format!(
847 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
848 are inside this compiler rather than programs it runs"
849 )));
850 }
851 "-Xassembler" | "-Xpreprocessor" => {
852 return Err(err(format!(
853 "{arg} hands an argument to a separate assembler or preprocessor, and both \
854 are inside this compiler rather than programs it runs"
855 )));
856 }
857 _ if arg.starts_with("-W") => {}
864 "-fno-ident"
870 | "-fident"
871 | "-funit-at-a-time"
872 | "-fno-unit-at-a-time"
873 | "-shared-libgcc"
874 | "-static-libgcc" => {}
875 _ if arg.starts_with('-') && arg.len() > 1 => {
876 return Err(err(format!("unknown option `{arg}`")));
881 }
882 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
883 }
884 }
885
886 link.sysroot = sysroot.clone();
893 if threads {
898 inputs.push(Input::library("pthread"));
899 }
900 if let Some(query) = query {
901 return Ok(Action::Print(answer(&query, &opts, &link)));
902 }
903 if opts.deps.instead_of_compiling {
909 opts.emit = EmitKind::Preprocessed;
910 }
911 if !nostdinc {
912 opts.search.push_system(runtime::DIR);
913 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
917 opts.search.push_system(dir);
918 }
919 }
920 opts.search.remove_duplicates();
924
925 if print_config {
928 return Ok(Action::PrintConfig(Box::new(opts)));
929 }
930 if print_pipeline {
931 return Ok(Action::PrintPipeline(Box::new(opts)));
932 }
933 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
934 if print_plan {
935 return Ok(Action::PrintPlan {
936 opts: Box::new(opts),
937 plan: Box::new(plan),
938 link: Box::new(link),
939 });
940 }
941 Ok(Action::Compile {
942 opts: Box::new(opts),
943 plan: Box::new(plan),
944 link: Box::new(link),
945 jobs,
946 verbose,
947 })
948}
949
950fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
956 let found = |name: &str| {
957 link::find_in_search(link, opts.target, name)
958 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
959 };
960 match query {
961 Query::Machine => opts.target.to_string(),
962 Query::Version => VERSION.to_owned(),
963 Query::Multiarch => link::multiarch(opts.target),
964 Query::SearchDirs => {
969 let here = std::env::current_exe()
970 .ok()
971 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
972 .unwrap_or_default();
973 let list = |dirs: &[PathBuf]| {
974 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
975 };
976 let libraries = link::search_dirs(link, opts.target);
977 format!(
978 "install: {}\nprograms: ={}\nlibraries: ={}",
979 here.display(),
980 list(&link.prefixes),
981 list(&libraries)
982 )
983 }
984 Query::FileName(name) => found(name),
985 Query::Libgcc => found("libgcc.a"),
989 Query::ProgName(name) => link
993 .prefixes
994 .iter()
995 .map(|dir| dir.join(name))
996 .find(|path| path.is_file())
997 .map_or_else(|| name.clone(), |path| path.display().to_string()),
998 }
999}
1000
1001#[must_use]
1007pub fn print_pipeline(opts: &Options) -> String {
1008 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1009 settings.toggles.clone_from(&opts.passes);
1010 settings.global_fuel = opts.pass_fuel_global;
1011 for (on, spec) in &opts.pass_gates {
1012 let _ = settings.gates.add(*on, spec);
1015 }
1016 rucc_opt::pipeline::print(&settings)
1017}
1018
1019#[must_use]
1024pub fn print_config(opts: &Options) -> String {
1025 let sess = Session::new(opts.clone());
1026 let t = &sess.target;
1027 let mut out = String::new();
1028 let _ = writeln!(out, "version: {VERSION}");
1029 let _ = writeln!(out, "target: {}", opts.target);
1033 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1034 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1035 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1036 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1037 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1038 let _ = writeln!(out, "long-width: {}", t.long_width);
1039 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1040 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1041 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1042 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1043 let regs: Vec<String> = t
1046 .regs
1047 .classes()
1048 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1049 .collect();
1050 let _ = writeln!(
1051 out,
1052 "registers: {}",
1053 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1054 );
1055 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1056 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1057 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1058 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1059 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1060 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1061 for dir in sess.opts.search.dirs() {
1064 let system = if dir.is_system { " (system)" } else { "" };
1065 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1066 }
1067 out
1068}
1069
1070fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1078 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1079}
1080
1081fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1084 if path == "-" {
1085 return write_out(&Output::Stdout, bytes);
1086 }
1087 write_out(&Output::File(path.to_owned()), bytes)
1088}
1089
1090fn write_deps(
1096 opts: &Options,
1097 plan: &Plan,
1098 job: &Job,
1099 found: &[Dependency],
1100 stderr: &mut impl std::io::Write,
1101) -> bool {
1102 let targets = if opts.deps.targets.is_empty() {
1103 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1104 } else {
1105 opts.deps.targets.clone()
1106 };
1107 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1108 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1111 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1115 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1116 }),
1117 None => write_out(&job.output, rule.as_bytes()),
1118 };
1119 if let Err(e) = wrote {
1120 let _ = writeln!(stderr, "rucc: error: {e}");
1121 return false;
1122 }
1123 true
1124}
1125
1126fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1132 let fs = OsFileSystem::new();
1133 let mut stderr = std::io::stderr().lock();
1134 let mut failed = false;
1135 for job in &plan.jobs {
1136 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1137 continue;
1140 }
1141 let started = std::time::Instant::now();
1142 let result = preprocess(opts, &job.input, &fs);
1143 if opts.time {
1144 say_time(&job.input, started.elapsed(), &mut stderr);
1145 }
1146 for message in &result.messages {
1147 let _ = writeln!(stderr, "{message}");
1148 }
1149 if result.failed() {
1150 failed = true;
1151 continue;
1152 }
1153 if opts.deps.emit {
1154 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1155 if opts.deps.instead_of_compiling {
1158 continue;
1159 }
1160 }
1161 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1162 let _ = writeln!(stderr, "rucc: error: {e}");
1163 failed = true;
1164 }
1165 }
1166 i32::from(failed)
1167}
1168
1169fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1175 let fs = OsFileSystem::new();
1176 let mut stderr = std::io::stderr().lock();
1177 let mut failed = false;
1178 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1179 failed |= !ok;
1180 let mut fired = Fired::new();
1181 for job in &plan.jobs {
1182 if !job.phases.contains(&Phase::Compile) {
1183 continue;
1184 }
1185 let started = std::time::Instant::now();
1189 let result = if job.kind == InputKind::Ir {
1190 compile_ir(opts, &job.input, &fs)
1191 } else {
1192 compile(opts, &job.input, &fs)
1193 };
1194 if opts.time {
1195 say_time(&job.input, started.elapsed(), &mut stderr);
1196 }
1197 fired.merge(&result.fired);
1198 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1199 failed |= !remarks.write(&result.remarks, &mut stderr);
1200 for message in &result.messages {
1201 let _ = writeln!(stderr, "{message}");
1202 }
1203 failed |= !write_temps(job, &result.temps, &mut stderr);
1206 if result.failed() {
1207 failed = true;
1208 continue;
1209 }
1210 if opts.deps.emit {
1215 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1216 }
1217 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1218 let _ = writeln!(stderr, "rucc: error: {e}");
1219 failed = true;
1220 }
1221 }
1222 failed |= !write_coverage(opts, &fired, &mut stderr);
1223 i32::from(failed)
1224}
1225
1226struct Scratch {
1233 dir: PathBuf,
1235}
1236
1237impl Scratch {
1238 fn new() -> Result<Scratch, String> {
1244 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1245 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1246 Ok(Scratch { dir })
1247 }
1248}
1249
1250impl Drop for Scratch {
1251 fn drop(&mut self) {
1252 let _ = std::fs::remove_dir_all(&self.dir);
1253 }
1254}
1255
1256fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1263 let linker = link::find(opts.target, link)?;
1264 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1265 Ok(link::render(&linker, &args))
1266}
1267
1268fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1275 let Some(job) = &plan.link else {
1276 let mut stderr = std::io::stderr().lock();
1279 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1280 return 1;
1281 };
1282 let linker = match link::find(opts.target, link) {
1285 Ok(linker) => linker,
1286 Err(why) => return complain(why),
1287 };
1288
1289 let scratch = match Scratch::new() {
1290 Ok(scratch) => scratch,
1291 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1292 };
1293
1294 let fs = OsFileSystem::new();
1295 let mut failed = false;
1296 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1299 let mut fired = Fired::new();
1300 {
1301 let mut stderr = std::io::stderr().lock();
1302 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1303 failed |= !ok;
1304 for (at, job) in plan.jobs.iter().enumerate() {
1305 let out = match &job.output {
1306 Output::Temporary(hint) => {
1307 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1310 }
1311 Output::File(path) => path.clone(),
1312 Output::Stdout => continue,
1315 };
1316 produced.push(out.clone());
1317 if !job.phases.contains(&Phase::Compile) {
1318 continue;
1319 }
1320 let started = std::time::Instant::now();
1321 let result = if job.kind == InputKind::Ir {
1322 compile_ir(opts, &job.input, &fs)
1323 } else {
1324 compile(opts, &job.input, &fs)
1325 };
1326 if opts.time {
1327 say_time(&job.input, started.elapsed(), &mut stderr);
1328 }
1329 fired.merge(&result.fired);
1330 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1331 failed |= !remarks.write(&result.remarks, &mut stderr);
1332 for message in &result.messages {
1333 let _ = writeln!(stderr, "{message}");
1334 }
1335 failed |= !write_temps(job, &result.temps, &mut stderr);
1336 if result.failed() {
1337 failed = true;
1338 continue;
1339 }
1340 if opts.deps.emit {
1345 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1346 }
1347 if !matches!(result.artifact, Artifact::Object(_)) {
1348 let _ = writeln!(
1353 stderr,
1354 "rucc: internal error: {}: no object file was produced for the link",
1355 job.input
1356 );
1357 failed = true;
1358 continue;
1359 }
1360 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1361 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1362 failed = true;
1363 }
1364 }
1365 failed |= !write_coverage(opts, &fired, &mut stderr);
1366 }
1367 if failed {
1368 return 1;
1372 }
1373
1374 let mut outputs = produced.into_iter();
1378 let mut items = Vec::with_capacity(job.inputs.len());
1379 for item in &job.inputs {
1380 match item {
1381 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1382 link::Item::File(_) => match outputs.next() {
1383 Some(path) => items.push(link::Item::File(path)),
1384 None => return complain("the plan asks the linker for a file nothing produced"),
1385 },
1386 }
1387 }
1388
1389 let args = match link::line(opts.target, link, &items, &job.output) {
1390 Ok(args) => args,
1391 Err(why) => return complain(why),
1392 };
1393 if verbose {
1394 let mut stderr = std::io::stderr().lock();
1395 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1396 }
1397 let started = std::time::Instant::now();
1398 let ran = link::run(&linker, &args);
1399 if opts.time {
1400 let mut stderr = std::io::stderr().lock();
1403 say_time(&linker.name, started.elapsed(), &mut stderr);
1404 }
1405 match ran {
1406 Ok(()) => 0,
1407 Err(link::Error::Refused { .. }) => 1,
1410 Err(why) => complain(why),
1411 }
1412}
1413
1414fn complain(why: impl std::fmt::Display) -> i32 {
1416 let mut stderr = std::io::stderr().lock();
1417 let _ = writeln!(stderr, "rucc: error: {why}");
1418 1
1419}
1420
1421fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1430 let Some(path) = &opts.rule_coverage else { return true };
1431 let Some(table) = coverage::table(opts.target.arch) else {
1432 let _ = writeln!(
1433 stderr,
1434 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1435 to report",
1436 opts.target
1437 );
1438 return false;
1439 };
1440 match std::fs::write(path, fired.listing(table)) {
1441 Ok(()) => true,
1442 Err(e) => {
1443 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1444 false
1445 }
1446 }
1447}
1448
1449struct Remarks {
1456 file: Option<String>,
1458 started: bool,
1461}
1462
1463impl Remarks {
1464 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1470 let mut ok = true;
1471 if let Some(path) = file {
1472 if let Err(e) = std::fs::write(path, "") {
1473 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1474 ok = false;
1475 }
1476 }
1477 (Self { file: file.cloned(), started: false }, ok)
1478 }
1479
1480 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1486 if text.is_empty() {
1487 return true;
1488 }
1489 let Some(path) = &self.file else {
1490 let _ = write!(stderr, "{text}");
1491 return true;
1492 };
1493 let opened = std::fs::OpenOptions::new()
1494 .write(true)
1495 .append(self.started)
1496 .truncate(!self.started)
1497 .create(true)
1498 .open(path);
1499 self.started = true;
1500 let result =
1501 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1502 if let Err(e) = result {
1503 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1504 return false;
1505 }
1506 true
1507 }
1508}
1509
1510fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1521 let stem = std::path::Path::new(input)
1522 .file_name()
1523 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1524 let mut ok = true;
1525 for dump in dumps {
1526 let path = format!("{stem}.{}.ir", dump.name);
1527 if let Err(e) = std::fs::write(&path, &dump.text) {
1528 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1529 ok = false;
1530 }
1531 }
1532 ok
1533}
1534
1535fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1541 let mut ok = true;
1542 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1543 for (path, text) in kept {
1544 let (Some(path), Some(text)) = (path, text) else { continue };
1547 if let Err(e) = std::fs::write(&path, text) {
1548 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1549 ok = false;
1550 }
1551 }
1552 ok
1553}
1554
1555fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1562 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1563}
1564
1565fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1572 match output {
1573 Output::Stdout => {
1574 let mut stdout = std::io::stdout().lock();
1575 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1576 }
1577 Output::File(path) | Output::Temporary(path) => {
1578 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1579 }
1580 }
1581}
1582
1583pub fn run(args: &[String]) -> i32 {
1588 match parse_args(args) {
1589 Ok(Action::Help) => {
1590 print!("{USAGE}");
1591 0
1592 }
1593 Ok(Action::Version) => {
1594 println!("rucc {VERSION}");
1595 0
1596 }
1597 Ok(Action::Print(line)) => {
1598 println!("{line}");
1599 0
1600 }
1601 Ok(Action::PrintConfig(opts)) => {
1602 print!("{}", print_config(&opts));
1603 0
1604 }
1605 Ok(Action::PrintPipeline(opts)) => {
1606 print!("{}", print_pipeline(&opts));
1607 0
1608 }
1609 Ok(Action::PrintPlan { opts, plan, link }) => {
1610 print!("{}", plan.render());
1611 if let Some(job) = &plan.link {
1615 match link_line(&opts, &link, job) {
1616 Ok(line) => println!("{line}"),
1617 Err(why) => {
1618 let mut stderr = std::io::stderr().lock();
1619 let _ = writeln!(stderr, "rucc: error: {why}");
1620 return 1;
1621 }
1622 }
1623 }
1624 0
1625 }
1626 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1627 {
1628 let mut stderr = std::io::stderr().lock();
1629 if verbose {
1630 let _ = write!(stderr, "{}", plan.render());
1631 let _ = writeln!(stderr, "workers: {}", jobs.count());
1632 }
1633 }
1634 if opts.emit == EmitKind::Preprocessed {
1635 return preprocess_all(&opts, &plan);
1636 }
1637 if opts.emit != EmitKind::Executable {
1638 return compile_all(&opts, &plan);
1639 }
1640 link_all(&opts, &plan, &link, verbose)
1641 }
1642 Err(e) => {
1643 let mut stderr = std::io::stderr().lock();
1644 let _ = writeln!(stderr, "rucc: error: {e}");
1645 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1646 1
1647 }
1648 }
1649}
1650
1651#[cfg(test)]
1652mod tests {
1653 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1654
1655 use super::*;
1656
1657 fn args(s: &[&str]) -> Vec<String> {
1658 s.iter().map(|x| (*x).to_owned()).collect()
1659 }
1660
1661 #[test]
1662 fn help_and_version_win_over_everything_else() {
1663 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1664 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1665 }
1666
1667 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1668 match parse_args(&args(s)).expect("expected a compilation") {
1669 Action::Compile { opts, plan, .. } => (opts, plan),
1670 other => panic!("expected a compilation, got {other:?}"),
1671 }
1672 }
1673
1674 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1675 match parse_args(&args(s)).expect("expected a compilation") {
1676 Action::Compile { link, plan, .. } => (link, plan),
1677 other => panic!("expected a compilation, got {other:?}"),
1678 }
1679 }
1680
1681 #[test]
1682 fn collects_inputs_and_flags() {
1683 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1684 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1685 assert_eq!(paths, vec!["a.c", "b.c"]);
1686 assert_eq!(opts.opt_level, OptLevel::O2);
1687 assert_eq!(opts.emit, EmitKind::Object);
1688 assert!(opts.debug_info);
1689 }
1690
1691 #[test]
1694 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1695 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1696 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1697
1698 let (plain, _) = compile(&["-c", "a.c"]);
1699 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1700
1701 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1702 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1703 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1704 }
1705
1706 #[test]
1707 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1708 let (opts, _) = compile(&["-O", "a.c"]);
1709 assert_eq!(opts.opt_level, OptLevel::O1);
1710 }
1711
1712 #[test]
1713 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1714 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1715 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1716 assert_eq!(plan.jobs[1].kind, InputKind::C);
1717 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1718 }
1719
1720 #[test]
1721 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1722 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1723 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1724 other => panic!("expected a compilation, got {other:?}"),
1725 };
1726 assert_eq!(jobs.count(), 4);
1727
1728 let default = match parse_args(&args(&["a.c"])).unwrap() {
1729 Action::Compile { jobs, .. } => jobs,
1730 other => panic!("expected a compilation, got {other:?}"),
1731 };
1732 assert_eq!(default, Jobs::available());
1733 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1734 }
1735
1736 #[test]
1737 fn triple_hash_prints_the_plan_and_runs_nothing() {
1738 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1739 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1740 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1741 }
1742
1743 #[test]
1744 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1745 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1749 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1750 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1751 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1752 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1756 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1757 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1758 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1759 }
1760
1761 #[test]
1762 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1763 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1764 let (plain, without) = compile(&["-c", "a.c"]);
1765 assert!(opts.time);
1766 assert!(!plain.time);
1767 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1770 }
1771
1772 #[test]
1773 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1774 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1775 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1776 }
1777
1778 #[test]
1779 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1780 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1781 assert!(e.message.contains("unknown option"), "{}", e.message);
1782 }
1783
1784 #[test]
1787 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1788 let (opts, _) = compile(&["-c", "a.c"]);
1789 assert!(!opts.permissive, "off unless it is asked for");
1790
1791 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1792 assert!(opts.permissive);
1793
1794 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1795 assert!(!opts.permissive);
1796 }
1797
1798 #[test]
1799 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1800 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1801 assert!(e.message.contains("trampoline"), "{}", e.message);
1802 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1803 }
1804
1805 #[test]
1806 fn the_flag_every_configure_script_writes_is_taken() {
1807 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1810 let (opts, _) = compile(&["-c", flag, "a.c"]);
1811 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1812 }
1813 }
1814
1815 #[test]
1816 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1817 for flag in [
1821 "-fno-common",
1822 "-fstrict-aliasing",
1823 "-fno-strict-aliasing",
1824 "-pipe",
1825 "-fdiagnostics-color",
1826 "-fno-diagnostics-color",
1827 "-fdiagnostics-color=always",
1828 "-fdiagnostics-color=never",
1829 "-fdiagnostics-color=auto",
1830 ] {
1831 let (opts, _) = compile(&["-c", flag, "a.c"]);
1832 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1833 }
1834 }
1835
1836 #[test]
1837 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1838 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1841 assert!(e.message.contains(".bss"), "{}", e.message);
1842 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1843 }
1844
1845 #[test]
1846 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1847 for flag in ["-fno-pic", "-fno-pie"] {
1848 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1849 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1850 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1853 }
1854 }
1855
1856 #[test]
1857 fn an_unsupported_target_names_itself() {
1858 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1859 assert!(e.message.contains("sparc64"), "{}", e.message);
1860 }
1861
1862 #[test]
1863 fn no_inputs_is_an_error_but_print_config_needs_none() {
1864 assert!(parse_args(&args(&[])).is_err());
1865 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1866 }
1867
1868 #[test]
1869 fn print_config_reports_the_target_it_was_given_not_the_host() {
1870 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1871 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1872 let text = print_config(&opts);
1873 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1874 assert!(text.contains("char-signed: false"), "{text}");
1875 assert!(text.contains("object-format: elf"), "{text}");
1876 assert!(text.contains("va-list: void-pointer"), "{text}");
1877 assert!(text.contains("registers: none"), "{text}");
1880 }
1881
1882 #[test]
1883 fn print_config_has_one_key_per_line_and_a_fixed_order() {
1884 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1885 let text = print_config(&opts);
1886 let keys: Vec<&str> =
1887 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1888 assert_eq!(keys[0], "version");
1889 assert_eq!(keys[1], "target");
1890 assert_eq!(keys.len(), 19);
1891 assert!(text.ends_with('\n'));
1892 }
1893
1894 #[test]
1895 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
1896 let (opts, _) = compile(&["a.c"]);
1897 assert_eq!(opts.safety, rucc_session::Safety::Off);
1898
1899 for (flag, tier) in [
1900 ("-fsafety=detect", rucc_session::Safety::Detect),
1901 ("-fsafety=enforce", rucc_session::Safety::Enforce),
1902 ("-fsafety=kernel", rucc_session::Safety::Kernel),
1903 ("-fsafety=off", rucc_session::Safety::Off),
1904 ] {
1905 let (opts, _) = compile(&[flag, "a.c"]);
1906 assert_eq!(opts.safety, tier, "{flag}");
1907 }
1908
1909 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
1911 assert_eq!(opts.safety, rucc_session::Safety::Off);
1912
1913 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
1916 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
1917 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
1918 }
1919
1920 #[test]
1921 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
1922 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1923 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1924 let text = print_pipeline(&opts);
1925 assert!(text.starts_with("level: -O2\n"), "{text}");
1926 assert!(text.contains("fold"), "{text}");
1927
1928 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
1929 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1930 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
1933
1934 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
1935 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1936 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1939 }
1940
1941 #[test]
1942 fn print_pipeline_takes_the_toggles_into_account() {
1943 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
1944 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1945 let text = print_pipeline(&opts);
1946 assert!(!text.contains("fold"), "{text}");
1949 assert!(text.contains("dce"), "{text}");
1950
1951 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
1955 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
1956 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
1957 let a = parse_args(&args(&spelled)).unwrap();
1958 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1959 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1960 }
1961
1962 #[test]
1963 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
1964 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1965 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1966 assert!(!print_pipeline(&opts).contains("global fuel"));
1967
1968 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
1969 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1970 let text = print_pipeline(&opts);
1971 assert!(text.contains("global fuel: 4"), "{text}");
1974 }
1975
1976 #[test]
1979 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
1980 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
1981 assert_eq!(
1982 opts.passes,
1983 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
1984 );
1985
1986 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
1987 assert!(e.message.contains("unknown option"), "{}", e.message);
1988 }
1989
1990 #[test]
1991 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
1992 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
1993 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
1994
1995 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
1996 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
1997 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
1998 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
1999 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2000 assert!(e.message.contains("not a number"), "{}", e.message);
2001 }
2002
2003 #[test]
2004 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2005 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2006 assert_eq!(opts.pass_fuel_global, None);
2007
2008 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2009 assert_eq!(opts.pass_fuel_global, Some(12));
2010 assert!(opts.pass_fuel.is_empty());
2013
2014 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2015 assert!(e.message.contains("not a number"), "{}", e.message);
2016 }
2017
2018 #[test]
2019 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2020 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2021 assert_eq!(
2022 opts.pass_gates,
2023 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2024 "the order is what decides, so it has to survive the parse"
2025 );
2026
2027 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2028 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2029 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2030 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2031 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2032 assert!(e.message.contains("is empty"), "{}", e.message);
2033 }
2034
2035 #[test]
2036 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2037 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2038 let text = print_pipeline(&opts);
2039 assert!(text.contains("fold, "), "{text}");
2040 assert!(text.contains("[off for main]"), "{text}");
2041 }
2042
2043 #[test]
2047 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2048 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2049 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2050
2051 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2052 assert!(e.message.contains("nosuch"), "{}", e.message);
2053 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2054 }
2055
2056 #[test]
2062 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2063 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2064 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2065 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2066
2067 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2068 assert_eq!(opts.opt_info, ["missed-note"]);
2069
2070 let (opts, _) =
2073 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2074 assert_eq!(opts.opt_info, ["missed", "all"]);
2075 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2076
2077 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2078 assert!(e.message.contains("vectorized"), "{}", e.message);
2079 assert!(e.message.contains("`missed`"), "{}", e.message);
2080 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2081 assert!(e.message.contains("no file"), "{}", e.message);
2082 }
2083
2084 #[test]
2085 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2086 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2087 assert!(opts.verify_each);
2088 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2089 }
2090
2091 #[test]
2092 fn dash_o_needs_an_argument() {
2093 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2094 assert_eq!(e.message, "-o requires an argument");
2095 }
2096
2097 #[test]
2098 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2099 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2100 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2101 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2102 }
2103
2104 #[test]
2105 fn the_include_flags_land_on_the_chain_each_one_names() {
2106 let (opts, _) = compile(&[
2109 "-Ii",
2110 "-iquote",
2111 "q",
2112 "-isystem",
2113 "sys",
2114 "-idirafter",
2115 "after",
2116 "--sysroot=/nowhere-at-all",
2117 "a.c",
2118 ]);
2119 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2120 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2123 assert!(!opts.search.dirs()[1].is_system);
2124 assert!(opts.search.dirs()[2].is_system);
2125 }
2126
2127 #[test]
2128 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2129 let (opts, _) = compile(&["a.c"]);
2133 let dirs = opts.search.dirs();
2134 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2135 assert_eq!(ours, Some(0), "{dirs:?}");
2136 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2137 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2138 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2139 }
2140
2141 #[test]
2142 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2143 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2144 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2145 assert_eq!(dirs, ["sys", runtime::DIR]);
2146 }
2147
2148 #[test]
2149 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2150 let (opts, _) =
2151 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2152 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2153 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2154 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2156 assert!(!opts.search.searches_current_dir());
2157 }
2158
2159 #[test]
2160 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2161 let (opts, _) = compile(&[
2162 "-iprefix",
2163 "/tools/",
2164 "-iwithprefix",
2165 "late",
2166 "-iwithprefixbefore",
2167 "early",
2168 "-iprefix",
2169 "/other/",
2170 "-iwithprefix",
2171 "last",
2172 "-nostdinc",
2173 "a.c",
2174 ]);
2175 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2176 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2179 assert!(!opts.search.dirs()[0].is_system);
2180 assert!(opts.search.dirs()[1].is_system);
2181 }
2182
2183 #[test]
2184 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2185 let (opts, _) =
2186 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2187 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2188 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2189 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2190 }
2191
2192 #[test]
2193 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2194 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2195 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2196 assert_eq!(dirs, ["i"]);
2197 }
2198
2199 #[test]
2200 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2201 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2202 assert_eq!(opts.std, Std::C11);
2203 assert!(opts.gnu_extensions);
2204
2205 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2206 assert_eq!(opts.std, Std::C99);
2207 assert!(!opts.gnu_extensions);
2208
2209 let (opts, _) = compile(&["-ansi", "a.c"]);
2210 assert_eq!(opts.std, Std::C89);
2211 assert!(!opts.gnu_extensions);
2212
2213 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2214 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2215 }
2216
2217 #[test]
2218 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2219 let (opts, _) = compile(&["-dM", "a.c"]);
2220 assert!(opts.dumps.macros);
2221
2222 let (opts, _) = compile(&["-dDM", "a.c"]);
2225 assert!(opts.dumps.macros);
2226 let (opts, _) = compile(&["-dD", "a.c"]);
2227 assert!(!opts.dumps.macros);
2228
2229 let (opts, _) = compile(&["a.c"]);
2230 assert!(!opts.dumps.any());
2231
2232 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2235 }
2236
2237 #[test]
2238 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2239 let (opts, _) = compile(&["a.c"]);
2240 assert_eq!(
2241 opts.gnuc,
2242 GnucVersion { major: 7, minor: 0, patch: 0 },
2243 "the lowest claim a modern glibc gives its own declarations to"
2244 );
2245
2246 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2247 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2248
2249 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2252 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2253
2254 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2255 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2256
2257 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2258 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2259
2260 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2261 assert!(e.message.contains("more than three"), "{}", e.message);
2262 }
2263
2264 #[test]
2265 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2266 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2267 assert!(opts.pedantic);
2268 assert_eq!(opts.std, Std::C17);
2269
2270 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2273 assert!(opts.pedantic);
2274
2275 let (opts, _) = compile(&["-std=c17", "a.c"]);
2276 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2277 }
2278
2279 #[test]
2280 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2281 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2282 assert!(!opts.line_markers);
2283 assert!(!opts.hosted);
2284 assert_eq!(opts.emit, EmitKind::Preprocessed);
2285 }
2286
2287 #[test]
2294 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2295 let (opts, _) = compile(&["-c", "a.c"]);
2296 assert!(opts.builtins, "a library name means the library function by default");
2297 assert!(opts.no_builtin.is_empty());
2298
2299 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2300 assert!(!opts.builtins);
2301
2302 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2303 assert!(opts.builtins, "the last mention decides");
2304
2305 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2306 assert!(opts.builtins, "one name is not the family");
2307 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2308 }
2309
2310 #[test]
2318 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2319 let (opts, _) = compile(&["-c", "a.c"]);
2320 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2321
2322 for (written, wanted) in [
2323 ("default", Visibility::Default),
2324 ("hidden", Visibility::Hidden),
2325 ("internal", Visibility::Hidden),
2326 ("protected", Visibility::Protected),
2327 ] {
2328 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2329 assert_eq!(opts.visibility, wanted, "{written}");
2330 }
2331
2332 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2335 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2336
2337 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2341 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2342 }
2343
2344 #[test]
2347 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2348 let (opts, _) = compile(&["-c", "a.c"]);
2349 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2350
2351 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2352 assert!(opts.gnu89_inline);
2353
2354 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2355 assert!(!opts.gnu89_inline, "the last mention decides");
2356
2357 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2362 assert!(!opts.gnu89_inline);
2363 }
2364
2365 #[test]
2368 fn the_two_frame_flags_are_read_in_both_directions() {
2369 let (opts, _) = compile(&["-c", "a.c"]);
2370 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2371 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2372
2373 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2374 assert!(opts.frame_pointer);
2375 assert!(!opts.red_zone);
2376
2377 let (opts, _) = compile(&[
2378 "-c",
2379 "-fno-omit-frame-pointer",
2380 "-fomit-frame-pointer",
2381 "-mno-red-zone",
2382 "-mred-zone",
2383 "a.c",
2384 ]);
2385 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2386 assert!(opts.red_zone);
2387 }
2388
2389 #[test]
2390 fn the_link_flags_are_collected_apart_from_the_compilation() {
2391 let (link, _) = linking(&[
2392 "-static",
2393 "-nostartfiles",
2394 "-rdynamic",
2395 "-s",
2396 "-fuse-ld=mold",
2397 "-L/opt/lib",
2398 "-B",
2399 "/opt/tools",
2400 "a.c",
2401 ]);
2402 assert!(link.is_static);
2403 assert!(link.no_startfiles);
2404 assert!(link.export_dynamic);
2405 assert!(link.strip);
2406 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2407 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2408 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2409 }
2410
2411 #[test]
2412 fn a_comma_in_dash_wl_separates_two_arguments() {
2413 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2414 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2415 }
2416
2417 #[test]
2418 fn a_library_keeps_its_place_between_the_objects() {
2419 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2424 let link = plan.link.expect("expected a link step");
2425 assert_eq!(
2426 link.inputs,
2427 vec![
2428 link::Item::File("a.o".into()),
2429 link::Item::Library("m".into()),
2430 link::Item::File("b.o".into()),
2431 ]
2432 );
2433 assert_eq!(plan.jobs.len(), 2);
2435 }
2436
2437 #[test]
2438 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2439 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2440 assert!(plan.link.is_none());
2441 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2442 }
2443
2444 #[test]
2445 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2446 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2447 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2448 }
2449
2450 fn printed(s: &[&str]) -> String {
2451 match parse_args(&args(s)).expect("expected an answer") {
2452 Action::Print(line) => line,
2453 other => panic!("expected an answer, got {other:?}"),
2454 }
2455 }
2456
2457 fn refused(s: &[&str]) -> String {
2458 parse_args(&args(s)).expect_err("expected a refusal").message
2459 }
2460
2461 #[test]
2462 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2463 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2467 assert!(!opts.warnings_are_errors);
2468 assert!(opts.warnings);
2469 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2471 assert!(opts.warnings_are_errors);
2472 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2473 assert!(!opts.warnings);
2474 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2475 assert!(opts.pedantic && opts.warnings_are_errors);
2476 }
2477
2478 #[test]
2479 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2480 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2482 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2483 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2484 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2485 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2486 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2487 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2490 assert!(no32.contains("32 bit target"), "{no32}");
2491 }
2492
2493 #[test]
2494 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2495 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2496 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2497 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2498 }
2499
2500 #[test]
2501 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2502 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2503 let (opts, _) =
2504 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2505 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2506 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2507 assert!(wrong.contains("sysv convention"), "{wrong}");
2508 }
2509
2510 #[test]
2511 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2512 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2513 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2514 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2517 assert_eq!(names, vec!["a.c"]);
2518 }
2519
2520 #[test]
2521 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2522 let target = "--target=x86_64-unknown-linux-gnu";
2523 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2524 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2525 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2526 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2527 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2530 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2531 let dirs = printed(&[target, "-print-search-dirs"]);
2532 assert!(dirs.starts_with("install: "), "{dirs}");
2533 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2534 }
2535
2536 #[test]
2537 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2538 let (opts, _) = compile(&["-M", "a.c"]);
2539 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2540 assert!(opts.deps.system_headers, "plain -M lists them");
2541 assert_eq!(opts.emit, EmitKind::Preprocessed);
2542
2543 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2546 assert_eq!(opts.emit, EmitKind::Preprocessed);
2547
2548 let (opts, _) = compile(&["-MM", "a.c"]);
2549 assert!(!opts.deps.system_headers);
2550 }
2551
2552 #[test]
2553 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2554 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2555 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2556 assert!(opts.deps.system_headers);
2557 assert_eq!(opts.emit, EmitKind::Object);
2558
2559 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2560 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2561 assert!(!opts.deps.system_headers);
2562 }
2563
2564 #[test]
2565 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2566 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2569 assert!(!opts.deps.system_headers);
2570 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2571 assert!(!opts.deps.system_headers);
2572 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2573 assert!(!opts.deps.system_headers);
2574 }
2575
2576 #[test]
2577 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2578 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2579 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2580 }
2581
2582 #[test]
2583 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2584 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2585 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2586 assert!(opts.deps.phony);
2587
2588 for flag in ["-MF", "-MT", "-MQ"] {
2589 let e = parse_args(&args(&[flag])).unwrap_err();
2590 assert!(e.message.contains("requires an argument"), "{}", e.message);
2591 }
2592 }
2593
2594 struct TempTree(PathBuf);
2596
2597 impl Drop for TempTree {
2598 fn drop(&mut self) {
2599 let _ = std::fs::remove_dir_all(&self.0);
2600 }
2601 }
2602
2603 impl TempTree {
2604 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2605 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2606 let _ = std::fs::remove_dir_all(&dir);
2607 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2608 for (path, text) in files {
2609 let at = dir.join(path);
2610 if let Some(parent) = at.parent() {
2611 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2612 }
2613 std::fs::write(&at, text).expect("writing a temporary file should work");
2614 }
2615 TempTree(dir)
2616 }
2617
2618 fn path(&self, name: &str) -> String {
2619 self.0.join(name).to_string_lossy().into_owned()
2620 }
2621 }
2622
2623 #[test]
2624 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2625 let tree = TempTree::new(
2629 "found",
2630 &[
2631 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2632 ("one.h", "#define X 0\n"),
2633 ("two.h", "#include \"one.h\"\n"),
2634 ],
2635 );
2636 let out = tree.path("dep.d");
2637 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2638 assert_eq!(code, 0);
2639
2640 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2641 let names: Vec<&str> = text.split_whitespace().collect();
2642 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2644 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2645 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2646 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2649 }
2650
2651 #[test]
2652 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2653 let tree = TempTree::new(
2656 "guarded",
2657 &[
2658 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2659 ("g.h", "#ifndef G\n#define G\n#endif\n"),
2660 ],
2661 );
2662 let out = tree.path("dep.d");
2663 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2664 assert_eq!(code, 0);
2665 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2666 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2667 }
2668
2669 #[test]
2670 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2671 let tree = TempTree::new(
2676 "preinclude",
2677 &[
2678 ("a.c", "int main(void) { return 0; }\n"),
2679 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2680 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2681 ],
2682 );
2683 let out = tree.path("a.i");
2684 let code = run(&args(&[
2685 "-E",
2686 "-include",
2687 &tree.path("i.h"),
2688 "-imacros",
2689 &tree.path("m.h"),
2690 "-o",
2691 &out,
2692 &tree.path("a.c"),
2693 ]));
2694 assert_eq!(code, 0);
2695 let text = std::fs::read_to_string(&out).expect("the output should have been written");
2696 assert!(text.contains("saw_it"), "{text}");
2697 assert!(!text.contains("macros_text"), "{text}");
2700 }
2701
2702 #[test]
2703 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
2704 let tree = TempTree::new(
2705 "preinclude-deps",
2706 &[
2707 ("a.c", "int main(void) { return 0; }\n"),
2708 ("i.h", "int from_include;\n"),
2709 ("m.h", "#define M 1\n"),
2710 ],
2711 );
2712 let out = tree.path("dep.d");
2713 let code = run(&args(&[
2714 "-MM",
2715 "-MF",
2716 &out,
2717 "-include",
2718 &tree.path("i.h"),
2719 "-imacros",
2720 &tree.path("m.h"),
2721 "-o",
2722 &tree.path("a.i"),
2723 &tree.path("a.c"),
2724 ]));
2725 assert_eq!(code, 0);
2726 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2727 assert!(text.contains("i.h"), "{text}");
2728 assert!(text.contains("m.h"), "{text}");
2729 }
2730
2731 #[test]
2732 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
2733 let tree = TempTree::new(
2737 "preinclude-missing",
2738 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
2739 );
2740 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
2741 assert_eq!(code, 1);
2742 }
2743
2744 #[test]
2745 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
2746 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
2750 assert_eq!(plan.output.as_deref(), Some("prog"));
2751 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
2752 assert_eq!(
2753 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
2754 Some("prog.d")
2755 );
2756 }
2757
2758 #[test]
2759 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
2760 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
2761 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
2762 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
2763 assert_eq!(plan.output, None);
2764 }
2765
2766 #[test]
2767 fn usage_fits_on_a_screen() {
2768 assert!(USAGE.lines().count() < 48, "usage text has grown past one screen");
2786 }
2787}