1#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.9")]
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, -fstack-protector-strong, -fstack-protector-all, -fno-stack-protector
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 "-nostdinc" => nostdinc = true,
401 "-o" => {
402 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
403 i += 1;
404 }
405 "-isysroot" => {
412 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
413 i += 1;
414 sysroot = Some(PathBuf::from(dir));
415 }
416 "-iquote" | "-isystem" | "-idirafter" => {
417 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
418 i += 1;
419 match arg {
420 "-iquote" => opts.search.push_quote(dir.clone()),
421 "-isystem" => opts.search.push_system(dir.clone()),
422 _ => opts.search.push_after(dir.clone()),
423 }
424 }
425 "-iprefix" => {
426 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
427 i += 1;
428 }
429 "-iwithprefix" | "-iwithprefixbefore" => {
435 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
436 i += 1;
437 let dir = format!("{iprefix}{dir}");
438 if arg == "-iwithprefix" {
439 opts.search.push_system(dir);
440 } else {
441 opts.search.push_bracket(dir);
442 }
443 }
444 "-include" | "-imacros" => {
445 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
446 i += 1;
447 opts.preincludes
448 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
449 }
450 "-I-" => opts.search.split_quote_chain(),
455 "-x" => {
456 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
457 i += 1;
458 forced = if lang == "none" {
459 None
460 } else {
461 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
462 };
463 }
464 _ if arg.starts_with("-D") => {
472 let value = joined_or_next(arg, 2, args, &mut i)?;
473 opts.defines.push(value);
474 }
475 _ if arg.starts_with("-U") => {
476 let value = joined_or_next(arg, 2, args, &mut i)?;
477 opts.undefines.push(value);
478 }
479 _ if arg.starts_with("-I") => {
480 let dir = joined_or_next(arg, 2, args, &mut i)?;
481 opts.search.push_bracket(dir);
482 }
483 _ if arg.starts_with("-std=") => {
484 let name = &arg["-std=".len()..];
485 let (std, gnu) = Std::from_flag(name)
486 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
487 opts.std = std;
488 opts.gnu_extensions = gnu;
489 }
490 _ if Dumps::is_family(arg) => {
499 opts.dumps.add(&arg[2..]);
500 }
501 _ if arg.starts_with("-fno-builtin-") => {
506 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
507 }
508 _ if arg.starts_with("-fgnuc-version=") => {
509 let v = &arg["-fgnuc-version=".len()..];
510 opts.gnuc = v.parse().map_err(err)?;
511 }
512 "-fnested-functions" => {
517 return Err(err(
518 "nested functions are not supported: a call to one goes through a trampoline \
519 written on the stack, which no target that enforces an unexecutable stack \
520 allows",
521 ));
522 }
523 "-fno-nested-functions" => {}
524 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
535 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
539 "-fsemantic-interposition" => opts.interposition = true,
546 "-fno-semantic-interposition" => opts.interposition = false,
547 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
552 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
553 "-funwind-tables" => opts.unwind_tables = true,
554 "-fno-unwind-tables" => opts.unwind_tables = false,
555 "-fno-pic" | "-fno-pie" => {
562 return Err(err(
563 "position dependent code is not supported: an address that may be in another \
564 object is loaded out of the global offset table, and nothing here emits the \
565 absolute form this asks for. Use -no-pie if what you meant was how to link",
566 ));
567 }
568 "-ffunction-sections" => opts.function_sections = true,
574 "-fno-function-sections" => opts.function_sections = false,
575 "-fdata-sections" => opts.data_sections = true,
576 "-fno-data-sections" => opts.data_sections = false,
577 "-fno-common" => {}
583 "-fcommon" => {
587 return Err(err(
588 "a tentative definition is written into .bss as its own symbol here, and \
589 nothing emits the common symbol this asks the linker to merge. Give the \
590 variable a definition in one file and declare it extern in the others",
591 ));
592 }
593 "-fstrict-aliasing" | "-fno-strict-aliasing" => {}
607 "-pipe" => {}
610 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
617 _ if arg.starts_with("-fdiagnostics-color=") => {}
618 "-static" => link.is_static = true,
622 "-shared" => link.shared = true,
623 "-pie" => link.pie = Some(true),
624 "-no-pie" | "-nopie" => link.pie = Some(false),
625 "-nostdlib" => link.no_stdlib = true,
626 "-nostartfiles" => link.no_startfiles = true,
627 "-nodefaultlibs" => link.no_defaultlibs = true,
628 "-fno-builtins-lib" => link.no_builtins_lib = true,
629 "-fbuiltins-lib" => link.no_builtins_lib = false,
630 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
631 "-s" => link.strip = true,
632 "-Xlinker" => {
633 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
634 i += 1;
635 link.passthrough.push(next.clone());
636 }
637 _ if arg.starts_with("-Wl,") => {
638 link.passthrough.extend(arg["-Wl,".len()..].split(',').map(str::to_owned));
641 }
642 _ if arg.starts_with("-fuse-ld=") => {
643 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
644 }
645 _ if arg.starts_with("-l") && arg.len() > 2 => {
646 inputs.push(Input::library(&arg[2..]));
647 }
648 "-l" => {
649 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
650 i += 1;
651 inputs.push(Input::library(next));
652 }
653 _ if arg.starts_with("-L") => {
654 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
655 }
656 _ if arg.starts_with("-B") => {
657 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
658 }
659 _ if arg.starts_with("-j") => {
660 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
661 }
662 _ if arg.starts_with("--sysroot=") => {
663 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
664 }
665 _ if arg.starts_with("--target=") => {
666 let t = &arg["--target=".len()..];
667 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
668 }
669 _ if arg.starts_with("--emit=") => {
670 let k = &arg["--emit=".len()..];
671 opts.emit = k
672 .parse()
673 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
674 }
675 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
681 "-Ofast" => {
687 return Err(err(
688 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
689 spec/04-driver-and-cli.md section 4.6",
690 ));
691 }
692 _ if arg.starts_with("-O") => {
693 opts.opt_level = arg[2..]
694 .parse()
695 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
696 }
697 _ if arg.starts_with("-fvisibility=") => {
701 let seen = &arg["-fvisibility=".len()..];
702 opts.visibility = seen.parse().map_err(|()| {
703 err(format!(
704 "`{seen}` is not a visibility, which is default, hidden, internal or \
705 protected"
706 ))
707 })?;
708 }
709 _ if arg.starts_with("-fsafety=") => {
714 let tier = &arg["-fsafety=".len()..];
715 opts.safety = tier.parse().map_err(|()| {
716 err(format!(
717 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
718 ))
719 })?;
720 }
721 _ if arg.starts_with("-fpass-fuel=") => {
725 let (name, count) = arg["-fpass-fuel=".len()..]
726 .split_once('=')
727 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
728 if rucc_opt::pass::find(name).is_none() {
729 return Err(err(format!(
730 "`{name}` is not a pass this compiler has, see --print-pipeline"
731 )));
732 }
733 let count: u32 = count
734 .parse()
735 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
736 opts.pass_fuel.push((name.to_owned(), count));
737 }
738 _ if arg.starts_with("-fpass-fuel-global=") => {
739 let count = &arg["-fpass-fuel-global=".len()..];
740 let count: u32 = count
741 .parse()
742 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
743 opts.pass_fuel_global = Some(count);
744 }
745 _ if arg == "-fopt-info"
750 || arg.starts_with("-fopt-info=")
751 || arg.starts_with("-fopt-info-") =>
752 {
753 let rest = &arg["-fopt-info".len()..];
754 let (kinds, file) = match rest.split_once('=') {
755 Some((kinds, file)) => (kinds, Some(file)),
756 None => (rest, None),
757 };
758 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
759 rucc_opt::Wants::none().add(kinds).map_err(err)?;
760 opts.opt_info.push(kinds.to_owned());
761 if let Some(file) = file {
762 if file.is_empty() {
763 return Err(err("-fopt-info= was given no file to write to"));
764 }
765 opts.opt_info_file = Some(file.to_owned());
766 }
767 }
768 _ if arg.starts_with("-fdump-ir=") => {
769 let spec = &arg["-fdump-ir=".len()..];
772 rucc_opt::Dumps::default().add(spec).map_err(err)?;
773 opts.dump_ir.push(spec.to_owned());
774 }
775 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
781 let on = arg.starts_with("-fenable-");
782 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
783 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
784 opts.pass_gates.push((on, spec.to_owned()));
785 }
786 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
787 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
788 }
789 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
790 opts.passes.push((arg["-f".len()..].to_owned(), true));
791 }
792 "-Zverify-each" => opts.verify_each = true,
798 _ if arg.starts_with("-Zrule-coverage=") => {
799 let file = &arg["-Zrule-coverage=".len()..];
800 if file.is_empty() {
801 return Err(err("-Zrule-coverage= needs a file to write to"));
802 }
803 opts.rule_coverage = Some(file.to_owned());
804 }
805 _ if arg.starts_with("-Zregister-pressure=") => {
806 let file = &arg["-Zregister-pressure=".len()..];
807 if file.is_empty() {
808 return Err(err("-Zregister-pressure= needs a file to write to"));
809 }
810 opts.register_pressure = Some(file.to_owned());
811 }
812 _ if arg.starts_with("-Z") => {
813 return Err(err(format!(
814 "`{arg}` is not an unstable option this compiler has, see \
815 spec/04-driver-and-cli.md section 4.11 for the ones it does"
816 )));
817 }
818 "-m64" | "-m32" | "-mx32" => {
823 let want: u32 = match arg {
824 "-m64" => 64,
825 _ => 32,
826 };
827 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
828 if have != want {
829 return Err(err(format!(
830 "{arg} asks for a {want} bit target and {} is {have} bit, use \
831 --target= to name the one you mean",
832 opts.target
833 )));
834 }
835 }
836 _ if arg.starts_with("-march=")
842 || arg.starts_with("-mtune=")
843 || arg.starts_with("-mcpu=") => {}
844 _ if arg.starts_with("-mabi=") => {
847 let want = &arg["-mabi=".len()..];
848 let have = match opts.target.arch {
849 rucc_target::Arch::X86_64 => "sysv",
850 rucc_target::Arch::Aarch64 => "lp64",
851 rucc_target::Arch::Riscv64 => "lp64d",
852 };
853 if want != have {
854 return Err(err(format!(
855 "{arg}: {} uses the {have} convention and this compiler has no other",
856 opts.target
857 )));
858 }
859 }
860 "-mcmodel=small" => {}
864 _ if arg.starts_with("-mcmodel=") => {
865 return Err(err(format!(
866 "{arg}: this compiler emits the small code model and no other, see \
867 spec/12-targets.md"
868 )));
869 }
870 _ if arg.starts_with("-specs=") => {
874 return Err(err(
875 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
876 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
877 section 4.4",
878 ));
879 }
880 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
886 return Err(err(format!(
887 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
888 are inside this compiler rather than programs it runs"
889 )));
890 }
891 "-Xassembler" | "-Xpreprocessor" => {
892 return Err(err(format!(
893 "{arg} hands an argument to a separate assembler or preprocessor, and both \
894 are inside this compiler rather than programs it runs"
895 )));
896 }
897 _ if arg.starts_with("-W") => {}
904 "-fno-ident"
910 | "-fident"
911 | "-funit-at-a-time"
912 | "-fno-unit-at-a-time"
913 | "-shared-libgcc"
914 | "-static-libgcc" => {}
915 _ if arg.starts_with('-') && arg.len() > 1 => {
916 return Err(err(format!("unknown option `{arg}`")));
921 }
922 _ => inputs.push(Input { path: arg.to_owned(), forced, library: false }),
923 }
924 }
925
926 link.sysroot = sysroot.clone();
933 if threads {
938 inputs.push(Input::library("pthread"));
939 }
940 if let Some(query) = query {
941 return Ok(Action::Print(answer(&query, &opts, &link)));
942 }
943 if opts.deps.instead_of_compiling {
949 opts.emit = EmitKind::Preprocessed;
950 }
951 if !nostdinc {
952 opts.search.push_system(runtime::DIR);
953 for dir in library::system_dirs(opts.target, sysroot.as_deref()) {
957 opts.search.push_system(dir);
958 }
959 }
960 opts.search.remove_duplicates();
964
965 if print_config {
968 return Ok(Action::PrintConfig(Box::new(opts)));
969 }
970 if print_pipeline {
971 return Ok(Action::PrintPipeline(Box::new(opts)));
972 }
973 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
974 if print_plan {
975 return Ok(Action::PrintPlan {
976 opts: Box::new(opts),
977 plan: Box::new(plan),
978 link: Box::new(link),
979 });
980 }
981 Ok(Action::Compile {
982 opts: Box::new(opts),
983 plan: Box::new(plan),
984 link: Box::new(link),
985 jobs,
986 verbose,
987 })
988}
989
990fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> String {
996 let found = |name: &str| {
997 link::find_in_search(link, opts.target, name)
998 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
999 };
1000 match query {
1001 Query::Machine => opts.target.to_string(),
1002 Query::Version => VERSION.to_owned(),
1003 Query::Multiarch => link::multiarch(opts.target),
1004 Query::SearchDirs => {
1009 let here = std::env::current_exe()
1010 .ok()
1011 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
1012 .unwrap_or_default();
1013 let list = |dirs: &[PathBuf]| {
1014 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
1015 };
1016 let libraries = link::search_dirs(link, opts.target);
1017 format!(
1018 "install: {}\nprograms: ={}\nlibraries: ={}",
1019 here.display(),
1020 list(&link.prefixes),
1021 list(&libraries)
1022 )
1023 }
1024 Query::FileName(name) => found(name),
1025 Query::Libgcc => found("libgcc.a"),
1029 Query::ProgName(name) => link
1033 .prefixes
1034 .iter()
1035 .map(|dir| dir.join(name))
1036 .find(|path| path.is_file())
1037 .map_or_else(|| name.clone(), |path| path.display().to_string()),
1038 }
1039}
1040
1041#[must_use]
1047pub fn print_pipeline(opts: &Options) -> String {
1048 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
1049 settings.toggles.clone_from(&opts.passes);
1050 settings.global_fuel = opts.pass_fuel_global;
1051 for (on, spec) in &opts.pass_gates {
1052 let _ = settings.gates.add(*on, spec);
1055 }
1056 rucc_opt::pipeline::print(&settings)
1057}
1058
1059#[must_use]
1064pub fn print_config(opts: &Options) -> String {
1065 let sess = Session::new(opts.clone());
1066 let t = &sess.target;
1067 let mut out = String::new();
1068 let _ = writeln!(out, "version: {VERSION}");
1069 let _ = writeln!(out, "target: {}", opts.target);
1073 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
1074 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
1075 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
1076 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
1077 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
1078 let _ = writeln!(out, "long-width: {}", t.long_width);
1079 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
1080 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
1081 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
1082 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
1083 let regs: Vec<String> = t
1086 .regs
1087 .classes()
1088 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
1089 .collect();
1090 let _ = writeln!(
1091 out,
1092 "registers: {}",
1093 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
1094 );
1095 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
1096 let _ = writeln!(out, "safety: {}", sess.opts.safety);
1097 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
1098 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
1099 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
1100 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
1101 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
1102 for dir in sess.opts.search.dirs() {
1105 let system = if dir.is_system { " (system)" } else { "" };
1106 let _ = writeln!(out, "include: {}{system}", dir.path.display());
1107 }
1108 out
1109}
1110
1111fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
1119 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
1120}
1121
1122fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
1125 if path == "-" {
1126 return write_out(&Output::Stdout, bytes);
1127 }
1128 write_out(&Output::File(path.to_owned()), bytes)
1129}
1130
1131fn write_deps(
1137 opts: &Options,
1138 plan: &Plan,
1139 job: &Job,
1140 found: &[Dependency],
1141 stderr: &mut impl std::io::Write,
1142) -> bool {
1143 let targets = if opts.deps.targets.is_empty() {
1144 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
1145 } else {
1146 opts.deps.targets.clone()
1147 };
1148 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
1149 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
1152 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
1156 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
1157 }),
1158 None => write_out(&job.output, rule.as_bytes()),
1159 };
1160 if let Err(e) = wrote {
1161 let _ = writeln!(stderr, "rucc: error: {e}");
1162 return false;
1163 }
1164 true
1165}
1166
1167fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
1173 let fs = OsFileSystem::new();
1174 let mut stderr = std::io::stderr().lock();
1175 let mut failed = false;
1176 for job in &plan.jobs {
1177 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
1178 continue;
1181 }
1182 let started = std::time::Instant::now();
1183 let result = preprocess(opts, &job.input, &fs);
1184 if opts.time {
1185 say_time(&job.input, started.elapsed(), &mut stderr);
1186 }
1187 for message in &result.messages {
1188 let _ = writeln!(stderr, "{message}");
1189 }
1190 if result.failed() {
1191 failed = true;
1192 continue;
1193 }
1194 if opts.deps.emit {
1195 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1196 if opts.deps.instead_of_compiling {
1199 continue;
1200 }
1201 }
1202 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
1203 let _ = writeln!(stderr, "rucc: error: {e}");
1204 failed = true;
1205 }
1206 }
1207 i32::from(failed)
1208}
1209
1210fn compile_all(opts: &Options, plan: &Plan) -> i32 {
1216 let fs = OsFileSystem::new();
1217 let mut stderr = std::io::stderr().lock();
1218 let mut failed = false;
1219 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1220 failed |= !ok;
1221 let mut fired = Fired::new();
1222 let mut pressure = Pressure::new();
1223 for job in &plan.jobs {
1224 if !job.phases.contains(&Phase::Compile) {
1225 continue;
1226 }
1227 let started = std::time::Instant::now();
1231 let result = if job.kind == InputKind::Ir {
1232 compile_ir(opts, &job.input, &fs)
1233 } else {
1234 compile(opts, &job.input, &fs)
1235 };
1236 if opts.time {
1237 say_time(&job.input, started.elapsed(), &mut stderr);
1238 }
1239 fired.merge(&result.fired);
1240 pressure.merge(&result.pressure);
1241 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1242 failed |= !remarks.write(&result.remarks, &mut stderr);
1243 for message in &result.messages {
1244 let _ = writeln!(stderr, "{message}");
1245 }
1246 failed |= !write_temps(job, &result.temps, &mut stderr);
1249 if result.failed() {
1250 failed = true;
1251 continue;
1252 }
1253 if opts.deps.emit {
1258 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1259 }
1260 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
1261 let _ = writeln!(stderr, "rucc: error: {e}");
1262 failed = true;
1263 }
1264 }
1265 failed |= !write_coverage(opts, &fired, &mut stderr);
1266 failed |= !write_pressure(opts, &pressure, &mut stderr);
1267 i32::from(failed)
1268}
1269
1270struct Scratch {
1277 dir: PathBuf,
1279}
1280
1281impl Scratch {
1282 fn new() -> Result<Scratch, String> {
1288 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
1289 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1290 Ok(Scratch { dir })
1291 }
1292}
1293
1294impl Drop for Scratch {
1295 fn drop(&mut self) {
1296 let _ = std::fs::remove_dir_all(&self.dir);
1297 }
1298}
1299
1300fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
1307 let linker = link::find(opts.target, link)?;
1308 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
1309 Ok(link::render(&linker, &args))
1310}
1311
1312fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
1319 let Some(job) = &plan.link else {
1320 let mut stderr = std::io::stderr().lock();
1323 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
1324 return 1;
1325 };
1326 let linker = match link::find(opts.target, link) {
1329 Ok(linker) => linker,
1330 Err(why) => return complain(why),
1331 };
1332
1333 let scratch = match Scratch::new() {
1334 Ok(scratch) => scratch,
1335 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
1336 };
1337
1338 let fs = OsFileSystem::new();
1339 let mut failed = false;
1340 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
1343 let mut fired = Fired::new();
1344 let mut pressure = Pressure::new();
1345 {
1346 let mut stderr = std::io::stderr().lock();
1347 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
1348 failed |= !ok;
1349 for (at, job) in plan.jobs.iter().enumerate() {
1350 let out = match &job.output {
1351 Output::Temporary(hint) => {
1352 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
1355 }
1356 Output::File(path) => path.clone(),
1357 Output::Stdout => continue,
1360 };
1361 produced.push(out.clone());
1362 if !job.phases.contains(&Phase::Compile) {
1363 continue;
1364 }
1365 let started = std::time::Instant::now();
1366 let result = if job.kind == InputKind::Ir {
1367 compile_ir(opts, &job.input, &fs)
1368 } else {
1369 compile(opts, &job.input, &fs)
1370 };
1371 if opts.time {
1372 say_time(&job.input, started.elapsed(), &mut stderr);
1373 }
1374 fired.merge(&result.fired);
1375 pressure.merge(&result.pressure);
1376 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
1377 failed |= !remarks.write(&result.remarks, &mut stderr);
1378 for message in &result.messages {
1379 let _ = writeln!(stderr, "{message}");
1380 }
1381 failed |= !write_temps(job, &result.temps, &mut stderr);
1382 if result.failed() {
1383 failed = true;
1384 continue;
1385 }
1386 if opts.deps.emit {
1391 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
1392 }
1393 if !matches!(result.artifact, Artifact::Object(_)) {
1394 let _ = writeln!(
1399 stderr,
1400 "rucc: internal error: {}: no object file was produced for the link",
1401 job.input
1402 );
1403 failed = true;
1404 continue;
1405 }
1406 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
1407 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
1408 failed = true;
1409 }
1410 }
1411 failed |= !write_coverage(opts, &fired, &mut stderr);
1412 failed |= !write_pressure(opts, &pressure, &mut stderr);
1413 }
1414 if failed {
1415 return 1;
1419 }
1420
1421 let mut outputs = produced.into_iter();
1425 let mut items = Vec::with_capacity(job.inputs.len());
1426 for item in &job.inputs {
1427 match item {
1428 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
1429 link::Item::File(_) => match outputs.next() {
1430 Some(path) => items.push(link::Item::File(path)),
1431 None => return complain("the plan asks the linker for a file nothing produced"),
1432 },
1433 }
1434 }
1435
1436 let args = match link::line(opts.target, link, &items, &job.output) {
1437 Ok(args) => args,
1438 Err(why) => return complain(why),
1439 };
1440 if verbose {
1441 let mut stderr = std::io::stderr().lock();
1442 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
1443 }
1444 let started = std::time::Instant::now();
1445 let ran = link::run(&linker, &args);
1446 if opts.time {
1447 let mut stderr = std::io::stderr().lock();
1450 say_time(&linker.name, started.elapsed(), &mut stderr);
1451 }
1452 match ran {
1453 Ok(()) => 0,
1454 Err(link::Error::Refused { .. }) => 1,
1457 Err(why) => complain(why),
1458 }
1459}
1460
1461fn complain(why: impl std::fmt::Display) -> i32 {
1463 let mut stderr = std::io::stderr().lock();
1464 let _ = writeln!(stderr, "rucc: error: {why}");
1465 1
1466}
1467
1468fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
1477 let Some(path) = &opts.rule_coverage else { return true };
1478 let Some(table) = coverage::table(opts.target.arch) else {
1479 let _ = writeln!(
1480 stderr,
1481 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
1482 to report",
1483 opts.target
1484 );
1485 return false;
1486 };
1487 match std::fs::write(path, fired.listing(table)) {
1488 Ok(()) => true,
1489 Err(e) => {
1490 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1491 false
1492 }
1493 }
1494}
1495
1496fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
1504 let Some(path) = &opts.register_pressure else { return true };
1505 match std::fs::write(path, pressure.listing()) {
1506 Ok(()) => true,
1507 Err(e) => {
1508 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1509 false
1510 }
1511 }
1512}
1513
1514struct Remarks {
1521 file: Option<String>,
1523 started: bool,
1526}
1527
1528impl Remarks {
1529 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
1535 let mut ok = true;
1536 if let Some(path) = file {
1537 if let Err(e) = std::fs::write(path, "") {
1538 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1539 ok = false;
1540 }
1541 }
1542 (Self { file: file.cloned(), started: false }, ok)
1543 }
1544
1545 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
1551 if text.is_empty() {
1552 return true;
1553 }
1554 let Some(path) = &self.file else {
1555 let _ = write!(stderr, "{text}");
1556 return true;
1557 };
1558 let opened = std::fs::OpenOptions::new()
1559 .write(true)
1560 .append(self.started)
1561 .truncate(!self.started)
1562 .create(true)
1563 .open(path);
1564 self.started = true;
1565 let result =
1566 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
1567 if let Err(e) = result {
1568 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1569 return false;
1570 }
1571 true
1572 }
1573}
1574
1575fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
1586 let stem = std::path::Path::new(input)
1587 .file_name()
1588 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
1589 let mut ok = true;
1590 for dump in dumps {
1591 let path = format!("{stem}.{}.ir", dump.name);
1592 if let Err(e) = std::fs::write(&path, &dump.text) {
1593 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1594 ok = false;
1595 }
1596 }
1597 ok
1598}
1599
1600fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
1606 let mut ok = true;
1607 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
1608 for (path, text) in kept {
1609 let (Some(path), Some(text)) = (path, text) else { continue };
1612 if let Err(e) = std::fs::write(&path, text) {
1613 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
1614 ok = false;
1615 }
1616 }
1617 ok
1618}
1619
1620fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
1627 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
1628}
1629
1630fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
1637 match output {
1638 Output::Stdout => {
1639 let mut stdout = std::io::stdout().lock();
1640 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
1641 }
1642 Output::File(path) | Output::Temporary(path) => {
1643 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
1644 }
1645 }
1646}
1647
1648pub fn run(args: &[String]) -> i32 {
1653 match parse_args(args) {
1654 Ok(Action::Help) => {
1655 print!("{USAGE}");
1656 0
1657 }
1658 Ok(Action::Version) => {
1659 println!("rucc {VERSION}");
1660 0
1661 }
1662 Ok(Action::Print(line)) => {
1663 println!("{line}");
1664 0
1665 }
1666 Ok(Action::PrintConfig(opts)) => {
1667 print!("{}", print_config(&opts));
1668 0
1669 }
1670 Ok(Action::PrintPipeline(opts)) => {
1671 print!("{}", print_pipeline(&opts));
1672 0
1673 }
1674 Ok(Action::PrintPlan { opts, plan, link }) => {
1675 print!("{}", plan.render());
1676 if let Some(job) = &plan.link {
1680 match link_line(&opts, &link, job) {
1681 Ok(line) => println!("{line}"),
1682 Err(why) => {
1683 let mut stderr = std::io::stderr().lock();
1684 let _ = writeln!(stderr, "rucc: error: {why}");
1685 return 1;
1686 }
1687 }
1688 }
1689 0
1690 }
1691 Ok(Action::Compile { opts, plan, link, jobs, verbose }) => {
1692 {
1693 let mut stderr = std::io::stderr().lock();
1694 if verbose {
1695 let _ = write!(stderr, "{}", plan.render());
1696 let _ = writeln!(stderr, "workers: {}", jobs.count());
1697 }
1698 }
1699 if opts.emit == EmitKind::Preprocessed {
1700 return preprocess_all(&opts, &plan);
1701 }
1702 if opts.emit != EmitKind::Executable {
1703 return compile_all(&opts, &plan);
1704 }
1705 link_all(&opts, &plan, &link, verbose)
1706 }
1707 Err(e) => {
1708 let mut stderr = std::io::stderr().lock();
1709 let _ = writeln!(stderr, "rucc: error: {e}");
1710 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
1711 1
1712 }
1713 }
1714}
1715
1716#[cfg(test)]
1717mod tests {
1718 use rucc_session::{GnucVersion, IncludeForm, OptLevel, Visibility};
1719
1720 use super::*;
1721
1722 fn args(s: &[&str]) -> Vec<String> {
1723 s.iter().map(|x| (*x).to_owned()).collect()
1724 }
1725
1726 #[test]
1727 fn help_and_version_win_over_everything_else() {
1728 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
1729 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
1730 }
1731
1732 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
1733 match parse_args(&args(s)).expect("expected a compilation") {
1734 Action::Compile { opts, plan, .. } => (opts, plan),
1735 other => panic!("expected a compilation, got {other:?}"),
1736 }
1737 }
1738
1739 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
1740 match parse_args(&args(s)).expect("expected a compilation") {
1741 Action::Compile { link, plan, .. } => (link, plan),
1742 other => panic!("expected a compilation, got {other:?}"),
1743 }
1744 }
1745
1746 #[test]
1747 fn collects_inputs_and_flags() {
1748 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
1749 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
1750 assert_eq!(paths, vec!["a.c", "b.c"]);
1751 assert_eq!(opts.opt_level, OptLevel::O2);
1752 assert_eq!(opts.emit, EmitKind::Object);
1753 assert!(opts.debug_info);
1754 }
1755
1756 #[test]
1759 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
1760 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
1761 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
1762
1763 let (plain, _) = compile(&["-c", "a.c"]);
1764 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
1765
1766 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
1767 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
1768 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
1769 }
1770
1771 #[test]
1773 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
1774 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
1775 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
1776
1777 let (plain, _) = compile(&["-c", "a.c"]);
1778 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
1779
1780 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
1781 }
1782
1783 #[test]
1784 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
1785 let (opts, _) = compile(&["-O", "a.c"]);
1786 assert_eq!(opts.opt_level, OptLevel::O1);
1787 }
1788
1789 #[test]
1790 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
1791 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
1792 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
1793 assert_eq!(plan.jobs[1].kind, InputKind::C);
1794 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
1795 }
1796
1797 #[test]
1798 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
1799 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
1800 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
1801 other => panic!("expected a compilation, got {other:?}"),
1802 };
1803 assert_eq!(jobs.count(), 4);
1804
1805 let default = match parse_args(&args(&["a.c"])).unwrap() {
1806 Action::Compile { jobs, .. } => jobs,
1807 other => panic!("expected a compilation, got {other:?}"),
1808 };
1809 assert_eq!(default, Jobs::available());
1810 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
1811 }
1812
1813 #[test]
1814 fn triple_hash_prints_the_plan_and_runs_nothing() {
1815 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
1816 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
1817 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
1818 }
1819
1820 #[test]
1821 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
1822 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
1826 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
1827 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
1828 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
1829 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
1833 assert_eq!(opts.save_temps, SaveTemps::Cwd);
1834 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
1835 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
1836 }
1837
1838 #[test]
1839 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
1840 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
1841 let (plain, without) = compile(&["-c", "a.c"]);
1842 assert!(opts.time);
1843 assert!(!plain.time);
1844 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
1847 }
1848
1849 #[test]
1850 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
1851 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
1852 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
1853 }
1854
1855 #[test]
1856 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
1857 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
1858 assert!(e.message.contains("unknown option"), "{}", e.message);
1859 }
1860
1861 #[test]
1864 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
1865 let (opts, _) = compile(&["-c", "a.c"]);
1866 assert!(!opts.permissive, "off unless it is asked for");
1867
1868 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
1869 assert!(opts.permissive);
1870
1871 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
1872 assert!(!opts.permissive);
1873 }
1874
1875 #[test]
1876 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
1877 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
1878 assert!(e.message.contains("trampoline"), "{}", e.message);
1879 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
1880 }
1881
1882 #[test]
1883 fn the_flag_every_configure_script_writes_is_taken() {
1884 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
1887 let (opts, _) = compile(&["-c", flag, "a.c"]);
1888 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1889 }
1890 }
1891
1892 #[test]
1893 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
1894 let (opts, _) = compile(&["-c", "a.c"]);
1895 assert!(opts.unwinds(), "the default is off");
1896 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
1897 assert!(!opts.unwinds(), "the build was not taken at its word");
1898 let (opts, _) = compile(&[
1899 "-c",
1900 "-fno-asynchronous-unwind-tables",
1901 "-fasynchronous-unwind-tables",
1902 "a.c",
1903 ]);
1904 assert!(opts.unwinds(), "the last flag did not win");
1905 let (opts, _) =
1909 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
1910 assert!(opts.unwinds(), "the weaker request was dropped");
1911 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
1912 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
1913 let (opts, _) =
1914 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
1915 assert!(!opts.unwinds(), "both were turned off and one stayed on");
1916 }
1917
1918 #[test]
1919 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
1920 for flag in [
1924 "-fno-common",
1925 "-fstrict-aliasing",
1926 "-fno-strict-aliasing",
1927 "-pipe",
1928 "-fdiagnostics-color",
1929 "-fno-diagnostics-color",
1930 "-fdiagnostics-color=always",
1931 "-fdiagnostics-color=never",
1932 "-fdiagnostics-color=auto",
1933 ] {
1934 let (opts, _) = compile(&["-c", flag, "a.c"]);
1935 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
1936 }
1937 }
1938
1939 #[test]
1940 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
1941 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
1944 assert!(e.message.contains(".bss"), "{}", e.message);
1945 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
1946 }
1947
1948 #[test]
1949 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
1950 for flag in ["-fno-pic", "-fno-pie"] {
1951 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
1952 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
1953 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
1956 }
1957 }
1958
1959 #[test]
1960 fn an_unsupported_target_names_itself() {
1961 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
1962 assert!(e.message.contains("sparc64"), "{}", e.message);
1963 }
1964
1965 #[test]
1966 fn no_inputs_is_an_error_but_print_config_needs_none() {
1967 assert!(parse_args(&args(&[])).is_err());
1968 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
1969 }
1970
1971 #[test]
1972 fn print_config_reports_the_target_it_was_given_not_the_host() {
1973 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
1974 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
1975 let text = print_config(&opts);
1976 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
1977 assert!(text.contains("char-signed: false"), "{text}");
1978 assert!(text.contains("object-format: elf"), "{text}");
1979 assert!(text.contains("va-list: void-pointer"), "{text}");
1980 assert!(text.contains("registers: none"), "{text}");
1983 }
1984
1985 #[test]
1986 fn print_config_has_one_key_per_line_and_a_fixed_order() {
1987 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1988 let text = print_config(&opts);
1989 let keys: Vec<&str> =
1990 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
1991 assert_eq!(keys[0], "version");
1992 assert_eq!(keys[1], "target");
1993 assert_eq!(keys.len(), 20);
1994 assert!(text.ends_with('\n'));
1995 }
1996
1997 #[test]
1998 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
1999 let (opts, _) = compile(&["a.c"]);
2000 assert_eq!(opts.safety, rucc_session::Safety::Off);
2001
2002 for (flag, tier) in [
2003 ("-fsafety=detect", rucc_session::Safety::Detect),
2004 ("-fsafety=enforce", rucc_session::Safety::Enforce),
2005 ("-fsafety=kernel", rucc_session::Safety::Kernel),
2006 ("-fsafety=off", rucc_session::Safety::Off),
2007 ] {
2008 let (opts, _) = compile(&[flag, "a.c"]);
2009 assert_eq!(opts.safety, tier, "{flag}");
2010 }
2011
2012 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
2014 assert_eq!(opts.safety, rucc_session::Safety::Off);
2015
2016 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
2019 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
2020 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
2021 }
2022
2023 #[test]
2024 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
2025 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2026 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2027 let text = print_pipeline(&opts);
2028 assert!(text.starts_with("level: -O2\n"), "{text}");
2029 assert!(text.contains("fold"), "{text}");
2030
2031 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
2032 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2033 assert!(print_pipeline(&opts).contains("1: simplify-cfg,"), "{}", print_pipeline(&opts));
2036
2037 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
2038 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2039 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2042 }
2043
2044 #[test]
2045 fn print_pipeline_takes_the_toggles_into_account() {
2046 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
2047 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2048 let text = print_pipeline(&opts);
2049 assert!(!text.contains("fold"), "{text}");
2052 assert!(text.contains("dce"), "{text}");
2053
2054 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
2058 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
2059 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
2060 let a = parse_args(&args(&spelled)).unwrap();
2061 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2062 assert!(print_pipeline(&opts).contains("no passes"), "{}", print_pipeline(&opts));
2063 }
2064
2065 #[test]
2066 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
2067 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
2068 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2069 assert!(!print_pipeline(&opts).contains("global fuel"));
2070
2071 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
2072 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
2073 let text = print_pipeline(&opts);
2074 assert!(text.contains("global fuel: 4"), "{text}");
2077 }
2078
2079 #[test]
2082 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
2083 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
2084 assert_eq!(
2085 opts.passes,
2086 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
2087 );
2088
2089 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
2090 assert!(e.message.contains("unknown option"), "{}", e.message);
2091 }
2092
2093 #[test]
2094 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
2095 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
2096 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
2097
2098 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
2099 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
2100 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
2101 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2102 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
2103 assert!(e.message.contains("not a number"), "{}", e.message);
2104 }
2105
2106 #[test]
2107 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
2108 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
2109 assert_eq!(opts.pass_fuel_global, None);
2110
2111 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
2112 assert_eq!(opts.pass_fuel_global, Some(12));
2113 assert!(opts.pass_fuel.is_empty());
2116
2117 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
2118 assert!(e.message.contains("not a number"), "{}", e.message);
2119 }
2120
2121 #[test]
2122 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
2123 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
2124 assert_eq!(
2125 opts.pass_gates,
2126 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
2127 "the order is what decides, so it has to survive the parse"
2128 );
2129
2130 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
2131 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
2132 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
2133 assert!(e.message.contains("ends before it starts"), "{}", e.message);
2134 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
2135 assert!(e.message.contains("is empty"), "{}", e.message);
2136 }
2137
2138 #[test]
2139 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
2140 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
2141 let text = print_pipeline(&opts);
2142 assert!(text.contains("fold, "), "{text}");
2143 assert!(text.contains("[off for main]"), "{text}");
2144 }
2145
2146 #[test]
2150 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
2151 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
2152 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
2153
2154 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
2155 assert!(e.message.contains("nosuch"), "{}", e.message);
2156 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
2157 }
2158
2159 #[test]
2165 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
2166 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
2167 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
2168 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
2169
2170 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
2171 assert_eq!(opts.opt_info, ["missed-note"]);
2172
2173 let (opts, _) =
2176 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
2177 assert_eq!(opts.opt_info, ["missed", "all"]);
2178 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
2179
2180 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
2181 assert!(e.message.contains("vectorized"), "{}", e.message);
2182 assert!(e.message.contains("`missed`"), "{}", e.message);
2183 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
2184 assert!(e.message.contains("no file"), "{}", e.message);
2185 }
2186
2187 #[test]
2188 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
2189 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
2190 assert!(opts.verify_each);
2191 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
2192 }
2193
2194 #[test]
2195 fn dash_o_needs_an_argument() {
2196 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
2197 assert_eq!(e.message, "-o requires an argument");
2198 }
2199
2200 #[test]
2201 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
2202 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
2203 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
2204 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
2205 }
2206
2207 #[test]
2208 fn the_include_flags_land_on_the_chain_each_one_names() {
2209 let (opts, _) = compile(&[
2212 "-Ii",
2213 "-iquote",
2214 "q",
2215 "-isystem",
2216 "sys",
2217 "-idirafter",
2218 "after",
2219 "--sysroot=/nowhere-at-all",
2220 "a.c",
2221 ]);
2222 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2223 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
2226 assert!(!opts.search.dirs()[1].is_system);
2227 assert!(opts.search.dirs()[2].is_system);
2228 }
2229
2230 #[test]
2231 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
2232 let (opts, _) = compile(&["a.c"]);
2236 let dirs = opts.search.dirs();
2237 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
2238 assert_eq!(ours, Some(0), "{dirs:?}");
2239 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
2240 let (bare, _) = compile(&["-nostdinc", "a.c"]);
2241 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
2242 }
2243
2244 #[test]
2245 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
2246 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
2247 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2248 assert_eq!(dirs, ["sys", runtime::DIR]);
2249 }
2250
2251 #[test]
2252 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
2253 let (opts, _) =
2254 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
2255 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2256 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
2257 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
2259 assert!(!opts.search.searches_current_dir());
2260 }
2261
2262 #[test]
2263 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
2264 let (opts, _) = compile(&[
2265 "-iprefix",
2266 "/tools/",
2267 "-iwithprefix",
2268 "late",
2269 "-iwithprefixbefore",
2270 "early",
2271 "-iprefix",
2272 "/other/",
2273 "-iwithprefix",
2274 "last",
2275 "-nostdinc",
2276 "a.c",
2277 ]);
2278 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2279 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
2282 assert!(!opts.search.dirs()[0].is_system);
2283 assert!(opts.search.dirs()[1].is_system);
2284 }
2285
2286 #[test]
2287 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
2288 let (opts, _) =
2289 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
2290 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
2291 assert_eq!(names, ["one.h", "two.h", "3.h"]);
2292 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
2293 }
2294
2295 #[test]
2296 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
2297 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
2298 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
2299 assert_eq!(dirs, ["i"]);
2300 }
2301
2302 #[test]
2303 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
2304 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
2305 assert_eq!(opts.std, Std::C11);
2306 assert!(opts.gnu_extensions);
2307
2308 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
2309 assert_eq!(opts.std, Std::C99);
2310 assert!(!opts.gnu_extensions);
2311
2312 let (opts, _) = compile(&["-ansi", "a.c"]);
2313 assert_eq!(opts.std, Std::C89);
2314 assert!(!opts.gnu_extensions);
2315
2316 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
2317 assert!(e.message.contains("unknown dialect"), "{}", e.message);
2318 }
2319
2320 #[test]
2321 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
2322 let (opts, _) = compile(&["-dM", "a.c"]);
2323 assert!(opts.dumps.macros);
2324
2325 let (opts, _) = compile(&["-dDM", "a.c"]);
2328 assert!(opts.dumps.macros);
2329 let (opts, _) = compile(&["-dD", "a.c"]);
2330 assert!(!opts.dumps.macros);
2331
2332 let (opts, _) = compile(&["a.c"]);
2333 assert!(!opts.dumps.any());
2334
2335 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
2338 }
2339
2340 #[test]
2341 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
2342 let (opts, _) = compile(&["a.c"]);
2343 assert_eq!(
2344 opts.gnuc,
2345 GnucVersion { major: 7, minor: 0, patch: 0 },
2346 "the lowest claim a modern glibc gives its own declarations to"
2347 );
2348
2349 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
2350 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
2351
2352 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
2355 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
2356
2357 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
2358 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
2359
2360 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
2361 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
2362
2363 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
2364 assert!(e.message.contains("more than three"), "{}", e.message);
2365 }
2366
2367 #[test]
2368 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
2369 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
2370 assert!(opts.pedantic);
2371 assert_eq!(opts.std, Std::C17);
2372
2373 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
2376 assert!(opts.pedantic);
2377
2378 let (opts, _) = compile(&["-std=c17", "a.c"]);
2379 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
2380 }
2381
2382 #[test]
2383 fn dash_p_and_dash_ffreestanding_reach_the_options() {
2384 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
2385 assert!(!opts.line_markers);
2386 assert!(!opts.hosted);
2387 assert_eq!(opts.emit, EmitKind::Preprocessed);
2388 }
2389
2390 #[test]
2397 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
2398 let (opts, _) = compile(&["-c", "a.c"]);
2399 assert!(opts.builtins, "a library name means the library function by default");
2400 assert!(opts.no_builtin.is_empty());
2401
2402 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
2403 assert!(!opts.builtins);
2404
2405 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
2406 assert!(opts.builtins, "the last mention decides");
2407
2408 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
2409 assert!(opts.builtins, "one name is not the family");
2410 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
2411 }
2412
2413 #[test]
2421 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
2422 let (opts, _) = compile(&["-c", "a.c"]);
2423 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
2424
2425 for (written, wanted) in [
2426 ("default", Visibility::Default),
2427 ("hidden", Visibility::Hidden),
2428 ("internal", Visibility::Hidden),
2429 ("protected", Visibility::Protected),
2430 ] {
2431 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
2432 assert_eq!(opts.visibility, wanted, "{written}");
2433 }
2434
2435 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
2438 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
2439
2440 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
2444 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
2445 }
2446
2447 #[test]
2455 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
2456 let (opts, _) = compile(&["-c", "a.c"]);
2457 assert!(!opts.function_sections, "one text section unless something says otherwise");
2458 assert!(!opts.data_sections);
2459
2460 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
2461 assert!(opts.function_sections);
2462 assert!(!opts.data_sections, "one flag is not the other");
2463
2464 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
2465 assert!(opts.data_sections);
2466 assert!(!opts.function_sections);
2467
2468 let (opts, _) = compile(&[
2471 "-c",
2472 "-ffunction-sections",
2473 "-fno-function-sections",
2474 "-fdata-sections",
2475 "-fno-data-sections",
2476 "a.c",
2477 ]);
2478 assert!(!opts.function_sections, "the last mention decides");
2479 assert!(!opts.data_sections, "the last mention decides");
2480 }
2481
2482 #[test]
2485 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
2486 let (opts, _) = compile(&["-c", "a.c"]);
2487 assert!(!opts.gnu89_inline, "C's reading of inline by default");
2488
2489 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
2490 assert!(opts.gnu89_inline);
2491
2492 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
2493 assert!(!opts.gnu89_inline, "the last mention decides");
2494
2495 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
2500 assert!(!opts.gnu89_inline);
2501 }
2502
2503 #[test]
2506 fn the_two_frame_flags_are_read_in_both_directions() {
2507 let (opts, _) = compile(&["-c", "a.c"]);
2508 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
2509 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
2510
2511 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
2512 assert!(opts.frame_pointer);
2513 assert!(!opts.red_zone);
2514
2515 let (opts, _) = compile(&[
2516 "-c",
2517 "-fno-omit-frame-pointer",
2518 "-fomit-frame-pointer",
2519 "-mno-red-zone",
2520 "-mred-zone",
2521 "a.c",
2522 ]);
2523 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
2524 assert!(opts.red_zone);
2525 }
2526
2527 #[test]
2530 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
2531 let (opts, _) = compile(&["-c", "a.c"]);
2532 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
2533
2534 for (flag, want) in [
2535 ("-fstack-protector", Protector::Buffers),
2536 ("-fstack-protector-strong", Protector::Strong),
2537 ("-fstack-protector-all", Protector::All),
2538 ] {
2539 let (opts, _) = compile(&["-c", flag, "a.c"]);
2540 assert_eq!(opts.protector, want, "{flag}");
2541 }
2542
2543 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
2546 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
2547 assert_eq!(opts.protector, Protector::None, "{off}");
2548 }
2549 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
2550 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
2551 }
2552
2553 #[test]
2554 fn the_link_flags_are_collected_apart_from_the_compilation() {
2555 let (link, _) = linking(&[
2556 "-static",
2557 "-nostartfiles",
2558 "-rdynamic",
2559 "-s",
2560 "-fuse-ld=mold",
2561 "-L/opt/lib",
2562 "-B",
2563 "/opt/tools",
2564 "a.c",
2565 ]);
2566 assert!(link.is_static);
2567 assert!(link.no_startfiles);
2568 assert!(link.export_dynamic);
2569 assert!(link.strip);
2570 assert_eq!(link.use_ld.as_deref(), Some("mold"));
2571 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
2572 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
2573 }
2574
2575 #[test]
2576 fn a_comma_in_dash_wl_separates_two_arguments() {
2577 let (link, _) = linking(&["-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
2578 assert_eq!(link.passthrough, vec!["-rpath", "/opt/lib", "--as-needed"]);
2579 }
2580
2581 #[test]
2582 fn a_library_keeps_its_place_between_the_objects() {
2583 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
2588 let link = plan.link.expect("expected a link step");
2589 assert_eq!(
2590 link.inputs,
2591 vec![
2592 link::Item::File("a.o".into()),
2593 link::Item::Library("m".into()),
2594 link::Item::File("b.o".into()),
2595 ]
2596 );
2597 assert_eq!(plan.jobs.len(), 2);
2599 }
2600
2601 #[test]
2602 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
2603 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
2604 assert!(plan.link.is_none());
2605 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
2606 }
2607
2608 #[test]
2609 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
2610 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
2611 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
2612 }
2613
2614 fn printed(s: &[&str]) -> String {
2615 match parse_args(&args(s)).expect("expected an answer") {
2616 Action::Print(line) => line,
2617 other => panic!("expected an answer, got {other:?}"),
2618 }
2619 }
2620
2621 fn refused(s: &[&str]) -> String {
2622 parse_args(&args(s)).expect_err("expected a refusal").message
2623 }
2624
2625 #[test]
2626 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
2627 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
2631 assert!(!opts.warnings_are_errors);
2632 assert!(opts.warnings);
2633 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
2635 assert!(opts.warnings_are_errors);
2636 let (opts, _) = compile(&["-w", "-c", "a.c"]);
2637 assert!(!opts.warnings);
2638 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
2639 assert!(opts.pedantic && opts.warnings_are_errors);
2640 }
2641
2642 #[test]
2643 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
2644 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
2646 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
2647 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
2648 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
2649 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
2650 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
2651 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
2654 assert!(no32.contains("32 bit target"), "{no32}");
2655 }
2656
2657 #[test]
2658 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
2659 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2660 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
2661 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
2662 }
2663
2664 #[test]
2665 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
2666 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
2667 let (opts, _) =
2668 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
2669 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
2670 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
2671 assert!(wrong.contains("sysv convention"), "{wrong}");
2672 }
2673
2674 #[test]
2675 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
2676 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
2677 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
2678 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
2681 assert_eq!(names, vec!["a.c"]);
2682 }
2683
2684 #[test]
2685 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
2686 let target = "--target=x86_64-unknown-linux-gnu";
2687 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
2688 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
2689 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
2690 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
2691 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
2694 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
2695 let dirs = printed(&[target, "-print-search-dirs"]);
2696 assert!(dirs.starts_with("install: "), "{dirs}");
2697 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
2698 }
2699
2700 #[test]
2701 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
2702 let (opts, _) = compile(&["-M", "a.c"]);
2703 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
2704 assert!(opts.deps.system_headers, "plain -M lists them");
2705 assert_eq!(opts.emit, EmitKind::Preprocessed);
2706
2707 let (opts, _) = compile(&["-M", "-c", "a.c"]);
2710 assert_eq!(opts.emit, EmitKind::Preprocessed);
2711
2712 let (opts, _) = compile(&["-MM", "a.c"]);
2713 assert!(!opts.deps.system_headers);
2714 }
2715
2716 #[test]
2717 fn the_two_that_end_in_d_leave_the_compilation_alone() {
2718 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
2719 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2720 assert!(opts.deps.system_headers);
2721 assert_eq!(opts.emit, EmitKind::Object);
2722
2723 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
2724 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
2725 assert!(!opts.deps.system_headers);
2726 }
2727
2728 #[test]
2729 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
2730 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
2733 assert!(!opts.deps.system_headers);
2734 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
2735 assert!(!opts.deps.system_headers);
2736 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
2737 assert!(!opts.deps.system_headers);
2738 }
2739
2740 #[test]
2741 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
2742 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
2743 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
2744 }
2745
2746 #[test]
2747 fn the_rest_of_the_family_is_a_file_and_a_switch() {
2748 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
2749 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
2750 assert!(opts.deps.phony);
2751
2752 for flag in ["-MF", "-MT", "-MQ"] {
2753 let e = parse_args(&args(&[flag])).unwrap_err();
2754 assert!(e.message.contains("requires an argument"), "{}", e.message);
2755 }
2756 }
2757
2758 struct TempTree(PathBuf);
2760
2761 impl Drop for TempTree {
2762 fn drop(&mut self) {
2763 let _ = std::fs::remove_dir_all(&self.0);
2764 }
2765 }
2766
2767 impl TempTree {
2768 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
2769 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
2770 let _ = std::fs::remove_dir_all(&dir);
2771 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
2772 for (path, text) in files {
2773 let at = dir.join(path);
2774 if let Some(parent) = at.parent() {
2775 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
2776 }
2777 std::fs::write(&at, text).expect("writing a temporary file should work");
2778 }
2779 TempTree(dir)
2780 }
2781
2782 fn path(&self, name: &str) -> String {
2783 self.0.join(name).to_string_lossy().into_owned()
2784 }
2785 }
2786
2787 #[test]
2788 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
2789 let tree = TempTree::new(
2793 "found",
2794 &[
2795 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
2796 ("one.h", "#define X 0\n"),
2797 ("two.h", "#include \"one.h\"\n"),
2798 ],
2799 );
2800 let out = tree.path("dep.d");
2801 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2802 assert_eq!(code, 0);
2803
2804 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2805 let names: Vec<&str> = text.split_whitespace().collect();
2806 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
2808 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
2809 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
2810 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
2813 }
2814
2815 #[test]
2816 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
2817 let tree = TempTree::new(
2820 "guarded",
2821 &[
2822 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
2823 ("g.h", "#ifndef G\n#define G\n#endif\n"),
2824 ],
2825 );
2826 let out = tree.path("dep.d");
2827 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
2828 assert_eq!(code, 0);
2829 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2830 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
2831 }
2832
2833 #[test]
2834 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
2835 let tree = TempTree::new(
2840 "preinclude",
2841 &[
2842 ("a.c", "int main(void) { return 0; }\n"),
2843 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
2844 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
2845 ],
2846 );
2847 let out = tree.path("a.i");
2848 let code = run(&args(&[
2849 "-E",
2850 "-include",
2851 &tree.path("i.h"),
2852 "-imacros",
2853 &tree.path("m.h"),
2854 "-o",
2855 &out,
2856 &tree.path("a.c"),
2857 ]));
2858 assert_eq!(code, 0);
2859 let text = std::fs::read_to_string(&out).expect("the output should have been written");
2860 assert!(text.contains("saw_it"), "{text}");
2861 assert!(!text.contains("macros_text"), "{text}");
2864 }
2865
2866 #[test]
2867 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
2868 let tree = TempTree::new(
2869 "preinclude-deps",
2870 &[
2871 ("a.c", "int main(void) { return 0; }\n"),
2872 ("i.h", "int from_include;\n"),
2873 ("m.h", "#define M 1\n"),
2874 ],
2875 );
2876 let out = tree.path("dep.d");
2877 let code = run(&args(&[
2878 "-MM",
2879 "-MF",
2880 &out,
2881 "-include",
2882 &tree.path("i.h"),
2883 "-imacros",
2884 &tree.path("m.h"),
2885 "-o",
2886 &tree.path("a.i"),
2887 &tree.path("a.c"),
2888 ]));
2889 assert_eq!(code, 0);
2890 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
2891 assert!(text.contains("i.h"), "{text}");
2892 assert!(text.contains("m.h"), "{text}");
2893 }
2894
2895 #[test]
2896 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
2897 let tree = TempTree::new(
2901 "preinclude-missing",
2902 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
2903 );
2904 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
2905 assert_eq!(code, 1);
2906 }
2907
2908 #[test]
2909 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
2910 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
2914 assert_eq!(plan.output.as_deref(), Some("prog"));
2915 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
2916 assert_eq!(
2917 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
2918 Some("prog.d")
2919 );
2920 }
2921
2922 #[test]
2923 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
2924 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
2925 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
2926 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
2927 assert_eq!(plan.output, None);
2928 }
2929
2930 #[test]
2931 fn usage_fits_on_a_screen() {
2932 assert!(USAGE.lines().count() < 51, "usage text has grown past one screen");
2956 }
2957}