1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.7")]
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 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
175 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
176 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
177 -fPIC -fpic -fPIE -fpie, -fno-common, -f[no-]strict-aliasing, -pipe what it does anyway
178 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
179 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
180 -Werror -pedantic -pedantic-errors -w how much to say, and whether it is fatal
181 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
182 -pthread build for more than one thread, and link the library for it
183 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
184 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
185 -j[n] compile n translation units at once, default all
186 -v, -### print each phase as it runs, or without running any
187 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
188 --target=<triple> generate code for <triple>
189 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
190 safety-summary, type-granules
191 --print-config, --print-pipeline print the configuration or the pipeline, and exit
192 --version print the version and exit
193 -h, --help print this message and exit
194
195See spec/04-driver-and-cli.md for the full flag reference.
196";
197
198fn joined_or_next(
202 arg: &str,
203 at: usize,
204 args: &[String],
205 i: &mut usize,
206) -> Result<String, CliError> {
207 if arg.len() > at {
208 return Ok(arg[at..].to_owned());
209 }
210 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
211 *i += 1;
212 Ok(next.clone())
213}
214
215pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
222 let host = Triple::host()
223 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
224 let mut opts = Options::new(host);
225 let mut inputs: Vec<Input> = Vec::new();
226 let mut print_config = false;
227 let mut print_pipeline = false;
228 let mut print_plan = false;
229 let mut verbose = false;
230 let mut jobs = Jobs::default();
231 let mut nostdinc = false;
232 let mut sysroot: Option<PathBuf> = None;
233 let mut output = None;
234 let mut link = LinkOptions::default();
235 let mut query: Option<Query> = None;
236 let mut threads = false;
237 let mut forced: Option<InputKind> = None;
240 let mut iprefix = String::new();
247
248 let mut i = 0;
249 while i < args.len() {
250 let arg = args[i].as_str();
251 i += 1;
252 match arg {
253 "-h" | "--help" => return Ok(Action::Help),
254 "--version" => return Ok(Action::Version),
255 "--print-config" => print_config = true,
256 "--print-pipeline" => print_pipeline = true,
257 "-###" => print_plan = true,
258 "-v" => verbose = true,
259 "-save-temps" => opts.save_temps = SaveTemps::Object,
263 _ if arg.starts_with("-save-temps=") => {
264 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
265 }
266 "-time" => opts.time = true,
269 "-c" => opts.emit = EmitKind::Object,
270 "-S" => opts.emit = EmitKind::Asm,
271 "-E" => opts.emit = EmitKind::Preprocessed,
272 "-g" => opts.debug_info = true,
273 "-g0" => opts.debug_info = false,
278 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
279 opts.debug_info = true;
280 }
281 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
284 _ if arg.starts_with("-gdwarf-") => {
285 return Err(err(format!(
286 "{arg}: this compiler writes DWARF 5 and no other version, see \
287 spec/11-debug-info.md"
288 )));
289 }
290 "-Werror" => opts.warnings_are_errors = true,
291 "-w" => opts.warnings = false,
294 "-pedantic-errors" => {
295 opts.pedantic = true;
296 opts.warnings_are_errors = true;
297 }
298 "-P" => opts.line_markers = false,
299 "-M" => {
306 opts.deps.emit = true;
307 opts.deps.instead_of_compiling = true;
308 }
309 "-MM" => {
310 opts.deps.emit = true;
311 opts.deps.instead_of_compiling = true;
312 opts.deps.system_headers = false;
313 }
314 "-MD" => opts.deps.emit = true,
315 "-MMD" => {
316 opts.deps.emit = true;
317 opts.deps.system_headers = false;
318 }
319 "-MP" => opts.deps.phony = true,
320 "-MF" | "-MT" | "-MQ" => {
323 let value =
324 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
325 i += 1;
326 match arg {
327 "-MF" => opts.deps.file = Some(value.clone()),
328 "-MT" => opts.deps.targets.push(value.clone()),
332 _ => opts.deps.targets.push(deps::escaped(value)),
333 }
334 }
335 "-dumpmachine" => query = Some(Query::Machine),
339 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
340 "-print-multiarch" => query = Some(Query::Multiarch),
341 "-print-search-dirs" => query = Some(Query::SearchDirs),
342 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
343 _ if arg.starts_with("-print-file-name=") => {
344 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
345 }
346 _ if arg.starts_with("-print-prog-name=") => {
347 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
348 }
349 "-pthread" | "-pthreads" => {
354 opts.defines.push("_REENTRANT".to_owned());
355 threads = true;
356 }
357 "-ansi" => {
358 opts.std = Std::C89;
359 opts.gnu_extensions = false;
360 }
361 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
364 "-fpermissive" => opts.permissive = true,
367 "-fno-permissive" => opts.permissive = false,
368 "-ffreestanding" => opts.hosted = false,
369 "-fhosted" => opts.hosted = true,
370 "-fno-builtin" => opts.builtins = false,
371 "-fbuiltin" => opts.builtins = true,
372 "-fgnu89-inline" => opts.gnu89_inline = true,
376 "-fno-gnu89-inline" => opts.gnu89_inline = false,
377 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
380 "-fomit-frame-pointer" => opts.frame_pointer = false,
381 "-mno-red-zone" => opts.red_zone = false,
382 "-mred-zone" => opts.red_zone = true,
383 "-nostdinc" => nostdinc = true,
387 "-o" => {
388 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
389 i += 1;
390 }
391 "-isysroot" => {
398 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
399 i += 1;
400 sysroot = Some(PathBuf::from(dir));
401 }
402 "-iquote" | "-isystem" | "-idirafter" => {
403 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
404 i += 1;
405 match arg {
406 "-iquote" => opts.search.push_quote(dir.clone()),
407 "-isystem" => opts.search.push_system(dir.clone()),
408 _ => opts.search.push_after(dir.clone()),
409 }
410 }
411 "-iprefix" => {
412 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
413 i += 1;
414 }
415 "-iwithprefix" | "-iwithprefixbefore" => {
421 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
422 i += 1;
423 let dir = format!("{iprefix}{dir}");
424 if arg == "-iwithprefix" {
425 opts.search.push_system(dir);
426 } else {
427 opts.search.push_bracket(dir);
428 }
429 }
430 "-include" | "-imacros" => {
431 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
432 i += 1;
433 opts.preincludes
434 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
435 }
436 "-I-" => opts.search.split_quote_chain(),
441 "-x" => {
442 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
443 i += 1;
444 forced = if lang == "none" {
445 None
446 } else {
447 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
448 };
449 }
450 _ if arg.starts_with("-D") => {
458 let value = joined_or_next(arg, 2, args, &mut i)?;
459 opts.defines.push(value);
460 }
461 _ if arg.starts_with("-U") => {
462 let value = joined_or_next(arg, 2, args, &mut i)?;
463 opts.undefines.push(value);
464 }
465 _ if arg.starts_with("-I") => {
466 let dir = joined_or_next(arg, 2, args, &mut i)?;
467 opts.search.push_bracket(dir);
468 }
469 _ if arg.starts_with("-std=") => {
470 let name = &arg["-std=".len()..];
471 let (std, gnu) = Std::from_flag(name)
472 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
473 opts.std = std;
474 opts.gnu_extensions = gnu;
475 }
476 _ if Dumps::is_family(arg) => {
485 opts.dumps.add(&arg[2..]);
486 }
487 _ if arg.starts_with("-fno-builtin-") => {
492 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
493 }
494 _ if arg.starts_with("-fgnuc-version=") => {
495 let v = &arg["-fgnuc-version=".len()..];
496 opts.gnuc = v.parse().map_err(err)?;
497 }
498 "-fnested-functions" => {
503 return Err(err(
504 "nested functions are not supported: a call to one goes through a trampoline \
505 written on the stack, which no target that enforces an unexecutable stack \
506 allows",
507 ));
508 }
509 "-fno-nested-functions" => {}
510 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
521 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
525 "-fsemantic-interposition" => opts.interposition = true,
532 "-fno-semantic-interposition" => opts.interposition = false,
533 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
538 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
539 "-funwind-tables" => opts.unwind_tables = true,
540 "-fno-unwind-tables" => opts.unwind_tables = false,
541 "-fno-pic" | "-fno-pie" => {
548 return Err(err(
549 "position dependent code is not supported: an address that may be in another \
550 object is loaded out of the global offset table, and nothing here emits the \
551 absolute form this asks for. Use -no-pie if what you meant was how to link",
552 ));
553 }
554 "-ffunction-sections" => opts.function_sections = true,
560 "-fno-function-sections" => opts.function_sections = false,
561 "-fdata-sections" => opts.data_sections = true,
562 "-fno-data-sections" => opts.data_sections = false,
563 "-fno-common" => {}
569 "-fcommon" => {
573 return Err(err(
574 "a tentative definition is written into .bss as its own symbol here, and \
575 nothing emits the common symbol this asks the linker to merge. Give the \
576 variable a definition in one file and declare it extern in the others",
577 ));
578 }
579 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
593 "-pipe" => {}
596 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
603 _ if arg.starts_with("-fdiagnostics-color=") => {}
604 "-static" => link.is_static = true,
608 "-shared" => link.shared = true,
609 "-pie" => link.pie = Some(true),
610 "-no-pie" | "-nopie" => link.pie = Some(false),
611 "-nostdlib" => link.no_stdlib = true,
612 "-nostartfiles" => link.no_startfiles = true,
613 "-nodefaultlibs" => link.no_defaultlibs = true,
614 "-fno-builtins-lib" => link.no_builtins_lib = true,
615 "-fbuiltins-lib" => link.no_builtins_lib = false,
616 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
617 "-s" => link.strip = true,
618 "-Xlinker" => {
619 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
620 i += 1;
621 link.passthrough.push(next.clone());
622 }
623 _ if arg.starts_with("-Wl,") => {
624 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
627 }
628 _ if arg.starts_with("-fuse-ld=") => {
629 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
630 }
631 _ if arg.starts_with("-l") && arg.len() > 2 => {
632 inputs.push(Input::library(&arg[2..]));
633 }
634 "-l" => {
635 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
636 i += 1;
637 inputs.push(Input::library(next));
638 }
639 _ if arg.starts_with("-L") => {
640 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
641 }
642 _ if arg.starts_with("-B") => {
643 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
644 }
645 _ if arg.starts_with("-j") => {
646 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
647 }
648 _ if arg.starts_with("--sysroot=") => {
649 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
650 }
651 _ if arg.starts_with("--target=") => {
652 let t = &arg["--target=".len()..];
653 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
654 }
655 _ if arg.starts_with("--emit=") => {
656 let k = &arg["--emit=".len()..];
657 opts.emit = k
658 .parse()
659 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
660 }
661 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
667 "-Ofast" => {
673 return Err(err(
674 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
675 spec/04-driver-and-cli.md section 4.6",
676 ));
677 }
678 _ if arg.starts_with("-O") => {
679 opts.opt_level = arg[2..]
680 .parse()
681 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
682 }
683 _ if arg.starts_with("-fvisibility=") => {
687 let seen = &arg["-fvisibility=".len()..];
688 opts.visibility = seen.parse().map_err(|()| {
689 err(format!(
690 "`{seen}` is not a visibility, which is default, hidden, internal or \
691 protected"
692 ))
693 })?;
694 }
695 _ if arg.starts_with("-fsafety=") => {
700 let tier = &arg["-fsafety=".len()..];
701 opts.safety = tier.parse().map_err(|()| {
702 err(format!(
703 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
704 ))
705 })?;
706 }
707 _ if arg.starts_with("-fpass-fuel=") => {
711 let (name, count) = arg["-fpass-fuel=".len()..]
712 .split_once('=')
713 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
714 if rucc_opt::pass::find(name).is_none() {
715 return Err(err(format!(
716 "`{name}` is not a pass this compiler has, see --print-pipeline"
717 )));
718 }
719 let count: u32 = count
720 .parse()
721 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
722 opts.pass_fuel.push((name.to_owned(), count));
723 }
724 _ if arg.starts_with("-fpass-fuel-global=") => {
725 let count = &arg["-fpass-fuel-global=".len()..];
726 let count: u32 = count
727 .parse()
728 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
729 opts.pass_fuel_global = Some(count);
730 }
731 _ if arg == "-fopt-info"
736 || arg.starts_with("-fopt-info=")
737 || arg.starts_with("-fopt-info-") =>
738 {
739 let rest = &arg["-fopt-info".len()..];
740 let (kinds, file) = match rest.split_once('=') {
741 Some((kinds, file)) => (kinds, Some(file)),
742 None => (rest, None),
743 };
744 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
745 rucc_opt::Wants::none().add(kinds).map_err(err)?;
746 opts.opt_info.push(kinds.to_owned());
747 if let Some(file) = file {
748 if file.is_empty() {
749 return Err(err("-fopt-info= was given no file to write to"));
750 }
751 opts.opt_info_file = Some(file.to_owned());
752 }
753 }
754 _ if arg.starts_with("-fdump-ir=") => {
755 let spec = &arg["-fdump-ir=".len()..];
758 rucc_opt::Dumps::default().add(spec).map_err(err)?;
759 opts.dump_ir.push(spec.to_owned());
760 }
761 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
767 let on = arg.starts_with("-fenable-");
768 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
769 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
770 opts.pass_gates.push((on, spec.to_owned()));
771 }
772 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
773 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
774 }
775 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
776 opts.passes.push((arg["-f".len()..].to_owned(), true));
777 }
778 "-Zverify-each" => opts.verify_each = true,
784 _ if arg.starts_with("-Zrule-coverage=") => {
785 let file = &arg["-Zrule-coverage=".len()..];
786 if file.is_empty() {
787 return Err(err("-Zrule-coverage= needs a file to write to"));
788 }
789 opts.rule_coverage = Some(file.to_owned());
790 }
791 _ if arg.starts_with("-Z") => {
792 return Err(err(format!(
793 "`{arg}` is not an unstable option this compiler has, see \
794 spec/04-driver-and-cli.md section 4.11 for the ones it does"
795 )));
796 }
797 "-m64" | "-m32" | "-mx32" => {
802 let want: u32 = match arg {
803 "-m64" => 64,
804 _ => 32,
805 };
806 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
807 if have != want {
808 return Err(err(format!(
809 "{arg} asks for a {want} bit target and {} is {have} bit, use \
810 --target= to name the one you mean",
811 opts.target
812 )));
813 }
814 }
815 _ if arg.starts_with("-march=")
821 || arg.starts_with("-mtune=")
822 || arg.starts_with("-mcpu=") => {}
823 _ if arg.starts_with("-mabi=") => {
826 let want = &arg["-mabi=".len()..];
827 let have = match opts.target.arch {
828 rucc_target::Arch::X86_64 => "sysv",
829 rucc_target::Arch::Aarch64 => "lp64",
830 rucc_target::Arch::Riscv64 => "lp64d",
831 };
832 if want != have {
833 return Err(err(format!(
834 "{arg}: {} uses the {have} convention and this compiler has no other",
835 opts.target
836 )));
837 }
838 }
839 "-mcmodel=small" => {}
843 _ if arg.starts_with("-mcmodel=") => {
844 return Err(err(format!(
845 "{arg}: this compiler emits the small code model and no other, see \
846 spec/12-targets.md"
847 )));
848 }
849 _ if arg.starts_with("-specs=") => {
853 return Err(err(
854 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
855 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
856 section 4.4",
857 ));
858 }
859 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
865 return Err(err(format!(
866 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
867 are inside this compiler rather than programs it runs"
868 )));
869 }
870 "-Xassembler" | "-Xpreprocessor" => {
871 return Err(err(format!(
872 "{arg} hands an argument to a separate assembler or preprocessor, and both \
873 are inside this compiler rather than programs it runs"
874 )));
875 }
876 _ if arg.starts_with("-W") => {}
883 "-fno-ident"
889 | "-fident"
890 | "-funit-at-a-time"
891 | "-fno-unit-at-a-time"
892 | "-shared-libgcc"
893 | "-static-libgcc" => {}
894 _ if arg.starts_with('-') && arg.len() > 1 => {
895 return Err(err(format!("unknown option `{arg}`")));
900 }
901 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
902 }
903 }
904
905 link.sysroot = sysroot.clone();
912 if threads {
917 inputs.push(Input::library("pthread"));
918 }
919 if let Some(query) = query {
920 return Ok(Action::Print(answer(&query, &opts, &link)));
921 }
922 if opts.deps.instead_of_compiling {
928 opts.emit = EmitKind::Preprocessed;
929 }
930 if !nostdinc {
931 opts.search.push_system(runtime::DIR);
932 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
936 opts.search.push_system(dir);
937 }
938 }
939 opts.search.remove_duplicates();
943
944 if print_config {
947 return Ok(Action::PrintConfig(Box::new(opts)));
948 }
949 if print_pipeline {
950 return Ok(Action::PrintPipeline(Box::new(opts)));
951 }
952 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
953 if print_plan {
954 return Ok(Action::PrintPlan {
955 opts: Box::new(opts),
956 plan: Box::new(plan),
957 link: Box::new(link),
958 });
959 }
960 Ok(Action::Compile {
961 opts: Box::new(opts),
962 plan: Box::new(plan),
963 link: Box::new(link),
964 jobs,
965 verbose,
966 })
967}
968
969fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
975 let found = |name: &str| {
976 link::find_in_search(link, opts.target, name)
977 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
978 };
979 match query {
980 Query::Machine => opts.target.to_string(),
981 Query::Version => VERSION.to_owned(),
982 Query::Multiarch => link::multiarch(opts.target),
983 Query::SearchDirs => {
988 let here = std::env::current_exe()
989 .ok()
990 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
991 .unwrap_or_default();
992 let list = |dirs: &[PathBuf]| {
993 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
994 };
995 let libraries = link::search_dirs(link, opts.target);
996 format!(
997 "install: {}\nprograms: ={}\nlibraries: ={}",
998 here.display(),
999 list(&link.prefixes),
1000 list(&libraries)
1001 )
1002 }
1003 Query::FileName(name) => found(name),
1004 Query::Libgcc => found("libgcc.a"),
1008 Query::ProgName(name) => link
1012 .prefixes
1013 .iter()
1014 .map(|dir| dir.join(name))
1015 .find(|path| path.is_file())
1016 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1017 }
1018}
1019
1020#[must_use]
1026pub fn print_pipeline(opts: &Options) -> String {
1027 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1028 settings.toggles.clone_from(&opts.passes);
1029 settings.global_fuel = opts.pass_fuel_global;
1030 for (on, spec) in &opts.pass_gates {
1031 let _ = settings.gates.add(*on, spec);
1034 }
1035 rucc_opt::pipeline::print(&settings)
1036}
1037
1038#[must_use]
1043pub fn print_config(opts: &Options) -> String {
1044 let sess = Session::new(opts.clone());
1045 let t = &sess.target;
1046 let mut out = String::new();
1047 let _ = writeln!(out, "version: {VERSION}");
1048 let _ = writeln!(out, "target: {}", opts.target);
1052 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1053 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1054 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1055 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1056 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1057 let _ = writeln!(out, "long-width: {}", t.long_width);
1058 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1059 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1060 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1061 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1062 let regs: Vec<String> = t
1065 .regs
1066 .classes()
1067 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1068 .collect();
1069 let _ = writeln!(
1070 out,
1071 "registers: {}",
1072 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1073 );
1074 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1075 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1076 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1077 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1078 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1079 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1080 for dir in sess.opts.search.dirs() {
1083 let system = if dir.is_system { " (system)" } else { "" };
1084 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1085 }
1086 out
1087}
1088
1089fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1097 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1098}
1099
1100fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1103 if path == "-" {
1104 return write_out(&Output::Stdout, bytes);
1105 }
1106 write_out(&Output::File(path.to_owned()), bytes)
1107}
1108
1109fn write_deps(
1115 opts: &Options,
1116 plan: &Plan,
1117 job: &Job,
1118 found: &[Dependency],
1119 stderr: &mut impl std::io::Write,
1120) -> bool {
1121 let targets = if opts.deps.targets.is_empty() {
1122 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1123 } else {
1124 opts.deps.targets.clone()
1125 };
1126 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1127 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1130 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1134 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1135 }),
1136 None => write_out(&job.output, rule.as_bytes()),
1137 };
1138 if let Err(e) = wrote {
1139 let _ = writeln!(stderr, "rucc: error: {e}");
1140 return false;
1141 }
1142 true
1143}
1144
1145fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1151 let fs = OsFileSystem::new();
1152 let mut stderr = std::io::stderr().lock();
1153 let mut failed = false;
1154 for job in &plan.jobs {
1155 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1156 continue;
1159 }
1160 let started = std::time::Instant::now();
1161 let result = preprocess(opts, &job.input, &fs);
1162 if opts.time {
1163 say_time(&job.input, started.elapsed(), &mut stderr);
1164 }
1165 for message in &result.messages {
1166 let _ = writeln!(stderr, "{message}");
1167 }
1168 if result.failed() {
1169 failed = true;
1170 continue;
1171 }
1172 if opts.deps.emit {
1173 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1174 if opts.deps.instead_of_compiling {
1177 continue;
1178 }
1179 }
1180 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1181 let _ = writeln!(stderr, "rucc: error: {e}");
1182 failed = true;
1183 }
1184 }
1185 i32::from(failed)
1186}
1187
1188fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1194 let fs = OsFileSystem::new();
1195 let mut stderr = std::io::stderr().lock();
1196 let mut failed = false;
1197 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1198 failed |= !ok;
1199 let mut fired = Fired::new();
1200 for job in &plan.jobs {
1201 if !job.phases.contains(&Phase::Compile) {
1202 continue;
1203 }
1204 let started = std::time::Instant::now();
1208 let result = if job.kind == InputKind::Ir {
1209 compile_ir(opts, &job.input, &fs)
1210 } else {
1211 compile(opts, &job.input, &fs)
1212 };
1213 if opts.time {
1214 say_time(&job.input, started.elapsed(), &mut stderr);
1215 }
1216 fired.merge(&result.fired);
1217 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1218 failed |= !remarks.write(&result.remarks, &mut stderr);
1219 for message in &result.messages {
1220 let _ = writeln!(stderr, "{message}");
1221 }
1222 failed |= !write_temps(job, &result.temps, &mut stderr);
1225 if result.failed() {
1226 failed = true;
1227 continue;
1228 }
1229 if opts.deps.emit {
1234 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1235 }
1236 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1237 let _ = writeln!(stderr, "rucc: error: {e}");
1238 failed = true;
1239 }
1240 }
1241 failed |= !write_coverage(opts, &fired, &mut stderr);
1242 i32::from(failed)
1243}
1244
1245struct Scratch {
1252 dir: PathBuf,
1254}
1255
1256impl Scratch {
1257 fn new() -> Result<Scratch, String> {
1263 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1264 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1265 Ok(Scratch { dir })
1266 }
1267}
1268
1269impl Drop for Scratch {
1270 fn drop(&mut self) {
1271 let _ = std::fs::remove_dir_all(&self.dir);
1272 }
1273}
1274
1275fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1282 let linker = link::find(opts.target, link)?;
1283 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1284 Ok(link::render(&linker, &args))
1285}
1286
1287fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1294 let Some(job) = &plan.link else {
1295 let mut stderr = std::io::stderr().lock();
1298 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1299 return 1;
1300 };
1301 let linker = match link::find(opts.target, link) {
1304 Ok(linker) => linker,
1305 Err(why) => return complain(why),
1306 };
1307
1308 let scratch = match Scratch::new() {
1309 Ok(scratch) => scratch,
1310 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1311 };
1312
1313 let fs = OsFileSystem::new();
1314 let mut failed = false;
1315 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1318 let mut fired = Fired::new();
1319 {
1320 let mut stderr = std::io::stderr().lock();
1321 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1322 failed |= !ok;
1323 for (at, job) in plan.jobs.iter().enumerate() {
1324 let out = match &job.output {
1325 Output::Temporary(hint) => {
1326 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1329 }
1330 Output::File(path) => path.clone(),
1331 Output::Stdout => continue,
1334 };
1335 produced.push(out.clone());
1336 if !job.phases.contains(&Phase::Compile) {
1337 continue;
1338 }
1339 let started = std::time::Instant::now();
1340 let result = if job.kind == InputKind::Ir {
1341 compile_ir(opts, &job.input, &fs)
1342 } else {
1343 compile(opts, &job.input, &fs)
1344 };
1345 if opts.time {
1346 say_time(&job.input, started.elapsed(), &mut stderr);
1347 }
1348 fired.merge(&result.fired);
1349 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1350 failed |= !remarks.write(&result.remarks, &mut stderr);
1351 for message in &result.messages {
1352 let _ = writeln!(stderr, "{message}");
1353 }
1354 failed |= !write_temps(job, &result.temps, &mut stderr);
1355 if result.failed() {
1356 failed = true;
1357 continue;
1358 }
1359 if opts.deps.emit {
1364 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1365 }
1366 if !matches!(result.artifact, Artifact::Object(_)) {
1367 let _ = writeln!(
1372 stderr,
1373 "rucc: internal error: {}: no object file was produced for the link",
1374 job.input
1375 );
1376 failed = true;
1377 continue;
1378 }
1379 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1380 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1381 failed = true;
1382 }
1383 }
1384 failed |= !write_coverage(opts, &fired, &mut stderr);
1385 }
1386 if failed {
1387 return 1;
1391 }
1392
1393 let mut outputs = produced.into_iter();
1397 let mut items = Vec::with_capacity(job.inputs.len());
1398 for item in &job.inputs {
1399 match item {
1400 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1401 link::Item::File(_) => match outputs.next() {
1402 Some(path) => items.push(link::Item::File(path)),
1403 None => return complain("the plan asks the linker for a file nothing produced"),
1404 },
1405 }
1406 }
1407
1408 let args = match link::line(opts.target, link, &items, &job.output) {
1409 Ok(args) => args,
1410 Err(why) => return complain(why),
1411 };
1412 if verbose {
1413 let mut stderr = std::io::stderr().lock();
1414 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1415 }
1416 let started = std::time::Instant::now();
1417 let ran = link::run(&linker, &args);
1418 if opts.time {
1419 let mut stderr = std::io::stderr().lock();
1422 say_time(&linker.name, started.elapsed(), &mut stderr);
1423 }
1424 match ran {
1425 Ok(()) => 0,
1426 Err(link::Error::Refused { .. }) => 1,
1429 Err(why) => complain(why),
1430 }
1431}
1432
1433fn complain(why: impl std::fmt::Display) -> i32 {
1435 let mut stderr = std::io::stderr().lock();
1436 let _ = writeln!(stderr, "rucc: error: {why}");
1437 1
1438}
1439
1440fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1449 let Some(path) = &opts.rule_coverage else { return true };
1450 let Some(table) = coverage::table(opts.target.arch) else {
1451 let _ = writeln!(
1452 stderr,
1453 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1454 to report",
1455 opts.target
1456 );
1457 return false;
1458 };
1459 match std::fs::write(path, fired.listing(table)) {
1460 Ok(()) => true,
1461 Err(e) => {
1462 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1463 false
1464 }
1465 }
1466}
1467
1468struct Remarks {
1475 file: Option<String>,
1477 started: bool,
1480}
1481
1482impl Remarks {
1483 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1489 let mut ok = true;
1490 if let Some(path) = file {
1491 if let Err(e) = std::fs::write(path, "") {
1492 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1493 ok = false;
1494 }
1495 }
1496 (Self { file: file.cloned(), started: false }, ok)
1497 }
1498
1499 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1505 if text.is_empty() {
1506 return true;
1507 }
1508 let Some(path) = &self.file else {
1509 let _ = write!(stderr, "{text}");
1510 return true;
1511 };
1512 let opened = std::fs::OpenOptions::new()
1513 .write(true)
1514 .append(self.started)
1515 .truncate(!self.started)
1516 .create(true)
1517 .open(path);
1518 self.started = true;
1519 let result =
1520 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1521 if let Err(e) = result {
1522 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1523 return false;
1524 }
1525 true
1526 }
1527}
1528
1529fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1540 let stem = std::path::Path::new(input)
1541 .file_name()
1542 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1543 let mut ok = true;
1544 for dump in dumps {
1545 let path = format!("{stem}.{}.ir", dump.name);
1546 if let Err(e) = std::fs::write(&path, &dump.text) {
1547 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1548 ok = false;
1549 }
1550 }
1551 ok
1552}
1553
1554fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1560 let mut ok = true;
1561 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1562 for (path, text) in kept {
1563 let (Some(path), Some(text)) = (path, text) else { continue };
1566 if let Err(e) = std::fs::write(&path, text) {
1567 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1568 ok = false;
1569 }
1570 }
1571 ok
1572}
1573
1574fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1581 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1582}
1583
1584fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1591 match output {
1592 Output::Stdout => {
1593 let mut stdout = std::io::stdout().lock();
1594 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1595 }
1596 Output::File(path) | Output::Temporary(path) => {
1597 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1598 }
1599 }
1600}
1601
1602pub fn run(args: &[String]) -> i32 {
1607 match parse_args(args) {
1608 Ok(Action::Help) => {
1609 print!("{USAGE}");
1610 0
1611 }
1612 Ok(Action::Version) => {
1613 println!("rucc {VERSION}");
1614 0
1615 }
1616 Ok(Action::Print(line)) => {
1617 println!("{line}");
1618 0
1619 }
1620 Ok(Action::PrintConfig(opts)) => {
1621 print!("{}", print_config(&opts));
1622 0
1623 }
1624 Ok(Action::PrintPipeline(opts)) => {
1625 print!("{}", print_pipeline(&opts));
1626 0
1627 }
1628 Ok(Action::PrintPlan { opts, plan, link }) => {
1629 print!("{}", plan.render());
1630 if let Some(job) = &plan.link {
1634 match link_line(&opts, &link, job) {
1635 Ok(line) => println!("{line}"),
1636 Err(why) => {
1637 let mut stderr = std::io::stderr().lock();
1638 let _ = writeln!(stderr, "rucc: error: {why}");
1639 return 1;
1640 }
1641 }
1642 }
1643 0
1644 }
1645 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1646 {
1647 let mut stderr = std::io::stderr().lock();
1648 if verbose {
1649 let _ = write!(stderr, "{}", plan.render());
1650 let _ = writeln!(stderr, "workers: {}", jobs.count());
1651 }
1652 }
1653 if opts.emit == EmitKind::Preprocessed {
1654 return preprocess_all(&opts, &plan);
1655 }
1656 if opts.emit != EmitKind::Executable {
1657 return compile_all(&opts, &plan);
1658 }
1659 link_all(&opts, &plan, &link, verbose)
1660 }
1661 Err(e) => {
1662 let mut stderr = std::io::stderr().lock();
1663 let _ = writeln!(stderr, "rucc: error: {e}");
1664 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1665 1
1666 }
1667 }
1668}
1669
1670#[cfg(test)]
1671mod tests {
1672 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1673
1674 use super::*;
1675
1676 fn args(s: &[&str]) -> Vec<String> {
1677 s.iter().map(|x| (*x).to_owned()).collect()
1678 }
1679
1680 #[test]
1681 fn help_and_version_win_over_everything_else() {
1682 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1683 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1684 }
1685
1686 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1687 match parse_args(&args(s)).expect("expected a compilation") {
1688 Action::Compile { opts, plan, .. } => (opts, plan),
1689 other => panic!("expected a compilation, got {other:?}"),
1690 }
1691 }
1692
1693 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1694 match parse_args(&args(s)).expect("expected a compilation") {
1695 Action::Compile { link, plan, .. } => (link, plan),
1696 other => panic!("expected a compilation, got {other:?}"),
1697 }
1698 }
1699
1700 #[test]
1701 fn collects_inputs_and_flags() {
1702 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1703 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1704 assert_eq!(paths, vec!["a.c", "b.c"]);
1705 assert_eq!(opts.opt_level, OptLevel::O2);
1706 assert_eq!(opts.emit, EmitKind::Object);
1707 assert!(opts.debug_info);
1708 }
1709
1710 #[test]
1713 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1714 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1715 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1716
1717 let (plain, _) = compile(&["-c", "a.c"]);
1718 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1719
1720 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1721 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1722 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1723 }
1724
1725 #[test]
1726 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1727 let (opts, _) = compile(&["-O", "a.c"]);
1728 assert_eq!(opts.opt_level, OptLevel::O1);
1729 }
1730
1731 #[test]
1732 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1733 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1734 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1735 assert_eq!(plan.jobs[1].kind, InputKind::C);
1736 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1737 }
1738
1739 #[test]
1740 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1741 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1742 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1743 other => panic!("expected a compilation, got {other:?}"),
1744 };
1745 assert_eq!(jobs.count(), 4);
1746
1747 let default = match parse_args(&args(&["a.c"])).unwrap() {
1748 Action::Compile { jobs, .. } => jobs,
1749 other => panic!("expected a compilation, got {other:?}"),
1750 };
1751 assert_eq!(default, Jobs::available());
1752 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1753 }
1754
1755 #[test]
1756 fn triple_hash_prints_the_plan_and_runs_nothing() {
1757 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1758 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1759 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1760 }
1761
1762 #[test]
1763 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1764 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1768 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1769 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1770 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1771 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1775 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1776 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1777 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1778 }
1779
1780 #[test]
1781 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1782 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1783 let (plain, without) = compile(&["-c", "a.c"]);
1784 assert!(opts.time);
1785 assert!(!plain.time);
1786 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1789 }
1790
1791 #[test]
1792 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1793 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1794 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1795 }
1796
1797 #[test]
1798 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1799 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1800 assert!(e.message.contains("unknown option"), "{}", e.message);
1801 }
1802
1803 #[test]
1806 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1807 let (opts, _) = compile(&["-c", "a.c"]);
1808 assert!(!opts.permissive, "off unless it is asked for");
1809
1810 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1811 assert!(opts.permissive);
1812
1813 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1814 assert!(!opts.permissive);
1815 }
1816
1817 #[test]
1818 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1819 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1820 assert!(e.message.contains("trampoline"), "{}", e.message);
1821 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1822 }
1823
1824 #[test]
1825 fn the_flag_every_configure_script_writes_is_taken() {
1826 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1829 let (opts, _) = compile(&["-c", flag, "a.c"]);
1830 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1831 }
1832 }
1833
1834 #[test]
1835 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1836 let (opts, _) = compile(&["-c", "a.c"]);
1837 assert!(opts.unwinds(), "the default is off");
1838 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1839 assert!(!opts.unwinds(), "the build was not taken at its word");
1840 let (opts, _) = compile(&[
1841 "-c",
1842 "-fno-asynchronous-unwind-tables",
1843 "-fasynchronous-unwind-tables",
1844 "a.c",
1845 ]);
1846 assert!(opts.unwinds(), "the last flag did not win");
1847 let (opts, _) =
1851 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1852 assert!(opts.unwinds(), "the weaker request was dropped");
1853 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
1854 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
1855 let (opts, _) =
1856 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
1857 assert!(!opts.unwinds(), "both were turned off and one stayed on");
1858 }
1859
1860 #[test]
1861 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1862 for flag in [
1866 "-fno-common",
1867 "-fstrict-aliasing",
1868 "-fno-strict-aliasing",
1869 "-pipe",
1870 "-fdiagnostics-color",
1871 "-fno-diagnostics-color",
1872 "-fdiagnostics-color=always",
1873 "-fdiagnostics-color=never",
1874 "-fdiagnostics-color=auto",
1875 ] {
1876 let (opts, _) = compile(&["-c", flag, "a.c"]);
1877 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1878 }
1879 }
1880
1881 #[test]
1882 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1883 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1886 assert!(e.message.contains(".bss"), "{}", e.message);
1887 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1888 }
1889
1890 #[test]
1891 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1892 for flag in ["-fno-pic", "-fno-pie"] {
1893 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1894 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1895 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1898 }
1899 }
1900
1901 #[test]
1902 fn an_unsupported_target_names_itself() {
1903 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1904 assert!(e.message.contains("sparc64"), "{}", e.message);
1905 }
1906
1907 #[test]
1908 fn no_inputs_is_an_error_but_print_config_needs_none() {
1909 assert!(parse_args(&args(&[])).is_err());
1910 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1911 }
1912
1913 #[test]
1914 fn print_config_reports_the_target_it_was_given_not_the_host() {
1915 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1916 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1917 let text = print_config(&opts);
1918 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1919 assert!(text.contains("char-signed: false"), "{text}");
1920 assert!(text.contains("object-format: elf"), "{text}");
1921 assert!(text.contains("va-list: void-pointer"), "{text}");
1922 assert!(text.contains("registers: none"), "{text}");
1925 }
1926
1927 #[test]
1928 fn print_config_has_one_key_per_line_and_a_fixed_order() {
1929 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1930 let text = print_config(&opts);
1931 let keys: Vec<&str> =
1932 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1933 assert_eq!(keys[0], "version");
1934 assert_eq!(keys[1], "target");
1935 assert_eq!(keys.len(), 19);
1936 assert!(text.ends_with('\n'));
1937 }
1938
1939 #[test]
1940 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
1941 let (opts, _) = compile(&["a.c"]);
1942 assert_eq!(opts.safety, rucc_session::Safety::Off);
1943
1944 for (flag, tier) in [
1945 ("-fsafety=detect", rucc_session::Safety::Detect),
1946 ("-fsafety=enforce", rucc_session::Safety::Enforce),
1947 ("-fsafety=kernel", rucc_session::Safety::Kernel),
1948 ("-fsafety=off", rucc_session::Safety::Off),
1949 ] {
1950 let (opts, _) = compile(&[flag, "a.c"]);
1951 assert_eq!(opts.safety, tier, "{flag}");
1952 }
1953
1954 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
1956 assert_eq!(opts.safety, rucc_session::Safety::Off);
1957
1958 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
1961 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
1962 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
1963 }
1964
1965 #[test]
1966 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
1967 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
1968 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1969 let text = print_pipeline(&opts);
1970 assert!(text.starts_with("level: -O2\n"), "{text}");
1971 assert!(text.contains("fold"), "{text}");
1972
1973 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
1974 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1975 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
1978
1979 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
1980 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1981 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
1984 }
1985
1986 #[test]
1987 fn print_pipeline_takes_the_toggles_into_account() {
1988 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
1989 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
1990 let text = print_pipeline(&opts);
1991 assert!(!text.contains("fold"), "{text}");
1994 assert!(text.contains("dce"), "{text}");
1995
1996 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
2000 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
2001 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
2002 let a = parse_args(&args(&spelled)).unwrap();
2003 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2004 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2005 }
2006
2007 #[test]
2008 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
2009 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2010 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2011 assert!(!print_pipeline(&opts).contains("global fuel"));
2012
2013 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2014 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2015 let text = print_pipeline(&opts);
2016 assert!(text.contains("global fuel: 4"), "{text}");
2019 }
2020
2021 #[test]
2024 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2025 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2026 assert_eq!(
2027 opts.passes,
2028 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2029 );
2030
2031 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2032 assert!(e.message.contains("unknown option"), "{}", e.message);
2033 }
2034
2035 #[test]
2036 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2037 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2038 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2039
2040 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2041 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2042 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2043 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2044 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2045 assert!(e.message.contains("not a number"), "{}", e.message);
2046 }
2047
2048 #[test]
2049 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2050 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2051 assert_eq!(opts.pass_fuel_global, None);
2052
2053 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2054 assert_eq!(opts.pass_fuel_global, Some(12));
2055 assert!(opts.pass_fuel.is_empty());
2058
2059 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2060 assert!(e.message.contains("not a number"), "{}", e.message);
2061 }
2062
2063 #[test]
2064 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2065 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2066 assert_eq!(
2067 opts.pass_gates,
2068 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2069 "the order is what decides, so it has to survive the parse"
2070 );
2071
2072 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2073 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2074 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2075 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2076 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2077 assert!(e.message.contains("is empty"), "{}", e.message);
2078 }
2079
2080 #[test]
2081 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2082 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2083 let text = print_pipeline(&opts);
2084 assert!(text.contains("fold, "), "{text}");
2085 assert!(text.contains("[off for main]"), "{text}");
2086 }
2087
2088 #[test]
2092 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2093 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2094 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2095
2096 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2097 assert!(e.message.contains("nosuch"), "{}", e.message);
2098 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2099 }
2100
2101 #[test]
2107 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2108 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2109 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2110 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2111
2112 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2113 assert_eq!(opts.opt_info, ["missed-note"]);
2114
2115 let (opts, _) =
2118 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2119 assert_eq!(opts.opt_info, ["missed", "all"]);
2120 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2121
2122 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2123 assert!(e.message.contains("vectorized"), "{}", e.message);
2124 assert!(e.message.contains("`missed`"), "{}", e.message);
2125 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2126 assert!(e.message.contains("no file"), "{}", e.message);
2127 }
2128
2129 #[test]
2130 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2131 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2132 assert!(opts.verify_each);
2133 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2134 }
2135
2136 #[test]
2137 fn dash_o_needs_an_argument() {
2138 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2139 assert_eq!(e.message, "-o requires an argument");
2140 }
2141
2142 #[test]
2143 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2144 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2145 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2146 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2147 }
2148
2149 #[test]
2150 fn the_include_flags_land_on_the_chain_each_one_names() {
2151 let (opts, _) = compile(&[
2154 "-Ii",
2155 "-iquote",
2156 "q",
2157 "-isystem",
2158 "sys",
2159 "-idirafter",
2160 "after",
2161 "--sysroot=/nowhere-at-all",
2162 "a.c",
2163 ]);
2164 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2165 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2168 assert!(!opts.search.dirs()[1].is_system);
2169 assert!(opts.search.dirs()[2].is_system);
2170 }
2171
2172 #[test]
2173 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2174 let (opts, _) = compile(&["a.c"]);
2178 let dirs = opts.search.dirs();
2179 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2180 assert_eq!(ours, Some(0), "{dirs:?}");
2181 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2182 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2183 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2184 }
2185
2186 #[test]
2187 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2188 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2189 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2190 assert_eq!(dirs, ["sys", runtime::DIR]);
2191 }
2192
2193 #[test]
2194 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2195 let (opts, _) =
2196 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2197 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2198 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2199 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2201 assert!(!opts.search.searches_current_dir());
2202 }
2203
2204 #[test]
2205 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2206 let (opts, _) = compile(&[
2207 "-iprefix",
2208 "/tools/",
2209 "-iwithprefix",
2210 "late",
2211 "-iwithprefixbefore",
2212 "early",
2213 "-iprefix",
2214 "/other/",
2215 "-iwithprefix",
2216 "last",
2217 "-nostdinc",
2218 "a.c",
2219 ]);
2220 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2221 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2224 assert!(!opts.search.dirs()[0].is_system);
2225 assert!(opts.search.dirs()[1].is_system);
2226 }
2227
2228 #[test]
2229 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2230 let (opts, _) =
2231 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2232 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2233 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2234 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2235 }
2236
2237 #[test]
2238 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2239 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2240 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2241 assert_eq!(dirs, ["i"]);
2242 }
2243
2244 #[test]
2245 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2246 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2247 assert_eq!(opts.std, Std::C11);
2248 assert!(opts.gnu_extensions);
2249
2250 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2251 assert_eq!(opts.std, Std::C99);
2252 assert!(!opts.gnu_extensions);
2253
2254 let (opts, _) = compile(&["-ansi", "a.c"]);
2255 assert_eq!(opts.std, Std::C89);
2256 assert!(!opts.gnu_extensions);
2257
2258 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2259 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2260 }
2261
2262 #[test]
2263 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2264 let (opts, _) = compile(&["-dM", "a.c"]);
2265 assert!(opts.dumps.macros);
2266
2267 let (opts, _) = compile(&["-dDM", "a.c"]);
2270 assert!(opts.dumps.macros);
2271 let (opts, _) = compile(&["-dD", "a.c"]);
2272 assert!(!opts.dumps.macros);
2273
2274 let (opts, _) = compile(&["a.c"]);
2275 assert!(!opts.dumps.any());
2276
2277 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2280 }
2281
2282 #[test]
2283 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2284 let (opts, _) = compile(&["a.c"]);
2285 assert_eq!(
2286 opts.gnuc,
2287 GnucVersion { major: 7, minor: 0, patch: 0 },
2288 "the lowest claim a modern glibc gives its own declarations to"
2289 );
2290
2291 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2292 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2293
2294 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2297 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2298
2299 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2300 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2301
2302 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2303 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2304
2305 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2306 assert!(e.message.contains("more than three"), "{}", e.message);
2307 }
2308
2309 #[test]
2310 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2311 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2312 assert!(opts.pedantic);
2313 assert_eq!(opts.std, Std::C17);
2314
2315 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2318 assert!(opts.pedantic);
2319
2320 let (opts, _) = compile(&["-std=c17", "a.c"]);
2321 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2322 }
2323
2324 #[test]
2325 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2326 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2327 assert!(!opts.line_markers);
2328 assert!(!opts.hosted);
2329 assert_eq!(opts.emit, EmitKind::Preprocessed);
2330 }
2331
2332 #[test]
2339 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2340 let (opts, _) = compile(&["-c", "a.c"]);
2341 assert!(opts.builtins, "a library name means the library function by default");
2342 assert!(opts.no_builtin.is_empty());
2343
2344 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2345 assert!(!opts.builtins);
2346
2347 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2348 assert!(opts.builtins, "the last mention decides");
2349
2350 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2351 assert!(opts.builtins, "one name is not the family");
2352 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2353 }
2354
2355 #[test]
2363 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2364 let (opts, _) = compile(&["-c", "a.c"]);
2365 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2366
2367 for (written, wanted) in [
2368 ("default", Visibility::Default),
2369 ("hidden", Visibility::Hidden),
2370 ("internal", Visibility::Hidden),
2371 ("protected", Visibility::Protected),
2372 ] {
2373 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2374 assert_eq!(opts.visibility, wanted, "{written}");
2375 }
2376
2377 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2380 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2381
2382 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2386 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2387 }
2388
2389 #[test]
2397 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
2398 let (opts, _) = compile(&["-c", "a.c"]);
2399 assert!(!opts.function_sections, "one text section unless something says otherwise");
2400 assert!(!opts.data_sections);
2401
2402 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
2403 assert!(opts.function_sections);
2404 assert!(!opts.data_sections, "one flag is not the other");
2405
2406 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
2407 assert!(opts.data_sections);
2408 assert!(!opts.function_sections);
2409
2410 let (opts, _) = compile(&[
2413 "-c",
2414 "-ffunction-sections",
2415 "-fno-function-sections",
2416 "-fdata-sections",
2417 "-fno-data-sections",
2418 "a.c",
2419 ]);
2420 assert!(!opts.function_sections, "the last mention decides");
2421 assert!(!opts.data_sections, "the last mention decides");
2422 }
2423
2424 #[test]
2427 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2428 let (opts, _) = compile(&["-c", "a.c"]);
2429 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2430
2431 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2432 assert!(opts.gnu89_inline);
2433
2434 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2435 assert!(!opts.gnu89_inline, "the last mention decides");
2436
2437 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2442 assert!(!opts.gnu89_inline);
2443 }
2444
2445 #[test]
2448 fn the_two_frame_flags_are_read_in_both_directions() {
2449 let (opts, _) = compile(&["-c", "a.c"]);
2450 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2451 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2452
2453 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2454 assert!(opts.frame_pointer);
2455 assert!(!opts.red_zone);
2456
2457 let (opts, _) = compile(&[
2458 "-c",
2459 "-fno-omit-frame-pointer",
2460 "-fomit-frame-pointer",
2461 "-mno-red-zone",
2462 "-mred-zone",
2463 "a.c",
2464 ]);
2465 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2466 assert!(opts.red_zone);
2467 }
2468
2469 #[test]
2470 fn the_link_flags_are_collected_apart_from_the_compilation() {
2471 let (link, _) = linking(&[
2472 "-static",
2473 "-nostartfiles",
2474 "-rdynamic",
2475 "-s",
2476 "-fuse-ld=mold",
2477 "-L/opt/lib",
2478 "-B",
2479 "/opt/tools",
2480 "a.c",
2481 ]);
2482 assert!(link.is_static);
2483 assert!(link.no_startfiles);
2484 assert!(link.export_dynamic);
2485 assert!(link.strip);
2486 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2487 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2488 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2489 }
2490
2491 #[test]
2492 fn a_comma_in_dash_wl_separates_two_arguments() {
2493 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2494 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2495 }
2496
2497 #[test]
2498 fn a_library_keeps_its_place_between_the_objects() {
2499 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2504 let link = plan.link.expect("expected a link step");
2505 assert_eq!(
2506 link.inputs,
2507 vec![
2508 link::Item::File("a.o".into()),
2509 link::Item::Library("m".into()),
2510 link::Item::File("b.o".into()),
2511 ]
2512 );
2513 assert_eq!(plan.jobs.len(), 2);
2515 }
2516
2517 #[test]
2518 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2519 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2520 assert!(plan.link.is_none());
2521 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2522 }
2523
2524 #[test]
2525 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2526 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2527 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2528 }
2529
2530 fn printed(s: &[&str]) -> String {
2531 match parse_args(&args(s)).expect("expected an answer") {
2532 Action::Print(line) => line,
2533 other => panic!("expected an answer, got {other:?}"),
2534 }
2535 }
2536
2537 fn refused(s: &[&str]) -> String {
2538 parse_args(&args(s)).expect_err("expected a refusal").message
2539 }
2540
2541 #[test]
2542 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2543 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2547 assert!(!opts.warnings_are_errors);
2548 assert!(opts.warnings);
2549 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2551 assert!(opts.warnings_are_errors);
2552 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2553 assert!(!opts.warnings);
2554 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2555 assert!(opts.pedantic && opts.warnings_are_errors);
2556 }
2557
2558 #[test]
2559 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2560 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2562 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2563 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2564 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2565 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2566 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2567 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2570 assert!(no32.contains("32 bit target"), "{no32}");
2571 }
2572
2573 #[test]
2574 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2575 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2576 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2577 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2578 }
2579
2580 #[test]
2581 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2582 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2583 let (opts, _) =
2584 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2585 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2586 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2587 assert!(wrong.contains("sysv convention"), "{wrong}");
2588 }
2589
2590 #[test]
2591 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2592 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2593 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2594 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2597 assert_eq!(names, vec!["a.c"]);
2598 }
2599
2600 #[test]
2601 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2602 let target = "--target=x86_64-unknown-linux-gnu";
2603 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2604 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2605 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2606 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2607 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2610 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2611 let dirs = printed(&[target, "-print-search-dirs"]);
2612 assert!(dirs.starts_with("install: "), "{dirs}");
2613 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2614 }
2615
2616 #[test]
2617 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2618 let (opts, _) = compile(&["-M", "a.c"]);
2619 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2620 assert!(opts.deps.system_headers, "plain -M lists them");
2621 assert_eq!(opts.emit, EmitKind::Preprocessed);
2622
2623 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2626 assert_eq!(opts.emit, EmitKind::Preprocessed);
2627
2628 let (opts, _) = compile(&["-MM", "a.c"]);
2629 assert!(!opts.deps.system_headers);
2630 }
2631
2632 #[test]
2633 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2634 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2635 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2636 assert!(opts.deps.system_headers);
2637 assert_eq!(opts.emit, EmitKind::Object);
2638
2639 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2640 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2641 assert!(!opts.deps.system_headers);
2642 }
2643
2644 #[test]
2645 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2646 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2649 assert!(!opts.deps.system_headers);
2650 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2651 assert!(!opts.deps.system_headers);
2652 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2653 assert!(!opts.deps.system_headers);
2654 }
2655
2656 #[test]
2657 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2658 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2659 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2660 }
2661
2662 #[test]
2663 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2664 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2665 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2666 assert!(opts.deps.phony);
2667
2668 for flag in ["-MF", "-MT", "-MQ"] {
2669 let e = parse_args(&args(&[flag])).unwrap_err();
2670 assert!(e.message.contains("requires an argument"), "{}", e.message);
2671 }
2672 }
2673
2674 struct TempTree(PathBuf);
2676
2677 impl Drop for TempTree {
2678 fn drop(&mut self) {
2679 let _ = std::fs::remove_dir_all(&self.0);
2680 }
2681 }
2682
2683 impl TempTree {
2684 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2685 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2686 let _ = std::fs::remove_dir_all(&dir);
2687 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2688 for (path, text) in files {
2689 let at = dir.join(path);
2690 if let Some(parent) = at.parent() {
2691 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2692 }
2693 std::fs::write(&at, text).expect("writing a temporary file should work");
2694 }
2695 TempTree(dir)
2696 }
2697
2698 fn path(&self, name: &str) -> String {
2699 self.0.join(name).to_string_lossy().into_owned()
2700 }
2701 }
2702
2703 #[test]
2704 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2705 let tree = TempTree::new(
2709 "found",
2710 &[
2711 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2712 ("one.h", "#define X 0\n"),
2713 ("two.h", "#include \"one.h\"\n"),
2714 ],
2715 );
2716 let out = tree.path("dep.d");
2717 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2718 assert_eq!(code, 0);
2719
2720 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2721 let names: Vec<&str> = text.split_whitespace().collect();
2722 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2724 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2725 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2726 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2729 }
2730
2731 #[test]
2732 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2733 let tree = TempTree::new(
2736 "guarded",
2737 &[
2738 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2739 ("g.h", "#ifndef G\n#define G\n#endif\n"),
2740 ],
2741 );
2742 let out = tree.path("dep.d");
2743 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2744 assert_eq!(code, 0);
2745 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2746 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2747 }
2748
2749 #[test]
2750 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2751 let tree = TempTree::new(
2756 "preinclude",
2757 &[
2758 ("a.c", "int main(void) { return 0; }\n"),
2759 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2760 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2761 ],
2762 );
2763 let out = tree.path("a.i");
2764 let code = run(&args(&[
2765 "-E",
2766 "-include",
2767 &tree.path("i.h"),
2768 "-imacros",
2769 &tree.path("m.h"),
2770 "-o",
2771 &out,
2772 &tree.path("a.c"),
2773 ]));
2774 assert_eq!(code, 0);
2775 let text = std::fs::read_to_string(&out).expect("the output should have been written");
2776 assert!(text.contains("saw_it"), "{text}");
2777 assert!(!text.contains("macros_text"), "{text}");
2780 }
2781
2782 #[test]
2783 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
2784 let tree = TempTree::new(
2785 "preinclude-deps",
2786 &[
2787 ("a.c", "int main(void) { return 0; }\n"),
2788 ("i.h", "int from_include;\n"),
2789 ("m.h", "#define M 1\n"),
2790 ],
2791 );
2792 let out = tree.path("dep.d");
2793 let code = run(&args(&[
2794 "-MM",
2795 "-MF",
2796 &out,
2797 "-include",
2798 &tree.path("i.h"),
2799 "-imacros",
2800 &tree.path("m.h"),
2801 "-o",
2802 &tree.path("a.i"),
2803 &tree.path("a.c"),
2804 ]));
2805 assert_eq!(code, 0);
2806 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2807 assert!(text.contains("i.h"), "{text}");
2808 assert!(text.contains("m.h"), "{text}");
2809 }
2810
2811 #[test]
2812 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
2813 let tree = TempTree::new(
2817 "preinclude-missing",
2818 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
2819 );
2820 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
2821 assert_eq!(code, 1);
2822 }
2823
2824 #[test]
2825 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
2826 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
2830 assert_eq!(plan.output.as_deref(), Some("prog"));
2831 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
2832 assert_eq!(
2833 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
2834 Some("prog.d")
2835 );
2836 }
2837
2838 #[test]
2839 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
2840 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
2841 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
2842 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
2843 assert_eq!(plan.output, None);
2844 }
2845
2846 #[test]
2847 fn usage_fits_on_a_screen() {
2848 assert!(USAGE.lines().count() < 50, "usage text has grown past one screen");
2869 }
2870}