1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.10")]
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 Dumps, EmitKind, Options, Pic, Preinclude, Protector, SaveTemps, Session, Std, runtime,
49};
50use rucc_target::Triple;
51
52use crate::link::LinkOptions;
53
54pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
55pub use crate::phase::{Input, InputKind, Job, LinkJob, Output, Phase, Plan};
56pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
57pub use crate::schedule::Jobs;
58
59pub const VERSION: &str = env!("CARGO_PKG_VERSION");
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Action {
65 Help,
67 Version,
69 Print(String),
75 PrintConfig(Box<Options>),
77 PrintPipeline(Box<Options>),
79 PrintPlan {
81 opts: Box<Options>,
83 plan: Box<Plan>,
85 link: Box<LinkOptions>,
87 },
88 Compile {
90 opts: Box<Options>,
92 plan: Box<Plan>,
94 link: Box<LinkOptions>,
96 jobs: Jobs,
98 verbose: bool,
100 },
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct CliError {
106 pub message: String,
109}
110
111impl std::fmt::Display for CliError {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 f.write_str(&self.message)
114 }
115}
116
117impl std::error::Error for CliError {}
118
119fn err(message: impl Into<String>) -> CliError {
120 CliError { message: message.into() }
121}
122
123enum Query {
129 Machine,
131 Version,
133 Multiarch,
135 SearchDirs,
137 FileName(String),
139 ProgName(String),
141 Libgcc,
143}
144
145pub const USAGE: &str = "\
150rucc, an optimizing C compiler
151
152usage: rucc [options] file...
153
154options:
155 -c compile and assemble, do not link
156 -S compile only, emit assembly
157 -E preprocess only
158 -o <file> write output to <file>, or to standard output for -
159 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
160 -I <dir> add <dir> to the include search path
161 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
162 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
163 -include <file>, -imacros <file> read <file> first, the second for its macros only
164 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
165 -P, -dM with -E: leave out the markers, or dump the macros
166 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
167 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
168 -std=<dialect> c89 through c23, and the gnu spellings
169 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
170 -x <lang> treat later inputs as <lang>, or none to stop
171 -O<level> optimize: 0, 1, 2, 3, s, z
172 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
173 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
174 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
175 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
176 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
177 -fstack-protector[-strong|-all], -fno-stack-protector, -f[no-]stack-clash-protection
178 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
179 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
180 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
181 -fPIC -fpic -fPIE -fpie, -fno-common, -f[no-]strict-aliasing, -pipe what it does anyway
182 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
183 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
184 -Werror -pedantic -pedantic-errors -w how much to say, and whether it is fatal
185 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
186 -pthread build for more than one thread, and link the library for it
187 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
188 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
189 -j[n] compile n translation units at once, default all
190 -v, -### print each phase as it runs, or without running any
191 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
192 --target=<triple> generate code for <triple>
193 --emit=<kind> exe, obj, asm, preprocessed, tast, ir, mir-final,
194 safety-summary, type-granules
195 --print-config, --print-pipeline print the configuration or the pipeline, and exit
196 --version print the version and exit
197 -h, --help print this message and exit
198
199See spec/04-driver-and-cli.md for the full flag reference.
200";
201
202fn joined_or_next(
206 arg: &str,
207 at: usize,
208 args: &[String],
209 i: &mut usize,
210) -> Result<String, CliError> {
211 if arg.len() > at {
212 return Ok(arg[at..].to_owned());
213 }
214 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
215 *i += 1;
216 Ok(next.clone())
217}
218
219pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
226 let host = Triple::host()
227 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
228 let mut opts = Options::new(host);
229 let mut inputs: Vec<Input> = Vec::new();
230 let mut print_config = false;
231 let mut print_pipeline = false;
232 let mut print_plan = false;
233 let mut verbose = false;
234 let mut jobs = Jobs::default();
235 let mut nostdinc = false;
236 let mut sysroot: Option<PathBuf> = None;
237 let mut output = None;
238 let mut link = LinkOptions::default();
239 let mut query: Option<Query> = None;
240 let mut threads = false;
241 let mut forced: Option<InputKind> = None;
244 let mut iprefix = String::new();
251
252 let mut i = 0;
253 while i < args.len() {
254 let arg = args[i].as_str();
255 i += 1;
256 match arg {
257 "-h" | "--help" => return Ok(Action::Help),
258 "--version" => return Ok(Action::Version),
259 "--print-config" => print_config = true,
260 "--print-pipeline" => print_pipeline = true,
261 "-###" => print_plan = true,
262 "-v" => verbose = true,
263 "-save-temps" => opts.save_temps = SaveTemps::Object,
267 _ if arg.starts_with("-save-temps=") => {
268 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
269 }
270 "-time" => opts.time = true,
273 "-c" => opts.emit = EmitKind::Object,
274 "-S" => opts.emit = EmitKind::Asm,
275 "-E" => opts.emit = EmitKind::Preprocessed,
276 "-g" => opts.debug_info = true,
277 "-g0" => opts.debug_info = false,
282 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
283 opts.debug_info = true;
284 }
285 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
288 _ if arg.starts_with("-gdwarf-") => {
289 return Err(err(format!(
290 "{arg}: this compiler writes DWARF 5 and no other version, see \
291 spec/11-debug-info.md"
292 )));
293 }
294 "-Werror" => opts.warnings_are_errors = true,
295 "-w" => opts.warnings = false,
298 "-pedantic-errors" => {
299 opts.pedantic = true;
300 opts.warnings_are_errors = true;
301 }
302 "-P" => opts.line_markers = false,
303 "-M" => {
310 opts.deps.emit = true;
311 opts.deps.instead_of_compiling = true;
312 }
313 "-MM" => {
314 opts.deps.emit = true;
315 opts.deps.instead_of_compiling = true;
316 opts.deps.system_headers = false;
317 }
318 "-MD" => opts.deps.emit = true,
319 "-MMD" => {
320 opts.deps.emit = true;
321 opts.deps.system_headers = false;
322 }
323 "-MP" => opts.deps.phony = true,
324 "-MF" | "-MT" | "-MQ" => {
327 let value =
328 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
329 i += 1;
330 match arg {
331 "-MF" => opts.deps.file = Some(value.clone()),
332 "-MT" => opts.deps.targets.push(value.clone()),
336 _ => opts.deps.targets.push(deps::escaped(value)),
337 }
338 }
339 "-dumpmachine" => query = Some(Query::Machine),
343 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
344 "-print-multiarch" => query = Some(Query::Multiarch),
345 "-print-search-dirs" => query = Some(Query::SearchDirs),
346 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
347 _ if arg.starts_with("-print-file-name=") => {
348 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
349 }
350 _ if arg.starts_with("-print-prog-name=") => {
351 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
352 }
353 "-pthread" | "-pthreads" => {
358 opts.defines.push("_REENTRANT".to_owned());
359 threads = true;
360 }
361 "-ansi" => {
362 opts.std = Std::C89;
363 opts.gnu_extensions = false;
364 }
365 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
368 "-fpermissive" => opts.permissive = true,
371 "-fno-permissive" => opts.permissive = false,
372 "-ffreestanding" => opts.hosted = false,
373 "-fhosted" => opts.hosted = true,
374 "-fno-builtin" => opts.builtins = false,
375 "-fbuiltin" => opts.builtins = true,
376 "-fgnu89-inline" => opts.gnu89_inline = true,
380 "-fno-gnu89-inline" => opts.gnu89_inline = false,
381 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
384 "-fomit-frame-pointer" => opts.frame_pointer = false,
385 "-mno-red-zone" => opts.red_zone = false,
386 "-mred-zone" => opts.red_zone = true,
387 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
392 opts.protector = Protector::None;
393 }
394 "-fstack-protector" => opts.protector = Protector::Buffers,
395 "-fstack-protector-strong" => opts.protector = Protector::Strong,
396 "-fstack-protector-all" => opts.protector = Protector::All,
397 "-fstack-clash-protection" => opts.stack_clash = true,
400 "-fno-stack-clash-protection" => opts.stack_clash = false,
401 "-nostdinc" => nostdinc = true,
405 "-o" => {
406 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
407 i += 1;
408 }
409 "-isysroot" => {
416 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
417 i += 1;
418 sysroot = Some(PathBuf::from(dir));
419 }
420 "-iquote" | "-isystem" | "-idirafter" => {
421 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
422 i += 1;
423 match arg {
424 "-iquote" => opts.search.push_quote(dir.clone()),
425 "-isystem" => opts.search.push_system(dir.clone()),
426 _ => opts.search.push_after(dir.clone()),
427 }
428 }
429 "-iprefix" => {
430 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
431 i += 1;
432 }
433 "-iwithprefix" | "-iwithprefixbefore" => {
439 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
440 i += 1;
441 let dir = format!("{iprefix}{dir}");
442 if arg == "-iwithprefix" {
443 opts.search.push_system(dir);
444 } else {
445 opts.search.push_bracket(dir);
446 }
447 }
448 "-include" | "-imacros" => {
449 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
450 i += 1;
451 opts.preincludes
452 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
453 }
454 "-I-" => opts.search.split_quote_chain(),
459 "-x" => {
460 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
461 i += 1;
462 forced = if lang == "none" {
463 None
464 } else {
465 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
466 };
467 }
468 _ if arg.starts_with("-D") => {
476 let value = joined_or_next(arg, 2, args, &mut i)?;
477 opts.defines.push(value);
478 }
479 _ if arg.starts_with("-U") => {
480 let value = joined_or_next(arg, 2, args, &mut i)?;
481 opts.undefines.push(value);
482 }
483 _ if arg.starts_with("-I") => {
484 let dir = joined_or_next(arg, 2, args, &mut i)?;
485 opts.search.push_bracket(dir);
486 }
487 _ if arg.starts_with("-std=") => {
488 let name = &arg["-std=".len()..];
489 let (std, gnu) = Std::from_flag(name)
490 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
491 opts.std = std;
492 opts.gnu_extensions = gnu;
493 }
494 _ if Dumps::is_family(arg) => {
503 opts.dumps.add(&arg[2..]);
504 }
505 _ if arg.starts_with("-fno-builtin-") => {
510 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
511 }
512 _ if arg.starts_with("-fgnuc-version=") => {
513 let v = &arg["-fgnuc-version=".len()..];
514 opts.gnuc = v.parse().map_err(err)?;
515 }
516 "-fnested-functions" => {
521 return Err(err(
522 "nested functions are not supported: a call to one goes through a trampoline \
523 written on the stack, which no target that enforces an unexecutable stack \
524 allows",
525 ));
526 }
527 "-fno-nested-functions" => {}
528 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
539 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
543 "-fsemantic-interposition" => opts.interposition = true,
550 "-fno-semantic-interposition" => opts.interposition = false,
551 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
556 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
557 "-funwind-tables" => opts.unwind_tables = true,
558 "-fno-unwind-tables" => opts.unwind_tables = false,
559 "-fno-pic" | "-fno-pie" => {
566 return Err(err(
567 "position dependent code is not supported: an address that may be in another \
568 object is loaded out of the global offset table, and nothing here emits the \
569 absolute form this asks for. Use -no-pie if what you meant was how to link",
570 ));
571 }
572 "-ffunction-sections" => opts.function_sections = true,
578 "-fno-function-sections" => opts.function_sections = false,
579 "-fdata-sections" => opts.data_sections = true,
580 "-fno-data-sections" => opts.data_sections = false,
581 "-fno-common" => {}
587 "-fcommon" => {
591 return Err(err(
592 "a tentative definition is written into .bss as its own symbol here, and \
593 nothing emits the common symbol this asks the linker to merge. Give the \
594 variable a definition in one file and declare it extern in the others",
595 ));
596 }
597 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
611 "-pipe" => {}
614 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
621 _ if arg.starts_with("-fdiagnostics-color=") => {}
622 "-static" => link.is_static = true,
626 "-shared" => link.shared = true,
627 "-pie" => link.pie = Some(true),
628 "-no-pie" | "-nopie" => link.pie = Some(false),
629 "-nostdlib" => link.no_stdlib = true,
630 "-nostartfiles" => link.no_startfiles = true,
631 "-nodefaultlibs" => link.no_defaultlibs = true,
632 "-fno-builtins-lib" => link.no_builtins_lib = true,
633 "-fbuiltins-lib" => link.no_builtins_lib = false,
634 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
635 "-s" => link.strip = true,
636 "-Xlinker" => {
637 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
638 i += 1;
639 link.passthrough.push(next.clone());
640 }
641 _ if arg.starts_with("-Wl,") => {
642 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
645 }
646 _ if arg.starts_with("-fuse-ld=") => {
647 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
648 }
649 _ if arg.starts_with("-l") && arg.len() > 2 => {
650 inputs.push(Input::library(&arg[2..]));
651 }
652 "-l" => {
653 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
654 i += 1;
655 inputs.push(Input::library(next));
656 }
657 _ if arg.starts_with("-L") => {
658 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
659 }
660 _ if arg.starts_with("-B") => {
661 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
662 }
663 _ if arg.starts_with("-j") => {
664 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
665 }
666 _ if arg.starts_with("--sysroot=") => {
667 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
668 }
669 _ if arg.starts_with("--target=") => {
670 let t = &arg["--target=".len()..];
671 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
672 }
673 _ if arg.starts_with("--emit=") => {
674 let k = &arg["--emit=".len()..];
675 opts.emit = k
676 .parse()
677 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
678 }
679 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
685 "-Ofast" => {
691 return Err(err(
692 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
693 spec/04-driver-and-cli.md section 4.6",
694 ));
695 }
696 _ if arg.starts_with("-O") => {
697 opts.opt_level = arg[2..]
698 .parse()
699 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
700 }
701 _ if arg.starts_with("-fvisibility=") => {
705 let seen = &arg["-fvisibility=".len()..];
706 opts.visibility = seen.parse().map_err(|()| {
707 err(format!(
708 "`{seen}` is not a visibility, which is default, hidden, internal or \
709 protected"
710 ))
711 })?;
712 }
713 _ if arg.starts_with("-fsafety=") => {
718 let tier = &arg["-fsafety=".len()..];
719 opts.safety = tier.parse().map_err(|()| {
720 err(format!(
721 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
722 ))
723 })?;
724 }
725 _ if arg.starts_with("-fpass-fuel=") => {
729 let (name, count) = arg["-fpass-fuel=".len()..]
730 .split_once('=')
731 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
732 if rucc_opt::pass::find(name).is_none() {
733 return Err(err(format!(
734 "`{name}` is not a pass this compiler has, see --print-pipeline"
735 )));
736 }
737 let count: u32 = count
738 .parse()
739 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
740 opts.pass_fuel.push((name.to_owned(), count));
741 }
742 _ if arg.starts_with("-fpass-fuel-global=") => {
743 let count = &arg["-fpass-fuel-global=".len()..];
744 let count: u32 = count
745 .parse()
746 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
747 opts.pass_fuel_global = Some(count);
748 }
749 _ if arg == "-fopt-info"
754 || arg.starts_with("-fopt-info=")
755 || arg.starts_with("-fopt-info-") =>
756 {
757 let rest = &arg["-fopt-info".len()..];
758 let (kinds, file) = match rest.split_once('=') {
759 Some((kinds, file)) => (kinds, Some(file)),
760 None => (rest, None),
761 };
762 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
763 rucc_opt::Wants::none().add(kinds).map_err(err)?;
764 opts.opt_info.push(kinds.to_owned());
765 if let Some(file) = file {
766 if file.is_empty() {
767 return Err(err("-fopt-info= was given no file to write to"));
768 }
769 opts.opt_info_file = Some(file.to_owned());
770 }
771 }
772 _ if arg.starts_with("-fdump-ir=") => {
773 let spec = &arg["-fdump-ir=".len()..];
776 rucc_opt::Dumps::default().add(spec).map_err(err)?;
777 opts.dump_ir.push(spec.to_owned());
778 }
779 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
785 let on = arg.starts_with("-fenable-");
786 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
787 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
788 opts.pass_gates.push((on, spec.to_owned()));
789 }
790 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
791 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
792 }
793 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
794 opts.passes.push((arg["-f".len()..].to_owned(), true));
795 }
796 "-Zverify-each" => opts.verify_each = true,
802 _ if arg.starts_with("-Zrule-coverage=") => {
803 let file = &arg["-Zrule-coverage=".len()..];
804 if file.is_empty() {
805 return Err(err("-Zrule-coverage= needs a file to write to"));
806 }
807 opts.rule_coverage = Some(file.to_owned());
808 }
809 _ if arg.starts_with("-Zregister-pressure=") => {
810 let file = &arg["-Zregister-pressure=".len()..];
811 if file.is_empty() {
812 return Err(err("-Zregister-pressure= needs a file to write to"));
813 }
814 opts.register_pressure = Some(file.to_owned());
815 }
816 _ if arg.starts_with("-Z") => {
817 return Err(err(format!(
818 "`{arg}` is not an unstable option this compiler has, see \
819 spec/04-driver-and-cli.md section 4.11 for the ones it does"
820 )));
821 }
822 "-m64" | "-m32" | "-mx32" => {
827 let want: u32 = match arg {
828 "-m64" => 64,
829 _ => 32,
830 };
831 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
832 if have != want {
833 return Err(err(format!(
834 "{arg} asks for a {want} bit target and {} is {have} bit, use \
835 --target= to name the one you mean",
836 opts.target
837 )));
838 }
839 }
840 _ if arg.starts_with("-march=")
846 || arg.starts_with("-mtune=")
847 || arg.starts_with("-mcpu=") => {}
848 _ if arg.starts_with("-mabi=") => {
851 let want = &arg["-mabi=".len()..];
852 let have = match opts.target.arch {
853 rucc_target::Arch::X86_64 => "sysv",
854 rucc_target::Arch::Aarch64 => "lp64",
855 rucc_target::Arch::Riscv64 => "lp64d",
856 };
857 if want != have {
858 return Err(err(format!(
859 "{arg}: {} uses the {have} convention and this compiler has no other",
860 opts.target
861 )));
862 }
863 }
864 "-mcmodel=small" => {}
868 _ if arg.starts_with("-mcmodel=") => {
869 return Err(err(format!(
870 "{arg}: this compiler emits the small code model and no other, see \
871 spec/12-targets.md"
872 )));
873 }
874 _ if arg.starts_with("-specs=") => {
878 return Err(err(
879 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
880 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
881 section 4.4",
882 ));
883 }
884 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
890 return Err(err(format!(
891 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
892 are inside this compiler rather than programs it runs"
893 )));
894 }
895 "-Xassembler" | "-Xpreprocessor" => {
896 return Err(err(format!(
897 "{arg} hands an argument to a separate assembler or preprocessor, and both \
898 are inside this compiler rather than programs it runs"
899 )));
900 }
901 _ if arg.starts_with("-W") => {}
908 "-fno-ident"
914 | "-fident"
915 | "-funit-at-a-time"
916 | "-fno-unit-at-a-time"
917 | "-shared-libgcc"
918 | "-static-libgcc" => {}
919 _ if arg.starts_with('-') && arg.len() > 1 => {
920 return Err(err(format!("unknown option `{arg}`")));
925 }
926 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
927 }
928 }
929
930 link.sysroot = sysroot.clone();
937 if threads {
942 inputs.push(Input::library("pthread"));
943 }
944 if let Some(query) = query {
945 return Ok(Action::Print(answer(&query, &opts, &link)));
946 }
947 if opts.deps.instead_of_compiling {
953 opts.emit = EmitKind::Preprocessed;
954 }
955 if !nostdinc {
956 opts.search.push_system(runtime::DIR);
957 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
961 opts.search.push_system(dir);
962 }
963 }
964 opts.search.remove_duplicates();
968
969 if print_config {
972 return Ok(Action::PrintConfig(Box::new(opts)));
973 }
974 if print_pipeline {
975 return Ok(Action::PrintPipeline(Box::new(opts)));
976 }
977 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
978 if print_plan {
979 return Ok(Action::PrintPlan {
980 opts: Box::new(opts),
981 plan: Box::new(plan),
982 link: Box::new(link),
983 });
984 }
985 Ok(Action::Compile {
986 opts: Box::new(opts),
987 plan: Box::new(plan),
988 link: Box::new(link),
989 jobs,
990 verbose,
991 })
992}
993
994fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
1000 let found = |name: &str| {
1001 link::find_in_search(link, opts.target, name)
1002 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
1003 };
1004 match query {
1005 Query::Machine => opts.target.to_string(),
1006 Query::Version => VERSION.to_owned(),
1007 Query::Multiarch => link::multiarch(opts.target),
1008 Query::SearchDirs => {
1013 let here = std::env::current_exe()
1014 .ok()
1015 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
1016 .unwrap_or_default();
1017 let list = |dirs: &[PathBuf]| {
1018 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
1019 };
1020 let libraries = link::search_dirs(link, opts.target);
1021 format!(
1022 "install: {}\nprograms: ={}\nlibraries: ={}",
1023 here.display(),
1024 list(&link.prefixes),
1025 list(&libraries)
1026 )
1027 }
1028 Query::FileName(name) => found(name),
1029 Query::Libgcc => found("libgcc.a"),
1033 Query::ProgName(name) => link
1037 .prefixes
1038 .iter()
1039 .map(|dir| dir.join(name))
1040 .find(|path| path.is_file())
1041 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1042 }
1043}
1044
1045#[must_use]
1051pub fn print_pipeline(opts: &Options) -> String {
1052 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1053 settings.toggles.clone_from(&opts.passes);
1054 settings.global_fuel = opts.pass_fuel_global;
1055 for (on, spec) in &opts.pass_gates {
1056 let _ = settings.gates.add(*on, spec);
1059 }
1060 rucc_opt::pipeline::print(&settings)
1061}
1062
1063#[must_use]
1068pub fn print_config(opts: &Options) -> String {
1069 let sess = Session::new(opts.clone());
1070 let t = &sess.target;
1071 let mut out = String::new();
1072 let _ = writeln!(out, "version: {VERSION}");
1073 let _ = writeln!(out, "target: {}", opts.target);
1077 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1078 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1079 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1080 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1081 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1082 let _ = writeln!(out, "long-width: {}", t.long_width);
1083 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1084 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1085 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1086 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1087 let regs: Vec<String> = t
1090 .regs
1091 .classes()
1092 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1093 .collect();
1094 let _ = writeln!(
1095 out,
1096 "registers: {}",
1097 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1098 );
1099 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1100 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1101 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1102 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1103 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1104 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1105 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
1106 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
1107 for dir in sess.opts.search.dirs() {
1110 let system = if dir.is_system { " (system)" } else { "" };
1111 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1112 }
1113 out
1114}
1115
1116fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1124 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1125}
1126
1127fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1130 if path == "-" {
1131 return write_out(&Output::Stdout, bytes);
1132 }
1133 write_out(&Output::File(path.to_owned()), bytes)
1134}
1135
1136fn write_deps(
1142 opts: &Options,
1143 plan: &Plan,
1144 job: &Job,
1145 found: &[Dependency],
1146 stderr: &mut impl std::io::Write,
1147) -> bool {
1148 let targets = if opts.deps.targets.is_empty() {
1149 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1150 } else {
1151 opts.deps.targets.clone()
1152 };
1153 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1154 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1157 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1161 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1162 }),
1163 None => write_out(&job.output, rule.as_bytes()),
1164 };
1165 if let Err(e) = wrote {
1166 let _ = writeln!(stderr, "rucc: error: {e}");
1167 return false;
1168 }
1169 true
1170}
1171
1172fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1178 let fs = OsFileSystem::new();
1179 let mut stderr = std::io::stderr().lock();
1180 let mut failed = false;
1181 for job in &plan.jobs {
1182 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1183 continue;
1186 }
1187 let started = std::time::Instant::now();
1188 let result = preprocess(opts, &job.input, &fs);
1189 if opts.time {
1190 say_time(&job.input, started.elapsed(), &mut stderr);
1191 }
1192 for message in &result.messages {
1193 let _ = writeln!(stderr, "{message}");
1194 }
1195 if result.failed() {
1196 failed = true;
1197 continue;
1198 }
1199 if opts.deps.emit {
1200 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1201 if opts.deps.instead_of_compiling {
1204 continue;
1205 }
1206 }
1207 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1208 let _ = writeln!(stderr, "rucc: error: {e}");
1209 failed = true;
1210 }
1211 }
1212 i32::from(failed)
1213}
1214
1215fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1221 let fs = OsFileSystem::new();
1222 let mut stderr = std::io::stderr().lock();
1223 let mut failed = false;
1224 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1225 failed |= !ok;
1226 let mut fired = Fired::new();
1227 let mut pressure = Pressure::new();
1228 for job in &plan.jobs {
1229 if !job.phases.contains(&Phase::Compile) {
1230 continue;
1231 }
1232 let started = std::time::Instant::now();
1236 let result = if job.kind == InputKind::Ir {
1237 compile_ir(opts, &job.input, &fs)
1238 } else {
1239 compile(opts, &job.input, &fs)
1240 };
1241 if opts.time {
1242 say_time(&job.input, started.elapsed(), &mut stderr);
1243 }
1244 fired.merge(&result.fired);
1245 pressure.merge(&result.pressure);
1246 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1247 failed |= !remarks.write(&result.remarks, &mut stderr);
1248 for message in &result.messages {
1249 let _ = writeln!(stderr, "{message}");
1250 }
1251 failed |= !write_temps(job, &result.temps, &mut stderr);
1254 if result.failed() {
1255 failed = true;
1256 continue;
1257 }
1258 if opts.deps.emit {
1263 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1264 }
1265 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1266 let _ = writeln!(stderr, "rucc: error: {e}");
1267 failed = true;
1268 }
1269 }
1270 failed |= !write_coverage(opts, &fired, &mut stderr);
1271 failed |= !write_pressure(opts, &pressure, &mut stderr);
1272 i32::from(failed)
1273}
1274
1275struct Scratch {
1282 dir: PathBuf,
1284}
1285
1286impl Scratch {
1287 fn new() -> Result<Scratch, String> {
1293 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1294 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1295 Ok(Scratch { dir })
1296 }
1297}
1298
1299impl Drop for Scratch {
1300 fn drop(&mut self) {
1301 let _ = std::fs::remove_dir_all(&self.dir);
1302 }
1303}
1304
1305fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1312 let linker = link::find(opts.target, link)?;
1313 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1314 Ok(link::render(&linker, &args))
1315}
1316
1317fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1324 let Some(job) = &plan.link else {
1325 let mut stderr = std::io::stderr().lock();
1328 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1329 return 1;
1330 };
1331 let linker = match link::find(opts.target, link) {
1334 Ok(linker) => linker,
1335 Err(why) => return complain(why),
1336 };
1337
1338 let scratch = match Scratch::new() {
1339 Ok(scratch) => scratch,
1340 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1341 };
1342
1343 let fs = OsFileSystem::new();
1344 let mut failed = false;
1345 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1348 let mut fired = Fired::new();
1349 let mut pressure = Pressure::new();
1350 {
1351 let mut stderr = std::io::stderr().lock();
1352 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1353 failed |= !ok;
1354 for (at, job) in plan.jobs.iter().enumerate() {
1355 let out = match &job.output {
1356 Output::Temporary(hint) => {
1357 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1360 }
1361 Output::File(path) => path.clone(),
1362 Output::Stdout => continue,
1365 };
1366 produced.push(out.clone());
1367 if !job.phases.contains(&Phase::Compile) {
1368 continue;
1369 }
1370 let started = std::time::Instant::now();
1371 let result = if job.kind == InputKind::Ir {
1372 compile_ir(opts, &job.input, &fs)
1373 } else {
1374 compile(opts, &job.input, &fs)
1375 };
1376 if opts.time {
1377 say_time(&job.input, started.elapsed(), &mut stderr);
1378 }
1379 fired.merge(&result.fired);
1380 pressure.merge(&result.pressure);
1381 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1382 failed |= !remarks.write(&result.remarks, &mut stderr);
1383 for message in &result.messages {
1384 let _ = writeln!(stderr, "{message}");
1385 }
1386 failed |= !write_temps(job, &result.temps, &mut stderr);
1387 if result.failed() {
1388 failed = true;
1389 continue;
1390 }
1391 if opts.deps.emit {
1396 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1397 }
1398 if !matches!(result.artifact, Artifact::Object(_)) {
1399 let _ = writeln!(
1404 stderr,
1405 "rucc: internal error: {}: no object file was produced for the link",
1406 job.input
1407 );
1408 failed = true;
1409 continue;
1410 }
1411 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1412 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1413 failed = true;
1414 }
1415 }
1416 failed |= !write_coverage(opts, &fired, &mut stderr);
1417 failed |= !write_pressure(opts, &pressure, &mut stderr);
1418 }
1419 if failed {
1420 return 1;
1424 }
1425
1426 let mut outputs = produced.into_iter();
1430 let mut items = Vec::with_capacity(job.inputs.len());
1431 for item in &job.inputs {
1432 match item {
1433 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1434 link::Item::File(_) => match outputs.next() {
1435 Some(path) => items.push(link::Item::File(path)),
1436 None => return complain("the plan asks the linker for a file nothing produced"),
1437 },
1438 }
1439 }
1440
1441 let args = match link::line(opts.target, link, &items, &job.output) {
1442 Ok(args) => args,
1443 Err(why) => return complain(why),
1444 };
1445 if verbose {
1446 let mut stderr = std::io::stderr().lock();
1447 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1448 }
1449 let started = std::time::Instant::now();
1450 let ran = link::run(&linker, &args);
1451 if opts.time {
1452 let mut stderr = std::io::stderr().lock();
1455 say_time(&linker.name, started.elapsed(), &mut stderr);
1456 }
1457 match ran {
1458 Ok(()) => 0,
1459 Err(link::Error::Refused { .. }) => 1,
1462 Err(why) => complain(why),
1463 }
1464}
1465
1466fn complain(why: impl std::fmt::Display) -> i32 {
1468 let mut stderr = std::io::stderr().lock();
1469 let _ = writeln!(stderr, "rucc: error: {why}");
1470 1
1471}
1472
1473fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1482 let Some(path) = &opts.rule_coverage else { return true };
1483 let Some(table) = coverage::table(opts.target.arch) else {
1484 let _ = writeln!(
1485 stderr,
1486 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1487 to report",
1488 opts.target
1489 );
1490 return false;
1491 };
1492 match std::fs::write(path, fired.listing(table)) {
1493 Ok(()) => true,
1494 Err(e) => {
1495 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1496 false
1497 }
1498 }
1499}
1500
1501fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
1509 let Some(path) = &opts.register_pressure else { return true };
1510 match std::fs::write(path, pressure.listing()) {
1511 Ok(()) => true,
1512 Err(e) => {
1513 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1514 false
1515 }
1516 }
1517}
1518
1519struct Remarks {
1526 file: Option<String>,
1528 started: bool,
1531}
1532
1533impl Remarks {
1534 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1540 let mut ok = true;
1541 if let Some(path) = file {
1542 if let Err(e) = std::fs::write(path, "") {
1543 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1544 ok = false;
1545 }
1546 }
1547 (Self { file: file.cloned(), started: false }, ok)
1548 }
1549
1550 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1556 if text.is_empty() {
1557 return true;
1558 }
1559 let Some(path) = &self.file else {
1560 let _ = write!(stderr, "{text}");
1561 return true;
1562 };
1563 let opened = std::fs::OpenOptions::new()
1564 .write(true)
1565 .append(self.started)
1566 .truncate(!self.started)
1567 .create(true)
1568 .open(path);
1569 self.started = true;
1570 let result =
1571 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1572 if let Err(e) = result {
1573 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1574 return false;
1575 }
1576 true
1577 }
1578}
1579
1580fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1591 let stem = std::path::Path::new(input)
1592 .file_name()
1593 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1594 let mut ok = true;
1595 for dump in dumps {
1596 let path = format!("{stem}.{}.ir", dump.name);
1597 if let Err(e) = std::fs::write(&path, &dump.text) {
1598 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1599 ok = false;
1600 }
1601 }
1602 ok
1603}
1604
1605fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1611 let mut ok = true;
1612 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1613 for (path, text) in kept {
1614 let (Some(path), Some(text)) = (path, text) else { continue };
1617 if let Err(e) = std::fs::write(&path, text) {
1618 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1619 ok = false;
1620 }
1621 }
1622 ok
1623}
1624
1625fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1632 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1633}
1634
1635fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1642 match output {
1643 Output::Stdout => {
1644 let mut stdout = std::io::stdout().lock();
1645 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1646 }
1647 Output::File(path) | Output::Temporary(path) => {
1648 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1649 }
1650 }
1651}
1652
1653pub fn run(args: &[String]) -> i32 {
1658 match parse_args(args) {
1659 Ok(Action::Help) => {
1660 print!("{USAGE}");
1661 0
1662 }
1663 Ok(Action::Version) => {
1664 println!("rucc {VERSION}");
1665 0
1666 }
1667 Ok(Action::Print(line)) => {
1668 println!("{line}");
1669 0
1670 }
1671 Ok(Action::PrintConfig(opts)) => {
1672 print!("{}", print_config(&opts));
1673 0
1674 }
1675 Ok(Action::PrintPipeline(opts)) => {
1676 print!("{}", print_pipeline(&opts));
1677 0
1678 }
1679 Ok(Action::PrintPlan { opts, plan, link }) => {
1680 print!("{}", plan.render());
1681 if let Some(job) = &plan.link {
1685 match link_line(&opts, &link, job) {
1686 Ok(line) => println!("{line}"),
1687 Err(why) => {
1688 let mut stderr = std::io::stderr().lock();
1689 let _ = writeln!(stderr, "rucc: error: {why}");
1690 return 1;
1691 }
1692 }
1693 }
1694 0
1695 }
1696 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1697 {
1698 let mut stderr = std::io::stderr().lock();
1699 if verbose {
1700 let _ = write!(stderr, "{}", plan.render());
1701 let _ = writeln!(stderr, "workers: {}", jobs.count());
1702 }
1703 }
1704 if opts.emit == EmitKind::Preprocessed {
1705 return preprocess_all(&opts, &plan);
1706 }
1707 if opts.emit != EmitKind::Executable {
1708 return compile_all(&opts, &plan);
1709 }
1710 link_all(&opts, &plan, &link, verbose)
1711 }
1712 Err(e) => {
1713 let mut stderr = std::io::stderr().lock();
1714 let _ = writeln!(stderr, "rucc: error: {e}");
1715 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1716 1
1717 }
1718 }
1719}
1720
1721#[cfg(test)]
1722mod tests {
1723 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1724
1725 use super::*;
1726
1727 fn args(s: &[&str]) -> Vec<String> {
1728 s.iter().map(|x| (*x).to_owned()).collect()
1729 }
1730
1731 #[test]
1732 fn help_and_version_win_over_everything_else() {
1733 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1734 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1735 }
1736
1737 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1738 match parse_args(&args(s)).expect("expected a compilation") {
1739 Action::Compile { opts, plan, .. } => (opts, plan),
1740 other => panic!("expected a compilation, got {other:?}"),
1741 }
1742 }
1743
1744 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1745 match parse_args(&args(s)).expect("expected a compilation") {
1746 Action::Compile { link, plan, .. } => (link, plan),
1747 other => panic!("expected a compilation, got {other:?}"),
1748 }
1749 }
1750
1751 #[test]
1752 fn collects_inputs_and_flags() {
1753 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1754 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1755 assert_eq!(paths, vec!["a.c", "b.c"]);
1756 assert_eq!(opts.opt_level, OptLevel::O2);
1757 assert_eq!(opts.emit, EmitKind::Object);
1758 assert!(opts.debug_info);
1759 }
1760
1761 #[test]
1764 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1765 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1766 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1767
1768 let (plain, _) = compile(&["-c", "a.c"]);
1769 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1770
1771 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1772 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1773 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1774 }
1775
1776 #[test]
1778 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
1779 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
1780 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
1781
1782 let (plain, _) = compile(&["-c", "a.c"]);
1783 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
1784
1785 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
1786 }
1787
1788 #[test]
1789 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1790 let (opts, _) = compile(&["-O", "a.c"]);
1791 assert_eq!(opts.opt_level, OptLevel::O1);
1792 }
1793
1794 #[test]
1795 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1796 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1797 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1798 assert_eq!(plan.jobs[1].kind, InputKind::C);
1799 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1800 }
1801
1802 #[test]
1803 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1804 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1805 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1806 other => panic!("expected a compilation, got {other:?}"),
1807 };
1808 assert_eq!(jobs.count(), 4);
1809
1810 let default = match parse_args(&args(&["a.c"])).unwrap() {
1811 Action::Compile { jobs, .. } => jobs,
1812 other => panic!("expected a compilation, got {other:?}"),
1813 };
1814 assert_eq!(default, Jobs::available());
1815 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1816 }
1817
1818 #[test]
1819 fn triple_hash_prints_the_plan_and_runs_nothing() {
1820 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1821 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1822 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1823 }
1824
1825 #[test]
1826 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1827 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1831 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1832 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1833 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1834 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1838 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1839 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1840 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1841 }
1842
1843 #[test]
1844 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1845 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1846 let (plain, without) = compile(&["-c", "a.c"]);
1847 assert!(opts.time);
1848 assert!(!plain.time);
1849 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1852 }
1853
1854 #[test]
1855 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1856 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1857 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1858 }
1859
1860 #[test]
1861 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1862 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1863 assert!(e.message.contains("unknown option"), "{}", e.message);
1864 }
1865
1866 #[test]
1869 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1870 let (opts, _) = compile(&["-c", "a.c"]);
1871 assert!(!opts.permissive, "off unless it is asked for");
1872
1873 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1874 assert!(opts.permissive);
1875
1876 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1877 assert!(!opts.permissive);
1878 }
1879
1880 #[test]
1881 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1882 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1883 assert!(e.message.contains("trampoline"), "{}", e.message);
1884 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1885 }
1886
1887 #[test]
1888 fn the_flag_every_configure_script_writes_is_taken() {
1889 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1892 let (opts, _) = compile(&["-c", flag, "a.c"]);
1893 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1894 }
1895 }
1896
1897 #[test]
1898 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1899 let (opts, _) = compile(&["-c", "a.c"]);
1900 assert!(opts.unwinds(), "the default is off");
1901 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1902 assert!(!opts.unwinds(), "the build was not taken at its word");
1903 let (opts, _) = compile(&[
1904 "-c",
1905 "-fno-asynchronous-unwind-tables",
1906 "-fasynchronous-unwind-tables",
1907 "a.c",
1908 ]);
1909 assert!(opts.unwinds(), "the last flag did not win");
1910 let (opts, _) =
1914 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1915 assert!(opts.unwinds(), "the weaker request was dropped");
1916 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
1917 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
1918 let (opts, _) =
1919 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
1920 assert!(!opts.unwinds(), "both were turned off and one stayed on");
1921 }
1922
1923 #[test]
1924 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1925 for flag in [
1929 "-fno-common",
1930 "-fstrict-aliasing",
1931 "-fno-strict-aliasing",
1932 "-pipe",
1933 "-fdiagnostics-color",
1934 "-fno-diagnostics-color",
1935 "-fdiagnostics-color=always",
1936 "-fdiagnostics-color=never",
1937 "-fdiagnostics-color=auto",
1938 ] {
1939 let (opts, _) = compile(&["-c", flag, "a.c"]);
1940 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1941 }
1942 }
1943
1944 #[test]
1945 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1946 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1949 assert!(e.message.contains(".bss"), "{}", e.message);
1950 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1951 }
1952
1953 #[test]
1954 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1955 for flag in ["-fno-pic", "-fno-pie"] {
1956 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1957 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1958 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1961 }
1962 }
1963
1964 #[test]
1965 fn an_unsupported_target_names_itself() {
1966 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1967 assert!(e.message.contains("sparc64"), "{}", e.message);
1968 }
1969
1970 #[test]
1971 fn no_inputs_is_an_error_but_print_config_needs_none() {
1972 assert!(parse_args(&args(&[])).is_err());
1973 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1974 }
1975
1976 #[test]
1977 fn print_config_reports_the_target_it_was_given_not_the_host() {
1978 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1979 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1980 let text = print_config(&opts);
1981 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1982 assert!(text.contains("char-signed: false"), "{text}");
1983 assert!(text.contains("object-format: elf"), "{text}");
1984 assert!(text.contains("va-list: void-pointer"), "{text}");
1985 assert!(text.contains("registers: none"), "{text}");
1988 }
1989
1990 #[test]
1991 fn print_config_has_one_key_per_line_and_a_fixed_order() {
1992 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1993 let text = print_config(&opts);
1994 let keys: Vec<&str> =
1995 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1996 assert_eq!(keys[0], "version");
1997 assert_eq!(keys[1], "target");
1998 assert_eq!(keys.len(), 21);
1999 assert!(text.ends_with('\n'));
2000 }
2001
2002 #[test]
2003 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
2004 let (opts, _) = compile(&["a.c"]);
2005 assert_eq!(opts.safety, rucc_session::Safety::Off);
2006
2007 for (flag, tier) in [
2008 ("-fsafety=detect", rucc_session::Safety::Detect),
2009 ("-fsafety=enforce", rucc_session::Safety::Enforce),
2010 ("-fsafety=kernel", rucc_session::Safety::Kernel),
2011 ("-fsafety=off", rucc_session::Safety::Off),
2012 ] {
2013 let (opts, _) = compile(&[flag, "a.c"]);
2014 assert_eq!(opts.safety, tier, "{flag}");
2015 }
2016
2017 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
2019 assert_eq!(opts.safety, rucc_session::Safety::Off);
2020
2021 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
2024 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
2025 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
2026 }
2027
2028 #[test]
2029 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
2030 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2031 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2032 let text = print_pipeline(&opts);
2033 assert!(text.starts_with("level: -O2\n"), "{text}");
2034 assert!(text.contains("fold"), "{text}");
2035
2036 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
2037 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2038 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
2041
2042 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
2043 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2044 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2047 }
2048
2049 #[test]
2050 fn print_pipeline_takes_the_toggles_into_account() {
2051 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
2052 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2053 let text = print_pipeline(&opts);
2054 assert!(!text.contains("fold"), "{text}");
2057 assert!(text.contains("dce"), "{text}");
2058
2059 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
2063 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
2064 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
2065 let a = parse_args(&args(&spelled)).unwrap();
2066 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2067 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2068 }
2069
2070 #[test]
2071 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
2072 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2073 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2074 assert!(!print_pipeline(&opts).contains("global fuel"));
2075
2076 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2077 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2078 let text = print_pipeline(&opts);
2079 assert!(text.contains("global fuel: 4"), "{text}");
2082 }
2083
2084 #[test]
2087 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2088 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2089 assert_eq!(
2090 opts.passes,
2091 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2092 );
2093
2094 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2095 assert!(e.message.contains("unknown option"), "{}", e.message);
2096 }
2097
2098 #[test]
2099 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2100 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2101 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2102
2103 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2104 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2105 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2106 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2107 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2108 assert!(e.message.contains("not a number"), "{}", e.message);
2109 }
2110
2111 #[test]
2112 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2113 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2114 assert_eq!(opts.pass_fuel_global, None);
2115
2116 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2117 assert_eq!(opts.pass_fuel_global, Some(12));
2118 assert!(opts.pass_fuel.is_empty());
2121
2122 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2123 assert!(e.message.contains("not a number"), "{}", e.message);
2124 }
2125
2126 #[test]
2127 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2128 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2129 assert_eq!(
2130 opts.pass_gates,
2131 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2132 "the order is what decides, so it has to survive the parse"
2133 );
2134
2135 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2136 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2137 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2138 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2139 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2140 assert!(e.message.contains("is empty"), "{}", e.message);
2141 }
2142
2143 #[test]
2144 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2145 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2146 let text = print_pipeline(&opts);
2147 assert!(text.contains("fold, "), "{text}");
2148 assert!(text.contains("[off for main]"), "{text}");
2149 }
2150
2151 #[test]
2155 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2156 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2157 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2158
2159 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2160 assert!(e.message.contains("nosuch"), "{}", e.message);
2161 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2162 }
2163
2164 #[test]
2170 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2171 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2172 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2173 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2174
2175 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2176 assert_eq!(opts.opt_info, ["missed-note"]);
2177
2178 let (opts, _) =
2181 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2182 assert_eq!(opts.opt_info, ["missed", "all"]);
2183 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2184
2185 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2186 assert!(e.message.contains("vectorized"), "{}", e.message);
2187 assert!(e.message.contains("`missed`"), "{}", e.message);
2188 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2189 assert!(e.message.contains("no file"), "{}", e.message);
2190 }
2191
2192 #[test]
2193 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2194 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2195 assert!(opts.verify_each);
2196 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2197 }
2198
2199 #[test]
2200 fn dash_o_needs_an_argument() {
2201 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2202 assert_eq!(e.message, "-o requires an argument");
2203 }
2204
2205 #[test]
2206 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2207 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2208 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2209 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2210 }
2211
2212 #[test]
2213 fn the_include_flags_land_on_the_chain_each_one_names() {
2214 let (opts, _) = compile(&[
2217 "-Ii",
2218 "-iquote",
2219 "q",
2220 "-isystem",
2221 "sys",
2222 "-idirafter",
2223 "after",
2224 "--sysroot=/nowhere-at-all",
2225 "a.c",
2226 ]);
2227 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2228 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2231 assert!(!opts.search.dirs()[1].is_system);
2232 assert!(opts.search.dirs()[2].is_system);
2233 }
2234
2235 #[test]
2236 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2237 let (opts, _) = compile(&["a.c"]);
2241 let dirs = opts.search.dirs();
2242 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2243 assert_eq!(ours, Some(0), "{dirs:?}");
2244 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2245 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2246 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2247 }
2248
2249 #[test]
2250 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2251 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2252 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2253 assert_eq!(dirs, ["sys", runtime::DIR]);
2254 }
2255
2256 #[test]
2257 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2258 let (opts, _) =
2259 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2260 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2261 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2262 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2264 assert!(!opts.search.searches_current_dir());
2265 }
2266
2267 #[test]
2268 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2269 let (opts, _) = compile(&[
2270 "-iprefix",
2271 "/tools/",
2272 "-iwithprefix",
2273 "late",
2274 "-iwithprefixbefore",
2275 "early",
2276 "-iprefix",
2277 "/other/",
2278 "-iwithprefix",
2279 "last",
2280 "-nostdinc",
2281 "a.c",
2282 ]);
2283 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2284 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2287 assert!(!opts.search.dirs()[0].is_system);
2288 assert!(opts.search.dirs()[1].is_system);
2289 }
2290
2291 #[test]
2292 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2293 let (opts, _) =
2294 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2295 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2296 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2297 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2298 }
2299
2300 #[test]
2301 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2302 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2303 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2304 assert_eq!(dirs, ["i"]);
2305 }
2306
2307 #[test]
2308 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2309 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2310 assert_eq!(opts.std, Std::C11);
2311 assert!(opts.gnu_extensions);
2312
2313 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2314 assert_eq!(opts.std, Std::C99);
2315 assert!(!opts.gnu_extensions);
2316
2317 let (opts, _) = compile(&["-ansi", "a.c"]);
2318 assert_eq!(opts.std, Std::C89);
2319 assert!(!opts.gnu_extensions);
2320
2321 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2322 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2323 }
2324
2325 #[test]
2326 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2327 let (opts, _) = compile(&["-dM", "a.c"]);
2328 assert!(opts.dumps.macros);
2329
2330 let (opts, _) = compile(&["-dDM", "a.c"]);
2333 assert!(opts.dumps.macros);
2334 let (opts, _) = compile(&["-dD", "a.c"]);
2335 assert!(!opts.dumps.macros);
2336
2337 let (opts, _) = compile(&["a.c"]);
2338 assert!(!opts.dumps.any());
2339
2340 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2343 }
2344
2345 #[test]
2346 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2347 let (opts, _) = compile(&["a.c"]);
2348 assert_eq!(
2349 opts.gnuc,
2350 GnucVersion { major: 7, minor: 0, patch: 0 },
2351 "the lowest claim a modern glibc gives its own declarations to"
2352 );
2353
2354 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2355 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2356
2357 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2360 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2361
2362 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2363 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2364
2365 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2366 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2367
2368 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2369 assert!(e.message.contains("more than three"), "{}", e.message);
2370 }
2371
2372 #[test]
2373 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2374 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2375 assert!(opts.pedantic);
2376 assert_eq!(opts.std, Std::C17);
2377
2378 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2381 assert!(opts.pedantic);
2382
2383 let (opts, _) = compile(&["-std=c17", "a.c"]);
2384 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2385 }
2386
2387 #[test]
2388 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2389 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2390 assert!(!opts.line_markers);
2391 assert!(!opts.hosted);
2392 assert_eq!(opts.emit, EmitKind::Preprocessed);
2393 }
2394
2395 #[test]
2402 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2403 let (opts, _) = compile(&["-c", "a.c"]);
2404 assert!(opts.builtins, "a library name means the library function by default");
2405 assert!(opts.no_builtin.is_empty());
2406
2407 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2408 assert!(!opts.builtins);
2409
2410 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2411 assert!(opts.builtins, "the last mention decides");
2412
2413 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2414 assert!(opts.builtins, "one name is not the family");
2415 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2416 }
2417
2418 #[test]
2426 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2427 let (opts, _) = compile(&["-c", "a.c"]);
2428 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2429
2430 for (written, wanted) in [
2431 ("default", Visibility::Default),
2432 ("hidden", Visibility::Hidden),
2433 ("internal", Visibility::Hidden),
2434 ("protected", Visibility::Protected),
2435 ] {
2436 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2437 assert_eq!(opts.visibility, wanted, "{written}");
2438 }
2439
2440 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2443 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2444
2445 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2449 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2450 }
2451
2452 #[test]
2460 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
2461 let (opts, _) = compile(&["-c", "a.c"]);
2462 assert!(!opts.function_sections, "one text section unless something says otherwise");
2463 assert!(!opts.data_sections);
2464
2465 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
2466 assert!(opts.function_sections);
2467 assert!(!opts.data_sections, "one flag is not the other");
2468
2469 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
2470 assert!(opts.data_sections);
2471 assert!(!opts.function_sections);
2472
2473 let (opts, _) = compile(&[
2476 "-c",
2477 "-ffunction-sections",
2478 "-fno-function-sections",
2479 "-fdata-sections",
2480 "-fno-data-sections",
2481 "a.c",
2482 ]);
2483 assert!(!opts.function_sections, "the last mention decides");
2484 assert!(!opts.data_sections, "the last mention decides");
2485 }
2486
2487 #[test]
2490 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2491 let (opts, _) = compile(&["-c", "a.c"]);
2492 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2493
2494 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2495 assert!(opts.gnu89_inline);
2496
2497 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2498 assert!(!opts.gnu89_inline, "the last mention decides");
2499
2500 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2505 assert!(!opts.gnu89_inline);
2506 }
2507
2508 #[test]
2511 fn the_two_frame_flags_are_read_in_both_directions() {
2512 let (opts, _) = compile(&["-c", "a.c"]);
2513 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2514 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2515
2516 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2517 assert!(opts.frame_pointer);
2518 assert!(!opts.red_zone);
2519
2520 let (opts, _) = compile(&[
2521 "-c",
2522 "-fno-omit-frame-pointer",
2523 "-fomit-frame-pointer",
2524 "-mno-red-zone",
2525 "-mred-zone",
2526 "a.c",
2527 ]);
2528 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2529 assert!(opts.red_zone);
2530 }
2531
2532 #[test]
2535 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
2536 let (opts, _) = compile(&["-c", "a.c"]);
2537 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
2538
2539 for (flag, want) in [
2540 ("-fstack-protector", Protector::Buffers),
2541 ("-fstack-protector-strong", Protector::Strong),
2542 ("-fstack-protector-all", Protector::All),
2543 ] {
2544 let (opts, _) = compile(&["-c", flag, "a.c"]);
2545 assert_eq!(opts.protector, want, "{flag}");
2546 }
2547
2548 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
2551 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
2552 assert_eq!(opts.protector, Protector::None, "{off}");
2553 }
2554 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
2555 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
2556 }
2557
2558 #[test]
2561 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
2562 let (opts, _) = compile(&["-c", "a.c"]);
2563 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
2564
2565 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
2566 assert!(opts.stack_clash);
2567
2568 let (opts, _) =
2571 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
2572 assert!(!opts.stack_clash);
2573 let (opts, _) =
2574 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
2575 assert!(opts.stack_clash, "the last one wins either way round");
2576
2577 let (opts, _) =
2579 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
2580 assert!(opts.stack_clash);
2581 assert_eq!(opts.protector, Protector::Strong);
2582 }
2583
2584 #[test]
2585 fn the_link_flags_are_collected_apart_from_the_compilation() {
2586 let (link, _) = linking(&[
2587 "-static",
2588 "-nostartfiles",
2589 "-rdynamic",
2590 "-s",
2591 "-fuse-ld=mold",
2592 "-L/opt/lib",
2593 "-B",
2594 "/opt/tools",
2595 "a.c",
2596 ]);
2597 assert!(link.is_static);
2598 assert!(link.no_startfiles);
2599 assert!(link.export_dynamic);
2600 assert!(link.strip);
2601 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2602 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2603 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2604 }
2605
2606 #[test]
2607 fn a_comma_in_dash_wl_separates_two_arguments() {
2608 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2609 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2610 }
2611
2612 #[test]
2613 fn a_library_keeps_its_place_between_the_objects() {
2614 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2619 let link = plan.link.expect("expected a link step");
2620 assert_eq!(
2621 link.inputs,
2622 vec![
2623 link::Item::File("a.o".into()),
2624 link::Item::Library("m".into()),
2625 link::Item::File("b.o".into()),
2626 ]
2627 );
2628 assert_eq!(plan.jobs.len(), 2);
2630 }
2631
2632 #[test]
2633 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2634 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2635 assert!(plan.link.is_none());
2636 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2637 }
2638
2639 #[test]
2640 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2641 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2642 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2643 }
2644
2645 fn printed(s: &[&str]) -> String {
2646 match parse_args(&args(s)).expect("expected an answer") {
2647 Action::Print(line) => line,
2648 other => panic!("expected an answer, got {other:?}"),
2649 }
2650 }
2651
2652 fn refused(s: &[&str]) -> String {
2653 parse_args(&args(s)).expect_err("expected a refusal").message
2654 }
2655
2656 #[test]
2657 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2658 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2662 assert!(!opts.warnings_are_errors);
2663 assert!(opts.warnings);
2664 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2666 assert!(opts.warnings_are_errors);
2667 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2668 assert!(!opts.warnings);
2669 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2670 assert!(opts.pedantic && opts.warnings_are_errors);
2671 }
2672
2673 #[test]
2674 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2675 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2677 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2678 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2679 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2680 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2681 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2682 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2685 assert!(no32.contains("32 bit target"), "{no32}");
2686 }
2687
2688 #[test]
2689 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2690 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2691 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2692 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2693 }
2694
2695 #[test]
2696 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2697 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2698 let (opts, _) =
2699 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2700 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2701 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2702 assert!(wrong.contains("sysv convention"), "{wrong}");
2703 }
2704
2705 #[test]
2706 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2707 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2708 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2709 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2712 assert_eq!(names, vec!["a.c"]);
2713 }
2714
2715 #[test]
2716 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2717 let target = "--target=x86_64-unknown-linux-gnu";
2718 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2719 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2720 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2721 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2722 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2725 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2726 let dirs = printed(&[target, "-print-search-dirs"]);
2727 assert!(dirs.starts_with("install: "), "{dirs}");
2728 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2729 }
2730
2731 #[test]
2732 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2733 let (opts, _) = compile(&["-M", "a.c"]);
2734 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2735 assert!(opts.deps.system_headers, "plain -M lists them");
2736 assert_eq!(opts.emit, EmitKind::Preprocessed);
2737
2738 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2741 assert_eq!(opts.emit, EmitKind::Preprocessed);
2742
2743 let (opts, _) = compile(&["-MM", "a.c"]);
2744 assert!(!opts.deps.system_headers);
2745 }
2746
2747 #[test]
2748 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2749 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2750 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2751 assert!(opts.deps.system_headers);
2752 assert_eq!(opts.emit, EmitKind::Object);
2753
2754 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2755 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2756 assert!(!opts.deps.system_headers);
2757 }
2758
2759 #[test]
2760 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2761 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2764 assert!(!opts.deps.system_headers);
2765 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2766 assert!(!opts.deps.system_headers);
2767 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2768 assert!(!opts.deps.system_headers);
2769 }
2770
2771 #[test]
2772 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2773 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2774 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2775 }
2776
2777 #[test]
2778 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2779 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2780 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2781 assert!(opts.deps.phony);
2782
2783 for flag in ["-MF", "-MT", "-MQ"] {
2784 let e = parse_args(&args(&[flag])).unwrap_err();
2785 assert!(e.message.contains("requires an argument"), "{}", e.message);
2786 }
2787 }
2788
2789 struct TempTree(PathBuf);
2791
2792 impl Drop for TempTree {
2793 fn drop(&mut self) {
2794 let _ = std::fs::remove_dir_all(&self.0);
2795 }
2796 }
2797
2798 impl TempTree {
2799 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2800 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2801 let _ = std::fs::remove_dir_all(&dir);
2802 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2803 for (path, text) in files {
2804 let at = dir.join(path);
2805 if let Some(parent) = at.parent() {
2806 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2807 }
2808 std::fs::write(&at, text).expect("writing a temporary file should work");
2809 }
2810 TempTree(dir)
2811 }
2812
2813 fn path(&self, name: &str) -> String {
2814 self.0.join(name).to_string_lossy().into_owned()
2815 }
2816 }
2817
2818 #[test]
2819 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2820 let tree = TempTree::new(
2824 "found",
2825 &[
2826 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2827 ("one.h", "#define X 0\n"),
2828 ("two.h", "#include \"one.h\"\n"),
2829 ],
2830 );
2831 let out = tree.path("dep.d");
2832 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2833 assert_eq!(code, 0);
2834
2835 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2836 let names: Vec<&str> = text.split_whitespace().collect();
2837 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2839 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2840 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2841 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2844 }
2845
2846 #[test]
2847 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2848 let tree = TempTree::new(
2851 "guarded",
2852 &[
2853 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2854 ("g.h", "#ifndef G\n#define G\n#endif\n"),
2855 ],
2856 );
2857 let out = tree.path("dep.d");
2858 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2859 assert_eq!(code, 0);
2860 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2861 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2862 }
2863
2864 #[test]
2865 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2866 let tree = TempTree::new(
2871 "preinclude",
2872 &[
2873 ("a.c", "int main(void) { return 0; }\n"),
2874 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2875 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2876 ],
2877 );
2878 let out = tree.path("a.i");
2879 let code = run(&args(&[
2880 "-E",
2881 "-include",
2882 &tree.path("i.h"),
2883 "-imacros",
2884 &tree.path("m.h"),
2885 "-o",
2886 &out,
2887 &tree.path("a.c"),
2888 ]));
2889 assert_eq!(code, 0);
2890 let text = std::fs::read_to_string(&out).expect("the output should have been written");
2891 assert!(text.contains("saw_it"), "{text}");
2892 assert!(!text.contains("macros_text"), "{text}");
2895 }
2896
2897 #[test]
2898 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
2899 let tree = TempTree::new(
2900 "preinclude-deps",
2901 &[
2902 ("a.c", "int main(void) { return 0; }\n"),
2903 ("i.h", "int from_include;\n"),
2904 ("m.h", "#define M 1\n"),
2905 ],
2906 );
2907 let out = tree.path("dep.d");
2908 let code = run(&args(&[
2909 "-MM",
2910 "-MF",
2911 &out,
2912 "-include",
2913 &tree.path("i.h"),
2914 "-imacros",
2915 &tree.path("m.h"),
2916 "-o",
2917 &tree.path("a.i"),
2918 &tree.path("a.c"),
2919 ]));
2920 assert_eq!(code, 0);
2921 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2922 assert!(text.contains("i.h"), "{text}");
2923 assert!(text.contains("m.h"), "{text}");
2924 }
2925
2926 #[test]
2927 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
2928 let tree = TempTree::new(
2932 "preinclude-missing",
2933 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
2934 );
2935 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
2936 assert_eq!(code, 1);
2937 }
2938
2939 #[test]
2940 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
2941 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
2945 assert_eq!(plan.output.as_deref(), Some("prog"));
2946 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
2947 assert_eq!(
2948 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
2949 Some("prog.d")
2950 );
2951 }
2952
2953 #[test]
2954 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
2955 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
2956 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
2957 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
2958 assert_eq!(plan.output, None);
2959 }
2960
2961 #[test]
2962 fn usage_fits_on_a_screen() {
2963 assert!(USAGE.lines().count() < 51, "usage text has grown past one screen");
2987 }
2988}