1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.13")]
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_codegen::pressure::Pressure;
46use rucc_pp::Dependency;
47use rucc_session::{
48 Control, Dumps, EmitKind, Options, Pic, Preinclude, Protector, SaveTemps, Session, Std, runtime,
49};
50use rucc_target::Triple;
51
52use crate::link::LinkOptions;
53
54pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
55pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
56pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
57pub use crate::schedule::Jobs;
58
59pub const VERSION: &str = env!("CARGO_PKG_VERSION");
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Action {
65 Help,
67 Version,
69 Print(String),
75 PrintConfig(Box<Options>),
77 PrintPipeline(Box<Options>),
79 PrintPlan {
81 opts: Box<Options>,
83 plan: Box<Plan>,
85 link: Box<LinkOptions>,
87 },
88 Compile {
90 opts: Box<Options>,
92 plan: Box<Plan>,
94 link: Box<LinkOptions>,
96 jobs: Jobs,
98 verbose: bool,
100 },
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct CliError {
106 pub message: String,
109}
110
111impl std::fmt::Display for CliError {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 f.write_str(&self.message)
114 }
115}
116
117impl std::error::Error for CliError {}
118
119fn err(message: impl Into<String>) -> CliError {
120 CliError { message: message.into() }
121}
122
123enum Query {
129 Machine,
131 Version,
133 Multiarch,
135 SearchDirs,
137 FileName(String),
139 ProgName(String),
141 Libgcc,
143}
144
145pub const USAGE: &str = "\
150rucc, an optimizing C compiler
151
152usage: rucc [options] file...
153
154options:
155 -c compile and assemble, do not link
156 -S compile only, emit assembly
157 -E preprocess only
158 -o <file> write output to <file>, or to standard output for -
159 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
160 -I <dir> add <dir> to the include search path
161 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
162 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
163 -include <file>, -imacros <file> read <file> first, the second for its macros only
164 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
165 -P, -dM with -E: leave out the markers, or dump the macros
166 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
167 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
168 -std=<dialect> c89 through c23, and the gnu spellings
169 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
170 -x <lang> treat later inputs as <lang>, or none to stop
171 -O<level> optimize: 0, 1, 2, 3, s, z
172 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
173 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
174 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
175 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
176 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
177 -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
178 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
179 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
180 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
181 -fPIC -fpic -fPIE -fpie, -fno-common, -f[no-]strict-aliasing, -pipe what it does anyway
182 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
183 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
184 -Werror -pedantic -pedantic-errors -w how much to say, and whether it is fatal
185 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
186 -pthread build for more than one thread, and link the library for it
187 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
188 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
189 -j[n] compile n translation units at once, default all
190 -v, -### print each phase as it runs, or without running any
191 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
192 --target=<triple> generate code for <triple>
193 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
194 safety-summary, type-granules
195 --print-config, --print-pipeline print the configuration or the pipeline, and exit
196 --version print the version and exit
197 -h, --help print this message and exit
198
199See spec/04-driver-and-cli.md for the full flag reference.
200";
201
202fn joined_or_next(
206 arg: &str,
207 at: usize,
208 args: &[String],
209 i: &mut usize,
210) -> Result<String, CliError> {
211 if arg.len() > at {
212 return Ok(arg[at..].to_owned());
213 }
214 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
215 *i += 1;
216 Ok(next.clone())
217}
218
219pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
226 let host = Triple::host()
227 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
228 let mut opts = Options::new(host);
229 let mut inputs: Vec<Input> = Vec::new();
230 let mut print_config = false;
231 let mut print_pipeline = false;
232 let mut print_plan = false;
233 let mut verbose = false;
234 let mut jobs = Jobs::default();
235 let mut nostdinc = false;
236 let mut sysroot: Option<PathBuf> = None;
237 let mut output = None;
238 let mut link = LinkOptions::default();
239 let mut query: Option<Query> = None;
240 let mut threads = false;
241 let mut forced: Option<InputKind> = None;
244 let mut iprefix = String::new();
251
252 let mut i = 0;
253 while i < args.len() {
254 let arg = args[i].as_str();
255 i += 1;
256 match arg {
257 "-h" | "--help" => return Ok(Action::Help),
258 "--version" => return Ok(Action::Version),
259 "--print-config" => print_config = true,
260 "--print-pipeline" => print_pipeline = true,
261 "-###" => print_plan = true,
262 "-v" => verbose = true,
263 "-save-temps" => opts.save_temps = SaveTemps::Object,
267 _ if arg.starts_with("-save-temps=") => {
268 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
269 }
270 "-time" => opts.time = true,
273 "-c" => opts.emit = EmitKind::Object,
274 "-S" => opts.emit = EmitKind::Asm,
275 "-E" => opts.emit = EmitKind::Preprocessed,
276 "-g" => opts.debug_info = true,
277 "-g0" => opts.debug_info = false,
282 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
283 opts.debug_info = true;
284 }
285 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
288 _ if arg.starts_with("-gdwarf-") => {
289 return Err(err(format!(
290 "{arg}: this compiler writes DWARF 5 and no other version, see \
291 spec/11-debug-info.md"
292 )));
293 }
294 "-Werror" => opts.warnings_are_errors = true,
295 "-w" => opts.warnings = false,
298 "-pedantic-errors" => {
299 opts.pedantic = true;
300 opts.warnings_are_errors = true;
301 }
302 "-P" => opts.line_markers = false,
303 "-M" => {
310 opts.deps.emit = true;
311 opts.deps.instead_of_compiling = true;
312 }
313 "-MM" => {
314 opts.deps.emit = true;
315 opts.deps.instead_of_compiling = true;
316 opts.deps.system_headers = false;
317 }
318 "-MD" => opts.deps.emit = true,
319 "-MMD" => {
320 opts.deps.emit = true;
321 opts.deps.system_headers = false;
322 }
323 "-MP" => opts.deps.phony = true,
324 "-MF" | "-MT" | "-MQ" => {
327 let value =
328 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
329 i += 1;
330 match arg {
331 "-MF" => opts.deps.file = Some(value.clone()),
332 "-MT" => opts.deps.targets.push(value.clone()),
336 _ => opts.deps.targets.push(deps::escaped(value)),
337 }
338 }
339 "-dumpmachine" => query = Some(Query::Machine),
343 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
344 "-print-multiarch" => query = Some(Query::Multiarch),
345 "-print-search-dirs" => query = Some(Query::SearchDirs),
346 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
347 _ if arg.starts_with("-print-file-name=") => {
348 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
349 }
350 _ if arg.starts_with("-print-prog-name=") => {
351 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
352 }
353 "-pthread" | "-pthreads" => {
358 opts.defines.push("_REENTRANT".to_owned());
359 threads = true;
360 }
361 "-ansi" => {
362 opts.std = Std::C89;
363 opts.gnu_extensions = false;
364 }
365 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
368 "-fpermissive" => opts.permissive = true,
371 "-fno-permissive" => opts.permissive = false,
372 "-ffreestanding" => opts.hosted = false,
373 "-fhosted" => opts.hosted = true,
374 "-fno-builtin" => opts.builtins = false,
375 "-fbuiltin" => opts.builtins = true,
376 "-fgnu89-inline" => opts.gnu89_inline = true,
380 "-fno-gnu89-inline" => opts.gnu89_inline = false,
381 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
384 "-fomit-frame-pointer" => opts.frame_pointer = false,
385 "-mno-red-zone" => opts.red_zone = false,
386 "-mred-zone" => opts.red_zone = true,
387 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
392 opts.protector = Protector::None;
393 }
394 "-fstack-protector" => opts.protector = Protector::Buffers,
395 "-fstack-protector-strong" => opts.protector = Protector::Strong,
396 "-fstack-protector-all" => opts.protector = Protector::All,
397 "-fstack-clash-protection" => opts.stack_clash = true,
400 "-fno-stack-clash-protection" => opts.stack_clash = false,
401 "-fcf-protection" => opts.control = Control::Full,
405 "-fno-cf-protection" => opts.control = Control::None,
406 "-nostdinc" => nostdinc = true,
410 "-o" => {
411 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
412 i += 1;
413 }
414 "-isysroot" => {
421 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
422 i += 1;
423 sysroot = Some(PathBuf::from(dir));
424 }
425 "-iquote" | "-isystem" | "-idirafter" => {
426 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
427 i += 1;
428 match arg {
429 "-iquote" => opts.search.push_quote(dir.clone()),
430 "-isystem" => opts.search.push_system(dir.clone()),
431 _ => opts.search.push_after(dir.clone()),
432 }
433 }
434 "-iprefix" => {
435 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
436 i += 1;
437 }
438 "-iwithprefix" | "-iwithprefixbefore" => {
444 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
445 i += 1;
446 let dir = format!("{iprefix}{dir}");
447 if arg == "-iwithprefix" {
448 opts.search.push_system(dir);
449 } else {
450 opts.search.push_bracket(dir);
451 }
452 }
453 "-include" | "-imacros" => {
454 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
455 i += 1;
456 opts.preincludes
457 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
458 }
459 "-I-" => opts.search.split_quote_chain(),
464 "-x" => {
465 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
466 i += 1;
467 forced = if lang == "none" {
468 None
469 } else {
470 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
471 };
472 }
473 _ if arg.starts_with("-D") => {
481 let value = joined_or_next(arg, 2, args, &mut i)?;
482 opts.defines.push(value);
483 }
484 _ if arg.starts_with("-U") => {
485 let value = joined_or_next(arg, 2, args, &mut i)?;
486 opts.undefines.push(value);
487 }
488 _ if arg.starts_with("-I") => {
489 let dir = joined_or_next(arg, 2, args, &mut i)?;
490 opts.search.push_bracket(dir);
491 }
492 _ if arg.starts_with("-std=") => {
493 let name = &arg["-std=".len()..];
494 let (std, gnu) = Std::from_flag(name)
495 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
496 opts.std = std;
497 opts.gnu_extensions = gnu;
498 }
499 _ if Dumps::is_family(arg) => {
508 opts.dumps.add(&arg[2..]);
509 }
510 _ if arg.starts_with("-fno-builtin-") => {
515 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
516 }
517 _ if arg.starts_with("-fgnuc-version=") => {
518 let v = &arg["-fgnuc-version=".len()..];
519 opts.gnuc = v.parse().map_err(err)?;
520 }
521 "-fnested-functions" => {
526 return Err(err(
527 "nested functions are not supported: a call to one goes through a trampoline \
528 written on the stack, which no target that enforces an unexecutable stack \
529 allows",
530 ));
531 }
532 "-fno-nested-functions" => {}
533 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
544 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
548 "-fsemantic-interposition" => opts.interposition = true,
555 "-fno-semantic-interposition" => opts.interposition = false,
556 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
561 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
562 "-funwind-tables" => opts.unwind_tables = true,
563 "-fno-unwind-tables" => opts.unwind_tables = false,
564 "-fno-pic" | "-fno-pie" => {
571 return Err(err(
572 "position dependent code is not supported: an address that may be in another \
573 object is loaded out of the global offset table, and nothing here emits the \
574 absolute form this asks for. Use -no-pie if what you meant was how to link",
575 ));
576 }
577 "-ffunction-sections" => opts.function_sections = true,
583 "-fno-function-sections" => opts.function_sections = false,
584 "-fdata-sections" => opts.data_sections = true,
585 "-fno-data-sections" => opts.data_sections = false,
586 "-fno-common" => {}
592 "-fcommon" => {
596 return Err(err(
597 "a tentative definition is written into .bss as its own symbol here, and \
598 nothing emits the common symbol this asks the linker to merge. Give the \
599 variable a definition in one file and declare it extern in the others",
600 ));
601 }
602 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
616 "-pipe" => {}
619 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
626 _ if arg.starts_with("-fdiagnostics-color=") => {}
627 "-static" => link.is_static = true,
631 "-shared" => link.shared = true,
632 "-pie" => link.pie = Some(true),
633 "-no-pie" | "-nopie" => link.pie = Some(false),
634 "-nostdlib" => link.no_stdlib = true,
635 "-nostartfiles" => link.no_startfiles = true,
636 "-nodefaultlibs" => link.no_defaultlibs = true,
637 "-fno-builtins-lib" => link.no_builtins_lib = true,
638 "-fbuiltins-lib" => link.no_builtins_lib = false,
639 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
640 "-s" => link.strip = true,
641 "-Xlinker" => {
642 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
643 i += 1;
644 link.passthrough.push(next.clone());
645 }
646 _ if arg.starts_with("-Wl,") => {
647 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
650 }
651 _ if arg.starts_with("-fuse-ld=") => {
652 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
653 }
654 _ if arg.starts_with("-l") && arg.len() > 2 => {
655 inputs.push(Input::library(&arg[2..]));
656 }
657 "-l" => {
658 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
659 i += 1;
660 inputs.push(Input::library(next));
661 }
662 _ if arg.starts_with("-L") => {
663 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
664 }
665 _ if arg.starts_with("-B") => {
666 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
667 }
668 _ if arg.starts_with("-j") => {
669 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
670 }
671 _ if arg.starts_with("--sysroot=") => {
672 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
673 }
674 _ if arg.starts_with("--target=") => {
675 let t = &arg["--target=".len()..];
676 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
677 }
678 _ if arg.starts_with("--emit=") => {
679 let k = &arg["--emit=".len()..];
680 opts.emit = k
681 .parse()
682 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
683 }
684 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
690 "-Ofast" => {
696 return Err(err(
697 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
698 spec/04-driver-and-cli.md section 4.6",
699 ));
700 }
701 _ if arg.starts_with("-O") => {
702 opts.opt_level = arg[2..]
703 .parse()
704 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
705 }
706 _ if arg.starts_with("-fvisibility=") => {
710 let seen = &arg["-fvisibility=".len()..];
711 opts.visibility = seen.parse().map_err(|()| {
712 err(format!(
713 "`{seen}` is not a visibility, which is default, hidden, internal or \
714 protected"
715 ))
716 })?;
717 }
718 _ if arg.starts_with("-fcf-protection=") => {
722 let edges = &arg["-fcf-protection=".len()..];
723 opts.control = edges.parse().map_err(|()| {
724 err(format!(
725 "`{edges}` is not a control flow protection, which is full, branch, \
726 return, none or check"
727 ))
728 })?;
729 }
730 _ if arg.starts_with("-fsafety=") => {
735 let tier = &arg["-fsafety=".len()..];
736 opts.safety = tier.parse().map_err(|()| {
737 err(format!(
738 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
739 ))
740 })?;
741 }
742 _ if arg.starts_with("-fpass-fuel=") => {
746 let (name, count) = arg["-fpass-fuel=".len()..]
747 .split_once('=')
748 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
749 if rucc_opt::pass::find(name).is_none() {
750 return Err(err(format!(
751 "`{name}` is not a pass this compiler has, see --print-pipeline"
752 )));
753 }
754 let count: u32 = count
755 .parse()
756 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
757 opts.pass_fuel.push((name.to_owned(), count));
758 }
759 _ if arg.starts_with("-fpass-fuel-global=") => {
760 let count = &arg["-fpass-fuel-global=".len()..];
761 let count: u32 = count
762 .parse()
763 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
764 opts.pass_fuel_global = Some(count);
765 }
766 _ if arg == "-fopt-info"
771 || arg.starts_with("-fopt-info=")
772 || arg.starts_with("-fopt-info-") =>
773 {
774 let rest = &arg["-fopt-info".len()..];
775 let (kinds, file) = match rest.split_once('=') {
776 Some((kinds, file)) => (kinds, Some(file)),
777 None => (rest, None),
778 };
779 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
780 rucc_opt::Wants::none().add(kinds).map_err(err)?;
781 opts.opt_info.push(kinds.to_owned());
782 if let Some(file) = file {
783 if file.is_empty() {
784 return Err(err("-fopt-info= was given no file to write to"));
785 }
786 opts.opt_info_file = Some(file.to_owned());
787 }
788 }
789 _ if arg.starts_with("-fdump-ir=") => {
790 let spec = &arg["-fdump-ir=".len()..];
793 rucc_opt::Dumps::default().add(spec).map_err(err)?;
794 opts.dump_ir.push(spec.to_owned());
795 }
796 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
802 let on = arg.starts_with("-fenable-");
803 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
804 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
805 opts.pass_gates.push((on, spec.to_owned()));
806 }
807 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
808 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
809 }
810 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
811 opts.passes.push((arg["-f".len()..].to_owned(), true));
812 }
813 "-Zverify-each" => opts.verify_each = true,
819 _ if arg.starts_with("-Zrule-coverage=") => {
820 let file = &arg["-Zrule-coverage=".len()..];
821 if file.is_empty() {
822 return Err(err("-Zrule-coverage= needs a file to write to"));
823 }
824 opts.rule_coverage = Some(file.to_owned());
825 }
826 _ if arg.starts_with("-Zregister-pressure=") => {
827 let file = &arg["-Zregister-pressure=".len()..];
828 if file.is_empty() {
829 return Err(err("-Zregister-pressure= needs a file to write to"));
830 }
831 opts.register_pressure = Some(file.to_owned());
832 }
833 _ if arg.starts_with("-Z") => {
834 return Err(err(format!(
835 "`{arg}` is not an unstable option this compiler has, see \
836 spec/04-driver-and-cli.md section 4.11 for the ones it does"
837 )));
838 }
839 "-m64" | "-m32" | "-mx32" => {
844 let want: u32 = match arg {
845 "-m64" => 64,
846 _ => 32,
847 };
848 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
849 if have != want {
850 return Err(err(format!(
851 "{arg} asks for a {want} bit target and {} is {have} bit, use \
852 --target= to name the one you mean",
853 opts.target
854 )));
855 }
856 }
857 _ if arg.starts_with("-march=")
863 || arg.starts_with("-mtune=")
864 || arg.starts_with("-mcpu=") => {}
865 _ if arg.starts_with("-mabi=") => {
868 let want = &arg["-mabi=".len()..];
869 let have = match opts.target.arch {
870 rucc_target::Arch::X86_64 => "sysv",
871 rucc_target::Arch::Aarch64 => "lp64",
872 rucc_target::Arch::Riscv64 => "lp64d",
873 };
874 if want != have {
875 return Err(err(format!(
876 "{arg}: {} uses the {have} convention and this compiler has no other",
877 opts.target
878 )));
879 }
880 }
881 "-mcmodel=small" => {}
885 _ if arg.starts_with("-mcmodel=") => {
886 return Err(err(format!(
887 "{arg}: this compiler emits the small code model and no other, see \
888 spec/12-targets.md"
889 )));
890 }
891 _ if arg.starts_with("-specs=") => {
895 return Err(err(
896 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
897 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
898 section 4.4",
899 ));
900 }
901 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
907 return Err(err(format!(
908 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
909 are inside this compiler rather than programs it runs"
910 )));
911 }
912 "-Xassembler" | "-Xpreprocessor" => {
913 return Err(err(format!(
914 "{arg} hands an argument to a separate assembler or preprocessor, and both \
915 are inside this compiler rather than programs it runs"
916 )));
917 }
918 _ if arg.starts_with("-W") => {}
925 "-fno-ident"
931 | "-fident"
932 | "-funit-at-a-time"
933 | "-fno-unit-at-a-time"
934 | "-shared-libgcc"
935 | "-static-libgcc" => {}
936 _ if arg.starts_with('-') && arg.len() > 1 => {
937 return Err(err(format!("unknown option `{arg}`")));
942 }
943 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
944 }
945 }
946
947 link.sysroot = sysroot.clone();
954 if threads {
959 inputs.push(Input::library("pthread"));
960 }
961 if let Some(query) = query {
962 return Ok(Action::Print(answer(&query, &opts, &link)));
963 }
964 if opts.deps.instead_of_compiling {
970 opts.emit = EmitKind::Preprocessed;
971 }
972 if !nostdinc {
973 opts.search.push_system(runtime::DIR);
974 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
978 opts.search.push_system(dir);
979 }
980 }
981 opts.search.remove_duplicates();
985
986 if print_config {
989 return Ok(Action::PrintConfig(Box::new(opts)));
990 }
991 if print_pipeline {
992 return Ok(Action::PrintPipeline(Box::new(opts)));
993 }
994 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
995 if print_plan {
996 return Ok(Action::PrintPlan {
997 opts: Box::new(opts),
998 plan: Box::new(plan),
999 link: Box::new(link),
1000 });
1001 }
1002 Ok(Action::Compile {
1003 opts: Box::new(opts),
1004 plan: Box::new(plan),
1005 link: Box::new(link),
1006 jobs,
1007 verbose,
1008 })
1009}
1010
1011fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
1017 let found = |name: &str| {
1018 link::find_in_search(link, opts.target, name)
1019 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
1020 };
1021 match query {
1022 Query::Machine => opts.target.to_string(),
1023 Query::Version => VERSION.to_owned(),
1024 Query::Multiarch => link::multiarch(opts.target),
1025 Query::SearchDirs => {
1030 let here = std::env::current_exe()
1031 .ok()
1032 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
1033 .unwrap_or_default();
1034 let list = |dirs: &[PathBuf]| {
1035 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
1036 };
1037 let libraries = link::search_dirs(link, opts.target);
1038 format!(
1039 "install: {}\nprograms: ={}\nlibraries: ={}",
1040 here.display(),
1041 list(&link.prefixes),
1042 list(&libraries)
1043 )
1044 }
1045 Query::FileName(name) => found(name),
1046 Query::Libgcc => found("libgcc.a"),
1050 Query::ProgName(name) => link
1054 .prefixes
1055 .iter()
1056 .map(|dir| dir.join(name))
1057 .find(|path| path.is_file())
1058 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1059 }
1060}
1061
1062#[must_use]
1068pub fn print_pipeline(opts: &Options) -> String {
1069 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1070 settings.toggles.clone_from(&opts.passes);
1071 settings.global_fuel = opts.pass_fuel_global;
1072 for (on, spec) in &opts.pass_gates {
1073 let _ = settings.gates.add(*on, spec);
1076 }
1077 rucc_opt::pipeline::print(&settings)
1078}
1079
1080#[must_use]
1085pub fn print_config(opts: &Options) -> String {
1086 let sess = Session::new(opts.clone());
1087 let t = &sess.target;
1088 let mut out = String::new();
1089 let _ = writeln!(out, "version: {VERSION}");
1090 let _ = writeln!(out, "target: {}", opts.target);
1094 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1095 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1096 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1097 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1098 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1099 let _ = writeln!(out, "long-width: {}", t.long_width);
1100 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1101 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1102 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1103 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1104 let regs: Vec<String> = t
1107 .regs
1108 .classes()
1109 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1110 .collect();
1111 let _ = writeln!(
1112 out,
1113 "registers: {}",
1114 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1115 );
1116 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1117 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1118 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1119 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1120 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1121 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1122 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
1123 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
1124 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
1125 for dir in sess.opts.search.dirs() {
1128 let system = if dir.is_system { " (system)" } else { "" };
1129 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1130 }
1131 out
1132}
1133
1134fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1142 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1143}
1144
1145fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1148 if path == "-" {
1149 return write_out(&Output::Stdout, bytes);
1150 }
1151 write_out(&Output::File(path.to_owned()), bytes)
1152}
1153
1154fn write_deps(
1160 opts: &Options,
1161 plan: &Plan,
1162 job: &Job,
1163 found: &[Dependency],
1164 stderr: &mut impl std::io::Write,
1165) -> bool {
1166 let targets = if opts.deps.targets.is_empty() {
1167 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1168 } else {
1169 opts.deps.targets.clone()
1170 };
1171 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1172 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1175 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1179 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1180 }),
1181 None => write_out(&job.output, rule.as_bytes()),
1182 };
1183 if let Err(e) = wrote {
1184 let _ = writeln!(stderr, "rucc: error: {e}");
1185 return false;
1186 }
1187 true
1188}
1189
1190fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1196 let fs = OsFileSystem::new();
1197 let mut stderr = std::io::stderr().lock();
1198 let mut failed = false;
1199 for job in &plan.jobs {
1200 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1201 continue;
1204 }
1205 let started = std::time::Instant::now();
1206 let result = preprocess(opts, &job.input, &fs);
1207 if opts.time {
1208 say_time(&job.input, started.elapsed(), &mut stderr);
1209 }
1210 for message in &result.messages {
1211 let _ = writeln!(stderr, "{message}");
1212 }
1213 if result.failed() {
1214 failed = true;
1215 continue;
1216 }
1217 if opts.deps.emit {
1218 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1219 if opts.deps.instead_of_compiling {
1222 continue;
1223 }
1224 }
1225 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1226 let _ = writeln!(stderr, "rucc: error: {e}");
1227 failed = true;
1228 }
1229 }
1230 i32::from(failed)
1231}
1232
1233fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1239 let fs = OsFileSystem::new();
1240 let mut stderr = std::io::stderr().lock();
1241 let mut failed = false;
1242 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1243 failed |= !ok;
1244 let mut fired = Fired::new();
1245 let mut pressure = Pressure::new();
1246 for job in &plan.jobs {
1247 if !job.phases.contains(&Phase::Compile) {
1248 continue;
1249 }
1250 let started = std::time::Instant::now();
1254 let result = if job.kind == InputKind::Ir {
1255 compile_ir(opts, &job.input, &fs)
1256 } else {
1257 compile(opts, &job.input, &fs)
1258 };
1259 if opts.time {
1260 say_time(&job.input, started.elapsed(), &mut stderr);
1261 }
1262 fired.merge(&result.fired);
1263 pressure.merge(&result.pressure);
1264 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1265 failed |= !remarks.write(&result.remarks, &mut stderr);
1266 for message in &result.messages {
1267 let _ = writeln!(stderr, "{message}");
1268 }
1269 failed |= !write_temps(job, &result.temps, &mut stderr);
1272 if result.failed() {
1273 failed = true;
1274 continue;
1275 }
1276 if opts.deps.emit {
1281 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1282 }
1283 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1284 let _ = writeln!(stderr, "rucc: error: {e}");
1285 failed = true;
1286 }
1287 }
1288 failed |= !write_coverage(opts, &fired, &mut stderr);
1289 failed |= !write_pressure(opts, &pressure, &mut stderr);
1290 i32::from(failed)
1291}
1292
1293struct Scratch {
1300 dir: PathBuf,
1302}
1303
1304impl Scratch {
1305 fn new() -> Result<Scratch, String> {
1311 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1312 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1313 Ok(Scratch { dir })
1314 }
1315}
1316
1317impl Drop for Scratch {
1318 fn drop(&mut self) {
1319 let _ = std::fs::remove_dir_all(&self.dir);
1320 }
1321}
1322
1323fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1330 let linker = link::find(opts.target, link)?;
1331 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1332 Ok(link::render(&linker, &args))
1333}
1334
1335fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1342 let Some(job) = &plan.link else {
1343 let mut stderr = std::io::stderr().lock();
1346 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1347 return 1;
1348 };
1349 let linker = match link::find(opts.target, link) {
1352 Ok(linker) => linker,
1353 Err(why) => return complain(why),
1354 };
1355
1356 let scratch = match Scratch::new() {
1357 Ok(scratch) => scratch,
1358 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1359 };
1360
1361 let fs = OsFileSystem::new();
1362 let mut failed = false;
1363 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1366 let mut fired = Fired::new();
1367 let mut pressure = Pressure::new();
1368 {
1369 let mut stderr = std::io::stderr().lock();
1370 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1371 failed |= !ok;
1372 for (at, job) in plan.jobs.iter().enumerate() {
1373 let out = match &job.output {
1374 Output::Temporary(hint) => {
1375 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1378 }
1379 Output::File(path) => path.clone(),
1380 Output::Stdout => continue,
1383 };
1384 produced.push(out.clone());
1385 if !job.phases.contains(&Phase::Compile) {
1386 continue;
1387 }
1388 let started = std::time::Instant::now();
1389 let result = if job.kind == InputKind::Ir {
1390 compile_ir(opts, &job.input, &fs)
1391 } else {
1392 compile(opts, &job.input, &fs)
1393 };
1394 if opts.time {
1395 say_time(&job.input, started.elapsed(), &mut stderr);
1396 }
1397 fired.merge(&result.fired);
1398 pressure.merge(&result.pressure);
1399 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1400 failed |= !remarks.write(&result.remarks, &mut stderr);
1401 for message in &result.messages {
1402 let _ = writeln!(stderr, "{message}");
1403 }
1404 failed |= !write_temps(job, &result.temps, &mut stderr);
1405 if result.failed() {
1406 failed = true;
1407 continue;
1408 }
1409 if opts.deps.emit {
1414 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1415 }
1416 if !matches!(result.artifact, Artifact::Object(_)) {
1417 let _ = writeln!(
1422 stderr,
1423 "rucc: internal error: {}: no object file was produced for the link",
1424 job.input
1425 );
1426 failed = true;
1427 continue;
1428 }
1429 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1430 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1431 failed = true;
1432 }
1433 }
1434 failed |= !write_coverage(opts, &fired, &mut stderr);
1435 failed |= !write_pressure(opts, &pressure, &mut stderr);
1436 }
1437 if failed {
1438 return 1;
1442 }
1443
1444 let mut outputs = produced.into_iter();
1448 let mut items = Vec::with_capacity(job.inputs.len());
1449 for item in &job.inputs {
1450 match item {
1451 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1452 link::Item::File(_) => match outputs.next() {
1453 Some(path) => items.push(link::Item::File(path)),
1454 None => return complain("the plan asks the linker for a file nothing produced"),
1455 },
1456 }
1457 }
1458
1459 let args = match link::line(opts.target, link, &items, &job.output) {
1460 Ok(args) => args,
1461 Err(why) => return complain(why),
1462 };
1463 if verbose {
1464 let mut stderr = std::io::stderr().lock();
1465 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1466 }
1467 let started = std::time::Instant::now();
1468 let ran = link::run(&linker, &args);
1469 if opts.time {
1470 let mut stderr = std::io::stderr().lock();
1473 say_time(&linker.name, started.elapsed(), &mut stderr);
1474 }
1475 match ran {
1476 Ok(()) => 0,
1477 Err(link::Error::Refused { .. }) => 1,
1480 Err(why) => complain(why),
1481 }
1482}
1483
1484fn complain(why: impl std::fmt::Display) -> i32 {
1486 let mut stderr = std::io::stderr().lock();
1487 let _ = writeln!(stderr, "rucc: error: {why}");
1488 1
1489}
1490
1491fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1500 let Some(path) = &opts.rule_coverage else { return true };
1501 let Some(table) = coverage::table(opts.target.arch) else {
1502 let _ = writeln!(
1503 stderr,
1504 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1505 to report",
1506 opts.target
1507 );
1508 return false;
1509 };
1510 match std::fs::write(path, fired.listing(table)) {
1511 Ok(()) => true,
1512 Err(e) => {
1513 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1514 false
1515 }
1516 }
1517}
1518
1519fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
1527 let Some(path) = &opts.register_pressure else { return true };
1528 match std::fs::write(path, pressure.listing()) {
1529 Ok(()) => true,
1530 Err(e) => {
1531 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1532 false
1533 }
1534 }
1535}
1536
1537struct Remarks {
1544 file: Option<String>,
1546 started: bool,
1549}
1550
1551impl Remarks {
1552 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1558 let mut ok = true;
1559 if let Some(path) = file {
1560 if let Err(e) = std::fs::write(path, "") {
1561 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1562 ok = false;
1563 }
1564 }
1565 (Self { file: file.cloned(), started: false }, ok)
1566 }
1567
1568 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1574 if text.is_empty() {
1575 return true;
1576 }
1577 let Some(path) = &self.file else {
1578 let _ = write!(stderr, "{text}");
1579 return true;
1580 };
1581 let opened = std::fs::OpenOptions::new()
1582 .write(true)
1583 .append(self.started)
1584 .truncate(!self.started)
1585 .create(true)
1586 .open(path);
1587 self.started = true;
1588 let result =
1589 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1590 if let Err(e) = result {
1591 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1592 return false;
1593 }
1594 true
1595 }
1596}
1597
1598fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1609 let stem = std::path::Path::new(input)
1610 .file_name()
1611 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1612 let mut ok = true;
1613 for dump in dumps {
1614 let path = format!("{stem}.{}.ir", dump.name);
1615 if let Err(e) = std::fs::write(&path, &dump.text) {
1616 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1617 ok = false;
1618 }
1619 }
1620 ok
1621}
1622
1623fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1629 let mut ok = true;
1630 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1631 for (path, text) in kept {
1632 let (Some(path), Some(text)) = (path, text) else { continue };
1635 if let Err(e) = std::fs::write(&path, text) {
1636 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1637 ok = false;
1638 }
1639 }
1640 ok
1641}
1642
1643fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1650 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1651}
1652
1653fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1660 match output {
1661 Output::Stdout => {
1662 let mut stdout = std::io::stdout().lock();
1663 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1664 }
1665 Output::File(path) | Output::Temporary(path) => {
1666 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1667 }
1668 }
1669}
1670
1671pub fn run(args: &[String]) -> i32 {
1676 match parse_args(args) {
1677 Ok(Action::Help) => {
1678 print!("{USAGE}");
1679 0
1680 }
1681 Ok(Action::Version) => {
1682 println!("rucc {VERSION}");
1683 0
1684 }
1685 Ok(Action::Print(line)) => {
1686 println!("{line}");
1687 0
1688 }
1689 Ok(Action::PrintConfig(opts)) => {
1690 print!("{}", print_config(&opts));
1691 0
1692 }
1693 Ok(Action::PrintPipeline(opts)) => {
1694 print!("{}", print_pipeline(&opts));
1695 0
1696 }
1697 Ok(Action::PrintPlan { opts, plan, link }) => {
1698 print!("{}", plan.render());
1699 if let Some(job) = &plan.link {
1703 match link_line(&opts, &link, job) {
1704 Ok(line) => println!("{line}"),
1705 Err(why) => {
1706 let mut stderr = std::io::stderr().lock();
1707 let _ = writeln!(stderr, "rucc: error: {why}");
1708 return 1;
1709 }
1710 }
1711 }
1712 0
1713 }
1714 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1715 {
1716 let mut stderr = std::io::stderr().lock();
1717 if verbose {
1718 let _ = write!(stderr, "{}", plan.render());
1719 let _ = writeln!(stderr, "workers: {}", jobs.count());
1720 }
1721 }
1722 if opts.emit == EmitKind::Preprocessed {
1723 return preprocess_all(&opts, &plan);
1724 }
1725 if opts.emit != EmitKind::Executable {
1726 return compile_all(&opts, &plan);
1727 }
1728 link_all(&opts, &plan, &link, verbose)
1729 }
1730 Err(e) => {
1731 let mut stderr = std::io::stderr().lock();
1732 let _ = writeln!(stderr, "rucc: error: {e}");
1733 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1734 1
1735 }
1736 }
1737}
1738
1739#[cfg(test)]
1740mod tests {
1741 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1742
1743 use super::*;
1744
1745 fn args(s: &[&str]) -> Vec<String> {
1746 s.iter().map(|x| (*x).to_owned()).collect()
1747 }
1748
1749 #[test]
1750 fn help_and_version_win_over_everything_else() {
1751 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1752 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1753 }
1754
1755 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1756 match parse_args(&args(s)).expect("expected a compilation") {
1757 Action::Compile { opts, plan, .. } => (opts, plan),
1758 other => panic!("expected a compilation, got {other:?}"),
1759 }
1760 }
1761
1762 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1763 match parse_args(&args(s)).expect("expected a compilation") {
1764 Action::Compile { link, plan, .. } => (link, plan),
1765 other => panic!("expected a compilation, got {other:?}"),
1766 }
1767 }
1768
1769 #[test]
1770 fn collects_inputs_and_flags() {
1771 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1772 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1773 assert_eq!(paths, vec!["a.c", "b.c"]);
1774 assert_eq!(opts.opt_level, OptLevel::O2);
1775 assert_eq!(opts.emit, EmitKind::Object);
1776 assert!(opts.debug_info);
1777 }
1778
1779 #[test]
1782 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1783 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1784 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1785
1786 let (plain, _) = compile(&["-c", "a.c"]);
1787 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1788
1789 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1790 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1791 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1792 }
1793
1794 #[test]
1796 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
1797 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
1798 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
1799
1800 let (plain, _) = compile(&["-c", "a.c"]);
1801 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
1802
1803 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
1804 }
1805
1806 #[test]
1807 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1808 let (opts, _) = compile(&["-O", "a.c"]);
1809 assert_eq!(opts.opt_level, OptLevel::O1);
1810 }
1811
1812 #[test]
1813 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1814 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1815 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1816 assert_eq!(plan.jobs[1].kind, InputKind::C);
1817 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1818 }
1819
1820 #[test]
1821 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1822 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1823 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1824 other => panic!("expected a compilation, got {other:?}"),
1825 };
1826 assert_eq!(jobs.count(), 4);
1827
1828 let default = match parse_args(&args(&["a.c"])).unwrap() {
1829 Action::Compile { jobs, .. } => jobs,
1830 other => panic!("expected a compilation, got {other:?}"),
1831 };
1832 assert_eq!(default, Jobs::available());
1833 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1834 }
1835
1836 #[test]
1837 fn triple_hash_prints_the_plan_and_runs_nothing() {
1838 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1839 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1840 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1841 }
1842
1843 #[test]
1844 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1845 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1849 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1850 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1851 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1852 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1856 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1857 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1858 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1859 }
1860
1861 #[test]
1862 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1863 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1864 let (plain, without) = compile(&["-c", "a.c"]);
1865 assert!(opts.time);
1866 assert!(!plain.time);
1867 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1870 }
1871
1872 #[test]
1873 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1874 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1875 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1876 }
1877
1878 #[test]
1879 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1880 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1881 assert!(e.message.contains("unknown option"), "{}", e.message);
1882 }
1883
1884 #[test]
1887 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1888 let (opts, _) = compile(&["-c", "a.c"]);
1889 assert!(!opts.permissive, "off unless it is asked for");
1890
1891 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1892 assert!(opts.permissive);
1893
1894 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1895 assert!(!opts.permissive);
1896 }
1897
1898 #[test]
1899 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1900 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1901 assert!(e.message.contains("trampoline"), "{}", e.message);
1902 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1903 }
1904
1905 #[test]
1906 fn the_flag_every_configure_script_writes_is_taken() {
1907 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1910 let (opts, _) = compile(&["-c", flag, "a.c"]);
1911 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1912 }
1913 }
1914
1915 #[test]
1916 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1917 let (opts, _) = compile(&["-c", "a.c"]);
1918 assert!(opts.unwinds(), "the default is off");
1919 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1920 assert!(!opts.unwinds(), "the build was not taken at its word");
1921 let (opts, _) = compile(&[
1922 "-c",
1923 "-fno-asynchronous-unwind-tables",
1924 "-fasynchronous-unwind-tables",
1925 "a.c",
1926 ]);
1927 assert!(opts.unwinds(), "the last flag did not win");
1928 let (opts, _) =
1932 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1933 assert!(opts.unwinds(), "the weaker request was dropped");
1934 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
1935 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
1936 let (opts, _) =
1937 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
1938 assert!(!opts.unwinds(), "both were turned off and one stayed on");
1939 }
1940
1941 #[test]
1942 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1943 for flag in [
1947 "-fno-common",
1948 "-fstrict-aliasing",
1949 "-fno-strict-aliasing",
1950 "-pipe",
1951 "-fdiagnostics-color",
1952 "-fno-diagnostics-color",
1953 "-fdiagnostics-color=always",
1954 "-fdiagnostics-color=never",
1955 "-fdiagnostics-color=auto",
1956 ] {
1957 let (opts, _) = compile(&["-c", flag, "a.c"]);
1958 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1959 }
1960 }
1961
1962 #[test]
1963 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1964 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1967 assert!(e.message.contains(".bss"), "{}", e.message);
1968 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1969 }
1970
1971 #[test]
1972 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1973 for flag in ["-fno-pic", "-fno-pie"] {
1974 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1975 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1976 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1979 }
1980 }
1981
1982 #[test]
1983 fn an_unsupported_target_names_itself() {
1984 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1985 assert!(e.message.contains("sparc64"), "{}", e.message);
1986 }
1987
1988 #[test]
1989 fn no_inputs_is_an_error_but_print_config_needs_none() {
1990 assert!(parse_args(&args(&[])).is_err());
1991 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1992 }
1993
1994 #[test]
1995 fn print_config_reports_the_target_it_was_given_not_the_host() {
1996 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1997 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1998 let text = print_config(&opts);
1999 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
2000 assert!(text.contains("char-signed: false"), "{text}");
2001 assert!(text.contains("object-format: elf"), "{text}");
2002 assert!(text.contains("va-list: void-pointer"), "{text}");
2003 assert!(text.contains("registers: none"), "{text}");
2006 }
2007
2008 #[test]
2009 fn print_config_has_one_key_per_line_and_a_fixed_order() {
2010 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
2011 let text = print_config(&opts);
2012 let keys: Vec<&str> =
2013 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
2014 assert_eq!(keys[0], "version");
2015 assert_eq!(keys[1], "target");
2016 assert_eq!(keys.len(), 22);
2017 assert!(text.ends_with('\n'));
2018 }
2019
2020 #[test]
2021 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
2022 let (opts, _) = compile(&["a.c"]);
2023 assert_eq!(opts.safety, rucc_session::Safety::Off);
2024
2025 for (flag, tier) in [
2026 ("-fsafety=detect", rucc_session::Safety::Detect),
2027 ("-fsafety=enforce", rucc_session::Safety::Enforce),
2028 ("-fsafety=kernel", rucc_session::Safety::Kernel),
2029 ("-fsafety=off", rucc_session::Safety::Off),
2030 ] {
2031 let (opts, _) = compile(&[flag, "a.c"]);
2032 assert_eq!(opts.safety, tier, "{flag}");
2033 }
2034
2035 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
2037 assert_eq!(opts.safety, rucc_session::Safety::Off);
2038
2039 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
2042 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
2043 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
2044 }
2045
2046 #[test]
2047 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
2048 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2049 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2050 let text = print_pipeline(&opts);
2051 assert!(text.starts_with("level: -O2\n"), "{text}");
2052 assert!(text.contains("fold"), "{text}");
2053
2054 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
2055 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2056 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
2059
2060 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
2061 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2062 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2065 }
2066
2067 #[test]
2068 fn print_pipeline_takes_the_toggles_into_account() {
2069 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
2070 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2071 let text = print_pipeline(&opts);
2072 assert!(!text.contains("fold"), "{text}");
2075 assert!(text.contains("dce"), "{text}");
2076
2077 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
2081 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
2082 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
2083 let a = parse_args(&args(&spelled)).unwrap();
2084 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2085 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2086 }
2087
2088 #[test]
2089 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
2090 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2091 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2092 assert!(!print_pipeline(&opts).contains("global fuel"));
2093
2094 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2095 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2096 let text = print_pipeline(&opts);
2097 assert!(text.contains("global fuel: 4"), "{text}");
2100 }
2101
2102 #[test]
2105 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2106 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2107 assert_eq!(
2108 opts.passes,
2109 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2110 );
2111
2112 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2113 assert!(e.message.contains("unknown option"), "{}", e.message);
2114 }
2115
2116 #[test]
2117 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2118 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2119 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2120
2121 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2122 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2123 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2124 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2125 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2126 assert!(e.message.contains("not a number"), "{}", e.message);
2127 }
2128
2129 #[test]
2130 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2131 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2132 assert_eq!(opts.pass_fuel_global, None);
2133
2134 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2135 assert_eq!(opts.pass_fuel_global, Some(12));
2136 assert!(opts.pass_fuel.is_empty());
2139
2140 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2141 assert!(e.message.contains("not a number"), "{}", e.message);
2142 }
2143
2144 #[test]
2145 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2146 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2147 assert_eq!(
2148 opts.pass_gates,
2149 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2150 "the order is what decides, so it has to survive the parse"
2151 );
2152
2153 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2154 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2155 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2156 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2157 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2158 assert!(e.message.contains("is empty"), "{}", e.message);
2159 }
2160
2161 #[test]
2162 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2163 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2164 let text = print_pipeline(&opts);
2165 assert!(text.contains("fold, "), "{text}");
2166 assert!(text.contains("[off for main]"), "{text}");
2167 }
2168
2169 #[test]
2173 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2174 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2175 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2176
2177 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2178 assert!(e.message.contains("nosuch"), "{}", e.message);
2179 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2180 }
2181
2182 #[test]
2188 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2189 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2190 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2191 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2192
2193 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2194 assert_eq!(opts.opt_info, ["missed-note"]);
2195
2196 let (opts, _) =
2199 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2200 assert_eq!(opts.opt_info, ["missed", "all"]);
2201 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2202
2203 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2204 assert!(e.message.contains("vectorized"), "{}", e.message);
2205 assert!(e.message.contains("`missed`"), "{}", e.message);
2206 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2207 assert!(e.message.contains("no file"), "{}", e.message);
2208 }
2209
2210 #[test]
2211 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2212 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2213 assert!(opts.verify_each);
2214 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2215 }
2216
2217 #[test]
2218 fn dash_o_needs_an_argument() {
2219 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2220 assert_eq!(e.message, "-o requires an argument");
2221 }
2222
2223 #[test]
2224 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2225 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2226 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2227 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2228 }
2229
2230 #[test]
2231 fn the_include_flags_land_on_the_chain_each_one_names() {
2232 let (opts, _) = compile(&[
2235 "-Ii",
2236 "-iquote",
2237 "q",
2238 "-isystem",
2239 "sys",
2240 "-idirafter",
2241 "after",
2242 "--sysroot=/nowhere-at-all",
2243 "a.c",
2244 ]);
2245 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2246 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2249 assert!(!opts.search.dirs()[1].is_system);
2250 assert!(opts.search.dirs()[2].is_system);
2251 }
2252
2253 #[test]
2254 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2255 let (opts, _) = compile(&["a.c"]);
2259 let dirs = opts.search.dirs();
2260 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2261 assert_eq!(ours, Some(0), "{dirs:?}");
2262 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2263 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2264 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2265 }
2266
2267 #[test]
2268 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2269 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2270 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2271 assert_eq!(dirs, ["sys", runtime::DIR]);
2272 }
2273
2274 #[test]
2275 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2276 let (opts, _) =
2277 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2278 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2279 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2280 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2282 assert!(!opts.search.searches_current_dir());
2283 }
2284
2285 #[test]
2286 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2287 let (opts, _) = compile(&[
2288 "-iprefix",
2289 "/tools/",
2290 "-iwithprefix",
2291 "late",
2292 "-iwithprefixbefore",
2293 "early",
2294 "-iprefix",
2295 "/other/",
2296 "-iwithprefix",
2297 "last",
2298 "-nostdinc",
2299 "a.c",
2300 ]);
2301 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2302 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2305 assert!(!opts.search.dirs()[0].is_system);
2306 assert!(opts.search.dirs()[1].is_system);
2307 }
2308
2309 #[test]
2310 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2311 let (opts, _) =
2312 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2313 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2314 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2315 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2316 }
2317
2318 #[test]
2319 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2320 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2321 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2322 assert_eq!(dirs, ["i"]);
2323 }
2324
2325 #[test]
2326 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2327 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2328 assert_eq!(opts.std, Std::C11);
2329 assert!(opts.gnu_extensions);
2330
2331 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2332 assert_eq!(opts.std, Std::C99);
2333 assert!(!opts.gnu_extensions);
2334
2335 let (opts, _) = compile(&["-ansi", "a.c"]);
2336 assert_eq!(opts.std, Std::C89);
2337 assert!(!opts.gnu_extensions);
2338
2339 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2340 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2341 }
2342
2343 #[test]
2344 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2345 let (opts, _) = compile(&["-dM", "a.c"]);
2346 assert!(opts.dumps.macros);
2347
2348 let (opts, _) = compile(&["-dDM", "a.c"]);
2351 assert!(opts.dumps.macros);
2352 let (opts, _) = compile(&["-dD", "a.c"]);
2353 assert!(!opts.dumps.macros);
2354
2355 let (opts, _) = compile(&["a.c"]);
2356 assert!(!opts.dumps.any());
2357
2358 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2361 }
2362
2363 #[test]
2364 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2365 let (opts, _) = compile(&["a.c"]);
2366 assert_eq!(
2367 opts.gnuc,
2368 GnucVersion { major: 7, minor: 0, patch: 0 },
2369 "the lowest claim a modern glibc gives its own declarations to"
2370 );
2371
2372 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2373 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2374
2375 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2378 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2379
2380 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2381 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2382
2383 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2384 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2385
2386 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2387 assert!(e.message.contains("more than three"), "{}", e.message);
2388 }
2389
2390 #[test]
2391 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2392 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2393 assert!(opts.pedantic);
2394 assert_eq!(opts.std, Std::C17);
2395
2396 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2399 assert!(opts.pedantic);
2400
2401 let (opts, _) = compile(&["-std=c17", "a.c"]);
2402 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2403 }
2404
2405 #[test]
2406 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2407 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2408 assert!(!opts.line_markers);
2409 assert!(!opts.hosted);
2410 assert_eq!(opts.emit, EmitKind::Preprocessed);
2411 }
2412
2413 #[test]
2420 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2421 let (opts, _) = compile(&["-c", "a.c"]);
2422 assert!(opts.builtins, "a library name means the library function by default");
2423 assert!(opts.no_builtin.is_empty());
2424
2425 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2426 assert!(!opts.builtins);
2427
2428 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2429 assert!(opts.builtins, "the last mention decides");
2430
2431 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2432 assert!(opts.builtins, "one name is not the family");
2433 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2434 }
2435
2436 #[test]
2444 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2445 let (opts, _) = compile(&["-c", "a.c"]);
2446 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2447
2448 for (written, wanted) in [
2449 ("default", Visibility::Default),
2450 ("hidden", Visibility::Hidden),
2451 ("internal", Visibility::Hidden),
2452 ("protected", Visibility::Protected),
2453 ] {
2454 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2455 assert_eq!(opts.visibility, wanted, "{written}");
2456 }
2457
2458 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2461 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2462
2463 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2467 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2468 }
2469
2470 #[test]
2478 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
2479 let (opts, _) = compile(&["-c", "a.c"]);
2480 assert!(!opts.function_sections, "one text section unless something says otherwise");
2481 assert!(!opts.data_sections);
2482
2483 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
2484 assert!(opts.function_sections);
2485 assert!(!opts.data_sections, "one flag is not the other");
2486
2487 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
2488 assert!(opts.data_sections);
2489 assert!(!opts.function_sections);
2490
2491 let (opts, _) = compile(&[
2494 "-c",
2495 "-ffunction-sections",
2496 "-fno-function-sections",
2497 "-fdata-sections",
2498 "-fno-data-sections",
2499 "a.c",
2500 ]);
2501 assert!(!opts.function_sections, "the last mention decides");
2502 assert!(!opts.data_sections, "the last mention decides");
2503 }
2504
2505 #[test]
2508 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2509 let (opts, _) = compile(&["-c", "a.c"]);
2510 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2511
2512 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2513 assert!(opts.gnu89_inline);
2514
2515 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2516 assert!(!opts.gnu89_inline, "the last mention decides");
2517
2518 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2523 assert!(!opts.gnu89_inline);
2524 }
2525
2526 #[test]
2529 fn the_two_frame_flags_are_read_in_both_directions() {
2530 let (opts, _) = compile(&["-c", "a.c"]);
2531 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2532 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2533
2534 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2535 assert!(opts.frame_pointer);
2536 assert!(!opts.red_zone);
2537
2538 let (opts, _) = compile(&[
2539 "-c",
2540 "-fno-omit-frame-pointer",
2541 "-fomit-frame-pointer",
2542 "-mno-red-zone",
2543 "-mred-zone",
2544 "a.c",
2545 ]);
2546 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2547 assert!(opts.red_zone);
2548 }
2549
2550 #[test]
2553 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
2554 let (opts, _) = compile(&["-c", "a.c"]);
2555 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
2556
2557 for (flag, want) in [
2558 ("-fstack-protector", Protector::Buffers),
2559 ("-fstack-protector-strong", Protector::Strong),
2560 ("-fstack-protector-all", Protector::All),
2561 ] {
2562 let (opts, _) = compile(&["-c", flag, "a.c"]);
2563 assert_eq!(opts.protector, want, "{flag}");
2564 }
2565
2566 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
2569 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
2570 assert_eq!(opts.protector, Protector::None, "{off}");
2571 }
2572 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
2573 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
2574 }
2575
2576 #[test]
2579 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
2580 let (opts, _) = compile(&["-c", "a.c"]);
2581 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
2582
2583 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
2584 assert!(opts.stack_clash);
2585
2586 let (opts, _) =
2589 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
2590 assert!(!opts.stack_clash);
2591 let (opts, _) =
2592 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
2593 assert!(opts.stack_clash, "the last one wins either way round");
2594
2595 let (opts, _) =
2597 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
2598 assert!(opts.stack_clash);
2599 assert_eq!(opts.protector, Protector::Strong);
2600 }
2601
2602 #[test]
2606 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
2607 let (opts, _) = compile(&["-c", "a.c"]);
2608 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
2609
2610 for (arg, want) in [
2611 ("-fcf-protection", Control::Full),
2612 ("-fcf-protection=full", Control::Full),
2613 ("-fcf-protection=branch", Control::Branch),
2614 ("-fcf-protection=return", Control::Return),
2615 ("-fcf-protection=none", Control::None),
2616 ("-fcf-protection=check", Control::Check),
2617 ] {
2618 let (opts, _) = compile(&["-c", arg, "a.c"]);
2619 assert_eq!(opts.control, want, "{arg}");
2620 }
2621
2622 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
2625 assert_eq!(opts.control, Control::None);
2626 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
2627 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
2628 }
2629
2630 #[test]
2636 fn a_control_flow_protection_nothing_means_is_refused() {
2637 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
2638 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
2639 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
2640 }
2641
2642 #[test]
2643 fn the_link_flags_are_collected_apart_from_the_compilation() {
2644 let (link, _) = linking(&[
2645 "-static",
2646 "-nostartfiles",
2647 "-rdynamic",
2648 "-s",
2649 "-fuse-ld=mold",
2650 "-L/opt/lib",
2651 "-B",
2652 "/opt/tools",
2653 "a.c",
2654 ]);
2655 assert!(link.is_static);
2656 assert!(link.no_startfiles);
2657 assert!(link.export_dynamic);
2658 assert!(link.strip);
2659 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2660 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2661 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2662 }
2663
2664 #[test]
2665 fn a_comma_in_dash_wl_separates_two_arguments() {
2666 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2667 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2668 }
2669
2670 #[test]
2671 fn a_library_keeps_its_place_between_the_objects() {
2672 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2677 let link = plan.link.expect("expected a link step");
2678 assert_eq!(
2679 link.inputs,
2680 vec![
2681 link::Item::File("a.o".into()),
2682 link::Item::Library("m".into()),
2683 link::Item::File("b.o".into()),
2684 ]
2685 );
2686 assert_eq!(plan.jobs.len(), 2);
2688 }
2689
2690 #[test]
2691 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2692 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2693 assert!(plan.link.is_none());
2694 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2695 }
2696
2697 #[test]
2698 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2699 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2700 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2701 }
2702
2703 fn printed(s: &[&str]) -> String {
2704 match parse_args(&args(s)).expect("expected an answer") {
2705 Action::Print(line) => line,
2706 other => panic!("expected an answer, got {other:?}"),
2707 }
2708 }
2709
2710 fn refused(s: &[&str]) -> String {
2711 parse_args(&args(s)).expect_err("expected a refusal").message
2712 }
2713
2714 #[test]
2715 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2716 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2720 assert!(!opts.warnings_are_errors);
2721 assert!(opts.warnings);
2722 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2724 assert!(opts.warnings_are_errors);
2725 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2726 assert!(!opts.warnings);
2727 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2728 assert!(opts.pedantic && opts.warnings_are_errors);
2729 }
2730
2731 #[test]
2732 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2733 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2735 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2736 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2737 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2738 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2739 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2740 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2743 assert!(no32.contains("32 bit target"), "{no32}");
2744 }
2745
2746 #[test]
2747 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2748 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2749 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2750 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2751 }
2752
2753 #[test]
2754 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2755 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2756 let (opts, _) =
2757 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2758 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2759 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2760 assert!(wrong.contains("sysv convention"), "{wrong}");
2761 }
2762
2763 #[test]
2764 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2765 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2766 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2767 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2770 assert_eq!(names, vec!["a.c"]);
2771 }
2772
2773 #[test]
2774 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2775 let target = "--target=x86_64-unknown-linux-gnu";
2776 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2777 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2778 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2779 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2780 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2783 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2784 let dirs = printed(&[target, "-print-search-dirs"]);
2785 assert!(dirs.starts_with("install: "), "{dirs}");
2786 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2787 }
2788
2789 #[test]
2790 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2791 let (opts, _) = compile(&["-M", "a.c"]);
2792 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2793 assert!(opts.deps.system_headers, "plain -M lists them");
2794 assert_eq!(opts.emit, EmitKind::Preprocessed);
2795
2796 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2799 assert_eq!(opts.emit, EmitKind::Preprocessed);
2800
2801 let (opts, _) = compile(&["-MM", "a.c"]);
2802 assert!(!opts.deps.system_headers);
2803 }
2804
2805 #[test]
2806 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2807 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2808 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2809 assert!(opts.deps.system_headers);
2810 assert_eq!(opts.emit, EmitKind::Object);
2811
2812 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2813 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2814 assert!(!opts.deps.system_headers);
2815 }
2816
2817 #[test]
2818 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2819 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2822 assert!(!opts.deps.system_headers);
2823 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2824 assert!(!opts.deps.system_headers);
2825 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2826 assert!(!opts.deps.system_headers);
2827 }
2828
2829 #[test]
2830 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2831 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2832 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2833 }
2834
2835 #[test]
2836 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2837 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2838 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2839 assert!(opts.deps.phony);
2840
2841 for flag in ["-MF", "-MT", "-MQ"] {
2842 let e = parse_args(&args(&[flag])).unwrap_err();
2843 assert!(e.message.contains("requires an argument"), "{}", e.message);
2844 }
2845 }
2846
2847 struct TempTree(PathBuf);
2849
2850 impl Drop for TempTree {
2851 fn drop(&mut self) {
2852 let _ = std::fs::remove_dir_all(&self.0);
2853 }
2854 }
2855
2856 impl TempTree {
2857 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2858 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2859 let _ = std::fs::remove_dir_all(&dir);
2860 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2861 for (path, text) in files {
2862 let at = dir.join(path);
2863 if let Some(parent) = at.parent() {
2864 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2865 }
2866 std::fs::write(&at, text).expect("writing a temporary file should work");
2867 }
2868 TempTree(dir)
2869 }
2870
2871 fn path(&self, name: &str) -> String {
2872 self.0.join(name).to_string_lossy().into_owned()
2873 }
2874 }
2875
2876 #[test]
2877 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2878 let tree = TempTree::new(
2882 "found",
2883 &[
2884 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2885 ("one.h", "#define X 0\n"),
2886 ("two.h", "#include \"one.h\"\n"),
2887 ],
2888 );
2889 let out = tree.path("dep.d");
2890 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2891 assert_eq!(code, 0);
2892
2893 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2894 let names: Vec<&str> = text.split_whitespace().collect();
2895 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2897 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2898 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2899 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2902 }
2903
2904 #[test]
2905 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2906 let tree = TempTree::new(
2909 "guarded",
2910 &[
2911 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2912 ("g.h", "#ifndef G\n#define G\n#endif\n"),
2913 ],
2914 );
2915 let out = tree.path("dep.d");
2916 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2917 assert_eq!(code, 0);
2918 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2919 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2920 }
2921
2922 #[test]
2923 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2924 let tree = TempTree::new(
2929 "preinclude",
2930 &[
2931 ("a.c", "int main(void) { return 0; }\n"),
2932 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2933 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2934 ],
2935 );
2936 let out = tree.path("a.i");
2937 let code = run(&args(&[
2938 "-E",
2939 "-include",
2940 &tree.path("i.h"),
2941 "-imacros",
2942 &tree.path("m.h"),
2943 "-o",
2944 &out,
2945 &tree.path("a.c"),
2946 ]));
2947 assert_eq!(code, 0);
2948 let text = std::fs::read_to_string(&out).expect("the output should have been written");
2949 assert!(text.contains("saw_it"), "{text}");
2950 assert!(!text.contains("macros_text"), "{text}");
2953 }
2954
2955 #[test]
2956 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
2957 let tree = TempTree::new(
2958 "preinclude-deps",
2959 &[
2960 ("a.c", "int main(void) { return 0; }\n"),
2961 ("i.h", "int from_include;\n"),
2962 ("m.h", "#define M 1\n"),
2963 ],
2964 );
2965 let out = tree.path("dep.d");
2966 let code = run(&args(&[
2967 "-MM",
2968 "-MF",
2969 &out,
2970 "-include",
2971 &tree.path("i.h"),
2972 "-imacros",
2973 &tree.path("m.h"),
2974 "-o",
2975 &tree.path("a.i"),
2976 &tree.path("a.c"),
2977 ]));
2978 assert_eq!(code, 0);
2979 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2980 assert!(text.contains("i.h"), "{text}");
2981 assert!(text.contains("m.h"), "{text}");
2982 }
2983
2984 #[test]
2985 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
2986 let tree = TempTree::new(
2990 "preinclude-missing",
2991 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
2992 );
2993 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
2994 assert_eq!(code, 1);
2995 }
2996
2997 #[test]
2998 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
2999 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
3003 assert_eq!(plan.output.as_deref(), Some("prog"));
3004 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
3005 assert_eq!(
3006 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
3007 Some("prog.d")
3008 );
3009 }
3010
3011 #[test]
3012 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
3013 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
3014 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
3015 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
3016 assert_eq!(plan.output, None);
3017 }
3018
3019 #[test]
3020 fn usage_fits_on_a_screen() {
3021 assert!(USAGE.lines().count() < 51, "usage text has grown past one screen");
3045 }
3046}