rucc_driver/lib.rs
1//! The driver: command line parsing, the phase graph, job scheduling and the linker
2//! invocation.
3//!
4//! Design: `spec/04-driver-and-cli.md`. Layer rank 13, see `spec/18-package-layout.md`.
5//!
6//! This is the only crate that is allowed to know the process exists. It reads the command
7//! line, touches the file system, spawns the linker and writes to the terminal, and it hands
8//! everything below it a [`Session`]. The binary crate is a `main` that calls
9//! [`run`] and nothing else, so that the whole driver is reachable from a test.
10//!
11//! # Status
12//!
13//! `--help`, `--version` and `--print-config` are real, which is the `M0` exit criterion in
14//! `spec/17-milestones.md`. The phase graph is real and `-###` prints it, and the scheduler
15//! that will run it is real and tested.
16//!
17//! Two phases run. `-E` reads the file, runs phase 4 over it and writes the result, to `-o` or
18//! to standard output. `--emit=tast` carries on through phase 7, the parse and the checking,
19//! and writes the typed tree. The flags those two read are real with them, which is `-D`, `-U`,
20//! `-I`, `-I-`, `-iquote`, `-isystem`, `-idirafter`, `-iprefix`, `-iwithprefix`,
21//! `-iwithprefixbefore`, `-include`, `-imacros`, `--sysroot=`, `-isysroot`, `-P`, `-std=`,
22//! `-fgnuc-version=`, `-ansi`, `-ffreestanding`, `-fno-builtin`, `-fno-builtin-<name>`,
23//! `-fgnu89-inline`, `-pedantic` and `-Werror`.
24//! The phases after them still say they are not implemented.
25//!
26//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
27//! explicitly unstable and will change without a major version bump.
28
29#![doc(html_root_url = "https://docs.rs/rucc-driver/0.10.73")]
30
31pub mod assemble;
32pub mod cache;
33pub mod compile;
34pub mod deps;
35pub mod fetch;
36mod glibc;
37pub mod install;
38pub mod library;
39pub mod link;
40mod map;
41pub mod phase;
42pub mod preprocess;
43pub mod schedule;
44
45use std::fmt::Write as _;
46use std::io::Write as _;
47use std::path::PathBuf;
48
49use rucc_codegen::coverage::{self, Fired};
50use rucc_codegen::lowering::Lowerings;
51use rucc_codegen::pressure::Pressure;
52use rucc_pp::Dependency;
53use rucc_session::{
54 Compress, Control, Dumps, EmitKind, Hook, Options, Pic, PrefixMap, Preinclude, Protector,
55 SaveTemps, Session, Std, Wrapping, runtime,
56};
57use rucc_sysroot::{Manifest, Sysroot};
58use rucc_target::{ObjectFormat, Triple};
59use rucc_tuple::TargetTuple;
60
61use crate::link::LinkOptions;
62
63pub use crate::assemble::assemble;
64pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
65pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan, Role};
66pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
67pub use crate::schedule::Jobs;
68
69/// The compiler's version, taken from the workspace manifest.
70pub const VERSION: &str = env!("CARGO_PKG_VERSION");
71
72/// What the command line asked for.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum Action {
75 /// Print usage and exit successfully.
76 Help,
77 /// Print the version and exit successfully.
78 Version,
79 /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
80 ///
81 /// A build system asks these before it compiles anything, and what it does with the answer
82 /// is paste it into a path or into another command line, so each one is a single line with
83 /// no decoration around it.
84 Print(String),
85 /// Print the resolved configuration and exit successfully.
86 PrintConfig(Box<Options>),
87 /// Print the passes the level will run and exit successfully.
88 PrintPipeline(Box<Options>),
89 /// Print the phase plan and the link line and exit successfully, which is `-###`.
90 PrintPlan {
91 /// The resolved options, which is what says what the link line is for.
92 opts: Box<Options>,
93 /// What to do to each input, and in what order.
94 plan: Box<Plan>,
95 /// What the command line said about linking.
96 link: Box<LinkOptions>,
97 },
98 /// `--fetch <tuple>`, which gets the sysroot this release pins for a target and installs it.
99 ///
100 /// The only action in this compiler that may run another program to move bytes onto the
101 /// machine, which is `spec/cross-compile/13-distribution.md` section 13.8's rule rather than a
102 /// property of how this happens to be written: a compilation has no branch that reaches it.
103 Fetch {
104 /// The artifact, from the table in [`rucc_sysroot::artifact`]. Resolved here rather than where the
105 /// work happens, so that a target nothing is pinned for is a refusal from the parser like
106 /// every other thing a command line can ask for and not have.
107 what: &'static rucc_sysroot::Pinned,
108 /// The target, which names the directory under the cache the tree is installed at and is
109 /// checked against the record inside the artifact.
110 target: TargetTuple,
111 /// Where the cache is, read where everything else that needs it reads it.
112 cache: PathBuf,
113 },
114 /// Compile the given inputs.
115 Compile {
116 /// The resolved options.
117 opts: Box<Options>,
118 /// What to do to each input, and in what order.
119 plan: Box<Plan>,
120 /// What the command line said about linking.
121 link: Box<LinkOptions>,
122 /// How many translation units to compile at once.
123 jobs: Jobs,
124 /// Whether `-v` asked for the plan to be printed while it runs.
125 verbose: bool,
126 /// What is worth saying about the command line before anything is compiled, printed as
127 /// warnings and once for the whole run rather than once per file.
128 ///
129 /// These are not diagnostics. A diagnostic is about a piece of source and has a span to
130 /// point at, and these are about the way two flags were combined, so there is nothing to
131 /// point at and nowhere below the driver that knows both halves. `-w` does not reach them
132 /// for the same reason it does not reach a refusal from the parser.
133 notes: Vec<String>,
134 },
135}
136
137/// Why a command line was rejected.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct CliError {
140 /// The message, lowercase and without a trailing period, in the same shape as any other
141 /// diagnostic.
142 pub message: String,
143}
144
145impl std::fmt::Display for CliError {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 f.write_str(&self.message)
148 }
149}
150
151impl std::error::Error for CliError {}
152
153fn err(message: impl Into<String>) -> CliError {
154 CliError { message: message.into() }
155}
156
157/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
158///
159/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
160/// the only one that lets a directory whose name contains an `=` be the old half. It also means
161/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
162/// trap until you notice the alternative traps the far more common case.
163fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
164 let rest = &arg[flag.len()..];
165 PrefixMap::split(rest).ok_or_else(|| {
166 let flag = flag.trim_end_matches('=');
167 err(format!(
168 "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
169 ))
170 })
171}
172
173/// A question the command line asked instead of asking for a compilation.
174///
175/// These are answered after the loop rather than where they are read, because every one of them
176/// is about the target or about the library search and the last word on both is the end of the
177/// command line.
178enum Query {
179 /// `-dumpmachine`, the triple.
180 Machine,
181 /// `-dumpversion` and `-dumpfullversion`, which are the same three numbers here.
182 Version,
183 /// `-print-multiarch`, the directory name a distribution files this target under.
184 Multiarch,
185 /// `-print-search-dirs`, in the three lines GCC prints.
186 SearchDirs,
187 /// `-print-sysroot`, the root the headers and the libraries are read under.
188 Sysroot,
189 /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
190 SysrootProvenance,
191 /// `-print-sysroot-digest`, the one number that names all of it.
192 SysrootDigest,
193 /// `-print-file-name=<name>`, the full path of a library file.
194 FileName(String),
195 /// `-print-prog-name=<name>`, the full path of a program.
196 ProgName(String),
197 /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
198 Libgcc,
199}
200
201/// Usage text.
202///
203/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
204/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
205pub const USAGE: &str = "\
206rucc, an optimizing C compiler
207
208usage: rucc [options] file...
209
210options:
211 -c compile and assemble, do not link
212 -S compile only, emit assembly
213 -E preprocess only
214 -o <file> write output to <file>, or to standard output for -
215 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
216 -I <dir> add <dir> to the include search path
217 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
218 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
219 -include <file>, -imacros <file> read <file> first, the second for its macros only
220 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
221 -P, -dM with -E: leave out the markers, or dump the macros
222 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
223 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
224 -std=<dialect> c89 through c23, and the gnu spellings
225 -fgnuc-version=<v> the GCC release to claim, default 7.0.0
226 -x <lang> treat later inputs as <lang>, or none to stop
227 -O<level> optimize: 0, 1, 2, 3, s, z
228 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
229 -f[no-]sanitize=<what> the negative is taken, the positive is refused by name
230 -f[no-]safety-subobject a write has to stay inside the member it names
231 -f[no-]safety-restrict two restrict pointers of one block may not meet
232 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
233 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
234 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
235 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
236 -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf compress debug sections, one file not two
237 -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects read, and not done yet
238 -fprofile-use[=<path>] -fprofile-dir=<dir> read too, where -fprofile-generate is refused
239 -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
240 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
241 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
242 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
243 -fPIC -fpic -fPIE -fpie, -fno-common, -pipe what it does anyway
244 -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks what it assumes anyway
245 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
246 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
247 -Werror -pedantic -pedantic-errors -w -W[no-]system-headers how much to say, and how fatal
248 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
249 -pg -p, -mfentry -mno-fentry call a profiler on the way in, and where that call goes
250 -fpatchable-function-entry=<n>[,<m>] room at the top of every function to patch later
251 -fwrapv, -fwrapv-pointer, -fno-strict-overflow signed or pointer overflow wraps
252 -ftrapv signed overflow stops the program instead
253 -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums change the ABI
254 -ffp-contract=<how> fuse a multiply and an addition: fast, on or off
255 -fexcess-precision=<how>, -f[no-]rounding-math, -f[no-]trapping-math what may be folded
256 -ffile-prefix-map=<old>=<new> rewrite that front of every path we put in the output
257 -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map= the same, one output each
258 -pthread build for more than one thread, and link the library for it
259 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
260 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
261 -print-sysroot the root the headers and the libraries are read under
262 -print-sysroot-provenance every input under it, where it came from and its licence
263 -print-sysroot-digest the sha256 of that record, which names the whole sysroot in one line
264 --fetch <tuple> get the sysroot this release pins for <tuple> and install it in the cache
265 --offline never download anything, which a compilation never does anyway
266 -j[n] compile n translation units at once, default all
267 -v, -### print each phase as it runs, or without running any
268 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
269 --target=<triple> generate code for <triple>
270 --emit=<kind> exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
271 safety-summary, type-granules
272 --print-config, --print-pipeline print the configuration or the pipeline, and exit
273 --version print the version and exit
274 -h, --help print this message and exit
275
276See spec/04-driver-and-cli.md for the full flag reference.
277";
278
279/// The argument of a flag that may be joined to it or may be the next word.
280///
281/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
282fn joined_or_next(
283 arg: &str,
284 at: usize,
285 args: &[String],
286 i: &mut usize,
287) -> Result<String, CliError> {
288 if arg.len() > at {
289 return Ok(arg[at..].to_owned());
290 }
291 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
292 *i += 1;
293 Ok(next.clone())
294}
295
296/// The smallest boundary a function is put on when the command line asked for no alignment at all.
297///
298/// Eight bytes, which is what gcc 16 gives `-fno-align-functions` on x86-64 and is a boundary every
299/// target this compiler has is happy with. It is not zero: a function still has to start somewhere
300/// an instruction may start, and the flag asks for the target's minimum rather than for none.
301const MIN_FUNC_ALIGN: u32 = 8;
302
303/// What `-falign-functions=N` asks for, as a power of two, or `None` for the target's own answer.
304///
305/// Zero and one both mean the default, which is gcc's reading of them, and everything else is
306/// rounded up to the next power of two, which is also gcc's: `-falign-functions=3` puts a function
307/// on a four byte boundary rather than being refused. Gives back `Err` shaped as an outer `None`
308/// only when the text is not a number, since that is the one thing gcc will not read either. A
309/// number larger than any alignment makes sense at is clamped rather than refused, for the same
310/// reason: this is a preference about speed and a build that wrote a silly one still deserves to
311/// compile.
312fn function_alignment(text: &str) -> Option<Option<u32>> {
313 // gcc takes `N:M:N2:M2`, where everything after the first number is about how far it is willing
314 // to go to reach the boundary. Only the boundary is answerable here, so the rest is read to
315 // check that it is numbers and then dropped.
316 let mut parts = text.split(':');
317 let first = parts.next()?;
318 if parts.any(|part| part.parse::<u64>().is_err()) {
319 return None;
320 }
321 let want: u64 = first.parse().ok()?;
322 if want <= 1 {
323 return Some(None);
324 }
325 let bytes = want.min(1 << 16).next_power_of_two();
326 Some(Some(u32::try_from(bytes).ok()?))
327}
328
329/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
330/// own.
331///
332/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
333/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
334/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
335/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
336/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
337/// because none of them is implemented.
338///
339/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
340/// those two spellings is read rather than by being on this list.
341const SANITIZERS: [&str; 34] = [
342 "address",
343 "kernel-address",
344 "hwaddress",
345 "kernel-hwaddress",
346 "pointer-compare",
347 "pointer-subtract",
348 "thread",
349 "leak",
350 "undefined",
351 "shift",
352 "shift-base",
353 "shift-exponent",
354 "integer-divide-by-zero",
355 "unreachable",
356 "vla-bound",
357 "null",
358 "return",
359 "signed-integer-overflow",
360 "bounds",
361 "bounds-strict",
362 "alignment",
363 "object-size",
364 "float-divide-by-zero",
365 "float-cast-overflow",
366 "nonnull-attribute",
367 "returns-nonnull-attribute",
368 "bool",
369 "enum",
370 "vptr",
371 "pointer-overflow",
372 "builtin",
373 "alias",
374 "restrict",
375 "memory",
376];
377
378/// Parses a command line, without the program name.
379///
380/// # Errors
381///
382/// Returns the message to print when the arguments do not name a compilation this compiler
383/// can attempt.
384pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
385 let host = Triple::host()
386 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
387 let mut opts = Options::new(host);
388 let mut inputs: Vec<Input> = Vec::new();
389 let mut print_config = false;
390 let mut print_pipeline = false;
391 let mut print_plan = false;
392 let mut verbose = false;
393 let mut jobs = Jobs::default();
394 let mut nostdinc = false;
395 let mut sysroot: Option<PathBuf> = None;
396 // What the command line is worth warning about, filled in after the loop rather than during it,
397 // because every question of this kind is about two flags and the last word on both of them is
398 // the end of the loop.
399 let mut notes: Vec<String> = Vec::new();
400 // The whole ten field target, kept beside the three field one because `--target=` can pin a
401 // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
402 // else today, and `None` is a command line that named no target, which is this machine.
403 let mut pinned: Option<TargetTuple> = None;
404 let mut output = None;
405 let mut link = LinkOptions::default();
406 let mut query: Option<Query> = None;
407 // What `--fetch` named, and whether `--offline` forbade it. Both are weighed after the loop
408 // because either can be written after the other.
409 let mut fetch: Option<String> = None;
410 let mut offline = false;
411 let mut threads = false;
412 // Which sanitizers are still asked for by the end of the command line. Accumulated across the
413 // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
414 // build that asks for a check and then takes it back has asked for nothing. What happens to a
415 // set that is not empty is decided after the loop.
416 let mut sanitizers: Vec<&str> = Vec::new();
417 // `-x` applies to inputs that come after it and stays in effect until the next one, which
418 // is why it is tracked across the loop rather than attached to a single argument.
419 let mut forced: Option<InputKind> = None;
420 // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
421 // the flags after it and not the ones before, so a command line may set it more than once.
422 // GCC's default is its own installed header directory with the last component taken off,
423 // which is a path a cross compiler's build system knows and passes; there is no equivalent
424 // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
425 // outright.
426 let mut iprefix = String::new();
427
428 let mut i = 0;
429 while i < args.len() {
430 let arg = args[i].as_str();
431 i += 1;
432 match arg {
433 "-h" | "--help" => return Ok(Action::Help),
434 "--version" => return Ok(Action::Version),
435 // The sysroot fetch, which is weighed after the loop rather than acted on here, because
436 // `--offline` written after it has to be able to forbid it. Both spellings, since a
437 // flag that takes a tuple gets written both ways and neither is a guess at what the
438 // other meant.
439 "--fetch" => {
440 let value = args
441 .get(i)
442 .ok_or_else(|| err("--fetch requires the target to get a sysroot for"))?;
443 i += 1;
444 fetch = Some(value.clone());
445 }
446 _ if arg.starts_with("--fetch=") => {
447 fetch = Some(arg["--fetch=".len()..].to_owned());
448 }
449 // Accepted on any command line and only ever read by the fetch, because an ordinary
450 // compile downloads nothing with or without it. So this flag takes nothing away today,
451 // which is the property section 13.2 asks for rather than an omission: a build that
452 // passes it is saying what it expects of this compiler, and what it expects is already
453 // true.
454 "--offline" => offline = true,
455 "--print-config" => print_config = true,
456 "--print-pipeline" => print_pipeline = true,
457 "-###" => print_plan = true,
458 "-v" => verbose = true,
459 // The files a compilation goes through, kept rather than thrown away. The bare
460 // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
461 // gcc 16 does; `SaveTemps::Object` carries the measurement.
462 "-save-temps" => opts.save_temps = SaveTemps::Object,
463 _ if arg.starts_with("-save-temps=") => {
464 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
465 }
466 // How long each step took. A misspelling of this is worth rejecting rather than
467 // ignoring, since a run that says nothing looks like a compilation that took no time.
468 "-time" => opts.time = true,
469 "-c" => opts.emit = EmitKind::Object,
470 "-S" => opts.emit = EmitKind::Asm,
471 "-E" => opts.emit = EmitKind::Preprocessed,
472 "-g" => opts.debug_info = true,
473 // GCC's own levels of how much debug information to write. Zero is none and every
474 // other number is some, and this compiler has one amount, so the numbers above zero
475 // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
476 // debugger on the machine prefers, which is what we emit anyway.
477 "-g0" => opts.debug_info = false,
478 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
479 opts.debug_info = true;
480 }
481 // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
482 // asks for another version is told rather than handed a file it cannot read.
483 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
484 _ if arg.starts_with("-gdwarf-") => {
485 return Err(err(format!(
486 "{arg}: this compiler writes DWARF 5 and no other version, see \
487 spec/11-debug-info.md"
488 )));
489 }
490 // Whether the debug information goes in a file of its own beside the object. gcc
491 // writes that `.dwo` whether or not it found anything to put in it, which means a
492 // build system that declares the file as an output gets one and a make rule that
493 // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
494 // flag that changes nothing and refuses one that changes what is produced, and a file
495 // that does not appear is the plainest change of that kind there is. The negative
496 // spelling is taken, because putting it all in the object is what happens anyway.
497 "-gno-split-dwarf" => {}
498 "-gsplit-dwarf" => {
499 return Err(err(format!(
500 "{arg}: this compiler writes no separate `.dwo` file, and a build that \
501 expects one beside each object would wait for a file that never arrives, \
502 see spec/11-debug-info.md"
503 )));
504 }
505 // How the debug sections are compressed. There are none yet, so every answer produces
506 // the same bytes and taking the flag promises nothing that is not kept. The value is
507 // still checked, because a typo in a distribution's flags is worth finding when the
508 // compiler reads it rather than when somebody later wonders why nothing got smaller.
509 // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
510 "-gz" => opts.compress = Compress::Zlib,
511 _ if arg.starts_with("-gz=") => {
512 let how = &arg["-gz=".len()..];
513 opts.compress = how.parse().map_err(|()| {
514 err(format!(
515 "`{how}` is not a way to compress debug sections, which is none, zlib, \
516 zlib-gnu or zstd"
517 ))
518 })?;
519 }
520 "-Werror" => opts.warnings_are_errors = true,
521 // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
522 // through rather than here, so that a warning `-w` dropped is not counted either.
523 "-w" => opts.warnings = false,
524 // Off by default, the way gcc has it off. A header that came with the machine is not
525 // one the person compiling can change, so a warning about it is noise, and under
526 // `-Werror` it is a build that stops on a line nobody in the project wrote. Somebody
527 // porting a header does want to hear all of it, which is what the flag is for.
528 "-Wsystem-headers" => opts.system_header_warnings = true,
529 "-Wno-system-headers" => opts.system_header_warnings = false,
530 "-pedantic-errors" => {
531 opts.pedantic = true;
532 opts.warnings_are_errors = true;
533 }
534 "-P" => opts.line_markers = false,
535 // The dependency family, which section 4.4 calls required because every build system
536 // that generates its own makefiles asks for it. The two that end in `D` write a file
537 // beside the object and let the compilation happen, and the two that do not write to
538 // standard output and stop after it. Nothing here turns the system headers back on
539 // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
540 // `-MM`: the flag asking for fewer of them is the one with something to say.
541 "-M" => {
542 opts.deps.emit = true;
543 opts.deps.instead_of_compiling = true;
544 }
545 "-MM" => {
546 opts.deps.emit = true;
547 opts.deps.instead_of_compiling = true;
548 opts.deps.system_headers = false;
549 }
550 "-MD" => opts.deps.emit = true,
551 "-MMD" => {
552 opts.deps.emit = true;
553 opts.deps.system_headers = false;
554 }
555 "-MP" => opts.deps.phony = true,
556 // These three take a word and only in the separated form, which is how GCC spells
557 // them and how every build system writes them.
558 "-MF" | "-MT" | "-MQ" => {
559 let value =
560 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
561 i += 1;
562 match arg {
563 "-MF" => opts.deps.file = Some(value.clone()),
564 // The whole of the difference between the two. `-MT` is for a build that has
565 // already escaped what it is passing, and `-MQ` is for one that has a name
566 // and wants it to arrive as that name.
567 "-MT" => opts.deps.targets.push(value.clone()),
568 _ => opts.deps.targets.push(deps::escaped(value)),
569 }
570 }
571 // The questions a build system asks before it compiles anything. Answered after the
572 // loop, because each one is about the target or the library search and the command
573 // line has not finished saying what those are.
574 "-dumpmachine" => query = Some(Query::Machine),
575 "-dumpversion" | "-dumpfullversion" => query = Some(Query::Version),
576 "-print-multiarch" => query = Some(Query::Multiarch),
577 "-print-search-dirs" => query = Some(Query::SearchDirs),
578 "-print-sysroot" => query = Some(Query::Sysroot),
579 // Both spellings, because this one is ours rather than GCC's and our own documents
580 // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
581 // two dashes like the other flags we invented, and document 12's table gives it one
582 // like the `-print-` family it sits in. A person who reads either and types what it
583 // says is right, so neither is refused.
584 "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
585 query = Some(Query::SysrootProvenance);
586 }
587 "-print-sysroot-digest" | "--print-sysroot-digest" => {
588 query = Some(Query::SysrootDigest);
589 }
590 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
591 _ if arg.starts_with("-print-file-name=") => {
592 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
593 }
594 _ if arg.starts_with("-print-prog-name=") => {
595 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
596 }
597 // A program built to run in more than one thread. On every platform this compiler
598 // targets that is a macro the library's headers read and one more library on the
599 // link line, and the library is added after the loop so that it lands after the
600 // objects that refer to it.
601 "-pthread" | "-pthreads" => {
602 opts.defines.push("_REENTRANT".to_owned());
603 threads = true;
604 }
605 "-ansi" => {
606 opts.std = Std::C89;
607 opts.gnu_extensions = false;
608 }
609 // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
610 // the spelling a build system that groups its warning flags tends to write.
611 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
612 // Both directions, because a build that needs this for one directory turns it back
613 // off for the next one rather than leaving it on for the whole tree.
614 "-fpermissive" => opts.permissive = true,
615 "-fno-permissive" => opts.permissive = false,
616 "-ffreestanding" => opts.hosted = false,
617 "-fhosted" => opts.hosted = true,
618 "-fno-builtin" => opts.builtins = false,
619 "-fbuiltin" => opts.builtins = true,
620 // The C89 dialects are under GNU's reading whatever this says, so turning it off
621 // there is turning off something the dialect asked for, which is accepted and does
622 // nothing. gcc refuses that command line, and there is nothing it could have meant.
623 "-fgnu89-inline" => opts.gnu89_inline = true,
624 "-fno-gnu89-inline" => opts.gnu89_inline = false,
625 // Both directions of each, because a build system that wants one of these usually
626 // writes it beside the flag that turns it back off for one directory.
627 "-fno-omit-frame-pointer" => opts.frame_pointer = true,
628 "-fomit-frame-pointer" => opts.frame_pointer = false,
629 // Both directions again, for the same reason, and a third answer for a command line
630 // that wrote neither: see `reorder_blocks` in `rucc_session`.
631 "-freorder-blocks" => opts.reorder_blocks = Some(true),
632 "-fno-reorder-blocks" => opts.reorder_blocks = Some(false),
633 // gcc's name for the scheduler that runs after the registers are handed out, which is
634 // the only one rucc has: see `schedule_insns` in `rucc_session`. gcc also takes
635 // `-fschedule-insns` for the pass before allocation, and taking that one here would be
636 // a flag that says a pass ran when none did.
637 "-fschedule-insns2" => opts.schedule_insns = Some(true),
638 "-fno-schedule-insns2" => opts.schedule_insns = Some(false),
639 "-mno-red-zone" => opts.red_zone = false,
640 "-mred-zone" => opts.red_zone = true,
641 // Four flags rather than one with an argument, which is how gcc spells them and how
642 // every build line writes them. Last one wins, because a package build puts
643 // `-fstack-protector-strong` in its global flags and a directory that cannot have one
644 // turns it back off on the line after.
645 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
646 opts.protector = Protector::None;
647 }
648 "-fstack-protector" => opts.protector = Protector::Buffers,
649 "-fstack-protector-strong" => opts.protector = Protector::Strong,
650 "-fstack-protector-all" => opts.protector = Protector::All,
651 // The other half of what a hardened build asks for, and it is a question about the
652 // frame rather than about the function, so it is a switch rather than a level.
653 "-fstack-clash-protection" => opts.stack_clash = true,
654 "-fno-stack-clash-protection" => opts.stack_clash = false,
655 // The third of them, and the one that is a question with an argument rather than a
656 // family of spellings, because what it asks about is which of the two edges of a
657 // control flow transfer is checked. Bare is both of them, which is what gcc does.
658 "-fcf-protection" => opts.control = Control::Full,
659 "-fno-cf-protection" => opts.control = Control::None,
660 // Two spellings of the same request, which is what gcc has as well. `-p` was the older
661 // profiler and `-pg` the one that also recorded who called whom, and on every platform
662 // this compiler targets there is now one hook and both ask for it.
663 "-pg" | "-p" => {
664 opts.profile = true;
665 link.profile = true;
666 }
667 // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
668 // say where the call goes and a command line that asked for no call has nowhere to put
669 // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
670 // directory is a build system that would otherwise fail on every other directory.
671 "-mfentry" => opts.hook = Hook::Early,
672 "-mno-fentry" => opts.hook = Hook::Late,
673 // GCC drops its own include directory along with the system ones, because its
674 // headers are half of a pair with the library's and half a pair is worse than
675 // none. A build that passes this is supplying the whole set itself.
676 "-nostdinc" => nostdinc = true,
677 "-o" => {
678 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
679 i += 1;
680 }
681 // The flags that take a directory only in the separated form. GCC spells them
682 // this way and nothing writes `-iquotedir`, so accepting the joined form would
683 // mean guessing at a path that starts with the flag's own letters.
684 // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
685 // two mean the same thing here: the configured directories are under there rather
686 // than under the root.
687 "-isysroot" => {
688 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
689 i += 1;
690 sysroot = Some(PathBuf::from(dir));
691 }
692 "-iquote" | "-isystem" | "-idirafter" => {
693 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
694 i += 1;
695 match arg {
696 "-iquote" => opts.search.push_quote(dir.clone()),
697 "-isystem" => opts.search.push_system(dir.clone()),
698 _ => opts.search.push_after(dir.clone()),
699 }
700 }
701 "-iprefix" => {
702 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
703 i += 1;
704 }
705 // Where GCC puts these is not where its manual says it puts them, and this is the
706 // measured answer rather than the documented one: `-iwithprefix` lands in the
707 // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
708 // the `-I` slot. A cross build that uses them is relying on the behaviour, since
709 // that is the compiler it was developed against.
710 "-iwithprefix" | "-iwithprefixbefore" => {
711 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
712 i += 1;
713 let dir = format!("{iprefix}{dir}");
714 if arg == "-iwithprefix" {
715 opts.search.push_system(dir);
716 } else {
717 opts.search.push_bracket(dir);
718 }
719 }
720 "-include" | "-imacros" => {
721 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
722 i += 1;
723 opts.preincludes
724 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
725 }
726 // The flag `-iquote` was introduced to replace, still passed by build systems old
727 // enough to predate the replacement. It is not a directory: it says that every `-I`
728 // so far is for quoted includes only, and that a quoted include stops looking next
729 // to the file that wrote it.
730 "-I-" => opts.search.split_quote_chain(),
731 "-x" => {
732 let lang = args.get(i).ok_or_else(|| err("-x requires an argument"))?;
733 i += 1;
734 forced = if lang == "none" {
735 None
736 } else {
737 Some(InputKind::from_x_arg(lang).map_err(|e| err(format!("{e}")))?)
738 };
739 }
740 // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
741 // translation units in one process rather than making the build system fork, and
742 // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
743 // to exist and has to be spelled the way `make` spells it.
744 // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
745 // and a build system may produce either, so both are read here rather than
746 // being normalised by whatever generated the command line.
747 _ if arg.starts_with("-D") => {
748 let value = joined_or_next(arg, 2, args, &mut i)?;
749 opts.defines.push(value);
750 }
751 _ if arg.starts_with("-U") => {
752 let value = joined_or_next(arg, 2, args, &mut i)?;
753 opts.undefines.push(value);
754 }
755 _ if arg.starts_with("-I") => {
756 let dir = joined_or_next(arg, 2, args, &mut i)?;
757 opts.search.push_bracket(dir);
758 }
759 _ if arg.starts_with("-std=") => {
760 let name = &arg["-std=".len()..];
761 let (std, gnu) = Std::from_flag(name)
762 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
763 opts.std = std;
764 opts.gnu_extensions = gnu;
765 }
766 // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
767 // handed, so a differential run that does not set it is comparing two compilers
768 // that believe they are different compilers.
769 // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
770 // that we have not written yet are accepted and ignored, because a dump is a
771 // debugging aid and a build that asks for one should still compile. A letter
772 // outside the family falls through to the unknown option error, which is what
773 // keeps `-dumpversion` from being read as a dump of nothing.
774 _ if Dumps::is_family(arg) => {
775 opts.dumps.add(&arg[2..]);
776 }
777 // One name at a time, which is what a build that means its own `memcpy` and the
778 // library's everything else writes. The name is not checked against a list, because
779 // the flag is about what the program means by a name and a program is allowed to mean
780 // something by a name this compiler has never heard of.
781 _ if arg.starts_with("-fno-builtin-") => {
782 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
783 }
784 _ if arg.starts_with("-fgnuc-version=") => {
785 let v = &arg["-fgnuc-version=".len()..];
786 opts.gnuc = v.parse().map_err(err)?;
787 }
788 // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
789 // than the unknown option one, because a build reaching for it is asking for a feature
790 // and deserves to be told it is not coming rather than told the spelling is wrong.
791 // The negative form is what this compiler does anyway, so it is taken and dropped.
792 "-fnested-functions" => {
793 return Err(err(
794 "nested functions are not supported: a call to one goes through a trampoline \
795 written on the stack, which no target that enforces an unexecutable stack \
796 allows",
797 ));
798 }
799 "-fno-nested-functions" => {}
800 // Which of the two links the output is for, which is a real difference and not a
801 // description of what happens anyway. Everything here is position independent either
802 // way, and what these decide is whether a name may be one another object defines or
803 // replaces, because a link that produces an executable puts every name in the same
804 // program and a link that produces a shared library does not.
805 //
806 // It matters that they are accepted at all, whatever they then do. Every autoconf and
807 // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
808 // be the `CC` of a project that has a configure script, whatever else it can do. That
809 // is how this was found: building SQLite's test fixture stopped on it.
810 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
811 // Not a synonym of the pair above, which is what they were treated as until #756. The
812 // library is the expensive answer and gcc makes it the one that has to be asked for,
813 // so this is also what nothing at all means.
814 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
815 // A different question from the pair above, and the one every distribution build of a
816 // shared library answers. `-fPIC` decides how an address is reached, and this decides
817 // whether the optimizer may believe a body it can see, because an exported name is one
818 // the dynamic linker may find another definition of first. On by default, which is
819 // gcc's arrangement and is the honest answer, and off is a promise the build makes and
820 // nothing checks.
821 "-fsemantic-interposition" => opts.interposition = true,
822 "-fno-semantic-interposition" => opts.interposition = false,
823 // Two requests rather than one, and the same table answers both, so what decides is
824 // whether either of them is standing. gcc arranges it the same way: the asynchronous
825 // one is the default here and it implies the other, and a line that asks for a table
826 // and against an asynchronous one gets a table.
827 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
828 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
829 "-funwind-tables" => opts.unwind_tables = true,
830 "-fno-unwind-tables" => opts.unwind_tables = false,
831 // The other direction is a request, not a description, and it is one this compiler
832 // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
833 // option error. Answering it by carrying on would be answering a different question:
834 // the code would still be position independent, which is correct everywhere an
835 // ordinary program runs and is wrong in a kernel, where the flag is written precisely
836 // because there is no loader to fill a global offset table in.
837 "-fno-pic" | "-fno-pie" => {
838 return Err(err(
839 "position dependent code is not supported: an address that may be in another \
840 object is loaded out of the global offset table, and nothing here emits the \
841 absolute form this asks for. Use -no-pie if what you meant was how to link",
842 ));
843 }
844 // A section per function and a section per variable, which is what makes
845 // `--gc-sections` able to drop anything: a linker can leave out a section nothing
846 // reaches and cannot leave out half of one. Both directions are taken, and the off
847 // one is the default rather than a refusal, since a build that writes it is asking
848 // for what happens anyway.
849 "-ffunction-sections" => opts.function_sections = true,
850 "-fno-function-sections" => opts.function_sections = false,
851 "-fdata-sections" => opts.data_sections = true,
852 "-fno-data-sections" => opts.data_sections = false,
853 // Another description of what this compiler does. A file scope declaration with no
854 // initializer is written into `.bss` as an ordinary defined symbol, not offered to the
855 // linker as a common one for it to merge, which is what `-fno-common` asks for and what
856 // gcc has done by default since 10. Nothing in the front end produces `Linkage::Common`
857 // at all.
858 "-fno-common" => {}
859 // What overflows rather than being undefined. Every one of these takes something away
860 // from the optimizer rather than asking it to do anything, which is why the negative
861 // spellings are the interesting ones and the positive spellings are the default.
862 //
863 // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
864 // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
865 // written here as the pair rather than kept as a third thing to test everywhere.
866 //
867 // `-ftrapv` is the exception and is the one that asks for something. It is the other
868 // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
869 // the other, which makes the last one on the command line the one that counts. That is
870 // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
871 // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
872 // question is left alone by both, because neither has anything to say about it.
873 "-fwrapv" => {
874 opts.wrapping.signed = true;
875 opts.wrapping.trap = false;
876 }
877 "-fno-wrapv" => opts.wrapping.signed = false,
878 "-fwrapv-pointer" => opts.wrapping.pointer = true,
879 "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
880 "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
881 // Which does not clear the checked one, because gcc does not: `-ftrapv
882 // -fstrict-overflow` still emits the calls. It says what is assumed and not what
883 // happens.
884 "-fstrict-overflow" => {
885 opts.wrapping.signed = false;
886 opts.wrapping.pointer = false;
887 }
888 "-ftrapv" => {
889 opts.wrapping.trap = true;
890 opts.wrapping.signed = false;
891 }
892 "-fno-trapv" => opts.wrapping.trap = false,
893 // The two flags that say what a plain `char` is, which is one question with two
894 // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
895 // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
896 // answers and the last one written wins. Nothing is set until one of them is given,
897 // because the target's own ABI is the answer otherwise and it is not the same answer
898 // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
899 "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
900 "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
901 // And the size of an enumeration, which is the other thing in this group that changes
902 // the ABI rather than the code.
903 "-fshort-enums" => opts.short_enums = true,
904 "-fno-short-enums" => opts.short_enums = false,
905 // And Microsoft's reading of an anonymous member, which changes the layout of every
906 // record that writes a tag on one. Nothing is set until one of them is given, because
907 // the target is the answer otherwise: gcc's mingw build has this on and its Linux
908 // build has it off.
909 "-fms-extensions" => opts.ms_extensions = Some(true),
910 "-fno-ms-extensions" => opts.ms_extensions = Some(false),
911 // And the request, which is the one that cannot be granted. It is a real difference and
912 // not a preference: two files each writing `int g;` link under `-fcommon` and are a
913 // duplicate definition without it, which is the whole reason the flag survives.
914 "-fcommon" => {
915 return Err(err(
916 "a tentative definition is written into .bss as its own symbol here, and \
917 nothing emits the common symbol this asks the linker to merge. Give the \
918 variable a definition in one file and declare it extern in the others",
919 ));
920 }
921 // Both directions of this one are recorded, and what they decide is whether lowering
922 // names the type each access goes through. Turning it off is the front end leaving the
923 // name off rather than a pass being told to ignore one it can see, which is one
924 // condition in one place, and it is the reading that survives link time optimization:
925 // a unit built with the flag off keeps its own answer when its bodies end up in a
926 // module beside bodies that were not.
927 //
928 // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
929 // and is tested, and no pass at any level asks the alias analysis anything today, so
930 // no program compiles differently for having passed this. The flag is wired anyway,
931 // because the change that makes a pass ask is not the change anybody will remember to
932 // wire it in, and a flag that is taken and dropped once the names mean something is
933 // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
934 // words.
935 "-fstrict-aliasing" => opts.strict_aliasing = true,
936 "-fno-strict-aliasing" => opts.strict_aliasing = false,
937 // The same shape of answer for the same reason, and the flag the kernel writes beside
938 // the one above it.
939 //
940 // Nothing here concludes that a pointer is not null from the fact that it was
941 // dereferenced. There is no such conclusion to draw from, because no pass records one:
942 // a load says where it read and nothing else, and a comparison against null is an
943 // ordinary comparison of two values the optimizer has no fact about. So a function
944 // that reads through a pointer and then tests it keeps the test, which is what the
945 // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
946 // to be asked for because it draws the conclusion by default.
947 //
948 // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
949 // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
950 // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
951 "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
952 // The floating point group, which goes the same way and for the same reason, and which
953 // is worth writing out because the reason is easy to get backwards.
954 //
955 // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
956 // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
957 // changed and that an exception raised by an operation may be looked at, so an
958 // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
959 // whose exception the program does not get. Nothing here folds any floating point
960 // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
961 // that runs, at every level. So both of those describe what already happens.
962 //
963 // The permissive ones are the other half, and they are licences rather than requests
964 // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
965 // `-fno-trapping-math` says nothing looks at the exceptions, which together are
966 // permission to fold. Not folding is the conservative side of that permission and is
967 // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
968 // speed and not correctness, which is the test section 4.1 puts a licence through.
969 "-frounding-math" | "-fno-rounding-math" => {}
970 // `-fno-trapping-math` is the one of the four that is kept, because there is one
971 // conversion this compiler does not fold and gcc folds under it, and the two answers
972 // differ. Converting a constant floating value to an integer type it does not fit in
973 // is undefined behaviour rather than a value: left to the hardware it is one
974 // instruction and the answer is the integer indefinite value, and folded it is the
975 // nearest end of the integer's range. Both compilers leave it to the instruction by
976 // default and gcc folds it under this flag, so a program built with it and compiled
977 // without it gets a different number rather than a slower one. `-ftrapping-math` is
978 // gcc's default, so a build spelling it out is asking for what it already has.
979 "-ftrapping-math" => opts.trapping_math = true,
980 "-fno-trapping-math" => opts.trapping_math = false,
981 // About temporary files rather than about code. There is nothing between the phases of
982 // one compilation here to write to a file in the first place.
983 "-pipe" => {}
984 // Nothing here writes colour, so all of these are the same answer, and it is the answer
985 // that costs nothing: the diagnostics come out plain either way and no build depends on
986 // an escape sequence being there. Taken rather than refused because cmake writes
987 // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
988 // makes this the second most common flag after `-fPIC` to stop a build over a question
989 // about how the text looks.
990 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
991 _ if arg.starts_with("-fdiagnostics-color=") => {}
992 // The link flags. None of them changes the compilation, which is why they are
993 // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
994 // error: it is a thing said to a linker that is not going to run.
995 "-static" => link.is_static = true,
996 "-shared" => link.shared = true,
997 "-pie" => link.pie = Some(true),
998 "-no-pie" | "-nopie" => link.pie = Some(false),
999 "-nostdlib" => link.no_stdlib = true,
1000 "-nostartfiles" => link.no_startfiles = true,
1001 "-nodefaultlibs" => link.no_defaultlibs = true,
1002 "-fno-builtins-lib" => link.no_builtins_lib = true,
1003 "-fbuiltins-lib" => link.no_builtins_lib = false,
1004 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
1005 "-s" => link.strip = true,
1006 // Into the ordered input list rather than a list of its own, because a great many of
1007 // the linker's options are a bracket around the files after them and an option that
1008 // lost its place among them says nothing. `--whole-archive` is the one that found this.
1009 "-Xlinker" => {
1010 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
1011 i += 1;
1012 inputs.push(Input::linker(next));
1013 }
1014 _ if arg.starts_with("-Wl,") => {
1015 // Commas separate arguments rather than being part of one, which is what makes
1016 // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
1017 inputs.extend(arg["-Wl,".len()..].split(',').map(Input::linker));
1018 }
1019 _ if arg.starts_with("-fuse-ld=") => {
1020 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
1021 }
1022 _ if arg.starts_with("-l") && arg.len() > 2 => {
1023 inputs.push(Input::library(&arg[2..]));
1024 }
1025 "-l" => {
1026 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
1027 i += 1;
1028 inputs.push(Input::library(next));
1029 }
1030 _ if arg.starts_with("-L") => {
1031 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1032 }
1033 _ if arg.starts_with("-B") => {
1034 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1035 }
1036 _ if arg.starts_with("-j") => {
1037 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
1038 }
1039 _ if arg.starts_with("--sysroot=") => {
1040 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
1041 }
1042 _ if arg.starts_with("--target=") => {
1043 let t = &arg["--target=".len()..];
1044 opts.target = t.parse().map_err(|e| err(format!("{e}")))?;
1045 // The same string again, as the model that has room for a libc version. A spelling
1046 // the three field parser took and this one does not is not an error, because the
1047 // one that decides what is compiled has already accepted it and the only thing
1048 // lost is a version nobody asked for.
1049 pinned = t.parse().ok();
1050 }
1051 _ if arg.starts_with("--emit=") => {
1052 let k = &arg["--emit=".len()..];
1053 opts.emit = k
1054 .parse()
1055 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
1056 }
1057 // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
1058 // to write. `-Og` is GCC's level for a build somebody is going to step through, and
1059 // it is `-O1` with the transformations that move code around left out; this compiler
1060 // has no such level yet, so it is the nearest one and `--print-pipeline` says what
1061 // that came to rather than the flag pretending otherwise.
1062 "-O" | "-Og" => opts.opt_level = rucc_session::OptLevel::O1,
1063 // The union of `-O3` and `-ffast-math`, and the second half of that changes what
1064 // floating point arithmetic means. Refused rather than taken as `-O3`, because a
1065 // build that asks for fast math and is quietly given ordinary arithmetic gets a
1066 // slower program than it asked for and a build that is given fast math it did not
1067 // ask for gets a wrong one.
1068 "-Ofast" => {
1069 return Err(err(
1070 "-Ofast is -O3 with fast math, and fast math is not implemented, see \
1071 spec/04-driver-and-cli.md section 4.6",
1072 ));
1073 }
1074 _ if arg.starts_with("-O") => {
1075 opts.opt_level = arg[2..]
1076 .parse()
1077 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
1078 }
1079 // How far a multiply and an addition may be fused into one rounding. Before the
1080 // optimizer's `-f` family below for the reason the ones under it are, and kept rather
1081 // than dropped because it is the one flag in its group this compiler could act on: it
1082 // rides into the IR as an attribute on each function with a body, so the day the code
1083 // generator forms an `fma` it already knows which functions were given permission.
1084 // Nothing forms one today, under any value of this and under any `-march=`.
1085 _ if arg.starts_with("-ffp-contract=") => {
1086 let how = &arg["-ffp-contract=".len()..];
1087 opts.fp_contract = how.parse().map_err(|()| {
1088 err(format!("`{how}` is not a contraction, which is fast, on or off"))
1089 })?;
1090 }
1091 // How much of an expression may be computed wider than it was written. The values are
1092 // gcc's and so is the refusal of anything else, and none of the three changes anything
1093 // here: an operation is computed in the type C says it is on every target this compiler
1094 // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
1095 // happens. `fast` and `16` are permission to be wider, which is a licence this takes
1096 // and does not use, the same way the two above are. The flag is worth taking because
1097 // glibc's headers and a good deal of configure output write it, and because the answer
1098 // it asks about is one this compiler can state rather than guess at: there is no x87
1099 // target here, which is the machine the whole question was invented for.
1100 // Whether a local and a spilled value that are never both wanted may be the same bytes
1101 // of the frame. gcc's three values, and two of them mean the same thing here: what rucc
1102 // shares is a local whose address provably never leaves the function, which is narrower
1103 // than `named_vars` and narrower still than `all`, so both of them get it. `none` is
1104 // the one that changes anything, and it is the flag a program that reads a local
1105 // through a pointer it kept past the end of the block writes.
1106 _ if arg.starts_with("-fstack-reuse=") => {
1107 let how = &arg["-fstack-reuse=".len()..];
1108 opts.stack_reuse = match how {
1109 "all" | "named_vars" => Some(true),
1110 "none" => Some(false),
1111 _ => {
1112 return Err(err(format!(
1113 "`{how}` is not a stack reuse, which is all, named_vars or none"
1114 )));
1115 }
1116 };
1117 }
1118 _ if arg.starts_with("-fexcess-precision=") => {
1119 let how = &arg["-fexcess-precision=".len()..];
1120 if !matches!(how, "16" | "fast" | "standard") {
1121 return Err(err(format!(
1122 "`{how}` is not an excess precision, which is 16, fast or standard"
1123 )));
1124 }
1125 }
1126 // Which front of a path is rewritten before it reaches the output, which is how a
1127 // build gets the same bytes out of two different directories. The four spellings are
1128 // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
1129 // once. Only the macro list does anything today, because `__FILE__` is the only place
1130 // a path reaches the output: there is no DWARF and no profile data yet, so the other
1131 // two are recorded for the work that will read them. The argument splits at the last
1132 // `=` rather than the first, which is gcc's rule and is what lets a directory with an
1133 // `=` in its name be the old half.
1134 _ if arg.starts_with("-fmacro-prefix-map=") => {
1135 let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1136 opts.prefix_map.macros.push(old, new);
1137 }
1138 _ if arg.starts_with("-fdebug-prefix-map=") => {
1139 let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1140 opts.prefix_map.debug.push(old, new);
1141 }
1142 _ if arg.starts_with("-fprofile-prefix-map=") => {
1143 let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1144 opts.prefix_map.profile.push(old, new);
1145 }
1146 _ if arg.starts_with("-ffile-prefix-map=") => {
1147 let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1148 opts.prefix_map.macros.push(old, new);
1149 opts.prefix_map.debug.push(old, new);
1150 opts.prefix_map.profile.push(old, new);
1151 }
1152 // A whole optimization rather than a flag, and the family is taken rather than
1153 // refused because of what ignoring it does. There is none of it here yet, so a build
1154 // that asks for it gets a program that is correct and slower than it could have been,
1155 // which is what section 4.1 means by a hint about speed and what every compilation at
1156 // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1157 // holds the bytecode and no machine code at all, and every object here holds the code,
1158 // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1159 // to this compiler gets objects that are more usable than the ones it asked for rather
1160 // than different ones. Every value is still checked against gcc's, because somebody
1161 // who wrote `-flto=thin` meant clang and had better hear about it here.
1162 "-flto" => opts.lto.requested = true,
1163 "-fno-lto" => opts.lto.requested = false,
1164 _ if arg.starts_with("-flto=") => {
1165 let how = &arg["-flto=".len()..];
1166 opts.lto.jobs = how.parse().map_err(|()| {
1167 err(format!(
1168 "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1169 count above zero"
1170 ))
1171 })?;
1172 opts.lto.requested = true;
1173 }
1174 _ if arg.starts_with("-flto-partition=") => {
1175 let how = &arg["-flto-partition=".len()..];
1176 opts.lto.partition = how.parse().map_err(|()| {
1177 err(format!(
1178 "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1179 or none"
1180 ))
1181 })?;
1182 }
1183 _ if arg.starts_with("-flto-compression-level=") => {
1184 let how = &arg["-flto-compression-level=".len()..];
1185 let level =
1186 how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1187 err(format!("`{how}` is not a compression level, 0 to 19"))
1188 })?;
1189 opts.lto.compression = Some(level);
1190 }
1191 // Whether the object keeps its machine code as well as the bytecode. It always does
1192 // here, so the first of these describes what happens and the second asks for an object
1193 // with less in it, which is a smaller file and not a different program, so both are
1194 // taken.
1195 "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1196 // Whether the linker is handed a plugin that does the link time work. The design in
1197 // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1198 // plugin into anybody, so neither answer is a question it has to hold.
1199 "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1200 // Reading a profile back. Taken for the reason the family above it is: nothing here
1201 // reads one, so a build that asks gets the program it would have got anyway, and gcc
1202 // itself produces a byte for byte identical object from `-fprofile-use` when there are
1203 // no counts beside the file. The path is recorded for the pass that will read it. The
1204 // warning gcc prints when it looked and found nothing is deliberately not copied,
1205 // because nothing here looks, and a warning about a file that was never opened would
1206 // fire on the builds that have a perfectly good profile as well as on the ones that
1207 // do not.
1208 "-fprofile-use" => opts.profile_data.requested = true,
1209 "-fno-profile-use" => opts.profile_data.requested = false,
1210 _ if arg.starts_with("-fprofile-use=") => {
1211 opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1212 opts.profile_data.requested = true;
1213 }
1214 _ if arg.starts_with("-fprofile-dir=") => {
1215 opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1216 }
1217 "-fprofile-abs-path" => opts.profile_data.absolute = true,
1218 "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1219 "-fprofile-correction" => opts.profile_data.correction = true,
1220 "-fno-profile-correction" => opts.profile_data.correction = false,
1221 "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1222 "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1223 // Writing the counts rather than reading them, which is refused rather than taken and
1224 // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1225 // file a build declared as an output never appears: the instrumented program writes a
1226 // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1227 // two stage build that got neither would go on to optimize against no counts at all
1228 // and report coverage of nothing, with nothing along the way saying so. The objects
1229 // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1230 // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1231 // this is a flag that changes the output rather than a hint about speed.
1232 "-fprofile-arcs"
1233 | "--coverage"
1234 | "-fcondition-coverage"
1235 | "-fpath-coverage"
1236 | "-fprofile-generate" => {
1237 return Err(err(format!(
1238 "{arg}: this compiler does not instrument for profiling, and a build that \
1239 expects the counts a run of the instrumented program writes would optimize \
1240 against nothing on its second pass, see spec/04-driver-and-cli.md"
1241 )));
1242 }
1243 _ if arg.starts_with("-fprofile-generate=") => {
1244 return Err(err(format!(
1245 "{arg}: this compiler does not instrument for profiling, and a build that \
1246 expects the counts a run of the instrumented program writes would optimize \
1247 against nothing on its second pass, see spec/04-driver-and-cli.md"
1248 )));
1249 }
1250 "-ftest-coverage" => {
1251 return Err(err(format!(
1252 "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1253 that expects one would wait for a file that never arrives, see \
1254 spec/04-driver-and-cli.md"
1255 )));
1256 }
1257 // The rest of the family describes instrumentation that is refused above, so what is
1258 // left to do with them is check them and drop them. They are checked because a
1259 // misspelling in a distribution's flags is worth finding here rather than on the day
1260 // the instrumentation lands, and dropped because there is nothing for an answer about
1261 // how a counter is written to be an answer about.
1262 _ if arg.starts_with("-fprofile-update=") => {
1263 let how = &arg["-fprofile-update=".len()..];
1264 if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1265 return Err(err(format!(
1266 "`{how}` is not a profile update method, which is single, atomic or \
1267 prefer-atomic"
1268 )));
1269 }
1270 }
1271 _ if arg.starts_with("-fprofile-reproducible=") => {
1272 let how = &arg["-fprofile-reproducible=".len()..];
1273 if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1274 return Err(err(format!(
1275 "`{how}` is not a profile reproducibility method, which is serial, \
1276 parallel-runs or multithreaded"
1277 )));
1278 }
1279 }
1280 "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1281 "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1282 _ if arg.starts_with("-fprofile-filter-files=")
1283 || arg.starts_with("-fprofile-exclude-files=")
1284 || arg.starts_with("-fprofile-note=") => {}
1285 // What every name gets when nothing in the source said, which the attribute in the
1286 // source overrides rather than the other way round. Before the optimizer's `-f`
1287 // family below for the reason the tier below it is.
1288 _ if arg.starts_with("-fvisibility=") => {
1289 let seen = &arg["-fvisibility=".len()..];
1290 opts.visibility = seen.parse().map_err(|()| {
1291 err(format!(
1292 "`{seen}` is not a visibility, which is default, hidden, internal or \
1293 protected"
1294 ))
1295 })?;
1296 }
1297 // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1298 // family below for the reason the two above it are, and last of the three so that the
1299 // bare spelling and the negative one are matched exactly rather than by this.
1300 _ if arg.starts_with("-fcf-protection=") => {
1301 let edges = &arg["-fcf-protection=".len()..];
1302 opts.control = edges.parse().map_err(|()| {
1303 err(format!(
1304 "`{edges}` is not a control flow protection, which is full, branch, \
1305 return, none or check"
1306 ))
1307 })?;
1308 }
1309 // How much room every function opens with for something to be written over later.
1310 // Before the optimizer's `-f` family below for the reason the ones above it are.
1311 _ if arg.starts_with("-fpatchable-function-entry=") => {
1312 let room = &arg["-fpatchable-function-entry=".len()..];
1313 opts.patchable = room.parse().map_err(|()| {
1314 err(format!(
1315 "`{room}` is not an amount of room to reserve, which is a number of bytes and then, after a comma, how many of them go in front of the function's own label"
1316 ))
1317 })?;
1318 }
1319 // The memory safety monitor, from section 15.4 of
1320 // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1321 // because a pass that took the name `safety=detect` would otherwise be handed the
1322 // flag, and the tier is not a pass.
1323 _ if arg.starts_with("-fsafety=") => {
1324 let tier = &arg["-fsafety=".len()..];
1325 opts.safety = tier.parse().map_err(|()| {
1326 err(format!(
1327 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1328 ))
1329 })?;
1330 }
1331 // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1332 // than folded into the tier because it is a departure somebody who has read that
1333 // section makes, and the two defaults it describes are a property of what is being
1334 // built rather than of how much checking is wanted.
1335 _ if arg.starts_with("-fsafety-init=") => {
1336 let mode = &arg["-fsafety-init=".len()..];
1337 opts.padding = mode.parse().map_err(|()| {
1338 err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1339 })?;
1340 }
1341 // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1342 // strict form of that section needs a member id the front end does not name yet and
1343 // accepting the spelling for it would be accepting a promise this build cannot keep.
1344 // Before `-fno-` is looked at below, for the reason the tier is.
1345 "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1346 "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1347 _ if arg.starts_with("-fsafety-subobject=") => {
1348 let form = &arg["-fsafety-subobject=".len()..];
1349 return Err(err(format!(
1350 "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1351 the strict form of section 9.4 is tamnd/rucc#967"
1352 )));
1353 }
1354 // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1355 // the one above has none: there is one form of this check and a spelling that suggested
1356 // otherwise would be promising something. Before `-fno-` is looked at below, the same
1357 // way.
1358 "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1359 "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1360 _ if arg.starts_with("-fsafety-restrict=") => {
1361 let form = &arg["-fsafety-restrict=".len()..];
1362 return Err(err(format!(
1363 "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1364 )));
1365 }
1366 // Section 9.5's races, which take a value because the section gives them three modes
1367 // and the difference between two of them is which classes get reported rather than how
1368 // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1369 // reason the two above spell theirs out.
1370 _ if arg.starts_with("-fsafety-races=") => {
1371 let mode = &arg["-fsafety-races=".len()..];
1372 opts.races = mode.parse().map_err(|()| {
1373 err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1374 })?;
1375 }
1376 "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1377 // The sanitizers of document 12, which are checks at run time rather than a way of
1378 // generating the same program. Each name is held to gcc 16's list, and what is still
1379 // asked for by the end of the line is answered after the loop, so that a command line
1380 // which turns one on and then off again is a command line that asked for nothing.
1381 //
1382 // Before the optimizer's `-f` family below, for the reason the tier above it is.
1383 _ if arg.starts_with("-fsanitize=") => {
1384 for one in arg["-fsanitize=".len()..].split(',') {
1385 if one == "all" {
1386 // gcc takes `all` only in the negative, because turning every check on at
1387 // once includes checks that contradict each other.
1388 return Err(err(
1389 "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1390 ));
1391 }
1392 if !SANITIZERS.contains(&one) {
1393 return Err(err(format!(
1394 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1395 )));
1396 }
1397 if !sanitizers.contains(&one) {
1398 sanitizers.push(one);
1399 }
1400 }
1401 }
1402 _ if arg.starts_with("-fno-sanitize=") => {
1403 for one in arg["-fno-sanitize=".len()..].split(',') {
1404 if one == "all" {
1405 sanitizers.clear();
1406 continue;
1407 }
1408 if !SANITIZERS.contains(&one) {
1409 return Err(err(format!(
1410 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1411 )));
1412 }
1413 sanitizers.retain(|asked| *asked != one);
1414 }
1415 }
1416 // What a check does when it fires, and where the records about the checked objects go.
1417 // Each of them is an answer about the sanitizers refused after the loop, so there is
1418 // nothing left for them to change here. The names are still held to the list, because
1419 // a misspelling in a build's flags is worth finding when the compiler reads it.
1420 _ if arg.starts_with("-fsanitize-recover=")
1421 || arg.starts_with("-fno-sanitize-recover=")
1422 || arg.starts_with("-fsanitize-trap=")
1423 || arg.starts_with("-fno-sanitize-trap=") =>
1424 {
1425 // The guard above matched on a spelling that has an `=` in it, so the tail is
1426 // whatever follows the first one.
1427 let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1428 for one in how.split(',') {
1429 if one != "all" && !SANITIZERS.contains(&one) {
1430 return Err(err(format!(
1431 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1432 )));
1433 }
1434 }
1435 }
1436 "-fsanitize-undefined-trap-on-error"
1437 | "-fsanitize-address-use-after-scope"
1438 | "-fno-sanitize-address-use-after-scope" => {}
1439 _ if arg.starts_with("-fsanitize-sections=") => {}
1440 // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1441 // keeping. Refused rather than dropped, because a fuzzer whose calls into
1442 // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1443 // and there is no point in the campaign where that announces itself.
1444 _ if arg.starts_with("-fsanitize-coverage=") => {
1445 let how = &arg["-fsanitize-coverage=".len()..];
1446 for one in how.split(',') {
1447 if !matches!(one, "trace-pc" | "trace-cmp") {
1448 return Err(err(format!(
1449 "`{one}` is not a coverage instrumentation, which is trace-pc or \
1450 trace-cmp"
1451 )));
1452 }
1453 }
1454 return Err(err(format!(
1455 "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1456 with it would run without any feedback at all, see \
1457 spec/04-driver-and-cli.md section 4.7"
1458 )));
1459 }
1460 // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1461 // after every `-f` the rest of the compiler answers to, so a pass can never take a
1462 // name that already means something else on the command line.
1463 _ if arg.starts_with("-fpass-fuel=") => {
1464 let (name, count) = arg["-fpass-fuel=".len()..]
1465 .split_once('=')
1466 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1467 if rucc_opt::pass::find(name).is_none() {
1468 return Err(err(format!(
1469 "`{name}` is not a pass this compiler has, see --print-pipeline"
1470 )));
1471 }
1472 let count: u32 = count
1473 .parse()
1474 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1475 opts.pass_fuel.push((name.to_owned(), count));
1476 }
1477 _ if arg.starts_with("-fpass-fuel-global=") => {
1478 let count = &arg["-fpass-fuel-global=".len()..];
1479 let count: u32 = count
1480 .parse()
1481 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1482 opts.pass_fuel_global = Some(count);
1483 }
1484 // Everything from `-fopt-info` to the end of the argument, which is optional
1485 // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1486 // where the remarks are printed, because by then the compilation somebody wanted
1487 // to hear about is over.
1488 _ if arg == "-fopt-info"
1489 || arg.starts_with("-fopt-info=")
1490 || arg.starts_with("-fopt-info-") =>
1491 {
1492 let rest = &arg["-fopt-info".len()..];
1493 let (kinds, file) = match rest.split_once('=') {
1494 Some((kinds, file)) => (kinds, Some(file)),
1495 None => (rest, None),
1496 };
1497 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1498 rucc_opt::Wants::none().add(kinds).map_err(err)?;
1499 opts.opt_info.push(kinds.to_owned());
1500 if let Some(file) = file {
1501 if file.is_empty() {
1502 return Err(err("-fopt-info= was given no file to write to"));
1503 }
1504 opts.opt_info_file = Some(file.to_owned());
1505 }
1506 }
1507 _ if arg.starts_with("-fdump-ir=") => {
1508 // Checked here rather than where the dumps are taken, because the compilation
1509 // that would have been dumped is over by then.
1510 let spec = &arg["-fdump-ir=".len()..];
1511 rucc_opt::Dumps::default().add(spec).map_err(err)?;
1512 opts.dump_ir.push(spec.to_owned());
1513 }
1514 // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1515 // otherwise take the flag away from the gate. Checked here rather than where the
1516 // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1517 // name that quietly gated nothing looks exactly like a pass that is not the guilty
1518 // one, and a bisection would carry on past the thing it was looking for.
1519 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1520 let on = arg.starts_with("-fenable-");
1521 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1522 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1523 opts.pass_gates.push((on, spec.to_owned()));
1524 }
1525 // gcc's spelling for a pass this compiler has under a shorter name. It goes above the
1526 // two arms below rather than into the pile of gcc pass names further down, because the
1527 // pass is here: dropping the flag would leave a build that asked for unrolling without
1528 // it, and refusing it stops the build outright, which is what libtommath's makefile
1529 // ran into. `-funroll-all-loops` is deliberately not in here: gcc's is the one that
1530 // unrolls without a trip count, which is a different and usually worse thing.
1531 "-funroll-loops" => opts.passes.push(("unroll".to_owned(), true)),
1532 "-fno-unroll-loops" => opts.passes.push(("unroll".to_owned(), false)),
1533 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1534 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1535 }
1536 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1537 opts.passes.push((arg["-f".len()..].to_owned(), true));
1538 }
1539 // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1540 // program reduced from a miscompilation usually names the pass that miscompiled it on
1541 // its `dg-options` line, and they arrive from hand written build files for the same
1542 // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1543 // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1544 // for a compiler that does not exist here, and the program it is attached to is a
1545 // correctness test that passes either way. Turning on a pass we do not have costs
1546 // speed, turning off a pass we do not have costs nothing, and neither changes what the
1547 // program computes.
1548 //
1549 // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1550 // compiler has rather than landing here, and the day one of these names becomes a pass
1551 // here it stops being taken and dropped without anybody editing this list.
1552 //
1553 // Two of them are prefixes rather than names, which is the one place this file takes a
1554 // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1555 // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1556 // nothing else, and there is no member of either that changes the meaning of a program
1557 // that was already correct. The rest are written out one at a time, because they live
1558 // in the flat `-f` namespace where the neighbours do change meanings.
1559 _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1560 _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1561 "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1562 "-fmodulo-sched" | "-fno-modulo-sched" => {}
1563 "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1564 _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1565 }
1566 "-fearly-inlining" | "-fno-early-inlining" => {}
1567 "-finline"
1568 | "-fno-inline"
1569 | "-finline-functions"
1570 | "-fno-inline-functions"
1571 | "-finline-small-functions"
1572 | "-fno-inline-small-functions"
1573 | "-finline-functions-called-once"
1574 | "-fno-inline-functions-called-once" => {}
1575 "-foptimize-strlen" | "-fno-optimize-strlen" => {}
1576 "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
1577 // Where a function starts, which is a thing this compiler already decides and so is a
1578 // request it can answer rather than one it has to drop. The bare form asks for the
1579 // target's default and the default here is the sixteen bytes gcc also gives, so it
1580 // says nothing; a number is a floor under every function that did not ask for more
1581 // itself; and the negative form asks for the smallest boundary the target has. gcc 16
1582 // rounds a number that is not a power of two up rather than refusing it, which is what
1583 // `=3` giving `.p2align 2` on x86-64 means, so this rounds too.
1584 "-falign-functions" => opts.align_functions = None,
1585 "-fno-align-functions" => opts.align_functions = Some(MIN_FUNC_ALIGN),
1586 _ if arg.starts_with("-falign-functions=") => {
1587 opts.align_functions = function_alignment(&arg["-falign-functions=".len()..])
1588 .ok_or_else(|| {
1589 err(format!("{arg}: the alignment has to be a number of bytes"))
1590 })?;
1591 }
1592 // The other three of the family, which are about padding in front of a label inside a
1593 // body. This compiler writes none, and what they ask for is speed: a loop that starts
1594 // on a cache line boundary computes what a loop that does not computes. So they are
1595 // taken and dropped for the reason `-march=` is, and they are kept out of the arm
1596 // above because the question they ask is a different one and the day one of them is
1597 // answered it will be answered separately.
1598 _ if arg.starts_with("-falign-labels")
1599 || arg.starts_with("-falign-loops")
1600 || arg.starts_with("-falign-jumps")
1601 || arg.starts_with("-fno-align-labels")
1602 || arg.starts_with("-fno-align-loops")
1603 || arg.starts_with("-fno-align-jumps") => {}
1604 // The charset flags are not in that pile, because an encoding is a statement about
1605 // what the bytes of the source mean rather than about how fast the output is. The
1606 // preprocessor reads UTF-8 and has no converter, so the one name that describes what
1607 // already happens is taken and every other name is refused. Spelled without regard to
1608 // case and with both of the spellings iconv answers to, since a build writes whichever
1609 // one its author typed.
1610 _ if arg.starts_with("-finput-charset=") => {
1611 let name = &arg["-finput-charset=".len()..];
1612 if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
1613 return Err(err(format!(
1614 "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
1615 converter, so a file in another encoding would be read as though it were \
1616 UTF-8 rather than converted",
1617 )));
1618 }
1619 }
1620 // The three that come in on the same `dg-options` lines and are the other half of
1621 // section 4.1's rule, because each of them changes what the program does and not how
1622 // fast it does it. The negative form of each is what this compiler does anyway, so it
1623 // is taken and dropped, which is the shape `-fnested-functions` has above.
1624 "-ffast-math" => {
1625 return Err(err(
1626 "-ffast-math is a licence to answer a floating point arithmetic differently \
1627 from the way the source wrote it, and it is not one flag: it defines \
1628 __FAST_MATH__, which a library header reads, and gcc links a startup file \
1629 that puts the hardware in flush to zero mode for the whole process. Taking it \
1630 and dropping it would change what other objects in the same program answer. \
1631 -ffp-contract= and -fexcess-precision= are the parts of it this compiler has",
1632 ));
1633 }
1634 "-fno-fast-math" => {}
1635 "-fnon-call-exceptions" => {
1636 return Err(err(
1637 "-fnon-call-exceptions is a promise that an instruction which is not a call \
1638 can raise an exception the unwinder finds a handler for, and nothing here \
1639 produces a landing pad for a trapping instruction. A program built without it \
1640 would unwind past the handler it wrote",
1641 ));
1642 }
1643 "-fno-non-call-exceptions" => {}
1644 "-finstrument-functions" => {
1645 return Err(err(
1646 "-finstrument-functions calls __cyg_profile_func_enter on entry to every \
1647 function and __cyg_profile_func_exit on the way out, and nothing here emits \
1648 either call. A program that asks for them usually counts them, so taking the \
1649 flag and dropping it would turn a program that fails loudly into one that \
1650 fails quietly",
1651 ));
1652 }
1653 "-fno-instrument-functions" => {}
1654 // The unstable options, spelled the way rustc spells them and carrying the same
1655 // promise, which is none: one of these may change or go away in any release. They are
1656 // measurements and debugging aids rather than things a build asks for, which is why
1657 // none of them is in the usage text and all of them are in section 4.11 of
1658 // `spec/04-driver-and-cli.md`.
1659 "-Zverify-each" => opts.verify_each = true,
1660 _ if arg.starts_with("-Zrule-coverage=") => {
1661 let file = &arg["-Zrule-coverage=".len()..];
1662 if file.is_empty() {
1663 return Err(err("-Zrule-coverage= needs a file to write to"));
1664 }
1665 opts.rule_coverage = Some(file.to_owned());
1666 }
1667 _ if arg.starts_with("-Zcycle-accurate-model=") => {
1668 let value = &arg["-Zcycle-accurate-model=".len()..];
1669 opts.cycle_accurate_model = match value {
1670 "yes" | "1" => Some(true),
1671 "no" | "0" => Some(false),
1672 _ => {
1673 return Err(err("-Zcycle-accurate-model= takes yes or no"));
1674 }
1675 };
1676 }
1677 _ if arg.starts_with("-Zlowering=") => {
1678 let file = &arg["-Zlowering=".len()..];
1679 if file.is_empty() {
1680 return Err(err("-Zlowering= needs a file to write to"));
1681 }
1682 opts.lowering_dump = Some(file.to_owned());
1683 }
1684 _ if arg.starts_with("-Zregister-pressure=") => {
1685 let file = &arg["-Zregister-pressure=".len()..];
1686 if file.is_empty() {
1687 return Err(err("-Zregister-pressure= needs a file to write to"));
1688 }
1689 opts.register_pressure = Some(file.to_owned());
1690 }
1691 _ if arg.starts_with("-Z") => {
1692 return Err(err(format!(
1693 "`{arg}` is not an unstable option this compiler has, see \
1694 spec/04-driver-and-cli.md section 4.11 for the ones it does"
1695 )));
1696 }
1697 // The word size, which is a statement about the target and is taken as one. A build
1698 // that says the size the target already has is saying nothing, and one that says the
1699 // other size is asking for a target this compiler does not have, which it is told
1700 // rather than being given the wrong one.
1701 "-m64" | "-m32" | "-mx32" => {
1702 let want: u32 = match arg {
1703 "-m64" => 64,
1704 _ => 32,
1705 };
1706 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
1707 if have != want {
1708 return Err(err(format!(
1709 "{arg} asks for a {want} bit target and {} is {have} bit, use \
1710 --target= to name the one you mean",
1711 opts.target
1712 )));
1713 }
1714 }
1715 // Which processor in the family to generate for. This compiler emits the base
1716 // instruction set of the architecture and nothing above it, so a program built with
1717 // any of these runs on the machine that was named; it is a program that could have
1718 // been faster rather than a program that is wrong, which is what makes these safe to
1719 // take and ignore where a flag that changed the meaning of the code would not be.
1720 _ if arg.starts_with("-march=")
1721 || arg.starts_with("-mtune=")
1722 || arg.starts_with("-mcpu=") => {}
1723 // The calling convention, which is not safe to ignore. Taken when it names the one
1724 // the target already uses and refused otherwise.
1725 _ if arg.starts_with("-mabi=") => {
1726 let want = &arg["-mabi=".len()..];
1727 let have = match opts.target.arch {
1728 rucc_target::Arch::X86_64 => "sysv",
1729 rucc_target::Arch::Aarch64 => "lp64",
1730 rucc_target::Arch::Riscv64 => "lp64d",
1731 };
1732 if want != have {
1733 return Err(err(format!(
1734 "{arg}: {} uses the {have} convention and this compiler has no other",
1735 opts.target
1736 )));
1737 }
1738 }
1739 // How far apart the pieces of the program may be. The small model is what we emit and
1740 // it is every hosted program's default; the kernel model is a different one and a
1741 // build that asks for it and does not get it links and then does not run.
1742 "-mcmodel=small" => {}
1743 _ if arg.starts_with("-mcmodel=") => {
1744 return Err(err(format!(
1745 "{arg}: this compiler emits the small code model and no other, see \
1746 spec/12-targets.md"
1747 )));
1748 }
1749 // GCC's own scripting language for how the driver builds a command line.
1750 // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
1751 // build reaching for it is told which flags do the same job.
1752 _ if arg.starts_with("-specs=") => {
1753 return Err(err(
1754 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
1755 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
1756 section 4.4",
1757 ));
1758 }
1759 // Arguments meant for a separate assembler or preprocessor, which this compiler does
1760 // not have: both are inside it and neither reads a command line. Refused rather than
1761 // dropped, because every one of these says something about the output and a build
1762 // that asked for `-Wa,--noexecstack` and was silently given an executable stack got
1763 // the opposite of what it asked for.
1764 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
1765 return Err(err(format!(
1766 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
1767 are inside this compiler rather than programs it runs"
1768 )));
1769 }
1770 "-Xassembler" | "-Xpreprocessor" => {
1771 return Err(err(format!(
1772 "{arg} hands an argument to a separate assembler or preprocessor, and both \
1773 are inside this compiler rather than programs it runs"
1774 )));
1775 }
1776 // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
1777 // this one as a rule about build systems rather than about warnings: autoconf finds
1778 // out whether a warning flag exists by passing it and looking at the exit status, so
1779 // a compiler that refuses one it has not heard of fails a configure script written
1780 // for a GCC newer than itself. The names are not checked against a list because this
1781 // compiler has no warning groups for a list to be of, which #485 is about.
1782 _ if arg.starts_with("-W") => {}
1783 // Flags that name something this compiler does not do and would not do differently
1784 // if it did. `-fno-ident` is about a comment in the output that we do not write
1785 // either way, and the others are about a way of ordering the compilation that has
1786 // been GCC's only way for twenty years. Section 4.1 asks for the list to be short
1787 // and for adding to it to be deliberate, which is why it is written out here.
1788 "-fno-ident"
1789 | "-fident"
1790 | "-funit-at-a-time"
1791 | "-fno-unit-at-a-time"
1792 | "-shared-libgcc"
1793 | "-static-libgcc" => {}
1794 _ if arg.starts_with('-') && arg.len() > 1 => {
1795 // Silently ignoring an unknown flag is how a build ends up not doing what
1796 // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
1797 // for the flags that change code generation, and the safe default until the
1798 // flag table is populated is to reject everything we do not know.
1799 return Err(err(format!("unknown option `{arg}`")));
1800 }
1801 _ => inputs.push(Input { path: arg.to_owned(), forced, role: Role::File }),
1802 }
1803 }
1804
1805 // The fetch, before anything that resolves a compilation, because `--fetch` does not describe
1806 // one. It is here rather than in the loop so that `--offline` can forbid it whichever order the
1807 // two were written in, and it is before the refusals below so that a command line asking for a
1808 // sysroot is not told about a sanitizer.
1809 if let Some(named) = fetch {
1810 return fetch_action(&named, offline, &inputs);
1811 }
1812
1813 // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
1814 // order: a directory the user names outranks the compiler's own, and the compiler's own
1815 // outranks the library's. It is pushed after the loop rather than before it because
1816 // `SearchPath` appends within a group and the position is what the order is.
1817 // The same directory the headers were looked for under, because a sysroot is a statement
1818 // about a whole installation and not about half of one.
1819 // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
1820 // command line that turns a check on and off again has asked for nothing. What is left is
1821 // refused rather than dropped, and it is the one place in this parser where the reason is not
1822 // that the output would differ. A sanitizer is a promise that the program is watched while it
1823 // runs, so a build that asks for one and is quietly given a program with no checks in it does
1824 // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
1825 // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
1826 // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
1827 // options.
1828 if let Some(first) = sanitizers.first() {
1829 return Err(err(format!(
1830 "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
1831 asked for one and got none would run its tests unchecked, see \
1832 spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
1833 compiler does have"
1834 )));
1835 }
1836 link.sysroot = sysroot.clone();
1837 // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
1838 // inside the link line, because a link line that read the environment could only be tested on a
1839 // machine whose environment said the right thing, and the link line is the last thing that
1840 // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
1841 link.cache = Some(cache::dir());
1842 // And the ten field spelling of the target, because the release on it decides two things the
1843 // three field one cannot say: whether a target that is this architecture is still a cross
1844 // compile, and which directory under the cache it is against. After the loop because the last
1845 // `--target=` on the command line is the one that counts.
1846 link.pinned = pinned;
1847 // After the loop rather than where `-pthread` was read, so that it lands after the objects
1848 // that refer to it. A static link takes the definitions it needs from a library when it
1849 // reaches it and not afterwards, so a library before the objects is a library that answers
1850 // nothing.
1851 if threads {
1852 inputs.push(Input::library("pthread"));
1853 }
1854 if let Some(query) = query {
1855 return Ok(Action::Print(answer(&query, &opts, &link)?));
1856 }
1857 // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
1858 // else the command line asked for. Read here rather than where the flag was, because a `-c`
1859 // written after it has to lose and the loop cannot know that until it has ended. The output
1860 // file is where the rule goes rather than where an object would have gone, and the last
1861 // phase being the preprocessor is what makes that true without a second rule for it.
1862 if opts.deps.instead_of_compiling {
1863 opts.emit = EmitKind::Preprocessed;
1864 }
1865 if !nostdinc {
1866 opts.search.push_system(runtime::DIR);
1867 // And the library's after ours, which is the other half of the same order. They go on
1868 // here rather than at the point `--target=` or `--sysroot=` was read because either
1869 // one changes the answer and the last word on both is the end of the loop.
1870 //
1871 // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
1872 // that the headers and the libraries come from the same place. A target that is this
1873 // machine reads this machine's headers, and a target that is not reads the ones in the
1874 // sysroot for it rather than the ones next door.
1875 let cross = link::cross_sysroot(opts.target, &link);
1876 let kernel = link::cross_kernel(opts.target, &link);
1877 // And the version of those headers, which only the bundled tree has an answer for. A host
1878 // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
1879 // and a second definition with a different value is a warning on every file, so the
1880 // condition is the same one that chose the directories.
1881 if cross.is_some() {
1882 let target = pinned.unwrap_or_else(|| opts.target.tuple());
1883 opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
1884 err(format!(
1885 "{skew}; pin a release the tree has, or name a tree that has that one \
1886 with --sysroot"
1887 ))
1888 })?;
1889 }
1890 let system =
1891 library::header_dirs(opts.target, sysroot.as_deref(), cross.as_ref(), kernel.as_ref());
1892 // The two licence walls of `spec/cross-compile/13-distribution.md` section 13.4, which are
1893 // the only way step 3 comes back with nothing on a hosted target. Section 8.6 asks for the
1894 // answer to name the licence and the lawful ways to get what is behind it, rather than
1895 // leaving a person with an `#include` that failed as though a directory had gone missing.
1896 //
1897 // It is left on the search path instead of refused here, because a program that includes
1898 // none of the library needs none of the SDK and section 8.6 is explicit that targeting the
1899 // platform has to keep working. So the reason waits until an include has actually failed,
1900 // which is the only moment it helps and the only moment it is true.
1901 //
1902 // The condition is that step 3 found nothing at all, so an `SDKROOT`, an `INCLUDE` or a mac
1903 // with Xcode on it all pass through untouched, and `-nostdinc` never reaches this block. A
1904 // `--sysroot` or `-isysroot` passes through as well, even when the tree it names turns out to
1905 // be empty or absent: somebody who wrote a path has already answered the question this
1906 // message asks, and answering it again over the top of a mistyped directory would hide the
1907 // mistake behind a licence notice.
1908 if system.is_empty() && sysroot.is_none() {
1909 let tuple = pinned.unwrap_or_else(|| opts.target.tuple());
1910 if let Some(wall) = rucc_sysroot::Wall::of(tuple) {
1911 opts.search.explain_missing_system(wall.no_headers(&tuple.to_canonical_string()));
1912 }
1913 }
1914 // And whether the tree somebody named is the release they asked for, which is the one
1915 // question left once the directories are settled and the only place both halves of it are
1916 // known. Only for a named tree, because that is the case where the release in the target
1917 // stops deciding anything, and `crate::glibc` is where the rest of the reasoning is.
1918 if sysroot.is_some() {
1919 notes.extend(glibc::skew(opts.target, pinned, &system));
1920 }
1921 for dir in system {
1922 opts.search.push_system(dir);
1923 }
1924 }
1925 // Once, here, rather than as each directory is pushed. A `-I` that names a system
1926 // directory has to lose to the system entry and the system entry is added last, so the
1927 // question cannot be answered until the whole path is known.
1928 opts.search.remove_duplicates();
1929
1930 // The target has to be resolved before the configuration is printed, so this check comes
1931 // after the loop rather than at the point `--print-config` was seen.
1932 if print_config {
1933 return Ok(Action::PrintConfig(Box::new(opts)));
1934 }
1935 if print_pipeline {
1936 return Ok(Action::PrintPipeline(Box::new(opts)));
1937 }
1938 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
1939 if print_plan {
1940 return Ok(Action::PrintPlan {
1941 opts: Box::new(opts),
1942 plan: Box::new(plan),
1943 link: Box::new(link),
1944 });
1945 }
1946 Ok(Action::Compile {
1947 opts: Box::new(opts),
1948 plan: Box::new(plan),
1949 link: Box::new(link),
1950 jobs,
1951 verbose,
1952 notes,
1953 })
1954}
1955
1956/// What `--fetch <tuple>` asked for, or why it is not a thing that can be done.
1957///
1958/// The lookup happens here rather than at the point the bytes would move, so that a target this
1959/// release pins nothing for is a refusal from the parser and the only code that runs a downloader is
1960/// code that already knows what it is getting.
1961///
1962/// # Errors
1963///
1964/// [`CliError`] when `--offline` forbade it, when there are input files as well, when the tuple is
1965/// not a target this compiler knows, when its sysroot is behind one of section 13.4's licence walls,
1966/// and when this release pins no artifact for it.
1967fn fetch_action(named: &str, offline: bool, inputs: &[Input]) -> Result<Action, CliError> {
1968 // Not a precedence question. Section 13.2 says `--offline` forbids a fetch entirely, so a
1969 // command line that writes both has asked for two opposite things and the answer is to say so
1970 // rather than to pick one of them.
1971 if offline {
1972 return Err(err(
1973 "--fetch asks for a download and --offline forbids every download, so this command \
1974 line asks for two opposite things. Drop one of them: --offline is how a build says it \
1975 will not reach the network, and --fetch is the only thing in this compiler that does",
1976 ));
1977 }
1978 if let Some(first) = inputs.first() {
1979 return Err(err(format!(
1980 "--fetch gets a sysroot and compiles nothing, so `{}` on the same command line is an \
1981 input that nothing would read",
1982 first.path
1983 )));
1984 }
1985 let target: TargetTuple = named
1986 .parse()
1987 .map_err(|why| err(format!("--fetch {named}: {why}, so there is no sysroot to get")))?;
1988 // The canonical spelling, because that is what a row is named by and what the directory under
1989 // the cache is called, and a person is free to write a tuple the long way round.
1990 let tuple = target.to_canonical_string();
1991 // Before the table is consulted, because a target behind a licence wall is not a row that has not
1992 // been written yet. Section 13.4 is that no release pins one of these ever, so the message says
1993 // the licence and the two lawful ways rather than naming the producer that will publish the rest.
1994 if let Some(wall) = rucc_sysroot::Wall::of(target) {
1995 return Err(err(format!("--fetch {tuple}: {}", wall.no_fetch(&tuple))));
1996 }
1997 let Some(what) = rucc_sysroot::pinned_for(&tuple) else {
1998 return Err(err(unpinned(&tuple)));
1999 };
2000 Ok(Action::Fetch { what, target, cache: cache::dir() })
2001}
2002
2003/// Why there is nothing to fetch for a target, which is a different sentence when the table is
2004/// empty.
2005///
2006/// A release that pins nothing and a release that pins eleven targets and not this one are two
2007/// situations, and a message that did not tell them apart would send somebody looking for a typo in
2008/// their tuple when the answer is that this work is not finished.
2009fn unpinned(tuple: &str) -> String {
2010 let pinned = rucc_sysroot::pinned_targets();
2011 if pinned.is_empty() {
2012 return format!(
2013 "this release pins no sysroot for {tuple}, and it pins none for any target yet. A \
2014 sysroot is built and published by the producer in tamnd/rucc-cross, per \
2015 spec/cross-compile/13-distribution.md section 13.8, and a release of this compiler \
2016 names one by URL and by hash afterwards. Until then, pass --sysroot=<dir> to compile \
2017 against a tree you have already"
2018 );
2019 }
2020 format!(
2021 "this release pins no sysroot for {tuple}. What it pins is {}. Pass --sysroot=<dir> to \
2022 compile against a tree you have already",
2023 pinned.join(", ")
2024 )
2025}
2026
2027/// Gets the artifact and installs it, saying what each step did.
2028///
2029/// The steps are section 13.8's and so are the messages: the transport is somebody else's program
2030/// and the check is ours, so a person reading this wants to know which downloader ran, that the
2031/// bytes matched, how many files the record named and where the tree ended up. A fetch of something
2032/// that is already there says that instead and moves nothing.
2033fn fetch_sysroot(what: &rucc_sysroot::Pinned, target: TargetTuple, cache: &std::path::Path) -> i32 {
2034 let tuple = target.to_canonical_string();
2035 let archive = what.archive_in(cache);
2036 let say = |line: &str| println!("rucc: {tuple}: {line}");
2037 match fetch::fetch(what.url, what.sha256, &archive) {
2038 Ok(fetch::Fetched::AlreadyThere) => {
2039 say(&format!("{} is already here and matches the hash", archive.display()));
2040 }
2041 Ok(fetch::Fetched::Downloaded(by)) => {
2042 say(&format!("downloaded {} with {}", what.url, by.program()));
2043 }
2044 Err(why) => return complain(why),
2045 }
2046 match install::install(&archive, what.sha256, target, cache) {
2047 Ok(done) => {
2048 match &done.before {
2049 install::Before::Nothing => {
2050 say(&format!("{} files installed at {}", done.files, done.root.display()));
2051 }
2052 install::Before::TheSame => {
2053 say(&format!(
2054 "the same sysroot is already at {}, so nothing moved",
2055 done.root.display()
2056 ));
2057 }
2058 install::Before::Different(was) => {
2059 say(&format!(
2060 "{} files installed at {}, over a tree whose record digested to {was}",
2061 done.files,
2062 done.root.display()
2063 ));
2064 }
2065 }
2066 say(&format!("the record digests to {}", done.digest));
2067 0
2068 }
2069 Err(why) => complain(why),
2070 }
2071}
2072
2073/// What one of the `-dump` and `-print` flags prints.
2074///
2075/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
2076/// which is what makes the answer safe to paste into a link line whether or not the file is
2077/// there, and this does the same.
2078fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
2079 let found = |name: &str| {
2080 link::find_in_search(link, opts.target, name)
2081 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
2082 };
2083 Ok(match query {
2084 Query::Machine => opts.target.to_string(),
2085 Query::Version => VERSION.to_owned(),
2086 Query::Multiarch => link::multiarch(opts.target),
2087 // The three lines GCC prints, in its order and with its punctuation, because what reads
2088 // them is a script written against that shape. There is no installation directory to
2089 // report: this compiler is one binary that works wherever it is copied, and the headers
2090 // it ships are inside it, so `install` is where the binary is and nothing is under it.
2091 Query::SearchDirs => {
2092 let here = std::env::current_exe()
2093 .ok()
2094 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
2095 .unwrap_or_default();
2096 let list = |dirs: &[PathBuf]| {
2097 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
2098 };
2099 let libraries = link::search_dirs(link, opts.target);
2100 format!(
2101 "install: {}\nprograms: ={}\nlibraries: ={}",
2102 here.display(),
2103 list(&link.prefixes),
2104 list(&libraries)
2105 )
2106 }
2107 // The root the rest of the answers are under, which a build system asks for when it wants
2108 // to find a file itself rather than ask for one by name, and which is the first thing to
2109 // look at when a cross build read a header nobody expected. A native compile has no
2110 // sysroot and the answer is the empty line, which is what GCC prints when it was
2111 // configured without one. `--sysroot` wins over ours because it wins everywhere else.
2112 Query::Sysroot => {
2113 sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
2114 }
2115 // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
2116 // compiler's own code, what it is, where it was got, its hash, its licence and whether it
2117 // was bundled, generated or fetched. What is printed is the manifest the sysroot already
2118 // carries rather than a second format saying the same things, because the three uses 13.5
2119 // gives for this are a licence notice, a reproducibility check and a security audit, and all
2120 // three are somebody else parsing it. One format is one parser to write.
2121 // Read and rendered rather than copied out, so that what comes back is the format this
2122 // build understands. The last newline comes off because whatever prints an answer adds
2123 // one, the way it does for every other query here. Keeping it would put a blank line at
2124 // the end of the one answer that is a file somebody diffs against the file it came from.
2125 Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
2126 Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
2127 None => String::new(),
2128 },
2129 // Section 13.2 of the same document, which asks for the hash of a cache directory's
2130 // contents in the directory's name. A name cannot carry one, because the path has to be
2131 // computable before anything has been read, by the producer about to write the files and by
2132 // the compiler about to read them, and neither has the contents when it asks. So the number
2133 // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
2134 // which means `sha256sum` over the manifest answers the same thing.
2135 Query::SysrootDigest => match sysroot_manifest(opts, link)? {
2136 Some(manifest) => manifest.digest(),
2137 None => String::new(),
2138 },
2139 Query::FileName(name) => found(name),
2140 // The name GCC gives the library of routines a compiler's output calls that the C
2141 // library does not have. Ours is built in and there is no file, so the answer is the
2142 // name itself, which is what GCC prints when it cannot find one either.
2143 Query::Libgcc => found("libgcc.a"),
2144 // A program rather than a library: the linker and the archiver are the ones a build asks
2145 // about, and this compiler finds them on the path or under `-B` rather than shipping
2146 // them, so the name back is the honest answer unless a `-B` prefix holds one.
2147 Query::ProgName(name) => link
2148 .prefixes
2149 .iter()
2150 .map(|dir| dir.join(name))
2151 .find(|path| path.is_file())
2152 .map_or_else(|| name.clone(), |path| path.display().to_string()),
2153 })
2154}
2155
2156/// The root every sysroot answer is about.
2157///
2158/// One function rather than a copy in each, because the other flags exist to say what is inside the
2159/// tree this one names, and two answers that disagreed about which tree that is would be a
2160/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
2161/// else.
2162fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
2163 link.sysroot
2164 .clone()
2165 .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
2166}
2167
2168/// The record of the sysroot this command line reads, when there is one to read.
2169///
2170/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
2171/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
2172/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
2173/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
2174/// inputs in it because that one still has its header lines.
2175///
2176/// # Errors
2177///
2178/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
2179/// record we could not read on to whoever asked would make their parser the one that finds the
2180/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
2181/// output.
2182fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
2183 let Some(root) = sysroot_root(opts, link) else {
2184 return Ok(None);
2185 };
2186 let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
2187 match std::fs::read_to_string(&path) {
2188 Ok(text) => Manifest::parse(&text)
2189 .map(Some)
2190 .map_err(|why| err(format!("{}: {why}", path.display()))),
2191 Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
2192 Err(why) => Err(err(format!("{}: {why}", path.display()))),
2193 }
2194}
2195
2196/// Renders the passes this level will run, in order, with what each one does.
2197///
2198/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
2199/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
2200/// emerges from which flags happen to be set, and this is how that list is read.
2201#[must_use]
2202pub fn print_pipeline(opts: &Options) -> String {
2203 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
2204 settings.toggles.clone_from(&opts.passes);
2205 settings.global_fuel = opts.pass_fuel_global;
2206 for (on, spec) in &opts.pass_gates {
2207 // Every spelling was checked while the arguments were parsed, so there is nothing here
2208 // this can refuse, and a listing is not the place to report it if there were.
2209 let _ = settings.gates.add(*on, spec);
2210 }
2211 rucc_opt::pipeline::print(&settings)
2212}
2213
2214/// Renders the resolved configuration.
2215///
2216/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
2217/// this output is diffed across hosts in CI and a reordering would read as a change.
2218#[must_use]
2219pub fn print_config(opts: &Options) -> String {
2220 let sess = Session::new(opts.clone());
2221 let t = &sess.target;
2222 let mut out = String::new();
2223 let _ = writeln!(out, "version: {VERSION}");
2224 // The three field triple the driver was given rather than the ten field tuple it widens to,
2225 // because this output is what a build system reads to find out what it asked for. The tuple is
2226 // the compiler's model of the machine and this line is a receipt for a command line.
2227 let _ = writeln!(out, "target: {}", opts.target);
2228 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
2229 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
2230 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
2231 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
2232 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
2233 let _ = writeln!(out, "long-width: {}", t.long_width);
2234 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
2235 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
2236 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
2237 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
2238 // The register file as a count per class, which is enough to tell a target whose registers
2239 // are described from one whose are not without printing sixteen names nobody asked for.
2240 let regs: Vec<String> = t
2241 .regs
2242 .classes()
2243 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
2244 .collect();
2245 let _ = writeln!(
2246 out,
2247 "registers: {}",
2248 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
2249 );
2250 // What the schedule was chosen with, which is a sentence rather than a name on purpose: two
2251 // runs of a benchmark that disagree are usually two models and not two compilers.
2252 let _ = writeln!(out, "timing-model: {}", t.timing.map_or("none", |timing| timing.model));
2253 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
2254 let _ = writeln!(out, "safety: {}", sess.opts.safety);
2255 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
2256 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
2257 let _ = writeln!(out, "frame-pointer: {}", sess.opts.frame_pointer);
2258 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
2259 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
2260 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
2261 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
2262 let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
2263 let _ = writeln!(out, "profile: {}", sess.opts.profile);
2264 let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
2265 // Last because it is the one key with more than one line under it, and the only one
2266 // whose value is a property of the machine rather than of the command line.
2267 for dir in sess.opts.search.dirs() {
2268 let system = if dir.is_system { " (system)" } else { "" };
2269 let _ = writeln!(out, "include: {}{system}", dir.path.display());
2270 }
2271 out
2272}
2273
2274/// The output name the make target is taken from, which is the `-o` argument or nothing.
2275///
2276/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
2277/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
2278/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
2279/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
2280/// `-S` on the argument does name what the rule builds, and it is used as written.
2281fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
2282 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
2283}
2284
2285/// Writes to a path the command line named rather than one the plan derived, where `-` is
2286/// standard output.
2287fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
2288 if path == "-" {
2289 return write_out(&Output::Stdout, bytes);
2290 }
2291 write_out(&Output::File(path.to_owned()), bytes)
2292}
2293
2294/// Writes the make rule for one input, and reports whether it got there.
2295///
2296/// A rule with no file of its own goes where the compilation it replaced would have written,
2297/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
2298/// `$@`, and the same line with the `-o` left off puts it on standard output.
2299fn write_deps(
2300 opts: &Options,
2301 plan: &Plan,
2302 job: &Job,
2303 found: &[Dependency],
2304 stderr: &mut impl std::io::Write,
2305) -> bool {
2306 let targets = if opts.deps.targets.is_empty() {
2307 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
2308 } else {
2309 opts.deps.targets.clone()
2310 };
2311 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
2312 // The file, on the other hand, is named after the `-o` in every mode that still has one to
2313 // spend, which is every mode except the two that spend it on the rule.
2314 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
2315 // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
2316 // named empty rather than absent, because a makefile that named it as a target of its
2317 // own is a makefile that will look for it.
2318 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
2319 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
2320 }),
2321 None => write_out(&job.output, rule.as_bytes()),
2322 };
2323 if let Err(e) = wrote {
2324 let _ = writeln!(stderr, "rucc: error: {e}");
2325 return false;
2326 }
2327 true
2328}
2329
2330/// Runs phase 4 over every input that has one, and writes what came out.
2331///
2332/// One input that fails does not stop the others. A build that reports every file it could
2333/// not preprocess in one run is worth more than one that stops at the first, and the exit
2334/// status is still a failure either way.
2335fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
2336 let fs = OsFileSystem::new();
2337 let mut stderr = std::io::stderr().lock();
2338 let mut failed = false;
2339 for job in &plan.jobs {
2340 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
2341 // An input that is already preprocessed, or an object file. GCC passes these
2342 // through untouched, and the plan has already said so in its notes.
2343 continue;
2344 }
2345 let started = std::time::Instant::now();
2346 let result = preprocess(opts, &job.input, &fs);
2347 if opts.time {
2348 say_time(&job.input, started.elapsed(), &mut stderr);
2349 }
2350 for message in &result.messages {
2351 let _ = writeln!(stderr, "{message}");
2352 }
2353 if result.failed() {
2354 failed = true;
2355 continue;
2356 }
2357 if opts.deps.emit {
2358 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2359 // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
2360 // to write. The other two asked for both and fall through to the text below.
2361 if opts.deps.instead_of_compiling {
2362 continue;
2363 }
2364 }
2365 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
2366 let _ = writeln!(stderr, "rucc: error: {e}");
2367 failed = true;
2368 }
2369 }
2370 i32::from(failed)
2371}
2372
2373/// Whether this job is a file of assembly that has to be assembled and that nothing here assembles.
2374///
2375/// The phases rather than the kind, because there are two kinds of assembly input and one of them
2376/// is preprocessed first, and because an object file also has no compile phase and is not this: it
2377/// has no phases at all and goes to the linker as it is. A `.s` on a `-c` line has exactly
2378/// [`Phase::Assemble`] left, and a `.S` has the preprocessor in front of it, and neither has
2379/// anything the front end can do.
2380fn needs_an_assembler(job: &Job) -> bool {
2381 job.phases.contains(&Phase::Assemble) && !job.phases.contains(&Phase::Compile)
2382}
2383
2384/// Whether the preprocessor runs over it on the way in, which is the whole difference between the
2385/// two kinds of assembly input.
2386fn assembly_wants_cpp(job: &Job) -> bool {
2387 job.phases.contains(&Phase::Preprocess)
2388}
2389
2390/// Runs the front end over every input that has a compile phase, and writes what came out.
2391///
2392/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
2393/// exit status is a failure either way. An input that is already assembly or an object has no
2394/// compile phase and is passed over here, which the plan has already said in its notes.
2395fn compile_all(opts: &Options, plan: &Plan) -> i32 {
2396 let fs = OsFileSystem::new();
2397 let mut stderr = std::io::stderr().lock();
2398 let mut failed = false;
2399 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2400 failed |= !ok;
2401 let mut fired = Fired::new();
2402 let mut pressure = Pressure::new();
2403 let mut lowerings = Lowerings::new();
2404 for job in &plan.jobs {
2405 if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
2406 continue;
2407 }
2408 // An input of IR is read back rather than compiled, since the C it came from is not
2409 // here any more. A file of assembly does not go through the front end at all and is
2410 // read by the assembler instead. Everything after this is the same for all three, so
2411 // the paths meet again at the messages and the file the result is written to.
2412 let started = std::time::Instant::now();
2413 let result = if needs_an_assembler(job) {
2414 assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
2415 } else if job.kind == InputKind::Ir {
2416 compile_ir(opts, &job.input, &fs)
2417 } else {
2418 compile(opts, &job.input, &fs)
2419 };
2420 if opts.time {
2421 say_time(&job.input, started.elapsed(), &mut stderr);
2422 }
2423 fired.merge(&result.fired);
2424 pressure.merge(&result.pressure);
2425 lowerings.merge(&result.lowerings);
2426 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
2427 failed |= !remarks.write(&result.remarks, &mut stderr);
2428 for message in &result.messages {
2429 let _ = writeln!(stderr, "{message}");
2430 }
2431 // Before the failure below, because a compilation that stopped in the back end is exactly
2432 // the one whose preprocessed source somebody wants to look at.
2433 failed |= !write_temps(job, &result.temps, &mut stderr);
2434 if result.failed() {
2435 failed = true;
2436 continue;
2437 }
2438 // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
2439 // this is the one path where both files come out of the same run. An input of IR has no
2440 // dependencies to report and produces an empty list, which produces a rule naming only
2441 // itself, and that is the honest answer rather than a missing file.
2442 if opts.deps.emit {
2443 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2444 }
2445 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
2446 let _ = writeln!(stderr, "rucc: error: {e}");
2447 failed = true;
2448 }
2449 }
2450 failed |= !write_coverage(opts, &fired, &mut stderr);
2451 failed |= !write_pressure(opts, &pressure, &mut stderr);
2452 failed |= !write_lowering(opts, &lowerings, &mut stderr);
2453 i32::from(failed)
2454}
2455
2456/// A directory for the object files only the link step ever sees, removed when it goes away.
2457///
2458/// `-c` writes its object where the user can see it and linking does not, which is the whole of
2459/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
2460/// every other compiler. Removing them on drop rather than at the end of a function is so that a
2461/// link that failed leaves nothing behind either.
2462struct Scratch {
2463 /// Where the objects go.
2464 dir: PathBuf,
2465}
2466
2467impl Scratch {
2468 /// Makes one, under whatever the platform calls its temporary directory.
2469 ///
2470 /// The name carries the process id so that two compilers running at once do not share a
2471 /// directory, which they would otherwise do the moment two of them compiled a file of the
2472 /// same name.
2473 fn new() -> Result<Scratch, String> {
2474 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
2475 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
2476 Ok(Scratch { dir })
2477 }
2478}
2479
2480impl Drop for Scratch {
2481 fn drop(&mut self) {
2482 let _ = std::fs::remove_dir_all(&self.dir);
2483 }
2484}
2485
2486/// The link line the plan describes, for `-###`.
2487///
2488/// The names in it are the hints the plan carries rather than the temporaries a real compilation
2489/// would choose, because `-###` prints the line without having compiled anything and so has
2490/// nothing to point at. That also makes the printed line readable rather than naming a directory
2491/// that only exists while a compilation is running.
2492fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
2493 let linker = link::find(opts.target, link)?;
2494 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
2495 Ok(link::render(&linker, &args))
2496}
2497
2498/// Compiles everything, then links it.
2499///
2500/// The objects go in a directory that is removed afterwards, which is why this is not
2501/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
2502/// and does not say where, because where is a question that only has an answer once something is
2503/// running.
2504fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
2505 let Some(job) = &plan.link else {
2506 // Every path into here comes from a plan whose last phase is the link, and such a plan
2507 // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
2508 let mut stderr = std::io::stderr().lock();
2509 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
2510 return 1;
2511 };
2512 // Before anything is compiled, because a linker that is not on the machine is worth knowing
2513 // about in the second it takes to look rather than after the compilation.
2514 // And before that, whether this link has a line at all and whether what it reads is on the
2515 // machine. Both are answerable now, and a target whose sysroot has not been built is worth
2516 // saying so about before the compilation rather than after it.
2517 if let Err(why) = link::preflight(opts.target, link) {
2518 return complain(why);
2519 }
2520 let linker = match link::find(opts.target, link) {
2521 Ok(linker) => linker,
2522 Err(why) => return complain(why),
2523 };
2524 // And whether the one that was found can do this link, which for one linker and one target is
2525 // a question only the linker itself can answer. Here rather than inside the search, because
2526 // what it does is refuse rather than move on to the next candidate: nothing else in the list
2527 // links a produced Windows sysroot either.
2528 if let Err(why) = link::suitable(opts.target, &linker) {
2529 return complain(why);
2530 }
2531
2532 let scratch = match Scratch::new() {
2533 Ok(scratch) => scratch,
2534 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
2535 };
2536
2537 let fs = OsFileSystem::new();
2538 let mut failed = false;
2539 // One per job, in job order, which is what lets the link line below be rebuilt with the real
2540 // paths in it: every job contributes exactly one file to the line and does so in this order.
2541 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
2542 let mut fired = Fired::new();
2543 let mut pressure = Pressure::new();
2544 let mut lowerings = Lowerings::new();
2545 {
2546 let mut stderr = std::io::stderr().lock();
2547 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2548 failed |= !ok;
2549 for (at, job) in plan.jobs.iter().enumerate() {
2550 let out = match &job.output {
2551 Output::Temporary(hint) => {
2552 // The index because two inputs in different directories can have the same
2553 // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
2554 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
2555 }
2556 Output::File(path) => path.clone(),
2557 // A job feeding the linker never writes to standard output, since the plan gives
2558 // it a temporary. This is here so that the match is total rather than a panic.
2559 Output::Stdout => continue,
2560 };
2561 produced.push(out.clone());
2562 if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
2563 continue;
2564 }
2565 let started = std::time::Instant::now();
2566 let result = if needs_an_assembler(job) {
2567 assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
2568 } else if job.kind == InputKind::Ir {
2569 compile_ir(opts, &job.input, &fs)
2570 } else {
2571 compile(opts, &job.input, &fs)
2572 };
2573 if opts.time {
2574 say_time(&job.input, started.elapsed(), &mut stderr);
2575 }
2576 fired.merge(&result.fired);
2577 pressure.merge(&result.pressure);
2578 lowerings.merge(&result.lowerings);
2579 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
2580 failed |= !remarks.write(&result.remarks, &mut stderr);
2581 for message in &result.messages {
2582 let _ = writeln!(stderr, "{message}");
2583 }
2584 failed |= !write_temps(job, &result.temps, &mut stderr);
2585 if result.failed() {
2586 failed = true;
2587 continue;
2588 }
2589 // A `-MD` on a command line that links writes the rule next to the executable and
2590 // names the executable as its target, since that is the file this source builds
2591 // here. The object it went through is in a temporary directory and is gone by the
2592 // time `make` reads any of this.
2593 if opts.deps.emit {
2594 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2595 }
2596 if !matches!(result.artifact, Artifact::Object { .. }) {
2597 // Worth saying rather than writing whatever it is and letting the linker read it.
2598 // An empty file is a valid empty linker script, so a link handed one gets as far
2599 // as reporting every symbol of this file undefined, which is a page of messages
2600 // about something that went wrong here.
2601 let _ = writeln!(
2602 stderr,
2603 "rucc: internal error: {}: no object file was produced for the link",
2604 job.input
2605 );
2606 failed = true;
2607 continue;
2608 }
2609 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
2610 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
2611 failed = true;
2612 }
2613 }
2614 failed |= !write_coverage(opts, &fired, &mut stderr);
2615 failed |= !write_pressure(opts, &pressure, &mut stderr);
2616 failed |= !write_lowering(opts, &lowerings, &mut stderr);
2617 failed |= !write_lowering(opts, &lowerings, &mut stderr);
2618 }
2619 if failed {
2620 // Nothing is linked from a compilation that did not finish. A linker run over the objects
2621 // that did compile would report every function of the file that did not as undefined,
2622 // which is a page of messages about a mistake already reported once.
2623 return 1;
2624 }
2625
2626 // The items in command line order with the temporaries filled in. A library and a word for the
2627 // linker contribute no job and pass through, and every file item takes the next job's real
2628 // output, which is what keeps whatever was written between two objects between them here.
2629 let mut outputs = produced.into_iter();
2630 let mut items = Vec::with_capacity(job.inputs.len());
2631 for item in &job.inputs {
2632 match item {
2633 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
2634 link::Item::Linker(arg) => items.push(link::Item::Linker(arg.clone())),
2635 link::Item::File(_) => match outputs.next() {
2636 Some(path) => items.push(link::Item::File(path)),
2637 None => return complain("the plan asks the linker for a file nothing produced"),
2638 },
2639 }
2640 }
2641
2642 let args = match link::line(opts.target, link, &items, &job.output) {
2643 Ok(args) => args,
2644 Err(why) => return complain(why),
2645 };
2646 if verbose {
2647 let mut stderr = std::io::stderr().lock();
2648 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
2649 }
2650 let started = std::time::Instant::now();
2651 let ran = link::run(&linker, &args);
2652 if opts.time {
2653 // The one step of a compilation that really is another program, so this line is the same
2654 // measurement gcc's is and names the linker the way gcc names `collect2`.
2655 let mut stderr = std::io::stderr().lock();
2656 say_time(&linker.name, started.elapsed(), &mut stderr);
2657 }
2658 match ran {
2659 Ok(()) => 0,
2660 // The linker has already said what was wrong on its own error output, and repeating that
2661 // linking failed would only push its message further up the screen.
2662 Err(link::Error::Refused { .. }) => 1,
2663 Err(why) => complain(why),
2664 }
2665}
2666
2667/// Compiles everything and writes the objects into one static library.
2668///
2669/// No temporary directory and no second program. The objects never reach the file system at all:
2670/// they go from the compiler into the archive writer, which is both faster than writing a directory
2671/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
2672/// member's index entries are the names the object writer says it wrote, and the only thing that
2673/// knows those is the run that wrote it.
2674///
2675/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
2676/// person can find, and they are written there as well as put in the archive.
2677fn archive_all(opts: &Options, plan: &Plan) -> i32 {
2678 let Some(job) = &plan.archive else {
2679 // Every path into here comes from a plan whose last phase is the archive, and such a plan
2680 // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
2681 return complain("there is nothing to put in an archive");
2682 };
2683 // Before anything is compiled, because a format this has no container for is worth knowing
2684 // about in the second it takes to look rather than after the whole compilation.
2685 let flavour = match opts.target.os.object_format() {
2686 ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
2687 ObjectFormat::Coff => rucc_archive::Flavour::Coff,
2688 // Mach-O wants the BSD flavour, whose index is a different member under a different name,
2689 // and wasm has no archives of its own at all. Neither has an object writer either, so a
2690 // command line reaching this would have failed in the next step regardless.
2691 format @ (ObjectFormat::MachO | ObjectFormat::Wasm) => {
2692 return complain(format!(
2693 "there is no archive format for {} objects in this compiler yet",
2694 format.as_str()
2695 ));
2696 }
2697 };
2698
2699 let fs = OsFileSystem::new();
2700 let mut failed = false;
2701 let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
2702 let mut names = job.members.iter();
2703 let mut fired = Fired::new();
2704 let mut pressure = Pressure::new();
2705 let mut lowerings = Lowerings::new();
2706 {
2707 let mut stderr = std::io::stderr().lock();
2708 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2709 failed |= !ok;
2710 for plan_job in &plan.jobs {
2711 // What the plan called this member. The two lists are walked together rather than the
2712 // name being worked out again here, so that what `-###` printed and what goes in the
2713 // file cannot come apart.
2714 let Some(member) = names.next() else {
2715 return complain("the plan asks the archive for a member nothing produced");
2716 };
2717 if !plan_job.phases.contains(&Phase::Compile) && !needs_an_assembler(plan_job) {
2718 // Neither something to compile nor something to assemble, so there is nothing to
2719 // put in, and an archive quietly missing a member is worse than a message.
2720 let _ = writeln!(
2721 &mut stderr,
2722 "rucc: error: {}: this compiler makes an archive out of what it compiles, and \
2723 there is nothing here for it to do",
2724 plan_job.input
2725 );
2726 failed = true;
2727 continue;
2728 }
2729 let started = std::time::Instant::now();
2730 let result = if needs_an_assembler(plan_job) {
2731 assemble(opts, &plan_job.input, assembly_wants_cpp(plan_job), &fs)
2732 } else if plan_job.kind == InputKind::Ir {
2733 compile_ir(opts, &plan_job.input, &fs)
2734 } else {
2735 compile(opts, &plan_job.input, &fs)
2736 };
2737 if opts.time {
2738 say_time(&plan_job.input, started.elapsed(), &mut stderr);
2739 }
2740 fired.merge(&result.fired);
2741 pressure.merge(&result.pressure);
2742 lowerings.merge(&result.lowerings);
2743 failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
2744 failed |= !remarks.write(&result.remarks, &mut stderr);
2745 for message in &result.messages {
2746 let _ = writeln!(stderr, "{message}");
2747 }
2748 failed |= !write_temps(plan_job, &result.temps, &mut stderr);
2749 if result.failed() {
2750 failed = true;
2751 continue;
2752 }
2753 if opts.deps.emit {
2754 failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
2755 }
2756 let Artifact::Object { bytes, defines } = result.artifact else {
2757 let _ = writeln!(
2758 stderr,
2759 "rucc: internal error: {}: no object file was produced for the archive",
2760 plan_job.input
2761 );
2762 failed = true;
2763 continue;
2764 };
2765 // Under `-save-temps` the plan gave the object a name a person can find, so it is
2766 // written there too. Otherwise it is only ever a member and never a file.
2767 if let Output::File(path) = &plan_job.output {
2768 if let Err(e) = std::fs::write(path, &bytes) {
2769 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2770 failed = true;
2771 }
2772 }
2773 members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
2774 }
2775 failed |= !write_coverage(opts, &fired, &mut stderr);
2776 failed |= !write_pressure(opts, &pressure, &mut stderr);
2777 failed |= !write_lowering(opts, &lowerings, &mut stderr);
2778 failed |= !write_lowering(opts, &lowerings, &mut stderr);
2779 }
2780 if failed {
2781 // Nothing is written from a compilation that did not finish, for the reason the link gives:
2782 // an archive missing the file that failed is one a link reports every name of as undefined,
2783 // which is a page of messages about a mistake already reported once.
2784 return 1;
2785 }
2786
2787 let bytes = match rucc_archive::write(flavour, &members) {
2788 Ok(bytes) => bytes,
2789 // Every one of these is a bug here rather than a program's mistake: the names came from the
2790 // object writer and the bodies came from this process.
2791 Err(why) => return complain(format!("the archive could not be written: {why}")),
2792 };
2793 match std::fs::write(&job.output, &bytes) {
2794 Ok(()) => 0,
2795 Err(e) => complain(format!("{}: {e}", job.output)),
2796 }
2797}
2798
2799/// Prints one driver level message and gives back the exit status that goes with it.
2800fn complain(why: impl std::fmt::Display) -> i32 {
2801 let mut stderr = std::io::stderr().lock();
2802 let _ = writeln!(stderr, "rucc: error: {why}");
2803 1
2804}
2805
2806/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
2807///
2808/// Once for the whole command line rather than once per input, because the question is which
2809/// lowering rules this run of the compiler reached and a file per input would leave the reader
2810/// unioning files to find out something one process already knew.
2811///
2812/// A file that could not be written is a failure and not a warning. What asks for this is a
2813/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
2814fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
2815 let Some(path) = &opts.rule_coverage else { return true };
2816 let Some(table) = coverage::table(opts.target.arch) else {
2817 let _ = writeln!(
2818 stderr,
2819 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
2820 to report",
2821 opts.target
2822 );
2823 return false;
2824 };
2825 match std::fs::write(path, fired.listing(table)) {
2826 Ok(()) => true,
2827 Err(e) => {
2828 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2829 false
2830 }
2831 }
2832}
2833
2834/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
2835///
2836/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
2837/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
2838/// rule table here, since every target this compiles for has an allocator, and a run that reached
2839/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
2840/// produced no code is still an answer and it is the honest one.
2841fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
2842 let Some(path) = &opts.register_pressure else { return true };
2843 match std::fs::write(path, pressure.listing()) {
2844 Ok(()) => true,
2845 Err(e) => {
2846 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2847 false
2848 }
2849 }
2850}
2851
2852/// Writes what `-Zlowering=FILE` asked for, and says whether it could.
2853///
2854/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
2855/// not be written is a failure for the reason it gives too. A run that reached no back end writes
2856/// an empty listing rather than nothing, the way [`write_pressure`] does and for the same reason.
2857fn write_lowering(opts: &Options, lowerings: &Lowerings, stderr: &mut impl std::io::Write) -> bool {
2858 let Some(path) = &opts.lowering_dump else { return true };
2859 match std::fs::write(path, lowerings.listing()) {
2860 Ok(()) => true,
2861 Err(e) => {
2862 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2863 false
2864 }
2865 }
2866}
2867
2868/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
2869///
2870/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
2871/// A file rather than the diagnostic stream is what a harness wants: the corpus in
2872/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
2873/// a few thousand remarks mixed into that would bury it.
2874struct Remarks {
2875 /// The file, if there is one.
2876 file: Option<String>,
2877 /// Whether anything has been written to it yet, which decides between truncating and
2878 /// appending. One file holds the whole run rather than the last input in it.
2879 started: bool,
2880}
2881
2882impl Remarks {
2883 /// Prepares the destination, emptying the file if there is one.
2884 ///
2885 /// Emptied here rather than at the first remark, because a run where no pass had anything to
2886 /// say should leave an empty file and not yesterday's. An absent file and an empty one are
2887 /// different facts and something reading this will act on the difference.
2888 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
2889 let mut ok = true;
2890 if let Some(path) = file {
2891 if let Err(e) = std::fs::write(path, "") {
2892 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2893 ok = false;
2894 }
2895 }
2896 (Self { file: file.cloned(), started: false }, ok)
2897 }
2898
2899 /// Writes one input's remarks, and says whether that worked.
2900 ///
2901 /// A file that cannot be written is a failure and not a warning, for the reason
2902 /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
2903 /// where nothing happened.
2904 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
2905 if text.is_empty() {
2906 return true;
2907 }
2908 let Some(path) = &self.file else {
2909 let _ = write!(stderr, "{text}");
2910 return true;
2911 };
2912 let opened = std::fs::OpenOptions::new()
2913 .write(true)
2914 .append(self.started)
2915 .truncate(!self.started)
2916 .create(true)
2917 .open(path);
2918 self.started = true;
2919 let result =
2920 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
2921 if let Err(e) = result {
2922 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2923 return false;
2924 }
2925 true
2926 }
2927}
2928
2929/// Writes what `-fdump-ir=` asked to see, one file per dump.
2930///
2931/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
2932/// after a run is the passes in the order they ran, per input. They go in the working directory
2933/// rather than beside the output, because a dump is something a person asked for at a prompt and
2934/// the working directory is where that person is.
2935///
2936/// A file that could not be written is a failure and not a warning, for the reason
2937/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
2938/// quietly did not happen looks exactly like a pass that did not run.
2939fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
2940 let stem = std::path::Path::new(input)
2941 .file_name()
2942 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
2943 let mut ok = true;
2944 for dump in dumps {
2945 let path = format!("{stem}.{}.ir", dump.name);
2946 if let Err(e) = std::fs::write(&path, &dump.text) {
2947 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2948 ok = false;
2949 }
2950 }
2951 ok
2952}
2953
2954/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
2955///
2956/// A file that could not be written is a failure rather than a warning, for the reason
2957/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
2958/// looks like a compilation that never went through that step.
2959fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
2960 let mut ok = true;
2961 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
2962 for (path, text) in kept {
2963 // A step the compilation did not reach has nothing to keep, and a job that is not keeping
2964 // that step has nowhere to put it. Either way there is no file here.
2965 let (Some(path), Some(text)) = (path, text) else { continue };
2966 if let Err(e) = std::fs::write(&path, text) {
2967 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
2968 ok = false;
2969 }
2970 }
2971 ok
2972}
2973
2974/// One line of `-time`, which is what a step was called and how long it took.
2975///
2976/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
2977/// no subprocess for anything but the link, so what is measured here is the wall clock of the
2978/// step and the second column is always zero. The shape of the line is kept because a person
2979/// reading it next to gcc's should not have to work out which column is which.
2980fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
2981 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
2982}
2983
2984/// Writes one job's result where the plan said it goes.
2985///
2986/// # Errors
2987///
2988/// Returns the message to print, which names the file when there is one, because "permission
2989/// denied" on its own does not say which file was refused.
2990fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
2991 match output {
2992 Output::Stdout => {
2993 let mut stdout = std::io::stdout().lock();
2994 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
2995 }
2996 Output::File(path) | Output::Temporary(path) => {
2997 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
2998 }
2999 }
3000}
3001
3002/// Runs the driver and returns the process exit code.
3003///
3004/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
3005/// is the one place in the compiler that is true.
3006pub fn run(args: &[String]) -> i32 {
3007 match parse_args(args) {
3008 Ok(Action::Help) => {
3009 print!("{USAGE}");
3010 0
3011 }
3012 Ok(Action::Version) => {
3013 println!("rucc {VERSION}");
3014 0
3015 }
3016 Ok(Action::Print(line)) => {
3017 println!("{line}");
3018 0
3019 }
3020 Ok(Action::PrintConfig(opts)) => {
3021 print!("{}", print_config(&opts));
3022 0
3023 }
3024 Ok(Action::PrintPipeline(opts)) => {
3025 print!("{}", print_pipeline(&opts));
3026 0
3027 }
3028 Ok(Action::PrintPlan { opts, plan, link }) => {
3029 print!("{}", plan.render());
3030 // The line as it would be typed, which is the half of `-###` that section 4.3 says
3031 // arrives with the link. It is printed even when the linker is not on this machine,
3032 // because what a build wants from `-###` is what the compiler would do.
3033 if let Some(job) = &plan.link {
3034 match link_line(&opts, &link, job) {
3035 Ok(line) => println!("{line}"),
3036 Err(why) => {
3037 let mut stderr = std::io::stderr().lock();
3038 let _ = writeln!(stderr, "rucc: error: {why}");
3039 return 1;
3040 }
3041 }
3042 }
3043 0
3044 }
3045 Ok(Action::Fetch { what, target, cache }) => fetch_sysroot(what, target, &cache),
3046 Ok(Action::Compile { opts, plan, link, jobs, verbose, notes }) => {
3047 {
3048 let mut stderr = std::io::stderr().lock();
3049 // Before the plan rather than after it, because a note is about the command line
3050 // and the plan is what the command line was read as, so the reader wants the two
3051 // in that order.
3052 for note in ¬es {
3053 let _ = writeln!(stderr, "rucc: warning: {note}");
3054 }
3055 if verbose {
3056 let _ = write!(stderr, "{}", plan.render());
3057 let _ = writeln!(stderr, "workers: {}", jobs.count());
3058 }
3059 }
3060 if opts.emit == EmitKind::Preprocessed {
3061 return preprocess_all(&opts, &plan);
3062 }
3063 if opts.emit == EmitKind::Archive {
3064 return archive_all(&opts, &plan);
3065 }
3066 if opts.emit != EmitKind::Executable {
3067 return compile_all(&opts, &plan);
3068 }
3069 link_all(&opts, &plan, &link, verbose)
3070 }
3071 Err(e) => {
3072 let mut stderr = std::io::stderr().lock();
3073 let _ = writeln!(stderr, "rucc: error: {e}");
3074 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
3075 1
3076 }
3077 }
3078}
3079
3080#[cfg(test)]
3081mod tests {
3082 use rucc_session::{
3083 Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
3084 };
3085
3086 use super::*;
3087
3088 fn args(s: &[&str]) -> Vec<String> {
3089 s.iter().map(|x| (*x).to_owned()).collect()
3090 }
3091
3092 /// A target to write down where the host would otherwise decide, for the tests whose answer
3093 /// would be a different one on a different machine.
3094 ///
3095 /// Most of the tests here never name a target, which is right, because most of what the driver
3096 /// does with a command line is the same wherever it runs and a test that pinned one would be
3097 /// saying so in every case for the sake of the two that need it. The two that need it are the
3098 /// ones whose answer comes off the target rather than off the command line: the name an object
3099 /// gets, which is `a.o` here and `a.obj` on Windows, and whether Microsoft's reading of a
3100 /// nameless member is on, which is off here and on there. Both are the compiler being right, and
3101 /// a test that leaves the target to the host is asking a question with two correct answers.
3102 const LINUX: &str = "--target=x86_64-unknown-linux-gnu";
3103
3104 #[test]
3105 fn help_and_version_win_over_everything_else() {
3106 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
3107 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
3108 }
3109
3110 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
3111 match parse_args(&args(s)).expect("expected a compilation") {
3112 Action::Compile { opts, plan, .. } => (opts, plan),
3113 other => panic!("expected a compilation, got {other:?}"),
3114 }
3115 }
3116
3117 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
3118 match parse_args(&args(s)).expect("expected a compilation") {
3119 Action::Compile { link, plan, .. } => (link, plan),
3120 other => panic!("expected a compilation, got {other:?}"),
3121 }
3122 }
3123
3124 fn notes(s: &[&str]) -> Vec<String> {
3125 match parse_args(&args(s)).expect("expected a compilation") {
3126 Action::Compile { notes, .. } => notes,
3127 other => panic!("expected a compilation, got {other:?}"),
3128 }
3129 }
3130
3131 /// The ordinary command line has nothing to say about itself, which is the property that makes
3132 /// a note worth reading when there is one.
3133 #[test]
3134 fn a_command_line_with_nothing_wrong_with_it_carries_no_notes() {
3135 assert_eq!(notes(&["-c", "a.c"]), Vec::<String>::new());
3136 }
3137
3138 /// A directory that is not there contributes nothing to the search path, so there is no tree to
3139 /// read a release out of and nothing to compare the pin against. Said as a test because this is
3140 /// the shape a hermetic machine takes: the probe reads the disk and every other machine has a
3141 /// different disk, so what can be asserted here is the silence.
3142 #[test]
3143 fn a_named_tree_that_is_not_on_the_machine_is_not_a_release_mismatch() {
3144 let said =
3145 notes(&["--target=x86_64-linux-gnu.2.28", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3146 assert_eq!(said, Vec::<String>::new());
3147 }
3148
3149 #[test]
3150 fn collects_inputs_and_flags() {
3151 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
3152 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
3153 assert_eq!(paths, vec!["a.c", "b.c"]);
3154 assert_eq!(opts.opt_level, OptLevel::O2);
3155 assert_eq!(opts.emit, EmitKind::Object);
3156 assert!(opts.debug_info);
3157 }
3158
3159 /// The unstable options, which are spelled apart from everything else on purpose: what is
3160 /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
3161 #[test]
3162 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
3163 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
3164 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
3165
3166 let (plain, _) = compile(&["-c", "a.c"]);
3167 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
3168
3169 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
3170 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
3171 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
3172 }
3173
3174 /// The other measurement written to a file, which reads the same way and fails the same way.
3175 #[test]
3176 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
3177 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
3178 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
3179
3180 let (plain, _) = compile(&["-c", "a.c"]);
3181 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
3182
3183 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
3184 }
3185
3186 /// The third one, which says what the pre-selection lowering group did.
3187 #[test]
3188 fn where_the_lowering_dump_goes_is_asked_for_the_same_way() {
3189 let (opts, _) = compile(&["-c", "-O2", "-Zlowering=/tmp/lowering.txt", "a.c"]);
3190 assert_eq!(opts.lowering_dump.as_deref(), Some("/tmp/lowering.txt"));
3191
3192 let (plain, _) = compile(&["-c", "a.c"]);
3193 assert_eq!(plain.lowering_dump, None, "nothing is dumped unless it was asked for");
3194
3195 assert!(parse_args(&args(&["-Zlowering=", "a.c"])).is_err(), "no file named");
3196 }
3197
3198 /// Scheduling, which has the three way answer every optimization flag has: on, off, and
3199 /// nothing said, which is whatever the optimization level asks for. The name is gcc's, and
3200 /// gcc's has a two in it because gcc has a scheduler before allocation and one after and this
3201 /// is the one after.
3202 #[test]
3203 fn scheduling_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
3204 let (on, _) = compile(&["-c", "-O0", "-fschedule-insns2", "a.c"]);
3205 assert_eq!(on.schedule_insns, Some(true));
3206
3207 let (off, _) = compile(&["-c", "-O2", "-fno-schedule-insns2", "a.c"]);
3208 assert_eq!(off.schedule_insns, Some(false));
3209
3210 let (quiet, _) = compile(&["-c", "-O2", "a.c"]);
3211 assert_eq!(quiet.schedule_insns, None, "nothing said, so the level decides");
3212 assert!(quiet.opt_level.schedules(), "and at this level the level says yes");
3213
3214 let (none, _) = compile(&["-c", "a.c"]);
3215 assert!(!none.opt_level.schedules(), "at no optimization it says no");
3216 }
3217
3218 /// Whether the timing model is worth holding an instruction back over, which is a `-Z` because
3219 /// it is a question about a target's description rather than about the program being compiled.
3220 #[test]
3221 fn whether_the_timing_model_is_cycle_accurate_can_be_overridden() {
3222 let (yes, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=yes", "a.c"]);
3223 assert_eq!(yes.cycle_accurate_model, Some(true));
3224
3225 let (no, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=no", "a.c"]);
3226 assert_eq!(no.cycle_accurate_model, Some(false));
3227
3228 let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3229 assert_eq!(plain.cycle_accurate_model, None, "the target's own answer stands");
3230
3231 let bad = parse_args(&args(&["-Zcycle-accurate-model=maybe", "a.c"]))
3232 .expect_err("it takes yes or no");
3233 assert!(bad.message.contains("yes or no"), "{}", bad.message);
3234 }
3235
3236 #[test]
3237 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
3238 let (opts, _) = compile(&["-O", "a.c"]);
3239 assert_eq!(opts.opt_level, OptLevel::O1);
3240 }
3241
3242 #[test]
3243 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
3244 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
3245 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
3246 assert_eq!(plan.jobs[1].kind, InputKind::C);
3247 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
3248 }
3249
3250 #[test]
3251 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
3252 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
3253 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
3254 other => panic!("expected a compilation, got {other:?}"),
3255 };
3256 assert_eq!(jobs.count(), 4);
3257
3258 let default = match parse_args(&args(&["a.c"])).unwrap() {
3259 Action::Compile { jobs, .. } => jobs,
3260 other => panic!("expected a compilation, got {other:?}"),
3261 };
3262 assert_eq!(default, Jobs::available());
3263 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
3264 }
3265
3266 #[test]
3267 fn triple_hash_prints_the_plan_and_runs_nothing() {
3268 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
3269 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
3270 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
3271 }
3272
3273 #[test]
3274 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
3275 // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
3276 // this, and following the compiler is what makes a build that reads either of them find
3277 // the files where they are.
3278 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
3279 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
3280 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
3281 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
3282 // The last one on the line decides, the way it does for every other flag with an
3283 // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
3284 // nothing and said nothing looks exactly like one where the files were not produced.
3285 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
3286 assert_eq!(opts.save_temps, SaveTemps::Cwd);
3287 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
3288 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
3289 }
3290
3291 #[test]
3292 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
3293 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
3294 let (plain, without) = compile(&["-c", "a.c"]);
3295 assert!(opts.time);
3296 assert!(!plain.time);
3297 // Against the same line without the flag rather than against a spelling of the object's
3298 // name, since what the object is called is the host's business and this is not about that.
3299 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
3300 }
3301
3302 #[test]
3303 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
3304 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
3305 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
3306 }
3307
3308 /// What `--fetch` says for a target this release pins nothing for, which is every target except
3309 /// the three windows-gnu ones today.
3310 #[test]
3311 fn a_fetch_of_a_target_nothing_is_pinned_for_says_so_rather_than_reaching_the_network() {
3312 let e = parse_args(&args(&["--fetch", "x86_64-linux-musl"])).unwrap_err();
3313 assert!(e.message.contains("pins no sysroot for x86_64-linux-musl"), "{}", e.message);
3314 // And what it does pin, because a release with some rows in the table and a release with
3315 // none are two situations and the second sentence is what tells them apart.
3316 assert!(e.message.contains("x86_64-windows-gnu"), "{}", e.message);
3317 // The joined spelling is the same flag.
3318 let joined = parse_args(&args(&["--fetch=x86_64-linux-musl"])).unwrap_err();
3319 assert_eq!(joined, e);
3320 }
3321
3322 /// The two targets a release will never pin, which is a different answer from the one above.
3323 ///
3324 /// Section 13.4. A person who reads "this release pins no sysroot yet" waits for a release that
3325 /// does, and no release of this compiler can ship either of these, so the message names the
3326 /// licence that decides it and what to do instead.
3327 #[test]
3328 fn a_fetch_of_a_target_behind_a_licence_wall_says_so_rather_than_saying_not_yet() {
3329 let e = parse_args(&args(&["--fetch", "aarch64-macos"])).unwrap_err();
3330 assert!(e.message.contains("Xcode licence"), "{}", e.message);
3331 assert!(e.message.contains("there never will be"), "{}", e.message);
3332 assert!(!e.message.contains("tamnd/rucc-cross"), "{}", e.message);
3333
3334 let e = parse_args(&args(&["--fetch", "x86_64-windows-msvc"])).unwrap_err();
3335 assert!(e.message.contains("redistributed"), "{}", e.message);
3336 // The way out of this one is a target rather than a download, and it is the default already.
3337 assert!(e.message.contains("mingw-w64"), "{}", e.message);
3338 // And the mingw-w64 target next to it is ours to ship and published, so the same flag has
3339 // something to get rather than a licence to explain.
3340 let action = parse_args(&args(&["--fetch", "x86_64-windows-gnu"])).expect("it is pinned");
3341 let Action::Fetch { what, .. } = action else { panic!("{action:?}") };
3342 assert_eq!(what.tuple, "x86_64-windows-gnu");
3343 }
3344
3345 /// An Apple target on a machine with no SDK, which is section 8.6's other host.
3346 ///
3347 /// Not run on a mac, where the SDK this is about is installed and the compile is the ordinary one
3348 /// that uses it. What the reason says is asserted in `rucc_sysroot::wall` and where it is printed
3349 /// is asserted in `rucc-pp`, so what is left here is that the driver works it out and leaves it
3350 /// where the preprocessor will find it, and that neither way past the wall leaves one behind.
3351 #[test]
3352 fn an_apple_target_with_no_sdk_anywhere_carries_the_licence_rather_than_a_missing_directory() {
3353 if cfg!(target_os = "macos") || std::env::var_os("SDKROOT").is_some() {
3354 return;
3355 }
3356 let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
3357 let why = opts.search.missing_system().expect("the wall is the reason there are none");
3358 assert!(why.contains("aarch64-macos needs a macOS SDK"), "{why}");
3359 assert!(why.contains("Xcode licence"), "{why}");
3360 assert!(why.contains("-isysroot"), "{why}");
3361
3362 // A program that includes none of the library needs none of the SDK, which is what section
3363 // 8.6 means by being able to target the platform without one, so there is nothing to explain.
3364 let (opts, _) = compile(&["--target=aarch64-macos", "-nostdinc", "-c", "a.c"]);
3365 assert_eq!(opts.search.missing_system(), None);
3366 // And naming a path is the other way through, whether or not the path is there: a mistyped
3367 // directory is a mistake to report on its own terms rather than a licence to explain.
3368 let (opts, _) = compile(&["--target=aarch64-macos", "-isysroot", "/opt/sdk", "-c", "a.c"]);
3369 assert_eq!(opts.search.missing_system(), None);
3370 }
3371
3372 /// The same wall on the compile side of an MSVC target, where the way past it is a tuple.
3373 ///
3374 /// Not run on Windows, for the same reason the one above is not run on a mac: the wall stands in
3375 /// front of an SDK this machine does not have, and a Windows machine is the kind that does. The
3376 /// driver asks `vswhere` where Visual Studio is and takes the newest kit under it, so on a box
3377 /// with the build tools installed there are headers, no wall and nothing here to be about.
3378 /// `INCLUDE` is the other way a machine has one and is the other half of the guard, since a
3379 /// person can set that anywhere while Visual Studio is only found on the platform it runs on.
3380 #[test]
3381 fn an_msvc_target_with_no_sdk_named_says_which_environment_needs_nothing_installed() {
3382 if cfg!(target_os = "windows") || std::env::var_os("INCLUDE").is_some() {
3383 return;
3384 }
3385 let (opts, _) = compile(&["--target=x86_64-windows-msvc", "-c", "a.c"]);
3386 let why = opts.search.missing_system().expect("the wall is the reason there are none");
3387 assert!(why.contains("the Windows SDK and its universal CRT"), "{why}");
3388 assert!(why.contains("mingw-w64"), "{why}");
3389 // And the mingw-w64 target has its headers from us, so nothing is missing to explain.
3390 let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-c", "a.c"]);
3391 assert_eq!(opts.search.missing_system(), None);
3392 }
3393
3394 #[test]
3395 fn a_fetch_with_no_target_and_a_fetch_of_a_tuple_that_is_not_one_both_say_which() {
3396 let e = parse_args(&args(&["--fetch"])).unwrap_err();
3397 assert!(e.message.contains("--fetch requires"), "{}", e.message);
3398 let e = parse_args(&args(&["--fetch", "sparc64-solaris-gnu"])).unwrap_err();
3399 assert!(e.message.contains("--fetch sparc64-solaris-gnu"), "{}", e.message);
3400 assert!(e.message.contains("no sysroot to get"), "{}", e.message);
3401 }
3402
3403 /// Both flags on one line ask for opposite things, in either order.
3404 #[test]
3405 fn a_fetch_and_offline_together_is_a_refusal_whichever_way_round_they_are_written() {
3406 for line in [
3407 vec!["--offline", "--fetch", "x86_64-linux-musl"],
3408 vec!["--fetch", "x86_64-linux-musl", "--offline"],
3409 ] {
3410 let e = parse_args(&args(&line)).unwrap_err();
3411 assert!(e.message.contains("two opposite things"), "{}", e.message);
3412 }
3413 }
3414
3415 #[test]
3416 fn a_fetch_does_not_compile_anything_and_says_so_when_it_is_handed_a_file() {
3417 let e = parse_args(&args(&["--fetch", "x86_64-linux-musl", "a.c"])).unwrap_err();
3418 assert!(e.message.contains("compiles nothing"), "{}", e.message);
3419 assert!(e.message.contains("a.c"), "{}", e.message);
3420 }
3421
3422 /// `--offline` on its own is accepted and changes nothing, because an ordinary compile
3423 /// downloads nothing with or without it. A build that passes it everywhere is the case this is
3424 /// for, and it must not lose the compilation it was passed beside.
3425 #[test]
3426 fn offline_on_a_compilation_is_the_same_compilation() {
3427 let (opts, plan) = compile(&["-c", "--offline", "a.c"]);
3428 let (plain, without) = compile(&["-c", "a.c"]);
3429 assert_eq!(opts.target, plain.target);
3430 assert_eq!(plan.jobs.len(), without.jobs.len());
3431 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
3432 }
3433
3434 #[test]
3435 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
3436 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
3437 assert!(e.message.contains("unknown option"), "{}", e.message);
3438 }
3439
3440 /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
3441 /// one directory needs the older rules and the rest of the tree does not.
3442 #[test]
3443 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
3444 let (opts, _) = compile(&["-c", "a.c"]);
3445 assert!(!opts.permissive, "off unless it is asked for");
3446
3447 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
3448 assert!(opts.permissive);
3449
3450 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
3451 assert!(!opts.permissive);
3452 }
3453
3454 #[test]
3455 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
3456 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
3457 assert!(e.message.contains("trampoline"), "{}", e.message);
3458 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
3459 }
3460
3461 #[test]
3462 fn the_flag_every_configure_script_writes_is_taken() {
3463 // All four spellings, because a build writes whichever one its macros picked and a
3464 // compiler that takes three of them is a compiler that fails on the fourth.
3465 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
3466 let (opts, _) = compile(&["-c", flag, "a.c"]);
3467 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3468 }
3469 }
3470
3471 #[test]
3472 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
3473 let (opts, _) = compile(&["-c", "a.c"]);
3474 assert!(opts.unwinds(), "the default is off");
3475 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
3476 assert!(!opts.unwinds(), "the build was not taken at its word");
3477 let (opts, _) = compile(&[
3478 "-c",
3479 "-fno-asynchronous-unwind-tables",
3480 "-fasynchronous-unwind-tables",
3481 "a.c",
3482 ]);
3483 assert!(opts.unwinds(), "the last flag did not win");
3484 // The weaker request, which the same table answers, so a line that asks for a table and
3485 // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
3486 // build turns the asynchronous one off globally and a directory asks for a table back.
3487 let (opts, _) =
3488 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
3489 assert!(opts.unwinds(), "the weaker request was dropped");
3490 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
3491 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
3492 let (opts, _) =
3493 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
3494 assert!(!opts.unwinds(), "both were turned off and one stayed on");
3495 }
3496
3497 #[test]
3498 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
3499 // Every one of these is on a real build line somewhere and every one of them was an
3500 // unknown option. What they have in common is that the answer rucc gives is the answer
3501 // they ask for, so there is nothing to implement and nothing to refuse.
3502 for flag in [
3503 "-fno-common",
3504 "-fstrict-aliasing",
3505 "-fno-strict-aliasing",
3506 "-fdelete-null-pointer-checks",
3507 "-fno-delete-null-pointer-checks",
3508 "-frounding-math",
3509 "-fno-rounding-math",
3510 "-fexcess-precision=standard",
3511 "-fexcess-precision=fast",
3512 "-fexcess-precision=16",
3513 "-pipe",
3514 "-fdiagnostics-color",
3515 "-fno-diagnostics-color",
3516 "-fdiagnostics-color=always",
3517 "-fdiagnostics-color=never",
3518 "-fdiagnostics-color=auto",
3519 ] {
3520 let (opts, _) = compile(&["-c", flag, "a.c"]);
3521 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3522 }
3523 }
3524
3525 #[test]
3526 fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
3527 let (opts, _) = compile(&["-c", "a.c"]);
3528 assert!(opts.trapping_math, "the default was not gcc's");
3529 let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
3530 assert!(!opts.trapping_math);
3531 let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
3532 assert!(opts.trapping_math, "spelling out the default turned it off");
3533 // The last one written wins, which is how a build line that inherits a flag from one
3534 // place and overrides it in another is read.
3535 let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
3536 assert!(opts.trapping_math);
3537 }
3538
3539 /// The flags a torture program writes on its own `dg-options` line, which is where most of
3540 /// these come from: a program reduced from a miscompilation names the pass that miscompiled
3541 /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
3542 /// tamnd/rucc#1019 is the list.
3543 #[test]
3544 fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
3545 for flag in [
3546 "-fno-tree-ccp",
3547 "-fno-tree-dominator-opts",
3548 "-fno-tree-vrp",
3549 "-fno-tree-bit-ccp",
3550 "-fno-tree-coalesce-vars",
3551 "-ftree-vectorize",
3552 "-ftree-loop-distribution",
3553 "-fno-ipa-cp",
3554 "-fipa-pta",
3555 "-fmodulo-sched",
3556 "-fno-vect-cost-model",
3557 "-fvect-cost-model=unlimited",
3558 "-fsimd-cost-model=cheap",
3559 "-fexpensive-optimizations",
3560 "-fno-early-inlining",
3561 "-fno-inline",
3562 "-finline-functions",
3563 "-foptimize-strlen",
3564 "-fno-ira-share-spill-slots",
3565 ] {
3566 let (opts, _) = compile(&["-c", flag, "a.c"]);
3567 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3568 assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
3569 }
3570 }
3571
3572 /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
3573 /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
3574 #[test]
3575 fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
3576 for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
3577 let (opts, _) = compile(&["-c", flag, "a.c"]);
3578 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3579 }
3580 }
3581
3582 /// A pass this compiler has keeps its flag, since the arms that read the registry are above
3583 /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
3584 /// is the program that writes it.
3585 #[test]
3586 fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
3587 let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
3588 assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
3589 }
3590
3591 /// gcc's name for the unroller reaches the unroller, in both directions. libtommath puts
3592 /// `-funroll-loops` in `CFLAGS` unconditionally, and before this it was an unknown option and
3593 /// the build stopped on its first file.
3594 #[test]
3595 fn the_gcc_spelling_of_the_unroller_turns_the_unroller_on_and_off() {
3596 let (opts, _) = compile(&["-c", "-funroll-loops", "a.c"]);
3597 assert_eq!(opts.passes, vec![("unroll".to_owned(), true)]);
3598 let (opts, _) = compile(&["-c", "-fno-unroll-loops", "a.c"]);
3599 assert_eq!(opts.passes, vec![("unroll".to_owned(), false)]);
3600 }
3601
3602 /// Where a function starts is a question this compiler answers, so the flag that asks about it
3603 /// is answered rather than dropped. femtolisp's Makefile writes the bare form on every compile
3604 /// of the project, and before this it was an unknown option and the build stopped on its first
3605 /// file. The numbers are gcc 16's, read off `-S` on x86-64: nothing and the bare form both
3606 /// give `.p2align 4`, `=32` gives 5, `=3` gives 2, and the negative form gives `.align 8`.
3607 #[test]
3608 fn the_alignment_of_a_function_is_a_request_this_compiler_can_answer() {
3609 let (opts, _) = compile(&["-c", "-falign-functions", "a.c"]);
3610 assert_eq!(opts.align_functions, None, "the bare form asks for the default");
3611
3612 let (opts, _) = compile(&["-c", "-falign-functions=32", "a.c"]);
3613 assert_eq!(opts.align_functions, Some(32));
3614
3615 let (opts, _) = compile(&["-c", "-falign-functions=3", "a.c"]);
3616 assert_eq!(opts.align_functions, Some(4), "rounded up rather than refused");
3617
3618 let (opts, _) = compile(&["-c", "-falign-functions=32:8", "a.c"]);
3619 assert_eq!(opts.align_functions, Some(32), "the boundary is the answerable half");
3620
3621 for flag in ["-falign-functions=0", "-falign-functions=1"] {
3622 let (opts, _) = compile(&["-c", flag, "a.c"]);
3623 assert_eq!(opts.align_functions, None, "{flag} means the default");
3624 }
3625
3626 let (opts, _) = compile(&["-c", "-fno-align-functions", "a.c"]);
3627 assert_eq!(opts.align_functions, Some(8), "the smallest boundary the target has");
3628
3629 // The last one on the line wins, which is how gcc reads a repeated flag.
3630 let (opts, _) = compile(&["-c", "-falign-functions=32", "-falign-functions", "a.c"]);
3631 assert_eq!(opts.align_functions, None);
3632
3633 let e = parse_args(&args(&["-c", "-falign-functions=big", "a.c"])).unwrap_err();
3634 assert!(e.message.contains("number of bytes"), "{}", e.message);
3635 }
3636
3637 /// The other three of the family are about padding inside a body, which nothing here writes,
3638 /// so they are taken and say nothing. Every spelling of each, since a build writes whichever
3639 /// one its author typed.
3640 #[test]
3641 fn the_alignment_flags_about_the_inside_of_a_body_are_taken_and_say_nothing() {
3642 for flag in [
3643 "-falign-labels",
3644 "-falign-loops",
3645 "-falign-jumps",
3646 "-falign-loops=16",
3647 "-falign-labels=32",
3648 "-fno-align-loops",
3649 "-fno-align-labels",
3650 "-fno-align-jumps",
3651 ] {
3652 let (opts, _) = compile(&["-c", flag, "a.c"]);
3653 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3654 assert_eq!(opts.align_functions, None, "{flag} is not about where a function starts");
3655 }
3656 }
3657
3658 /// The encoding of the source is not a question about speed, so the one name that describes
3659 /// what the preprocessor does is taken and every other name is refused.
3660 #[test]
3661 fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
3662 for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
3663 let (opts, _) = compile(&["-c", flag, "a.c"]);
3664 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
3665 }
3666
3667 let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
3668 assert!(e.message.contains("latin1"), "{}", e.message);
3669 assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
3670 }
3671
3672 /// The other half of the same rule. Each of these changes what the program does rather than
3673 /// how fast it does it, so each is refused with the reason, and the negative of each is what
3674 /// happens anyway and is taken.
3675 #[test]
3676 fn the_three_that_change_the_answer_are_refused_and_their_negatives_are_taken() {
3677 for (flag, word) in [
3678 ("-ffast-math", "__FAST_MATH__"),
3679 ("-fnon-call-exceptions", "landing pad"),
3680 ("-finstrument-functions", "__cyg_profile_func_enter"),
3681 ] {
3682 let e = parse_args(&args(&["-c", flag, "a.c"])).unwrap_err();
3683 assert!(e.message.contains(word), "{flag}: {}", e.message);
3684 assert!(!e.message.contains("unknown option"), "{flag} deserves a reason");
3685
3686 let off = format!("-fno-{}", flag.trim_start_matches("-f"));
3687 let (opts, _) = compile(&["-c", &off, "a.c"]);
3688 assert_eq!(opts.emit, EmitKind::Object, "{off}");
3689 }
3690 }
3691
3692 #[test]
3693 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
3694 // The one of that family that is a request rather than a description, and it is a real
3695 // difference: two files each writing `int g;` link under it and do not without it.
3696 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
3697 assert!(e.message.contains(".bss"), "{}", e.message);
3698 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
3699 }
3700
3701 #[test]
3702 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
3703 for flag in ["-fno-pic", "-fno-pie"] {
3704 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
3705 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
3706 // The one it may have meant, since the two are a letter apart and one of them is
3707 // about linking and is taken.
3708 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
3709 }
3710 }
3711
3712 #[test]
3713 fn an_unsupported_target_names_itself() {
3714 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
3715 assert!(e.message.contains("sparc64"), "{}", e.message);
3716 }
3717
3718 #[test]
3719 fn no_inputs_is_an_error_but_print_config_needs_none() {
3720 assert!(parse_args(&args(&[])).is_err());
3721 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
3722 }
3723
3724 #[test]
3725 fn print_config_reports_the_target_it_was_given_not_the_host() {
3726 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
3727 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
3728 let text = print_config(&opts);
3729 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
3730 assert!(text.contains("char-signed: false"), "{text}");
3731 assert!(text.contains("object-format: elf"), "{text}");
3732 assert!(text.contains("va-list: void-pointer"), "{text}");
3733 // RISC-V has a register file and this compiler has not written it down yet, and the
3734 // dump says which of those two it is rather than leaving the line out.
3735 assert!(text.contains("registers: none"), "{text}");
3736 assert!(text.contains("timing-model: none"), "{text}");
3737 }
3738
3739 /// The model the schedule was chosen with, which is a receipt anybody comparing two runs of a
3740 /// benchmark needs: two numbers that disagree are usually two models and not two compilers.
3741 #[test]
3742 fn print_config_names_the_model_the_schedule_was_chosen_with() {
3743 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
3744 let text = print_config(&opts);
3745 let line = text.lines().find(|l| l.starts_with("timing-model:")).expect("the model");
3746 assert!(line.contains("Skylake"), "{line}");
3747 assert!(line.contains("published"), "a sentence saying where it came from: {line}");
3748 }
3749
3750 #[test]
3751 fn print_config_has_one_key_per_line_and_a_fixed_order() {
3752 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
3753 let text = print_config(&opts);
3754 let keys: Vec<&str> =
3755 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
3756 assert_eq!(keys[0], "version");
3757 assert_eq!(keys[1], "target");
3758 assert_eq!(keys.len(), 26);
3759 assert!(text.ends_with('\n'));
3760 }
3761
3762 #[test]
3763 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
3764 let (opts, _) = compile(&["a.c"]);
3765 assert_eq!(opts.safety, rucc_session::Safety::Off);
3766
3767 for (flag, tier) in [
3768 ("-fsafety=detect", rucc_session::Safety::Detect),
3769 ("-fsafety=enforce", rucc_session::Safety::Enforce),
3770 ("-fsafety=kernel", rucc_session::Safety::Kernel),
3771 ("-fsafety=off", rucc_session::Safety::Off),
3772 ] {
3773 let (opts, _) = compile(&[flag, "a.c"]);
3774 assert_eq!(opts.safety, tier, "{flag}");
3775 }
3776
3777 // The last one wins, the way every other repeated flag on this command line does.
3778 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
3779 assert_eq!(opts.safety, rucc_session::Safety::Off);
3780
3781 // A misspelled tier is refused rather than ignored. Silently compiling without the
3782 // monitor a build asked for is the one failure mode this feature cannot have.
3783 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
3784 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
3785 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
3786 }
3787
3788 #[test]
3789 fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
3790 // The default is the one section 9.3 of document 09 gives library code, which is that
3791 // padding does not participate, so a record filled a member at a time is not reported.
3792 let (opts, _) = compile(&["a.c"]);
3793 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
3794
3795 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
3796 assert_eq!(opts.padding, rucc_session::Padding::Tracked);
3797
3798 let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
3799 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
3800
3801 // The tier is still a tier. A flag whose name starts the same way must not be eaten by
3802 // the one above it, which is the thing worth pinning about a pair of names like these.
3803 let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
3804 assert_eq!(opts.safety, rucc_session::Safety::Off);
3805
3806 let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
3807 assert!(e.message.contains("is not a padding mode"), "{}", e.message);
3808 }
3809
3810 #[test]
3811 fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
3812 // Off by default, because a store to allocated storage sets its effective type and C 6.5
3813 // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
3814 let (opts, _) = compile(&["a.c"]);
3815 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
3816
3817 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
3818 assert_eq!(opts.subobject, rucc_session::Subobject::Members);
3819
3820 let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
3821 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
3822
3823 // It takes no value. The form that would take one is the strict reading of section 9.4,
3824 // which is not written yet, so say so rather than accept a spelling that does nothing.
3825 let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
3826 assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
3827 }
3828
3829 #[test]
3830 fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
3831 // Off by default, because the record a block keeps is the union of what each pointer
3832 // reached, so two pointers striding through one array without landing on the same byte are
3833 // reported and by the letter of the standard those are different objects. Row Y8 is a build
3834 // deciding it would rather know.
3835 let (opts, _) = compile(&["a.c"]);
3836 assert_eq!(opts.promise, rucc_session::Promise::Off);
3837
3838 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
3839 assert_eq!(opts.promise, rucc_session::Promise::Blocks);
3840
3841 let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
3842 assert_eq!(opts.promise, rucc_session::Promise::Off);
3843
3844 // The tier is still a tier, which is the thing worth pinning about a pair of names where
3845 // one is the front of the other.
3846 let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
3847 assert_eq!(opts.safety, rucc_session::Safety::Off);
3848
3849 let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
3850 assert!(e.message.contains("takes no value"), "{}", e.message);
3851 }
3852
3853 #[test]
3854 fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
3855 // Three modes rather than a bare flag, because section 9.5 gives two answers that record
3856 // the same thing and report different classes, so a flag with no value could not say which
3857 // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
3858 // argument: this is the one plane where an edge nobody interposed costs a false report.
3859 let (opts, _) = compile(&["a.c"]);
3860 assert_eq!(opts.races, rucc_session::Races::Off);
3861
3862 let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
3863 assert_eq!(opts.races, rucc_session::Races::Metadata);
3864
3865 let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
3866 assert_eq!(opts.races, rucc_session::Races::Pointer);
3867
3868 // Last one wins, as it does for every other mode flag here.
3869 let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
3870 assert_eq!(opts.races, rucc_session::Races::Off);
3871
3872 let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
3873 assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
3874 }
3875
3876 #[test]
3877 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
3878 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
3879 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3880 let text = print_pipeline(&opts);
3881 assert!(text.starts_with("level: -O2\n"), "{text}");
3882 assert!(text.contains("fold"), "{text}");
3883
3884 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
3885 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3886 // Two passes run at `-O0` and neither is an optimization. The first moves what
3887 // `__builtin_expect` said onto the branch and takes the instruction away, so that nothing
3888 // past the optimizer has to know the instruction exists. The second removes code nothing
3889 // reaches. See issue 359.
3890 assert!(print_pipeline(&opts).contains("1: expect,"), "{}", print_pipeline(&opts));
3891 assert!(print_pipeline(&opts).contains("2: simplify-cfg,"), "{}", print_pipeline(&opts));
3892
3893 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
3894 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3895 // The second turns off and the first does not, because nothing below the optimizer lowers
3896 // what it removes, so `-fno-expect` is a compile that stops rather than one that runs.
3897 let text = print_pipeline(&opts);
3898 assert!(text.contains("1: expect,"), "{text}");
3899 assert!(!text.contains("simplify-cfg"), "{text}");
3900 }
3901
3902 #[test]
3903 fn print_pipeline_takes_the_toggles_into_account() {
3904 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
3905 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3906 let text = print_pipeline(&opts);
3907 // The one that was named is gone and the rest of the level is not, which is the whole
3908 // of what a toggle promises.
3909 assert!(!text.contains("fold"), "{text}");
3910 assert!(text.contains("dce"), "{text}");
3911
3912 // Every pass the compiler has, named off. Built from the registry rather than written
3913 // out, so a pass added later is turned off here too and this keeps testing the thing it
3914 // is about, which is that the toggles can empty a level down to the passes that are not
3915 // optional. Those are named, because a listing that is all of them is a level nobody
3916 // emptied and the assertion would pass while saying nothing.
3917 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
3918 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
3919 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
3920 let a = parse_args(&args(&spelled)).unwrap();
3921 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3922 let text = print_pipeline(&opts);
3923 let left: Vec<&str> =
3924 rucc_opt::PASSES.iter().filter(|p| p.required()).map(|p| p.name()).collect();
3925 assert_eq!(left, vec!["expect"], "{text}");
3926 for (at, name) in left.iter().enumerate() {
3927 assert!(text.contains(&format!("{}: {name},", at + 1)), "{text}");
3928 }
3929 assert!(!text.contains("dce"), "{text}");
3930 }
3931
3932 #[test]
3933 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
3934 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
3935 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3936 assert!(!print_pipeline(&opts).contains("global fuel"));
3937
3938 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
3939 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
3940 let text = print_pipeline(&opts);
3941 // Because the listing is the answer to what this compilation will do, and a run that
3942 // stops after four rewrites is not doing what the level says it does.
3943 assert!(text.contains("global fuel: 4"), "{text}");
3944 }
3945
3946 /// A pass is turned on and off by its own name, and the order the flags were given in is
3947 /// kept, because the last spelling of a name is the one that decides.
3948 #[test]
3949 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
3950 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
3951 assert_eq!(
3952 opts.passes,
3953 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
3954 );
3955
3956 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
3957 assert!(e.message.contains("unknown option"), "{}", e.message);
3958 }
3959
3960 #[test]
3961 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
3962 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
3963 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
3964
3965 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
3966 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
3967 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
3968 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
3969 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
3970 assert!(e.message.contains("not a number"), "{}", e.message);
3971 }
3972
3973 #[test]
3974 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
3975 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
3976 assert_eq!(opts.pass_fuel_global, None);
3977
3978 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
3979 assert_eq!(opts.pass_fuel_global, Some(12));
3980 // And it is not the per pass flag with a longer name, so neither spelling swallows the
3981 // other.
3982 assert!(opts.pass_fuel.is_empty());
3983
3984 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
3985 assert!(e.message.contains("not a number"), "{}", e.message);
3986 }
3987
3988 #[test]
3989 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
3990 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
3991 assert_eq!(
3992 opts.pass_gates,
3993 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
3994 "the order is what decides, so it has to survive the parse"
3995 );
3996
3997 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
3998 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
3999 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
4000 assert!(e.message.contains("ends before it starts"), "{}", e.message);
4001 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
4002 assert!(e.message.contains("is empty"), "{}", e.message);
4003 }
4004
4005 #[test]
4006 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
4007 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
4008 let text = print_pipeline(&opts);
4009 assert!(text.contains("fold, "), "{text}");
4010 assert!(text.contains("[off for main]"), "{text}");
4011 }
4012
4013 /// The spelling is checked while the arguments are read, because a dump that names a pass
4014 /// this compiler does not have is a typo, and a typo found after the compilation has run is
4015 /// found too late to be any use.
4016 #[test]
4017 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
4018 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
4019 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
4020
4021 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
4022 assert!(e.message.contains("nosuch"), "{}", e.message);
4023 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
4024 }
4025
4026 /// Every spelling `-fopt-info` takes, and the one it does not.
4027 ///
4028 /// The keywords are checked here for the same reason a dump's pass name is: a person who
4029 /// misspelled one gets no output, and no output is also what a compilation where nothing
4030 /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
4031 #[test]
4032 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
4033 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
4034 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
4035 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
4036
4037 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
4038 assert_eq!(opts.opt_info, ["missed-note"]);
4039
4040 // Two flags add up rather than the second replacing the first, and the file is the last
4041 // one that named a file, which is how GCC treats both.
4042 let (opts, _) =
4043 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
4044 assert_eq!(opts.opt_info, ["missed", "all"]);
4045 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
4046
4047 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
4048 assert!(e.message.contains("vectorized"), "{}", e.message);
4049 assert!(e.message.contains("`missed`"), "{}", e.message);
4050 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
4051 assert!(e.message.contains("no file"), "{}", e.message);
4052 }
4053
4054 #[test]
4055 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
4056 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
4057 assert!(opts.verify_each);
4058 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
4059 }
4060
4061 #[test]
4062 fn dash_o_needs_an_argument() {
4063 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
4064 assert_eq!(e.message, "-o requires an argument");
4065 }
4066
4067 #[test]
4068 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
4069 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
4070 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
4071 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
4072 }
4073
4074 #[test]
4075 fn the_include_flags_land_on_the_chain_each_one_names() {
4076 // A sysroot with nothing under it, so that the library's own directories are the
4077 // same on every machine this test runs on, which is none of them.
4078 let (opts, _) = compile(&[
4079 "-Ii",
4080 "-iquote",
4081 "q",
4082 "-isystem",
4083 "sys",
4084 "-idirafter",
4085 "after",
4086 "--sysroot=/nowhere-at-all",
4087 "a.c",
4088 ]);
4089 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4090 // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
4091 // which is where GCC puts its own: a directory the user named outranks ours.
4092 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
4093 assert!(!opts.search.dirs()[1].is_system);
4094 assert!(opts.search.dirs()[2].is_system);
4095 }
4096
4097 #[test]
4098 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
4099 // Which machine this runs on decides what is on the path, so the test is about the
4100 // order rather than about the names: ours is on it, the library's follow it, and
4101 // `-nostdinc` is the one flag that takes both halves of the pair off at once.
4102 let (opts, _) = compile(&["a.c"]);
4103 let dirs = opts.search.dirs();
4104 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
4105 assert_eq!(ours, Some(0), "{dirs:?}");
4106 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
4107 let (bare, _) = compile(&["-nostdinc", "a.c"]);
4108 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
4109 }
4110
4111 #[test]
4112 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
4113 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
4114 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4115 assert_eq!(dirs, ["sys", runtime::DIR]);
4116 }
4117
4118 #[test]
4119 fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
4120 // The target is not the machine this test runs on wherever it runs, so the answer is the
4121 // same on all of them: the libc's two include directories for that target, the kernel's
4122 // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
4123 // program that builds on the build machine and is wrong everywhere else.
4124 let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
4125 let dirs: Vec<&std::path::Path> =
4126 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4127 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
4128 let kernel = cache::dir().join("kernel-headers");
4129 assert_eq!(dirs.len(), 5, "{dirs:?}");
4130 assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
4131 assert_eq!(dirs[1], root.join("include").join("riscv64"));
4132 assert_eq!(dirs[2], root.join("include").join("generic"));
4133 // The kernel's, which are beside the sysroots rather than inside one, because every target
4134 // that shares an architecture reads the same files.
4135 assert_eq!(dirs[3], kernel.join("riscv"));
4136 assert_eq!(dirs[4], kernel.join("generic"));
4137 }
4138
4139 #[test]
4140 fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
4141 // The other side of the same answer. Windows has its own system headers and no `linux/` at
4142 // all, so the list is the libc's own and the question never arises, which is the `None` that
4143 // `link::cross_kernel` returns rather than a directory nothing would be found in.
4144 //
4145 // The libc's own is one directory rather than two here, because mingw-w64 publishes a single
4146 // header tree for every architecture and `Sysroot::splits_by_arch` says so.
4147 let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
4148 let dirs: Vec<&std::path::Path> =
4149 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4150 assert_eq!(dirs.len(), 2, "{dirs:?}");
4151 assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
4152 }
4153
4154 #[test]
4155 fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
4156 // One tree serves every glibc release, so the release is what the target supplies, and the
4157 // condition is the same one that chose the directories. A host glibc and a tree somebody
4158 // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
4159 // different values is a warning on every compilation of every file.
4160 //
4161 // The architecture is chosen against this machine's rather than written down, because the
4162 // bundled tree is only in effect for a target that is not this machine. The first version of
4163 // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
4164 // Linux runner, so it passed here and failed there.
4165 let gnu = format!("--target={}-linux-gnu", cross_arch());
4166 let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
4167 assert_eq!(bundled.glibc_minor, Some(44));
4168 let pin = format!("{gnu}.2.28");
4169 let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
4170 assert_eq!(pinned.glibc_minor, Some(28));
4171
4172 let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
4173 assert_eq!(named.glibc_minor, None);
4174 let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
4175 assert_eq!(none.glibc_minor, None);
4176 let musl = format!("--target={}-linux-musl", cross_arch());
4177 let (musl, _) = compile(&[&musl, "-c", "a.c"]);
4178 assert_eq!(musl.glibc_minor, None);
4179
4180 // And this machine's own target gets nothing, whatever this machine is, because its headers
4181 // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
4182 // that is the case this test had backwards; on a mac it is true for the other reason, which
4183 // is that Darwin is not a glibc target at all.
4184 if let Some(host) = Triple::host() {
4185 let native = format!("--target={}", host.tuple());
4186 let (native, _) = compile(&[&native, "-c", "a.c"]);
4187 assert_eq!(native.glibc_minor, None);
4188 }
4189 }
4190
4191 #[test]
4192 fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
4193 // The end to end half of the answer in `link::cross_for`. A release named for this machine's
4194 // own target is a cross compile, so the headers are the bundled tree's and the macro says
4195 // what was asked for rather than what this machine has.
4196 //
4197 // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
4198 // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
4199 // where the case lives.
4200 let Some(host) = Triple::host() else { return };
4201 if host.env != rucc_target::Env::Gnu {
4202 return;
4203 }
4204 let pin = format!("--target={}.2.28", host.tuple());
4205 let (opts, _) = compile(&[&pin, "-c", "a.c"]);
4206 assert_eq!(opts.glibc_minor, Some(28));
4207 let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
4208 let dirs: Vec<&std::path::Path> =
4209 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4210 assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
4211 // And nothing of this machine's, which is the failure this was: a program compiled against
4212 // 2.44 declarations and told it was 2.28.
4213 assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
4214 }
4215
4216 /// An architecture that is not this machine's, out of the three the driver has targets for.
4217 ///
4218 /// A test about the bundled sysroot has to name a target that is not the host, because a target
4219 /// that is the host reads the host's own headers and libraries. Asking which machine this is
4220 /// beats picking a row and hoping, and it is two lines.
4221 fn cross_arch() -> &'static str {
4222 match Triple::host().map(|host| host.arch) {
4223 Some(rucc_target::Arch::X86_64) => "aarch64",
4224 _ => "x86_64",
4225 }
4226 }
4227
4228 #[test]
4229 fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
4230 // Both versions in the message, because the two things a person can do about it are pin a
4231 // release the tree has and name a sysroot that has the one they asked for, and neither is a
4232 // choice they can make without knowing which release the tree is.
4233 //
4234 // Not this machine's architecture, for the reason the test above gives: the refusal is about
4235 // the bundled tree, and the bundled tree is not what a target that is this machine reads.
4236 let target = format!("--target={}-linux-gnu.2.99", cross_arch());
4237 let message = refused(&[&target, "-c", "a.c"]);
4238 assert!(message.contains("asked for glibc 2.99"), "{message}");
4239 assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
4240 assert!(message.contains("--sysroot"), "{message}");
4241 }
4242
4243 #[test]
4244 fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
4245 // The tree somebody assembled beats the one we would build, on the headers as on the
4246 // libraries. It is empty here, which is why the list comes out short: the directories under
4247 // it are checked for rather than assumed, and a tree that is not there offers nothing.
4248 let (opts, _) =
4249 compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
4250 let dirs: Vec<&std::path::Path> =
4251 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
4252 assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
4253 }
4254
4255 #[test]
4256 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
4257 let (opts, _) =
4258 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
4259 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4260 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
4261 // An angled include sees only what came after the flag.
4262 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
4263 assert!(!opts.search.searches_current_dir());
4264 }
4265
4266 #[test]
4267 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
4268 let (opts, _) = compile(&[
4269 "-iprefix",
4270 "/tools/",
4271 "-iwithprefix",
4272 "late",
4273 "-iwithprefixbefore",
4274 "early",
4275 "-iprefix",
4276 "/other/",
4277 "-iwithprefix",
4278 "last",
4279 "-nostdinc",
4280 "a.c",
4281 ]);
4282 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4283 // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
4284 // puts them rather than where its manual says it does.
4285 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
4286 assert!(!opts.search.dirs()[0].is_system);
4287 assert!(opts.search.dirs()[1].is_system);
4288 }
4289
4290 #[test]
4291 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
4292 let (opts, _) =
4293 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
4294 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
4295 assert_eq!(names, ["one.h", "two.h", "3.h"]);
4296 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
4297 }
4298
4299 #[test]
4300 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
4301 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
4302 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
4303 assert_eq!(dirs, ["i"]);
4304 }
4305
4306 #[test]
4307 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
4308 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
4309 assert_eq!(opts.std, Std::C11);
4310 assert!(opts.gnu_extensions);
4311
4312 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
4313 assert_eq!(opts.std, Std::C99);
4314 assert!(!opts.gnu_extensions);
4315
4316 let (opts, _) = compile(&["-ansi", "a.c"]);
4317 assert_eq!(opts.std, Std::C89);
4318 assert!(!opts.gnu_extensions);
4319
4320 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
4321 assert!(e.message.contains("unknown dialect"), "{}", e.message);
4322 }
4323
4324 #[test]
4325 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
4326 let (opts, _) = compile(&["-dM", "a.c"]);
4327 assert!(opts.dumps.macros);
4328
4329 // Packed, the way GCC takes them, and a letter in the family we have not written yet
4330 // is accepted and does nothing rather than failing a build.
4331 let (opts, _) = compile(&["-dDM", "a.c"]);
4332 assert!(opts.dumps.macros);
4333 let (opts, _) = compile(&["-dD", "a.c"]);
4334 assert!(!opts.dumps.macros);
4335
4336 let (opts, _) = compile(&["a.c"]);
4337 assert!(!opts.dumps.any());
4338
4339 // `-dumpversion` is a different flag that happens to start the same way, and it is read
4340 // as itself rather than as a dump of nothing.
4341 assert_eq!(printed(&["-dumpversion", "a.c"]), VERSION);
4342 }
4343
4344 #[test]
4345 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
4346 let (opts, _) = compile(&["a.c"]);
4347 assert_eq!(
4348 opts.gnuc,
4349 GnucVersion { major: 7, minor: 0, patch: 0 },
4350 "the lowest claim a modern glibc gives its own declarations to"
4351 );
4352
4353 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
4354 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
4355
4356 // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
4357 // patchlevel and a harness that pastes that back has to be understood.
4358 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
4359 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
4360
4361 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
4362 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
4363
4364 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
4365 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
4366
4367 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
4368 assert!(e.message.contains("more than three"), "{}", e.message);
4369 }
4370
4371 #[test]
4372 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
4373 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
4374 assert!(opts.pedantic);
4375 assert_eq!(opts.std, Std::C17);
4376
4377 // The `-W` family's name for it, which is what a build that groups its warning flags
4378 // tends to write.
4379 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
4380 assert!(opts.pedantic);
4381
4382 let (opts, _) = compile(&["-std=c17", "a.c"]);
4383 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
4384 }
4385
4386 #[test]
4387 fn dash_p_and_dash_ffreestanding_reach_the_options() {
4388 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
4389 assert!(!opts.line_markers);
4390 assert!(!opts.hosted);
4391 assert_eq!(opts.emit, EmitKind::Preprocessed);
4392 }
4393
4394 /// The two ways a build says it means its own function by a name the C library also has.
4395 ///
4396 /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
4397 /// build writes when it means its own `memcpy` and the library's everything else. The name is
4398 /// kept as it was written and not checked against anything, because a program is allowed to
4399 /// mean something by a name this compiler has never heard of.
4400 #[test]
4401 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
4402 let (opts, _) = compile(&["-c", "a.c"]);
4403 assert!(opts.builtins, "a library name means the library function by default");
4404 assert!(opts.no_builtin.is_empty());
4405
4406 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
4407 assert!(!opts.builtins);
4408
4409 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
4410 assert!(opts.builtins, "the last mention decides");
4411
4412 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
4413 assert!(opts.builtins, "one name is not the family");
4414 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
4415 }
4416
4417 /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
4418 /// and which was refused as an unknown option until now.
4419 ///
4420 /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
4421 /// the address across a component boundary, and nothing derives anything from that promise
4422 /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
4423 /// over a distinction this compiler does not make.
4424 #[test]
4425 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
4426 let (opts, _) = compile(&["-c", "a.c"]);
4427 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
4428
4429 for (written, wanted) in [
4430 ("default", Visibility::Default),
4431 ("hidden", Visibility::Hidden),
4432 ("internal", Visibility::Hidden),
4433 ("protected", Visibility::Protected),
4434 ] {
4435 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
4436 assert_eq!(opts.visibility, wanted, "{written}");
4437 }
4438
4439 // The last mention decides, which is what every other flag of this shape does and what a
4440 // build that turns something off for one directory relies on.
4441 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
4442 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
4443
4444 // A spelling gcc does not take is refused rather than read as the default, because a
4445 // build that meant hidden and got exported is a library with the wrong interface and
4446 // nothing said about it anywhere.
4447 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
4448 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
4449 }
4450
4451 /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
4452 /// described, and the values are gcc 16's three.
4453 #[test]
4454 fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
4455 let (opts, _) = compile(&["-c", "a.c"]);
4456 assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
4457
4458 for (written, wanted) in
4459 [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
4460 {
4461 let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
4462 assert_eq!(opts.fp_contract, wanted, "{written}");
4463 }
4464
4465 let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
4466 assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
4467
4468 // Refused rather than read as one of the three, because a build that asked for no fusing
4469 // and was given the default would be one whose numbers change and whose command line says
4470 // they should not. gcc refuses the same spellings and names the same three in its message.
4471 for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
4472 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
4473 assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
4474 }
4475
4476 // And the other one that takes a value, which is taken and kept nowhere: every operation
4477 // here is computed in the type it was written in, so `standard` is what happens and the
4478 // other two are permission to do something this does not do.
4479 let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
4480 assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
4481 }
4482
4483 /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
4484 /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
4485 /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
4486 #[test]
4487 fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
4488 let (opts, _) = compile(&["-c", "a.c"]);
4489 assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
4490 assert!(opts.prefix_map.debug.is_empty(), "nor here");
4491 assert!(opts.prefix_map.profile.is_empty(), "nor here");
4492
4493 let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
4494 assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
4495 assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
4496
4497 let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
4498 assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
4499 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
4500
4501 let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
4502 assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
4503 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
4504
4505 let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
4506 for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
4507 assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
4508 }
4509
4510 // Every mention is kept and the last one that matches wins, unlike the flags above whose
4511 // last mention replaces the earlier ones. A build writes one of these per source root and
4512 // expects all of them to be in force, which is the whole point of a list.
4513 let (opts, _) =
4514 compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
4515 assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
4516 assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
4517
4518 // An argument with no `=` is refused rather than ignored, because a build whose paths were
4519 // meant to be rewritten and were not is one that ships the build directory's name and says
4520 // nothing about it. gcc refuses the same thing.
4521 for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
4522 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
4523 assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
4524 }
4525 }
4526
4527 /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
4528 /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
4529 /// one. A kernel and an embedded image are both linked that way.
4530 ///
4531 /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
4532 /// the other is a build that measured something: splitting the code is nearly free at link time
4533 /// and splitting the data can defeat the linker's ordering of what is next to what.
4534 #[test]
4535 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
4536 let (opts, _) = compile(&["-c", "a.c"]);
4537 assert!(!opts.function_sections, "one text section unless something says otherwise");
4538 assert!(!opts.data_sections);
4539
4540 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
4541 assert!(opts.function_sections);
4542 assert!(!opts.data_sections, "one flag is not the other");
4543
4544 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
4545 assert!(opts.data_sections);
4546 assert!(!opts.function_sections);
4547
4548 // Both directions taken, and the off one is what happens anyway rather than a refusal,
4549 // since a build that writes it is asking for the default.
4550 let (opts, _) = compile(&[
4551 "-c",
4552 "-ffunction-sections",
4553 "-fno-function-sections",
4554 "-fdata-sections",
4555 "-fno-data-sections",
4556 "a.c",
4557 ]);
4558 assert!(!opts.function_sections, "the last mention decides");
4559 assert!(!opts.data_sections, "the last mention decides");
4560 }
4561
4562 /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
4563 /// line, since the dialect asks for GNU's reading further in rather than through this.
4564 #[test]
4565 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
4566 let (opts, _) = compile(&["-c", "a.c"]);
4567 assert!(!opts.gnu89_inline, "C's reading of inline by default");
4568
4569 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
4570 assert!(opts.gnu89_inline);
4571
4572 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
4573 assert!(!opts.gnu89_inline, "the last mention decides");
4574
4575 // The C89 dialects are under GNU's reading whether this was written or not, so the flag
4576 // stays off there and the dialect is what the checker and the macro set both ask. That is
4577 // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
4578 // dialect already has. gcc refuses that command line, which is measured in the issue.
4579 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
4580 assert!(!opts.gnu89_inline);
4581 }
4582
4583 /// Both spellings of both frame flags, since a build that wants one usually writes the
4584 /// other beside it for the one file that has to be compiled the ordinary way.
4585 #[test]
4586 fn the_two_frame_flags_are_read_in_both_directions() {
4587 let (opts, _) = compile(&["-c", "a.c"]);
4588 assert!(!opts.frame_pointer, "gcc omits it above -O0 and so does this");
4589 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
4590
4591 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
4592 assert!(opts.frame_pointer);
4593 assert!(!opts.red_zone);
4594
4595 let (opts, _) = compile(&[
4596 "-c",
4597 "-fno-omit-frame-pointer",
4598 "-fomit-frame-pointer",
4599 "-mno-red-zone",
4600 "-mred-zone",
4601 "a.c",
4602 ]);
4603 assert!(!opts.frame_pointer, "the last one wins, as it does in gcc");
4604 assert!(opts.red_zone);
4605 }
4606
4607 /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
4608 /// spelled three ways because a build that turns one off writes whichever it turned on.
4609 #[test]
4610 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
4611 let (opts, _) = compile(&["-c", "a.c"]);
4612 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
4613
4614 for (flag, want) in [
4615 ("-fstack-protector", Protector::Buffers),
4616 ("-fstack-protector-strong", Protector::Strong),
4617 ("-fstack-protector-all", Protector::All),
4618 ] {
4619 let (opts, _) = compile(&["-c", flag, "a.c"]);
4620 assert_eq!(opts.protector, want, "{flag}");
4621 }
4622
4623 // What a package build does: the strong one in the global flags and one directory that
4624 // cannot have a protector turning it off on the line after.
4625 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
4626 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
4627 assert_eq!(opts.protector, Protector::None, "{off}");
4628 }
4629 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
4630 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
4631 }
4632
4633 /// A switch rather than a level, because how a frame is taken is one question and which
4634 /// functions get a canary is another, and gcc spells it that way for the same reason.
4635 #[test]
4636 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
4637 let (opts, _) = compile(&["-c", "a.c"]);
4638 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
4639
4640 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
4641 assert!(opts.stack_clash);
4642
4643 // The same shape a package build uses for the protector: on in the global flags and off
4644 // for the one directory that cannot have it.
4645 let (opts, _) =
4646 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
4647 assert!(!opts.stack_clash);
4648 let (opts, _) =
4649 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
4650 assert!(opts.stack_clash, "the last one wins either way round");
4651
4652 // The two are independent, since one is about the frame and the other about the function.
4653 let (opts, _) =
4654 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
4655 assert!(opts.stack_clash);
4656 assert_eq!(opts.protector, Protector::Strong);
4657 }
4658
4659 /// One flag with an argument rather than a family of spellings, because what it asks about is
4660 /// which of the two edges of a control flow transfer is checked and the two are not separate
4661 /// questions to the hardware.
4662 #[test]
4663 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
4664 let (opts, _) = compile(&["-c", "a.c"]);
4665 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
4666
4667 for (arg, want) in [
4668 ("-fcf-protection", Control::Full),
4669 ("-fcf-protection=full", Control::Full),
4670 ("-fcf-protection=branch", Control::Branch),
4671 ("-fcf-protection=return", Control::Return),
4672 ("-fcf-protection=none", Control::None),
4673 ("-fcf-protection=check", Control::Check),
4674 ] {
4675 let (opts, _) = compile(&["-c", arg, "a.c"]);
4676 assert_eq!(opts.control, want, "{arg}");
4677 }
4678
4679 // The shape a package build uses: on in the global flags and off for the one directory
4680 // that cannot have it, whichever of the two spellings of off it reaches for.
4681 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
4682 assert_eq!(opts.control, Control::None);
4683 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
4684 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
4685 }
4686
4687 /// The profiler is asked for by two spellings, and where its hook goes by two more.
4688 ///
4689 /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
4690 /// asks for no call, which is what gcc does with it, and a build system that sets it globally
4691 /// and asks for the profile per directory needs that to be true rather than an error.
4692 ///
4693 /// The link is asserted alongside, because the flag changes it too and a build that compiled
4694 /// with it and linked without it is a program that calls the hook everywhere and never writes a
4695 /// profile.
4696 #[test]
4697 fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
4698 let (opts, _) = compile(&["-c", "a.c"]);
4699 assert!(!opts.profile);
4700 assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
4701
4702 for arg in ["-pg", "-p"] {
4703 let (opts, _) = compile(&["-c", arg, "a.c"]);
4704 assert!(opts.profile, "{arg}");
4705 let (link, _) = linking(&[arg, "a.c"]);
4706 assert!(link.profile, "{arg} changes the link as well");
4707 }
4708
4709 for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
4710 let (opts, _) = compile(&["-c", arg, "a.c"]);
4711 assert_eq!(opts.hook, want, "{arg}");
4712 assert!(!opts.profile, "{arg} asks for no call of its own");
4713 }
4714
4715 let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
4716 assert_eq!(opts.hook, Hook::Late, "the last one wins");
4717 assert!(opts.profile);
4718 }
4719
4720 /// How much room a patcher is promised, which is one number or two.
4721 ///
4722 /// A command line that did not ask is asserted alongside, because the flag has to be written to
4723 /// mean anything and a build that reserved room nobody asked for would grow every function in
4724 /// it for nothing.
4725 #[test]
4726 fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
4727 let (opts, _) = compile(&["-c", "a.c"]);
4728 assert_eq!(opts.patchable, Patchable::default());
4729 assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
4730
4731 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
4732 assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
4733
4734 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
4735 assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
4736 assert_eq!(opts.patchable.after(), 2);
4737
4738 // The last one wins, which is what every other flag of this shape does and what a build
4739 // that adds one to a command line it did not write is relying on.
4740 let (opts, _) = compile(&[
4741 "-c",
4742 "-fpatchable-function-entry=5,3",
4743 "-fpatchable-function-entry=2",
4744 "a.c",
4745 ]);
4746 assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
4747 }
4748
4749 /// And a request nothing could satisfy is refused rather than rounded into one that can be.
4750 #[test]
4751 fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
4752 for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
4753 let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
4754 assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
4755 }
4756 }
4757
4758 /// What wraps rather than being undefined, which is two questions and three flags.
4759 ///
4760 /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
4761 /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
4762 /// only what it asked for.
4763 #[test]
4764 fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
4765 let (opts, _) = compile(&["-c", "a.c"]);
4766 assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
4767
4768 let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
4769 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
4770
4771 let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
4772 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
4773
4774 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
4775 assert_eq!(opts.wrapping, Wrapping::ALL);
4776
4777 // And the last one wins, in both directions. A build that turns one of these on globally
4778 // and off for one directory is relying on that, and so is one that writes the pair and
4779 // then takes half of it back.
4780 let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
4781 assert_eq!(opts.wrapping, Wrapping::NONE);
4782
4783 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
4784 assert_eq!(opts.wrapping, Wrapping::NONE);
4785
4786 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
4787 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
4788 }
4789
4790 /// And the other answer to the signed question cannot be held at the same time as the first.
4791 ///
4792 /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
4793 /// resolves it by letting the last one win rather than by reporting anything. That was measured
4794 /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
4795 /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
4796 #[test]
4797 fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
4798 let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
4799 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
4800
4801 let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
4802 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
4803
4804 let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
4805 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
4806
4807 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
4808 assert_eq!(opts.wrapping, Wrapping::ALL);
4809
4810 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
4811 assert_eq!(opts.wrapping, Wrapping::NONE);
4812
4813 // And the flag that says what may be assumed says nothing about what happens, so it leaves
4814 // this alone where it takes the wrapping away. gcc does the same.
4815 let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
4816 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
4817 }
4818
4819 /// What a plain `char` is, which is four spellings of two answers and nothing by default.
4820 ///
4821 /// Nothing is the target's own answer and has to stay distinct from both of the others, since
4822 /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
4823 /// The negative spellings are the other flag rather than a way of asking for the default, which
4824 /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
4825 /// `-fno-unsigned-char` does not.
4826 #[test]
4827 fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
4828 let (opts, _) = compile(&["-c", "a.c"]);
4829 assert_eq!(opts.char_signed, None);
4830
4831 for flag in ["-fsigned-char", "-fno-unsigned-char"] {
4832 let (opts, _) = compile(&["-c", flag, "a.c"]);
4833 assert_eq!(opts.char_signed, Some(true), "{flag}");
4834 }
4835
4836 for flag in ["-funsigned-char", "-fno-signed-char"] {
4837 let (opts, _) = compile(&["-c", flag, "a.c"]);
4838 assert_eq!(opts.char_signed, Some(false), "{flag}");
4839 }
4840
4841 // And the last one wins, which is what a build that sets one globally and the other for a
4842 // directory relies on.
4843 let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
4844 assert_eq!(opts.char_signed, Some(true));
4845
4846 // And what is asked for reaches the target, because that is what every other part of the
4847 // compiler asks. The triple is one whose own answer is the opposite, so a session that
4848 // ignored the flag would still read as signed here.
4849 let (opts, _) =
4850 compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
4851 assert!(Session::new(*opts).target.char_is_signed);
4852 let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
4853 assert!(!Session::new(*opts).target.char_is_signed);
4854 }
4855
4856 /// And the size of an enumeration, which is one question with two spellings.
4857 #[test]
4858 fn the_smallest_enumeration_is_asked_for_and_taken_back() {
4859 let (opts, _) = compile(&["-c", "a.c"]);
4860 assert!(!opts.short_enums);
4861
4862 let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
4863 assert!(opts.short_enums);
4864
4865 let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
4866 assert!(!opts.short_enums);
4867
4868 let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
4869 assert!(opts.short_enums);
4870 }
4871
4872 /// And Microsoft's reading of an anonymous member, which the target answers where the command
4873 /// line said nothing. gcc's mingw build has it on and its Linux build has it off, so a header
4874 /// that closes a nameless union with a macro that expands to nothing is read the way the
4875 /// compiler that platform ships would read it.
4876 #[test]
4877 fn the_microsoft_reading_of_a_member_follows_the_target_until_it_is_asked_for() {
4878 // Named rather than left to the host, since the answer this asks for is the one a target
4879 // that is not Windows gives and on a Windows machine the host is not one of those.
4880 let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
4881 assert!(!Session::new(*opts).ms_extensions());
4882
4883 let (opts, _) = compile(&["-c", "--target=x86_64-pc-windows-gnu", "a.c"]);
4884 assert!(Session::new(*opts).ms_extensions());
4885
4886 let (opts, _) = compile(&["-c", "-fms-extensions", "a.c"]);
4887 assert!(Session::new(*opts).ms_extensions());
4888
4889 let (opts, _) =
4890 compile(&["-c", "--target=x86_64-pc-windows-gnu", "-fno-ms-extensions", "a.c"]);
4891 assert!(!Session::new(*opts).ms_extensions());
4892 }
4893
4894 /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
4895 ///
4896 /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
4897 /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
4898 /// family would report it as an unknown pass. Neither is the news the build wants.
4899 #[test]
4900 fn a_control_flow_protection_nothing_means_is_refused() {
4901 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
4902 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
4903 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
4904 }
4905
4906 #[test]
4907 fn the_link_flags_are_collected_apart_from_the_compilation() {
4908 let (link, _) = linking(&[
4909 "-static",
4910 "-nostartfiles",
4911 "-rdynamic",
4912 "-s",
4913 "-fuse-ld=mold",
4914 "-L/opt/lib",
4915 "-B",
4916 "/opt/tools",
4917 "a.c",
4918 ]);
4919 assert!(link.is_static);
4920 assert!(link.no_startfiles);
4921 assert!(link.export_dynamic);
4922 assert!(link.strip);
4923 assert_eq!(link.use_ld.as_deref(), Some("mold"));
4924 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
4925 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
4926 }
4927
4928 #[test]
4929 fn a_comma_in_dash_wl_separates_two_arguments() {
4930 // The target is written down because the name of the object is derived from it, and `a.o`
4931 // on a Linux host is `a.obj` on a Windows one. What is under test is the splitting of the
4932 // argument, which has nothing to do with either.
4933 let (_, plan) = linking(&[LINUX, "-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
4934 let link = plan.link.expect("expected a link step");
4935 assert_eq!(
4936 link.inputs,
4937 vec![
4938 link::Item::Linker("-rpath".into()),
4939 link::Item::Linker("/opt/lib".into()),
4940 link::Item::Linker("--as-needed".into()),
4941 link::Item::File("a.o".into()),
4942 ]
4943 );
4944 }
4945
4946 #[test]
4947 fn a_word_for_the_linker_keeps_its_place_among_the_files_too() {
4948 // What libtool writes around a set of convenience archives, and what #1279 was. Both words
4949 // are about the files between them, so the pair collected out of the line and appended to
4950 // the end is two options that bracket nothing and an archive that went in empty.
4951 let (_, plan) = linking(&[
4952 "--target=x86_64-unknown-linux-gnu",
4953 "a.c",
4954 "-Wl,--whole-archive",
4955 "libaesni.a",
4956 "-Wl,--no-whole-archive",
4957 "-lm",
4958 ]);
4959 let link = plan.link.expect("expected a link step");
4960 assert_eq!(
4961 link.inputs,
4962 vec![
4963 link::Item::File("a.o".into()),
4964 link::Item::Linker("--whole-archive".into()),
4965 link::Item::File("libaesni.a".into()),
4966 link::Item::Linker("--no-whole-archive".into()),
4967 link::Item::Library("m".into()),
4968 ]
4969 );
4970 // And it is not a job, because there is nothing to compile in a word for the linker.
4971 assert_eq!(plan.jobs.len(), 2);
4972 }
4973
4974 #[test]
4975 fn a_word_for_the_linker_on_a_dash_c_line_is_dropped_without_a_word() {
4976 // GCC says nothing about one either. `-Wl,` on a compile line is what a build system
4977 // writes when one variable holds the flags for both, and a note here would be a note on
4978 // every compile of every autotools project.
4979 let (_, plan) = linking(&["-c", "-Wl,--as-needed", "a.c"]);
4980 assert!(plan.link.is_none());
4981 assert!(plan.notes.is_empty(), "{:?}", plan.notes);
4982 assert_eq!(plan.jobs.len(), 1);
4983 }
4984
4985 #[test]
4986 fn a_library_keeps_its_place_between_the_objects() {
4987 // Link order is semantic: `-lm` written between two files resolves for the one before
4988 // it and not for the one after, so a library cannot be collected into a list of its own.
4989 // The target is named because the suffix of an object is the target's and this asserts
4990 // on the names: the same command line on a Windows host plans two `.obj` files.
4991 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
4992 let link = plan.link.expect("expected a link step");
4993 assert_eq!(
4994 link.inputs,
4995 vec![
4996 link::Item::File("a.o".into()),
4997 link::Item::Library("m".into()),
4998 link::Item::File("b.o".into()),
4999 ]
5000 );
5001 // And it is not a job, because there is nothing to compile in a library.
5002 assert_eq!(plan.jobs.len(), 2);
5003 }
5004
5005 #[test]
5006 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
5007 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
5008 assert!(plan.link.is_none());
5009 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
5010 }
5011
5012 #[test]
5013 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
5014 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
5015 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
5016 }
5017
5018 fn printed(s: &[&str]) -> String {
5019 match parse_args(&args(s)).expect("expected an answer") {
5020 Action::Print(line) => line,
5021 other => panic!("expected an answer, got {other:?}"),
5022 }
5023 }
5024
5025 fn refused(s: &[&str]) -> String {
5026 parse_args(&args(s)).expect_err("expected a refusal").message
5027 }
5028
5029 #[test]
5030 fn a_warning_flag_this_compiler_has_not_heard_of_is_taken_rather_than_refused() {
5031 // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
5032 // out whether a warning flag exists by passing it and looking at the exit status, so a
5033 // compiler that refuses one it does not know fails a script written for a newer GCC.
5034 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
5035 assert!(!opts.warnings_are_errors);
5036 assert!(opts.warnings);
5037 // The two spellings that do mean something are still read.
5038 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
5039 assert!(opts.warnings_are_errors);
5040 let (opts, _) = compile(&["-w", "-c", "a.c"]);
5041 assert!(!opts.warnings);
5042 // Off without being asked, the way gcc has it off, and both spellings are read.
5043 let (opts, _) = compile(&["-c", "a.c"]);
5044 assert!(!opts.system_header_warnings);
5045 let (opts, _) = compile(&["-Wsystem-headers", "-c", "a.c"]);
5046 assert!(opts.system_header_warnings);
5047 let (opts, _) = compile(&["-Wsystem-headers", "-Wno-system-headers", "-c", "a.c"]);
5048 assert!(!opts.system_header_warnings);
5049 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
5050 assert!(opts.pedantic && opts.warnings_are_errors);
5051 }
5052
5053 #[test]
5054 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
5055 // Every one of these says something about the output, so the wrong answer is silence.
5056 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
5057 assert!(refused(&["-Wp,-DX", "-c", "a.c"]).contains("separate assembler"));
5058 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
5059 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
5060 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
5061 assert!(refused(&["-Ofast", "-c", "a.c"]).contains("fast math"));
5062 // The word size the target does not have, which is a target this compiler was not asked
5063 // for rather than a flag it does not know.
5064 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
5065 assert!(no32.contains("32 bit target"), "{no32}");
5066 }
5067
5068 /// `-gz` and the two spellings of the split, which are the two questions about the shape of
5069 /// the debug output rather than about how much of it there is.
5070 ///
5071 /// Both answers here are about what happens when there is debug information to shape, and
5072 /// there is none yet, so what is being asserted is that the flags are read and remembered
5073 /// rather than that anything changed in the output. That is the whole of what taking them
5074 /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
5075 /// it comes to find out what the command line said.
5076 #[test]
5077 fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
5078 let (opts, _) = compile(&["-c", "a.c"]);
5079 assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
5080
5081 // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
5082 // which describes the flag without ever saying which algorithm it picks.
5083 assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
5084 for (spelling, want) in [
5085 ("none", Compress::None),
5086 ("zlib", Compress::Zlib),
5087 ("zlib-gnu", Compress::ZlibGnu),
5088 ("zstd", Compress::Zstd),
5089 ] {
5090 let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
5091 assert_eq!(opts.compress, want, "{spelling}");
5092 }
5093
5094 // A value nothing here has heard of is refused rather than rounded to the nearest one,
5095 // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
5096 // reader may not understand and would have no way of finding out.
5097 for bad in ["-gz=gzip", "-gz="] {
5098 let failed = refused(&[bad, "-c", "a.c"]);
5099 assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
5100 }
5101
5102 // The split is refused in the direction that would have written a file and taken in the
5103 // direction that describes what happens. A build system that names the `.dwo` as an
5104 // output has to hear about it now rather than at the point the file is missing.
5105 let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
5106 assert!(opts.debug_info, "the negative spelling says nothing about how much");
5107 let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
5108 assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
5109 }
5110
5111 /// The `-flto` family, which is the whole of an optimization this compiler does not do.
5112 ///
5113 /// Taken rather than refused because ignoring it gives a correct program that is slower than
5114 /// it could have been, which is section 4.1's hint about speed. The values are still held to
5115 /// gcc's, so a command line written for clang is told rather than quietly taken.
5116 #[test]
5117 fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
5118 let (opts, _) = compile(&["-c", "a.c"]);
5119 assert!(!opts.lto.requested, "nothing asks unless the command line does");
5120
5121 let (opts, _) = compile(&["-flto", "-c", "a.c"]);
5122 assert!(opts.lto.requested);
5123 assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
5124
5125 // The last of the two directions wins, the same as every other pair of `-f` spellings.
5126 assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
5127 assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
5128
5129 // A count is a count, and asking for one implies asking for the optimization.
5130 for (spelling, want) in [
5131 ("auto", LtoJobs::Auto),
5132 ("jobserver", LtoJobs::Jobserver),
5133 ("1", LtoJobs::One),
5134 ("8", LtoJobs::Count(8)),
5135 ] {
5136 let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
5137 assert_eq!(opts.lto.jobs, want, "{spelling}");
5138 assert!(opts.lto.requested, "{spelling} asks for it too");
5139 }
5140
5141 // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
5142 // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
5143 // different compiler and gets told so here rather than getting a serial link.
5144 for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
5145 let failed = refused(&[bad, "-c", "a.c"]);
5146 assert!(failed.contains("link time jobs"), "{bad}: {failed}");
5147 }
5148
5149 // How the program is cut up before the work is spread over it.
5150 assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
5151 for (spelling, want) in [
5152 ("balanced", Partition::Balanced),
5153 ("1to1", Partition::OneToOne),
5154 ("one", Partition::One),
5155 ("max", Partition::Max),
5156 ("none", Partition::None),
5157 ] {
5158 let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
5159 assert_eq!(opts.lto.partition, want, "{spelling}");
5160 }
5161 assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
5162
5163 // And how hard the bytecode is compressed on its way into the object, which is zstd's
5164 // range of levels and is the range gcc checks an argument against.
5165 assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
5166 assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
5167 let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
5168 assert_eq!(opts.lto.compression, Some(19));
5169 for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
5170 let failed = refused(&[bad, "-c", "a.c"]);
5171 assert!(failed.contains("compression level"), "{bad}: {failed}");
5172 }
5173
5174 // The two pairs that describe an arrangement rather than ask for one. Every object here
5175 // holds its machine code, so the fat spelling is what already happens and the other is a
5176 // smaller file rather than a different program, and the plugin pair is about a tool the
5177 // design in `spec/09-optimizer.md` never loads.
5178 for taken in [
5179 "-ffat-lto-objects",
5180 "-fno-fat-lto-objects",
5181 "-fuse-linker-plugin",
5182 "-fno-use-linker-plugin",
5183 ] {
5184 let (opts, _) = compile(&[taken, "-c", "a.c"]);
5185 assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
5186 }
5187 }
5188
5189 /// The profile family, which is the only one here that splits down the middle.
5190 ///
5191 /// Reading a profile is taken and writing one is refused, and the line between them is the one
5192 /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
5193 /// slower than it could have been, and ignoring a request to write them means a file the build
5194 /// declared as an output never appears.
5195 #[test]
5196 fn reading_a_profile_is_taken_and_writing_one_is_refused() {
5197 let (opts, _) = compile(&["-c", "a.c"]);
5198 assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
5199 assert_eq!(opts.profile_data.path, None);
5200
5201 let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
5202 assert!(opts.profile_data.requested);
5203 assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
5204
5205 let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
5206 assert!(opts.profile_data.requested, "naming a path asks for it too");
5207 assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
5208
5209 // The last of the two directions wins, the same as every other pair of `-f` spellings.
5210 assert!(
5211 !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
5212 );
5213 assert!(
5214 compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
5215 );
5216
5217 // The rest of the reading half, which is where the files are and three answers about what
5218 // to make of what is in them.
5219 let (opts, _) = compile(&[
5220 "-fprofile-dir=/build/profiles",
5221 "-fprofile-abs-path",
5222 "-fprofile-correction",
5223 "-fprofile-partial-training",
5224 "-c",
5225 "a.c",
5226 ]);
5227 assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
5228 assert!(opts.profile_data.absolute);
5229 assert!(opts.profile_data.correction);
5230 assert!(opts.profile_data.partial_training);
5231
5232 // Writing one, which is refused by name. The first four instrument the program and the
5233 // last writes a file beside the object, and a build that got neither and no message would
5234 // go on to optimize against counts that were never gathered.
5235 for writing in [
5236 "-fprofile-generate",
5237 "-fprofile-generate=/build/profiles",
5238 "-fprofile-arcs",
5239 "--coverage",
5240 "-fcondition-coverage",
5241 "-fpath-coverage",
5242 ] {
5243 let failed = refused(&[writing, "-c", "a.c"]);
5244 assert!(failed.contains("instrument"), "{writing}: {failed}");
5245 }
5246 assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
5247
5248 // The negative spellings of the refused half are what already happens, so they are taken.
5249 for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
5250 let (opts, _) = compile(&[taken, "-c", "a.c"]);
5251 assert!(!opts.profile_data.requested, "{taken} asks for nothing");
5252 }
5253
5254 // And the flags that describe the instrumentation that is refused above, which are checked
5255 // and dropped. Checked because a typo is worth finding here rather than on the day the
5256 // instrumentation lands.
5257 for taken in [
5258 "-fprofile-update=single",
5259 "-fprofile-update=atomic",
5260 "-fprofile-update=prefer-atomic",
5261 "-fprofile-reproducible=serial",
5262 "-fprofile-reproducible=parallel-runs",
5263 "-fprofile-reproducible=multithreaded",
5264 "-fprofile-values",
5265 "-fno-profile-values",
5266 "-fprofile-info-section",
5267 "-fprofile-filter-files=a.c",
5268 "-fprofile-exclude-files=b.c",
5269 "-fprofile-note=a.gcno",
5270 ] {
5271 let (opts, _) = compile(&[taken, "-c", "a.c"]);
5272 assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
5273 }
5274 assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
5275 assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
5276 }
5277
5278 /// The sanitizers, which are refused by name and are the one family refused for a reason that
5279 /// is not about the bytes.
5280 ///
5281 /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
5282 /// for one and was quietly given a program with no checks in it gets a test suite that passes
5283 /// for the wrong reason rather than a slower program.
5284 #[test]
5285 fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
5286 for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
5287 let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
5288 assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
5289 assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
5290 }
5291
5292 // A list is every name in it, and the first one still standing is the one named.
5293 let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
5294 assert!(failed.contains("address"), "{failed}");
5295
5296 // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
5297 // with a typo in it has a different problem from somebody who wrote a real one.
5298 for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
5299 let failed = refused(&[bad, "-c", "a.c"]);
5300 assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
5301 }
5302
5303 // gcc takes `all` only in the negative, and so does this.
5304 assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
5305
5306 // Asking and then taking it back is asking for nothing, which is why the answer waits for
5307 // the end of the line. A build whose shared flags turn a check on and whose rule for one
5308 // file turns it off again compiles that file here.
5309 for pair in [
5310 ["-fsanitize=address", "-fno-sanitize=address"],
5311 ["-fsanitize=address,undefined", "-fno-sanitize=all"],
5312 ["-fsanitize=undefined", "-fno-sanitize=undefined"],
5313 ] {
5314 let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
5315 assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
5316 }
5317 // And the other order still asks, because the last word is the one that counts.
5318 assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
5319
5320 // What a check does when it fires is an answer about checks that are refused, so there is
5321 // nothing left for it to change and it is taken.
5322 for taken in [
5323 "-fsanitize-recover=undefined",
5324 "-fno-sanitize-recover=all",
5325 "-fsanitize-trap=undefined",
5326 "-fno-sanitize-trap=all",
5327 "-fsanitize-undefined-trap-on-error",
5328 "-fsanitize-address-use-after-scope",
5329 "-fno-sanitize-address-use-after-scope",
5330 "-fsanitize-sections=.data",
5331 ] {
5332 let (opts, _) = compile(&[taken, "-c", "a.c"]);
5333 assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
5334 }
5335 assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
5336
5337 // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
5338 // feedback runs blind and never says so.
5339 let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
5340 assert!(failed.contains("feedback"), "{failed}");
5341 let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
5342 assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
5343 }
5344
5345 #[test]
5346 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
5347 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
5348 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
5349 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
5350 }
5351
5352 #[test]
5353 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
5354 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
5355 let (opts, _) =
5356 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
5357 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
5358 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
5359 assert!(wrong.contains("sysv convention"), "{wrong}");
5360 }
5361
5362 #[test]
5363 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
5364 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
5365 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
5366 // After the input, because a static link takes what it needs from a library when it
5367 // reaches it and not afterwards.
5368 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
5369 assert_eq!(names, vec!["a.c"]);
5370 }
5371
5372 #[test]
5373 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
5374 let target = "--target=x86_64-unknown-linux-gnu";
5375 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
5376 assert_eq!(printed(&[target, "-dumpversion"]), VERSION);
5377 assert_eq!(printed(&[target, "-dumpfullversion"]), VERSION);
5378 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
5379 // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
5380 // answer safe to paste into a link line whether or not the file is there.
5381 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
5382 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
5383 let dirs = printed(&[target, "-print-search-dirs"]);
5384 assert!(dirs.starts_with("install: "), "{dirs}");
5385 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
5386 }
5387
5388 #[test]
5389 fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
5390 // A tree the user named is the answer whatever the target is, because it is the answer to
5391 // every other question too.
5392 assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
5393
5394 // A target that is no machine this suite runs on is read under the cache, and the answer is
5395 // the root rather than one of the directories under it, since what asks is looking for a
5396 // file of its own.
5397 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
5398 assert_eq!(
5399 printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
5400 root.display().to_string()
5401 );
5402
5403 // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
5404 // was configured without one rather than a `/` that would be a claim about the filesystem.
5405 let host = Triple::host().expect("a host this compiler knows");
5406 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot"]), "");
5407 }
5408
5409 #[test]
5410 fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
5411 // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
5412 // is the record that already has them, so the flag prints that rather than a second format.
5413 let manifest = "rucc sysroot manifest 3\n\
5414 target\tx86_64-linux-musl\n\
5415 kernel\t6.12\n\
5416 include/generic/stdio.h\tmusl-1.2.5\t\
5417 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
5418 0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
5419 bundled\n\
5420 lib/libc.so\tmusl-1.2.5\t\
5421 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
5422 1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
5423 generated\n";
5424 let tree = TempTree::new("provenance", &[("manifest", manifest)]);
5425 let sysroot = format!("--sysroot={}", tree.0.display());
5426 // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
5427 // the flag parses the record and renders it again rather than picking fields out of it. That
5428 // is the reason it prints a manifest and not a format of its own.
5429 //
5430 // The answer is the file without its last newline, because whatever prints it adds one. The
5431 // file is what somebody diffs the output against, so the two have to be the same bytes.
5432 assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
5433
5434 // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
5435 // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
5436 // tell it from a manifest with no inputs because that one still has its two header lines.
5437 let bare = TempTree::new("provenance-bare", &[]);
5438 assert_eq!(
5439 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
5440 ""
5441 );
5442
5443 // And a compile for this machine has no sysroot at all, which is the same empty answer
5444 // `-print-sysroot` gives for it.
5445 let host = Triple::host().expect("a host this compiler knows");
5446 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
5447
5448 // And the other spelling, which section 13.5 is the document that writes.
5449 assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
5450
5451 // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
5452 // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
5453 // the bytes it is over are the bytes of the file. The number here is that hash of the
5454 // fixture above, computed by `sha256sum` rather than by this compiler.
5455 assert_eq!(
5456 printed(&[&sysroot, "-print-sysroot-digest"]),
5457 "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
5458 );
5459 assert_eq!(
5460 printed(&[&sysroot, "--print-sysroot-digest"]),
5461 printed(&[&sysroot, "-print-sysroot-digest"])
5462 );
5463
5464 // And the two empty answers are empty here too, because a digest of nothing would read as a
5465 // claim about a sysroot rather than as the absence of one.
5466 assert_eq!(
5467 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
5468 ""
5469 );
5470 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
5471 }
5472
5473 #[test]
5474 fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
5475 // Passing a file we could not parse to whoever asked would make their parser the one that
5476 // finds the problem, and the three uses section 13.5 gives for this are all somebody else
5477 // parsing it.
5478 let tree = TempTree::new(
5479 "provenance-bad",
5480 &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
5481 );
5482 let message =
5483 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
5484 assert!(message.contains("manifest"), "{message}");
5485 assert!(message.contains("1 fields where an input has six"), "{message}");
5486
5487 // The digest is refused for the same file and for a stronger reason: a hash of bytes this
5488 // build cannot read would be a number that names a record nobody can act on.
5489 let digest =
5490 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
5491 assert_eq!(digest, message);
5492 }
5493
5494 #[test]
5495 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
5496 let (opts, _) = compile(&["-M", "a.c"]);
5497 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
5498 assert!(opts.deps.system_headers, "plain -M lists them");
5499 assert_eq!(opts.emit, EmitKind::Preprocessed);
5500
5501 // Even where a later flag asked for something else, because the family is a mode and
5502 // the mode is what the run is for.
5503 let (opts, _) = compile(&["-M", "-c", "a.c"]);
5504 assert_eq!(opts.emit, EmitKind::Preprocessed);
5505
5506 let (opts, _) = compile(&["-MM", "a.c"]);
5507 assert!(!opts.deps.system_headers);
5508 }
5509
5510 #[test]
5511 fn the_two_that_end_in_d_leave_the_compilation_alone() {
5512 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
5513 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
5514 assert!(opts.deps.system_headers);
5515 assert_eq!(opts.emit, EmitKind::Object);
5516
5517 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
5518 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
5519 assert!(!opts.deps.system_headers);
5520 }
5521
5522 #[test]
5523 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
5524 // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
5525 // the answer, because the other one never asked the question.
5526 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
5527 assert!(!opts.deps.system_headers);
5528 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
5529 assert!(!opts.deps.system_headers);
5530 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
5531 assert!(!opts.deps.system_headers);
5532 }
5533
5534 #[test]
5535 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
5536 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
5537 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
5538 }
5539
5540 #[test]
5541 fn the_rest_of_the_family_is_a_file_and_a_switch() {
5542 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
5543 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
5544 assert!(opts.deps.phony);
5545
5546 for flag in ["-MF", "-MT", "-MQ"] {
5547 let e = parse_args(&args(&[flag])).unwrap_err();
5548 assert!(e.message.contains("requires an argument"), "{}", e.message);
5549 }
5550 }
5551
5552 /// A directory of sources for one test, removed when the test is done with it.
5553 struct TempTree(PathBuf);
5554
5555 impl Drop for TempTree {
5556 fn drop(&mut self) {
5557 let _ = std::fs::remove_dir_all(&self.0);
5558 }
5559 }
5560
5561 impl TempTree {
5562 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
5563 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
5564 let _ = std::fs::remove_dir_all(&dir);
5565 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
5566 for (path, text) in files {
5567 let at = dir.join(path);
5568 if let Some(parent) = at.parent() {
5569 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
5570 }
5571 std::fs::write(&at, text).expect("writing a temporary file should work");
5572 }
5573 TempTree(dir)
5574 }
5575
5576 fn path(&self, name: &str) -> String {
5577 self.0.join(name).to_string_lossy().into_owned()
5578 }
5579 }
5580
5581 #[test]
5582 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
5583 // End to end, because the list comes from the preprocessor and the format comes from
5584 // somewhere else, and a test of either half on its own would pass with the two of them
5585 // wired up backwards.
5586 let tree = TempTree::new(
5587 "found",
5588 &[
5589 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
5590 ("one.h", "#define X 0\n"),
5591 ("two.h", "#include \"one.h\"\n"),
5592 ],
5593 );
5594 let out = tree.path("dep.d");
5595 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
5596 assert_eq!(code, 0);
5597
5598 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
5599 let names: Vec<&str> = text.split_whitespace().collect();
5600 // The target, the source, and each header once however many times it was reached.
5601 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
5602 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
5603 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
5604 // And the `-o` went to the file the rule replaced, which is left empty rather than
5605 // absent because a makefile that named it as a target will look for it.
5606 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
5607 }
5608
5609 #[test]
5610 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
5611 // The multiple-include optimization means the second reach never opens the file. It is
5612 // still a file this translation unit was built from, so it is still in the rule.
5613 let tree = TempTree::new(
5614 "guarded",
5615 &[
5616 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
5617 ("g.h", "#ifndef G\n#define G\n#endif\n"),
5618 ],
5619 );
5620 let out = tree.path("dep.d");
5621 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
5622 assert_eq!(code, 0);
5623 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
5624 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
5625 }
5626
5627 #[test]
5628 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
5629 // Measured against GCC rather than read: the two flags the other way round produce the
5630 // same output byte for byte, so the command line order between the two families does not
5631 // decide anything and the order within one does. The `-include` file here can only see
5632 // the definition if the `-imacros` file that was written after it ran first.
5633 let tree = TempTree::new(
5634 "preinclude",
5635 &[
5636 ("a.c", "int main(void) { return 0; }\n"),
5637 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
5638 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
5639 ],
5640 );
5641 let out = tree.path("a.i");
5642 let code = run(&args(&[
5643 "-E",
5644 "-include",
5645 &tree.path("i.h"),
5646 "-imacros",
5647 &tree.path("m.h"),
5648 "-o",
5649 &out,
5650 &tree.path("a.c"),
5651 ]));
5652 assert_eq!(code, 0);
5653 let text = std::fs::read_to_string(&out).expect("the output should have been written");
5654 assert!(text.contains("saw_it"), "{text}");
5655 // And the text of the `-imacros` file is thrown away, which is the whole difference
5656 // between the two flags.
5657 assert!(!text.contains("macros_text"), "{text}");
5658 }
5659
5660 #[test]
5661 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
5662 let tree = TempTree::new(
5663 "preinclude-deps",
5664 &[
5665 ("a.c", "int main(void) { return 0; }\n"),
5666 ("i.h", "int from_include;\n"),
5667 ("m.h", "#define M 1\n"),
5668 ],
5669 );
5670 let out = tree.path("dep.d");
5671 let code = run(&args(&[
5672 "-MM",
5673 "-MF",
5674 &out,
5675 "-include",
5676 &tree.path("i.h"),
5677 "-imacros",
5678 &tree.path("m.h"),
5679 "-o",
5680 &tree.path("a.i"),
5681 &tree.path("a.c"),
5682 ]));
5683 assert_eq!(code, 0);
5684 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
5685 assert!(text.contains("i.h"), "{text}");
5686 assert!(text.contains("m.h"), "{text}");
5687 }
5688
5689 #[test]
5690 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
5691 // Including the directory of the source file, which is not on the path for these: the
5692 // command line was not written there, so a name in it is relative to where the compiler
5693 // was run rather than to where the source sits.
5694 let tree = TempTree::new(
5695 "preinclude-missing",
5696 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
5697 );
5698 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
5699 assert_eq!(code, 1);
5700 }
5701
5702 #[test]
5703 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
5704 // The object a link goes through is in a temporary directory and is gone before `make`
5705 // reads any of this, so the rule that named it would be a rule for a file that is never
5706 // there. The target and the file are both the `-o`, which is the executable.
5707 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
5708 assert_eq!(plan.output.as_deref(), Some("prog"));
5709 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
5710 assert_eq!(
5711 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
5712 Some("prog.d")
5713 );
5714 }
5715
5716 #[test]
5717 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
5718 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
5719 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
5720 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
5721 assert_eq!(plan.output, None);
5722 }
5723
5724 #[test]
5725 fn usage_fits_on_a_screen() {
5726 // Not a style preference. A help text that scrolls is one nobody reads, and this is
5727 // the cheapest way to keep it honest as flags accumulate. The number goes up only when
5728 // a family of flags arrives that has nowhere to share a line, which the two pass gates
5729 // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
5730 // the lines that family took. The four it went up by last are the flags a build system
5731 // passes without being asked to: how much to say, what machine to generate for, threads,
5732 // and the questions `configure` asks before it compiles anything. The one it went up by
5733 // last is the second line of `--emit`, whose kinds are a family that has now outgrown
5734 // one line and has nowhere else to go. The two it went up by last are the dependency
5735 // family, which is eight flags that share nothing with anything above them. The one it
5736 // went up by last is the four spellings of position independent code, which every
5737 // configure script writes and which could only have shared the link line, and that line
5738 // is already four characters short of the limit. The two it went up by last are the rest
5739 // of the include family, which is six more flags that change where a header is looked for
5740 // and two that name a header outright. The one it went up by last is the pair that keeps
5741 // the intermediate files and times the steps, which belong next to the two flags above
5742 // them that are also about watching a compilation rather than changing one. The two it
5743 // went up by last are the section flags and the visibility flag, which are what a build
5744 // that cares about the size of what it ships and about which names it exports writes, and
5745 // the second of them was already taken and only missing from here. The one it went up by
5746 // last is the stack protector, which is four spellings of one question and which every
5747 // distribution puts on every command line it issues, so a build that reads this list
5748 // looking for it and does not find it has to go and read the specification instead. The one
5749 // it went up by last is the profiler, which is two spellings of the request and two of
5750 // where the call goes, and which is about watching a program run rather than about what is
5751 // generated, so it shares its subject with nothing above it. The one it went up by last is
5752 // the room a function opens with for something to be written over it later, which takes an
5753 // argument of its own shape and is what a kernel build asks for, so it fits beside the
5754 // profiler and nothing else. The one it went up by last is what overflows rather than being
5755 // undefined, which is three spellings of two questions and which a kernel build and a great
5756 // deal of code written before the standard settled both pass. The one it went up by last is
5757 // the other answer to the first of those questions, which could not share the line because
5758 // what it asks for is the opposite of what the flags on that line ask for. The one it went
5759 // up by last is the split of the line that lists what this compiler does anyway into that
5760 // and what it assumes anyway, which are two different claims that were sharing a line until
5761 // the second of them got a second flag and the line stopped fitting. The one it went up by
5762 // last is the three flags that change the ABI rather than the code, which have to be given
5763 // to every file in a program or none of them and which therefore belong somewhere a person
5764 // reading this list will see them. The one it went up by last is the floating point group,
5765 // which is two lines rather than one because the first of them is a choice this compiler
5766 // records and the rest are claims about what it does anyway, and putting a real setting on
5767 // the same line as three flags that change nothing would be misleading about both. The one
5768 // it went up by last is the flag that says a write has to stay inside the member it names,
5769 // which is a setting rather than a claim and so cannot share the line above it, that being
5770 // the one that picks a tier. The two it went up by last are the prefix mapping family,
5771 // which is four flags whose whole job is to keep a build's output the same from two
5772 // different directories, and which a person chasing a reproducible build comes here
5773 // looking for by name. The one it went up by last is how the debug sections are compressed
5774 // and whether they go in a file of their own, which are two questions about the shape of
5775 // the debug output, where the line above them is about how much of it there is. The one it
5776 // went up by last is the `restrict` contract, which is a setting for the same reason the
5777 // flag that keeps a write inside its member is and which is the check a person who has been
5778 // bitten by a vectorizer comes here looking for. The one it went up by last is link time
5779 // optimization, which is a whole optimization rather than a flag and which says so on its
5780 // own line, because a build that passes it and reads this looking for what it got is
5781 // asking a question no other line here answers. The one it went up by last is the sysroot,
5782 // which is the question somebody asks when a cross build read a file nobody expected, and
5783 // which has no room on the line above it because the answers there are a path each and this
5784 // one is the root all of them are under. The one it went up by last is what is inside that
5785 // root and where each of it came from, which is a question about a whole tree rather than
5786 // about a path and which is long enough on its own that it could not have shared a line with
5787 // anything. The one it went up by last is the profile family, which splits down the middle
5788 // where no other family here does, so the line has to name the half that is taken and the
5789 // half that is refused or it would be read as taking both. The one it went up by last is
5790 // the sanitizers, which are what somebody reaching for a checked build writes first and
5791 // which belong beside the tier that is the nearest thing here to what they asked for. The
5792 // one it went up by last is the digest of that record, which is the same tree as one number
5793 // and could not share the line above it because that line prints a few hundred lines and
5794 // this one prints sixty four characters, and a reader who wants the short answer is looking
5795 // for it by name rather than reading the long one. The one it went up by last is the
5796 // sysroot fetch, which is the only command here that gets something from somewhere else and
5797 // is therefore the one a person wants to have read before they run it rather than after.
5798 // And the flag beside it that forbids every download, which earns its line by being what a
5799 // build in a sealed environment passes and by meaning something even though an ordinary
5800 // compile downloads nothing either way.
5801 assert!(USAGE.lines().count() < 72, "usage text has grown past one screen");
5802 }
5803}