1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.18")]
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 -ftrapv signed overflow stops the program instead
191 -pthread build for more than one thread, and link the library for it
192 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
193 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
194 -j[n] compile n translation units at once, default all
195 -v, -### print each phase as it runs, or without running any
196 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
197 --target=<triple> generate code for <triple>
198 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
199 safety-summary, type-granules
200 --print-config, --print-pipeline print the configuration or the pipeline, and exit
201 --version print the version and exit
202 -h, --help print this message and exit
203
204See spec/04-driver-and-cli.md for the full flag reference.
205";
206
207fn joined_or_next(
211 arg: &str,
212 at: usize,
213 args: &[String],
214 i: &mut usize,
215) -> Result<String, CliError> {
216 if arg.len() > at {
217 return Ok(arg[at..].to_owned());
218 }
219 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
220 *i += 1;
221 Ok(next.clone())
222}
223
224pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
231 let host = Triple::host()
232 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
233 let mut opts = Options::new(host);
234 let mut inputs: Vec<Input> = Vec::new();
235 let mut print_config = false;
236 let mut print_pipeline = false;
237 let mut print_plan = false;
238 let mut verbose = false;
239 let mut jobs = Jobs::default();
240 let mut nostdinc = false;
241 let mut sysroot: Option<PathBuf> = None;
242 let mut output = None;
243 let mut link = LinkOptions::default();
244 let mut query: Option<Query> = None;
245 let mut threads = false;
246 let mut forced: Option<InputKind> = None;
249 let mut iprefix = String::new();
256
257 let mut i = 0;
258 while i < args.len() {
259 let arg = args[i].as_str();
260 i += 1;
261 match arg {
262 "-h" | "--help" => return Ok(Action::Help),
263 "--version" => return Ok(Action::Version),
264 "--print-config" => print_config = true,
265 "--print-pipeline" => print_pipeline = true,
266 "-###" => print_plan = true,
267 "-v" => verbose = true,
268 "-save-temps" => opts.save_temps = SaveTemps::Object,
272 _ if arg.starts_with("-save-temps=") => {
273 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
274 }
275 "-time" => opts.time = true,
278 "-c" => opts.emit = EmitKind::Object,
279 "-S" => opts.emit = EmitKind::Asm,
280 "-E" => opts.emit = EmitKind::Preprocessed,
281 "-g" => opts.debug_info = true,
282 "-g0" => opts.debug_info = false,
287 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
288 opts.debug_info = true;
289 }
290 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
293 _ if arg.starts_with("-gdwarf-") => {
294 return Err(err(format!(
295 "{arg}: this compiler writes DWARF 5 and no other version, see \
296 spec/11-debug-info.md"
297 )));
298 }
299 "-Werror" => opts.warnings_are_errors = true,
300 "-w" => opts.warnings = false,
303 "-pedantic-errors" => {
304 opts.pedantic = true;
305 opts.warnings_are_errors = true;
306 }
307 "-P" => opts.line_markers = false,
308 "-M" => {
315 opts.deps.emit = true;
316 opts.deps.instead_of_compiling = true;
317 }
318 "-MM" => {
319 opts.deps.emit = true;
320 opts.deps.instead_of_compiling = true;
321 opts.deps.system_headers = false;
322 }
323 "-MD" => opts.deps.emit = true,
324 "-MMD" => {
325 opts.deps.emit = true;
326 opts.deps.system_headers = false;
327 }
328 "-MP" => opts.deps.phony = true,
329 "-MF" | "-MT" | "-MQ" => {
332 let value =
333 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
334 i += 1;
335 match arg {
336 "-MF" => opts.deps.file = Some(value.clone()),
337 "-MT" => opts.deps.targets.push(value.clone()),
341 _ => opts.deps.targets.push(deps::escaped(value)),
342 }
343 }
344 "-dumpmachine" => query = Some(Query::Machine),
348 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
349 "-print-multiarch" => query = Some(Query::Multiarch),
350 "-print-search-dirs" => query = Some(Query::SearchDirs),
351 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
352 _ if arg.starts_with("-print-file-name=") => {
353 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
354 }
355 _ if arg.starts_with("-print-prog-name=") => {
356 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
357 }
358 "-pthread" | "-pthreads" => {
363 opts.defines.push("_REENTRANT".to_owned());
364 threads = true;
365 }
366 "-ansi" => {
367 opts.std = Std::C89;
368 opts.gnu_extensions = false;
369 }
370 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
373 "-fpermissive" => opts.permissive = true,
376 "-fno-permissive" => opts.permissive = false,
377 "-ffreestanding" => opts.hosted = false,
378 "-fhosted" => opts.hosted = true,
379 "-fno-builtin" => opts.builtins = false,
380 "-fbuiltin" => opts.builtins = true,
381 "-fgnu89-inline" => opts.gnu89_inline = true,
385 "-fno-gnu89-inline" => opts.gnu89_inline = false,
386 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
389 "-fomit-frame-pointer" => opts.frame_pointer = false,
390 "-mno-red-zone" => opts.red_zone = false,
391 "-mred-zone" => opts.red_zone = true,
392 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
397 opts.protector = Protector::None;
398 }
399 "-fstack-protector" => opts.protector = Protector::Buffers,
400 "-fstack-protector-strong" => opts.protector = Protector::Strong,
401 "-fstack-protector-all" => opts.protector = Protector::All,
402 "-fstack-clash-protection" => opts.stack_clash = true,
405 "-fno-stack-clash-protection" => opts.stack_clash = false,
406 "-fcf-protection" => opts.control = Control::Full,
410 "-fno-cf-protection" => opts.control = Control::None,
411 "-pg" | "-p" => {
415 opts.profile = true;
416 link.profile = true;
417 }
418 "-mfentry" => opts.hook = Hook::Early,
423 "-mno-fentry" => opts.hook = Hook::Late,
424 "-nostdinc" => nostdinc = true,
428 "-o" => {
429 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
430 i += 1;
431 }
432 "-isysroot" => {
439 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
440 i += 1;
441 sysroot = Some(PathBuf::from(dir));
442 }
443 "-iquote" | "-isystem" | "-idirafter" => {
444 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
445 i += 1;
446 match arg {
447 "-iquote" => opts.search.push_quote(dir.clone()),
448 "-isystem" => opts.search.push_system(dir.clone()),
449 _ => opts.search.push_after(dir.clone()),
450 }
451 }
452 "-iprefix" => {
453 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
454 i += 1;
455 }
456 "-iwithprefix" | "-iwithprefixbefore" => {
462 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
463 i += 1;
464 let dir = format!("{iprefix}{dir}");
465 if arg == "-iwithprefix" {
466 opts.search.push_system(dir);
467 } else {
468 opts.search.push_bracket(dir);
469 }
470 }
471 "-include" | "-imacros" => {
472 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
473 i += 1;
474 opts.preincludes
475 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
476 }
477 "-I-" => opts.search.split_quote_chain(),
482 "-x" => {
483 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
484 i += 1;
485 forced = if lang == "none" {
486 None
487 } else {
488 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
489 };
490 }
491 _ if arg.starts_with("-D") => {
499 let value = joined_or_next(arg, 2, args, &mut i)?;
500 opts.defines.push(value);
501 }
502 _ if arg.starts_with("-U") => {
503 let value = joined_or_next(arg, 2, args, &mut i)?;
504 opts.undefines.push(value);
505 }
506 _ if arg.starts_with("-I") => {
507 let dir = joined_or_next(arg, 2, args, &mut i)?;
508 opts.search.push_bracket(dir);
509 }
510 _ if arg.starts_with("-std=") => {
511 let name = &arg["-std=".len()..];
512 let (std, gnu) = Std::from_flag(name)
513 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
514 opts.std = std;
515 opts.gnu_extensions = gnu;
516 }
517 _ if Dumps::is_family(arg) => {
526 opts.dumps.add(&arg[2..]);
527 }
528 _ if arg.starts_with("-fno-builtin-") => {
533 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
534 }
535 _ if arg.starts_with("-fgnuc-version=") => {
536 let v = &arg["-fgnuc-version=".len()..];
537 opts.gnuc = v.parse().map_err(err)?;
538 }
539 "-fnested-functions" => {
544 return Err(err(
545 "nested functions are not supported: a call to one goes through a trampoline \
546 written on the stack, which no target that enforces an unexecutable stack \
547 allows",
548 ));
549 }
550 "-fno-nested-functions" => {}
551 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
562 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
566 "-fsemantic-interposition" => opts.interposition = true,
573 "-fno-semantic-interposition" => opts.interposition = false,
574 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
579 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
580 "-funwind-tables" => opts.unwind_tables = true,
581 "-fno-unwind-tables" => opts.unwind_tables = false,
582 "-fno-pic" | "-fno-pie" => {
589 return Err(err(
590 "position dependent code is not supported: an address that may be in another \
591 object is loaded out of the global offset table, and nothing here emits the \
592 absolute form this asks for. Use -no-pie if what you meant was how to link",
593 ));
594 }
595 "-ffunction-sections" => opts.function_sections = true,
601 "-fno-function-sections" => opts.function_sections = false,
602 "-fdata-sections" => opts.data_sections = true,
603 "-fno-data-sections" => opts.data_sections = false,
604 "-fno-common" => {}
610 "-fwrapv" => {
625 opts.wrapping.signed = true;
626 opts.wrapping.trap = false;
627 }
628 "-fno-wrapv" => opts.wrapping.signed = false,
629 "-fwrapv-pointer" => opts.wrapping.pointer = true,
630 "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
631 "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
632 "-fstrict-overflow" => {
636 opts.wrapping.signed = false;
637 opts.wrapping.pointer = false;
638 }
639 "-ftrapv" => {
640 opts.wrapping.trap = true;
641 opts.wrapping.signed = false;
642 }
643 "-fno-trapv" => opts.wrapping.trap = false,
644 "-fcommon" => {
648 return Err(err(
649 "a tentative definition is written into .bss as its own symbol here, and \
650 nothing emits the common symbol this asks the linker to merge. Give the \
651 variable a definition in one file and declare it extern in the others",
652 ));
653 }
654 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
668 "-pipe" => {}
671 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
678 _ if arg.starts_with("-fdiagnostics-color=") => {}
679 "-static" => link.is_static = true,
683 "-shared" => link.shared = true,
684 "-pie" => link.pie = Some(true),
685 "-no-pie" | "-nopie" => link.pie = Some(false),
686 "-nostdlib" => link.no_stdlib = true,
687 "-nostartfiles" => link.no_startfiles = true,
688 "-nodefaultlibs" => link.no_defaultlibs = true,
689 "-fno-builtins-lib" => link.no_builtins_lib = true,
690 "-fbuiltins-lib" => link.no_builtins_lib = false,
691 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
692 "-s" => link.strip = true,
693 "-Xlinker" => {
694 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
695 i += 1;
696 link.passthrough.push(next.clone());
697 }
698 _ if arg.starts_with("-Wl,") => {
699 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
702 }
703 _ if arg.starts_with("-fuse-ld=") => {
704 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
705 }
706 _ if arg.starts_with("-l") && arg.len() > 2 => {
707 inputs.push(Input::library(&arg[2..]));
708 }
709 "-l" => {
710 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
711 i += 1;
712 inputs.push(Input::library(next));
713 }
714 _ if arg.starts_with("-L") => {
715 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
716 }
717 _ if arg.starts_with("-B") => {
718 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
719 }
720 _ if arg.starts_with("-j") => {
721 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
722 }
723 _ if arg.starts_with("--sysroot=") => {
724 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
725 }
726 _ if arg.starts_with("--target=") => {
727 let t = &arg["--target=".len()..];
728 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
729 }
730 _ if arg.starts_with("--emit=") => {
731 let k = &arg["--emit=".len()..];
732 opts.emit = k
733 .parse()
734 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
735 }
736 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
742 "-Ofast" => {
748 return Err(err(
749 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
750 spec/04-driver-and-cli.md section 4.6",
751 ));
752 }
753 _ if arg.starts_with("-O") => {
754 opts.opt_level = arg[2..]
755 .parse()
756 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
757 }
758 _ if arg.starts_with("-fvisibility=") => {
762 let seen = &arg["-fvisibility=".len()..];
763 opts.visibility = seen.parse().map_err(|()| {
764 err(format!(
765 "`{seen}` is not a visibility, which is default, hidden, internal or \
766 protected"
767 ))
768 })?;
769 }
770 _ if arg.starts_with("-fcf-protection=") => {
774 let edges = &arg["-fcf-protection=".len()..];
775 opts.control = edges.parse().map_err(|()| {
776 err(format!(
777 "`{edges}` is not a control flow protection, which is full, branch, \
778 return, none or check"
779 ))
780 })?;
781 }
782 _ if arg.starts_with("-fpatchable-function-entry=") => {
785 let room = &arg["-fpatchable-function-entry=".len()..];
786 opts.patchable = room.parse().map_err(|()| {
787 err(format!(
788 "`{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"
789 ))
790 })?;
791 }
792 _ if arg.starts_with("-fsafety=") => {
797 let tier = &arg["-fsafety=".len()..];
798 opts.safety = tier.parse().map_err(|()| {
799 err(format!(
800 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
801 ))
802 })?;
803 }
804 _ if arg.starts_with("-fpass-fuel=") => {
808 let (name, count) = arg["-fpass-fuel=".len()..]
809 .split_once('=')
810 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
811 if rucc_opt::pass::find(name).is_none() {
812 return Err(err(format!(
813 "`{name}` is not a pass this compiler has, see --print-pipeline"
814 )));
815 }
816 let count: u32 = count
817 .parse()
818 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
819 opts.pass_fuel.push((name.to_owned(), count));
820 }
821 _ if arg.starts_with("-fpass-fuel-global=") => {
822 let count = &arg["-fpass-fuel-global=".len()..];
823 let count: u32 = count
824 .parse()
825 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
826 opts.pass_fuel_global = Some(count);
827 }
828 _ if arg == "-fopt-info"
833 || arg.starts_with("-fopt-info=")
834 || arg.starts_with("-fopt-info-") =>
835 {
836 let rest = &arg["-fopt-info".len()..];
837 let (kinds, file) = match rest.split_once('=') {
838 Some((kinds, file)) => (kinds, Some(file)),
839 None => (rest, None),
840 };
841 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
842 rucc_opt::Wants::none().add(kinds).map_err(err)?;
843 opts.opt_info.push(kinds.to_owned());
844 if let Some(file) = file {
845 if file.is_empty() {
846 return Err(err("-fopt-info= was given no file to write to"));
847 }
848 opts.opt_info_file = Some(file.to_owned());
849 }
850 }
851 _ if arg.starts_with("-fdump-ir=") => {
852 let spec = &arg["-fdump-ir=".len()..];
855 rucc_opt::Dumps::default().add(spec).map_err(err)?;
856 opts.dump_ir.push(spec.to_owned());
857 }
858 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
864 let on = arg.starts_with("-fenable-");
865 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
866 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
867 opts.pass_gates.push((on, spec.to_owned()));
868 }
869 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
870 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
871 }
872 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
873 opts.passes.push((arg["-f".len()..].to_owned(), true));
874 }
875 "-Zverify-each" => opts.verify_each = true,
881 _ if arg.starts_with("-Zrule-coverage=") => {
882 let file = &arg["-Zrule-coverage=".len()..];
883 if file.is_empty() {
884 return Err(err("-Zrule-coverage= needs a file to write to"));
885 }
886 opts.rule_coverage = Some(file.to_owned());
887 }
888 _ if arg.starts_with("-Zregister-pressure=") => {
889 let file = &arg["-Zregister-pressure=".len()..];
890 if file.is_empty() {
891 return Err(err("-Zregister-pressure= needs a file to write to"));
892 }
893 opts.register_pressure = Some(file.to_owned());
894 }
895 _ if arg.starts_with("-Z") => {
896 return Err(err(format!(
897 "`{arg}` is not an unstable option this compiler has, see \
898 spec/04-driver-and-cli.md section 4.11 for the ones it does"
899 )));
900 }
901 "-m64" | "-m32" | "-mx32" => {
906 let want: u32 = match arg {
907 "-m64" => 64,
908 _ => 32,
909 };
910 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
911 if have != want {
912 return Err(err(format!(
913 "{arg} asks for a {want} bit target and {} is {have} bit, use \
914 --target= to name the one you mean",
915 opts.target
916 )));
917 }
918 }
919 _ if arg.starts_with("-march=")
925 || arg.starts_with("-mtune=")
926 || arg.starts_with("-mcpu=") => {}
927 _ if arg.starts_with("-mabi=") => {
930 let want = &arg["-mabi=".len()..];
931 let have = match opts.target.arch {
932 rucc_target::Arch::X86_64 => "sysv",
933 rucc_target::Arch::Aarch64 => "lp64",
934 rucc_target::Arch::Riscv64 => "lp64d",
935 };
936 if want != have {
937 return Err(err(format!(
938 "{arg}: {} uses the {have} convention and this compiler has no other",
939 opts.target
940 )));
941 }
942 }
943 "-mcmodel=small" => {}
947 _ if arg.starts_with("-mcmodel=") => {
948 return Err(err(format!(
949 "{arg}: this compiler emits the small code model and no other, see \
950 spec/12-targets.md"
951 )));
952 }
953 _ if arg.starts_with("-specs=") => {
957 return Err(err(
958 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
959 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
960 section 4.4",
961 ));
962 }
963 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
969 return Err(err(format!(
970 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
971 are inside this compiler rather than programs it runs"
972 )));
973 }
974 "-Xassembler" | "-Xpreprocessor" => {
975 return Err(err(format!(
976 "{arg} hands an argument to a separate assembler or preprocessor, and both \
977 are inside this compiler rather than programs it runs"
978 )));
979 }
980 _ if arg.starts_with("-W") => {}
987 "-fno-ident"
993 | "-fident"
994 | "-funit-at-a-time"
995 | "-fno-unit-at-a-time"
996 | "-shared-libgcc"
997 | "-static-libgcc" => {}
998 _ if arg.starts_with('-') && arg.len() > 1 => {
999 return Err(err(format!("unknown option `{arg}`")));
1004 }
1005 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
1006 }
1007 }
1008
1009 link.sysroot = sysroot.clone();
1016 if threads {
1021 inputs.push(Input::library("pthread"));
1022 }
1023 if let Some(query) = query {
1024 return Ok(Action::Print(answer(&query, &opts, &link)));
1025 }
1026 if opts.deps.instead_of_compiling {
1032 opts.emit = EmitKind::Preprocessed;
1033 }
1034 if !nostdinc {
1035 opts.search.push_system(runtime::DIR);
1036 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
1040 opts.search.push_system(dir);
1041 }
1042 }
1043 opts.search.remove_duplicates();
1047
1048 if print_config {
1051 return Ok(Action::PrintConfig(Box::new(opts)));
1052 }
1053 if print_pipeline {
1054 return Ok(Action::PrintPipeline(Box::new(opts)));
1055 }
1056 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
1057 if print_plan {
1058 return Ok(Action::PrintPlan {
1059 opts: Box::new(opts),
1060 plan: Box::new(plan),
1061 link: Box::new(link),
1062 });
1063 }
1064 Ok(Action::Compile {
1065 opts: Box::new(opts),
1066 plan: Box::new(plan),
1067 link: Box::new(link),
1068 jobs,
1069 verbose,
1070 })
1071}
1072
1073fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
1079 let found = |name: &str| {
1080 link::find_in_search(link, opts.target, name)
1081 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
1082 };
1083 match query {
1084 Query::Machine => opts.target.to_string(),
1085 Query::Version => VERSION.to_owned(),
1086 Query::Multiarch => link::multiarch(opts.target),
1087 Query::SearchDirs => {
1092 let here = std::env::current_exe()
1093 .ok()
1094 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
1095 .unwrap_or_default();
1096 let list = |dirs: &[PathBuf]| {
1097 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
1098 };
1099 let libraries = link::search_dirs(link, opts.target);
1100 format!(
1101 "install: {}\nprograms: ={}\nlibraries: ={}",
1102 here.display(),
1103 list(&link.prefixes),
1104 list(&libraries)
1105 )
1106 }
1107 Query::FileName(name) => found(name),
1108 Query::Libgcc => found("libgcc.a"),
1112 Query::ProgName(name) => link
1116 .prefixes
1117 .iter()
1118 .map(|dir| dir.join(name))
1119 .find(|path| path.is_file())
1120 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1121 }
1122}
1123
1124#[must_use]
1130pub fn print_pipeline(opts: &Options) -> String {
1131 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1132 settings.toggles.clone_from(&opts.passes);
1133 settings.global_fuel = opts.pass_fuel_global;
1134 for (on, spec) in &opts.pass_gates {
1135 let _ = settings.gates.add(*on, spec);
1138 }
1139 rucc_opt::pipeline::print(&settings)
1140}
1141
1142#[must_use]
1147pub fn print_config(opts: &Options) -> String {
1148 let sess = Session::new(opts.clone());
1149 let t = &sess.target;
1150 let mut out = String::new();
1151 let _ = writeln!(out, "version: {VERSION}");
1152 let _ = writeln!(out, "target: {}", opts.target);
1156 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1157 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1158 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1159 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1160 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1161 let _ = writeln!(out, "long-width: {}", t.long_width);
1162 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1163 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1164 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1165 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1166 let regs: Vec<String> = t
1169 .regs
1170 .classes()
1171 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1172 .collect();
1173 let _ = writeln!(
1174 out,
1175 "registers: {}",
1176 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1177 );
1178 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1179 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1180 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1181 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1182 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1183 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1184 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
1185 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
1186 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
1187 let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
1188 let _ = writeln!(out, "profile: {}", sess.opts.profile);
1189 let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
1190 for dir in sess.opts.search.dirs() {
1193 let system = if dir.is_system { " (system)" } else { "" };
1194 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1195 }
1196 out
1197}
1198
1199fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1207 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1208}
1209
1210fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1213 if path == "-" {
1214 return write_out(&Output::Stdout, bytes);
1215 }
1216 write_out(&Output::File(path.to_owned()), bytes)
1217}
1218
1219fn write_deps(
1225 opts: &Options,
1226 plan: &Plan,
1227 job: &Job,
1228 found: &[Dependency],
1229 stderr: &mut impl std::io::Write,
1230) -> bool {
1231 let targets = if opts.deps.targets.is_empty() {
1232 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1233 } else {
1234 opts.deps.targets.clone()
1235 };
1236 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1237 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1240 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1244 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1245 }),
1246 None => write_out(&job.output, rule.as_bytes()),
1247 };
1248 if let Err(e) = wrote {
1249 let _ = writeln!(stderr, "rucc: error: {e}");
1250 return false;
1251 }
1252 true
1253}
1254
1255fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1261 let fs = OsFileSystem::new();
1262 let mut stderr = std::io::stderr().lock();
1263 let mut failed = false;
1264 for job in &plan.jobs {
1265 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1266 continue;
1269 }
1270 let started = std::time::Instant::now();
1271 let result = preprocess(opts, &job.input, &fs);
1272 if opts.time {
1273 say_time(&job.input, started.elapsed(), &mut stderr);
1274 }
1275 for message in &result.messages {
1276 let _ = writeln!(stderr, "{message}");
1277 }
1278 if result.failed() {
1279 failed = true;
1280 continue;
1281 }
1282 if opts.deps.emit {
1283 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1284 if opts.deps.instead_of_compiling {
1287 continue;
1288 }
1289 }
1290 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1291 let _ = writeln!(stderr, "rucc: error: {e}");
1292 failed = true;
1293 }
1294 }
1295 i32::from(failed)
1296}
1297
1298fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1304 let fs = OsFileSystem::new();
1305 let mut stderr = std::io::stderr().lock();
1306 let mut failed = false;
1307 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1308 failed |= !ok;
1309 let mut fired = Fired::new();
1310 let mut pressure = Pressure::new();
1311 for job in &plan.jobs {
1312 if !job.phases.contains(&Phase::Compile) {
1313 continue;
1314 }
1315 let started = std::time::Instant::now();
1319 let result = if job.kind == InputKind::Ir {
1320 compile_ir(opts, &job.input, &fs)
1321 } else {
1322 compile(opts, &job.input, &fs)
1323 };
1324 if opts.time {
1325 say_time(&job.input, started.elapsed(), &mut stderr);
1326 }
1327 fired.merge(&result.fired);
1328 pressure.merge(&result.pressure);
1329 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1330 failed |= !remarks.write(&result.remarks, &mut stderr);
1331 for message in &result.messages {
1332 let _ = writeln!(stderr, "{message}");
1333 }
1334 failed |= !write_temps(job, &result.temps, &mut stderr);
1337 if result.failed() {
1338 failed = true;
1339 continue;
1340 }
1341 if opts.deps.emit {
1346 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1347 }
1348 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1349 let _ = writeln!(stderr, "rucc: error: {e}");
1350 failed = true;
1351 }
1352 }
1353 failed |= !write_coverage(opts, &fired, &mut stderr);
1354 failed |= !write_pressure(opts, &pressure, &mut stderr);
1355 i32::from(failed)
1356}
1357
1358struct Scratch {
1365 dir: PathBuf,
1367}
1368
1369impl Scratch {
1370 fn new() -> Result<Scratch, String> {
1376 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1377 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1378 Ok(Scratch { dir })
1379 }
1380}
1381
1382impl Drop for Scratch {
1383 fn drop(&mut self) {
1384 let _ = std::fs::remove_dir_all(&self.dir);
1385 }
1386}
1387
1388fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1395 let linker = link::find(opts.target, link)?;
1396 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1397 Ok(link::render(&linker, &args))
1398}
1399
1400fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1407 let Some(job) = &plan.link else {
1408 let mut stderr = std::io::stderr().lock();
1411 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1412 return 1;
1413 };
1414 let linker = match link::find(opts.target, link) {
1417 Ok(linker) => linker,
1418 Err(why) => return complain(why),
1419 };
1420
1421 let scratch = match Scratch::new() {
1422 Ok(scratch) => scratch,
1423 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1424 };
1425
1426 let fs = OsFileSystem::new();
1427 let mut failed = false;
1428 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1431 let mut fired = Fired::new();
1432 let mut pressure = Pressure::new();
1433 {
1434 let mut stderr = std::io::stderr().lock();
1435 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1436 failed |= !ok;
1437 for (at, job) in plan.jobs.iter().enumerate() {
1438 let out = match &job.output {
1439 Output::Temporary(hint) => {
1440 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1443 }
1444 Output::File(path) => path.clone(),
1445 Output::Stdout => continue,
1448 };
1449 produced.push(out.clone());
1450 if !job.phases.contains(&Phase::Compile) {
1451 continue;
1452 }
1453 let started = std::time::Instant::now();
1454 let result = if job.kind == InputKind::Ir {
1455 compile_ir(opts, &job.input, &fs)
1456 } else {
1457 compile(opts, &job.input, &fs)
1458 };
1459 if opts.time {
1460 say_time(&job.input, started.elapsed(), &mut stderr);
1461 }
1462 fired.merge(&result.fired);
1463 pressure.merge(&result.pressure);
1464 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1465 failed |= !remarks.write(&result.remarks, &mut stderr);
1466 for message in &result.messages {
1467 let _ = writeln!(stderr, "{message}");
1468 }
1469 failed |= !write_temps(job, &result.temps, &mut stderr);
1470 if result.failed() {
1471 failed = true;
1472 continue;
1473 }
1474 if opts.deps.emit {
1479 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1480 }
1481 if !matches!(result.artifact, Artifact::Object(_)) {
1482 let _ = writeln!(
1487 stderr,
1488 "rucc: internal error: {}: no object file was produced for the link",
1489 job.input
1490 );
1491 failed = true;
1492 continue;
1493 }
1494 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1495 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1496 failed = true;
1497 }
1498 }
1499 failed |= !write_coverage(opts, &fired, &mut stderr);
1500 failed |= !write_pressure(opts, &pressure, &mut stderr);
1501 }
1502 if failed {
1503 return 1;
1507 }
1508
1509 let mut outputs = produced.into_iter();
1513 let mut items = Vec::with_capacity(job.inputs.len());
1514 for item in &job.inputs {
1515 match item {
1516 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1517 link::Item::File(_) => match outputs.next() {
1518 Some(path) => items.push(link::Item::File(path)),
1519 None => return complain("the plan asks the linker for a file nothing produced"),
1520 },
1521 }
1522 }
1523
1524 let args = match link::line(opts.target, link, &items, &job.output) {
1525 Ok(args) => args,
1526 Err(why) => return complain(why),
1527 };
1528 if verbose {
1529 let mut stderr = std::io::stderr().lock();
1530 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1531 }
1532 let started = std::time::Instant::now();
1533 let ran = link::run(&linker, &args);
1534 if opts.time {
1535 let mut stderr = std::io::stderr().lock();
1538 say_time(&linker.name, started.elapsed(), &mut stderr);
1539 }
1540 match ran {
1541 Ok(()) => 0,
1542 Err(link::Error::Refused { .. }) => 1,
1545 Err(why) => complain(why),
1546 }
1547}
1548
1549fn complain(why: impl std::fmt::Display) -> i32 {
1551 let mut stderr = std::io::stderr().lock();
1552 let _ = writeln!(stderr, "rucc: error: {why}");
1553 1
1554}
1555
1556fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1565 let Some(path) = &opts.rule_coverage else { return true };
1566 let Some(table) = coverage::table(opts.target.arch) else {
1567 let _ = writeln!(
1568 stderr,
1569 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1570 to report",
1571 opts.target
1572 );
1573 return false;
1574 };
1575 match std::fs::write(path, fired.listing(table)) {
1576 Ok(()) => true,
1577 Err(e) => {
1578 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1579 false
1580 }
1581 }
1582}
1583
1584fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
1592 let Some(path) = &opts.register_pressure else { return true };
1593 match std::fs::write(path, pressure.listing()) {
1594 Ok(()) => true,
1595 Err(e) => {
1596 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1597 false
1598 }
1599 }
1600}
1601
1602struct Remarks {
1609 file: Option<String>,
1611 started: bool,
1614}
1615
1616impl Remarks {
1617 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1623 let mut ok = true;
1624 if let Some(path) = file {
1625 if let Err(e) = std::fs::write(path, "") {
1626 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1627 ok = false;
1628 }
1629 }
1630 (Self { file: file.cloned(), started: false }, ok)
1631 }
1632
1633 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1639 if text.is_empty() {
1640 return true;
1641 }
1642 let Some(path) = &self.file else {
1643 let _ = write!(stderr, "{text}");
1644 return true;
1645 };
1646 let opened = std::fs::OpenOptions::new()
1647 .write(true)
1648 .append(self.started)
1649 .truncate(!self.started)
1650 .create(true)
1651 .open(path);
1652 self.started = true;
1653 let result =
1654 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1655 if let Err(e) = result {
1656 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1657 return false;
1658 }
1659 true
1660 }
1661}
1662
1663fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1674 let stem = std::path::Path::new(input)
1675 .file_name()
1676 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1677 let mut ok = true;
1678 for dump in dumps {
1679 let path = format!("{stem}.{}.ir", dump.name);
1680 if let Err(e) = std::fs::write(&path, &dump.text) {
1681 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1682 ok = false;
1683 }
1684 }
1685 ok
1686}
1687
1688fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1694 let mut ok = true;
1695 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1696 for (path, text) in kept {
1697 let (Some(path), Some(text)) = (path, text) else { continue };
1700 if let Err(e) = std::fs::write(&path, text) {
1701 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1702 ok = false;
1703 }
1704 }
1705 ok
1706}
1707
1708fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1715 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1716}
1717
1718fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1725 match output {
1726 Output::Stdout => {
1727 let mut stdout = std::io::stdout().lock();
1728 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1729 }
1730 Output::File(path) | Output::Temporary(path) => {
1731 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1732 }
1733 }
1734}
1735
1736pub fn run(args: &[String]) -> i32 {
1741 match parse_args(args) {
1742 Ok(Action::Help) => {
1743 print!("{USAGE}");
1744 0
1745 }
1746 Ok(Action::Version) => {
1747 println!("rucc {VERSION}");
1748 0
1749 }
1750 Ok(Action::Print(line)) => {
1751 println!("{line}");
1752 0
1753 }
1754 Ok(Action::PrintConfig(opts)) => {
1755 print!("{}", print_config(&opts));
1756 0
1757 }
1758 Ok(Action::PrintPipeline(opts)) => {
1759 print!("{}", print_pipeline(&opts));
1760 0
1761 }
1762 Ok(Action::PrintPlan { opts, plan, link }) => {
1763 print!("{}", plan.render());
1764 if let Some(job) = &plan.link {
1768 match link_line(&opts, &link, job) {
1769 Ok(line) => println!("{line}"),
1770 Err(why) => {
1771 let mut stderr = std::io::stderr().lock();
1772 let _ = writeln!(stderr, "rucc: error: {why}");
1773 return 1;
1774 }
1775 }
1776 }
1777 0
1778 }
1779 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1780 {
1781 let mut stderr = std::io::stderr().lock();
1782 if verbose {
1783 let _ = write!(stderr, "{}", plan.render());
1784 let _ = writeln!(stderr, "workers: {}", jobs.count());
1785 }
1786 }
1787 if opts.emit == EmitKind::Preprocessed {
1788 return preprocess_all(&opts, &plan);
1789 }
1790 if opts.emit != EmitKind::Executable {
1791 return compile_all(&opts, &plan);
1792 }
1793 link_all(&opts, &plan, &link, verbose)
1794 }
1795 Err(e) => {
1796 let mut stderr = std::io::stderr().lock();
1797 let _ = writeln!(stderr, "rucc: error: {e}");
1798 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1799 1
1800 }
1801 }
1802}
1803
1804#[cfg(test)]
1805mod tests {
1806 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Patchable, Visibility};
1807
1808 use super::*;
1809
1810 fn args(s: &[&str]) -> Vec<String> {
1811 s.iter().map(|x| (*x).to_owned()).collect()
1812 }
1813
1814 #[test]
1815 fn help_and_version_win_over_everything_else() {
1816 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1817 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1818 }
1819
1820 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1821 match parse_args(&args(s)).expect("expected a compilation") {
1822 Action::Compile { opts, plan, .. } => (opts, plan),
1823 other => panic!("expected a compilation, got {other:?}"),
1824 }
1825 }
1826
1827 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1828 match parse_args(&args(s)).expect("expected a compilation") {
1829 Action::Compile { link, plan, .. } => (link, plan),
1830 other => panic!("expected a compilation, got {other:?}"),
1831 }
1832 }
1833
1834 #[test]
1835 fn collects_inputs_and_flags() {
1836 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1837 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1838 assert_eq!(paths, vec!["a.c", "b.c"]);
1839 assert_eq!(opts.opt_level, OptLevel::O2);
1840 assert_eq!(opts.emit, EmitKind::Object);
1841 assert!(opts.debug_info);
1842 }
1843
1844 #[test]
1847 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1848 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1849 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1850
1851 let (plain, _) = compile(&["-c", "a.c"]);
1852 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1853
1854 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1855 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1856 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1857 }
1858
1859 #[test]
1861 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
1862 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
1863 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
1864
1865 let (plain, _) = compile(&["-c", "a.c"]);
1866 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
1867
1868 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
1869 }
1870
1871 #[test]
1872 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1873 let (opts, _) = compile(&["-O", "a.c"]);
1874 assert_eq!(opts.opt_level, OptLevel::O1);
1875 }
1876
1877 #[test]
1878 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1879 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1880 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1881 assert_eq!(plan.jobs[1].kind, InputKind::C);
1882 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1883 }
1884
1885 #[test]
1886 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1887 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1888 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1889 other => panic!("expected a compilation, got {other:?}"),
1890 };
1891 assert_eq!(jobs.count(), 4);
1892
1893 let default = match parse_args(&args(&["a.c"])).unwrap() {
1894 Action::Compile { jobs, .. } => jobs,
1895 other => panic!("expected a compilation, got {other:?}"),
1896 };
1897 assert_eq!(default, Jobs::available());
1898 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1899 }
1900
1901 #[test]
1902 fn triple_hash_prints_the_plan_and_runs_nothing() {
1903 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1904 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1905 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1906 }
1907
1908 #[test]
1909 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1910 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1914 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1915 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1916 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1917 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1921 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1922 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1923 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1924 }
1925
1926 #[test]
1927 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1928 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1929 let (plain, without) = compile(&["-c", "a.c"]);
1930 assert!(opts.time);
1931 assert!(!plain.time);
1932 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1935 }
1936
1937 #[test]
1938 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1939 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1940 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1941 }
1942
1943 #[test]
1944 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1945 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1946 assert!(e.message.contains("unknown option"), "{}", e.message);
1947 }
1948
1949 #[test]
1952 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1953 let (opts, _) = compile(&["-c", "a.c"]);
1954 assert!(!opts.permissive, "off unless it is asked for");
1955
1956 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1957 assert!(opts.permissive);
1958
1959 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1960 assert!(!opts.permissive);
1961 }
1962
1963 #[test]
1964 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1965 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1966 assert!(e.message.contains("trampoline"), "{}", e.message);
1967 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1968 }
1969
1970 #[test]
1971 fn the_flag_every_configure_script_writes_is_taken() {
1972 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1975 let (opts, _) = compile(&["-c", flag, "a.c"]);
1976 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1977 }
1978 }
1979
1980 #[test]
1981 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1982 let (opts, _) = compile(&["-c", "a.c"]);
1983 assert!(opts.unwinds(), "the default is off");
1984 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1985 assert!(!opts.unwinds(), "the build was not taken at its word");
1986 let (opts, _) = compile(&[
1987 "-c",
1988 "-fno-asynchronous-unwind-tables",
1989 "-fasynchronous-unwind-tables",
1990 "a.c",
1991 ]);
1992 assert!(opts.unwinds(), "the last flag did not win");
1993 let (opts, _) =
1997 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1998 assert!(opts.unwinds(), "the weaker request was dropped");
1999 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
2000 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
2001 let (opts, _) =
2002 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
2003 assert!(!opts.unwinds(), "both were turned off and one stayed on");
2004 }
2005
2006 #[test]
2007 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
2008 for flag in [
2012 "-fno-common",
2013 "-fstrict-aliasing",
2014 "-fno-strict-aliasing",
2015 "-pipe",
2016 "-fdiagnostics-color",
2017 "-fno-diagnostics-color",
2018 "-fdiagnostics-color=always",
2019 "-fdiagnostics-color=never",
2020 "-fdiagnostics-color=auto",
2021 ] {
2022 let (opts, _) = compile(&["-c", flag, "a.c"]);
2023 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
2024 }
2025 }
2026
2027 #[test]
2028 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
2029 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
2032 assert!(e.message.contains(".bss"), "{}", e.message);
2033 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
2034 }
2035
2036 #[test]
2037 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
2038 for flag in ["-fno-pic", "-fno-pie"] {
2039 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
2040 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
2041 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
2044 }
2045 }
2046
2047 #[test]
2048 fn an_unsupported_target_names_itself() {
2049 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
2050 assert!(e.message.contains("sparc64"), "{}", e.message);
2051 }
2052
2053 #[test]
2054 fn no_inputs_is_an_error_but_print_config_needs_none() {
2055 assert!(parse_args(&args(&[])).is_err());
2056 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
2057 }
2058
2059 #[test]
2060 fn print_config_reports_the_target_it_was_given_not_the_host() {
2061 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
2062 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
2063 let text = print_config(&opts);
2064 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
2065 assert!(text.contains("char-signed: false"), "{text}");
2066 assert!(text.contains("object-format: elf"), "{text}");
2067 assert!(text.contains("va-list: void-pointer"), "{text}");
2068 assert!(text.contains("registers: none"), "{text}");
2071 }
2072
2073 #[test]
2074 fn print_config_has_one_key_per_line_and_a_fixed_order() {
2075 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
2076 let text = print_config(&opts);
2077 let keys: Vec<&str> =
2078 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
2079 assert_eq!(keys[0], "version");
2080 assert_eq!(keys[1], "target");
2081 assert_eq!(keys.len(), 25);
2082 assert!(text.ends_with('\n'));
2083 }
2084
2085 #[test]
2086 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
2087 let (opts, _) = compile(&["a.c"]);
2088 assert_eq!(opts.safety, rucc_session::Safety::Off);
2089
2090 for (flag, tier) in [
2091 ("-fsafety=detect", rucc_session::Safety::Detect),
2092 ("-fsafety=enforce", rucc_session::Safety::Enforce),
2093 ("-fsafety=kernel", rucc_session::Safety::Kernel),
2094 ("-fsafety=off", rucc_session::Safety::Off),
2095 ] {
2096 let (opts, _) = compile(&[flag, "a.c"]);
2097 assert_eq!(opts.safety, tier, "{flag}");
2098 }
2099
2100 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
2102 assert_eq!(opts.safety, rucc_session::Safety::Off);
2103
2104 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
2107 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
2108 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
2109 }
2110
2111 #[test]
2112 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
2113 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2114 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2115 let text = print_pipeline(&opts);
2116 assert!(text.starts_with("level: -O2\n"), "{text}");
2117 assert!(text.contains("fold"), "{text}");
2118
2119 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
2120 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2121 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
2124
2125 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
2126 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2127 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2130 }
2131
2132 #[test]
2133 fn print_pipeline_takes_the_toggles_into_account() {
2134 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
2135 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2136 let text = print_pipeline(&opts);
2137 assert!(!text.contains("fold"), "{text}");
2140 assert!(text.contains("dce"), "{text}");
2141
2142 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
2146 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
2147 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
2148 let a = parse_args(&args(&spelled)).unwrap();
2149 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2150 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2151 }
2152
2153 #[test]
2154 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
2155 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2156 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2157 assert!(!print_pipeline(&opts).contains("global fuel"));
2158
2159 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2160 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2161 let text = print_pipeline(&opts);
2162 assert!(text.contains("global fuel: 4"), "{text}");
2165 }
2166
2167 #[test]
2170 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2171 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2172 assert_eq!(
2173 opts.passes,
2174 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2175 );
2176
2177 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2178 assert!(e.message.contains("unknown option"), "{}", e.message);
2179 }
2180
2181 #[test]
2182 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2183 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2184 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2185
2186 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2187 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2188 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2189 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2190 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2191 assert!(e.message.contains("not a number"), "{}", e.message);
2192 }
2193
2194 #[test]
2195 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2196 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2197 assert_eq!(opts.pass_fuel_global, None);
2198
2199 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2200 assert_eq!(opts.pass_fuel_global, Some(12));
2201 assert!(opts.pass_fuel.is_empty());
2204
2205 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2206 assert!(e.message.contains("not a number"), "{}", e.message);
2207 }
2208
2209 #[test]
2210 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2211 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2212 assert_eq!(
2213 opts.pass_gates,
2214 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2215 "the order is what decides, so it has to survive the parse"
2216 );
2217
2218 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2219 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2220 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2221 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2222 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2223 assert!(e.message.contains("is empty"), "{}", e.message);
2224 }
2225
2226 #[test]
2227 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2228 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2229 let text = print_pipeline(&opts);
2230 assert!(text.contains("fold, "), "{text}");
2231 assert!(text.contains("[off for main]"), "{text}");
2232 }
2233
2234 #[test]
2238 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2239 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2240 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2241
2242 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2243 assert!(e.message.contains("nosuch"), "{}", e.message);
2244 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2245 }
2246
2247 #[test]
2253 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2254 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2255 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2256 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2257
2258 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2259 assert_eq!(opts.opt_info, ["missed-note"]);
2260
2261 let (opts, _) =
2264 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2265 assert_eq!(opts.opt_info, ["missed", "all"]);
2266 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2267
2268 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2269 assert!(e.message.contains("vectorized"), "{}", e.message);
2270 assert!(e.message.contains("`missed`"), "{}", e.message);
2271 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2272 assert!(e.message.contains("no file"), "{}", e.message);
2273 }
2274
2275 #[test]
2276 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2277 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2278 assert!(opts.verify_each);
2279 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2280 }
2281
2282 #[test]
2283 fn dash_o_needs_an_argument() {
2284 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2285 assert_eq!(e.message, "-o requires an argument");
2286 }
2287
2288 #[test]
2289 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2290 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2291 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2292 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2293 }
2294
2295 #[test]
2296 fn the_include_flags_land_on_the_chain_each_one_names() {
2297 let (opts, _) = compile(&[
2300 "-Ii",
2301 "-iquote",
2302 "q",
2303 "-isystem",
2304 "sys",
2305 "-idirafter",
2306 "after",
2307 "--sysroot=/nowhere-at-all",
2308 "a.c",
2309 ]);
2310 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2311 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2314 assert!(!opts.search.dirs()[1].is_system);
2315 assert!(opts.search.dirs()[2].is_system);
2316 }
2317
2318 #[test]
2319 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2320 let (opts, _) = compile(&["a.c"]);
2324 let dirs = opts.search.dirs();
2325 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2326 assert_eq!(ours, Some(0), "{dirs:?}");
2327 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2328 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2329 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2330 }
2331
2332 #[test]
2333 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2334 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2335 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2336 assert_eq!(dirs, ["sys", runtime::DIR]);
2337 }
2338
2339 #[test]
2340 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2341 let (opts, _) =
2342 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2343 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2344 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2345 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2347 assert!(!opts.search.searches_current_dir());
2348 }
2349
2350 #[test]
2351 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2352 let (opts, _) = compile(&[
2353 "-iprefix",
2354 "/tools/",
2355 "-iwithprefix",
2356 "late",
2357 "-iwithprefixbefore",
2358 "early",
2359 "-iprefix",
2360 "/other/",
2361 "-iwithprefix",
2362 "last",
2363 "-nostdinc",
2364 "a.c",
2365 ]);
2366 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2367 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2370 assert!(!opts.search.dirs()[0].is_system);
2371 assert!(opts.search.dirs()[1].is_system);
2372 }
2373
2374 #[test]
2375 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2376 let (opts, _) =
2377 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2378 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2379 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2380 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2381 }
2382
2383 #[test]
2384 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2385 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2386 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2387 assert_eq!(dirs, ["i"]);
2388 }
2389
2390 #[test]
2391 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2392 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2393 assert_eq!(opts.std, Std::C11);
2394 assert!(opts.gnu_extensions);
2395
2396 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2397 assert_eq!(opts.std, Std::C99);
2398 assert!(!opts.gnu_extensions);
2399
2400 let (opts, _) = compile(&["-ansi", "a.c"]);
2401 assert_eq!(opts.std, Std::C89);
2402 assert!(!opts.gnu_extensions);
2403
2404 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2405 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2406 }
2407
2408 #[test]
2409 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2410 let (opts, _) = compile(&["-dM", "a.c"]);
2411 assert!(opts.dumps.macros);
2412
2413 let (opts, _) = compile(&["-dDM", "a.c"]);
2416 assert!(opts.dumps.macros);
2417 let (opts, _) = compile(&["-dD", "a.c"]);
2418 assert!(!opts.dumps.macros);
2419
2420 let (opts, _) = compile(&["a.c"]);
2421 assert!(!opts.dumps.any());
2422
2423 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2426 }
2427
2428 #[test]
2429 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2430 let (opts, _) = compile(&["a.c"]);
2431 assert_eq!(
2432 opts.gnuc,
2433 GnucVersion { major: 7, minor: 0, patch: 0 },
2434 "the lowest claim a modern glibc gives its own declarations to"
2435 );
2436
2437 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2438 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2439
2440 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2443 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2444
2445 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2446 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2447
2448 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2449 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2450
2451 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2452 assert!(e.message.contains("more than three"), "{}", e.message);
2453 }
2454
2455 #[test]
2456 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2457 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2458 assert!(opts.pedantic);
2459 assert_eq!(opts.std, Std::C17);
2460
2461 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2464 assert!(opts.pedantic);
2465
2466 let (opts, _) = compile(&["-std=c17", "a.c"]);
2467 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2468 }
2469
2470 #[test]
2471 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2472 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2473 assert!(!opts.line_markers);
2474 assert!(!opts.hosted);
2475 assert_eq!(opts.emit, EmitKind::Preprocessed);
2476 }
2477
2478 #[test]
2485 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2486 let (opts, _) = compile(&["-c", "a.c"]);
2487 assert!(opts.builtins, "a library name means the library function by default");
2488 assert!(opts.no_builtin.is_empty());
2489
2490 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2491 assert!(!opts.builtins);
2492
2493 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2494 assert!(opts.builtins, "the last mention decides");
2495
2496 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2497 assert!(opts.builtins, "one name is not the family");
2498 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2499 }
2500
2501 #[test]
2509 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2510 let (opts, _) = compile(&["-c", "a.c"]);
2511 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2512
2513 for (written, wanted) in [
2514 ("default", Visibility::Default),
2515 ("hidden", Visibility::Hidden),
2516 ("internal", Visibility::Hidden),
2517 ("protected", Visibility::Protected),
2518 ] {
2519 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2520 assert_eq!(opts.visibility, wanted, "{written}");
2521 }
2522
2523 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2526 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2527
2528 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2532 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2533 }
2534
2535 #[test]
2543 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
2544 let (opts, _) = compile(&["-c", "a.c"]);
2545 assert!(!opts.function_sections, "one text section unless something says otherwise");
2546 assert!(!opts.data_sections);
2547
2548 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
2549 assert!(opts.function_sections);
2550 assert!(!opts.data_sections, "one flag is not the other");
2551
2552 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
2553 assert!(opts.data_sections);
2554 assert!(!opts.function_sections);
2555
2556 let (opts, _) = compile(&[
2559 "-c",
2560 "-ffunction-sections",
2561 "-fno-function-sections",
2562 "-fdata-sections",
2563 "-fno-data-sections",
2564 "a.c",
2565 ]);
2566 assert!(!opts.function_sections, "the last mention decides");
2567 assert!(!opts.data_sections, "the last mention decides");
2568 }
2569
2570 #[test]
2573 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2574 let (opts, _) = compile(&["-c", "a.c"]);
2575 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2576
2577 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2578 assert!(opts.gnu89_inline);
2579
2580 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2581 assert!(!opts.gnu89_inline, "the last mention decides");
2582
2583 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2588 assert!(!opts.gnu89_inline);
2589 }
2590
2591 #[test]
2594 fn the_two_frame_flags_are_read_in_both_directions() {
2595 let (opts, _) = compile(&["-c", "a.c"]);
2596 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2597 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2598
2599 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2600 assert!(opts.frame_pointer);
2601 assert!(!opts.red_zone);
2602
2603 let (opts, _) = compile(&[
2604 "-c",
2605 "-fno-omit-frame-pointer",
2606 "-fomit-frame-pointer",
2607 "-mno-red-zone",
2608 "-mred-zone",
2609 "a.c",
2610 ]);
2611 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2612 assert!(opts.red_zone);
2613 }
2614
2615 #[test]
2618 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
2619 let (opts, _) = compile(&["-c", "a.c"]);
2620 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
2621
2622 for (flag, want) in [
2623 ("-fstack-protector", Protector::Buffers),
2624 ("-fstack-protector-strong", Protector::Strong),
2625 ("-fstack-protector-all", Protector::All),
2626 ] {
2627 let (opts, _) = compile(&["-c", flag, "a.c"]);
2628 assert_eq!(opts.protector, want, "{flag}");
2629 }
2630
2631 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
2634 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
2635 assert_eq!(opts.protector, Protector::None, "{off}");
2636 }
2637 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
2638 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
2639 }
2640
2641 #[test]
2644 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
2645 let (opts, _) = compile(&["-c", "a.c"]);
2646 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
2647
2648 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
2649 assert!(opts.stack_clash);
2650
2651 let (opts, _) =
2654 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
2655 assert!(!opts.stack_clash);
2656 let (opts, _) =
2657 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
2658 assert!(opts.stack_clash, "the last one wins either way round");
2659
2660 let (opts, _) =
2662 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
2663 assert!(opts.stack_clash);
2664 assert_eq!(opts.protector, Protector::Strong);
2665 }
2666
2667 #[test]
2671 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
2672 let (opts, _) = compile(&["-c", "a.c"]);
2673 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
2674
2675 for (arg, want) in [
2676 ("-fcf-protection", Control::Full),
2677 ("-fcf-protection=full", Control::Full),
2678 ("-fcf-protection=branch", Control::Branch),
2679 ("-fcf-protection=return", Control::Return),
2680 ("-fcf-protection=none", Control::None),
2681 ("-fcf-protection=check", Control::Check),
2682 ] {
2683 let (opts, _) = compile(&["-c", arg, "a.c"]);
2684 assert_eq!(opts.control, want, "{arg}");
2685 }
2686
2687 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
2690 assert_eq!(opts.control, Control::None);
2691 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
2692 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
2693 }
2694
2695 #[test]
2705 fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
2706 let (opts, _) = compile(&["-c", "a.c"]);
2707 assert!(!opts.profile);
2708 assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
2709
2710 for arg in ["-pg", "-p"] {
2711 let (opts, _) = compile(&["-c", arg, "a.c"]);
2712 assert!(opts.profile, "{arg}");
2713 let (link, _) = linking(&[arg, "a.c"]);
2714 assert!(link.profile, "{arg} changes the link as well");
2715 }
2716
2717 for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
2718 let (opts, _) = compile(&["-c", arg, "a.c"]);
2719 assert_eq!(opts.hook, want, "{arg}");
2720 assert!(!opts.profile, "{arg} asks for no call of its own");
2721 }
2722
2723 let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
2724 assert_eq!(opts.hook, Hook::Late, "the last one wins");
2725 assert!(opts.profile);
2726 }
2727
2728 #[test]
2734 fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
2735 let (opts, _) = compile(&["-c", "a.c"]);
2736 assert_eq!(opts.patchable, Patchable::default());
2737 assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
2738
2739 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
2740 assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
2741
2742 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
2743 assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
2744 assert_eq!(opts.patchable.after(), 2);
2745
2746 let (opts, _) = compile(&[
2749 "-c",
2750 "-fpatchable-function-entry=5,3",
2751 "-fpatchable-function-entry=2",
2752 "a.c",
2753 ]);
2754 assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
2755 }
2756
2757 #[test]
2759 fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
2760 for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
2761 let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
2762 assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
2763 }
2764 }
2765
2766 #[test]
2772 fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
2773 let (opts, _) = compile(&["-c", "a.c"]);
2774 assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
2775
2776 let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
2777 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
2778
2779 let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
2780 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
2781
2782 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
2783 assert_eq!(opts.wrapping, Wrapping::ALL);
2784
2785 let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
2789 assert_eq!(opts.wrapping, Wrapping::NONE);
2790
2791 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
2792 assert_eq!(opts.wrapping, Wrapping::NONE);
2793
2794 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
2795 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
2796 }
2797
2798 #[test]
2805 fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
2806 let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
2807 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
2808
2809 let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
2810 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
2811
2812 let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
2813 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
2814
2815 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
2816 assert_eq!(opts.wrapping, Wrapping::ALL);
2817
2818 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
2819 assert_eq!(opts.wrapping, Wrapping::NONE);
2820
2821 let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
2824 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
2825 }
2826
2827 #[test]
2833 fn a_control_flow_protection_nothing_means_is_refused() {
2834 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
2835 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
2836 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
2837 }
2838
2839 #[test]
2840 fn the_link_flags_are_collected_apart_from_the_compilation() {
2841 let (link, _) = linking(&[
2842 "-static",
2843 "-nostartfiles",
2844 "-rdynamic",
2845 "-s",
2846 "-fuse-ld=mold",
2847 "-L/opt/lib",
2848 "-B",
2849 "/opt/tools",
2850 "a.c",
2851 ]);
2852 assert!(link.is_static);
2853 assert!(link.no_startfiles);
2854 assert!(link.export_dynamic);
2855 assert!(link.strip);
2856 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2857 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2858 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2859 }
2860
2861 #[test]
2862 fn a_comma_in_dash_wl_separates_two_arguments() {
2863 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2864 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2865 }
2866
2867 #[test]
2868 fn a_library_keeps_its_place_between_the_objects() {
2869 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2874 let link = plan.link.expect("expected a link step");
2875 assert_eq!(
2876 link.inputs,
2877 vec![
2878 link::Item::File("a.o".into()),
2879 link::Item::Library("m".into()),
2880 link::Item::File("b.o".into()),
2881 ]
2882 );
2883 assert_eq!(plan.jobs.len(), 2);
2885 }
2886
2887 #[test]
2888 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2889 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2890 assert!(plan.link.is_none());
2891 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2892 }
2893
2894 #[test]
2895 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2896 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2897 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2898 }
2899
2900 fn printed(s: &[&str]) -> String {
2901 match parse_args(&args(s)).expect("expected an answer") {
2902 Action::Print(line) => line,
2903 other => panic!("expected an answer, got {other:?}"),
2904 }
2905 }
2906
2907 fn refused(s: &[&str]) -> String {
2908 parse_args(&args(s)).expect_err("expected a refusal").message
2909 }
2910
2911 #[test]
2912 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2913 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2917 assert!(!opts.warnings_are_errors);
2918 assert!(opts.warnings);
2919 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2921 assert!(opts.warnings_are_errors);
2922 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2923 assert!(!opts.warnings);
2924 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2925 assert!(opts.pedantic && opts.warnings_are_errors);
2926 }
2927
2928 #[test]
2929 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2930 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2932 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2933 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2934 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2935 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2936 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2937 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2940 assert!(no32.contains("32 bit target"), "{no32}");
2941 }
2942
2943 #[test]
2944 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2945 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2946 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2947 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2948 }
2949
2950 #[test]
2951 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2952 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2953 let (opts, _) =
2954 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2955 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2956 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2957 assert!(wrong.contains("sysv convention"), "{wrong}");
2958 }
2959
2960 #[test]
2961 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2962 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2963 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2964 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2967 assert_eq!(names, vec!["a.c"]);
2968 }
2969
2970 #[test]
2971 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2972 let target = "--target=x86_64-unknown-linux-gnu";
2973 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2974 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2975 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2976 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2977 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2980 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2981 let dirs = printed(&[target, "-print-search-dirs"]);
2982 assert!(dirs.starts_with("install: "), "{dirs}");
2983 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2984 }
2985
2986 #[test]
2987 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2988 let (opts, _) = compile(&["-M", "a.c"]);
2989 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2990 assert!(opts.deps.system_headers, "plain -M lists them");
2991 assert_eq!(opts.emit, EmitKind::Preprocessed);
2992
2993 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2996 assert_eq!(opts.emit, EmitKind::Preprocessed);
2997
2998 let (opts, _) = compile(&["-MM", "a.c"]);
2999 assert!(!opts.deps.system_headers);
3000 }
3001
3002 #[test]
3003 fn the_two_that_end_in_d_leave_the_compilation_alone() {
3004 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
3005 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
3006 assert!(opts.deps.system_headers);
3007 assert_eq!(opts.emit, EmitKind::Object);
3008
3009 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
3010 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
3011 assert!(!opts.deps.system_headers);
3012 }
3013
3014 #[test]
3015 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
3016 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
3019 assert!(!opts.deps.system_headers);
3020 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
3021 assert!(!opts.deps.system_headers);
3022 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
3023 assert!(!opts.deps.system_headers);
3024 }
3025
3026 #[test]
3027 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
3028 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
3029 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
3030 }
3031
3032 #[test]
3033 fn the_rest_of_the_family_is_a_file_and_a_switch() {
3034 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
3035 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
3036 assert!(opts.deps.phony);
3037
3038 for flag in ["-MF", "-MT", "-MQ"] {
3039 let e = parse_args(&args(&[flag])).unwrap_err();
3040 assert!(e.message.contains("requires an argument"), "{}", e.message);
3041 }
3042 }
3043
3044 struct TempTree(PathBuf);
3046
3047 impl Drop for TempTree {
3048 fn drop(&mut self) {
3049 let _ = std::fs::remove_dir_all(&self.0);
3050 }
3051 }
3052
3053 impl TempTree {
3054 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
3055 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
3056 let _ = std::fs::remove_dir_all(&dir);
3057 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
3058 for (path, text) in files {
3059 let at = dir.join(path);
3060 if let Some(parent) = at.parent() {
3061 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
3062 }
3063 std::fs::write(&at, text).expect("writing a temporary file should work");
3064 }
3065 TempTree(dir)
3066 }
3067
3068 fn path(&self, name: &str) -> String {
3069 self.0.join(name).to_string_lossy().into_owned()
3070 }
3071 }
3072
3073 #[test]
3074 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
3075 let tree = TempTree::new(
3079 "found",
3080 &[
3081 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
3082 ("one.h", "#define X 0\n"),
3083 ("two.h", "#include \"one.h\"\n"),
3084 ],
3085 );
3086 let out = tree.path("dep.d");
3087 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
3088 assert_eq!(code, 0);
3089
3090 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
3091 let names: Vec<&str> = text.split_whitespace().collect();
3092 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
3094 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
3095 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
3096 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
3099 }
3100
3101 #[test]
3102 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
3103 let tree = TempTree::new(
3106 "guarded",
3107 &[
3108 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
3109 ("g.h", "#ifndef G\n#define G\n#endif\n"),
3110 ],
3111 );
3112 let out = tree.path("dep.d");
3113 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
3114 assert_eq!(code, 0);
3115 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
3116 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
3117 }
3118
3119 #[test]
3120 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
3121 let tree = TempTree::new(
3126 "preinclude",
3127 &[
3128 ("a.c", "int main(void) { return 0; }\n"),
3129 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
3130 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
3131 ],
3132 );
3133 let out = tree.path("a.i");
3134 let code = run(&args(&[
3135 "-E",
3136 "-include",
3137 &tree.path("i.h"),
3138 "-imacros",
3139 &tree.path("m.h"),
3140 "-o",
3141 &out,
3142 &tree.path("a.c"),
3143 ]));
3144 assert_eq!(code, 0);
3145 let text = std::fs::read_to_string(&out).expect("the output should have been written");
3146 assert!(text.contains("saw_it"), "{text}");
3147 assert!(!text.contains("macros_text"), "{text}");
3150 }
3151
3152 #[test]
3153 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
3154 let tree = TempTree::new(
3155 "preinclude-deps",
3156 &[
3157 ("a.c", "int main(void) { return 0; }\n"),
3158 ("i.h", "int from_include;\n"),
3159 ("m.h", "#define M 1\n"),
3160 ],
3161 );
3162 let out = tree.path("dep.d");
3163 let code = run(&args(&[
3164 "-MM",
3165 "-MF",
3166 &out,
3167 "-include",
3168 &tree.path("i.h"),
3169 "-imacros",
3170 &tree.path("m.h"),
3171 "-o",
3172 &tree.path("a.i"),
3173 &tree.path("a.c"),
3174 ]));
3175 assert_eq!(code, 0);
3176 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
3177 assert!(text.contains("i.h"), "{text}");
3178 assert!(text.contains("m.h"), "{text}");
3179 }
3180
3181 #[test]
3182 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
3183 let tree = TempTree::new(
3187 "preinclude-missing",
3188 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
3189 );
3190 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
3191 assert_eq!(code, 1);
3192 }
3193
3194 #[test]
3195 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
3196 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
3200 assert_eq!(plan.output.as_deref(), Some("prog"));
3201 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
3202 assert_eq!(
3203 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
3204 Some("prog.d")
3205 );
3206 }
3207
3208 #[test]
3209 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
3210 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
3211 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
3212 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
3213 assert_eq!(plan.output, None);
3214 }
3215
3216 #[test]
3217 fn usage_fits_on_a_screen() {
3218 assert!(USAGE.lines().count() < 55, "usage text has grown past one screen");
3252 }
3253}