1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.16")]
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 Wrapping, 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 -fpatchable-function-entry=<n>[,<m>] room at the top of every function to patch later
189 -fwrapv, -fwrapv-pointer, -fno-strict-overflow signed or pointer overflow wraps
190 -pthread build for more than one thread, and link the library for it
191 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
192 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
193 -j[n] compile n translation units at once, default all
194 -v, -### print each phase as it runs, or without running any
195 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
196 --target=<triple> generate code for <triple>
197 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
198 safety-summary, type-granules
199 --print-config, --print-pipeline print the configuration or the pipeline, and exit
200 --version print the version and exit
201 -h, --help print this message and exit
202
203See spec/04-driver-and-cli.md for the full flag reference.
204";
205
206fn joined_or_next(
210 arg: &str,
211 at: usize,
212 args: &[String],
213 i: &mut usize,
214) -> Result<String, CliError> {
215 if arg.len() > at {
216 return Ok(arg[at..].to_owned());
217 }
218 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
219 *i += 1;
220 Ok(next.clone())
221}
222
223pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
230 let host = Triple::host()
231 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
232 let mut opts = Options::new(host);
233 let mut inputs: Vec<Input> = Vec::new();
234 let mut print_config = false;
235 let mut print_pipeline = false;
236 let mut print_plan = false;
237 let mut verbose = false;
238 let mut jobs = Jobs::default();
239 let mut nostdinc = false;
240 let mut sysroot: Option<PathBuf> = None;
241 let mut output = None;
242 let mut link = LinkOptions::default();
243 let mut query: Option<Query> = None;
244 let mut threads = false;
245 let mut forced: Option<InputKind> = None;
248 let mut iprefix = String::new();
255
256 let mut i = 0;
257 while i < args.len() {
258 let arg = args[i].as_str();
259 i += 1;
260 match arg {
261 "-h" | "--help" => return Ok(Action::Help),
262 "--version" => return Ok(Action::Version),
263 "--print-config" => print_config = true,
264 "--print-pipeline" => print_pipeline = true,
265 "-###" => print_plan = true,
266 "-v" => verbose = true,
267 "-save-temps" => opts.save_temps = SaveTemps::Object,
271 _ if arg.starts_with("-save-temps=") => {
272 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
273 }
274 "-time" => opts.time = true,
277 "-c" => opts.emit = EmitKind::Object,
278 "-S" => opts.emit = EmitKind::Asm,
279 "-E" => opts.emit = EmitKind::Preprocessed,
280 "-g" => opts.debug_info = true,
281 "-g0" => opts.debug_info = false,
286 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
287 opts.debug_info = true;
288 }
289 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
292 _ if arg.starts_with("-gdwarf-") => {
293 return Err(err(format!(
294 "{arg}: this compiler writes DWARF 5 and no other version, see \
295 spec/11-debug-info.md"
296 )));
297 }
298 "-Werror" => opts.warnings_are_errors = true,
299 "-w" => opts.warnings = false,
302 "-pedantic-errors" => {
303 opts.pedantic = true;
304 opts.warnings_are_errors = true;
305 }
306 "-P" => opts.line_markers = false,
307 "-M" => {
314 opts.deps.emit = true;
315 opts.deps.instead_of_compiling = true;
316 }
317 "-MM" => {
318 opts.deps.emit = true;
319 opts.deps.instead_of_compiling = true;
320 opts.deps.system_headers = false;
321 }
322 "-MD" => opts.deps.emit = true,
323 "-MMD" => {
324 opts.deps.emit = true;
325 opts.deps.system_headers = false;
326 }
327 "-MP" => opts.deps.phony = true,
328 "-MF" | "-MT" | "-MQ" => {
331 let value =
332 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
333 i += 1;
334 match arg {
335 "-MF" => opts.deps.file = Some(value.clone()),
336 "-MT" => opts.deps.targets.push(value.clone()),
340 _ => opts.deps.targets.push(deps::escaped(value)),
341 }
342 }
343 "-dumpmachine" => query = Some(Query::Machine),
347 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
348 "-print-multiarch" => query = Some(Query::Multiarch),
349 "-print-search-dirs" => query = Some(Query::SearchDirs),
350 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
351 _ if arg.starts_with("-print-file-name=") => {
352 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
353 }
354 _ if arg.starts_with("-print-prog-name=") => {
355 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
356 }
357 "-pthread" | "-pthreads" => {
362 opts.defines.push("_REENTRANT".to_owned());
363 threads = true;
364 }
365 "-ansi" => {
366 opts.std = Std::C89;
367 opts.gnu_extensions = false;
368 }
369 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
372 "-fpermissive" => opts.permissive = true,
375 "-fno-permissive" => opts.permissive = false,
376 "-ffreestanding" => opts.hosted = false,
377 "-fhosted" => opts.hosted = true,
378 "-fno-builtin" => opts.builtins = false,
379 "-fbuiltin" => opts.builtins = true,
380 "-fgnu89-inline" => opts.gnu89_inline = true,
384 "-fno-gnu89-inline" => opts.gnu89_inline = false,
385 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
388 "-fomit-frame-pointer" => opts.frame_pointer = false,
389 "-mno-red-zone" => opts.red_zone = false,
390 "-mred-zone" => opts.red_zone = true,
391 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
396 opts.protector = Protector::None;
397 }
398 "-fstack-protector" => opts.protector = Protector::Buffers,
399 "-fstack-protector-strong" => opts.protector = Protector::Strong,
400 "-fstack-protector-all" => opts.protector = Protector::All,
401 "-fstack-clash-protection" => opts.stack_clash = true,
404 "-fno-stack-clash-protection" => opts.stack_clash = false,
405 "-fcf-protection" => opts.control = Control::Full,
409 "-fno-cf-protection" => opts.control = Control::None,
410 "-pg" | "-p" => {
414 opts.profile = true;
415 link.profile = true;
416 }
417 "-mfentry" => opts.hook = Hook::Early,
422 "-mno-fentry" => opts.hook = Hook::Late,
423 "-nostdinc" => nostdinc = true,
427 "-o" => {
428 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
429 i += 1;
430 }
431 "-isysroot" => {
438 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
439 i += 1;
440 sysroot = Some(PathBuf::from(dir));
441 }
442 "-iquote" | "-isystem" | "-idirafter" => {
443 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
444 i += 1;
445 match arg {
446 "-iquote" => opts.search.push_quote(dir.clone()),
447 "-isystem" => opts.search.push_system(dir.clone()),
448 _ => opts.search.push_after(dir.clone()),
449 }
450 }
451 "-iprefix" => {
452 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
453 i += 1;
454 }
455 "-iwithprefix" | "-iwithprefixbefore" => {
461 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
462 i += 1;
463 let dir = format!("{iprefix}{dir}");
464 if arg == "-iwithprefix" {
465 opts.search.push_system(dir);
466 } else {
467 opts.search.push_bracket(dir);
468 }
469 }
470 "-include" | "-imacros" => {
471 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
472 i += 1;
473 opts.preincludes
474 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
475 }
476 "-I-" => opts.search.split_quote_chain(),
481 "-x" => {
482 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
483 i += 1;
484 forced = if lang == "none" {
485 None
486 } else {
487 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
488 };
489 }
490 _ if arg.starts_with("-D") => {
498 let value = joined_or_next(arg, 2, args, &mut i)?;
499 opts.defines.push(value);
500 }
501 _ if arg.starts_with("-U") => {
502 let value = joined_or_next(arg, 2, args, &mut i)?;
503 opts.undefines.push(value);
504 }
505 _ if arg.starts_with("-I") => {
506 let dir = joined_or_next(arg, 2, args, &mut i)?;
507 opts.search.push_bracket(dir);
508 }
509 _ if arg.starts_with("-std=") => {
510 let name = &arg["-std=".len()..];
511 let (std, gnu) = Std::from_flag(name)
512 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
513 opts.std = std;
514 opts.gnu_extensions = gnu;
515 }
516 _ if Dumps::is_family(arg) => {
525 opts.dumps.add(&arg[2..]);
526 }
527 _ if arg.starts_with("-fno-builtin-") => {
532 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
533 }
534 _ if arg.starts_with("-fgnuc-version=") => {
535 let v = &arg["-fgnuc-version=".len()..];
536 opts.gnuc = v.parse().map_err(err)?;
537 }
538 "-fnested-functions" => {
543 return Err(err(
544 "nested functions are not supported: a call to one goes through a trampoline \
545 written on the stack, which no target that enforces an unexecutable stack \
546 allows",
547 ));
548 }
549 "-fno-nested-functions" => {}
550 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
561 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
565 "-fsemantic-interposition" => opts.interposition = true,
572 "-fno-semantic-interposition" => opts.interposition = false,
573 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
578 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
579 "-funwind-tables" => opts.unwind_tables = true,
580 "-fno-unwind-tables" => opts.unwind_tables = false,
581 "-fno-pic" | "-fno-pie" => {
588 return Err(err(
589 "position dependent code is not supported: an address that may be in another \
590 object is loaded out of the global offset table, and nothing here emits the \
591 absolute form this asks for. Use -no-pie if what you meant was how to link",
592 ));
593 }
594 "-ffunction-sections" => opts.function_sections = true,
600 "-fno-function-sections" => opts.function_sections = false,
601 "-fdata-sections" => opts.data_sections = true,
602 "-fno-data-sections" => opts.data_sections = false,
603 "-fno-common" => {}
609 "-fwrapv" => opts.wrapping.signed = true,
617 "-fno-wrapv" => opts.wrapping.signed = false,
618 "-fwrapv-pointer" => opts.wrapping.pointer = true,
619 "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
620 "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
621 "-fstrict-overflow" => opts.wrapping = Wrapping::NONE,
622 "-fcommon" => {
626 return Err(err(
627 "a tentative definition is written into .bss as its own symbol here, and \
628 nothing emits the common symbol this asks the linker to merge. Give the \
629 variable a definition in one file and declare it extern in the others",
630 ));
631 }
632 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
646 "-pipe" => {}
649 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
656 _ if arg.starts_with("-fdiagnostics-color=") => {}
657 "-static" => link.is_static = true,
661 "-shared" => link.shared = true,
662 "-pie" => link.pie = Some(true),
663 "-no-pie" | "-nopie" => link.pie = Some(false),
664 "-nostdlib" => link.no_stdlib = true,
665 "-nostartfiles" => link.no_startfiles = true,
666 "-nodefaultlibs" => link.no_defaultlibs = true,
667 "-fno-builtins-lib" => link.no_builtins_lib = true,
668 "-fbuiltins-lib" => link.no_builtins_lib = false,
669 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
670 "-s" => link.strip = true,
671 "-Xlinker" => {
672 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
673 i += 1;
674 link.passthrough.push(next.clone());
675 }
676 _ if arg.starts_with("-Wl,") => {
677 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
680 }
681 _ if arg.starts_with("-fuse-ld=") => {
682 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
683 }
684 _ if arg.starts_with("-l") && arg.len() > 2 => {
685 inputs.push(Input::library(&arg[2..]));
686 }
687 "-l" => {
688 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
689 i += 1;
690 inputs.push(Input::library(next));
691 }
692 _ if arg.starts_with("-L") => {
693 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
694 }
695 _ if arg.starts_with("-B") => {
696 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
697 }
698 _ if arg.starts_with("-j") => {
699 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
700 }
701 _ if arg.starts_with("--sysroot=") => {
702 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
703 }
704 _ if arg.starts_with("--target=") => {
705 let t = &arg["--target=".len()..];
706 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
707 }
708 _ if arg.starts_with("--emit=") => {
709 let k = &arg["--emit=".len()..];
710 opts.emit = k
711 .parse()
712 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
713 }
714 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
720 "-Ofast" => {
726 return Err(err(
727 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
728 spec/04-driver-and-cli.md section 4.6",
729 ));
730 }
731 _ if arg.starts_with("-O") => {
732 opts.opt_level = arg[2..]
733 .parse()
734 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
735 }
736 _ if arg.starts_with("-fvisibility=") => {
740 let seen = &arg["-fvisibility=".len()..];
741 opts.visibility = seen.parse().map_err(|()| {
742 err(format!(
743 "`{seen}` is not a visibility, which is default, hidden, internal or \
744 protected"
745 ))
746 })?;
747 }
748 _ if arg.starts_with("-fcf-protection=") => {
752 let edges = &arg["-fcf-protection=".len()..];
753 opts.control = edges.parse().map_err(|()| {
754 err(format!(
755 "`{edges}` is not a control flow protection, which is full, branch, \
756 return, none or check"
757 ))
758 })?;
759 }
760 _ if arg.starts_with("-fpatchable-function-entry=") => {
763 let room = &arg["-fpatchable-function-entry=".len()..];
764 opts.patchable = room.parse().map_err(|()| {
765 err(format!(
766 "`{room}` is not an amount of room to reserve, which is a number of bytes and then, after a comma, how many of them go in front of the function's own label"
767 ))
768 })?;
769 }
770 _ if arg.starts_with("-fsafety=") => {
775 let tier = &arg["-fsafety=".len()..];
776 opts.safety = tier.parse().map_err(|()| {
777 err(format!(
778 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
779 ))
780 })?;
781 }
782 _ if arg.starts_with("-fpass-fuel=") => {
786 let (name, count) = arg["-fpass-fuel=".len()..]
787 .split_once('=')
788 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
789 if rucc_opt::pass::find(name).is_none() {
790 return Err(err(format!(
791 "`{name}` is not a pass this compiler has, see --print-pipeline"
792 )));
793 }
794 let count: u32 = count
795 .parse()
796 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
797 opts.pass_fuel.push((name.to_owned(), count));
798 }
799 _ if arg.starts_with("-fpass-fuel-global=") => {
800 let count = &arg["-fpass-fuel-global=".len()..];
801 let count: u32 = count
802 .parse()
803 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
804 opts.pass_fuel_global = Some(count);
805 }
806 _ if arg == "-fopt-info"
811 || arg.starts_with("-fopt-info=")
812 || arg.starts_with("-fopt-info-") =>
813 {
814 let rest = &arg["-fopt-info".len()..];
815 let (kinds, file) = match rest.split_once('=') {
816 Some((kinds, file)) => (kinds, Some(file)),
817 None => (rest, None),
818 };
819 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
820 rucc_opt::Wants::none().add(kinds).map_err(err)?;
821 opts.opt_info.push(kinds.to_owned());
822 if let Some(file) = file {
823 if file.is_empty() {
824 return Err(err("-fopt-info= was given no file to write to"));
825 }
826 opts.opt_info_file = Some(file.to_owned());
827 }
828 }
829 _ if arg.starts_with("-fdump-ir=") => {
830 let spec = &arg["-fdump-ir=".len()..];
833 rucc_opt::Dumps::default().add(spec).map_err(err)?;
834 opts.dump_ir.push(spec.to_owned());
835 }
836 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
842 let on = arg.starts_with("-fenable-");
843 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
844 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
845 opts.pass_gates.push((on, spec.to_owned()));
846 }
847 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
848 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
849 }
850 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
851 opts.passes.push((arg["-f".len()..].to_owned(), true));
852 }
853 "-Zverify-each" => opts.verify_each = true,
859 _ if arg.starts_with("-Zrule-coverage=") => {
860 let file = &arg["-Zrule-coverage=".len()..];
861 if file.is_empty() {
862 return Err(err("-Zrule-coverage= needs a file to write to"));
863 }
864 opts.rule_coverage = Some(file.to_owned());
865 }
866 _ if arg.starts_with("-Zregister-pressure=") => {
867 let file = &arg["-Zregister-pressure=".len()..];
868 if file.is_empty() {
869 return Err(err("-Zregister-pressure= needs a file to write to"));
870 }
871 opts.register_pressure = Some(file.to_owned());
872 }
873 _ if arg.starts_with("-Z") => {
874 return Err(err(format!(
875 "`{arg}` is not an unstable option this compiler has, see \
876 spec/04-driver-and-cli.md section 4.11 for the ones it does"
877 )));
878 }
879 "-m64" | "-m32" | "-mx32" => {
884 let want: u32 = match arg {
885 "-m64" => 64,
886 _ => 32,
887 };
888 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
889 if have != want {
890 return Err(err(format!(
891 "{arg} asks for a {want} bit target and {} is {have} bit, use \
892 --target= to name the one you mean",
893 opts.target
894 )));
895 }
896 }
897 _ if arg.starts_with("-march=")
903 || arg.starts_with("-mtune=")
904 || arg.starts_with("-mcpu=") => {}
905 _ if arg.starts_with("-mabi=") => {
908 let want = &arg["-mabi=".len()..];
909 let have = match opts.target.arch {
910 rucc_target::Arch::X86_64 => "sysv",
911 rucc_target::Arch::Aarch64 => "lp64",
912 rucc_target::Arch::Riscv64 => "lp64d",
913 };
914 if want != have {
915 return Err(err(format!(
916 "{arg}: {} uses the {have} convention and this compiler has no other",
917 opts.target
918 )));
919 }
920 }
921 "-mcmodel=small" => {}
925 _ if arg.starts_with("-mcmodel=") => {
926 return Err(err(format!(
927 "{arg}: this compiler emits the small code model and no other, see \
928 spec/12-targets.md"
929 )));
930 }
931 _ if arg.starts_with("-specs=") => {
935 return Err(err(
936 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
937 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
938 section 4.4",
939 ));
940 }
941 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
947 return Err(err(format!(
948 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
949 are inside this compiler rather than programs it runs"
950 )));
951 }
952 "-Xassembler" | "-Xpreprocessor" => {
953 return Err(err(format!(
954 "{arg} hands an argument to a separate assembler or preprocessor, and both \
955 are inside this compiler rather than programs it runs"
956 )));
957 }
958 _ if arg.starts_with("-W") => {}
965 "-fno-ident"
971 | "-fident"
972 | "-funit-at-a-time"
973 | "-fno-unit-at-a-time"
974 | "-shared-libgcc"
975 | "-static-libgcc" => {}
976 _ if arg.starts_with('-') && arg.len() > 1 => {
977 return Err(err(format!("unknown option `{arg}`")));
982 }
983 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
984 }
985 }
986
987 link.sysroot = sysroot.clone();
994 if threads {
999 inputs.push(Input::library("pthread"));
1000 }
1001 if let Some(query) = query {
1002 return Ok(Action::Print(answer(&query, &opts, &link)));
1003 }
1004 if opts.deps.instead_of_compiling {
1010 opts.emit = EmitKind::Preprocessed;
1011 }
1012 if !nostdinc {
1013 opts.search.push_system(runtime::DIR);
1014 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
1018 opts.search.push_system(dir);
1019 }
1020 }
1021 opts.search.remove_duplicates();
1025
1026 if print_config {
1029 return Ok(Action::PrintConfig(Box::new(opts)));
1030 }
1031 if print_pipeline {
1032 return Ok(Action::PrintPipeline(Box::new(opts)));
1033 }
1034 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
1035 if print_plan {
1036 return Ok(Action::PrintPlan {
1037 opts: Box::new(opts),
1038 plan: Box::new(plan),
1039 link: Box::new(link),
1040 });
1041 }
1042 Ok(Action::Compile {
1043 opts: Box::new(opts),
1044 plan: Box::new(plan),
1045 link: Box::new(link),
1046 jobs,
1047 verbose,
1048 })
1049}
1050
1051fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
1057 let found = |name: &str| {
1058 link::find_in_search(link, opts.target, name)
1059 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
1060 };
1061 match query {
1062 Query::Machine => opts.target.to_string(),
1063 Query::Version => VERSION.to_owned(),
1064 Query::Multiarch => link::multiarch(opts.target),
1065 Query::SearchDirs => {
1070 let here = std::env::current_exe()
1071 .ok()
1072 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
1073 .unwrap_or_default();
1074 let list = |dirs: &[PathBuf]| {
1075 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
1076 };
1077 let libraries = link::search_dirs(link, opts.target);
1078 format!(
1079 "install: {}\nprograms: ={}\nlibraries: ={}",
1080 here.display(),
1081 list(&link.prefixes),
1082 list(&libraries)
1083 )
1084 }
1085 Query::FileName(name) => found(name),
1086 Query::Libgcc => found("libgcc.a"),
1090 Query::ProgName(name) => link
1094 .prefixes
1095 .iter()
1096 .map(|dir| dir.join(name))
1097 .find(|path| path.is_file())
1098 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1099 }
1100}
1101
1102#[must_use]
1108pub fn print_pipeline(opts: &Options) -> String {
1109 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1110 settings.toggles.clone_from(&opts.passes);
1111 settings.global_fuel = opts.pass_fuel_global;
1112 for (on, spec) in &opts.pass_gates {
1113 let _ = settings.gates.add(*on, spec);
1116 }
1117 rucc_opt::pipeline::print(&settings)
1118}
1119
1120#[must_use]
1125pub fn print_config(opts: &Options) -> String {
1126 let sess = Session::new(opts.clone());
1127 let t = &sess.target;
1128 let mut out = String::new();
1129 let _ = writeln!(out, "version: {VERSION}");
1130 let _ = writeln!(out, "target: {}", opts.target);
1134 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1135 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1136 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1137 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1138 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1139 let _ = writeln!(out, "long-width: {}", t.long_width);
1140 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1141 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1142 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1143 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1144 let regs: Vec<String> = t
1147 .regs
1148 .classes()
1149 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1150 .collect();
1151 let _ = writeln!(
1152 out,
1153 "registers: {}",
1154 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1155 );
1156 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1157 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1158 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1159 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1160 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1161 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1162 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
1163 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
1164 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
1165 let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
1166 let _ = writeln!(out, "profile: {}", sess.opts.profile);
1167 let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
1168 for dir in sess.opts.search.dirs() {
1171 let system = if dir.is_system { " (system)" } else { "" };
1172 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1173 }
1174 out
1175}
1176
1177fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1185 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1186}
1187
1188fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1191 if path == "-" {
1192 return write_out(&Output::Stdout, bytes);
1193 }
1194 write_out(&Output::File(path.to_owned()), bytes)
1195}
1196
1197fn write_deps(
1203 opts: &Options,
1204 plan: &Plan,
1205 job: &Job,
1206 found: &[Dependency],
1207 stderr: &mut impl std::io::Write,
1208) -> bool {
1209 let targets = if opts.deps.targets.is_empty() {
1210 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1211 } else {
1212 opts.deps.targets.clone()
1213 };
1214 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1215 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1218 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1222 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1223 }),
1224 None => write_out(&job.output, rule.as_bytes()),
1225 };
1226 if let Err(e) = wrote {
1227 let _ = writeln!(stderr, "rucc: error: {e}");
1228 return false;
1229 }
1230 true
1231}
1232
1233fn preprocess_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 for job in &plan.jobs {
1243 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1244 continue;
1247 }
1248 let started = std::time::Instant::now();
1249 let result = preprocess(opts, &job.input, &fs);
1250 if opts.time {
1251 say_time(&job.input, started.elapsed(), &mut stderr);
1252 }
1253 for message in &result.messages {
1254 let _ = writeln!(stderr, "{message}");
1255 }
1256 if result.failed() {
1257 failed = true;
1258 continue;
1259 }
1260 if opts.deps.emit {
1261 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1262 if opts.deps.instead_of_compiling {
1265 continue;
1266 }
1267 }
1268 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1269 let _ = writeln!(stderr, "rucc: error: {e}");
1270 failed = true;
1271 }
1272 }
1273 i32::from(failed)
1274}
1275
1276fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1282 let fs = OsFileSystem::new();
1283 let mut stderr = std::io::stderr().lock();
1284 let mut failed = false;
1285 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1286 failed |= !ok;
1287 let mut fired = Fired::new();
1288 let mut pressure = Pressure::new();
1289 for job in &plan.jobs {
1290 if !job.phases.contains(&Phase::Compile) {
1291 continue;
1292 }
1293 let started = std::time::Instant::now();
1297 let result = if job.kind == InputKind::Ir {
1298 compile_ir(opts, &job.input, &fs)
1299 } else {
1300 compile(opts, &job.input, &fs)
1301 };
1302 if opts.time {
1303 say_time(&job.input, started.elapsed(), &mut stderr);
1304 }
1305 fired.merge(&result.fired);
1306 pressure.merge(&result.pressure);
1307 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1308 failed |= !remarks.write(&result.remarks, &mut stderr);
1309 for message in &result.messages {
1310 let _ = writeln!(stderr, "{message}");
1311 }
1312 failed |= !write_temps(job, &result.temps, &mut stderr);
1315 if result.failed() {
1316 failed = true;
1317 continue;
1318 }
1319 if opts.deps.emit {
1324 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1325 }
1326 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1327 let _ = writeln!(stderr, "rucc: error: {e}");
1328 failed = true;
1329 }
1330 }
1331 failed |= !write_coverage(opts, &fired, &mut stderr);
1332 failed |= !write_pressure(opts, &pressure, &mut stderr);
1333 i32::from(failed)
1334}
1335
1336struct Scratch {
1343 dir: PathBuf,
1345}
1346
1347impl Scratch {
1348 fn new() -> Result<Scratch, String> {
1354 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1355 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1356 Ok(Scratch { dir })
1357 }
1358}
1359
1360impl Drop for Scratch {
1361 fn drop(&mut self) {
1362 let _ = std::fs::remove_dir_all(&self.dir);
1363 }
1364}
1365
1366fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1373 let linker = link::find(opts.target, link)?;
1374 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1375 Ok(link::render(&linker, &args))
1376}
1377
1378fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1385 let Some(job) = &plan.link else {
1386 let mut stderr = std::io::stderr().lock();
1389 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1390 return 1;
1391 };
1392 let linker = match link::find(opts.target, link) {
1395 Ok(linker) => linker,
1396 Err(why) => return complain(why),
1397 };
1398
1399 let scratch = match Scratch::new() {
1400 Ok(scratch) => scratch,
1401 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1402 };
1403
1404 let fs = OsFileSystem::new();
1405 let mut failed = false;
1406 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1409 let mut fired = Fired::new();
1410 let mut pressure = Pressure::new();
1411 {
1412 let mut stderr = std::io::stderr().lock();
1413 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1414 failed |= !ok;
1415 for (at, job) in plan.jobs.iter().enumerate() {
1416 let out = match &job.output {
1417 Output::Temporary(hint) => {
1418 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1421 }
1422 Output::File(path) => path.clone(),
1423 Output::Stdout => continue,
1426 };
1427 produced.push(out.clone());
1428 if !job.phases.contains(&Phase::Compile) {
1429 continue;
1430 }
1431 let started = std::time::Instant::now();
1432 let result = if job.kind == InputKind::Ir {
1433 compile_ir(opts, &job.input, &fs)
1434 } else {
1435 compile(opts, &job.input, &fs)
1436 };
1437 if opts.time {
1438 say_time(&job.input, started.elapsed(), &mut stderr);
1439 }
1440 fired.merge(&result.fired);
1441 pressure.merge(&result.pressure);
1442 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1443 failed |= !remarks.write(&result.remarks, &mut stderr);
1444 for message in &result.messages {
1445 let _ = writeln!(stderr, "{message}");
1446 }
1447 failed |= !write_temps(job, &result.temps, &mut stderr);
1448 if result.failed() {
1449 failed = true;
1450 continue;
1451 }
1452 if opts.deps.emit {
1457 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1458 }
1459 if !matches!(result.artifact, Artifact::Object(_)) {
1460 let _ = writeln!(
1465 stderr,
1466 "rucc: internal error: {}: no object file was produced for the link",
1467 job.input
1468 );
1469 failed = true;
1470 continue;
1471 }
1472 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1473 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1474 failed = true;
1475 }
1476 }
1477 failed |= !write_coverage(opts, &fired, &mut stderr);
1478 failed |= !write_pressure(opts, &pressure, &mut stderr);
1479 }
1480 if failed {
1481 return 1;
1485 }
1486
1487 let mut outputs = produced.into_iter();
1491 let mut items = Vec::with_capacity(job.inputs.len());
1492 for item in &job.inputs {
1493 match item {
1494 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1495 link::Item::File(_) => match outputs.next() {
1496 Some(path) => items.push(link::Item::File(path)),
1497 None => return complain("the plan asks the linker for a file nothing produced"),
1498 },
1499 }
1500 }
1501
1502 let args = match link::line(opts.target, link, &items, &job.output) {
1503 Ok(args) => args,
1504 Err(why) => return complain(why),
1505 };
1506 if verbose {
1507 let mut stderr = std::io::stderr().lock();
1508 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1509 }
1510 let started = std::time::Instant::now();
1511 let ran = link::run(&linker, &args);
1512 if opts.time {
1513 let mut stderr = std::io::stderr().lock();
1516 say_time(&linker.name, started.elapsed(), &mut stderr);
1517 }
1518 match ran {
1519 Ok(()) => 0,
1520 Err(link::Error::Refused { .. }) => 1,
1523 Err(why) => complain(why),
1524 }
1525}
1526
1527fn complain(why: impl std::fmt::Display) -> i32 {
1529 let mut stderr = std::io::stderr().lock();
1530 let _ = writeln!(stderr, "rucc: error: {why}");
1531 1
1532}
1533
1534fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1543 let Some(path) = &opts.rule_coverage else { return true };
1544 let Some(table) = coverage::table(opts.target.arch) else {
1545 let _ = writeln!(
1546 stderr,
1547 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1548 to report",
1549 opts.target
1550 );
1551 return false;
1552 };
1553 match std::fs::write(path, fired.listing(table)) {
1554 Ok(()) => true,
1555 Err(e) => {
1556 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1557 false
1558 }
1559 }
1560}
1561
1562fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
1570 let Some(path) = &opts.register_pressure else { return true };
1571 match std::fs::write(path, pressure.listing()) {
1572 Ok(()) => true,
1573 Err(e) => {
1574 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1575 false
1576 }
1577 }
1578}
1579
1580struct Remarks {
1587 file: Option<String>,
1589 started: bool,
1592}
1593
1594impl Remarks {
1595 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1601 let mut ok = true;
1602 if let Some(path) = file {
1603 if let Err(e) = std::fs::write(path, "") {
1604 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1605 ok = false;
1606 }
1607 }
1608 (Self { file: file.cloned(), started: false }, ok)
1609 }
1610
1611 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1617 if text.is_empty() {
1618 return true;
1619 }
1620 let Some(path) = &self.file else {
1621 let _ = write!(stderr, "{text}");
1622 return true;
1623 };
1624 let opened = std::fs::OpenOptions::new()
1625 .write(true)
1626 .append(self.started)
1627 .truncate(!self.started)
1628 .create(true)
1629 .open(path);
1630 self.started = true;
1631 let result =
1632 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1633 if let Err(e) = result {
1634 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1635 return false;
1636 }
1637 true
1638 }
1639}
1640
1641fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1652 let stem = std::path::Path::new(input)
1653 .file_name()
1654 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1655 let mut ok = true;
1656 for dump in dumps {
1657 let path = format!("{stem}.{}.ir", dump.name);
1658 if let Err(e) = std::fs::write(&path, &dump.text) {
1659 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1660 ok = false;
1661 }
1662 }
1663 ok
1664}
1665
1666fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1672 let mut ok = true;
1673 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1674 for (path, text) in kept {
1675 let (Some(path), Some(text)) = (path, text) else { continue };
1678 if let Err(e) = std::fs::write(&path, text) {
1679 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1680 ok = false;
1681 }
1682 }
1683 ok
1684}
1685
1686fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1693 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1694}
1695
1696fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1703 match output {
1704 Output::Stdout => {
1705 let mut stdout = std::io::stdout().lock();
1706 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1707 }
1708 Output::File(path) | Output::Temporary(path) => {
1709 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1710 }
1711 }
1712}
1713
1714pub fn run(args: &[String]) -> i32 {
1719 match parse_args(args) {
1720 Ok(Action::Help) => {
1721 print!("{USAGE}");
1722 0
1723 }
1724 Ok(Action::Version) => {
1725 println!("rucc {VERSION}");
1726 0
1727 }
1728 Ok(Action::Print(line)) => {
1729 println!("{line}");
1730 0
1731 }
1732 Ok(Action::PrintConfig(opts)) => {
1733 print!("{}", print_config(&opts));
1734 0
1735 }
1736 Ok(Action::PrintPipeline(opts)) => {
1737 print!("{}", print_pipeline(&opts));
1738 0
1739 }
1740 Ok(Action::PrintPlan { opts, plan, link }) => {
1741 print!("{}", plan.render());
1742 if let Some(job) = &plan.link {
1746 match link_line(&opts, &link, job) {
1747 Ok(line) => println!("{line}"),
1748 Err(why) => {
1749 let mut stderr = std::io::stderr().lock();
1750 let _ = writeln!(stderr, "rucc: error: {why}");
1751 return 1;
1752 }
1753 }
1754 }
1755 0
1756 }
1757 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1758 {
1759 let mut stderr = std::io::stderr().lock();
1760 if verbose {
1761 let _ = write!(stderr, "{}", plan.render());
1762 let _ = writeln!(stderr, "workers: {}", jobs.count());
1763 }
1764 }
1765 if opts.emit == EmitKind::Preprocessed {
1766 return preprocess_all(&opts, &plan);
1767 }
1768 if opts.emit != EmitKind::Executable {
1769 return compile_all(&opts, &plan);
1770 }
1771 link_all(&opts, &plan, &link, verbose)
1772 }
1773 Err(e) => {
1774 let mut stderr = std::io::stderr().lock();
1775 let _ = writeln!(stderr, "rucc: error: {e}");
1776 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1777 1
1778 }
1779 }
1780}
1781
1782#[cfg(test)]
1783mod tests {
1784 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Patchable, Visibility};
1785
1786 use super::*;
1787
1788 fn args(s: &[&str]) -> Vec<String> {
1789 s.iter().map(|x| (*x).to_owned()).collect()
1790 }
1791
1792 #[test]
1793 fn help_and_version_win_over_everything_else() {
1794 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1795 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1796 }
1797
1798 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1799 match parse_args(&args(s)).expect("expected a compilation") {
1800 Action::Compile { opts, plan, .. } => (opts, plan),
1801 other => panic!("expected a compilation, got {other:?}"),
1802 }
1803 }
1804
1805 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1806 match parse_args(&args(s)).expect("expected a compilation") {
1807 Action::Compile { link, plan, .. } => (link, plan),
1808 other => panic!("expected a compilation, got {other:?}"),
1809 }
1810 }
1811
1812 #[test]
1813 fn collects_inputs_and_flags() {
1814 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1815 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1816 assert_eq!(paths, vec!["a.c", "b.c"]);
1817 assert_eq!(opts.opt_level, OptLevel::O2);
1818 assert_eq!(opts.emit, EmitKind::Object);
1819 assert!(opts.debug_info);
1820 }
1821
1822 #[test]
1825 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1826 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1827 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1828
1829 let (plain, _) = compile(&["-c", "a.c"]);
1830 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1831
1832 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1833 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1834 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1835 }
1836
1837 #[test]
1839 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
1840 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
1841 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
1842
1843 let (plain, _) = compile(&["-c", "a.c"]);
1844 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
1845
1846 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
1847 }
1848
1849 #[test]
1850 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1851 let (opts, _) = compile(&["-O", "a.c"]);
1852 assert_eq!(opts.opt_level, OptLevel::O1);
1853 }
1854
1855 #[test]
1856 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1857 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1858 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1859 assert_eq!(plan.jobs[1].kind, InputKind::C);
1860 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1861 }
1862
1863 #[test]
1864 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1865 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1866 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1867 other => panic!("expected a compilation, got {other:?}"),
1868 };
1869 assert_eq!(jobs.count(), 4);
1870
1871 let default = match parse_args(&args(&["a.c"])).unwrap() {
1872 Action::Compile { jobs, .. } => jobs,
1873 other => panic!("expected a compilation, got {other:?}"),
1874 };
1875 assert_eq!(default, Jobs::available());
1876 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1877 }
1878
1879 #[test]
1880 fn triple_hash_prints_the_plan_and_runs_nothing() {
1881 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1882 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1883 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1884 }
1885
1886 #[test]
1887 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1888 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1892 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1893 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1894 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1895 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1899 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1900 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1901 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1902 }
1903
1904 #[test]
1905 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1906 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1907 let (plain, without) = compile(&["-c", "a.c"]);
1908 assert!(opts.time);
1909 assert!(!plain.time);
1910 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1913 }
1914
1915 #[test]
1916 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1917 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1918 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1919 }
1920
1921 #[test]
1922 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1923 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1924 assert!(e.message.contains("unknown option"), "{}", e.message);
1925 }
1926
1927 #[test]
1930 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1931 let (opts, _) = compile(&["-c", "a.c"]);
1932 assert!(!opts.permissive, "off unless it is asked for");
1933
1934 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1935 assert!(opts.permissive);
1936
1937 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1938 assert!(!opts.permissive);
1939 }
1940
1941 #[test]
1942 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1943 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1944 assert!(e.message.contains("trampoline"), "{}", e.message);
1945 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1946 }
1947
1948 #[test]
1949 fn the_flag_every_configure_script_writes_is_taken() {
1950 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1953 let (opts, _) = compile(&["-c", flag, "a.c"]);
1954 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1955 }
1956 }
1957
1958 #[test]
1959 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1960 let (opts, _) = compile(&["-c", "a.c"]);
1961 assert!(opts.unwinds(), "the default is off");
1962 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1963 assert!(!opts.unwinds(), "the build was not taken at its word");
1964 let (opts, _) = compile(&[
1965 "-c",
1966 "-fno-asynchronous-unwind-tables",
1967 "-fasynchronous-unwind-tables",
1968 "a.c",
1969 ]);
1970 assert!(opts.unwinds(), "the last flag did not win");
1971 let (opts, _) =
1975 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1976 assert!(opts.unwinds(), "the weaker request was dropped");
1977 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
1978 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
1979 let (opts, _) =
1980 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
1981 assert!(!opts.unwinds(), "both were turned off and one stayed on");
1982 }
1983
1984 #[test]
1985 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1986 for flag in [
1990 "-fno-common",
1991 "-fstrict-aliasing",
1992 "-fno-strict-aliasing",
1993 "-pipe",
1994 "-fdiagnostics-color",
1995 "-fno-diagnostics-color",
1996 "-fdiagnostics-color=always",
1997 "-fdiagnostics-color=never",
1998 "-fdiagnostics-color=auto",
1999 ] {
2000 let (opts, _) = compile(&["-c", flag, "a.c"]);
2001 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
2002 }
2003 }
2004
2005 #[test]
2006 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
2007 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
2010 assert!(e.message.contains(".bss"), "{}", e.message);
2011 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
2012 }
2013
2014 #[test]
2015 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
2016 for flag in ["-fno-pic", "-fno-pie"] {
2017 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
2018 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
2019 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
2022 }
2023 }
2024
2025 #[test]
2026 fn an_unsupported_target_names_itself() {
2027 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
2028 assert!(e.message.contains("sparc64"), "{}", e.message);
2029 }
2030
2031 #[test]
2032 fn no_inputs_is_an_error_but_print_config_needs_none() {
2033 assert!(parse_args(&args(&[])).is_err());
2034 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
2035 }
2036
2037 #[test]
2038 fn print_config_reports_the_target_it_was_given_not_the_host() {
2039 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
2040 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
2041 let text = print_config(&opts);
2042 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
2043 assert!(text.contains("char-signed: false"), "{text}");
2044 assert!(text.contains("object-format: elf"), "{text}");
2045 assert!(text.contains("va-list: void-pointer"), "{text}");
2046 assert!(text.contains("registers: none"), "{text}");
2049 }
2050
2051 #[test]
2052 fn print_config_has_one_key_per_line_and_a_fixed_order() {
2053 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
2054 let text = print_config(&opts);
2055 let keys: Vec<&str> =
2056 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
2057 assert_eq!(keys[0], "version");
2058 assert_eq!(keys[1], "target");
2059 assert_eq!(keys.len(), 25);
2060 assert!(text.ends_with('\n'));
2061 }
2062
2063 #[test]
2064 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
2065 let (opts, _) = compile(&["a.c"]);
2066 assert_eq!(opts.safety, rucc_session::Safety::Off);
2067
2068 for (flag, tier) in [
2069 ("-fsafety=detect", rucc_session::Safety::Detect),
2070 ("-fsafety=enforce", rucc_session::Safety::Enforce),
2071 ("-fsafety=kernel", rucc_session::Safety::Kernel),
2072 ("-fsafety=off", rucc_session::Safety::Off),
2073 ] {
2074 let (opts, _) = compile(&[flag, "a.c"]);
2075 assert_eq!(opts.safety, tier, "{flag}");
2076 }
2077
2078 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
2080 assert_eq!(opts.safety, rucc_session::Safety::Off);
2081
2082 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
2085 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
2086 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
2087 }
2088
2089 #[test]
2090 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
2091 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2092 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2093 let text = print_pipeline(&opts);
2094 assert!(text.starts_with("level: -O2\n"), "{text}");
2095 assert!(text.contains("fold"), "{text}");
2096
2097 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
2098 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2099 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
2102
2103 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
2104 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2105 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2108 }
2109
2110 #[test]
2111 fn print_pipeline_takes_the_toggles_into_account() {
2112 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
2113 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2114 let text = print_pipeline(&opts);
2115 assert!(!text.contains("fold"), "{text}");
2118 assert!(text.contains("dce"), "{text}");
2119
2120 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
2124 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
2125 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
2126 let a = parse_args(&args(&spelled)).unwrap();
2127 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2128 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2129 }
2130
2131 #[test]
2132 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
2133 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2134 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2135 assert!(!print_pipeline(&opts).contains("global fuel"));
2136
2137 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2138 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2139 let text = print_pipeline(&opts);
2140 assert!(text.contains("global fuel: 4"), "{text}");
2143 }
2144
2145 #[test]
2148 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2149 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2150 assert_eq!(
2151 opts.passes,
2152 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2153 );
2154
2155 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2156 assert!(e.message.contains("unknown option"), "{}", e.message);
2157 }
2158
2159 #[test]
2160 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2161 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2162 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2163
2164 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2165 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2166 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2167 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2168 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2169 assert!(e.message.contains("not a number"), "{}", e.message);
2170 }
2171
2172 #[test]
2173 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2174 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2175 assert_eq!(opts.pass_fuel_global, None);
2176
2177 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2178 assert_eq!(opts.pass_fuel_global, Some(12));
2179 assert!(opts.pass_fuel.is_empty());
2182
2183 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2184 assert!(e.message.contains("not a number"), "{}", e.message);
2185 }
2186
2187 #[test]
2188 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2189 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2190 assert_eq!(
2191 opts.pass_gates,
2192 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2193 "the order is what decides, so it has to survive the parse"
2194 );
2195
2196 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2197 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2198 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2199 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2200 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2201 assert!(e.message.contains("is empty"), "{}", e.message);
2202 }
2203
2204 #[test]
2205 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2206 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2207 let text = print_pipeline(&opts);
2208 assert!(text.contains("fold, "), "{text}");
2209 assert!(text.contains("[off for main]"), "{text}");
2210 }
2211
2212 #[test]
2216 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2217 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2218 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2219
2220 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2221 assert!(e.message.contains("nosuch"), "{}", e.message);
2222 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2223 }
2224
2225 #[test]
2231 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2232 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2233 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2234 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2235
2236 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2237 assert_eq!(opts.opt_info, ["missed-note"]);
2238
2239 let (opts, _) =
2242 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2243 assert_eq!(opts.opt_info, ["missed", "all"]);
2244 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2245
2246 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2247 assert!(e.message.contains("vectorized"), "{}", e.message);
2248 assert!(e.message.contains("`missed`"), "{}", e.message);
2249 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2250 assert!(e.message.contains("no file"), "{}", e.message);
2251 }
2252
2253 #[test]
2254 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2255 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2256 assert!(opts.verify_each);
2257 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2258 }
2259
2260 #[test]
2261 fn dash_o_needs_an_argument() {
2262 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2263 assert_eq!(e.message, "-o requires an argument");
2264 }
2265
2266 #[test]
2267 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2268 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2269 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2270 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2271 }
2272
2273 #[test]
2274 fn the_include_flags_land_on_the_chain_each_one_names() {
2275 let (opts, _) = compile(&[
2278 "-Ii",
2279 "-iquote",
2280 "q",
2281 "-isystem",
2282 "sys",
2283 "-idirafter",
2284 "after",
2285 "--sysroot=/nowhere-at-all",
2286 "a.c",
2287 ]);
2288 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2289 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2292 assert!(!opts.search.dirs()[1].is_system);
2293 assert!(opts.search.dirs()[2].is_system);
2294 }
2295
2296 #[test]
2297 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2298 let (opts, _) = compile(&["a.c"]);
2302 let dirs = opts.search.dirs();
2303 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2304 assert_eq!(ours, Some(0), "{dirs:?}");
2305 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2306 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2307 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2308 }
2309
2310 #[test]
2311 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2312 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2313 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2314 assert_eq!(dirs, ["sys", runtime::DIR]);
2315 }
2316
2317 #[test]
2318 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2319 let (opts, _) =
2320 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2321 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2322 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2323 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2325 assert!(!opts.search.searches_current_dir());
2326 }
2327
2328 #[test]
2329 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2330 let (opts, _) = compile(&[
2331 "-iprefix",
2332 "/tools/",
2333 "-iwithprefix",
2334 "late",
2335 "-iwithprefixbefore",
2336 "early",
2337 "-iprefix",
2338 "/other/",
2339 "-iwithprefix",
2340 "last",
2341 "-nostdinc",
2342 "a.c",
2343 ]);
2344 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2345 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2348 assert!(!opts.search.dirs()[0].is_system);
2349 assert!(opts.search.dirs()[1].is_system);
2350 }
2351
2352 #[test]
2353 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2354 let (opts, _) =
2355 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2356 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2357 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2358 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2359 }
2360
2361 #[test]
2362 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2363 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2364 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2365 assert_eq!(dirs, ["i"]);
2366 }
2367
2368 #[test]
2369 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2370 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2371 assert_eq!(opts.std, Std::C11);
2372 assert!(opts.gnu_extensions);
2373
2374 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2375 assert_eq!(opts.std, Std::C99);
2376 assert!(!opts.gnu_extensions);
2377
2378 let (opts, _) = compile(&["-ansi", "a.c"]);
2379 assert_eq!(opts.std, Std::C89);
2380 assert!(!opts.gnu_extensions);
2381
2382 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2383 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2384 }
2385
2386 #[test]
2387 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2388 let (opts, _) = compile(&["-dM", "a.c"]);
2389 assert!(opts.dumps.macros);
2390
2391 let (opts, _) = compile(&["-dDM", "a.c"]);
2394 assert!(opts.dumps.macros);
2395 let (opts, _) = compile(&["-dD", "a.c"]);
2396 assert!(!opts.dumps.macros);
2397
2398 let (opts, _) = compile(&["a.c"]);
2399 assert!(!opts.dumps.any());
2400
2401 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2404 }
2405
2406 #[test]
2407 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2408 let (opts, _) = compile(&["a.c"]);
2409 assert_eq!(
2410 opts.gnuc,
2411 GnucVersion { major: 7, minor: 0, patch: 0 },
2412 "the lowest claim a modern glibc gives its own declarations to"
2413 );
2414
2415 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2416 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2417
2418 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2421 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2422
2423 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2424 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2425
2426 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2427 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2428
2429 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2430 assert!(e.message.contains("more than three"), "{}", e.message);
2431 }
2432
2433 #[test]
2434 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2435 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2436 assert!(opts.pedantic);
2437 assert_eq!(opts.std, Std::C17);
2438
2439 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2442 assert!(opts.pedantic);
2443
2444 let (opts, _) = compile(&["-std=c17", "a.c"]);
2445 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2446 }
2447
2448 #[test]
2449 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2450 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2451 assert!(!opts.line_markers);
2452 assert!(!opts.hosted);
2453 assert_eq!(opts.emit, EmitKind::Preprocessed);
2454 }
2455
2456 #[test]
2463 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2464 let (opts, _) = compile(&["-c", "a.c"]);
2465 assert!(opts.builtins, "a library name means the library function by default");
2466 assert!(opts.no_builtin.is_empty());
2467
2468 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2469 assert!(!opts.builtins);
2470
2471 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2472 assert!(opts.builtins, "the last mention decides");
2473
2474 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2475 assert!(opts.builtins, "one name is not the family");
2476 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2477 }
2478
2479 #[test]
2487 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2488 let (opts, _) = compile(&["-c", "a.c"]);
2489 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2490
2491 for (written, wanted) in [
2492 ("default", Visibility::Default),
2493 ("hidden", Visibility::Hidden),
2494 ("internal", Visibility::Hidden),
2495 ("protected", Visibility::Protected),
2496 ] {
2497 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2498 assert_eq!(opts.visibility, wanted, "{written}");
2499 }
2500
2501 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2504 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2505
2506 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2510 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2511 }
2512
2513 #[test]
2521 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
2522 let (opts, _) = compile(&["-c", "a.c"]);
2523 assert!(!opts.function_sections, "one text section unless something says otherwise");
2524 assert!(!opts.data_sections);
2525
2526 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
2527 assert!(opts.function_sections);
2528 assert!(!opts.data_sections, "one flag is not the other");
2529
2530 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
2531 assert!(opts.data_sections);
2532 assert!(!opts.function_sections);
2533
2534 let (opts, _) = compile(&[
2537 "-c",
2538 "-ffunction-sections",
2539 "-fno-function-sections",
2540 "-fdata-sections",
2541 "-fno-data-sections",
2542 "a.c",
2543 ]);
2544 assert!(!opts.function_sections, "the last mention decides");
2545 assert!(!opts.data_sections, "the last mention decides");
2546 }
2547
2548 #[test]
2551 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2552 let (opts, _) = compile(&["-c", "a.c"]);
2553 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2554
2555 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2556 assert!(opts.gnu89_inline);
2557
2558 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2559 assert!(!opts.gnu89_inline, "the last mention decides");
2560
2561 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2566 assert!(!opts.gnu89_inline);
2567 }
2568
2569 #[test]
2572 fn the_two_frame_flags_are_read_in_both_directions() {
2573 let (opts, _) = compile(&["-c", "a.c"]);
2574 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2575 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2576
2577 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2578 assert!(opts.frame_pointer);
2579 assert!(!opts.red_zone);
2580
2581 let (opts, _) = compile(&[
2582 "-c",
2583 "-fno-omit-frame-pointer",
2584 "-fomit-frame-pointer",
2585 "-mno-red-zone",
2586 "-mred-zone",
2587 "a.c",
2588 ]);
2589 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2590 assert!(opts.red_zone);
2591 }
2592
2593 #[test]
2596 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
2597 let (opts, _) = compile(&["-c", "a.c"]);
2598 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
2599
2600 for (flag, want) in [
2601 ("-fstack-protector", Protector::Buffers),
2602 ("-fstack-protector-strong", Protector::Strong),
2603 ("-fstack-protector-all", Protector::All),
2604 ] {
2605 let (opts, _) = compile(&["-c", flag, "a.c"]);
2606 assert_eq!(opts.protector, want, "{flag}");
2607 }
2608
2609 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
2612 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
2613 assert_eq!(opts.protector, Protector::None, "{off}");
2614 }
2615 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
2616 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
2617 }
2618
2619 #[test]
2622 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
2623 let (opts, _) = compile(&["-c", "a.c"]);
2624 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
2625
2626 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
2627 assert!(opts.stack_clash);
2628
2629 let (opts, _) =
2632 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
2633 assert!(!opts.stack_clash);
2634 let (opts, _) =
2635 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
2636 assert!(opts.stack_clash, "the last one wins either way round");
2637
2638 let (opts, _) =
2640 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
2641 assert!(opts.stack_clash);
2642 assert_eq!(opts.protector, Protector::Strong);
2643 }
2644
2645 #[test]
2649 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
2650 let (opts, _) = compile(&["-c", "a.c"]);
2651 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
2652
2653 for (arg, want) in [
2654 ("-fcf-protection", Control::Full),
2655 ("-fcf-protection=full", Control::Full),
2656 ("-fcf-protection=branch", Control::Branch),
2657 ("-fcf-protection=return", Control::Return),
2658 ("-fcf-protection=none", Control::None),
2659 ("-fcf-protection=check", Control::Check),
2660 ] {
2661 let (opts, _) = compile(&["-c", arg, "a.c"]);
2662 assert_eq!(opts.control, want, "{arg}");
2663 }
2664
2665 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
2668 assert_eq!(opts.control, Control::None);
2669 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
2670 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
2671 }
2672
2673 #[test]
2683 fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
2684 let (opts, _) = compile(&["-c", "a.c"]);
2685 assert!(!opts.profile);
2686 assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
2687
2688 for arg in ["-pg", "-p"] {
2689 let (opts, _) = compile(&["-c", arg, "a.c"]);
2690 assert!(opts.profile, "{arg}");
2691 let (link, _) = linking(&[arg, "a.c"]);
2692 assert!(link.profile, "{arg} changes the link as well");
2693 }
2694
2695 for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
2696 let (opts, _) = compile(&["-c", arg, "a.c"]);
2697 assert_eq!(opts.hook, want, "{arg}");
2698 assert!(!opts.profile, "{arg} asks for no call of its own");
2699 }
2700
2701 let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
2702 assert_eq!(opts.hook, Hook::Late, "the last one wins");
2703 assert!(opts.profile);
2704 }
2705
2706 #[test]
2712 fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
2713 let (opts, _) = compile(&["-c", "a.c"]);
2714 assert_eq!(opts.patchable, Patchable::default());
2715 assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
2716
2717 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
2718 assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
2719
2720 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
2721 assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
2722 assert_eq!(opts.patchable.after(), 2);
2723
2724 let (opts, _) = compile(&[
2727 "-c",
2728 "-fpatchable-function-entry=5,3",
2729 "-fpatchable-function-entry=2",
2730 "a.c",
2731 ]);
2732 assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
2733 }
2734
2735 #[test]
2737 fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
2738 for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
2739 let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
2740 assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
2741 }
2742 }
2743
2744 #[test]
2750 fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
2751 let (opts, _) = compile(&["-c", "a.c"]);
2752 assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
2753
2754 let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
2755 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false });
2756
2757 let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
2758 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true });
2759
2760 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
2761 assert_eq!(opts.wrapping, Wrapping::ALL);
2762
2763 let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
2767 assert_eq!(opts.wrapping, Wrapping::NONE);
2768
2769 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
2770 assert_eq!(opts.wrapping, Wrapping::NONE);
2771
2772 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
2773 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false });
2774 }
2775
2776 #[test]
2782 fn a_control_flow_protection_nothing_means_is_refused() {
2783 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
2784 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
2785 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
2786 }
2787
2788 #[test]
2789 fn the_link_flags_are_collected_apart_from_the_compilation() {
2790 let (link, _) = linking(&[
2791 "-static",
2792 "-nostartfiles",
2793 "-rdynamic",
2794 "-s",
2795 "-fuse-ld=mold",
2796 "-L/opt/lib",
2797 "-B",
2798 "/opt/tools",
2799 "a.c",
2800 ]);
2801 assert!(link.is_static);
2802 assert!(link.no_startfiles);
2803 assert!(link.export_dynamic);
2804 assert!(link.strip);
2805 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2806 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2807 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2808 }
2809
2810 #[test]
2811 fn a_comma_in_dash_wl_separates_two_arguments() {
2812 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2813 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2814 }
2815
2816 #[test]
2817 fn a_library_keeps_its_place_between_the_objects() {
2818 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2823 let link = plan.link.expect("expected a link step");
2824 assert_eq!(
2825 link.inputs,
2826 vec![
2827 link::Item::File("a.o".into()),
2828 link::Item::Library("m".into()),
2829 link::Item::File("b.o".into()),
2830 ]
2831 );
2832 assert_eq!(plan.jobs.len(), 2);
2834 }
2835
2836 #[test]
2837 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2838 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2839 assert!(plan.link.is_none());
2840 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2841 }
2842
2843 #[test]
2844 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2845 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2846 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2847 }
2848
2849 fn printed(s: &[&str]) -> String {
2850 match parse_args(&args(s)).expect("expected an answer") {
2851 Action::Print(line) => line,
2852 other => panic!("expected an answer, got {other:?}"),
2853 }
2854 }
2855
2856 fn refused(s: &[&str]) -> String {
2857 parse_args(&args(s)).expect_err("expected a refusal").message
2858 }
2859
2860 #[test]
2861 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2862 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2866 assert!(!opts.warnings_are_errors);
2867 assert!(opts.warnings);
2868 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2870 assert!(opts.warnings_are_errors);
2871 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2872 assert!(!opts.warnings);
2873 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2874 assert!(opts.pedantic && opts.warnings_are_errors);
2875 }
2876
2877 #[test]
2878 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2879 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2881 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2882 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2883 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2884 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2885 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2886 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2889 assert!(no32.contains("32 bit target"), "{no32}");
2890 }
2891
2892 #[test]
2893 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2894 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2895 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2896 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2897 }
2898
2899 #[test]
2900 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2901 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2902 let (opts, _) =
2903 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2904 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2905 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2906 assert!(wrong.contains("sysv convention"), "{wrong}");
2907 }
2908
2909 #[test]
2910 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2911 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2912 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2913 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2916 assert_eq!(names, vec!["a.c"]);
2917 }
2918
2919 #[test]
2920 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2921 let target = "--target=x86_64-unknown-linux-gnu";
2922 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2923 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2924 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2925 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2926 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2929 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2930 let dirs = printed(&[target, "-print-search-dirs"]);
2931 assert!(dirs.starts_with("install: "), "{dirs}");
2932 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2933 }
2934
2935 #[test]
2936 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2937 let (opts, _) = compile(&["-M", "a.c"]);
2938 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2939 assert!(opts.deps.system_headers, "plain -M lists them");
2940 assert_eq!(opts.emit, EmitKind::Preprocessed);
2941
2942 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2945 assert_eq!(opts.emit, EmitKind::Preprocessed);
2946
2947 let (opts, _) = compile(&["-MM", "a.c"]);
2948 assert!(!opts.deps.system_headers);
2949 }
2950
2951 #[test]
2952 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2953 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2954 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2955 assert!(opts.deps.system_headers);
2956 assert_eq!(opts.emit, EmitKind::Object);
2957
2958 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2959 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2960 assert!(!opts.deps.system_headers);
2961 }
2962
2963 #[test]
2964 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2965 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2968 assert!(!opts.deps.system_headers);
2969 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2970 assert!(!opts.deps.system_headers);
2971 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2972 assert!(!opts.deps.system_headers);
2973 }
2974
2975 #[test]
2976 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2977 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2978 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2979 }
2980
2981 #[test]
2982 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2983 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2984 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2985 assert!(opts.deps.phony);
2986
2987 for flag in ["-MF", "-MT", "-MQ"] {
2988 let e = parse_args(&args(&[flag])).unwrap_err();
2989 assert!(e.message.contains("requires an argument"), "{}", e.message);
2990 }
2991 }
2992
2993 struct TempTree(PathBuf);
2995
2996 impl Drop for TempTree {
2997 fn drop(&mut self) {
2998 let _ = std::fs::remove_dir_all(&self.0);
2999 }
3000 }
3001
3002 impl TempTree {
3003 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
3004 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
3005 let _ = std::fs::remove_dir_all(&dir);
3006 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
3007 for (path, text) in files {
3008 let at = dir.join(path);
3009 if let Some(parent) = at.parent() {
3010 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
3011 }
3012 std::fs::write(&at, text).expect("writing a temporary file should work");
3013 }
3014 TempTree(dir)
3015 }
3016
3017 fn path(&self, name: &str) -> String {
3018 self.0.join(name).to_string_lossy().into_owned()
3019 }
3020 }
3021
3022 #[test]
3023 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
3024 let tree = TempTree::new(
3028 "found",
3029 &[
3030 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
3031 ("one.h", "#define X 0\n"),
3032 ("two.h", "#include \"one.h\"\n"),
3033 ],
3034 );
3035 let out = tree.path("dep.d");
3036 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
3037 assert_eq!(code, 0);
3038
3039 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
3040 let names: Vec<&str> = text.split_whitespace().collect();
3041 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
3043 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
3044 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
3045 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
3048 }
3049
3050 #[test]
3051 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
3052 let tree = TempTree::new(
3055 "guarded",
3056 &[
3057 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
3058 ("g.h", "#ifndef G\n#define G\n#endif\n"),
3059 ],
3060 );
3061 let out = tree.path("dep.d");
3062 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
3063 assert_eq!(code, 0);
3064 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
3065 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
3066 }
3067
3068 #[test]
3069 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
3070 let tree = TempTree::new(
3075 "preinclude",
3076 &[
3077 ("a.c", "int main(void) { return 0; }\n"),
3078 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
3079 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
3080 ],
3081 );
3082 let out = tree.path("a.i");
3083 let code = run(&args(&[
3084 "-E",
3085 "-include",
3086 &tree.path("i.h"),
3087 "-imacros",
3088 &tree.path("m.h"),
3089 "-o",
3090 &out,
3091 &tree.path("a.c"),
3092 ]));
3093 assert_eq!(code, 0);
3094 let text = std::fs::read_to_string(&out).expect("the output should have been written");
3095 assert!(text.contains("saw_it"), "{text}");
3096 assert!(!text.contains("macros_text"), "{text}");
3099 }
3100
3101 #[test]
3102 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
3103 let tree = TempTree::new(
3104 "preinclude-deps",
3105 &[
3106 ("a.c", "int main(void) { return 0; }\n"),
3107 ("i.h", "int from_include;\n"),
3108 ("m.h", "#define M 1\n"),
3109 ],
3110 );
3111 let out = tree.path("dep.d");
3112 let code = run(&args(&[
3113 "-MM",
3114 "-MF",
3115 &out,
3116 "-include",
3117 &tree.path("i.h"),
3118 "-imacros",
3119 &tree.path("m.h"),
3120 "-o",
3121 &tree.path("a.i"),
3122 &tree.path("a.c"),
3123 ]));
3124 assert_eq!(code, 0);
3125 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
3126 assert!(text.contains("i.h"), "{text}");
3127 assert!(text.contains("m.h"), "{text}");
3128 }
3129
3130 #[test]
3131 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
3132 let tree = TempTree::new(
3136 "preinclude-missing",
3137 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
3138 );
3139 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
3140 assert_eq!(code, 1);
3141 }
3142
3143 #[test]
3144 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
3145 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
3149 assert_eq!(plan.output.as_deref(), Some("prog"));
3150 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
3151 assert_eq!(
3152 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
3153 Some("prog.d")
3154 );
3155 }
3156
3157 #[test]
3158 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
3159 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
3160 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
3161 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
3162 assert_eq!(plan.output, None);
3163 }
3164
3165 #[test]
3166 fn usage_fits_on_a_screen() {
3167 assert!(USAGE.lines().count() < 54, "usage text has grown past one screen");
3199 }
3200}