1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.15")]
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, Hook, Options, Pic, Preinclude, Protector, SaveTemps, Session, Std,
49 runtime,
50};
51use rucc_target::Triple;
52
53use crate::link::LinkOptions;
54
55pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
56pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
57pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
58pub use crate::schedule::Jobs;
59
60pub const VERSION: &str = env!("CARGO_PKG_VERSION");
62
63#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum Action {
66 Help,
68 Version,
70 Print(String),
76 PrintConfig(Box<Options>),
78 PrintPipeline(Box<Options>),
80 PrintPlan {
82 opts: Box<Options>,
84 plan: Box<Plan>,
86 link: Box<LinkOptions>,
88 },
89 Compile {
91 opts: Box<Options>,
93 plan: Box<Plan>,
95 link: Box<LinkOptions>,
97 jobs: Jobs,
99 verbose: bool,
101 },
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct CliError {
107 pub message: String,
110}
111
112impl std::fmt::Display for CliError {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.write_str(&self.message)
115 }
116}
117
118impl std::error::Error for CliError {}
119
120fn err(message: impl Into<String>) -> CliError {
121 CliError { message: message.into() }
122}
123
124enum Query {
130 Machine,
132 Version,
134 Multiarch,
136 SearchDirs,
138 FileName(String),
140 ProgName(String),
142 Libgcc,
144}
145
146pub const USAGE: &str = "\
151rucc, an optimizing C compiler
152
153usage: rucc [options] file...
154
155options:
156 -c compile and assemble, do not link
157 -S compile only, emit assembly
158 -E preprocess only
159 -o <file> write output to <file>, or to standard output for -
160 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
161 -I <dir> add <dir> to the include search path
162 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
163 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
164 -include <file>, -imacros <file> read <file> first, the second for its macros only
165 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
166 -P, -dM with -E: leave out the markers, or dump the macros
167 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
168 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
169 -std=<dialect> c89 through c23, and the gnu spellings
170 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
171 -x <lang> treat later inputs as <lang>, or none to stop
172 -O<level> optimize: 0, 1, 2, 3, s, z
173 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
174 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
175 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
176 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
177 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
178 -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
179 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
180 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
181 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
182 -fPIC -fpic -fPIE -fpie, -fno-common, -f[no-]strict-aliasing, -pipe what it does anyway
183 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
184 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
185 -Werror -pedantic -pedantic-errors -w how much to say, and whether it is fatal
186 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
187 -pg -p, -mfentry -mno-fentry call a profiler on the way in, and where that call goes
188 -pthread build for more than one thread, and link the library for it
189 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
190 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
191 -j[n] compile n translation units at once, default all
192 -v, -### print each phase as it runs, or without running any
193 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
194 --target=<triple> generate code for <triple>
195 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
196 safety-summary, type-granules
197 --print-config, --print-pipeline print the configuration or the pipeline, and exit
198 --version print the version and exit
199 -h, --help print this message and exit
200
201See spec/04-driver-and-cli.md for the full flag reference.
202";
203
204fn joined_or_next(
208 arg: &str,
209 at: usize,
210 args: &[String],
211 i: &mut usize,
212) -> Result<String, CliError> {
213 if arg.len() > at {
214 return Ok(arg[at..].to_owned());
215 }
216 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
217 *i += 1;
218 Ok(next.clone())
219}
220
221pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
228 let host = Triple::host()
229 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
230 let mut opts = Options::new(host);
231 let mut inputs: Vec<Input> = Vec::new();
232 let mut print_config = false;
233 let mut print_pipeline = false;
234 let mut print_plan = false;
235 let mut verbose = false;
236 let mut jobs = Jobs::default();
237 let mut nostdinc = false;
238 let mut sysroot: Option<PathBuf> = None;
239 let mut output = None;
240 let mut link = LinkOptions::default();
241 let mut query: Option<Query> = None;
242 let mut threads = false;
243 let mut forced: Option<InputKind> = None;
246 let mut iprefix = String::new();
253
254 let mut i = 0;
255 while i < args.len() {
256 let arg = args[i].as_str();
257 i += 1;
258 match arg {
259 "-h" | "--help" => return Ok(Action::Help),
260 "--version" => return Ok(Action::Version),
261 "--print-config" => print_config = true,
262 "--print-pipeline" => print_pipeline = true,
263 "-###" => print_plan = true,
264 "-v" => verbose = true,
265 "-save-temps" => opts.save_temps = SaveTemps::Object,
269 _ if arg.starts_with("-save-temps=") => {
270 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
271 }
272 "-time" => opts.time = true,
275 "-c" => opts.emit = EmitKind::Object,
276 "-S" => opts.emit = EmitKind::Asm,
277 "-E" => opts.emit = EmitKind::Preprocessed,
278 "-g" => opts.debug_info = true,
279 "-g0" => opts.debug_info = false,
284 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
285 opts.debug_info = true;
286 }
287 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
290 _ if arg.starts_with("-gdwarf-") => {
291 return Err(err(format!(
292 "{arg}: this compiler writes DWARF 5 and no other version, see \
293 spec/11-debug-info.md"
294 )));
295 }
296 "-Werror" => opts.warnings_are_errors = true,
297 "-w" => opts.warnings = false,
300 "-pedantic-errors" => {
301 opts.pedantic = true;
302 opts.warnings_are_errors = true;
303 }
304 "-P" => opts.line_markers = false,
305 "-M" => {
312 opts.deps.emit = true;
313 opts.deps.instead_of_compiling = true;
314 }
315 "-MM" => {
316 opts.deps.emit = true;
317 opts.deps.instead_of_compiling = true;
318 opts.deps.system_headers = false;
319 }
320 "-MD" => opts.deps.emit = true,
321 "-MMD" => {
322 opts.deps.emit = true;
323 opts.deps.system_headers = false;
324 }
325 "-MP" => opts.deps.phony = true,
326 "-MF" | "-MT" | "-MQ" => {
329 let value =
330 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
331 i += 1;
332 match arg {
333 "-MF" => opts.deps.file = Some(value.clone()),
334 "-MT" => opts.deps.targets.push(value.clone()),
338 _ => opts.deps.targets.push(deps::escaped(value)),
339 }
340 }
341 "-dumpmachine" => query = Some(Query::Machine),
345 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
346 "-print-multiarch" => query = Some(Query::Multiarch),
347 "-print-search-dirs" => query = Some(Query::SearchDirs),
348 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
349 _ if arg.starts_with("-print-file-name=") => {
350 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
351 }
352 _ if arg.starts_with("-print-prog-name=") => {
353 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
354 }
355 "-pthread" | "-pthreads" => {
360 opts.defines.push("_REENTRANT".to_owned());
361 threads = true;
362 }
363 "-ansi" => {
364 opts.std = Std::C89;
365 opts.gnu_extensions = false;
366 }
367 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
370 "-fpermissive" => opts.permissive = true,
373 "-fno-permissive" => opts.permissive = false,
374 "-ffreestanding" => opts.hosted = false,
375 "-fhosted" => opts.hosted = true,
376 "-fno-builtin" => opts.builtins = false,
377 "-fbuiltin" => opts.builtins = true,
378 "-fgnu89-inline" => opts.gnu89_inline = true,
382 "-fno-gnu89-inline" => opts.gnu89_inline = false,
383 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
386 "-fomit-frame-pointer" => opts.frame_pointer = false,
387 "-mno-red-zone" => opts.red_zone = false,
388 "-mred-zone" => opts.red_zone = true,
389 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
394 opts.protector = Protector::None;
395 }
396 "-fstack-protector" => opts.protector = Protector::Buffers,
397 "-fstack-protector-strong" => opts.protector = Protector::Strong,
398 "-fstack-protector-all" => opts.protector = Protector::All,
399 "-fstack-clash-protection" => opts.stack_clash = true,
402 "-fno-stack-clash-protection" => opts.stack_clash = false,
403 "-fcf-protection" => opts.control = Control::Full,
407 "-fno-cf-protection" => opts.control = Control::None,
408 "-pg" | "-p" => {
412 opts.profile = true;
413 link.profile = true;
414 }
415 "-mfentry" => opts.hook = Hook::Early,
420 "-mno-fentry" => opts.hook = Hook::Late,
421 "-nostdinc" => nostdinc = true,
425 "-o" => {
426 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
427 i += 1;
428 }
429 "-isysroot" => {
436 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
437 i += 1;
438 sysroot = Some(PathBuf::from(dir));
439 }
440 "-iquote" | "-isystem" | "-idirafter" => {
441 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
442 i += 1;
443 match arg {
444 "-iquote" => opts.search.push_quote(dir.clone()),
445 "-isystem" => opts.search.push_system(dir.clone()),
446 _ => opts.search.push_after(dir.clone()),
447 }
448 }
449 "-iprefix" => {
450 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
451 i += 1;
452 }
453 "-iwithprefix" | "-iwithprefixbefore" => {
459 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
460 i += 1;
461 let dir = format!("{iprefix}{dir}");
462 if arg == "-iwithprefix" {
463 opts.search.push_system(dir);
464 } else {
465 opts.search.push_bracket(dir);
466 }
467 }
468 "-include" | "-imacros" => {
469 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
470 i += 1;
471 opts.preincludes
472 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
473 }
474 "-I-" => opts.search.split_quote_chain(),
479 "-x" => {
480 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
481 i += 1;
482 forced = if lang == "none" {
483 None
484 } else {
485 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
486 };
487 }
488 _ if arg.starts_with("-D") => {
496 let value = joined_or_next(arg, 2, args, &mut i)?;
497 opts.defines.push(value);
498 }
499 _ if arg.starts_with("-U") => {
500 let value = joined_or_next(arg, 2, args, &mut i)?;
501 opts.undefines.push(value);
502 }
503 _ if arg.starts_with("-I") => {
504 let dir = joined_or_next(arg, 2, args, &mut i)?;
505 opts.search.push_bracket(dir);
506 }
507 _ if arg.starts_with("-std=") => {
508 let name = &arg["-std=".len()..];
509 let (std, gnu) = Std::from_flag(name)
510 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
511 opts.std = std;
512 opts.gnu_extensions = gnu;
513 }
514 _ if Dumps::is_family(arg) => {
523 opts.dumps.add(&arg[2..]);
524 }
525 _ if arg.starts_with("-fno-builtin-") => {
530 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
531 }
532 _ if arg.starts_with("-fgnuc-version=") => {
533 let v = &arg["-fgnuc-version=".len()..];
534 opts.gnuc = v.parse().map_err(err)?;
535 }
536 "-fnested-functions" => {
541 return Err(err(
542 "nested functions are not supported: a call to one goes through a trampoline \
543 written on the stack, which no target that enforces an unexecutable stack \
544 allows",
545 ));
546 }
547 "-fno-nested-functions" => {}
548 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
559 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
563 "-fsemantic-interposition" => opts.interposition = true,
570 "-fno-semantic-interposition" => opts.interposition = false,
571 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
576 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
577 "-funwind-tables" => opts.unwind_tables = true,
578 "-fno-unwind-tables" => opts.unwind_tables = false,
579 "-fno-pic" | "-fno-pie" => {
586 return Err(err(
587 "position dependent code is not supported: an address that may be in another \
588 object is loaded out of the global offset table, and nothing here emits the \
589 absolute form this asks for. Use -no-pie if what you meant was how to link",
590 ));
591 }
592 "-ffunction-sections" => opts.function_sections = true,
598 "-fno-function-sections" => opts.function_sections = false,
599 "-fdata-sections" => opts.data_sections = true,
600 "-fno-data-sections" => opts.data_sections = false,
601 "-fno-common" => {}
607 "-fcommon" => {
611 return Err(err(
612 "a tentative definition is written into .bss as its own symbol here, and \
613 nothing emits the common symbol this asks the linker to merge. Give the \
614 variable a definition in one file and declare it extern in the others",
615 ));
616 }
617 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
631 "-pipe" => {}
634 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
641 _ if arg.starts_with("-fdiagnostics-color=") => {}
642 "-static" => link.is_static = true,
646 "-shared" => link.shared = true,
647 "-pie" => link.pie = Some(true),
648 "-no-pie" | "-nopie" => link.pie = Some(false),
649 "-nostdlib" => link.no_stdlib = true,
650 "-nostartfiles" => link.no_startfiles = true,
651 "-nodefaultlibs" => link.no_defaultlibs = true,
652 "-fno-builtins-lib" => link.no_builtins_lib = true,
653 "-fbuiltins-lib" => link.no_builtins_lib = false,
654 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
655 "-s" => link.strip = true,
656 "-Xlinker" => {
657 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
658 i += 1;
659 link.passthrough.push(next.clone());
660 }
661 _ if arg.starts_with("-Wl,") => {
662 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
665 }
666 _ if arg.starts_with("-fuse-ld=") => {
667 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
668 }
669 _ if arg.starts_with("-l") && arg.len() > 2 => {
670 inputs.push(Input::library(&arg[2..]));
671 }
672 "-l" => {
673 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
674 i += 1;
675 inputs.push(Input::library(next));
676 }
677 _ if arg.starts_with("-L") => {
678 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
679 }
680 _ if arg.starts_with("-B") => {
681 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
682 }
683 _ if arg.starts_with("-j") => {
684 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
685 }
686 _ if arg.starts_with("--sysroot=") => {
687 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
688 }
689 _ if arg.starts_with("--target=") => {
690 let t = &arg["--target=".len()..];
691 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
692 }
693 _ if arg.starts_with("--emit=") => {
694 let k = &arg["--emit=".len()..];
695 opts.emit = k
696 .parse()
697 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
698 }
699 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
705 "-Ofast" => {
711 return Err(err(
712 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
713 spec/04-driver-and-cli.md section 4.6",
714 ));
715 }
716 _ if arg.starts_with("-O") => {
717 opts.opt_level = arg[2..]
718 .parse()
719 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
720 }
721 _ if arg.starts_with("-fvisibility=") => {
725 let seen = &arg["-fvisibility=".len()..];
726 opts.visibility = seen.parse().map_err(|()| {
727 err(format!(
728 "`{seen}` is not a visibility, which is default, hidden, internal or \
729 protected"
730 ))
731 })?;
732 }
733 _ if arg.starts_with("-fcf-protection=") => {
737 let edges = &arg["-fcf-protection=".len()..];
738 opts.control = edges.parse().map_err(|()| {
739 err(format!(
740 "`{edges}` is not a control flow protection, which is full, branch, \
741 return, none or check"
742 ))
743 })?;
744 }
745 _ if arg.starts_with("-fsafety=") => {
750 let tier = &arg["-fsafety=".len()..];
751 opts.safety = tier.parse().map_err(|()| {
752 err(format!(
753 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
754 ))
755 })?;
756 }
757 _ if arg.starts_with("-fpass-fuel=") => {
761 let (name, count) = arg["-fpass-fuel=".len()..]
762 .split_once('=')
763 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
764 if rucc_opt::pass::find(name).is_none() {
765 return Err(err(format!(
766 "`{name}` is not a pass this compiler has, see --print-pipeline"
767 )));
768 }
769 let count: u32 = count
770 .parse()
771 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
772 opts.pass_fuel.push((name.to_owned(), count));
773 }
774 _ if arg.starts_with("-fpass-fuel-global=") => {
775 let count = &arg["-fpass-fuel-global=".len()..];
776 let count: u32 = count
777 .parse()
778 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
779 opts.pass_fuel_global = Some(count);
780 }
781 _ if arg == "-fopt-info"
786 || arg.starts_with("-fopt-info=")
787 || arg.starts_with("-fopt-info-") =>
788 {
789 let rest = &arg["-fopt-info".len()..];
790 let (kinds, file) = match rest.split_once('=') {
791 Some((kinds, file)) => (kinds, Some(file)),
792 None => (rest, None),
793 };
794 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
795 rucc_opt::Wants::none().add(kinds).map_err(err)?;
796 opts.opt_info.push(kinds.to_owned());
797 if let Some(file) = file {
798 if file.is_empty() {
799 return Err(err("-fopt-info= was given no file to write to"));
800 }
801 opts.opt_info_file = Some(file.to_owned());
802 }
803 }
804 _ if arg.starts_with("-fdump-ir=") => {
805 let spec = &arg["-fdump-ir=".len()..];
808 rucc_opt::Dumps::default().add(spec).map_err(err)?;
809 opts.dump_ir.push(spec.to_owned());
810 }
811 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
817 let on = arg.starts_with("-fenable-");
818 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
819 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
820 opts.pass_gates.push((on, spec.to_owned()));
821 }
822 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
823 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
824 }
825 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
826 opts.passes.push((arg["-f".len()..].to_owned(), true));
827 }
828 "-Zverify-each" => opts.verify_each = true,
834 _ if arg.starts_with("-Zrule-coverage=") => {
835 let file = &arg["-Zrule-coverage=".len()..];
836 if file.is_empty() {
837 return Err(err("-Zrule-coverage= needs a file to write to"));
838 }
839 opts.rule_coverage = Some(file.to_owned());
840 }
841 _ if arg.starts_with("-Zregister-pressure=") => {
842 let file = &arg["-Zregister-pressure=".len()..];
843 if file.is_empty() {
844 return Err(err("-Zregister-pressure= needs a file to write to"));
845 }
846 opts.register_pressure = Some(file.to_owned());
847 }
848 _ if arg.starts_with("-Z") => {
849 return Err(err(format!(
850 "`{arg}` is not an unstable option this compiler has, see \
851 spec/04-driver-and-cli.md section 4.11 for the ones it does"
852 )));
853 }
854 "-m64" | "-m32" | "-mx32" => {
859 let want: u32 = match arg {
860 "-m64" => 64,
861 _ => 32,
862 };
863 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
864 if have != want {
865 return Err(err(format!(
866 "{arg} asks for a {want} bit target and {} is {have} bit, use \
867 --target= to name the one you mean",
868 opts.target
869 )));
870 }
871 }
872 _ if arg.starts_with("-march=")
878 || arg.starts_with("-mtune=")
879 || arg.starts_with("-mcpu=") => {}
880 _ if arg.starts_with("-mabi=") => {
883 let want = &arg["-mabi=".len()..];
884 let have = match opts.target.arch {
885 rucc_target::Arch::X86_64 => "sysv",
886 rucc_target::Arch::Aarch64 => "lp64",
887 rucc_target::Arch::Riscv64 => "lp64d",
888 };
889 if want != have {
890 return Err(err(format!(
891 "{arg}: {} uses the {have} convention and this compiler has no other",
892 opts.target
893 )));
894 }
895 }
896 "-mcmodel=small" => {}
900 _ if arg.starts_with("-mcmodel=") => {
901 return Err(err(format!(
902 "{arg}: this compiler emits the small code model and no other, see \
903 spec/12-targets.md"
904 )));
905 }
906 _ if arg.starts_with("-specs=") => {
910 return Err(err(
911 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
912 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
913 section 4.4",
914 ));
915 }
916 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
922 return Err(err(format!(
923 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
924 are inside this compiler rather than programs it runs"
925 )));
926 }
927 "-Xassembler" | "-Xpreprocessor" => {
928 return Err(err(format!(
929 "{arg} hands an argument to a separate assembler or preprocessor, and both \
930 are inside this compiler rather than programs it runs"
931 )));
932 }
933 _ if arg.starts_with("-W") => {}
940 "-fno-ident"
946 | "-fident"
947 | "-funit-at-a-time"
948 | "-fno-unit-at-a-time"
949 | "-shared-libgcc"
950 | "-static-libgcc" => {}
951 _ if arg.starts_with('-') && arg.len() > 1 => {
952 return Err(err(format!("unknown option `{arg}`")));
957 }
958 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
959 }
960 }
961
962 link.sysroot = sysroot.clone();
969 if threads {
974 inputs.push(Input::library("pthread"));
975 }
976 if let Some(query) = query {
977 return Ok(Action::Print(answer(&query, &opts, &link)));
978 }
979 if opts.deps.instead_of_compiling {
985 opts.emit = EmitKind::Preprocessed;
986 }
987 if !nostdinc {
988 opts.search.push_system(runtime::DIR);
989 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
993 opts.search.push_system(dir);
994 }
995 }
996 opts.search.remove_duplicates();
1000
1001 if print_config {
1004 return Ok(Action::PrintConfig(Box::new(opts)));
1005 }
1006 if print_pipeline {
1007 return Ok(Action::PrintPipeline(Box::new(opts)));
1008 }
1009 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
1010 if print_plan {
1011 return Ok(Action::PrintPlan {
1012 opts: Box::new(opts),
1013 plan: Box::new(plan),
1014 link: Box::new(link),
1015 });
1016 }
1017 Ok(Action::Compile {
1018 opts: Box::new(opts),
1019 plan: Box::new(plan),
1020 link: Box::new(link),
1021 jobs,
1022 verbose,
1023 })
1024}
1025
1026fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
1032 let found = |name: &str| {
1033 link::find_in_search(link, opts.target, name)
1034 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
1035 };
1036 match query {
1037 Query::Machine => opts.target.to_string(),
1038 Query::Version => VERSION.to_owned(),
1039 Query::Multiarch => link::multiarch(opts.target),
1040 Query::SearchDirs => {
1045 let here = std::env::current_exe()
1046 .ok()
1047 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
1048 .unwrap_or_default();
1049 let list = |dirs: &[PathBuf]| {
1050 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
1051 };
1052 let libraries = link::search_dirs(link, opts.target);
1053 format!(
1054 "install: {}\nprograms: ={}\nlibraries: ={}",
1055 here.display(),
1056 list(&link.prefixes),
1057 list(&libraries)
1058 )
1059 }
1060 Query::FileName(name) => found(name),
1061 Query::Libgcc => found("libgcc.a"),
1065 Query::ProgName(name) => link
1069 .prefixes
1070 .iter()
1071 .map(|dir| dir.join(name))
1072 .find(|path| path.is_file())
1073 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1074 }
1075}
1076
1077#[must_use]
1083pub fn print_pipeline(opts: &Options) -> String {
1084 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1085 settings.toggles.clone_from(&opts.passes);
1086 settings.global_fuel = opts.pass_fuel_global;
1087 for (on, spec) in &opts.pass_gates {
1088 let _ = settings.gates.add(*on, spec);
1091 }
1092 rucc_opt::pipeline::print(&settings)
1093}
1094
1095#[must_use]
1100pub fn print_config(opts: &Options) -> String {
1101 let sess = Session::new(opts.clone());
1102 let t = &sess.target;
1103 let mut out = String::new();
1104 let _ = writeln!(out, "version: {VERSION}");
1105 let _ = writeln!(out, "target: {}", opts.target);
1109 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1110 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1111 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1112 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1113 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1114 let _ = writeln!(out, "long-width: {}", t.long_width);
1115 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1116 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1117 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1118 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1119 let regs: Vec<String> = t
1122 .regs
1123 .classes()
1124 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1125 .collect();
1126 let _ = writeln!(
1127 out,
1128 "registers: {}",
1129 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1130 );
1131 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1132 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1133 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1134 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1135 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1136 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1137 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
1138 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
1139 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
1140 let _ = writeln!(out, "profile: {}", sess.opts.profile);
1141 let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
1142 for dir in sess.opts.search.dirs() {
1145 let system = if dir.is_system { " (system)" } else { "" };
1146 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1147 }
1148 out
1149}
1150
1151fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1159 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1160}
1161
1162fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1165 if path == "-" {
1166 return write_out(&Output::Stdout, bytes);
1167 }
1168 write_out(&Output::File(path.to_owned()), bytes)
1169}
1170
1171fn write_deps(
1177 opts: &Options,
1178 plan: &Plan,
1179 job: &Job,
1180 found: &[Dependency],
1181 stderr: &mut impl std::io::Write,
1182) -> bool {
1183 let targets = if opts.deps.targets.is_empty() {
1184 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1185 } else {
1186 opts.deps.targets.clone()
1187 };
1188 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1189 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1192 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1196 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1197 }),
1198 None => write_out(&job.output, rule.as_bytes()),
1199 };
1200 if let Err(e) = wrote {
1201 let _ = writeln!(stderr, "rucc: error: {e}");
1202 return false;
1203 }
1204 true
1205}
1206
1207fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1213 let fs = OsFileSystem::new();
1214 let mut stderr = std::io::stderr().lock();
1215 let mut failed = false;
1216 for job in &plan.jobs {
1217 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1218 continue;
1221 }
1222 let started = std::time::Instant::now();
1223 let result = preprocess(opts, &job.input, &fs);
1224 if opts.time {
1225 say_time(&job.input, started.elapsed(), &mut stderr);
1226 }
1227 for message in &result.messages {
1228 let _ = writeln!(stderr, "{message}");
1229 }
1230 if result.failed() {
1231 failed = true;
1232 continue;
1233 }
1234 if opts.deps.emit {
1235 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1236 if opts.deps.instead_of_compiling {
1239 continue;
1240 }
1241 }
1242 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1243 let _ = writeln!(stderr, "rucc: error: {e}");
1244 failed = true;
1245 }
1246 }
1247 i32::from(failed)
1248}
1249
1250fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1256 let fs = OsFileSystem::new();
1257 let mut stderr = std::io::stderr().lock();
1258 let mut failed = false;
1259 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1260 failed |= !ok;
1261 let mut fired = Fired::new();
1262 let mut pressure = Pressure::new();
1263 for job in &plan.jobs {
1264 if !job.phases.contains(&Phase::Compile) {
1265 continue;
1266 }
1267 let started = std::time::Instant::now();
1271 let result = if job.kind == InputKind::Ir {
1272 compile_ir(opts, &job.input, &fs)
1273 } else {
1274 compile(opts, &job.input, &fs)
1275 };
1276 if opts.time {
1277 say_time(&job.input, started.elapsed(), &mut stderr);
1278 }
1279 fired.merge(&result.fired);
1280 pressure.merge(&result.pressure);
1281 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1282 failed |= !remarks.write(&result.remarks, &mut stderr);
1283 for message in &result.messages {
1284 let _ = writeln!(stderr, "{message}");
1285 }
1286 failed |= !write_temps(job, &result.temps, &mut stderr);
1289 if result.failed() {
1290 failed = true;
1291 continue;
1292 }
1293 if opts.deps.emit {
1298 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1299 }
1300 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1301 let _ = writeln!(stderr, "rucc: error: {e}");
1302 failed = true;
1303 }
1304 }
1305 failed |= !write_coverage(opts, &fired, &mut stderr);
1306 failed |= !write_pressure(opts, &pressure, &mut stderr);
1307 i32::from(failed)
1308}
1309
1310struct Scratch {
1317 dir: PathBuf,
1319}
1320
1321impl Scratch {
1322 fn new() -> Result<Scratch, String> {
1328 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1329 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1330 Ok(Scratch { dir })
1331 }
1332}
1333
1334impl Drop for Scratch {
1335 fn drop(&mut self) {
1336 let _ = std::fs::remove_dir_all(&self.dir);
1337 }
1338}
1339
1340fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1347 let linker = link::find(opts.target, link)?;
1348 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1349 Ok(link::render(&linker, &args))
1350}
1351
1352fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1359 let Some(job) = &plan.link else {
1360 let mut stderr = std::io::stderr().lock();
1363 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1364 return 1;
1365 };
1366 let linker = match link::find(opts.target, link) {
1369 Ok(linker) => linker,
1370 Err(why) => return complain(why),
1371 };
1372
1373 let scratch = match Scratch::new() {
1374 Ok(scratch) => scratch,
1375 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1376 };
1377
1378 let fs = OsFileSystem::new();
1379 let mut failed = false;
1380 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1383 let mut fired = Fired::new();
1384 let mut pressure = Pressure::new();
1385 {
1386 let mut stderr = std::io::stderr().lock();
1387 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1388 failed |= !ok;
1389 for (at, job) in plan.jobs.iter().enumerate() {
1390 let out = match &job.output {
1391 Output::Temporary(hint) => {
1392 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1395 }
1396 Output::File(path) => path.clone(),
1397 Output::Stdout => continue,
1400 };
1401 produced.push(out.clone());
1402 if !job.phases.contains(&Phase::Compile) {
1403 continue;
1404 }
1405 let started = std::time::Instant::now();
1406 let result = if job.kind == InputKind::Ir {
1407 compile_ir(opts, &job.input, &fs)
1408 } else {
1409 compile(opts, &job.input, &fs)
1410 };
1411 if opts.time {
1412 say_time(&job.input, started.elapsed(), &mut stderr);
1413 }
1414 fired.merge(&result.fired);
1415 pressure.merge(&result.pressure);
1416 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1417 failed |= !remarks.write(&result.remarks, &mut stderr);
1418 for message in &result.messages {
1419 let _ = writeln!(stderr, "{message}");
1420 }
1421 failed |= !write_temps(job, &result.temps, &mut stderr);
1422 if result.failed() {
1423 failed = true;
1424 continue;
1425 }
1426 if opts.deps.emit {
1431 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1432 }
1433 if !matches!(result.artifact, Artifact::Object(_)) {
1434 let _ = writeln!(
1439 stderr,
1440 "rucc: internal error: {}: no object file was produced for the link",
1441 job.input
1442 );
1443 failed = true;
1444 continue;
1445 }
1446 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1447 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1448 failed = true;
1449 }
1450 }
1451 failed |= !write_coverage(opts, &fired, &mut stderr);
1452 failed |= !write_pressure(opts, &pressure, &mut stderr);
1453 }
1454 if failed {
1455 return 1;
1459 }
1460
1461 let mut outputs = produced.into_iter();
1465 let mut items = Vec::with_capacity(job.inputs.len());
1466 for item in &job.inputs {
1467 match item {
1468 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1469 link::Item::File(_) => match outputs.next() {
1470 Some(path) => items.push(link::Item::File(path)),
1471 None => return complain("the plan asks the linker for a file nothing produced"),
1472 },
1473 }
1474 }
1475
1476 let args = match link::line(opts.target, link, &items, &job.output) {
1477 Ok(args) => args,
1478 Err(why) => return complain(why),
1479 };
1480 if verbose {
1481 let mut stderr = std::io::stderr().lock();
1482 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1483 }
1484 let started = std::time::Instant::now();
1485 let ran = link::run(&linker, &args);
1486 if opts.time {
1487 let mut stderr = std::io::stderr().lock();
1490 say_time(&linker.name, started.elapsed(), &mut stderr);
1491 }
1492 match ran {
1493 Ok(()) => 0,
1494 Err(link::Error::Refused { .. }) => 1,
1497 Err(why) => complain(why),
1498 }
1499}
1500
1501fn complain(why: impl std::fmt::Display) -> i32 {
1503 let mut stderr = std::io::stderr().lock();
1504 let _ = writeln!(stderr, "rucc: error: {why}");
1505 1
1506}
1507
1508fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1517 let Some(path) = &opts.rule_coverage else { return true };
1518 let Some(table) = coverage::table(opts.target.arch) else {
1519 let _ = writeln!(
1520 stderr,
1521 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1522 to report",
1523 opts.target
1524 );
1525 return false;
1526 };
1527 match std::fs::write(path, fired.listing(table)) {
1528 Ok(()) => true,
1529 Err(e) => {
1530 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1531 false
1532 }
1533 }
1534}
1535
1536fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
1544 let Some(path) = &opts.register_pressure else { return true };
1545 match std::fs::write(path, pressure.listing()) {
1546 Ok(()) => true,
1547 Err(e) => {
1548 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1549 false
1550 }
1551 }
1552}
1553
1554struct Remarks {
1561 file: Option<String>,
1563 started: bool,
1566}
1567
1568impl Remarks {
1569 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1575 let mut ok = true;
1576 if let Some(path) = file {
1577 if let Err(e) = std::fs::write(path, "") {
1578 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1579 ok = false;
1580 }
1581 }
1582 (Self { file: file.cloned(), started: false }, ok)
1583 }
1584
1585 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1591 if text.is_empty() {
1592 return true;
1593 }
1594 let Some(path) = &self.file else {
1595 let _ = write!(stderr, "{text}");
1596 return true;
1597 };
1598 let opened = std::fs::OpenOptions::new()
1599 .write(true)
1600 .append(self.started)
1601 .truncate(!self.started)
1602 .create(true)
1603 .open(path);
1604 self.started = true;
1605 let result =
1606 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1607 if let Err(e) = result {
1608 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1609 return false;
1610 }
1611 true
1612 }
1613}
1614
1615fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1626 let stem = std::path::Path::new(input)
1627 .file_name()
1628 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1629 let mut ok = true;
1630 for dump in dumps {
1631 let path = format!("{stem}.{}.ir", dump.name);
1632 if let Err(e) = std::fs::write(&path, &dump.text) {
1633 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1634 ok = false;
1635 }
1636 }
1637 ok
1638}
1639
1640fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1646 let mut ok = true;
1647 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1648 for (path, text) in kept {
1649 let (Some(path), Some(text)) = (path, text) else { continue };
1652 if let Err(e) = std::fs::write(&path, text) {
1653 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1654 ok = false;
1655 }
1656 }
1657 ok
1658}
1659
1660fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1667 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1668}
1669
1670fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1677 match output {
1678 Output::Stdout => {
1679 let mut stdout = std::io::stdout().lock();
1680 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1681 }
1682 Output::File(path) | Output::Temporary(path) => {
1683 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1684 }
1685 }
1686}
1687
1688pub fn run(args: &[String]) -> i32 {
1693 match parse_args(args) {
1694 Ok(Action::Help) => {
1695 print!("{USAGE}");
1696 0
1697 }
1698 Ok(Action::Version) => {
1699 println!("rucc {VERSION}");
1700 0
1701 }
1702 Ok(Action::Print(line)) => {
1703 println!("{line}");
1704 0
1705 }
1706 Ok(Action::PrintConfig(opts)) => {
1707 print!("{}", print_config(&opts));
1708 0
1709 }
1710 Ok(Action::PrintPipeline(opts)) => {
1711 print!("{}", print_pipeline(&opts));
1712 0
1713 }
1714 Ok(Action::PrintPlan { opts, plan, link }) => {
1715 print!("{}", plan.render());
1716 if let Some(job) = &plan.link {
1720 match link_line(&opts, &link, job) {
1721 Ok(line) => println!("{line}"),
1722 Err(why) => {
1723 let mut stderr = std::io::stderr().lock();
1724 let _ = writeln!(stderr, "rucc: error: {why}");
1725 return 1;
1726 }
1727 }
1728 }
1729 0
1730 }
1731 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1732 {
1733 let mut stderr = std::io::stderr().lock();
1734 if verbose {
1735 let _ = write!(stderr, "{}", plan.render());
1736 let _ = writeln!(stderr, "workers: {}", jobs.count());
1737 }
1738 }
1739 if opts.emit == EmitKind::Preprocessed {
1740 return preprocess_all(&opts, &plan);
1741 }
1742 if opts.emit != EmitKind::Executable {
1743 return compile_all(&opts, &plan);
1744 }
1745 link_all(&opts, &plan, &link, verbose)
1746 }
1747 Err(e) => {
1748 let mut stderr = std::io::stderr().lock();
1749 let _ = writeln!(stderr, "rucc: error: {e}");
1750 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1751 1
1752 }
1753 }
1754}
1755
1756#[cfg(test)]
1757mod tests {
1758 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1759
1760 use super::*;
1761
1762 fn args(s: &[&str]) -> Vec<String> {
1763 s.iter().map(|x| (*x).to_owned()).collect()
1764 }
1765
1766 #[test]
1767 fn help_and_version_win_over_everything_else() {
1768 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1769 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1770 }
1771
1772 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1773 match parse_args(&args(s)).expect("expected a compilation") {
1774 Action::Compile { opts, plan, .. } => (opts, plan),
1775 other => panic!("expected a compilation, got {other:?}"),
1776 }
1777 }
1778
1779 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1780 match parse_args(&args(s)).expect("expected a compilation") {
1781 Action::Compile { link, plan, .. } => (link, plan),
1782 other => panic!("expected a compilation, got {other:?}"),
1783 }
1784 }
1785
1786 #[test]
1787 fn collects_inputs_and_flags() {
1788 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1789 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1790 assert_eq!(paths, vec!["a.c", "b.c"]);
1791 assert_eq!(opts.opt_level, OptLevel::O2);
1792 assert_eq!(opts.emit, EmitKind::Object);
1793 assert!(opts.debug_info);
1794 }
1795
1796 #[test]
1799 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1800 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1801 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1802
1803 let (plain, _) = compile(&["-c", "a.c"]);
1804 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1805
1806 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1807 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1808 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1809 }
1810
1811 #[test]
1813 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
1814 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
1815 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
1816
1817 let (plain, _) = compile(&["-c", "a.c"]);
1818 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
1819
1820 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
1821 }
1822
1823 #[test]
1824 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1825 let (opts, _) = compile(&["-O", "a.c"]);
1826 assert_eq!(opts.opt_level, OptLevel::O1);
1827 }
1828
1829 #[test]
1830 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1831 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1832 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1833 assert_eq!(plan.jobs[1].kind, InputKind::C);
1834 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1835 }
1836
1837 #[test]
1838 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1839 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1840 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1841 other => panic!("expected a compilation, got {other:?}"),
1842 };
1843 assert_eq!(jobs.count(), 4);
1844
1845 let default = match parse_args(&args(&["a.c"])).unwrap() {
1846 Action::Compile { jobs, .. } => jobs,
1847 other => panic!("expected a compilation, got {other:?}"),
1848 };
1849 assert_eq!(default, Jobs::available());
1850 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1851 }
1852
1853 #[test]
1854 fn triple_hash_prints_the_plan_and_runs_nothing() {
1855 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1856 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1857 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1858 }
1859
1860 #[test]
1861 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1862 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1866 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1867 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1868 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1869 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1873 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1874 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1875 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1876 }
1877
1878 #[test]
1879 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1880 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1881 let (plain, without) = compile(&["-c", "a.c"]);
1882 assert!(opts.time);
1883 assert!(!plain.time);
1884 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1887 }
1888
1889 #[test]
1890 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1891 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1892 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1893 }
1894
1895 #[test]
1896 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1897 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1898 assert!(e.message.contains("unknown option"), "{}", e.message);
1899 }
1900
1901 #[test]
1904 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1905 let (opts, _) = compile(&["-c", "a.c"]);
1906 assert!(!opts.permissive, "off unless it is asked for");
1907
1908 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1909 assert!(opts.permissive);
1910
1911 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1912 assert!(!opts.permissive);
1913 }
1914
1915 #[test]
1916 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1917 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1918 assert!(e.message.contains("trampoline"), "{}", e.message);
1919 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1920 }
1921
1922 #[test]
1923 fn the_flag_every_configure_script_writes_is_taken() {
1924 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1927 let (opts, _) = compile(&["-c", flag, "a.c"]);
1928 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1929 }
1930 }
1931
1932 #[test]
1933 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1934 let (opts, _) = compile(&["-c", "a.c"]);
1935 assert!(opts.unwinds(), "the default is off");
1936 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1937 assert!(!opts.unwinds(), "the build was not taken at its word");
1938 let (opts, _) = compile(&[
1939 "-c",
1940 "-fno-asynchronous-unwind-tables",
1941 "-fasynchronous-unwind-tables",
1942 "a.c",
1943 ]);
1944 assert!(opts.unwinds(), "the last flag did not win");
1945 let (opts, _) =
1949 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1950 assert!(opts.unwinds(), "the weaker request was dropped");
1951 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
1952 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
1953 let (opts, _) =
1954 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
1955 assert!(!opts.unwinds(), "both were turned off and one stayed on");
1956 }
1957
1958 #[test]
1959 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1960 for flag in [
1964 "-fno-common",
1965 "-fstrict-aliasing",
1966 "-fno-strict-aliasing",
1967 "-pipe",
1968 "-fdiagnostics-color",
1969 "-fno-diagnostics-color",
1970 "-fdiagnostics-color=always",
1971 "-fdiagnostics-color=never",
1972 "-fdiagnostics-color=auto",
1973 ] {
1974 let (opts, _) = compile(&["-c", flag, "a.c"]);
1975 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1976 }
1977 }
1978
1979 #[test]
1980 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1981 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1984 assert!(e.message.contains(".bss"), "{}", e.message);
1985 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1986 }
1987
1988 #[test]
1989 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1990 for flag in ["-fno-pic", "-fno-pie"] {
1991 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1992 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1993 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1996 }
1997 }
1998
1999 #[test]
2000 fn an_unsupported_target_names_itself() {
2001 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
2002 assert!(e.message.contains("sparc64"), "{}", e.message);
2003 }
2004
2005 #[test]
2006 fn no_inputs_is_an_error_but_print_config_needs_none() {
2007 assert!(parse_args(&args(&[])).is_err());
2008 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
2009 }
2010
2011 #[test]
2012 fn print_config_reports_the_target_it_was_given_not_the_host() {
2013 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
2014 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
2015 let text = print_config(&opts);
2016 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
2017 assert!(text.contains("char-signed: false"), "{text}");
2018 assert!(text.contains("object-format: elf"), "{text}");
2019 assert!(text.contains("va-list: void-pointer"), "{text}");
2020 assert!(text.contains("registers: none"), "{text}");
2023 }
2024
2025 #[test]
2026 fn print_config_has_one_key_per_line_and_a_fixed_order() {
2027 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
2028 let text = print_config(&opts);
2029 let keys: Vec<&str> =
2030 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
2031 assert_eq!(keys[0], "version");
2032 assert_eq!(keys[1], "target");
2033 assert_eq!(keys.len(), 24);
2034 assert!(text.ends_with('\n'));
2035 }
2036
2037 #[test]
2038 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
2039 let (opts, _) = compile(&["a.c"]);
2040 assert_eq!(opts.safety, rucc_session::Safety::Off);
2041
2042 for (flag, tier) in [
2043 ("-fsafety=detect", rucc_session::Safety::Detect),
2044 ("-fsafety=enforce", rucc_session::Safety::Enforce),
2045 ("-fsafety=kernel", rucc_session::Safety::Kernel),
2046 ("-fsafety=off", rucc_session::Safety::Off),
2047 ] {
2048 let (opts, _) = compile(&[flag, "a.c"]);
2049 assert_eq!(opts.safety, tier, "{flag}");
2050 }
2051
2052 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
2054 assert_eq!(opts.safety, rucc_session::Safety::Off);
2055
2056 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
2059 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
2060 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
2061 }
2062
2063 #[test]
2064 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
2065 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2066 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2067 let text = print_pipeline(&opts);
2068 assert!(text.starts_with("level: -O2\n"), "{text}");
2069 assert!(text.contains("fold"), "{text}");
2070
2071 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
2072 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2073 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
2076
2077 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
2078 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2079 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2082 }
2083
2084 #[test]
2085 fn print_pipeline_takes_the_toggles_into_account() {
2086 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
2087 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2088 let text = print_pipeline(&opts);
2089 assert!(!text.contains("fold"), "{text}");
2092 assert!(text.contains("dce"), "{text}");
2093
2094 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
2098 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
2099 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
2100 let a = parse_args(&args(&spelled)).unwrap();
2101 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2102 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2103 }
2104
2105 #[test]
2106 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
2107 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2108 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2109 assert!(!print_pipeline(&opts).contains("global fuel"));
2110
2111 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2112 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2113 let text = print_pipeline(&opts);
2114 assert!(text.contains("global fuel: 4"), "{text}");
2117 }
2118
2119 #[test]
2122 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2123 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2124 assert_eq!(
2125 opts.passes,
2126 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2127 );
2128
2129 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2130 assert!(e.message.contains("unknown option"), "{}", e.message);
2131 }
2132
2133 #[test]
2134 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2135 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2136 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2137
2138 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2139 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2140 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2141 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2142 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2143 assert!(e.message.contains("not a number"), "{}", e.message);
2144 }
2145
2146 #[test]
2147 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2148 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2149 assert_eq!(opts.pass_fuel_global, None);
2150
2151 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2152 assert_eq!(opts.pass_fuel_global, Some(12));
2153 assert!(opts.pass_fuel.is_empty());
2156
2157 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2158 assert!(e.message.contains("not a number"), "{}", e.message);
2159 }
2160
2161 #[test]
2162 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2163 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2164 assert_eq!(
2165 opts.pass_gates,
2166 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2167 "the order is what decides, so it has to survive the parse"
2168 );
2169
2170 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2171 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2172 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2173 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2174 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2175 assert!(e.message.contains("is empty"), "{}", e.message);
2176 }
2177
2178 #[test]
2179 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2180 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2181 let text = print_pipeline(&opts);
2182 assert!(text.contains("fold, "), "{text}");
2183 assert!(text.contains("[off for main]"), "{text}");
2184 }
2185
2186 #[test]
2190 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2191 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2192 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2193
2194 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2195 assert!(e.message.contains("nosuch"), "{}", e.message);
2196 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2197 }
2198
2199 #[test]
2205 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2206 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2207 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2208 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2209
2210 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2211 assert_eq!(opts.opt_info, ["missed-note"]);
2212
2213 let (opts, _) =
2216 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2217 assert_eq!(opts.opt_info, ["missed", "all"]);
2218 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2219
2220 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2221 assert!(e.message.contains("vectorized"), "{}", e.message);
2222 assert!(e.message.contains("`missed`"), "{}", e.message);
2223 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2224 assert!(e.message.contains("no file"), "{}", e.message);
2225 }
2226
2227 #[test]
2228 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2229 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2230 assert!(opts.verify_each);
2231 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2232 }
2233
2234 #[test]
2235 fn dash_o_needs_an_argument() {
2236 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2237 assert_eq!(e.message, "-o requires an argument");
2238 }
2239
2240 #[test]
2241 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2242 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2243 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2244 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2245 }
2246
2247 #[test]
2248 fn the_include_flags_land_on_the_chain_each_one_names() {
2249 let (opts, _) = compile(&[
2252 "-Ii",
2253 "-iquote",
2254 "q",
2255 "-isystem",
2256 "sys",
2257 "-idirafter",
2258 "after",
2259 "--sysroot=/nowhere-at-all",
2260 "a.c",
2261 ]);
2262 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2263 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2266 assert!(!opts.search.dirs()[1].is_system);
2267 assert!(opts.search.dirs()[2].is_system);
2268 }
2269
2270 #[test]
2271 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2272 let (opts, _) = compile(&["a.c"]);
2276 let dirs = opts.search.dirs();
2277 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2278 assert_eq!(ours, Some(0), "{dirs:?}");
2279 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2280 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2281 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2282 }
2283
2284 #[test]
2285 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2286 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2287 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2288 assert_eq!(dirs, ["sys", runtime::DIR]);
2289 }
2290
2291 #[test]
2292 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2293 let (opts, _) =
2294 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2295 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2296 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2297 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2299 assert!(!opts.search.searches_current_dir());
2300 }
2301
2302 #[test]
2303 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2304 let (opts, _) = compile(&[
2305 "-iprefix",
2306 "/tools/",
2307 "-iwithprefix",
2308 "late",
2309 "-iwithprefixbefore",
2310 "early",
2311 "-iprefix",
2312 "/other/",
2313 "-iwithprefix",
2314 "last",
2315 "-nostdinc",
2316 "a.c",
2317 ]);
2318 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2319 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2322 assert!(!opts.search.dirs()[0].is_system);
2323 assert!(opts.search.dirs()[1].is_system);
2324 }
2325
2326 #[test]
2327 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2328 let (opts, _) =
2329 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2330 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2331 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2332 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2333 }
2334
2335 #[test]
2336 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2337 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2338 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2339 assert_eq!(dirs, ["i"]);
2340 }
2341
2342 #[test]
2343 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2344 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2345 assert_eq!(opts.std, Std::C11);
2346 assert!(opts.gnu_extensions);
2347
2348 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2349 assert_eq!(opts.std, Std::C99);
2350 assert!(!opts.gnu_extensions);
2351
2352 let (opts, _) = compile(&["-ansi", "a.c"]);
2353 assert_eq!(opts.std, Std::C89);
2354 assert!(!opts.gnu_extensions);
2355
2356 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2357 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2358 }
2359
2360 #[test]
2361 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2362 let (opts, _) = compile(&["-dM", "a.c"]);
2363 assert!(opts.dumps.macros);
2364
2365 let (opts, _) = compile(&["-dDM", "a.c"]);
2368 assert!(opts.dumps.macros);
2369 let (opts, _) = compile(&["-dD", "a.c"]);
2370 assert!(!opts.dumps.macros);
2371
2372 let (opts, _) = compile(&["a.c"]);
2373 assert!(!opts.dumps.any());
2374
2375 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2378 }
2379
2380 #[test]
2381 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2382 let (opts, _) = compile(&["a.c"]);
2383 assert_eq!(
2384 opts.gnuc,
2385 GnucVersion { major: 7, minor: 0, patch: 0 },
2386 "the lowest claim a modern glibc gives its own declarations to"
2387 );
2388
2389 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2390 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2391
2392 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2395 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2396
2397 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2398 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2399
2400 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2401 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2402
2403 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2404 assert!(e.message.contains("more than three"), "{}", e.message);
2405 }
2406
2407 #[test]
2408 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2409 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2410 assert!(opts.pedantic);
2411 assert_eq!(opts.std, Std::C17);
2412
2413 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2416 assert!(opts.pedantic);
2417
2418 let (opts, _) = compile(&["-std=c17", "a.c"]);
2419 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2420 }
2421
2422 #[test]
2423 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2424 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2425 assert!(!opts.line_markers);
2426 assert!(!opts.hosted);
2427 assert_eq!(opts.emit, EmitKind::Preprocessed);
2428 }
2429
2430 #[test]
2437 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2438 let (opts, _) = compile(&["-c", "a.c"]);
2439 assert!(opts.builtins, "a library name means the library function by default");
2440 assert!(opts.no_builtin.is_empty());
2441
2442 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2443 assert!(!opts.builtins);
2444
2445 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2446 assert!(opts.builtins, "the last mention decides");
2447
2448 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2449 assert!(opts.builtins, "one name is not the family");
2450 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2451 }
2452
2453 #[test]
2461 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2462 let (opts, _) = compile(&["-c", "a.c"]);
2463 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2464
2465 for (written, wanted) in [
2466 ("default", Visibility::Default),
2467 ("hidden", Visibility::Hidden),
2468 ("internal", Visibility::Hidden),
2469 ("protected", Visibility::Protected),
2470 ] {
2471 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2472 assert_eq!(opts.visibility, wanted, "{written}");
2473 }
2474
2475 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2478 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2479
2480 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2484 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2485 }
2486
2487 #[test]
2495 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
2496 let (opts, _) = compile(&["-c", "a.c"]);
2497 assert!(!opts.function_sections, "one text section unless something says otherwise");
2498 assert!(!opts.data_sections);
2499
2500 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
2501 assert!(opts.function_sections);
2502 assert!(!opts.data_sections, "one flag is not the other");
2503
2504 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
2505 assert!(opts.data_sections);
2506 assert!(!opts.function_sections);
2507
2508 let (opts, _) = compile(&[
2511 "-c",
2512 "-ffunction-sections",
2513 "-fno-function-sections",
2514 "-fdata-sections",
2515 "-fno-data-sections",
2516 "a.c",
2517 ]);
2518 assert!(!opts.function_sections, "the last mention decides");
2519 assert!(!opts.data_sections, "the last mention decides");
2520 }
2521
2522 #[test]
2525 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2526 let (opts, _) = compile(&["-c", "a.c"]);
2527 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2528
2529 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2530 assert!(opts.gnu89_inline);
2531
2532 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2533 assert!(!opts.gnu89_inline, "the last mention decides");
2534
2535 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2540 assert!(!opts.gnu89_inline);
2541 }
2542
2543 #[test]
2546 fn the_two_frame_flags_are_read_in_both_directions() {
2547 let (opts, _) = compile(&["-c", "a.c"]);
2548 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2549 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2550
2551 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2552 assert!(opts.frame_pointer);
2553 assert!(!opts.red_zone);
2554
2555 let (opts, _) = compile(&[
2556 "-c",
2557 "-fno-omit-frame-pointer",
2558 "-fomit-frame-pointer",
2559 "-mno-red-zone",
2560 "-mred-zone",
2561 "a.c",
2562 ]);
2563 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2564 assert!(opts.red_zone);
2565 }
2566
2567 #[test]
2570 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
2571 let (opts, _) = compile(&["-c", "a.c"]);
2572 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
2573
2574 for (flag, want) in [
2575 ("-fstack-protector", Protector::Buffers),
2576 ("-fstack-protector-strong", Protector::Strong),
2577 ("-fstack-protector-all", Protector::All),
2578 ] {
2579 let (opts, _) = compile(&["-c", flag, "a.c"]);
2580 assert_eq!(opts.protector, want, "{flag}");
2581 }
2582
2583 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
2586 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
2587 assert_eq!(opts.protector, Protector::None, "{off}");
2588 }
2589 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
2590 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
2591 }
2592
2593 #[test]
2596 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
2597 let (opts, _) = compile(&["-c", "a.c"]);
2598 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
2599
2600 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
2601 assert!(opts.stack_clash);
2602
2603 let (opts, _) =
2606 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
2607 assert!(!opts.stack_clash);
2608 let (opts, _) =
2609 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
2610 assert!(opts.stack_clash, "the last one wins either way round");
2611
2612 let (opts, _) =
2614 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
2615 assert!(opts.stack_clash);
2616 assert_eq!(opts.protector, Protector::Strong);
2617 }
2618
2619 #[test]
2623 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
2624 let (opts, _) = compile(&["-c", "a.c"]);
2625 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
2626
2627 for (arg, want) in [
2628 ("-fcf-protection", Control::Full),
2629 ("-fcf-protection=full", Control::Full),
2630 ("-fcf-protection=branch", Control::Branch),
2631 ("-fcf-protection=return", Control::Return),
2632 ("-fcf-protection=none", Control::None),
2633 ("-fcf-protection=check", Control::Check),
2634 ] {
2635 let (opts, _) = compile(&["-c", arg, "a.c"]);
2636 assert_eq!(opts.control, want, "{arg}");
2637 }
2638
2639 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
2642 assert_eq!(opts.control, Control::None);
2643 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
2644 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
2645 }
2646
2647 #[test]
2657 fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
2658 let (opts, _) = compile(&["-c", "a.c"]);
2659 assert!(!opts.profile);
2660 assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
2661
2662 for arg in ["-pg", "-p"] {
2663 let (opts, _) = compile(&["-c", arg, "a.c"]);
2664 assert!(opts.profile, "{arg}");
2665 let (link, _) = linking(&[arg, "a.c"]);
2666 assert!(link.profile, "{arg} changes the link as well");
2667 }
2668
2669 for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
2670 let (opts, _) = compile(&["-c", arg, "a.c"]);
2671 assert_eq!(opts.hook, want, "{arg}");
2672 assert!(!opts.profile, "{arg} asks for no call of its own");
2673 }
2674
2675 let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
2676 assert_eq!(opts.hook, Hook::Late, "the last one wins");
2677 assert!(opts.profile);
2678 }
2679
2680 #[test]
2686 fn a_control_flow_protection_nothing_means_is_refused() {
2687 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
2688 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
2689 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
2690 }
2691
2692 #[test]
2693 fn the_link_flags_are_collected_apart_from_the_compilation() {
2694 let (link, _) = linking(&[
2695 "-static",
2696 "-nostartfiles",
2697 "-rdynamic",
2698 "-s",
2699 "-fuse-ld=mold",
2700 "-L/opt/lib",
2701 "-B",
2702 "/opt/tools",
2703 "a.c",
2704 ]);
2705 assert!(link.is_static);
2706 assert!(link.no_startfiles);
2707 assert!(link.export_dynamic);
2708 assert!(link.strip);
2709 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2710 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2711 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2712 }
2713
2714 #[test]
2715 fn a_comma_in_dash_wl_separates_two_arguments() {
2716 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2717 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2718 }
2719
2720 #[test]
2721 fn a_library_keeps_its_place_between_the_objects() {
2722 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2727 let link = plan.link.expect("expected a link step");
2728 assert_eq!(
2729 link.inputs,
2730 vec![
2731 link::Item::File("a.o".into()),
2732 link::Item::Library("m".into()),
2733 link::Item::File("b.o".into()),
2734 ]
2735 );
2736 assert_eq!(plan.jobs.len(), 2);
2738 }
2739
2740 #[test]
2741 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2742 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2743 assert!(plan.link.is_none());
2744 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2745 }
2746
2747 #[test]
2748 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2749 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2750 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2751 }
2752
2753 fn printed(s: &[&str]) -> String {
2754 match parse_args(&args(s)).expect("expected an answer") {
2755 Action::Print(line) => line,
2756 other => panic!("expected an answer, got {other:?}"),
2757 }
2758 }
2759
2760 fn refused(s: &[&str]) -> String {
2761 parse_args(&args(s)).expect_err("expected a refusal").message
2762 }
2763
2764 #[test]
2765 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2766 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2770 assert!(!opts.warnings_are_errors);
2771 assert!(opts.warnings);
2772 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2774 assert!(opts.warnings_are_errors);
2775 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2776 assert!(!opts.warnings);
2777 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2778 assert!(opts.pedantic && opts.warnings_are_errors);
2779 }
2780
2781 #[test]
2782 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2783 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2785 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2786 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2787 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2788 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2789 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2790 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2793 assert!(no32.contains("32 bit target"), "{no32}");
2794 }
2795
2796 #[test]
2797 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2798 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2799 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2800 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2801 }
2802
2803 #[test]
2804 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2805 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2806 let (opts, _) =
2807 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2808 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2809 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2810 assert!(wrong.contains("sysv convention"), "{wrong}");
2811 }
2812
2813 #[test]
2814 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2815 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2816 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2817 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2820 assert_eq!(names, vec!["a.c"]);
2821 }
2822
2823 #[test]
2824 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2825 let target = "--target=x86_64-unknown-linux-gnu";
2826 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2827 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2828 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2829 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2830 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2833 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2834 let dirs = printed(&[target, "-print-search-dirs"]);
2835 assert!(dirs.starts_with("install: "), "{dirs}");
2836 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2837 }
2838
2839 #[test]
2840 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2841 let (opts, _) = compile(&["-M", "a.c"]);
2842 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2843 assert!(opts.deps.system_headers, "plain -M lists them");
2844 assert_eq!(opts.emit, EmitKind::Preprocessed);
2845
2846 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2849 assert_eq!(opts.emit, EmitKind::Preprocessed);
2850
2851 let (opts, _) = compile(&["-MM", "a.c"]);
2852 assert!(!opts.deps.system_headers);
2853 }
2854
2855 #[test]
2856 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2857 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2858 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2859 assert!(opts.deps.system_headers);
2860 assert_eq!(opts.emit, EmitKind::Object);
2861
2862 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2863 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2864 assert!(!opts.deps.system_headers);
2865 }
2866
2867 #[test]
2868 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2869 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2872 assert!(!opts.deps.system_headers);
2873 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2874 assert!(!opts.deps.system_headers);
2875 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2876 assert!(!opts.deps.system_headers);
2877 }
2878
2879 #[test]
2880 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2881 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2882 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2883 }
2884
2885 #[test]
2886 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2887 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2888 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2889 assert!(opts.deps.phony);
2890
2891 for flag in ["-MF", "-MT", "-MQ"] {
2892 let e = parse_args(&args(&[flag])).unwrap_err();
2893 assert!(e.message.contains("requires an argument"), "{}", e.message);
2894 }
2895 }
2896
2897 struct TempTree(PathBuf);
2899
2900 impl Drop for TempTree {
2901 fn drop(&mut self) {
2902 let _ = std::fs::remove_dir_all(&self.0);
2903 }
2904 }
2905
2906 impl TempTree {
2907 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2908 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2909 let _ = std::fs::remove_dir_all(&dir);
2910 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2911 for (path, text) in files {
2912 let at = dir.join(path);
2913 if let Some(parent) = at.parent() {
2914 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2915 }
2916 std::fs::write(&at, text).expect("writing a temporary file should work");
2917 }
2918 TempTree(dir)
2919 }
2920
2921 fn path(&self, name: &str) -> String {
2922 self.0.join(name).to_string_lossy().into_owned()
2923 }
2924 }
2925
2926 #[test]
2927 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2928 let tree = TempTree::new(
2932 "found",
2933 &[
2934 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2935 ("one.h", "#define X 0\n"),
2936 ("two.h", "#include \"one.h\"\n"),
2937 ],
2938 );
2939 let out = tree.path("dep.d");
2940 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2941 assert_eq!(code, 0);
2942
2943 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2944 let names: Vec<&str> = text.split_whitespace().collect();
2945 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2947 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2948 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2949 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2952 }
2953
2954 #[test]
2955 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2956 let tree = TempTree::new(
2959 "guarded",
2960 &[
2961 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2962 ("g.h", "#ifndef G\n#define G\n#endif\n"),
2963 ],
2964 );
2965 let out = tree.path("dep.d");
2966 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2967 assert_eq!(code, 0);
2968 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2969 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2970 }
2971
2972 #[test]
2973 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2974 let tree = TempTree::new(
2979 "preinclude",
2980 &[
2981 ("a.c", "int main(void) { return 0; }\n"),
2982 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2983 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2984 ],
2985 );
2986 let out = tree.path("a.i");
2987 let code = run(&args(&[
2988 "-E",
2989 "-include",
2990 &tree.path("i.h"),
2991 "-imacros",
2992 &tree.path("m.h"),
2993 "-o",
2994 &out,
2995 &tree.path("a.c"),
2996 ]));
2997 assert_eq!(code, 0);
2998 let text = std::fs::read_to_string(&out).expect("the output should have been written");
2999 assert!(text.contains("saw_it"), "{text}");
3000 assert!(!text.contains("macros_text"), "{text}");
3003 }
3004
3005 #[test]
3006 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
3007 let tree = TempTree::new(
3008 "preinclude-deps",
3009 &[
3010 ("a.c", "int main(void) { return 0; }\n"),
3011 ("i.h", "int from_include;\n"),
3012 ("m.h", "#define M 1\n"),
3013 ],
3014 );
3015 let out = tree.path("dep.d");
3016 let code = run(&args(&[
3017 "-MM",
3018 "-MF",
3019 &out,
3020 "-include",
3021 &tree.path("i.h"),
3022 "-imacros",
3023 &tree.path("m.h"),
3024 "-o",
3025 &tree.path("a.i"),
3026 &tree.path("a.c"),
3027 ]));
3028 assert_eq!(code, 0);
3029 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
3030 assert!(text.contains("i.h"), "{text}");
3031 assert!(text.contains("m.h"), "{text}");
3032 }
3033
3034 #[test]
3035 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
3036 let tree = TempTree::new(
3040 "preinclude-missing",
3041 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
3042 );
3043 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
3044 assert_eq!(code, 1);
3045 }
3046
3047 #[test]
3048 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
3049 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
3053 assert_eq!(plan.output.as_deref(), Some("prog"));
3054 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
3055 assert_eq!(
3056 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
3057 Some("prog.d")
3058 );
3059 }
3060
3061 #[test]
3062 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
3063 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
3064 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
3065 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
3066 assert_eq!(plan.output, None);
3067 }
3068
3069 #[test]
3070 fn usage_fits_on_a_screen() {
3071 assert!(USAGE.lines().count() < 52, "usage text has grown past one screen");
3098 }
3099}