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