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.18")]
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;
46pub mod trace;
47mod warnings;
48
49use std::fmt::Write as _;
50use std::io::Write as _;
51use std::path::PathBuf;
52
53use rucc_codegen::coverage::{self, Fired};
54use rucc_codegen::lowering::Lowerings;
55use rucc_codegen::pressure::Pressure;
56use rucc_pp::Dependency;
57use rucc_session::{
58 Compress, Control, Dumps, EmitKind, Hook, Math, Options, Pic, PrefixMap, Preinclude, Protector,
59 SaveTemps, Session, Std, Wrapping, runtime,
60};
61use rucc_sysroot::{Manifest, Sysroot};
62use rucc_target::{ObjectFormat, Triple};
63use rucc_tuple::TargetTuple;
64
65use crate::link::LinkOptions;
66
67pub use crate::assemble::assemble;
68pub use crate::compile::{Artifact, Compiled, Temps, compile, compile_ir};
69pub use crate::phase::{ArchiveJob, Input, InputKind, Job, LinkJob, Output, Phase, Plan, Role};
70pub use crate::preprocess::{OsFileSystem, Preprocessed, preprocess};
71pub use crate::schedule::Jobs;
72
73/// The compiler's version, taken from the workspace manifest.
74pub const VERSION: &str = env!("CARGO_PKG_VERSION");
75
76/// What the command line asked for.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum Action {
79 /// Print usage and exit successfully.
80 Help,
81 /// Print the version and exit successfully.
82 Version,
83 /// Print one line and exit successfully, which is what the `-dump` and `-print` family do.
84 ///
85 /// A build system asks these before it compiles anything, and what it does with the answer
86 /// is paste it into a path or into another command line, so each one is a single line with
87 /// no decoration around it.
88 Print(String),
89 /// Print the resolved configuration and exit successfully.
90 PrintConfig(Box<Options>),
91 /// Print the passes the level will run and exit successfully.
92 PrintPipeline(Box<Options>),
93 /// Print the phase plan and the link line and exit successfully, which is `-###`.
94 PrintPlan {
95 /// The resolved options, which is what says what the link line is for.
96 opts: Box<Options>,
97 /// What to do to each input, and in what order.
98 plan: Box<Plan>,
99 /// What the command line said about linking.
100 link: Box<LinkOptions>,
101 },
102 /// `--fetch <tuple>`, which gets the sysroot this release pins for a target and installs it.
103 ///
104 /// The only action in this compiler that may run another program to move bytes onto the
105 /// machine, which is `spec/cross-compile/13-distribution.md` section 13.8's rule rather than a
106 /// property of how this happens to be written: a compilation has no branch that reaches it.
107 Fetch {
108 /// The artifact, from the table in [`rucc_sysroot::artifact`]. Resolved here rather than where the
109 /// work happens, so that a target nothing is pinned for is a refusal from the parser like
110 /// every other thing a command line can ask for and not have.
111 what: &'static rucc_sysroot::Pinned,
112 /// The target, which names the directory under the cache the tree is installed at and is
113 /// checked against the record inside the artifact.
114 target: TargetTuple,
115 /// Where the cache is, read where everything else that needs it reads it.
116 cache: PathBuf,
117 },
118 /// `--fetch-msvc-sdk <tuple>`, which gets what is behind Microsoft's licence wall.
119 ///
120 /// The other action that may run another program to move bytes onto the machine, and the only
121 /// one that asks a person to accept somebody else's licence first.
122 /// `spec/cross-compile/13-distribution.md` section 13.4 is why it is a command of its own
123 /// rather than something `--fetch` does when it recognises the target: no release pins an
124 /// artifact for these, and nothing about this may ever happen because a compile wanted it to.
125 FetchMsvcSdk {
126 /// The target, which says which architecture's CRT library package is wanted.
127 target: TargetTuple,
128 /// Whether `--accept-licence` was on the command line. Without it the licence and the list
129 /// are printed and nothing is downloaded, which is the whole of what the flag is for.
130 accepted: bool,
131 /// Where the cache is, read where everything else that needs it reads it.
132 cache: PathBuf,
133 },
134 /// Compile the given inputs.
135 Compile {
136 /// The resolved options.
137 opts: Box<Options>,
138 /// What to do to each input, and in what order.
139 plan: Box<Plan>,
140 /// What the command line said about linking.
141 link: Box<LinkOptions>,
142 /// How many translation units to compile at once.
143 jobs: Jobs,
144 /// Whether `-v` asked for the plan to be printed while it runs.
145 verbose: bool,
146 /// What is worth saying about the command line before anything is compiled, printed as
147 /// warnings and once for the whole run rather than once per file.
148 ///
149 /// These are not diagnostics. A diagnostic is about a piece of source and has a span to
150 /// point at, and these are about the way two flags were combined, so there is nothing to
151 /// point at and nowhere below the driver that knows both halves. `-w` does not reach them
152 /// for the same reason it does not reach a refusal from the parser.
153 notes: Vec<String>,
154 },
155}
156
157/// Why a command line was rejected.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct CliError {
160 /// The message, lowercase and without a trailing period, in the same shape as any other
161 /// diagnostic.
162 pub message: String,
163}
164
165impl std::fmt::Display for CliError {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 f.write_str(&self.message)
168 }
169}
170
171impl std::error::Error for CliError {}
172
173fn err(message: impl Into<String>) -> CliError {
174 CliError { message: message.into() }
175}
176
177/// The two halves of one prefix mapping flag's argument, where `flag` includes its trailing `=`.
178///
179/// The split is at the last `=` in what follows the flag, not the first, which is gcc's rule and
180/// the only one that lets a directory whose name contains an `=` be the old half. It also means
181/// `-fmacro-prefix-map=a=b=c` rewrites `a=b` to `c` rather than `a` to `b=c`, which looks like a
182/// trap until you notice the alternative traps the far more common case.
183fn rewrite<'a>(arg: &'a str, flag: &str) -> Result<(&'a str, &'a str), CliError> {
184 let rest = &arg[flag.len()..];
185 PrefixMap::split(rest).ok_or_else(|| {
186 let flag = flag.trim_end_matches('=');
187 err(format!(
188 "`{rest}` is not a rewrite for `{flag}`, which is an old prefix, an `=` and a new one"
189 ))
190 })
191}
192
193/// A question the command line asked instead of asking for a compilation.
194///
195/// These are answered after the loop rather than where they are read, because every one of them
196/// is about the target or about the library search and the last word on both is the end of the
197/// command line.
198enum Query {
199 /// `-dumpmachine`, the triple.
200 Machine,
201 /// `-dumpversion`, the major number of the GCC release this compiler claims to be.
202 Version,
203 /// `-dumpfullversion`, the same release in all three numbers.
204 FullVersion,
205 /// `-print-multiarch`, the directory name a distribution files this target under.
206 Multiarch,
207 /// `-print-search-dirs`, in the three lines GCC prints.
208 SearchDirs,
209 /// `-print-sysroot`, the root the headers and the libraries are read under.
210 Sysroot,
211 /// `-print-sysroot-provenance`, what is in that root and where each of it came from.
212 SysrootProvenance,
213 /// `-print-sysroot-digest`, the one number that names all of it.
214 SysrootDigest,
215 /// `-print-file-name=<name>`, the full path of a library file.
216 FileName(String),
217 /// `-print-prog-name=<name>`, the full path of a program.
218 ProgName(String),
219 /// `-print-libgcc-file-name`, which is `-print-file-name=libgcc.a` under another spelling.
220 Libgcc,
221}
222
223/// Usage text.
224///
225/// Deliberately short. `spec/04-driver-and-cli.md` puts the full flag reference in the
226/// manual page, because a `--help` nobody can read in one screen is a `--help` nobody reads.
227pub const USAGE: &str = "\
228rucc, an optimizing C compiler
229
230usage: rucc [options] file...
231
232options:
233 -c compile and assemble, do not link
234 -S compile only, emit assembly
235 -E preprocess only
236 -o <file> write output to <file>, or to standard output for -
237 -D <name>[=<value>], -U <name> define a macro, or undefine one after every -D
238 -I <dir> add <dir> to the include search path
239 -iquote -isystem -idirafter <dir> the other chains, -nostdinc drops ours
240 -I-, -iprefix <p>, -iwithprefix[before] <dir> the older spellings of those
241 -include <file>, -imacros <file> read <file> first, the second for its macros only
242 --sysroot=<dir> look for the library's headers under <dir>, -isysroot too
243 -P, -dM with -E: leave out the markers, or dump the macros
244 -M -MM -MD -MMD write a make rule for the source, the last two compile as well
245 -MF <file> -MT <t> -MQ <t> -MP where the rule goes, what it builds, targets with no recipe
246 -std=<dialect> c89 through c2y, and the gnu spellings
247 -fgnuc-version=<v> the GCC release to claim, default 16.0.0
248 -x <lang> treat later inputs as <lang>, or none to stop
249 -O<level> optimize: 0, 1, 2, 3, s, z, fast
250 -fsafety=<tier> check memory safety: off, detect, enforce, kernel
251 -f[no-]sanitize=<what> the negative is taken, the positive is refused by name
252 -f[no-]safety-subobject a write has to stay inside the member it names
253 -f[no-]safety-restrict two restrict pointers of one block may not meet
254 -f<pass> -fno-<pass> -fdump-ir=<what> -fopt-info[-<kind>][=FILE]
255 -fpass-fuel=<pass>=<n>, -fpass-fuel-global=<n> stop a pass, or all of them, after n
256 -fdisable-<pass>[=<funcs>], -fenable-<pass>[=<funcs>] run a pass on some functions only
257 -g -g0 -gdwarf-5, -fno-omit-frame-pointer, -mno-red-zone debug info, frame pointer, red zone
258 -gz[=none|zlib|zlib-gnu|zstd] -gno-split-dwarf compress debug sections, one file not two
259 -flto[=auto|jobserver|<n>] -fno-lto -ffat-lto-objects read, and not done yet
260 -fprofile-use[=<path>] -fprofile-dir=<dir> read too, where -fprofile-generate is refused
261 -f[no-]stack-protector[-strong|-all], -f[no-]stack-clash-protection, -fcf-protection=<edges>
262 -ffunction-sections -fdata-sections a section per function or variable, for --gc-sections
263 -fvisibility=<what> default, hidden, internal or protected, when nothing in the source said
264 -l<name>, -L <dir>, -B <dir> link a library, where to look for one, where our own tools are
265 -fPIC -fpic -fPIE -fpie, -fno-common, -pipe what it does anyway
266 -f[no-]strict-aliasing, -f[no-]delete-null-pointer-checks what it assumes anyway
267 -static -shared -pie -no-pie -nostdlib -nostartfiles -nodefaultlibs -rdynamic -s how to link
268 -Wl,<arg>, -Xlinker <arg>, -fuse-ld=<name> hand an argument to the linker, or pick one
269 -Werror -pedantic -pedantic-errors -w -W[no-]system-headers how much to say, and how fatal
270 -m64 -march= -mtune= -mcpu= -mabi= -mcmodel= what machine to generate for
271 -pg -p, -mfentry -mno-fentry call a profiler on the way in, and where that call goes
272 -fpatchable-function-entry=<n>[,<m>] room at the top of every function to patch later
273 -fwrapv, -fwrapv-pointer, -fno-strict-overflow, -ftrapv overflow wraps, or stops the program
274 -f[no-]exceptions, -f[no-]non-call-exceptions let an exception unwind through the code
275 -f[no-]signed-char, -f[no-]unsigned-char, -f[no-]short-enums change the ABI
276 -ffp-contract=<how> fuse a multiply and an addition: fast, on or off
277 -f[no-]fast-math and each of its members, -f[no-]rounding-math, -fexcess-precision=<how>
278 -ffile-prefix-map=<old>=<new> rewrite that front of every path we put in the output
279 -fmacro-prefix-map= -fdebug-prefix-map= -fprofile-prefix-map= the same, one output each
280 -pthread build for more than one thread, and link the library for it
281 -dumpmachine -dumpversion -print-multiarch -print-search-dirs what this compiler is
282 -print-file-name=<name> -print-prog-name=<name> where a file or a program is
283 -print-sysroot the root the headers and the libraries are read under
284 -print-sysroot-provenance every input under it, where it came from and its licence
285 -print-sysroot-digest the sha256 of that record, which names the whole sysroot in one line
286 --fetch <tuple> get the sysroot this release pins for <tuple> and install it in the cache
287 --fetch-msvc-sdk <tuple> Microsoft's licence, then the SDK behind it with --accept-licence
288 --offline never download anything, which a compilation never does anyway
289 -j[n] compile n translation units at once, default all
290 -v, -### print each phase as it runs, or without running any
291 -save-temps[=cwd|obj], -time keep the .i and the .s, say how long each step took
292 --target=<triple> generate code for <triple>, which a name like <triple>-rucc also does
293 --emit=<kind> exe, obj, archive, asm, preprocessed, tast, ir, mir-final,
294 safety-summary, type-granules
295 --print-config, --print-pipeline print the configuration or the pipeline, and exit
296 --version print the version and exit
297 -h, --help print this message and exit
298
299See spec/04-driver-and-cli.md for the full flag reference.
300";
301
302/// The argument of a flag that may be joined to it or may be the next word.
303///
304/// `-DFOO` and `-D FOO` are the same thing, and `at` is where the flag's own letters end.
305fn joined_or_next(
306 arg: &str,
307 at: usize,
308 args: &[String],
309 i: &mut usize,
310) -> Result<String, CliError> {
311 if arg.len() > at {
312 return Ok(arg[at..].to_owned());
313 }
314 let next = args.get(*i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
315 *i += 1;
316 Ok(next.clone())
317}
318
319/// The smallest boundary a function is put on when the command line asked for no alignment at all.
320///
321/// Eight bytes, which is what gcc 16 gives `-fno-align-functions` on x86-64 and is a boundary every
322/// target this compiler has is happy with. It is not zero: a function still has to start somewhere
323/// an instruction may start, and the flag asks for the target's minimum rather than for none.
324const MIN_FUNC_ALIGN: u32 = 8;
325
326/// What `-falign-functions=N` asks for, as a power of two, or `None` for the target's own answer.
327///
328/// Zero and one both mean the default, which is gcc's reading of them, and everything else is
329/// rounded up to the next power of two, which is also gcc's: `-falign-functions=3` puts a function
330/// on a four byte boundary rather than being refused. Gives back `Err` shaped as an outer `None`
331/// only when the text is not a number, since that is the one thing gcc will not read either. A
332/// number larger than any alignment makes sense at is clamped rather than refused, for the same
333/// reason: this is a preference about speed and a build that wrote a silly one still deserves to
334/// compile.
335fn function_alignment(text: &str) -> Option<Option<u32>> {
336 // gcc takes `N:M:N2:M2`, where everything after the first number is about how far it is willing
337 // to go to reach the boundary. Only the boundary is answerable here, so the rest is read to
338 // check that it is numbers and then dropped.
339 let mut parts = text.split(':');
340 let first = parts.next()?;
341 if parts.any(|part| part.parse::<u64>().is_err()) {
342 return None;
343 }
344 let want: u64 = first.parse().ok()?;
345 if want <= 1 {
346 return Some(None);
347 }
348 let bytes = want.min(1 << 16).next_power_of_two();
349 Some(Some(u32::try_from(bytes).ok()?))
350}
351
352/// Every name that may follow `-fsanitize=`, which is gcc 16's list and three of this compiler's
353/// own.
354///
355/// The three are on it because `spec/07-types-and-semantics.md` section 7.7 already promises them:
356/// each undefined behaviour this compiler exploits is listed there with the check that detects it,
357/// and `alias`, `restrict` and `memory` are checks gcc has no spelling for. gcc refuses `memory`
358/// outright, since the sanitizer of that name is clang's. A name being here means it is a name
359/// rather than a typo, and nothing more than that: every one of them is refused after the loop,
360/// because none of them is implemented.
361///
362/// `all` is deliberately absent. gcc takes it only in the negative, so it is handled where each of
363/// those two spellings is read rather than by being on this list.
364const SANITIZERS: [&str; 34] = [
365 "address",
366 "kernel-address",
367 "hwaddress",
368 "kernel-hwaddress",
369 "pointer-compare",
370 "pointer-subtract",
371 "thread",
372 "leak",
373 "undefined",
374 "shift",
375 "shift-base",
376 "shift-exponent",
377 "integer-divide-by-zero",
378 "unreachable",
379 "vla-bound",
380 "null",
381 "return",
382 "signed-integer-overflow",
383 "bounds",
384 "bounds-strict",
385 "alignment",
386 "object-size",
387 "float-divide-by-zero",
388 "float-cast-overflow",
389 "nonnull-attribute",
390 "returns-nonnull-attribute",
391 "bool",
392 "enum",
393 "vptr",
394 "pointer-overflow",
395 "builtin",
396 "alias",
397 "restrict",
398 "memory",
399];
400
401/// The command line with every `@file` replaced by the words in the file, the way gcc does it.
402///
403/// Meson writes the link of a large target this way, so that a command line holding a thousand
404/// objects stays under the limit the system puts on one. Postgres's `postgres` executable is the
405/// one link in its tree that meson writes as `@postgres.rsp`, and before this the name went to
406/// the linker as it was. GNU ld reads response files itself, so it opened the file and found
407/// `-Wl,--as-needed` in it, which is a driver flag it has never heard of.
408///
409/// The rules are libiberty's `expandargv`, since that is what gcc and every other GNU tool read
410/// these files with. Words are split on white space, a single or a double quote keeps white
411/// space in a word until the matching quote, and a backslash makes the character after it an
412/// ordinary one, inside quotes as well as outside. A word the file gives that starts with `@` is
413/// read as a response file in turn. A name that cannot be opened is left on the command line as
414/// it was, which is what gcc does and which is how a file really called `@x.c` still reaches the
415/// loop, where it is refused as an unknown input rather than swallowed. The depth is capped so a
416/// file that names itself is an error and not a hang.
417fn response_files(args: &[String]) -> Result<Vec<String>, CliError> {
418 const DEEPEST: usize = 64;
419 fn expand(args: &[String], depth: usize, out: &mut Vec<String>) -> Result<(), CliError> {
420 for arg in args {
421 let Some(name) = arg.strip_prefix('@') else {
422 out.push(arg.clone());
423 continue;
424 };
425 let Ok(text) = std::fs::read_to_string(name) else {
426 out.push(arg.clone());
427 continue;
428 };
429 if depth == DEEPEST {
430 return Err(err(format!("response file '{name}' is nested too deeply")));
431 }
432 expand(&response_words(&text), depth + 1, out)?;
433 }
434 Ok(())
435 }
436 if !args.iter().any(|arg| arg.starts_with('@')) {
437 return Ok(args.to_vec());
438 }
439 let mut out = Vec::with_capacity(args.len());
440 expand(args, 0, &mut out)?;
441 Ok(out)
442}
443
444/// The words of one response file, split the way libiberty's `buildargv` splits them.
445fn response_words(text: &str) -> Vec<String> {
446 let mut words = Vec::new();
447 let mut word = String::new();
448 // Whether a word has begun, which is not the same as `word` having something in it: `''` is
449 // an empty word of its own and has to reach the command line as one.
450 let mut begun = false;
451 let mut quote: Option<char> = None;
452 let mut chars = text.chars();
453 while let Some(c) = chars.next() {
454 match c {
455 '\\' => {
456 if let Some(next) = chars.next() {
457 word.push(next);
458 }
459 begun = true;
460 }
461 _ if quote == Some(c) => quote = None,
462 _ if quote.is_some() => word.push(c),
463 '\'' | '"' => {
464 quote = Some(c);
465 begun = true;
466 }
467 _ if c.is_whitespace() => {
468 if begun {
469 words.push(std::mem::take(&mut word));
470 begun = false;
471 }
472 }
473 _ => {
474 word.push(c);
475 begun = true;
476 }
477 }
478 }
479 if begun {
480 words.push(word);
481 }
482 words
483}
484
485/// The command line with every `-Wp,` this compiler understands spelled as its own flags.
486///
487/// The preprocessor is inside this compiler, so what a build hands it through `-Wp,` has to be
488/// read here. Kbuild is the reason: every object in the Linux kernel and in busybox is compiled
489/// with `-Wp,-MD,dir/.name.o.d`, which is cpp's spelling of `-MD -MF dir/.name.o.d`. cpp's `-MD`
490/// and `-MMD` take the file as their next word where the driver's do not, and the rest are the
491/// same flags in both. A `-Wp,` holding anything else is left as it was so the loop refuses it,
492/// because dropping part of what a build asked the preprocessor for would be the silent kind of
493/// wrong.
494fn preprocessor_args(args: &[String]) -> Vec<String> {
495 let mut out = Vec::with_capacity(args.len());
496 for arg in args {
497 let Some(list) = arg.strip_prefix("-Wp,") else {
498 out.push(arg.clone());
499 continue;
500 };
501 let words: Vec<&str> = list.split(',').collect();
502 let mut spelled = Vec::new();
503 let mut i = 0;
504 let understood = loop {
505 let Some(&word) = words.get(i) else {
506 break true;
507 };
508 i += 1;
509 match word {
510 "-MD" | "-MMD" | "-MF" | "-MT" | "-MQ" => {
511 let Some(&value) = words.get(i) else {
512 break false;
513 };
514 i += 1;
515 if word == "-MD" || word == "-MMD" {
516 spelled.extend([word.to_owned(), "-MF".to_owned()]);
517 } else {
518 spelled.push(word.to_owned());
519 }
520 spelled.push(value.to_owned());
521 }
522 "-MP" => spelled.push(word.to_owned()),
523 _ if word.len() > 2
524 && (word.starts_with("-D")
525 || word.starts_with("-U")
526 || word.starts_with("-I")) =>
527 {
528 spelled.push(word.to_owned());
529 }
530 _ => break false,
531 }
532 };
533 if understood {
534 out.extend(spelled);
535 } else {
536 out.push(arg.clone());
537 }
538 }
539 out
540}
541
542/// The extension a `-m` flag names and whether it turns it on, when it names one.
543///
544/// `-mno-` is the off form of every one of them, which is also how gcc spells it. A flag that is
545/// not an extension, `-mno-red-zone` say, is `None` and is left to the rest of the parser.
546fn isa_name(arg: &str) -> Option<(&str, rucc_target::Feature, bool)> {
547 let rest = arg.strip_prefix("-m")?;
548 let (name, on) = match rest.strip_prefix("no-") {
549 Some(name) => (name, false),
550 None => (rest, true),
551 };
552 let known =
553 if on { rucc_target::Feature::named(name) } else { rucc_target::Feature::named_off(name) };
554 known.map(|feature| (name, feature, on))
555}
556
557/// The extensions the machine running the compiler has, which is what `-march=native` means.
558///
559/// Asked of the processor with `cpuid`, through the standard library, and only when the compiler
560/// is running on an x86-64 at all. Anywhere else there is no processor to ask about an x86-64 one,
561/// and gcc on such a machine builds for the baseline, which is what this does. The list is the
562/// extensions whose names are stable in the standard library at this workspace's minimum Rust
563/// version, which covers everything [`rucc_target::Feature::honoured`] says yes to and a good deal
564/// that it does not.
565fn native_isa() -> rucc_target::Isa {
566 let base = rucc_target::Isa::baseline();
567 #[cfg(target_arch = "x86_64")]
568 {
569 let mut isa = rucc_target::Choices::new();
570 macro_rules! asked {
571 ($($detected:tt => $name:literal),* $(,)?) => {
572 $(if std::arch::is_x86_feature_detected!($detected) {
573 isa.read($name).expect("a name gcc knows");
574 })*
575 };
576 }
577 asked! {
578 "sse3" => "sse3",
579 "ssse3" => "ssse3",
580 "sse4.1" => "sse4.1",
581 "sse4.2" => "sse4.2",
582 "sse4a" => "sse4a",
583 "popcnt" => "popcnt",
584 "avx" => "avx",
585 "avx2" => "avx2",
586 "fma" => "fma",
587 "f16c" => "f16c",
588 "bmi1" => "bmi",
589 "bmi2" => "bmi2",
590 "lzcnt" => "lzcnt",
591 "xsave" => "xsave",
592 "aes" => "aes",
593 "pclmulqdq" => "pclmul",
594 "sha" => "sha",
595 "cmpxchg16b" => "cx16",
596 "adx" => "adx",
597 "rdrand" => "rdrnd",
598 "rdseed" => "rdseed",
599 }
600 isa.over(base)
601 }
602 #[cfg(not(target_arch = "x86_64"))]
603 base
604}
605
606/// Parses a command line, without the program name.
607///
608/// # Errors
609///
610/// Returns the message to print when the arguments do not name a compilation this compiler
611/// can attempt.
612pub fn parse_args(args: &[String]) -> Result<Action, CliError> {
613 let expanded = preprocessor_args(&response_files(args)?);
614 let args = expanded.as_slice();
615 let host = Triple::host()
616 .ok_or_else(|| err("this host is not a supported target and no --target was given"))?;
617 let mut opts = Options::new(host);
618 // Where the compiler is running, which is what `DW_AT_comp_dir` is and what a debugger joins a
619 // relative file name onto. Asked here rather than where the debug sections are written, because
620 // this is the one layer that is allowed to look at the process it is in, and because a command
621 // line that compiles four files should give the same answer for all four.
622 opts.working_dir = std::env::current_dir().ok().map(|dir| dir.to_string_lossy().into_owned());
623 let mut inputs: Vec<Input> = Vec::new();
624 let mut print_config = false;
625 let mut print_pipeline = false;
626 let mut print_plan = false;
627 let mut verbose = false;
628 let mut jobs = Jobs::default();
629 let mut nostdinc = false;
630 let mut sysroot: Option<PathBuf> = None;
631 // What the command line is worth warning about, filled in after the loop rather than during it,
632 // because every question of this kind is about two flags and the last word on both of them is
633 // the end of the loop.
634 let mut notes: Vec<String> = Vec::new();
635 // The whole ten field target, kept beside the three field one because `--target=` can pin a
636 // libc version and `Triple` has nowhere to put it. It decides `__GLIBC_MINOR__` and nothing
637 // else today, and `None` is a command line that named no target, which is this machine.
638 let mut pinned: Option<TargetTuple> = None;
639 let mut min_version: Option<rucc_tuple::Version> = None;
640 let mut output = None;
641 let mut link = LinkOptions::default();
642 let mut query: Option<Query> = None;
643 // What `--fetch` named, and whether `--offline` forbade it. Both are weighed after the loop
644 // because either can be written after the other.
645 let mut fetch: Option<String> = None;
646 // The other fetch, kept apart from the one above because they are different commands with
647 // different rules, and weighed after the loop for the same reason that one is.
648 let mut fetch_msvc: Option<String> = None;
649 let mut accepted = false;
650 let mut offline = false;
651 let mut threads = false;
652 // Which sanitizers are still asked for by the end of the command line. Accumulated across the
653 // loop rather than answered where it was read, because `-fno-sanitize=` turns one off and a
654 // build that asks for a check and then takes it back has asked for nothing. What happens to a
655 // set that is not empty is decided after the loop.
656 let mut sanitizers: Vec<&str> = Vec::new();
657 // The `-ffast-math` family in the order it was written, replayed after the loop on top of
658 // what `-Ofast` implies. gcc applies a level's defaults before any flag and the flags in order
659 // after that, so `-fno-fast-math -Ofast` is not fast math, and only a replay can say so.
660 let mut math_flags: Vec<&str> = Vec::new();
661 let mut ofast = false;
662 // `-mdaz-ftz` and `-mno-daz-ftz`, which decide the startup file directly and outrank the
663 // family on that one question.
664 let mut daz_ftz: Option<bool> = None;
665 // The instruction set extensions the `-m` flags named, in order, and the processor `-march`
666 // named last. Both are weighed after the loop, because a processor supplies only what no flag
667 // spoke for whichever order they came in, and because `--target=` may come after either and
668 // decide that neither means anything. See `rucc_target::isa`.
669 let mut isa = rucc_target::Choices::new();
670 let mut isa_flag: Option<&str> = None;
671 let mut march: Option<&str> = None;
672 // What `-fexceptions` and `-fno-exceptions` last said, if either was written. It is kept apart
673 // from the field because `-fnon-call-exceptions` turns exceptions on only when neither was,
674 // which is gcc's rule and is why `-fno-exceptions -fnon-call-exceptions` defines no
675 // `__EXCEPTIONS` whichever order the two come in.
676 let mut exceptions: Option<bool> = None;
677 // `-x` applies to inputs that come after it and stays in effect until the next one, which
678 // is why it is tracked across the loop rather than attached to a single argument.
679 let mut forced: Option<InputKind> = None;
680 // What `-iprefix` last said, stuck on the front of every later `-iwithprefix`. It applies to
681 // the flags after it and not the ones before, so a command line may set it more than once.
682 // GCC's default is its own installed header directory with the last component taken off,
683 // which is a path a cross compiler's build system knows and passes; there is no equivalent
684 // here, so with no `-iprefix` the prefix is nothing and `-iwithprefix` names a directory
685 // outright.
686 let mut iprefix = String::new();
687
688 let mut i = 0;
689 while i < args.len() {
690 let arg = args[i].as_str();
691 i += 1;
692 match arg {
693 "-h" | "--help" => return Ok(Action::Help),
694 "--version" => return Ok(Action::Version),
695 // The sysroot fetch, which is weighed after the loop rather than acted on here, because
696 // `--offline` written after it has to be able to forbid it. Both spellings, since a
697 // flag that takes a tuple gets written both ways and neither is a guess at what the
698 // other meant.
699 "--fetch" => {
700 let value = args
701 .get(i)
702 .ok_or_else(|| err("--fetch requires the target to get a sysroot for"))?;
703 i += 1;
704 fetch = Some(value.clone());
705 }
706 _ if arg.starts_with("--fetch=") => {
707 fetch = Some(arg["--fetch=".len()..].to_owned());
708 }
709 // The other fetch, which is section 13.4's. Same two spellings for the same reason,
710 // and weighed after the loop so that `--offline` and `--accept-licence` written after
711 // it are read whichever order somebody put them in.
712 "--fetch-msvc-sdk" => {
713 let value = args.get(i).ok_or_else(|| {
714 err("--fetch-msvc-sdk requires the target to get the SDK for")
715 })?;
716 i += 1;
717 fetch_msvc = Some(value.clone());
718 }
719 _ if arg.starts_with("--fetch-msvc-sdk=") => {
720 fetch_msvc = Some(arg["--fetch-msvc-sdk=".len()..].to_owned());
721 }
722 // Both spellings of the word, because the compiler's own prose uses one of them and
723 // most of the people typing this will reach for the other, and being told that a flag
724 // is not a flag over the letter in the middle of it is a puzzle rather than a message.
725 "--accept-licence" | "--accept-license" => accepted = true,
726 // Accepted on any command line and only ever read by the fetch, because an ordinary
727 // compile downloads nothing with or without it. So this flag takes nothing away today,
728 // which is the property section 13.2 asks for rather than an omission: a build that
729 // passes it is saying what it expects of this compiler, and what it expects is already
730 // true.
731 "--offline" => offline = true,
732 "--print-config" => print_config = true,
733 "--print-pipeline" => print_pipeline = true,
734 "-###" => print_plan = true,
735 "-v" => verbose = true,
736 // The files a compilation goes through, kept rather than thrown away. The bare
737 // spelling means `=obj` and not `=cwd`, which is not what the manual says and is what
738 // gcc 16 does; `SaveTemps::Object` carries the measurement.
739 "-save-temps" => opts.save_temps = SaveTemps::Object,
740 _ if arg.starts_with("-save-temps=") => {
741 opts.save_temps = arg["-save-temps=".len()..].parse().map_err(err)?;
742 }
743 // How long each step took. A misspelling of this is worth rejecting rather than
744 // ignoring, since a run that says nothing looks like a compilation that took no time.
745 "-time" => opts.time = true,
746 "-c" => opts.emit = EmitKind::Object,
747 "-S" => opts.emit = EmitKind::Asm,
748 "-E" => opts.emit = EmitKind::Preprocessed,
749 "-fsyntax-only" => opts.emit = EmitKind::SyntaxOnly,
750 "-g" => opts.debug_info = true,
751 // GCC's own levels of how much debug information to write. Zero is none and every
752 // other number is some, and this compiler has one amount, so the numbers above zero
753 // all mean the same thing here. `-ggdb` is the same flag asking for whatever the
754 // debugger on the machine prefers, which is what we emit anyway.
755 "-g0" => opts.debug_info = false,
756 "-g1" | "-g2" | "-g3" | "-ggdb" | "-ggdb1" | "-ggdb2" | "-ggdb3" => {
757 opts.debug_info = true;
758 }
759 // The version of DWARF to write. We write DWARF 5 and nothing else, so a build that
760 // asks for another version is told rather than handed a file it cannot read.
761 "-gdwarf" | "-gdwarf-5" => opts.debug_info = true,
762 _ if arg.starts_with("-gdwarf-") => {
763 return Err(err(format!(
764 "{arg}: this compiler writes DWARF 5 and no other version, see \
765 spec/11-debug-info.md"
766 )));
767 }
768 // Whether the debug information goes in a file of its own beside the object. gcc
769 // writes that `.dwo` whether or not it found anything to put in it, which means a
770 // build system that declares the file as an output gets one and a make rule that
771 // depends on it fires. Refused for that reason rather than taken: section 4.1 takes a
772 // flag that changes nothing and refuses one that changes what is produced, and a file
773 // that does not appear is the plainest change of that kind there is. The negative
774 // spelling is taken, because putting it all in the object is what happens anyway.
775 "-gno-split-dwarf" => {}
776 "-gsplit-dwarf" => {
777 return Err(err(format!(
778 "{arg}: this compiler writes no separate `.dwo` file, and a build that \
779 expects one beside each object would wait for a file that never arrives, \
780 see spec/11-debug-info.md"
781 )));
782 }
783 // How the debug sections are compressed. There are none yet, so every answer produces
784 // the same bytes and taking the flag promises nothing that is not kept. The value is
785 // still checked, because a typo in a distribution's flags is worth finding when the
786 // compiler reads it rather than when somebody later wonders why nothing got smaller.
787 // Bare `-gz` means `zlib`, which the manual leaves for the reader to discover.
788 "-gz" => opts.compress = Compress::Zlib,
789 _ if arg.starts_with("-gz=") => {
790 let how = &arg["-gz=".len()..];
791 opts.compress = how.parse().map_err(|()| {
792 err(format!(
793 "`{how}` is not a way to compress debug sections, which is none, zlib, \
794 zlib-gnu or zstd"
795 ))
796 })?;
797 }
798 "-Werror" => opts.warnings_are_errors = true,
799 // Nothing that is not fatal is said at all. Read at the one place a diagnostic goes
800 // through rather than here, so that a warning `-w` dropped is not counted either.
801 "-w" => opts.warnings = false,
802 // Off by default, the way gcc has it off. A header that came with the machine is not
803 // one the person compiling can change, so a warning about it is noise, and under
804 // `-Werror` it is a build that stops on a line nobody in the project wrote. Somebody
805 // porting a header does want to hear all of it, which is what the flag is for.
806 "-Wsystem-headers" => opts.system_header_warnings = true,
807 "-Wno-system-headers" => opts.system_header_warnings = false,
808 "-pedantic-errors" => {
809 opts.pedantic = true;
810 opts.warnings_are_errors = true;
811 }
812 "-P" => opts.line_markers = false,
813 // The dependency family, which section 4.4 calls required because every build system
814 // that generates its own makefiles asks for it. The two that end in `D` write a file
815 // beside the object and let the compilation happen, and the two that do not write to
816 // standard output and stop after it. Nothing here turns the system headers back on
817 // once a flag has turned them off, which is GCC's behaviour and is why `-MM -M` is
818 // `-MM`: the flag asking for fewer of them is the one with something to say.
819 "-M" => {
820 opts.deps.emit = true;
821 opts.deps.instead_of_compiling = true;
822 }
823 "-MM" => {
824 opts.deps.emit = true;
825 opts.deps.instead_of_compiling = true;
826 opts.deps.system_headers = false;
827 }
828 "-MD" => opts.deps.emit = true,
829 "-MMD" => {
830 opts.deps.emit = true;
831 opts.deps.system_headers = false;
832 }
833 "-MP" => opts.deps.phony = true,
834 // These three take a word and only in the separated form, which is how GCC spells
835 // them and how every build system writes them.
836 "-MF" | "-MT" | "-MQ" => {
837 let value =
838 args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
839 i += 1;
840 match arg {
841 "-MF" => opts.deps.file = Some(value.clone()),
842 // The whole of the difference between the two. `-MT` is for a build that has
843 // already escaped what it is passing, and `-MQ` is for one that has a name
844 // and wants it to arrive as that name.
845 "-MT" => opts.deps.targets.push(value.clone()),
846 _ => opts.deps.targets.push(deps::escaped(value)),
847 }
848 }
849 // The questions a build system asks before it compiles anything. Answered after the
850 // loop, because each one is about the target or the library search and the command
851 // line has not finished saying what those are.
852 "-dumpmachine" => query = Some(Query::Machine),
853 // Both answer with the GCC release in `__GNUC__` rather than our own version, because
854 // what asks is a build script deciding which GCC it is talking to, and `0.11` reads as
855 // a GCC too old to have anything. GCC 7 and later print only the major number for the
856 // first one, and that is the shape the scripts were written against.
857 "-dumpversion" => query = Some(Query::Version),
858 "-dumpfullversion" => query = Some(Query::FullVersion),
859 "-print-multiarch" => query = Some(Query::Multiarch),
860 "-print-search-dirs" => query = Some(Query::SearchDirs),
861 "-print-sysroot" => query = Some(Query::Sysroot),
862 // Both spellings, because this one is ours rather than GCC's and our own documents
863 // write it both ways: section 13.5 of `spec/cross-compile/13-distribution.md` gives it
864 // two dashes like the other flags we invented, and document 12's table gives it one
865 // like the `-print-` family it sits in. A person who reads either and types what it
866 // says is right, so neither is refused.
867 "-print-sysroot-provenance" | "--print-sysroot-provenance" => {
868 query = Some(Query::SysrootProvenance);
869 }
870 "-print-sysroot-digest" | "--print-sysroot-digest" => {
871 query = Some(Query::SysrootDigest);
872 }
873 "-print-libgcc-file-name" => query = Some(Query::Libgcc),
874 _ if arg.starts_with("-print-file-name=") => {
875 query = Some(Query::FileName(arg["-print-file-name=".len()..].to_owned()));
876 }
877 _ if arg.starts_with("-print-prog-name=") => {
878 query = Some(Query::ProgName(arg["-print-prog-name=".len()..].to_owned()));
879 }
880 // A program built to run in more than one thread. On every platform this compiler
881 // targets that is a macro the library's headers read and one more library on the
882 // link line, and the library is added after the loop so that it lands after the
883 // objects that refer to it.
884 "-pthread" | "-pthreads" => {
885 opts.defines.push("_REENTRANT".to_owned());
886 threads = true;
887 }
888 "-ansi" => {
889 opts.std = Std::C89;
890 opts.gnu_extensions = false;
891 }
892 // `-Wpedantic` is the same flag under the name the `-W` family gives it, which is
893 // the spelling a build system that groups its warning flags tends to write.
894 "-pedantic" | "-Wpedantic" => opts.pedantic = true,
895 // Both directions, because a build that needs this for one directory turns it back
896 // off for the next one rather than leaving it on for the whole tree.
897 "-fpermissive" => opts.permissive = true,
898 "-fno-permissive" => opts.permissive = false,
899 "-ffreestanding" => opts.hosted = false,
900 "-fhosted" => opts.hosted = true,
901 "-fno-builtin" => opts.builtins = false,
902 "-fbuiltin" => opts.builtins = true,
903 // The C89 dialects are under GNU's reading whatever this says, so turning it off
904 // there is turning off something the dialect asked for, which is accepted and does
905 // nothing. gcc refuses that command line, and there is nothing it could have meant.
906 "-fgnu89-inline" => opts.gnu89_inline = true,
907 "-fno-gnu89-inline" => opts.gnu89_inline = false,
908 // Both directions of each, because a build system that wants one of these usually
909 // writes it beside the flag that turns it back off for one directory.
910 "-fno-omit-frame-pointer" => opts.frame_pointer = Some(true),
911 "-fomit-frame-pointer" => opts.frame_pointer = Some(false),
912 // Both directions again, for the same reason, and a third answer for a command line
913 // that wrote neither: see `reorder_blocks` in `rucc_session`.
914 "-freorder-blocks" => opts.reorder_blocks = Some(true),
915 "-fno-reorder-blocks" => opts.reorder_blocks = Some(false),
916 // gcc's name for the scheduler that runs after the registers are handed out, which is
917 // the only one rucc has: see `schedule_insns` in `rucc_session`. gcc also takes
918 // `-fschedule-insns` for the pass before allocation, and taking that one here would be
919 // a flag that says a pass ran when none did.
920 "-fschedule-insns2" => opts.schedule_insns = Some(true),
921 "-fno-schedule-insns2" => opts.schedule_insns = Some(false),
922 // A call in tail position as a jump: see `sibling_calls` in `rucc_session`.
923 "-foptimize-sibling-calls" => opts.sibling_calls = Some(true),
924 "-fno-optimize-sibling-calls" => opts.sibling_calls = Some(false),
925 "-mno-red-zone" => opts.red_zone = false,
926 "-mred-zone" => opts.red_zone = true,
927 // Four flags rather than one with an argument, which is how gcc spells them and how
928 // every build line writes them. Last one wins, because a package build puts
929 // `-fstack-protector-strong` in its global flags and a directory that cannot have one
930 // turns it back off on the line after.
931 "-fno-stack-protector" | "-fno-stack-protector-all" | "-fno-stack-protector-strong" => {
932 opts.protector = Protector::None;
933 }
934 "-fstack-protector" => opts.protector = Protector::Buffers,
935 "-fstack-protector-strong" => opts.protector = Protector::Strong,
936 "-fstack-protector-all" => opts.protector = Protector::All,
937 // The other half of what a hardened build asks for, and it is a question about the
938 // frame rather than about the function, so it is a switch rather than a level.
939 "-fstack-clash-protection" => opts.stack_clash = true,
940 "-fno-stack-clash-protection" => opts.stack_clash = false,
941 // The third of them, and the one that is a question with an argument rather than a
942 // family of spellings, because what it asks about is which of the two edges of a
943 // control flow transfer is checked. Bare is both of them, which is what gcc does.
944 "-fcf-protection" => opts.control = Control::Full,
945 "-fno-cf-protection" => opts.control = Control::None,
946 // Two spellings of the same request, which is what gcc has as well. `-p` was the older
947 // profiler and `-pg` the one that also recorded who called whom, and on every platform
948 // this compiler targets there is now one hook and both ask for it.
949 "-pg" | "-p" => {
950 opts.profile = true;
951 link.profile = true;
952 }
953 // Accepted on their own and doing nothing on their own, which is gcc's behaviour: they
954 // say where the call goes and a command line that asked for no call has nowhere to put
955 // one. That matters because a build system that sets `-mfentry` globally and `-pg` per
956 // directory is a build system that would otherwise fail on every other directory.
957 "-mfentry" => opts.hook = Hook::Early,
958 "-mno-fentry" => opts.hook = Hook::Late,
959 // GCC drops its own include directory along with the system ones, because its
960 // headers are half of a pair with the library's and half a pair is worse than
961 // none. A build that passes this is supplying the whole set itself.
962 "-nostdinc" => nostdinc = true,
963 "-o" => {
964 output = Some(args.get(i).ok_or_else(|| err("-o requires an argument"))?.clone());
965 i += 1;
966 }
967 // The flags that take a directory only in the separated form. GCC spells them
968 // this way and nothing writes `-iquotedir`, so accepting the joined form would
969 // mean guessing at a path that starts with the flag's own letters.
970 // Apple's spelling of `--sysroot`, and the one its own build systems pass. The
971 // two mean the same thing here: the configured directories are under there rather
972 // than under the root.
973 "-isysroot" => {
974 let dir = args.get(i).ok_or_else(|| err("-isysroot requires an argument"))?;
975 i += 1;
976 sysroot = Some(PathBuf::from(dir));
977 }
978 "-iquote" | "-isystem" | "-idirafter" => {
979 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
980 i += 1;
981 match arg {
982 "-iquote" => opts.search.push_quote(dir.clone()),
983 "-isystem" => opts.search.push_system(dir.clone()),
984 _ => opts.search.push_after(dir.clone()),
985 }
986 }
987 "-iprefix" => {
988 iprefix = args.get(i).ok_or_else(|| err("-iprefix requires an argument"))?.clone();
989 i += 1;
990 }
991 // Where GCC puts these is not where its manual says it puts them, and this is the
992 // measured answer rather than the documented one: `-iwithprefix` lands in the
993 // `-isystem` slot and not the `-idirafter` slot, and `-iwithprefixbefore` lands in
994 // the `-I` slot. A cross build that uses them is relying on the behaviour, since
995 // that is the compiler it was developed against.
996 "-iwithprefix" | "-iwithprefixbefore" => {
997 let dir = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
998 i += 1;
999 let dir = format!("{iprefix}{dir}");
1000 if arg == "-iwithprefix" {
1001 opts.search.push_system(dir);
1002 } else {
1003 opts.search.push_bracket(dir);
1004 }
1005 }
1006 "-include" | "-imacros" => {
1007 let name = args.get(i).ok_or_else(|| err(format!("{arg} requires an argument")))?;
1008 i += 1;
1009 opts.preincludes
1010 .push(Preinclude { name: name.clone(), macros_only: arg == "-imacros" });
1011 }
1012 // The flag `-iquote` was introduced to replace, still passed by build systems old
1013 // enough to predate the replacement. It is not a directory: it says that every `-I`
1014 // so far is for quoted includes only, and that a quoted include stops looking next
1015 // to the file that wrote it.
1016 "-I-" => opts.search.split_quote_chain(),
1017 // `-x c` and `-xc`, both of which gcc takes. busybox and toybox probe the compiler
1018 // with the joined one.
1019 _ if arg.starts_with("-x") => {
1020 let lang = joined_or_next(arg, 2, args, &mut i)?;
1021 forced = if lang == "none" {
1022 None
1023 } else {
1024 Some(InputKind::from_x_arg(&lang).map_err(|e| err(format!("{e}")))?)
1025 };
1026 }
1027 // Not a GCC flag. spec/03-architecture.md section 3.5 compiles several
1028 // translation units in one process rather than making the build system fork, and
1029 // section 3.8's determinism check compares `-j1` against `-j16`, so the knob has
1030 // to exist and has to be spelled the way `make` spells it.
1031 // `-DFOO`, `-D FOO` and the same for `-U` and `-I`. Both forms are in wide use
1032 // and a build system may produce either, so both are read here rather than
1033 // being normalised by whatever generated the command line.
1034 _ if arg.starts_with("-D") => {
1035 let value = joined_or_next(arg, 2, args, &mut i)?;
1036 opts.defines.push(value);
1037 }
1038 _ if arg.starts_with("-U") => {
1039 let value = joined_or_next(arg, 2, args, &mut i)?;
1040 opts.undefines.push(value);
1041 }
1042 _ if arg.starts_with("-I") => {
1043 let dir = joined_or_next(arg, 2, args, &mut i)?;
1044 opts.search.push_bracket(dir);
1045 }
1046 _ if arg.starts_with("-std=") => {
1047 let name = &arg["-std=".len()..];
1048 let (std, gnu) = Std::from_flag(name)
1049 .ok_or_else(|| err(format!("unknown dialect `{name}`, see --help")))?;
1050 opts.std = std;
1051 opts.gnu_extensions = gnu;
1052 }
1053 // Section 4.5. The claim decides which half of glibc's `sys/cdefs.h` we are
1054 // handed, so a differential run that does not set it is comparing two compilers
1055 // that believe they are different compilers.
1056 // GCC packs these into one flag, so `-dDI` is two of them. Letters in the family
1057 // that we have not written yet are accepted and ignored, because a dump is a
1058 // debugging aid and a build that asks for one should still compile. A letter
1059 // outside the family falls through to the unknown option error, which is what
1060 // keeps `-dumpversion` from being read as a dump of nothing.
1061 _ if Dumps::is_family(arg) => {
1062 opts.dumps.add(&arg[2..]);
1063 }
1064 // One name at a time, which is what a build that means its own `memcpy` and the
1065 // library's everything else writes. The name is not checked against a list, because
1066 // the flag is about what the program means by a name and a program is allowed to mean
1067 // something by a name this compiler has never heard of.
1068 _ if arg.starts_with("-fno-builtin-") => {
1069 opts.no_builtin.push(arg["-fno-builtin-".len()..].to_owned());
1070 }
1071 _ if arg.starts_with("-fgnuc-version=") => {
1072 let v = &arg["-fgnuc-version=".len()..];
1073 opts.gnuc = v.parse().map_err(err)?;
1074 }
1075 // spec/13-gnu-compat.md section 13.3 promises this flag an error that says why rather
1076 // than the unknown option one, because a build reaching for it is asking for a feature
1077 // and deserves to be told it is not coming rather than told the spelling is wrong.
1078 // The negative form is what this compiler does anyway, so it is taken and dropped.
1079 "-fnested-functions" => {
1080 return Err(err(
1081 "nested functions are not supported: a call to one goes through a trampoline \
1082 written on the stack, which no target that enforces an unexecutable stack \
1083 allows",
1084 ));
1085 }
1086 "-fno-nested-functions" => {}
1087 // Which of the two links the output is for, which is a real difference and not a
1088 // description of what happens anyway. Everything here is position independent either
1089 // way, and what these decide is whether a name may be one another object defines or
1090 // replaces, because a link that produces an executable puts every name in the same
1091 // program and a link that produces a shared library does not.
1092 //
1093 // It matters that they are accepted at all, whatever they then do. Every autoconf and
1094 // cmake build puts `-fPIC` on the compile line, so a compiler that rejects it cannot
1095 // be the `CC` of a project that has a configure script, whatever else it can do. That
1096 // is how this was found: building SQLite's test fixture stopped on it.
1097 "-fPIC" | "-fpic" => opts.pic = Pic::Library,
1098 // Not a synonym of the pair above, which is what they were treated as until #756. The
1099 // library is the expensive answer and gcc makes it the one that has to be asked for,
1100 // so this is also what nothing at all means.
1101 "-fPIE" | "-fpie" => opts.pic = Pic::Executable,
1102 // A different question from the pair above, and the one every distribution build of a
1103 // shared library answers. `-fPIC` decides how an address is reached, and this decides
1104 // whether the optimizer may believe a body it can see, because an exported name is one
1105 // the dynamic linker may find another definition of first. On by default, which is
1106 // gcc's arrangement and is the honest answer, and off is a promise the build makes and
1107 // nothing checks.
1108 "-fsemantic-interposition" => opts.interposition = true,
1109 "-fno-semantic-interposition" => opts.interposition = false,
1110 // Two requests rather than one, and the same table answers both, so what decides is
1111 // whether either of them is standing. gcc arranges it the same way: the asynchronous
1112 // one is the default here and it implies the other, and a line that asks for a table
1113 // and against an asynchronous one gets a table.
1114 "-fasynchronous-unwind-tables" => opts.async_unwind_tables = true,
1115 "-fno-asynchronous-unwind-tables" => opts.async_unwind_tables = false,
1116 "-funwind-tables" => opts.unwind_tables = true,
1117 "-fno-unwind-tables" => opts.unwind_tables = false,
1118 // The other direction is a request, not a description, and it is one this compiler
1119 // cannot grant, so it gets the treatment section 13.3 asks for rather than the unknown
1120 // option error. Answering it by carrying on would be answering a different question:
1121 // the code would still be position independent, which is correct everywhere an
1122 // ordinary program runs and is wrong in a kernel, where the flag is written precisely
1123 // because there is no loader to fill a global offset table in.
1124 "-fno-pic" | "-fno-pie" => {
1125 return Err(err(
1126 "position dependent code is not supported: an address that may be in another \
1127 object is loaded out of the global offset table, and nothing here emits the \
1128 absolute form this asks for. Use -no-pie if what you meant was how to link",
1129 ));
1130 }
1131 // A section per function and a section per variable, which is what makes
1132 // `--gc-sections` able to drop anything: a linker can leave out a section nothing
1133 // reaches and cannot leave out half of one. Both directions are taken, and the off
1134 // one is the default rather than a refusal, since a build that writes it is asking
1135 // for what happens anyway.
1136 "-ffunction-sections" => opts.function_sections = true,
1137 "-fno-function-sections" => opts.function_sections = false,
1138 "-fdata-sections" => opts.data_sections = true,
1139 "-fno-data-sections" => opts.data_sections = false,
1140 // Another description of what this compiler does. A file scope declaration with no
1141 // initializer is written into `.bss` as an ordinary defined symbol, not offered to the
1142 // linker as a common one for it to merge, which is what `-fno-common` asks for and what
1143 // gcc has done by default since 10. Nothing in the front end produces `Linkage::Common`
1144 // at all.
1145 "-fno-common" => {}
1146 // What overflows rather than being undefined. Every one of these takes something away
1147 // from the optimizer rather than asking it to do anything, which is why the negative
1148 // spellings are the interesting ones and the positive spellings are the default.
1149 //
1150 // `-fno-strict-overflow` is both of the others, which is gcc's own reading of it: its
1151 // help text for `-fstrict-overflow` says "negated as -fwrapv -fwrapv-pointer". So it is
1152 // written here as the pair rather than kept as a third thing to test everywhere.
1153 //
1154 // `-ftrapv` is the exception and is the one that asks for something. It is the other
1155 // answer to the question `-fwrapv` answers, so the two cannot both hold and each clears
1156 // the other, which makes the last one on the command line the one that counts. That is
1157 // gcc 16's behaviour and was measured rather than read: `-ftrapv -fwrapv` emits no
1158 // checked calls and `-fwrapv -ftrapv` emits them. The positive spelling of the pointer
1159 // question is left alone by both, because neither has anything to say about it.
1160 "-fwrapv" => {
1161 opts.wrapping.signed = true;
1162 opts.wrapping.trap = false;
1163 }
1164 "-fno-wrapv" => opts.wrapping.signed = false,
1165 "-fwrapv-pointer" => opts.wrapping.pointer = true,
1166 "-fno-wrapv-pointer" => opts.wrapping.pointer = false,
1167 "-fno-strict-overflow" => opts.wrapping = Wrapping::ALL,
1168 // Which does not clear the checked one, because gcc does not: `-ftrapv
1169 // -fstrict-overflow` still emits the calls. It says what is assumed and not what
1170 // happens.
1171 "-fstrict-overflow" => {
1172 opts.wrapping.signed = false;
1173 opts.wrapping.pointer = false;
1174 }
1175 "-ftrapv" => {
1176 opts.wrapping.trap = true;
1177 opts.wrapping.signed = false;
1178 }
1179 "-fno-trapv" => opts.wrapping.trap = false,
1180 // The two flags that say what a plain `char` is, which is one question with two
1181 // spellings each: gcc reads `-fno-signed-char` as `-funsigned-char` and
1182 // `-fno-unsigned-char` as `-fsigned-char`, so there are four ways to write two
1183 // answers and the last one written wins. Nothing is set until one of them is given,
1184 // because the target's own ABI is the answer otherwise and it is not the same answer
1185 // everywhere: x86-64 and Apple's arm64 are signed, Linux's arm64 is not.
1186 "-fsigned-char" | "-fno-unsigned-char" => opts.char_signed = Some(true),
1187 "-funsigned-char" | "-fno-signed-char" => opts.char_signed = Some(false),
1188 // And the size of an enumeration, which is the other thing in this group that changes
1189 // the ABI rather than the code.
1190 "-fshort-enums" => opts.short_enums = true,
1191 "-fno-short-enums" => opts.short_enums = false,
1192 // And Microsoft's reading of an anonymous member, which changes the layout of every
1193 // record that writes a tag on one. Nothing is set until one of them is given, because
1194 // the target is the answer otherwise: gcc's mingw build has this on and its Linux
1195 // build has it off.
1196 "-fms-extensions" => opts.ms_extensions = Some(true),
1197 "-fno-ms-extensions" => opts.ms_extensions = Some(false),
1198 // And the request, which is the one that cannot be granted. It is a real difference and
1199 // not a preference: two files each writing `int g;` link under `-fcommon` and are a
1200 // duplicate definition without it, which is the whole reason the flag survives.
1201 "-fcommon" => {
1202 return Err(err(
1203 "a tentative definition is written into .bss as its own symbol here, and \
1204 nothing emits the common symbol this asks the linker to merge. Give the \
1205 variable a definition in one file and declare it extern in the others",
1206 ));
1207 }
1208 // Both directions of this one are recorded, and what they decide is whether lowering
1209 // names the type each access goes through. Turning it off is the front end leaving the
1210 // name off rather than a pass being told to ignore one it can see, which is one
1211 // condition in one place, and it is the reading that survives link time optimization:
1212 // a unit built with the flag off keeps its own answer when its bodies end up in a
1213 // module beside bodies that were not.
1214 //
1215 // Nothing in the pipeline reads those names yet. Layer 3 of the alias analysis does
1216 // and is tested, and no pass at any level asks the alias analysis anything today, so
1217 // no program compiles differently for having passed this. The flag is wired anyway,
1218 // because the change that makes a pass ask is not the change anybody will remember to
1219 // wire it in, and a flag that is taken and dropped once the names mean something is
1220 // the miscompilation `spec/04-driver-and-cli.md` section 4.1 warns about in as many
1221 // words.
1222 "-fstrict-aliasing" => opts.strict_aliasing = true,
1223 "-fno-strict-aliasing" => opts.strict_aliasing = false,
1224 // The same shape of answer for the same reason, and the flag the kernel writes beside
1225 // the one above it.
1226 //
1227 // Nothing here concludes that a pointer is not null from the fact that it was
1228 // dereferenced. There is no such conclusion to draw from, because no pass records one:
1229 // a load says where it read and nothing else, and a comparison against null is an
1230 // ordinary comparison of two values the optimizer has no fact about. So a function
1231 // that reads through a pointer and then tests it keeps the test, which is what the
1232 // kernel wants and what `-fno-delete-null-pointer-checks` asks for, and what gcc has
1233 // to be asked for because it draws the conclusion by default.
1234 //
1235 // `-fdelete-null-pointer-checks` is the request to draw it, and it goes the way
1236 // `-fstrict-aliasing` does: assuming less than was asked for costs speed and not
1237 // correctness, and `-O2` implies it, so refusing it would stop builds for nothing.
1238 "-fdelete-null-pointer-checks" | "-fno-delete-null-pointer-checks" => {}
1239 // The floating point group, which goes the same way and for the same reason, and which
1240 // is worth writing out because the reason is easy to get backwards.
1241 //
1242 // Each of these has a restrictive spelling and a permissive one. The restrictive ones,
1243 // `-frounding-math` and `-ftrapping-math`, say that the rounding mode may have been
1244 // changed and that an exception raised by an operation may be looked at, so an
1245 // arithmetic the compiler folds at compile time is an arithmetic whose rounding and
1246 // whose exception the program does not get. Nothing here folds any floating point
1247 // arithmetic in a function body: `0.1 + 0.2` is an `fadd` and `1.0 / 0.0` is a divide
1248 // that runs, at every level. So both of those describe what already happens.
1249 //
1250 // The permissive ones are the other half, and they are licences rather than requests
1251 // for an answer. `-fno-rounding-math` says the rounding mode is the default one and
1252 // `-fno-trapping-math` says nothing looks at the exceptions, which together are
1253 // permission to fold. Not folding is the conservative side of that permission and is
1254 // what a program is entitled to whichever was written, so `-fno-rounding-math` costs
1255 // speed and not correctness, which is the test section 4.1 puts a licence through.
1256 "-frounding-math" | "-fno-rounding-math" => {}
1257 // `-fno-trapping-math` is the one of the four that is kept, because there is one
1258 // conversion this compiler does not fold and gcc folds under it, and the two answers
1259 // differ. Converting a constant floating value to an integer type it does not fit in
1260 // is undefined behaviour rather than a value: left to the hardware it is one
1261 // instruction and the answer is the integer indefinite value, and folded it is the
1262 // nearest end of the integer's range. Both compilers leave it to the instruction by
1263 // default and gcc folds it under this flag, so a program built with it and compiled
1264 // without it gets a different number rather than a slower one. `-ftrapping-math` is
1265 // gcc's default, so a build spelling it out is asking for what it already has.
1266 //
1267 // The rest of the family goes with it, `-ffast-math` included, and all of them are
1268 // taken now. Each is a licence rather than a request and nothing here folds floating
1269 // point arithmetic, so the code does not change. What does change is the macros gcc
1270 // defines for each licence, which a header reads, and the startup file `-ffast-math`
1271 // links, which puts the hardware in flush to zero mode. Both are done after the loop,
1272 // because the family is a set of switches over the same fields and the last word on
1273 // each of them is the end of the command line.
1274 "-ftrapping-math"
1275 | "-fno-trapping-math"
1276 | "-ffast-math"
1277 | "-fno-fast-math"
1278 | "-funsafe-math-optimizations"
1279 | "-fno-unsafe-math-optimizations"
1280 | "-fmath-errno"
1281 | "-fno-math-errno"
1282 | "-ffinite-math-only"
1283 | "-fno-finite-math-only"
1284 | "-fsigned-zeros"
1285 | "-fno-signed-zeros"
1286 | "-freciprocal-math"
1287 | "-fno-reciprocal-math"
1288 | "-fassociative-math"
1289 | "-fno-associative-math" => math_flags.push(arg),
1290 // Whether the startup file that sets flush to zero is linked, asked directly. gcc
1291 // links it for a shared object too when this is written, which the family does not.
1292 "-mdaz-ftz" => daz_ftz = Some(true),
1293 "-mno-daz-ftz" => daz_ftz = Some(false),
1294 // About temporary files rather than about code. There is nothing between the phases of
1295 // one compilation here to write to a file in the first place.
1296 "-pipe" => {}
1297 // Preprocess the input, which a C compile always does. GCC has it for Fortran, and
1298 // meson writes it when it asks a compiler for its predefined macros.
1299 "-cpp" => {}
1300 // Nothing here writes colour, so all of these are the same answer, and it is the answer
1301 // that costs nothing: the diagnostics come out plain either way and no build depends on
1302 // an escape sequence being there. Taken rather than refused because cmake writes
1303 // `-fdiagnostics-color=always` on every compile line when the generator is ninja, which
1304 // makes this the second most common flag after `-fPIC` to stop a build over a question
1305 // about how the text looks.
1306 "-fdiagnostics-color" | "-fno-diagnostics-color" => {}
1307 _ if arg.starts_with("-fdiagnostics-color=") => {}
1308 // The link flags. None of them changes the compilation, which is why they are
1309 // collected apart from `opts` and why `-lm` on a `-c` line is a note rather than an
1310 // error: it is a thing said to a linker that is not going to run.
1311 "-static" => link.is_static = true,
1312 "-shared" => link.shared = true,
1313 "-r" => link.relocatable = true,
1314 "-pie" => link.pie = Some(true),
1315 "-no-pie" | "-nopie" => link.pie = Some(false),
1316 "-nostdlib" => link.no_stdlib = true,
1317 "-nostartfiles" => link.no_startfiles = true,
1318 "-nodefaultlibs" => link.no_defaultlibs = true,
1319 "-fno-builtins-lib" => link.no_builtins_lib = true,
1320 "-fbuiltins-lib" => link.no_builtins_lib = false,
1321 "-rdynamic" | "-export-dynamic" => link.export_dynamic = true,
1322 "-s" => link.strip = true,
1323 // Into the ordered input list rather than a list of its own, because a great many of
1324 // the linker's options are a bracket around the files after them and an option that
1325 // lost its place among them says nothing. `--whole-archive` is the one that found this.
1326 "-Xlinker" => {
1327 let next = args.get(i).ok_or_else(|| err("-Xlinker requires an argument"))?;
1328 i += 1;
1329 inputs.push(Input::linker(next));
1330 }
1331 _ if arg.starts_with("-Wl,") => {
1332 // Commas separate arguments rather than being part of one, which is what makes
1333 // `-Wl,-rpath,/opt/lib` two words to the linker and one word here.
1334 inputs.extend(arg["-Wl,".len()..].split(',').map(Input::linker));
1335 }
1336 _ if arg.starts_with("-fuse-ld=") => {
1337 link.use_ld = Some(arg["-fuse-ld=".len()..].to_owned());
1338 }
1339 _ if arg.starts_with("-l") && arg.len() > 2 => {
1340 inputs.push(Input::library(&arg[2..]));
1341 }
1342 "-l" => {
1343 let next = args.get(i).ok_or_else(|| err("-l requires an argument"))?;
1344 i += 1;
1345 inputs.push(Input::library(next));
1346 }
1347 _ if arg.starts_with("-L") => {
1348 link.search.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1349 }
1350 _ if arg.starts_with("-B") => {
1351 link.prefixes.push(PathBuf::from(joined_or_next(arg, 2, args, &mut i)?));
1352 }
1353 _ if arg.starts_with("-j") => {
1354 jobs = Jobs::parse(&arg[2..]).map_err(err)?;
1355 }
1356 _ if arg.starts_with("--sysroot=") => {
1357 sysroot = Some(PathBuf::from(&arg["--sysroot=".len()..]));
1358 }
1359 _ if arg.starts_with("--target=") => {
1360 let t = &arg["--target=".len()..];
1361 // The same string again, as the model that has room for a libc version. A spelling
1362 // the three field parser took and this one does not is not an error, because the
1363 // one that decides what is compiled has already accepted it and the only thing
1364 // lost is a version nobody asked for.
1365 pinned = t.parse().ok();
1366 // The other way round is a deployment target the three field parser has no room
1367 // for, `aarch64-macos.13`, and the triple is the one the tuple narrows to.
1368 opts.target = match t.parse() {
1369 Ok(triple) => triple,
1370 Err(e) => {
1371 pinned.and_then(Triple::from_tuple).ok_or_else(|| err(format!("{e}")))?
1372 }
1373 };
1374 }
1375 _ if arg.starts_with("--emit=") => {
1376 let k = &arg["--emit=".len()..];
1377 opts.emit = k
1378 .parse()
1379 .map_err(|()| err(format!("unknown --emit kind `{k}`, see --help")))?;
1380 }
1381 // A bare `-O` is `-O1`, which is what GCC has and what a hand written makefile tends
1382 // to write. `-Og` is GCC's level for a build somebody is going to step through, and
1383 // it is `-O1` with the transformations that move code around left out; this compiler
1384 // has no such level yet, so it is the nearest one and `--print-pipeline` says what
1385 // that came to rather than the flag pretending otherwise.
1386 "-O" | "-Og" => {
1387 opts.opt_level = rucc_session::OptLevel::O1;
1388 ofast = false;
1389 }
1390 // The union of `-O3` and `-ffast-math`. The second half is a default rather than a
1391 // flag, which is why it is remembered here and applied after the loop: a later level
1392 // takes it back, and so does a `-fno-fast-math` written on either side of it.
1393 "-Ofast" => {
1394 opts.opt_level = rucc_session::OptLevel::O3;
1395 ofast = true;
1396 }
1397 _ if arg.starts_with("-O") => {
1398 ofast = false;
1399 opts.opt_level = arg[2..]
1400 .parse()
1401 .map_err(|()| err(format!("unknown optimization level `{arg}`")))?;
1402 }
1403 // How far a multiply and an addition may be fused into one rounding. Before the
1404 // optimizer's `-f` family below for the reason the ones under it are, and kept rather
1405 // than dropped because it is the one flag in its group this compiler could act on: it
1406 // rides into the IR as an attribute on each function with a body, so the day the code
1407 // generator forms an `fma` it already knows which functions were given permission.
1408 // Nothing forms one today, under any value of this and under any `-march=`.
1409 _ if arg.starts_with("-ffp-contract=") => {
1410 let how = &arg["-ffp-contract=".len()..];
1411 opts.fp_contract = how.parse().map_err(|()| {
1412 err(format!("`{how}` is not a contraction, which is fast, on or off"))
1413 })?;
1414 }
1415 // How much of an expression may be computed wider than it was written. The values are
1416 // gcc's and so is the refusal of anything else, and none of the three changes anything
1417 // here: an operation is computed in the type C says it is on every target this compiler
1418 // has a back end for, so `__FLT_EVAL_METHOD__` is 0 and `standard` is already what
1419 // happens. `fast` and `16` are permission to be wider, which is a licence this takes
1420 // and does not use, the same way the two above are. The flag is worth taking because
1421 // glibc's headers and a good deal of configure output write it, and because the answer
1422 // it asks about is one this compiler can state rather than guess at: there is no x87
1423 // target here, which is the machine the whole question was invented for.
1424 // Whether a local and a spilled value that are never both wanted may be the same bytes
1425 // of the frame. gcc's three values, and two of them mean the same thing here: what rucc
1426 // shares is a local whose address provably never leaves the function, which is narrower
1427 // than `named_vars` and narrower still than `all`, so both of them get it. `none` is
1428 // the one that changes anything, and it is the flag a program that reads a local
1429 // through a pointer it kept past the end of the block writes.
1430 _ if arg.starts_with("-fstack-reuse=") => {
1431 let how = &arg["-fstack-reuse=".len()..];
1432 opts.stack_reuse = match how {
1433 "all" | "named_vars" => Some(true),
1434 "none" => Some(false),
1435 _ => {
1436 return Err(err(format!(
1437 "`{how}` is not a stack reuse, which is all, named_vars or none"
1438 )));
1439 }
1440 };
1441 }
1442 _ if arg.starts_with("-fexcess-precision=") => {
1443 let how = &arg["-fexcess-precision=".len()..];
1444 if !matches!(how, "16" | "fast" | "standard") {
1445 return Err(err(format!(
1446 "`{how}` is not an excess precision, which is 16, fast or standard"
1447 )));
1448 }
1449 }
1450 // Which front of a path is rewritten before it reaches the output, which is how a
1451 // build gets the same bytes out of two different directories. The four spellings are
1452 // one flag each into three lists, and `-ffile-prefix-map=` is the three of them at
1453 // once. Only the macro list does anything today, because `__FILE__` is the only place
1454 // a path reaches the output: there is no DWARF and no profile data yet, so the other
1455 // two are recorded for the work that will read them. The argument splits at the last
1456 // `=` rather than the first, which is gcc's rule and is what lets a directory with an
1457 // `=` in its name be the old half.
1458 _ if arg.starts_with("-fmacro-prefix-map=") => {
1459 let (old, new) = rewrite(arg, "-fmacro-prefix-map=")?;
1460 opts.prefix_map.macros.push(old, new);
1461 }
1462 _ if arg.starts_with("-fdebug-prefix-map=") => {
1463 let (old, new) = rewrite(arg, "-fdebug-prefix-map=")?;
1464 opts.prefix_map.debug.push(old, new);
1465 }
1466 _ if arg.starts_with("-fprofile-prefix-map=") => {
1467 let (old, new) = rewrite(arg, "-fprofile-prefix-map=")?;
1468 opts.prefix_map.profile.push(old, new);
1469 }
1470 _ if arg.starts_with("-ffile-prefix-map=") => {
1471 let (old, new) = rewrite(arg, "-ffile-prefix-map=")?;
1472 opts.prefix_map.macros.push(old, new);
1473 opts.prefix_map.debug.push(old, new);
1474 opts.prefix_map.profile.push(old, new);
1475 }
1476 // A whole optimization rather than a flag, and the family is taken rather than
1477 // refused because of what ignoring it does. There is none of it here yet, so a build
1478 // that asks for it gets a program that is correct and slower than it could have been,
1479 // which is what section 4.1 means by a hint about speed and what every compilation at
1480 // `-O0` already is. The objects settle the rest of the argument: gcc's `-flto` object
1481 // holds the bytecode and no machine code at all, and every object here holds the code,
1482 // which is exactly what `-ffat-lto-objects` asks gcc for. So a build passing `-flto`
1483 // to this compiler gets objects that are more usable than the ones it asked for rather
1484 // than different ones. Every value is still checked against gcc's, because somebody
1485 // who wrote `-flto=thin` meant clang and had better hear about it here.
1486 "-flto" => opts.lto.requested = true,
1487 "-fno-lto" => opts.lto.requested = false,
1488 _ if arg.starts_with("-flto=") => {
1489 let how = &arg["-flto=".len()..];
1490 opts.lto.jobs = how.parse().map_err(|()| {
1491 err(format!(
1492 "`{how}` is not a number of link time jobs, which is auto, jobserver or a \
1493 count above zero"
1494 ))
1495 })?;
1496 opts.lto.requested = true;
1497 }
1498 _ if arg.starts_with("-flto-partition=") => {
1499 let how = &arg["-flto-partition=".len()..];
1500 opts.lto.partition = how.parse().map_err(|()| {
1501 err(format!(
1502 "`{how}` is not a partitioning model, which is balanced, 1to1, one, max \
1503 or none"
1504 ))
1505 })?;
1506 }
1507 _ if arg.starts_with("-flto-compression-level=") => {
1508 let how = &arg["-flto-compression-level=".len()..];
1509 let level =
1510 how.parse::<u8>().ok().filter(|level| *level <= 19).ok_or_else(|| {
1511 err(format!("`{how}` is not a compression level, 0 to 19"))
1512 })?;
1513 opts.lto.compression = Some(level);
1514 }
1515 // Whether the object keeps its machine code as well as the bytecode. It always does
1516 // here, so the first of these describes what happens and the second asks for an object
1517 // with less in it, which is a smaller file and not a different program, so both are
1518 // taken.
1519 "-ffat-lto-objects" | "-fno-fat-lto-objects" => {}
1520 // Whether the linker is handed a plugin that does the link time work. The design in
1521 // `spec/09-optimizer.md` has this driver doing that work itself and never loading a
1522 // plugin into anybody, so neither answer is a question it has to hold.
1523 "-fuse-linker-plugin" | "-fno-use-linker-plugin" => {}
1524 // Reading a profile back. Taken for the reason the family above it is: nothing here
1525 // reads one, so a build that asks gets the program it would have got anyway, and gcc
1526 // itself produces a byte for byte identical object from `-fprofile-use` when there are
1527 // no counts beside the file. The path is recorded for the pass that will read it. The
1528 // warning gcc prints when it looked and found nothing is deliberately not copied,
1529 // because nothing here looks, and a warning about a file that was never opened would
1530 // fire on the builds that have a perfectly good profile as well as on the ones that
1531 // do not.
1532 "-fprofile-use" => opts.profile_data.requested = true,
1533 "-fno-profile-use" => opts.profile_data.requested = false,
1534 _ if arg.starts_with("-fprofile-use=") => {
1535 opts.profile_data.path = Some(arg["-fprofile-use=".len()..].to_string());
1536 opts.profile_data.requested = true;
1537 }
1538 _ if arg.starts_with("-fprofile-dir=") => {
1539 opts.profile_data.dir = Some(arg["-fprofile-dir=".len()..].to_string());
1540 }
1541 "-fprofile-abs-path" => opts.profile_data.absolute = true,
1542 "-fno-profile-abs-path" => opts.profile_data.absolute = false,
1543 "-fprofile-correction" => opts.profile_data.correction = true,
1544 "-fno-profile-correction" => opts.profile_data.correction = false,
1545 "-fprofile-partial-training" => opts.profile_data.partial_training = true,
1546 "-fno-profile-partial-training" => opts.profile_data.partial_training = false,
1547 // Writing the counts rather than reading them, which is refused rather than taken and
1548 // is the same line `-gsplit-dwarf` falls on the far side of. Ignoring these means a
1549 // file a build declared as an output never appears: the instrumented program writes a
1550 // `.gcda` as it exits and `-ftest-coverage` writes a `.gcno` beside the object, and a
1551 // two stage build that got neither would go on to optimize against no counts at all
1552 // and report coverage of nothing, with nothing along the way saying so. The objects
1553 // say the rest: gcc's `-fprofile-generate` object holds 375 bytes of code where a
1554 // plain one holds 71, and 296 bytes of counters that a plain one does not have, so
1555 // this is a flag that changes the output rather than a hint about speed.
1556 "-fprofile-arcs"
1557 | "--coverage"
1558 | "-fcondition-coverage"
1559 | "-fpath-coverage"
1560 | "-fprofile-generate" => {
1561 return Err(err(format!(
1562 "{arg}: this compiler does not instrument for profiling, and a build that \
1563 expects the counts a run of the instrumented program writes would optimize \
1564 against nothing on its second pass, see spec/04-driver-and-cli.md"
1565 )));
1566 }
1567 _ if arg.starts_with("-fprofile-generate=") => {
1568 return Err(err(format!(
1569 "{arg}: this compiler does not instrument for profiling, and a build that \
1570 expects the counts a run of the instrumented program writes would optimize \
1571 against nothing on its second pass, see spec/04-driver-and-cli.md"
1572 )));
1573 }
1574 "-ftest-coverage" => {
1575 return Err(err(format!(
1576 "{arg}: this compiler writes no `.gcno` file beside the object, and a build \
1577 that expects one would wait for a file that never arrives, see \
1578 spec/04-driver-and-cli.md"
1579 )));
1580 }
1581 // The rest of the family describes instrumentation that is refused above, so what is
1582 // left to do with them is check them and drop them. They are checked because a
1583 // misspelling in a distribution's flags is worth finding here rather than on the day
1584 // the instrumentation lands, and dropped because there is nothing for an answer about
1585 // how a counter is written to be an answer about.
1586 _ if arg.starts_with("-fprofile-update=") => {
1587 let how = &arg["-fprofile-update=".len()..];
1588 if !matches!(how, "single" | "atomic" | "prefer-atomic") {
1589 return Err(err(format!(
1590 "`{how}` is not a profile update method, which is single, atomic or \
1591 prefer-atomic"
1592 )));
1593 }
1594 }
1595 _ if arg.starts_with("-fprofile-reproducible=") => {
1596 let how = &arg["-fprofile-reproducible=".len()..];
1597 if !matches!(how, "serial" | "parallel-runs" | "multithreaded") {
1598 return Err(err(format!(
1599 "`{how}` is not a profile reproducibility method, which is serial, \
1600 parallel-runs or multithreaded"
1601 )));
1602 }
1603 }
1604 "-fprofile-values" | "-fno-profile-values" | "-fprofile-info-section" => {}
1605 "-fno-test-coverage" | "-fno-profile-arcs" | "-fno-profile-generate" => {}
1606 _ if arg.starts_with("-fprofile-filter-files=")
1607 || arg.starts_with("-fprofile-exclude-files=")
1608 || arg.starts_with("-fprofile-note=") => {}
1609 // What every name gets when nothing in the source said, which the attribute in the
1610 // source overrides rather than the other way round. Before the optimizer's `-f`
1611 // family below for the reason the tier below it is.
1612 _ if arg.starts_with("-fvisibility=") => {
1613 let seen = &arg["-fvisibility=".len()..];
1614 opts.visibility = seen.parse().map_err(|()| {
1615 err(format!(
1616 "`{seen}` is not a visibility, which is default, hidden, internal or \
1617 protected"
1618 ))
1619 })?;
1620 }
1621 // Which edges of a control flow transfer are checked. Before the optimizer's `-f`
1622 // family below for the reason the two above it are, and last of the three so that the
1623 // bare spelling and the negative one are matched exactly rather than by this.
1624 _ if arg.starts_with("-fcf-protection=") => {
1625 let edges = &arg["-fcf-protection=".len()..];
1626 opts.control = edges.parse().map_err(|()| {
1627 err(format!(
1628 "`{edges}` is not a control flow protection, which is full, branch, \
1629 return, none or check"
1630 ))
1631 })?;
1632 }
1633 // How much room every function opens with for something to be written over later.
1634 // Before the optimizer's `-f` family below for the reason the ones above it are.
1635 _ if arg.starts_with("-fpatchable-function-entry=") => {
1636 let room = &arg["-fpatchable-function-entry=".len()..];
1637 opts.patchable = room.parse().map_err(|()| {
1638 err(format!(
1639 "`{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"
1640 ))
1641 })?;
1642 }
1643 // The memory safety monitor, from section 15.4 of
1644 // `spec/safe-memory/15-integration.md`. Before the optimizer's `-f` family below,
1645 // because a pass that took the name `safety=detect` would otherwise be handed the
1646 // flag, and the tier is not a pass.
1647 _ if arg.starts_with("-fsafety=") => {
1648 let tier = &arg["-fsafety=".len()..];
1649 opts.safety = tier.parse().map_err(|()| {
1650 err(format!(
1651 "`{tier}` is not a safety tier, which is off, detect, enforce or kernel"
1652 ))
1653 })?;
1654 }
1655 // Whether padding participates, from section 9.3 of document 09. Spelled out rather
1656 // than folded into the tier because it is a departure somebody who has read that
1657 // section makes, and the two defaults it describes are a property of what is being
1658 // built rather than of how much checking is wanted.
1659 _ if arg.starts_with("-fsafety-init=") => {
1660 let mode = &arg["-fsafety-init=".len()..];
1661 opts.padding = mode.parse().map_err(|()| {
1662 err(format!("`{mode}` is not a padding mode, which is padding or nopadding"))
1663 })?;
1664 }
1665 // Row S4, from section 9.4 of document 09. A bare flag with no value, because the
1666 // strict form of that section needs a member id the front end does not name yet and
1667 // accepting the spelling for it would be accepting a promise this build cannot keep.
1668 // Before `-fno-` is looked at below, for the reason the tier is.
1669 "-fsafety-subobject" => opts.subobject = rucc_session::Subobject::Members,
1670 "-fno-safety-subobject" => opts.subobject = rucc_session::Subobject::Off,
1671 _ if arg.starts_with("-fsafety-subobject=") => {
1672 let form = &arg["-fsafety-subobject=".len()..];
1673 return Err(err(format!(
1674 "`{form}` is not a form of -fsafety-subobject. The flag takes no value, and \
1675 the strict form of section 9.4 is tamnd/rucc#967"
1676 )));
1677 }
1678 // Row Y8, from section 9.6 of document 09. A bare flag with no value, for the reason
1679 // the one above has none: there is one form of this check and a spelling that suggested
1680 // otherwise would be promising something. Before `-fno-` is looked at below, the same
1681 // way.
1682 "-fsafety-restrict" => opts.promise = rucc_session::Promise::Blocks,
1683 "-fno-safety-restrict" => opts.promise = rucc_session::Promise::Off,
1684 _ if arg.starts_with("-fsafety-restrict=") => {
1685 let form = &arg["-fsafety-restrict=".len()..];
1686 return Err(err(format!(
1687 "`{form}` is not a form of -fsafety-restrict. The flag takes no value."
1688 )));
1689 }
1690 // Section 9.5's races, which take a value because the section gives them three modes
1691 // and the difference between two of them is which classes get reported rather than how
1692 // much is recorded. `-fno-` is the same as `=off` and is spelled out here for the same
1693 // reason the two above spell theirs out.
1694 _ if arg.starts_with("-fsafety-races=") => {
1695 let mode = &arg["-fsafety-races=".len()..];
1696 opts.races = mode.parse().map_err(|()| {
1697 err(format!("`{mode}` is not a race mode, which is off, metadata or pointer"))
1698 })?;
1699 }
1700 "-fno-safety-races" => opts.races = rucc_session::Races::Off,
1701 // The sanitizers of document 12, which are checks at run time rather than a way of
1702 // generating the same program. Each name is held to gcc 16's list, and what is still
1703 // asked for by the end of the line is answered after the loop, so that a command line
1704 // which turns one on and then off again is a command line that asked for nothing.
1705 //
1706 // Before the optimizer's `-f` family below, for the reason the tier above it is.
1707 _ if arg.starts_with("-fsanitize=") => {
1708 for one in arg["-fsanitize=".len()..].split(',') {
1709 if one == "all" {
1710 // gcc takes `all` only in the negative, because turning every check on at
1711 // once includes checks that contradict each other.
1712 return Err(err(
1713 "`-fsanitize=all` is not a gcc option, only `-fno-sanitize=all` is",
1714 ));
1715 }
1716 if !SANITIZERS.contains(&one) {
1717 return Err(err(format!(
1718 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1719 )));
1720 }
1721 if !sanitizers.contains(&one) {
1722 sanitizers.push(one);
1723 }
1724 }
1725 }
1726 _ if arg.starts_with("-fno-sanitize=") => {
1727 for one in arg["-fno-sanitize=".len()..].split(',') {
1728 if one == "all" {
1729 sanitizers.clear();
1730 continue;
1731 }
1732 if !SANITIZERS.contains(&one) {
1733 return Err(err(format!(
1734 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1735 )));
1736 }
1737 sanitizers.retain(|asked| *asked != one);
1738 }
1739 }
1740 // What a check does when it fires, and where the records about the checked objects go.
1741 // Each of them is an answer about the sanitizers refused after the loop, so there is
1742 // nothing left for them to change here. The names are still held to the list, because
1743 // a misspelling in a build's flags is worth finding when the compiler reads it.
1744 _ if arg.starts_with("-fsanitize-recover=")
1745 || arg.starts_with("-fno-sanitize-recover=")
1746 || arg.starts_with("-fsanitize-trap=")
1747 || arg.starts_with("-fno-sanitize-trap=") =>
1748 {
1749 // The guard above matched on a spelling that has an `=` in it, so the tail is
1750 // whatever follows the first one.
1751 let how = arg.split_once('=').map_or("", |(_, rest)| rest);
1752 for one in how.split(',') {
1753 if one != "all" && !SANITIZERS.contains(&one) {
1754 return Err(err(format!(
1755 "`{one}` is not a sanitizer, see spec/04-driver-and-cli.md section 4.7"
1756 )));
1757 }
1758 }
1759 }
1760 "-fsanitize-undefined-trap-on-error"
1761 | "-fsanitize-address-use-after-scope"
1762 | "-fno-sanitize-address-use-after-scope" => {}
1763 _ if arg.starts_with("-fsanitize-sections=") => {}
1764 // Counting which edges a run reached, which is how a fuzzer knows an input was worth
1765 // keeping. Refused rather than dropped, because a fuzzer whose calls into
1766 // `__sanitizer_cov_*` were never generated runs blind and reports coverage of nothing,
1767 // and there is no point in the campaign where that announces itself.
1768 _ if arg.starts_with("-fsanitize-coverage=") => {
1769 let how = &arg["-fsanitize-coverage=".len()..];
1770 for one in how.split(',') {
1771 if !matches!(one, "trace-pc" | "trace-cmp") {
1772 return Err(err(format!(
1773 "`{one}` is not a coverage instrumentation, which is trace-pc or \
1774 trace-cmp"
1775 )));
1776 }
1777 }
1778 return Err(err(format!(
1779 "{arg}: this compiler generates no coverage callbacks, and a fuzzer built \
1780 with it would run without any feedback at all, see \
1781 spec/04-driver-and-cli.md section 4.7"
1782 )));
1783 }
1784 // The optimizer's own flags, from section 9.10 of `spec/09-optimizer.md`. These come
1785 // after every `-f` the rest of the compiler answers to, so a pass can never take a
1786 // name that already means something else on the command line.
1787 _ if arg.starts_with("-fpass-fuel=") => {
1788 let (name, count) = arg["-fpass-fuel=".len()..]
1789 .split_once('=')
1790 .ok_or_else(|| err("-fpass-fuel= is spelled <pass>=<count>"))?;
1791 if rucc_opt::pass::find(name).is_none() {
1792 return Err(err(format!(
1793 "`{name}` is not a pass this compiler has, see --print-pipeline"
1794 )));
1795 }
1796 let count: u32 = count
1797 .parse()
1798 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1799 opts.pass_fuel.push((name.to_owned(), count));
1800 }
1801 _ if arg.starts_with("-fpass-fuel-global=") => {
1802 let count = &arg["-fpass-fuel-global=".len()..];
1803 let count: u32 = count
1804 .parse()
1805 .map_err(|_| err(format!("`{count}` is not a number of transformations")))?;
1806 opts.pass_fuel_global = Some(count);
1807 }
1808 _ if arg.starts_with("-frucc-trace=") => {
1809 let path = &arg["-frucc-trace=".len()..];
1810 if path.is_empty() {
1811 return Err(err("-frucc-trace= needs a file to write to"));
1812 }
1813 opts.trace = Some(path.to_owned());
1814 }
1815 // Everything from `-fopt-info` to the end of the argument, which is optional
1816 // keywords joined by hyphens and an optional `=<file>`. Checked here rather than
1817 // where the remarks are printed, because by then the compilation somebody wanted
1818 // to hear about is over.
1819 _ if arg == "-fopt-info"
1820 || arg.starts_with("-fopt-info=")
1821 || arg.starts_with("-fopt-info-") =>
1822 {
1823 let rest = &arg["-fopt-info".len()..];
1824 let (kinds, file) = match rest.split_once('=') {
1825 Some((kinds, file)) => (kinds, Some(file)),
1826 None => (rest, None),
1827 };
1828 let kinds = kinds.strip_prefix('-').unwrap_or(kinds);
1829 rucc_opt::Wants::none().add(kinds).map_err(err)?;
1830 opts.opt_info.push(kinds.to_owned());
1831 if let Some(file) = file {
1832 if file.is_empty() {
1833 return Err(err("-fopt-info= was given no file to write to"));
1834 }
1835 opts.opt_info_file = Some(file.to_owned());
1836 }
1837 }
1838 _ if arg.starts_with("-fdump-ir=") => {
1839 // Checked here rather than where the dumps are taken, because the compilation
1840 // that would have been dumped is over by then.
1841 let spec = &arg["-fdump-ir=".len()..];
1842 rucc_opt::Dumps::default().add(spec).map_err(err)?;
1843 opts.dump_ir.push(spec.to_owned());
1844 }
1845 // Before the bare `-f<pass>` below, because a pass called `enable-something` would
1846 // otherwise take the flag away from the gate. Checked here rather than where the
1847 // pipeline reads it, for the reason that applies to all of these: a misspelled pass
1848 // name that quietly gated nothing looks exactly like a pass that is not the guilty
1849 // one, and a bisection would carry on past the thing it was looking for.
1850 _ if arg.starts_with("-fdisable-") || arg.starts_with("-fenable-") => {
1851 let on = arg.starts_with("-fenable-");
1852 let spec = &arg[if on { "-fenable-".len() } else { "-fdisable-".len() }..];
1853 rucc_opt::Gates::default().add(on, spec).map_err(err)?;
1854 opts.pass_gates.push((on, spec.to_owned()));
1855 }
1856 // gcc's spelling for a pass this compiler has under a shorter name. It goes above the
1857 // two arms below rather than into the pile of gcc pass names further down, because the
1858 // pass is here: dropping the flag would leave a build that asked for unrolling without
1859 // it, and refusing it stops the build outright, which is what libtommath's makefile
1860 // ran into. `-funroll-all-loops` is deliberately not in here: gcc's is the one that
1861 // unrolls without a trip count, which is a different and usually worse thing.
1862 "-funroll-loops" => opts.passes.push(("unroll".to_owned(), true)),
1863 "-fno-unroll-loops" => opts.passes.push(("unroll".to_owned(), false)),
1864 // Here rather than through the two arms below, because what this names is not a
1865 // `rucc_opt::Pass`. Section 34.6's propagation is a module at a time and everything in
1866 // the pass list is one function at a time. `-fipa-cp-clone` is deliberately not here:
1867 // gcc turns that one on at `-O3` and it is in the list of what M4 does not build.
1868 "-fipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), true)),
1869 "-fno-ipa-cp" => opts.passes.push((rucc_opt::ipcp::NAME.to_owned(), false)),
1870 // The other half of the same section, here for the same reason, and `-fipa-sra` in gcc
1871 // is the aggregate splitting as well as the parameter removal. Asking for it gets the
1872 // half that is built.
1873 "-fipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), true)),
1874 "-fno-ipa-sra" => opts.passes.push((rucc_opt::ipasra::NAME.to_owned(), false)),
1875 // And the printf family fold, which is a module at a time for the same reason and so is
1876 // not a `rucc_opt::Pass` either. gcc has no flag of its own for this one, since
1877 // `-fno-builtin` already turns it off along with everything else the standard names
1878 // mean. This spelling is for taking one thing away during a bisection without taking
1879 // the rest of section 20.1 away with it.
1880 "-flibcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), true)),
1881 "-fno-libcall" => opts.passes.push((rucc_opt::libcall::NAME.to_owned(), false)),
1882 _ if arg.strip_prefix("-fno-").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1883 opts.passes.push((arg["-fno-".len()..].to_owned(), false));
1884 }
1885 _ if arg.strip_prefix("-f").is_some_and(|n| rucc_opt::pass::find(n).is_some()) => {
1886 opts.passes.push((arg["-f".len()..].to_owned(), true));
1887 }
1888 // The flags that name a pass of gcc's own. They arrive from the torture suite, where a
1889 // program reduced from a miscompilation usually names the pass that miscompiled it on
1890 // its `dg-options` line, and they arrive from hand written build files for the same
1891 // reason. Section 4.1 sorts a flag by what the output would be without it, and by that
1892 // rule these are one pile: a flag that turns one of gcc's passes on or off is asking
1893 // for a compiler that does not exist here, and the program it is attached to is a
1894 // correctness test that passes either way. Turning on a pass we do not have costs
1895 // speed, turning off a pass we do not have costs nothing, and neither changes what the
1896 // program computes.
1897 //
1898 // rucc's own pass names are matched above this, so `-fno-dce` turns off the dce this
1899 // compiler has rather than landing here, and the day one of these names becomes a pass
1900 // here it stops being taken and dropped without anybody editing this list.
1901 //
1902 // Two of them are prefixes rather than names, which is the one place this file takes a
1903 // family instead of a flag. gcc files its gimple passes under `-ftree-` and its
1904 // interprocedural passes under `-fipa-`, both namespaces are pass selection and
1905 // nothing else, and there is no member of either that changes the meaning of a program
1906 // that was already correct. The rest are written out one at a time, because they live
1907 // in the flat `-f` namespace where the neighbours do change meanings.
1908 _ if arg.starts_with("-ftree-") || arg.starts_with("-fno-tree-") => {}
1909 _ if arg.starts_with("-fipa-") || arg.starts_with("-fno-ipa-") => {}
1910 "-fexpensive-optimizations" | "-fno-expensive-optimizations" => {}
1911 "-fmodulo-sched" | "-fno-modulo-sched" => {}
1912 "-fvect-cost-model" | "-fno-vect-cost-model" => {}
1913 _ if arg.starts_with("-fvect-cost-model=") || arg.starts_with("-fsimd-cost-model=") => {
1914 }
1915 "-fearly-inlining" | "-fno-early-inlining" => {}
1916 // The one of the family that does reach the optimizer, since the step it names is built:
1917 // `-fno-inline` stops a function declared `inline` from being inlined and leaves
1918 // `always_inline` alone, which is what it does in gcc.
1919 "-finline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), true)),
1920 "-fno-inline" => opts.passes.push((rucc_opt::inline::NAME.to_owned(), false)),
1921 // The called once half of the same step, on its own, which leaves the `inline` hint and
1922 // `always_inline` as they are. tamnd/rucc#1966.
1923 "-finline-functions-called-once" => {
1924 opts.passes.push((rucc_opt::inline::ONCE.to_owned(), true));
1925 }
1926 "-fno-inline-functions-called-once" => {
1927 opts.passes.push((rucc_opt::inline::ONCE.to_owned(), false));
1928 }
1929 "-finline-functions"
1930 | "-fno-inline-functions"
1931 | "-finline-small-functions"
1932 | "-fno-inline-small-functions" => {}
1933 "-foptimize-strlen" | "-fno-optimize-strlen" => {}
1934 "-fira-share-spill-slots" | "-fno-ira-share-spill-slots" => {}
1935 // Where a function starts, which is a thing this compiler already decides and so is a
1936 // request it can answer rather than one it has to drop. The bare form asks for the
1937 // target's default and the default here is the sixteen bytes gcc also gives, so it
1938 // says nothing; a number is a floor under every function that did not ask for more
1939 // itself; and the negative form asks for the smallest boundary the target has. gcc 16
1940 // rounds a number that is not a power of two up rather than refusing it, which is what
1941 // `=3` giving `.p2align 2` on x86-64 means, so this rounds too.
1942 "-falign-functions" => opts.align_functions = None,
1943 "-fno-align-functions" => opts.align_functions = Some(MIN_FUNC_ALIGN),
1944 _ if arg.starts_with("-falign-functions=") => {
1945 opts.align_functions = function_alignment(&arg["-falign-functions=".len()..])
1946 .ok_or_else(|| {
1947 err(format!("{arg}: the alignment has to be a number of bytes"))
1948 })?;
1949 }
1950 // The head of every hot loop, which is padded when this is asked for so that a loop that
1951 // fits in a 64 byte line does not cross one. Both directions of the plain form are
1952 // answered. A number is taken and says nothing, because the boundary here is the
1953 // line's and a build that names another is asking for speed rather than for a
1954 // different program.
1955 "-falign-loops" => opts.align_loops = Some(true),
1956 "-fno-align-loops" => opts.align_loops = Some(false),
1957 // The other two of the family, which are about padding in front of any label and in
1958 // front of a label only a jump reaches. This compiler writes neither, and what they
1959 // ask for is speed: a label on a boundary computes what a label off one computes. So
1960 // they are taken and dropped for the reason `-march=` is, and the numbered form of
1961 // the loop flag with them.
1962 _ if arg.starts_with("-falign-labels")
1963 || arg.starts_with("-falign-loops=")
1964 || arg.starts_with("-falign-jumps")
1965 || arg.starts_with("-fno-align-labels")
1966 || arg.starts_with("-fno-align-jumps") => {}
1967 // The charset flags are not in that pile, because an encoding is a statement about
1968 // what the bytes of the source mean rather than about how fast the output is. The
1969 // preprocessor reads UTF-8 and has no converter, so the one name that describes what
1970 // already happens is taken and every other name is refused. Spelled without regard to
1971 // case and with both of the spellings iconv answers to, since a build writes whichever
1972 // one its author typed.
1973 _ if arg.starts_with("-finput-charset=") => {
1974 let name = &arg["-finput-charset=".len()..];
1975 if !name.eq_ignore_ascii_case("utf-8") && !name.eq_ignore_ascii_case("utf8") {
1976 return Err(err(format!(
1977 "-finput-charset={name}: the preprocessor reads UTF-8 and has no \
1978 converter, so a file in another encoding would be read as though it were \
1979 UTF-8 rather than converted",
1980 )));
1981 }
1982 }
1983 // What C has of exceptions, which is a `cleanup` handler an unwind has to run and the
1984 // `__EXCEPTIONS` that tells a header so. The walk is what turns down the handler it has
1985 // no landing pad for, so a unit with none of them is taken whole.
1986 "-fexceptions" => exceptions = Some(true),
1987 "-fno-exceptions" => exceptions = Some(false),
1988 "-fnon-call-exceptions" => opts.non_call_exceptions = true,
1989 "-fno-non-call-exceptions" => opts.non_call_exceptions = false,
1990 // Whether an instruction that could raise one may still be deleted when nothing uses
1991 // what it computes. Nothing here keeps a dead one, and neither does gcc in a C unit
1992 // with no handler around it, so both spellings describe the code as it is.
1993 "-fdelete-dead-exceptions" | "-fno-delete-dead-exceptions" => {}
1994 "-finstrument-functions" => opts.instrument_functions = true,
1995 "-fno-instrument-functions" => opts.instrument_functions = false,
1996 // The unstable options, spelled the way rustc spells them and carrying the same
1997 // promise, which is none: one of these may change or go away in any release. They are
1998 // measurements and debugging aids rather than things a build asks for, which is why
1999 // none of them is in the usage text and all of them are in section 4.11 of
2000 // `spec/04-driver-and-cli.md`.
2001 "-Zverify-each" => opts.verify_each = true,
2002 _ if arg.starts_with("-Zrule-coverage=") => {
2003 let file = &arg["-Zrule-coverage=".len()..];
2004 if file.is_empty() {
2005 return Err(err("-Zrule-coverage= needs a file to write to"));
2006 }
2007 opts.rule_coverage = Some(file.to_owned());
2008 }
2009 _ if arg.starts_with("-Zcycle-accurate-model=") => {
2010 let value = &arg["-Zcycle-accurate-model=".len()..];
2011 opts.cycle_accurate_model = match value {
2012 "yes" | "1" => Some(true),
2013 "no" | "0" => Some(false),
2014 _ => {
2015 return Err(err("-Zcycle-accurate-model= takes yes or no"));
2016 }
2017 };
2018 }
2019 _ if arg.starts_with("-Zswitch=") => {
2020 let shape = &arg["-Zswitch=".len()..];
2021 if rucc_codegen::switch::Force::named(shape).is_none() {
2022 return Err(err("-Zswitch= takes table, tree or walk"));
2023 }
2024 opts.switch_shape = Some(shape.to_owned());
2025 }
2026 _ if arg.starts_with("-Zlowering=") => {
2027 let file = &arg["-Zlowering=".len()..];
2028 if file.is_empty() {
2029 return Err(err("-Zlowering= needs a file to write to"));
2030 }
2031 opts.lowering_dump = Some(file.to_owned());
2032 }
2033 _ if arg.starts_with("-Zregister-pressure=") => {
2034 let file = &arg["-Zregister-pressure=".len()..];
2035 if file.is_empty() {
2036 return Err(err("-Zregister-pressure= needs a file to write to"));
2037 }
2038 opts.register_pressure = Some(file.to_owned());
2039 }
2040 _ if arg.starts_with("-Z") => {
2041 return Err(err(format!(
2042 "`{arg}` is not an unstable option this compiler has, see \
2043 spec/04-driver-and-cli.md section 4.11 for the ones it does"
2044 )));
2045 }
2046 // The word size, which is a statement about the target and is taken as one. A build
2047 // that says the size the target already has is saying nothing, and one that says the
2048 // other size is asking for a target this compiler does not have, which it is told
2049 // rather than being given the wrong one.
2050 "-m64" | "-m32" | "-mx32" => {
2051 let want: u32 = match arg {
2052 "-m64" => 64,
2053 _ => 32,
2054 };
2055 let have = rucc_target::TargetInfo::new(opts.target).pointer_width;
2056 if have != want {
2057 return Err(err(format!(
2058 "{arg} asks for a {want} bit target and {} is {have} bit, use \
2059 --target= to name the one you mean",
2060 opts.target
2061 )));
2062 }
2063 }
2064 // One extension of the x86-64 instruction set, on or off, which is `-msse4.2` and its
2065 // relatives. Only the ones this compiler has the intrinsics for may be turned on for a
2066 // whole unit, because what turning one on does here is define the macro, and a macro
2067 // is a promise to a header that the names behind it exist. Turning one off is taken
2068 // for any name gcc knows, since nothing is promised by it, except for the baseline:
2069 // SSE2 is where the psABI passes a `double`, so a unit without it is a different
2070 // calling convention and not a smaller instruction set.
2071 _ if isa_name(arg).is_some() => {
2072 let Some((_, feature, on)) = isa_name(arg) else { continue };
2073 if on && !feature.honoured() {
2074 return Err(err(format!(
2075 "{arg}: this compiler has no intrinsics for {} yet, so it cannot build a \
2076 whole unit for it",
2077 feature.name()
2078 )));
2079 }
2080 if !on && rucc_target::Isa::baseline().has(feature) {
2081 return Err(err(format!(
2082 "{arg}: {} is part of the x86-64 baseline and the psABI passes values in \
2083 it, so a unit built without it would call and be called differently",
2084 feature.name()
2085 )));
2086 }
2087 isa.read(&arg["-m".len()..]).map_err(|_| err(format!("unknown option `{arg}`")))?;
2088 isa_flag.get_or_insert(arg);
2089 }
2090 // Which processor in the family to build for. What it decides is the extensions of
2091 // the instruction set the unit may assume, which is the macros, and only on x86-64;
2092 // see `rucc_target::isa`. A processor it has no list for is built for as the
2093 // baseline, which is a program that could have been faster rather than a program
2094 // that is wrong, and the same goes for every other target's processors. `-mtune=`
2095 // says what to schedule for and changes nothing a program can see.
2096 _ if arg.starts_with("-march=") => march = Some(&arg["-march=".len()..]),
2097 _ if arg.starts_with("-mtune=") || arg.starts_with("-mcpu=") => {}
2098 // The calling convention, which is not safe to ignore. Taken when it names the one
2099 // the target already uses and refused otherwise.
2100 _ if arg.starts_with("-mabi=") => {
2101 let want = &arg["-mabi=".len()..];
2102 let have = match opts.target.arch {
2103 rucc_target::Arch::X86_64 => "sysv",
2104 rucc_target::Arch::Aarch64 => "lp64",
2105 rucc_target::Arch::Riscv64 => "lp64d",
2106 };
2107 if want != have {
2108 return Err(err(format!(
2109 "{arg}: {} uses the {have} convention and this compiler has no other",
2110 opts.target
2111 )));
2112 }
2113 }
2114 // How far apart the pieces of the program may be. The small model is what we emit and
2115 // it is every hosted program's default; the kernel model is a different one and a
2116 // build that asks for it and does not get it links and then does not run.
2117 "-mcmodel=small" => {}
2118 // clang's spellings of the deployment target, which it takes over a version in the
2119 // tuple. gcc on a Mac takes the first. A target that is not Apple ignores it, as
2120 // clang does, so a makefile that always passes it still builds for Linux.
2121 _ if arg.starts_with("-mmacosx-version-min=")
2122 || arg.starts_with("-mmacos-version-min=") =>
2123 {
2124 let text = &arg[arg.find('=').map_or(arg.len(), |i| i + 1)..];
2125 let version = rucc_tuple::Version::parse(text)
2126 .ok_or_else(|| err(format!("`{text}` in `{arg}` is not a version")))?;
2127 min_version = Some(version);
2128 }
2129 _ if arg.starts_with("-mcmodel=") => {
2130 return Err(err(format!(
2131 "{arg}: this compiler emits the small code model and no other, see \
2132 spec/12-targets.md"
2133 )));
2134 }
2135 // GCC's own scripting language for how the driver builds a command line.
2136 // `spec/04-driver-and-cli.md` section 4.4 settles that we will not have it, so a
2137 // build reaching for it is told which flags do the same job.
2138 _ if arg.starts_with("-specs=") => {
2139 return Err(err(
2140 "-specs= is not supported: the parts of it builds rely on are -B, -L, \
2141 -nostdlib, -nostartfiles and -Wl,, see spec/04-driver-and-cli.md \
2142 section 4.4",
2143 ));
2144 }
2145 // Arguments meant for a separate assembler, which this compiler does not have: it is
2146 // inside it and does not read a command line. Refused rather than dropped, because
2147 // every one of these says something about the output and a build that asked for
2148 // `-Wa,--noexecstack` and was silently given an executable stack got the opposite of
2149 // what it asked for. The `-Wp,` ones this compiler understands were turned into its
2150 // own flags before the loop, so one that reaches here is one it does not.
2151 _ if arg.starts_with("-Wa,") || arg.starts_with("-Wp,") => {
2152 return Err(err(format!(
2153 "`{arg}` is an argument for a separate assembler or preprocessor, and both \
2154 are inside this compiler rather than programs it runs"
2155 )));
2156 }
2157 "-Xassembler" | "-Xpreprocessor" => {
2158 return Err(err(format!(
2159 "{arg} hands an argument to a separate assembler or preprocessor, and both \
2160 are inside this compiler rather than programs it runs"
2161 )));
2162 }
2163 // Everything else in the `-W` family. `spec/04-driver-and-cli.md` section 4.1 has
2164 // this one as a rule about build systems rather than about warnings: autoconf and
2165 // meson find out whether a warning flag exists by passing it and looking at the exit
2166 // status, so the answer has to be gcc's. A name gcc knows is accepted, and one it does
2167 // not is refused, the way gcc refuses clang's names. `-Wno-` of a name nobody knows is
2168 // accepted, because gcc accepts it too, but `-Werror=` and `-Wno-error=` of one are
2169 // not. None of them turns anything on yet, which #485 is about.
2170 _ if arg.starts_with("-W") => {
2171 let name = &arg["-W".len()..];
2172 let named = name.strip_prefix("error=").or_else(|| name.strip_prefix("no-error="));
2173 if let Some(named) = named {
2174 if !warnings::known(named) {
2175 return Err(err(format!("`{arg}`: no option `-W{named}`")));
2176 }
2177 } else if !name.is_empty() && !name.starts_with("no-") && !warnings::known(name) {
2178 return Err(err(format!("unknown option `{arg}`")));
2179 }
2180 }
2181 // Flags that name something this compiler does not do and would not do differently
2182 // if it did. `-fno-ident` is about a comment in the output that we do not write
2183 // either way, and the others are about a way of ordering the compilation that has
2184 // been GCC's only way for twenty years. Section 4.1 asks for the list to be short
2185 // and for adding to it to be deliberate, which is why it is written out here.
2186 "-fno-ident"
2187 | "-fident"
2188 | "-funit-at-a-time"
2189 | "-fno-unit-at-a-time"
2190 | "-shared-libgcc"
2191 | "-static-libgcc"
2192 | "-fpch-deps"
2193 | "-fno-pch-deps" => {}
2194 _ if arg.starts_with('-') && arg.len() > 1 => {
2195 // Silently ignoring an unknown flag is how a build ends up not doing what
2196 // its author asked. spec/13-gnu-compat.md section 13.4 makes this an error
2197 // for the flags that change code generation, and the safe default until the
2198 // flag table is populated is to reject everything we do not know.
2199 return Err(err(format!("unknown option `{arg}`")));
2200 }
2201 _ => inputs.push(Input { path: arg.to_owned(), forced, role: Role::File }),
2202 }
2203 }
2204
2205 // The fetch, before anything that resolves a compilation, because `--fetch` does not describe
2206 // one. It is here rather than in the loop so that `--offline` can forbid it whichever order the
2207 // two were written in, and it is before the refusals below so that a command line asking for a
2208 // sysroot is not told about a sanitizer.
2209 if let Some(named) = fetch {
2210 if fetch_msvc.is_some() {
2211 return Err(err(
2212 "--fetch and --fetch-msvc-sdk are two different commands and this command line \
2213 asked for both. --fetch gets a sysroot this release pins by URL and by hash, and \
2214 --fetch-msvc-sdk gets what is behind Microsoft's licence wall, which no release \
2215 pins and which nobody may republish. Run whichever one you meant",
2216 ));
2217 }
2218 return fetch_action(&named, offline, &inputs);
2219 }
2220 if let Some(named) = fetch_msvc {
2221 return fetch_msvc_action(&named, offline, accepted, &inputs);
2222 }
2223 if accepted {
2224 return Err(err(
2225 "--accept-licence says that Microsoft's Visual Studio Build Tools licence is accepted, \
2226 and nothing on this command line asked for anything that licence covers. \
2227 --fetch-msvc-sdk <tuple> is the command it belongs to, and an ordinary compile \
2228 downloads nothing with it or without it",
2229 ));
2230 }
2231
2232 // Last, so that it lands after every `-isystem` the command line gave. That is GCC's
2233 // order: a directory the user names outranks the compiler's own, and the compiler's own
2234 // outranks the library's. It is pushed after the loop rather than before it because
2235 // `SearchPath` appends within a group and the position is what the order is.
2236 // The same directory the headers were looked for under, because a sysroot is a statement
2237 // about a whole installation and not about half of one.
2238 // After the loop, because `-fno-sanitize=` can take back what an earlier flag asked for and a
2239 // command line that turns a check on and off again has asked for nothing. What is left is
2240 // refused rather than dropped, and it is the one place in this parser where the reason is not
2241 // that the output would differ. A sanitizer is a promise that the program is watched while it
2242 // runs, so a build that asks for one and is quietly given a program with no checks in it does
2243 // not get a slower program or a bigger file, it gets a test suite that passes for the wrong
2244 // reason. `-fsafety=` is the checking this compiler does have, and the message says so, because
2245 // somebody reaching for `-fsanitize=address` wants the nearest thing rather than a list of
2246 // options.
2247 if let Some(first) = sanitizers.first() {
2248 return Err(err(format!(
2249 "-fsanitize={first}: this compiler has no sanitizer instrumentation, and a build that \
2250 asked for one and got none would run its tests unchecked, see \
2251 spec/04-driver-and-cli.md section 4.7. `-fsafety=detect` is the memory checking this \
2252 compiler does have"
2253 )));
2254 }
2255 // The fast math family, replayed in order on top of what `-Ofast` implies. The startup file is
2256 // gcc's spec rather than the fields: it is linked when `-Ofast`, `-ffast-math` or
2257 // `-funsafe-math-optimizations` is still in force at the end of the line, whatever a later
2258 // member took back, and `-mdaz-ftz` decides it outright.
2259 let mut math = Math::default();
2260 let mut trapping = if ofast { math.set_fast(true) } else { true };
2261 for flag in &math_flags {
2262 match *flag {
2263 "-ftrapping-math" => trapping = true,
2264 "-fno-trapping-math" => trapping = false,
2265 "-ffast-math" => trapping = math.set_fast(true),
2266 "-fno-fast-math" => trapping = math.set_fast(false),
2267 "-funsafe-math-optimizations" => trapping = math.set_unsafe(true),
2268 "-fno-unsafe-math-optimizations" => trapping = math.set_unsafe(false),
2269 "-fmath-errno" => math.errno = true,
2270 "-fno-math-errno" => math.errno = false,
2271 "-ffinite-math-only" => math.finite_only = true,
2272 "-fno-finite-math-only" => math.finite_only = false,
2273 "-fsigned-zeros" => math.signed_zeros = true,
2274 "-fno-signed-zeros" => math.signed_zeros = false,
2275 "-freciprocal-math" => math.reciprocal = true,
2276 "-fno-reciprocal-math" => math.reciprocal = false,
2277 "-fassociative-math" => math.associative = true,
2278 "-fno-associative-math" => math.associative = false,
2279 _ => unreachable!("{flag} is not in the family"),
2280 }
2281 }
2282 opts.trapping_math = trapping;
2283 opts.math = math;
2284 let last = |on: &str, off: &str| {
2285 math_flags.iter().rev().find(|f| **f == on || **f == off).is_some_and(|f| *f == on)
2286 };
2287 link.fast_math = ofast
2288 || last("-ffast-math", "-fno-fast-math")
2289 || last("-funsafe-math-optimizations", "-fno-unsafe-math-optimizations");
2290 link.daz_ftz = daz_ftz;
2291 // The extensions, now that the target is known. On x86-64 the processor supplies whatever no
2292 // flag said. Anywhere else there are none to have, and a flag naming one is gcc's unknown
2293 // option there too, so it is refused the same way it would have been had it not looked like
2294 // an x86 flag.
2295 match opts.target.arch {
2296 rucc_target::Arch::X86_64 => {
2297 let base = match march {
2298 Some("native") => native_isa(),
2299 Some(name) => {
2300 rucc_target::Isa::level(name).unwrap_or_else(rucc_target::Isa::baseline)
2301 }
2302 None => rucc_target::Isa::baseline(),
2303 };
2304 opts.isa = isa.over(base);
2305 }
2306 rucc_target::Arch::Aarch64 | rucc_target::Arch::Riscv64 => {
2307 if let Some(flag) = isa_flag {
2308 return Err(err(format!("unknown option `{flag}`")));
2309 }
2310 opts.isa = rucc_target::Isa::NONE;
2311 }
2312 }
2313 opts.exceptions = exceptions.unwrap_or(opts.non_call_exceptions);
2314 link.sysroot = sysroot.clone();
2315 // Where a sysroot for a target that is not this machine would be. Read once, here, rather than
2316 // inside the link line, because a link line that read the environment could only be tested on a
2317 // machine whose environment said the right thing, and the link line is the last thing that
2318 // touches a binary. `spec/cross-compile/13-distribution.md` section 13.2 owns the answer.
2319 link.cache = Some(cache::dir());
2320 // And where a distribution's cross packages would have put a tree for the target, which is only
2321 // read when the target is not this machine and there is no sysroot of ours for it.
2322 link.usr = Some(PathBuf::from("/usr"));
2323 // And the ten field spelling of the target, because the release on it decides two things the
2324 // three field one cannot say: whether a target that is this architecture is still a cross
2325 // compile, and which directory under the cache it is against. After the loop because the last
2326 // `--target=` on the command line is the one that counts.
2327 link.pinned = pinned;
2328 // The deployment target, from the flag if there was one and from the tuple otherwise. Only an
2329 // Apple platform has one: anywhere else a version on the tuple is a libc or a preview number.
2330 if opts.target.os == rucc_target::Os::Darwin {
2331 opts.os_version = min_version.or_else(|| pinned.and_then(TargetTuple::os_version));
2332 }
2333 // After the loop rather than where `-pthread` was read, so that it lands after the objects
2334 // that refer to it. A static link takes the definitions it needs from a library when it
2335 // reaches it and not afterwards, so a library before the objects is a library that answers
2336 // nothing.
2337 if threads {
2338 inputs.push(Input::library("pthread"));
2339 }
2340 if let Some(query) = query {
2341 return Ok(Action::Print(answer(&query, &opts, &link)?));
2342 }
2343 // `-M` and `-MM` produce the rule and nothing else, so the run stops after phase 4 whatever
2344 // else the command line asked for. Read here rather than where the flag was, because a `-c`
2345 // written after it has to lose and the loop cannot know that until it has ended. The output
2346 // file is where the rule goes rather than where an object would have gone, and the last
2347 // phase being the preprocessor is what makes that true without a second rule for it.
2348 if opts.deps.instead_of_compiling {
2349 opts.emit = EmitKind::Preprocessed;
2350 }
2351 if !nostdinc {
2352 opts.search.push_system(runtime::DIR);
2353 // And the library's after ours, which is the other half of the same order. They go on
2354 // here rather than at the point `--target=` or `--sysroot=` was read because either
2355 // one changes the answer and the last word on both is the end of the loop.
2356 //
2357 // Which library's is the question `link::cross_sysroot` answers, and it is asked here so
2358 // that the headers and the libraries come from the same place. A target that is this
2359 // machine reads this machine's headers, and a target that is not reads the ones in the
2360 // sysroot for it rather than the ones next door.
2361 let cross = link::cross_sysroot(opts.target, &link);
2362 let kernel = link::cross_kernel(opts.target, &link);
2363 let distro = link::distro_cross(opts.target, &link);
2364 // And the version of those headers, which only the bundled tree has an answer for. A host
2365 // glibc and a tree the user named both define `__GLIBC_MINOR__` in their own `features.h`,
2366 // and a second definition with a different value is a warning on every file, so the
2367 // condition is the same one that chose the directories.
2368 if cross.is_some() {
2369 let target = pinned.unwrap_or_else(|| opts.target.tuple());
2370 opts.glibc_minor = rucc_sysroot::bundled_glibc_minor(target).map_err(|skew| {
2371 err(format!(
2372 "{skew}; pin a release the tree has, or name a tree that has that one \
2373 with --sysroot"
2374 ))
2375 })?;
2376 }
2377 let system = library::header_dirs(
2378 opts.target,
2379 sysroot.as_deref(),
2380 cross.as_ref(),
2381 kernel.as_ref(),
2382 distro.as_ref(),
2383 );
2384 // The two licence walls of `spec/cross-compile/13-distribution.md` section 13.4, which are
2385 // the only way step 3 comes back with nothing on a hosted target. Section 8.6 asks for the
2386 // answer to name the licence and the lawful ways to get what is behind it, rather than
2387 // leaving a person with an `#include` that failed as though a directory had gone missing.
2388 //
2389 // It is left on the search path instead of refused here, because a program that includes
2390 // none of the library needs none of the SDK and section 8.6 is explicit that targeting the
2391 // platform has to keep working. So the reason waits until an include has actually failed,
2392 // which is the only moment it helps and the only moment it is true.
2393 //
2394 // The condition is that step 3 found nothing at all, so an `SDKROOT`, an `INCLUDE` or a mac
2395 // with Xcode on it all pass through untouched, and `-nostdinc` never reaches this block. A
2396 // `--sysroot` or `-isysroot` passes through as well, even when the tree it names turns out to
2397 // be empty or absent: somebody who wrote a path has already answered the question this
2398 // message asks, and answering it again over the top of a mistyped directory would hide the
2399 // mistake behind a licence notice.
2400 if system.is_empty() && sysroot.is_none() {
2401 let tuple = pinned.unwrap_or_else(|| opts.target.tuple());
2402 if let Some(wall) = rucc_sysroot::Wall::of(tuple) {
2403 opts.search.explain_missing_system(wall.no_headers(&tuple.to_canonical_string()));
2404 }
2405 }
2406 // And whether the tree somebody named is the release they asked for, which is the one
2407 // question left once the directories are settled and the only place both halves of it are
2408 // known. Only for a named tree, because that is the case where the release in the target
2409 // stops deciding anything, and `crate::glibc` is where the rest of the reasoning is.
2410 if sysroot.is_some() {
2411 notes.extend(glibc::skew(opts.target, pinned, &system));
2412 }
2413 for dir in system {
2414 opts.search.push_system(dir);
2415 }
2416 }
2417 // Once, here, rather than as each directory is pushed. A `-I` that names a system
2418 // directory has to lose to the system entry and the system entry is added last, so the
2419 // question cannot be answered until the whole path is known.
2420 opts.search.remove_duplicates();
2421
2422 // The target has to be resolved before the configuration is printed, so this check comes
2423 // after the loop rather than at the point `--print-config` was seen.
2424 if print_config {
2425 return Ok(Action::PrintConfig(Box::new(opts)));
2426 }
2427 if print_pipeline {
2428 return Ok(Action::PrintPipeline(Box::new(opts)));
2429 }
2430 let plan = Plan::new(&opts, &inputs, output.as_deref()).map_err(|e| err(e.message))?;
2431 if print_plan {
2432 return Ok(Action::PrintPlan {
2433 opts: Box::new(opts),
2434 plan: Box::new(plan),
2435 link: Box::new(link),
2436 });
2437 }
2438 Ok(Action::Compile {
2439 opts: Box::new(opts),
2440 plan: Box::new(plan),
2441 link: Box::new(link),
2442 jobs,
2443 verbose,
2444 notes,
2445 })
2446}
2447
2448/// What `--fetch <tuple>` asked for, or why it is not a thing that can be done.
2449///
2450/// The lookup happens here rather than at the point the bytes would move, so that a target this
2451/// release pins nothing for is a refusal from the parser and the only code that runs a downloader is
2452/// code that already knows what it is getting.
2453///
2454/// # Errors
2455///
2456/// [`CliError`] when `--offline` forbade it, when there are input files as well, when the tuple is
2457/// not a target this compiler knows, when its sysroot is behind one of section 13.4's licence walls,
2458/// and when this release pins no artifact for it.
2459fn fetch_action(named: &str, offline: bool, inputs: &[Input]) -> Result<Action, CliError> {
2460 // Not a precedence question. Section 13.2 says `--offline` forbids a fetch entirely, so a
2461 // command line that writes both has asked for two opposite things and the answer is to say so
2462 // rather than to pick one of them.
2463 if offline {
2464 return Err(err(
2465 "--fetch asks for a download and --offline forbids every download, so this command \
2466 line asks for two opposite things. Drop one of them: --offline is how a build says it \
2467 will not reach the network, and --fetch is one of the two things in this compiler \
2468 that reaches it",
2469 ));
2470 }
2471 if let Some(first) = inputs.first() {
2472 return Err(err(format!(
2473 "--fetch gets a sysroot and compiles nothing, so `{}` on the same command line is an \
2474 input that nothing would read",
2475 first.path
2476 )));
2477 }
2478 let target: TargetTuple = named
2479 .parse()
2480 .map_err(|why| err(format!("--fetch {named}: {why}, so there is no sysroot to get")))?;
2481 // The canonical spelling, because that is what a row is named by and what the directory under
2482 // the cache is called, and a person is free to write a tuple the long way round.
2483 let tuple = target.to_canonical_string();
2484 // Before the table is consulted, because a target behind a licence wall is not a row that has not
2485 // been written yet. Section 13.4 is that no release pins one of these ever, so the message says
2486 // the licence and the two lawful ways rather than naming the producer that will publish the rest.
2487 if let Some(wall) = rucc_sysroot::Wall::of(target) {
2488 return Err(err(format!("--fetch {tuple}: {}", wall.no_fetch(&tuple))));
2489 }
2490 let Some(what) = rucc_sysroot::pinned_for_target(target) else {
2491 return Err(err(unpinned(&tuple)));
2492 };
2493 Ok(Action::Fetch { what, target, cache: cache::dir() })
2494}
2495
2496/// What `--fetch-msvc-sdk <tuple>` asks for, weighed the same way the fetch above is.
2497///
2498/// The target is resolved here rather than where the work happens, so that a tuple this compiler
2499/// does not know and a target that is not behind Microsoft's wall are refusals from the parser like
2500/// every other thing a command line can ask for and not have. Whether the licence was accepted is
2501/// carried rather than acted on, because what it changes is what the command does and not whether
2502/// the command line made sense.
2503///
2504/// # Errors
2505///
2506/// [`CliError`] when `--offline` forbade it, when there are input files as well, and when the tuple
2507/// is not a target this compiler knows.
2508fn fetch_msvc_action(
2509 named: &str,
2510 offline: bool,
2511 accepted: bool,
2512 inputs: &[Input],
2513) -> Result<Action, CliError> {
2514 if offline {
2515 return Err(err(
2516 "--fetch-msvc-sdk asks for a download and --offline forbids every download, so this \
2517 command line asks for two opposite things. Drop one of them: --offline is how a build \
2518 says it will not reach the network",
2519 ));
2520 }
2521 if let Some(first) = inputs.first() {
2522 return Err(err(format!(
2523 "--fetch-msvc-sdk gets an SDK and compiles nothing, so `{}` on the same command line \
2524 is an input that nothing would read",
2525 first.path
2526 )));
2527 }
2528 let target: TargetTuple = named.parse().map_err(|why| {
2529 err(format!("--fetch-msvc-sdk {named}: {why}, so there is no SDK to get"))
2530 })?;
2531 Ok(Action::FetchMsvcSdk { target, accepted, cache: cache::dir() })
2532}
2533
2534/// Why there is nothing to fetch for a target, which is a different sentence when the table is
2535/// empty.
2536///
2537/// A release that pins nothing and a release that pins eleven targets and not this one are two
2538/// situations, and a message that did not tell them apart would send somebody looking for a typo in
2539/// their tuple when the answer is that this work is not finished.
2540fn unpinned(tuple: &str) -> String {
2541 let pinned = rucc_sysroot::pinned_targets();
2542 if pinned.is_empty() {
2543 return format!(
2544 "this release pins no sysroot for {tuple}, and it pins none for any target yet. A \
2545 sysroot is built and published by the producer in tamnd/rucc-cross, per \
2546 spec/cross-compile/13-distribution.md section 13.8, and a release of this compiler \
2547 names one by URL and by hash afterwards. Until then, pass --sysroot=<dir> to compile \
2548 against a tree you have already"
2549 );
2550 }
2551 format!(
2552 "this release pins no sysroot for {tuple}. What it pins is {}. Pass --sysroot=<dir> to \
2553 compile against a tree you have already",
2554 pinned.join(", ")
2555 )
2556}
2557
2558/// Gets the artifact and installs it, saying what each step did.
2559///
2560/// The steps are section 13.8's and so are the messages: the transport is somebody else's program
2561/// and the check is ours, so a person reading this wants to know which downloader ran, that the
2562/// bytes matched, how many files the record named and where the tree ended up. A fetch of something
2563/// that is already there says that instead and moves nothing.
2564///
2565/// A Linux target is two artifacts, its own sysroot and the kernel header tree every Linux target
2566/// shares, and `kernel` is the second one when the target reads it. It is fetched after the sysroot
2567/// and by the same two steps, so a machine that has fetched one Linux target already has it and a
2568/// second target's fetch says so and moves nothing.
2569fn fetch_sysroot(
2570 what: &rucc_sysroot::Pinned,
2571 kernel: Option<&rucc_sysroot::Pinned>,
2572 target: TargetTuple,
2573 cache: &std::path::Path,
2574) -> i32 {
2575 let tuple = target.to_canonical_string();
2576 let say = |line: &str| println!("rucc: {tuple}: {line}");
2577 if let Err(why) = bring(what, cache, &say) {
2578 return complain(why);
2579 }
2580 let archive = what.archive_in(cache);
2581 match install::install(&archive, what.sha256, target, cache) {
2582 Ok(done) => report(&done, "sysroot", &say),
2583 Err(why) => return complain(why),
2584 }
2585 let Some(kernel) = kernel else { return 0 };
2586 if let Err(why) = bring(kernel, cache, &say) {
2587 return complain(why);
2588 }
2589 match install::install_kernel(&kernel.archive_in(cache), kernel.sha256, cache) {
2590 Ok(done) => {
2591 report(&done, "kernel header tree", &say);
2592 0
2593 }
2594 Err(why) => complain(why),
2595 }
2596}
2597
2598/// The download half of a fetch, for one artifact.
2599fn bring(
2600 what: &rucc_sysroot::Pinned,
2601 cache: &std::path::Path,
2602 say: &impl Fn(&str),
2603) -> Result<(), CliError> {
2604 let archive = what.archive_in(cache);
2605 match fetch::fetch(what.url, what.sha256, &archive)? {
2606 fetch::Fetched::AlreadyThere => {
2607 say(&format!("{} is already here and matches the hash", archive.display()));
2608 }
2609 fetch::Fetched::Downloaded(by) => {
2610 say(&format!("downloaded {} with {}", what.url, by.program()));
2611 }
2612 }
2613 Ok(())
2614}
2615
2616/// What an install did, in the words a person reading a fetch wants.
2617fn report(done: &install::Installed, what: &str, say: &impl Fn(&str)) {
2618 match &done.before {
2619 install::Before::Nothing => {
2620 say(&format!("{} files installed at {}", done.files, done.root.display()));
2621 }
2622 install::Before::TheSame => {
2623 say(&format!(
2624 "the same {what} is already at {}, so nothing moved",
2625 done.root.display()
2626 ));
2627 }
2628 install::Before::Different(was) => {
2629 say(&format!(
2630 "{} files installed at {}, over a tree whose record digested to {was}",
2631 done.files,
2632 done.root.display()
2633 ));
2634 }
2635 }
2636 say(&format!("the {what}'s record digests to {}", done.digest));
2637}
2638
2639/// What one of the `-dump` and `-print` flags prints.
2640///
2641/// GCC prints the name back unchanged when it cannot find the file a `-print` flag asked about,
2642/// which is what makes the answer safe to paste into a link line whether or not the file is
2643/// there, and this does the same.
2644fn answer(query: &Query, opts: &Options, link: &LinkOptions) -> Result<String, CliError> {
2645 let found = |name: &str| {
2646 link::find_in_search(link, opts.target, name)
2647 .map_or_else(|| name.to_owned(), |path| path.display().to_string())
2648 };
2649 Ok(match query {
2650 Query::Machine => opts.target.to_string(),
2651 Query::Version => opts.gnuc.major.to_string(),
2652 Query::FullVersion => {
2653 format!("{}.{}.{}", opts.gnuc.major, opts.gnuc.minor, opts.gnuc.patch)
2654 }
2655 Query::Multiarch => link::multiarch(opts.target),
2656 // The three lines GCC prints, in its order and with its punctuation, because what reads
2657 // them is a script written against that shape. There is no installation directory to
2658 // report: this compiler is one binary that works wherever it is copied, and the headers
2659 // it ships are inside it, so `install` is where the binary is and nothing is under it.
2660 Query::SearchDirs => {
2661 let here = std::env::current_exe()
2662 .ok()
2663 .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
2664 .unwrap_or_default();
2665 let list = |dirs: &[PathBuf]| {
2666 dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(":")
2667 };
2668 let libraries = link::search_dirs(link, opts.target);
2669 format!(
2670 "install: {}\nprograms: ={}\nlibraries: ={}",
2671 here.display(),
2672 list(&link.prefixes),
2673 list(&libraries)
2674 )
2675 }
2676 // The root the rest of the answers are under, which a build system asks for when it wants
2677 // to find a file itself rather than ask for one by name, and which is the first thing to
2678 // look at when a cross build read a header nobody expected. A native compile has no
2679 // sysroot and the answer is the empty line, which is what GCC prints when it was
2680 // configured without one. `--sysroot` wins over ours because it wins everywhere else.
2681 Query::Sysroot => {
2682 sysroot_root(opts, link).map(|root| root.display().to_string()).unwrap_or_default()
2683 }
2684 // Section 13.5 of `spec/cross-compile/13-distribution.md`: for every input that is not this
2685 // compiler's own code, what it is, where it was got, its hash, its licence and whether it
2686 // was bundled, generated or fetched. What is printed is the manifest the sysroot already
2687 // carries rather than a second format saying the same things, because the three uses 13.5
2688 // gives for this are a licence notice, a reproducibility check and a security audit, and all
2689 // three are somebody else parsing it. One format is one parser to write.
2690 // Read and rendered rather than copied out, so that what comes back is the format this
2691 // build understands. The last newline comes off because whatever prints an answer adds
2692 // one, the way it does for every other query here. Keeping it would put a blank line at
2693 // the end of the one answer that is a file somebody diffs against the file it came from.
2694 Query::SysrootProvenance => match sysroot_manifest(opts, link)? {
2695 Some(manifest) => manifest.render().trim_end_matches('\n').to_string(),
2696 None => String::new(),
2697 },
2698 // Section 13.2 of the same document, which asks for the hash of a cache directory's
2699 // contents in the directory's name. A name cannot carry one, because the path has to be
2700 // computable before anything has been read, by the producer about to write the files and by
2701 // the compiler about to read them, and neither has the contents when it asks. So the number
2702 // is here instead, and it is the sha256 of the record rather than of a walk of the tree,
2703 // which means `sha256sum` over the manifest answers the same thing.
2704 Query::SysrootDigest => match sysroot_manifest(opts, link)? {
2705 Some(manifest) => manifest.digest(),
2706 None => String::new(),
2707 },
2708 Query::FileName(name) => found(name),
2709 // The name GCC gives the library of routines a compiler's output calls that the C
2710 // library does not have. Ours is built in and there is no file, so the answer is the
2711 // name itself, which is what GCC prints when it cannot find one either.
2712 Query::Libgcc => found("libgcc.a"),
2713 // A program rather than a library: the linker and the archiver are the ones a build asks
2714 // about, and this compiler finds them on the path or under `-B` rather than shipping
2715 // them, so the name back is the honest answer unless a `-B` prefix holds one.
2716 Query::ProgName(name) => link
2717 .prefixes
2718 .iter()
2719 .map(|dir| dir.join(name))
2720 .find(|path| path.is_file())
2721 .map_or_else(|| name.clone(), |path| path.display().to_string()),
2722 })
2723}
2724
2725/// The root every sysroot answer is about.
2726///
2727/// One function rather than a copy in each, because the other flags exist to say what is inside the
2728/// tree this one names, and two answers that disagreed about which tree that is would be a
2729/// difference nobody would think to look for. `--sysroot` wins over ours because it wins everywhere
2730/// else.
2731fn sysroot_root(opts: &Options, link: &LinkOptions) -> Option<PathBuf> {
2732 link.sysroot
2733 .clone()
2734 .or_else(|| link::cross_sysroot(opts.target, link).map(|at| at.root().to_path_buf()))
2735}
2736
2737/// The record of the sysroot this command line reads, when there is one to read.
2738///
2739/// [`None`] covers two cases that both print nothing, and they are different things. A compile for
2740/// this machine has no sysroot at all, and a tree somebody laid out themselves and pointed
2741/// `--sysroot` at carries no manifest, so nothing here knows where any of it came from. Saying
2742/// nothing is the only honest answer to either, and a reader can tell it from a manifest with no
2743/// inputs in it because that one still has its header lines.
2744///
2745/// # Errors
2746///
2747/// A manifest this build cannot parse, and anything else that went wrong reading the file. Passing a
2748/// record we could not read on to whoever asked would make their parser the one that finds the
2749/// problem, and every use section 13.5 gives for these two flags is somebody else reading the
2750/// output.
2751fn sysroot_manifest(opts: &Options, link: &LinkOptions) -> Result<Option<Manifest>, CliError> {
2752 let Some(root) = sysroot_root(opts, link) else {
2753 return Ok(None);
2754 };
2755 let path = Sysroot::at(root, opts.target.tuple()).manifest_path();
2756 match std::fs::read_to_string(&path) {
2757 Ok(text) => Manifest::parse(&text)
2758 .map(Some)
2759 .map_err(|why| err(format!("{}: {why}", path.display()))),
2760 Err(why) if why.kind() == std::io::ErrorKind::NotFound => Ok(None),
2761 Err(why) => Err(err(format!("{}: {why}", path.display()))),
2762 }
2763}
2764
2765/// Renders the passes this level will run, in order, with what each one does.
2766///
2767/// The level is the whole of the answer unless a `-f` flag edited it, which is section 9.1 of
2768/// `spec/09-optimizer.md`: a level is a list somebody wrote down rather than something that
2769/// emerges from which flags happen to be set, and this is how that list is read.
2770#[must_use]
2771pub fn print_pipeline(opts: &Options) -> String {
2772 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
2773 settings.toggles.clone_from(&opts.passes);
2774 settings.global_fuel = opts.pass_fuel_global;
2775 for (on, spec) in &opts.pass_gates {
2776 // Every spelling was checked while the arguments were parsed, so there is nothing here
2777 // this can refuse, and a listing is not the place to report it if there were.
2778 let _ = settings.gates.add(*on, spec);
2779 }
2780 rucc_opt::pipeline::print(&settings)
2781}
2782
2783/// Renders the resolved configuration.
2784///
2785/// One `key: value` per line, sorted by nothing in particular but fixed in order, because
2786/// this output is diffed across hosts in CI and a reordering would read as a change.
2787#[must_use]
2788pub fn print_config(opts: &Options) -> String {
2789 let sess = Session::new(opts.clone());
2790 let t = &sess.target;
2791 let mut out = String::new();
2792 let _ = writeln!(out, "version: {VERSION}");
2793 // The three field triple the driver was given rather than the ten field tuple it widens to,
2794 // because this output is what a build system reads to find out what it asked for. The tuple is
2795 // the compiler's model of the machine and this line is a receipt for a command line.
2796 let _ = writeln!(out, "target: {}", opts.target);
2797 let _ = writeln!(out, "arch: {}", opts.target.arch.as_str());
2798 let _ = writeln!(out, "os: {}", opts.target.os.as_str());
2799 let _ = writeln!(out, "env: {}", opts.target.env.as_str());
2800 let _ = writeln!(out, "object-format: {}", t.object_format.as_str());
2801 let _ = writeln!(out, "pointer-width: {}", t.pointer_width);
2802 let _ = writeln!(out, "long-width: {}", t.long_width);
2803 let _ = writeln!(out, "long-double-width: {}", t.long_double_width);
2804 let _ = writeln!(out, "endian: {}", if t.little_endian { "little" } else { "big" });
2805 let _ = writeln!(out, "char-signed: {}", t.char_is_signed);
2806 let _ = writeln!(out, "va-list: {}", t.va_list.map_or("none", |list| list.as_str()));
2807 // The register file as a count per class, which is enough to tell a target whose registers
2808 // are described from one whose are not without printing sixteen names nobody asked for.
2809 let regs: Vec<String> = t
2810 .regs
2811 .classes()
2812 .map(|(class, info)| format!("{} {}", info.name, t.regs.len(class)))
2813 .collect();
2814 let _ = writeln!(
2815 out,
2816 "registers: {}",
2817 if regs.is_empty() { "none".to_string() } else { regs.join(", ") }
2818 );
2819 // What the schedule was chosen with, which is a sentence rather than a name on purpose: two
2820 // runs of a benchmark that disagree are usually two models and not two compilers.
2821 let _ = writeln!(out, "timing-model: {}", t.timing.map_or("none", |timing| timing.model));
2822 let _ = writeln!(out, "opt-level: {}", sess.opts.opt_level);
2823 let _ = writeln!(out, "safety: {}", sess.opts.safety);
2824 let _ = writeln!(out, "emit: {}", sess.opts.emit.as_str());
2825 let _ = writeln!(out, "debug-info: {}", sess.opts.debug_info);
2826 let _ = writeln!(out, "frame-pointer: {}", sess.opts.keeps_frame_pointer());
2827 let _ = writeln!(out, "red-zone: {}", sess.opts.red_zone);
2828 let _ = writeln!(out, "stack-protector: {}", sess.opts.protector);
2829 let _ = writeln!(out, "stack-clash-protection: {}", sess.opts.stack_clash);
2830 let _ = writeln!(out, "cf-protection: {}", sess.opts.control);
2831 let _ = writeln!(out, "patchable-function-entry: {}", sess.opts.patchable);
2832 let _ = writeln!(out, "profile: {}", sess.opts.profile);
2833 let _ = writeln!(out, "profile-hook: {}", sess.opts.hook);
2834 // Last because it is the one key with more than one line under it, and the only one
2835 // whose value is a property of the machine rather than of the command line.
2836 for dir in sess.opts.search.dirs() {
2837 let system = if dir.is_system { " (system)" } else { "" };
2838 let _ = writeln!(out, "include: {}{system}", dir.path.display());
2839 }
2840 out
2841}
2842
2843/// The output name the make target is taken from, which is the `-o` argument or nothing.
2844///
2845/// A run that stops at the preprocessor has not named an object, whatever its `-o` says: under
2846/// `-E` that argument is the preprocessed text and under `-M` it is the rule itself, and neither
2847/// is a file `make` would rebuild by running this rule. GCC agrees and falls back to the source
2848/// name in both, which is why a `-MD -E -o out.i` writes `out.d` holding a rule for `a.o`. From
2849/// `-S` on the argument does name what the rule builds, and it is used as written.
2850fn deps_target_output<'a>(opts: &Options, plan: &'a Plan) -> Option<&'a str> {
2851 if opts.emit == EmitKind::Preprocessed { None } else { plan.output.as_deref() }
2852}
2853
2854/// Writes to a path the command line named rather than one the plan derived, where `-` is
2855/// standard output.
2856fn write_named(path: &str, bytes: &[u8]) -> Result<(), String> {
2857 if path == "-" {
2858 return write_out(&Output::Stdout, bytes);
2859 }
2860 write_out(&Output::File(path.to_owned()), bytes)
2861}
2862
2863/// Writes the make rule for one input, and reports whether it got there.
2864///
2865/// A rule with no file of its own goes where the compilation it replaced would have written,
2866/// which is what makes the usual makefile recipe work: `rucc -M $< -o $@` leaves the rule in
2867/// `$@`, and the same line with the `-o` left off puts it on standard output.
2868fn write_deps(
2869 opts: &Options,
2870 plan: &Plan,
2871 job: &Job,
2872 found: &[Dependency],
2873 stderr: &mut impl std::io::Write,
2874) -> bool {
2875 let targets = if opts.deps.targets.is_empty() {
2876 vec![deps::default_target(&job.input, deps_target_output(opts, plan))]
2877 } else {
2878 opts.deps.targets.clone()
2879 };
2880 let rule = deps::rule(&opts.deps, &targets, &job.input, found);
2881 // The file, on the other hand, is named after the `-o` in every mode that still has one to
2882 // spend, which is every mode except the two that spend it on the rule.
2883 let wrote = match deps::default_file(&opts.deps, &job.input, plan.output.as_deref()) {
2884 // A `-MF` on a run that had nowhere else to put the rule leaves the file the `-o`
2885 // named empty rather than absent, because a makefile that named it as a target of its
2886 // own is a makefile that will look for it.
2887 Some(path) => write_named(&path, rule.as_bytes()).and_then(|()| {
2888 if opts.deps.instead_of_compiling { write_out(&job.output, b"") } else { Ok(()) }
2889 }),
2890 None => write_out(&job.output, rule.as_bytes()),
2891 };
2892 if let Err(e) = wrote {
2893 let _ = writeln!(stderr, "rucc: error: {e}");
2894 return false;
2895 }
2896 true
2897}
2898
2899/// Runs phase 4 over every input that has one, and writes what came out.
2900///
2901/// One input that fails does not stop the others. A build that reports every file it could
2902/// not preprocess in one run is worth more than one that stops at the first, and the exit
2903/// status is still a failure either way.
2904fn preprocess_all(opts: &Options, plan: &Plan) -> i32 {
2905 let fs = OsFileSystem::new();
2906 let mut stderr = std::io::stderr().lock();
2907 let mut failed = false;
2908 for job in &plan.jobs {
2909 if !job.phases.first().is_some_and(|p| *p == Phase::Preprocess) {
2910 // An input that is already preprocessed, or an object file. GCC passes these
2911 // through untouched, and the plan has already said so in its notes.
2912 continue;
2913 }
2914 let started = std::time::Instant::now();
2915 let result = preprocess(opts, &job.input, &fs);
2916 if opts.time {
2917 say_time(&job.input, started.elapsed(), &mut stderr);
2918 }
2919 for message in &result.messages {
2920 let _ = writeln!(stderr, "{message}");
2921 }
2922 if result.failed() {
2923 failed = true;
2924 continue;
2925 }
2926 if opts.deps.emit {
2927 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
2928 // `-M` and `-MM` asked for the rule instead of the text, so there is nothing else
2929 // to write. The other two asked for both and fall through to the text below.
2930 if opts.deps.instead_of_compiling {
2931 continue;
2932 }
2933 }
2934 if let Err(e) = write_out(&job.output, result.text.as_bytes()) {
2935 let _ = writeln!(stderr, "rucc: error: {e}");
2936 failed = true;
2937 }
2938 }
2939 i32::from(failed)
2940}
2941
2942/// Whether this job is a file of assembly that has to be assembled and that nothing here assembles.
2943///
2944/// The phases rather than the kind, because there are two kinds of assembly input and one of them
2945/// is preprocessed first, and because an object file also has no compile phase and is not this: it
2946/// has no phases at all and goes to the linker as it is. A `.s` on a `-c` line has exactly
2947/// [`Phase::Assemble`] left, and a `.S` has the preprocessor in front of it, and neither has
2948/// anything the front end can do.
2949fn needs_an_assembler(job: &Job) -> bool {
2950 job.phases.contains(&Phase::Assemble) && !job.phases.contains(&Phase::Compile)
2951}
2952
2953/// Whether the preprocessor runs over it on the way in, which is the whole difference between the
2954/// two kinds of assembly input.
2955fn assembly_wants_cpp(job: &Job) -> bool {
2956 job.phases.contains(&Phase::Preprocess)
2957}
2958
2959/// Runs the front end over every input that has a compile phase, and writes what came out.
2960///
2961/// The same rule as [`preprocess_all`]: one input that fails does not stop the others, and the
2962/// exit status is a failure either way. An input that is already assembly or an object has no
2963/// compile phase and is passed over here, which the plan has already said in its notes.
2964fn compile_all(opts: &Options, plan: &Plan) -> i32 {
2965 let fs = OsFileSystem::new();
2966 let mut stderr = std::io::stderr().lock();
2967 let mut failed = false;
2968 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
2969 failed |= !ok;
2970 let mut fired = Fired::new();
2971 let mut pressure = Pressure::new();
2972 let mut lowerings = Lowerings::new();
2973 for job in &plan.jobs {
2974 if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
2975 continue;
2976 }
2977 // An input of IR is read back rather than compiled, since the C it came from is not
2978 // here any more. A file of assembly does not go through the front end at all and is
2979 // read by the assembler instead. Everything after this is the same for all three, so
2980 // the paths meet again at the messages and the file the result is written to.
2981 let started = std::time::Instant::now();
2982 let result = if needs_an_assembler(job) {
2983 assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
2984 } else if job.kind == InputKind::Ir {
2985 compile_ir(opts, &job.input, &fs)
2986 } else {
2987 compile(opts, &job.input, &fs)
2988 };
2989 if opts.time {
2990 say_time(&job.input, started.elapsed(), &mut stderr);
2991 }
2992 failed |= !write_trace(opts, job, started, &result, &mut stderr);
2993 fired.merge(&result.fired);
2994 pressure.merge(&result.pressure);
2995 lowerings.merge(&result.lowerings);
2996 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
2997 failed |= !remarks.write(&result.remarks, &mut stderr);
2998 for message in &result.messages {
2999 let _ = writeln!(stderr, "{message}");
3000 }
3001 // Before the failure below, because a compilation that stopped in the back end is exactly
3002 // the one whose preprocessed source somebody wants to look at.
3003 failed |= !write_temps(job, &result.temps, &mut stderr);
3004 if result.failed() {
3005 failed = true;
3006 continue;
3007 }
3008 // `-MD` and `-MMD` write the rule beside the object and let the compilation happen, so
3009 // this is the one path where both files come out of the same run. An input of IR has no
3010 // dependencies to report and produces an empty list, which produces a rule naming only
3011 // itself, and that is the honest answer rather than a missing file.
3012 if opts.deps.emit {
3013 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3014 }
3015 if let Err(e) = write_out(&job.output, result.artifact.bytes()) {
3016 let _ = writeln!(stderr, "rucc: error: {e}");
3017 failed = true;
3018 }
3019 }
3020 failed |= !write_coverage(opts, &fired, &mut stderr);
3021 failed |= !write_pressure(opts, &pressure, &mut stderr);
3022 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3023 i32::from(failed)
3024}
3025
3026/// A directory for the object files only the link step ever sees, removed when it goes away.
3027///
3028/// `-c` writes its object where the user can see it and linking does not, which is the whole of
3029/// the difference: a `rucc a.c b.c` leaves an executable behind and nothing else, the same as
3030/// every other compiler. Removing them on drop rather than at the end of a function is so that a
3031/// link that failed leaves nothing behind either.
3032struct Scratch {
3033 /// Where the objects go.
3034 dir: PathBuf,
3035}
3036
3037impl Scratch {
3038 /// Makes one, under whatever the platform calls its temporary directory.
3039 ///
3040 /// The name carries the process id so that two compilers running at once do not share a
3041 /// directory, which they would otherwise do the moment two of them compiled a file of the
3042 /// same name.
3043 fn new() -> Result<Scratch, String> {
3044 let dir = std::env::temp_dir().join(format!("rucc-{}", std::process::id()));
3045 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
3046 Ok(Scratch { dir })
3047 }
3048}
3049
3050impl Drop for Scratch {
3051 fn drop(&mut self) {
3052 let _ = std::fs::remove_dir_all(&self.dir);
3053 }
3054}
3055
3056/// The link line the plan describes, for `-###`.
3057///
3058/// The names in it are the hints the plan carries rather than the temporaries a real compilation
3059/// would choose, because `-###` prints the line without having compiled anything and so has
3060/// nothing to point at. That also makes the printed line readable rather than naming a directory
3061/// that only exists while a compilation is running.
3062fn link_line(opts: &Options, link: &LinkOptions, job: &LinkJob) -> Result<String, link::Error> {
3063 let linker = link::find(opts.target, link)?;
3064 let args = link::line(opts.target, link, &job.inputs, &job.output)?;
3065 Ok(link::render(&linker, &args))
3066}
3067
3068/// Compiles everything, then links it.
3069///
3070/// The objects go in a directory that is removed afterwards, which is why this is not
3071/// [`compile_all`] followed by a link: the plan says an object feeding the linker is temporary
3072/// and does not say where, because where is a question that only has an answer once something is
3073/// running.
3074fn link_all(opts: &Options, plan: &Plan, link: &LinkOptions, verbose: bool) -> i32 {
3075 let Some(job) = &plan.link else {
3076 // Every path into here comes from a plan whose last phase is the link, and such a plan
3077 // has a link job. Saying so is cheaper than an unwrap that would have to be explained.
3078 let mut stderr = std::io::stderr().lock();
3079 let _ = writeln!(stderr, "rucc: error: there is nothing to link");
3080 return 1;
3081 };
3082 // Before anything is compiled, because a linker that is not on the machine is worth knowing
3083 // about in the second it takes to look rather than after the compilation.
3084 // And before that, whether this link has a line at all and whether what it reads is on the
3085 // machine. Both are answerable now, and a target whose sysroot has not been built is worth
3086 // saying so about before the compilation rather than after it.
3087 if let Err(why) = link::preflight(opts.target, link) {
3088 return complain(why);
3089 }
3090 let linker = match link::find(opts.target, link) {
3091 Ok(linker) => linker,
3092 Err(why) => return complain(why),
3093 };
3094 // And whether the one that was found can do this link, which for one linker and one target is
3095 // a question only the linker itself can answer. Here rather than inside the search, because
3096 // what it does is refuse rather than move on to the next candidate: nothing else in the list
3097 // links a produced Windows sysroot either.
3098 if let Err(why) = link::suitable(opts.target, &linker) {
3099 return complain(why);
3100 }
3101 // The glibc stubs, which are the one part of a cross sysroot written here rather than fetched.
3102 // Before compiling for the same reason as the rest, and never for `-###`, which writes nothing.
3103 if let Err(why) = link::write_stubs(opts.target, link) {
3104 return complain(why);
3105 }
3106
3107 let scratch = match Scratch::new() {
3108 Ok(scratch) => scratch,
3109 Err(why) => return complain(format!("could not make a place for the object files: {why}")),
3110 };
3111
3112 let fs = OsFileSystem::new();
3113 let mut failed = false;
3114 // One per job, in job order, which is what lets the link line below be rebuilt with the real
3115 // paths in it: every job contributes exactly one file to the line and does so in this order.
3116 let mut produced: Vec<String> = Vec::with_capacity(plan.jobs.len());
3117 let mut fired = Fired::new();
3118 let mut pressure = Pressure::new();
3119 let mut lowerings = Lowerings::new();
3120 {
3121 let mut stderr = std::io::stderr().lock();
3122 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3123 failed |= !ok;
3124 for (at, job) in plan.jobs.iter().enumerate() {
3125 let out = match &job.output {
3126 Output::Temporary(hint) => {
3127 // The index because two inputs in different directories can have the same
3128 // name, and the two objects of `rucc a/x.c b/x.c` must not be one file.
3129 scratch.dir.join(format!("{at}-{hint}")).display().to_string()
3130 }
3131 Output::File(path) => path.clone(),
3132 // A job feeding the linker never writes to standard output, since the plan gives
3133 // it a temporary. This is here so that the match is total rather than a panic.
3134 Output::Stdout => continue,
3135 };
3136 produced.push(out.clone());
3137 if !job.phases.contains(&Phase::Compile) && !needs_an_assembler(job) {
3138 continue;
3139 }
3140 let started = std::time::Instant::now();
3141 let result = if needs_an_assembler(job) {
3142 assemble(opts, &job.input, assembly_wants_cpp(job), &fs)
3143 } else if job.kind == InputKind::Ir {
3144 compile_ir(opts, &job.input, &fs)
3145 } else {
3146 compile(opts, &job.input, &fs)
3147 };
3148 if opts.time {
3149 say_time(&job.input, started.elapsed(), &mut stderr);
3150 }
3151 failed |= !write_trace(opts, job, started, &result, &mut stderr);
3152 fired.merge(&result.fired);
3153 pressure.merge(&result.pressure);
3154 lowerings.merge(&result.lowerings);
3155 failed |= !write_dumps(&job.input, &result.dumps, &mut stderr);
3156 failed |= !remarks.write(&result.remarks, &mut stderr);
3157 for message in &result.messages {
3158 let _ = writeln!(stderr, "{message}");
3159 }
3160 failed |= !write_temps(job, &result.temps, &mut stderr);
3161 if result.failed() {
3162 failed = true;
3163 continue;
3164 }
3165 // A `-MD` on a command line that links writes the rule next to the executable and
3166 // names the executable as its target, since that is the file this source builds
3167 // here. The object it went through is in a temporary directory and is gone by the
3168 // time `make` reads any of this.
3169 if opts.deps.emit {
3170 failed |= !write_deps(opts, plan, job, &result.deps, &mut stderr);
3171 }
3172 if !matches!(result.artifact, Artifact::Object { .. }) {
3173 // Worth saying rather than writing whatever it is and letting the linker read it.
3174 // An empty file is a valid empty linker script, so a link handed one gets as far
3175 // as reporting every symbol of this file undefined, which is a page of messages
3176 // about something that went wrong here.
3177 let _ = writeln!(
3178 stderr,
3179 "rucc: internal error: {}: no object file was produced for the link",
3180 job.input
3181 );
3182 failed = true;
3183 continue;
3184 }
3185 if let Err(e) = std::fs::write(&out, result.artifact.bytes()) {
3186 let _ = writeln!(stderr, "rucc: error: {out}: {e}");
3187 failed = true;
3188 }
3189 }
3190 failed |= !write_coverage(opts, &fired, &mut stderr);
3191 failed |= !write_pressure(opts, &pressure, &mut stderr);
3192 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3193 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3194 }
3195 if failed {
3196 // Nothing is linked from a compilation that did not finish. A linker run over the objects
3197 // that did compile would report every function of the file that did not as undefined,
3198 // which is a page of messages about a mistake already reported once.
3199 return 1;
3200 }
3201
3202 // The items in command line order with the temporaries filled in. A library and a word for the
3203 // linker contribute no job and pass through, and every file item takes the next job's real
3204 // output, which is what keeps whatever was written between two objects between them here.
3205 let mut outputs = produced.into_iter();
3206 let mut items = Vec::with_capacity(job.inputs.len());
3207 for item in &job.inputs {
3208 match item {
3209 link::Item::Library(name) => items.push(link::Item::Library(name.clone())),
3210 link::Item::Linker(arg) => items.push(link::Item::Linker(arg.clone())),
3211 link::Item::File(_) => match outputs.next() {
3212 Some(path) => items.push(link::Item::File(path)),
3213 None => return complain("the plan asks the linker for a file nothing produced"),
3214 },
3215 }
3216 }
3217
3218 let args = match link::line(opts.target, link, &items, &job.output) {
3219 Ok(args) => args,
3220 Err(why) => return complain(why),
3221 };
3222 if verbose {
3223 let mut stderr = std::io::stderr().lock();
3224 let _ = writeln!(stderr, "{}", link::render(&linker, &args));
3225 }
3226 let started = std::time::Instant::now();
3227 let ran = link::run(&linker, &args);
3228 if opts.time {
3229 // The one step of a compilation that really is another program, so this line is the same
3230 // measurement gcc's is and names the linker the way gcc names `collect2`.
3231 let mut stderr = std::io::stderr().lock();
3232 say_time(&linker.name, started.elapsed(), &mut stderr);
3233 }
3234 match ran {
3235 Ok(()) => 0,
3236 // The linker has already said what was wrong on its own error output, and repeating that
3237 // linking failed would only push its message further up the screen.
3238 Err(link::Error::Refused { .. }) => 1,
3239 Err(why) => complain(why),
3240 }
3241}
3242
3243/// Compiles everything and writes the objects into one static library.
3244///
3245/// No temporary directory and no second program. The objects never reach the file system at all:
3246/// they go from the compiler into the archive writer, which is both faster than writing a directory
3247/// of files for an `ar` to read back and the reason the symbol index can be written at all. A
3248/// member's index entries are the names the object writer says it wrote, and the only thing that
3249/// knows those is the run that wrote it.
3250///
3251/// `-save-temps` is the exception. It asked for the objects to be kept, the plan gave them names a
3252/// person can find, and they are written there as well as put in the archive.
3253fn archive_all(opts: &Options, plan: &Plan) -> i32 {
3254 let Some(job) = &plan.archive else {
3255 // Every path into here comes from a plan whose last phase is the archive, and such a plan
3256 // has an archive job. Saying so is cheaper than an unwrap that would have to be explained.
3257 return complain("there is nothing to put in an archive");
3258 };
3259 // Before anything is compiled, because a format this has no container for is worth knowing
3260 // about in the second it takes to look rather than after the whole compilation.
3261 let flavour = match opts.target.os.object_format() {
3262 ObjectFormat::Elf => rucc_archive::Flavour::Gnu,
3263 ObjectFormat::Coff => rucc_archive::Flavour::Coff,
3264 // Mach-O wants the BSD flavour, whose index is a different member under a different name
3265 // and which is not written yet, and wasm has no archives of its own at all.
3266 format @ (ObjectFormat::MachO | ObjectFormat::Wasm) => {
3267 return complain(format!(
3268 "there is no archive format for {} objects in this compiler yet",
3269 format.as_str()
3270 ));
3271 }
3272 };
3273
3274 let fs = OsFileSystem::new();
3275 let mut failed = false;
3276 let mut members: Vec<rucc_archive::Member> = Vec::with_capacity(plan.jobs.len());
3277 let mut names = job.members.iter();
3278 let mut fired = Fired::new();
3279 let mut pressure = Pressure::new();
3280 let mut lowerings = Lowerings::new();
3281 {
3282 let mut stderr = std::io::stderr().lock();
3283 let (mut remarks, ok) = Remarks::new(opts.opt_info_file.as_ref(), &mut stderr);
3284 failed |= !ok;
3285 for plan_job in &plan.jobs {
3286 // What the plan called this member. The two lists are walked together rather than the
3287 // name being worked out again here, so that what `-###` printed and what goes in the
3288 // file cannot come apart.
3289 let Some(member) = names.next() else {
3290 return complain("the plan asks the archive for a member nothing produced");
3291 };
3292 if !plan_job.phases.contains(&Phase::Compile) && !needs_an_assembler(plan_job) {
3293 // Neither something to compile nor something to assemble, so there is nothing to
3294 // put in, and an archive quietly missing a member is worse than a message.
3295 let _ = writeln!(
3296 &mut stderr,
3297 "rucc: error: {}: this compiler makes an archive out of what it compiles, and \
3298 there is nothing here for it to do",
3299 plan_job.input
3300 );
3301 failed = true;
3302 continue;
3303 }
3304 let started = std::time::Instant::now();
3305 let result = if needs_an_assembler(plan_job) {
3306 assemble(opts, &plan_job.input, assembly_wants_cpp(plan_job), &fs)
3307 } else if plan_job.kind == InputKind::Ir {
3308 compile_ir(opts, &plan_job.input, &fs)
3309 } else {
3310 compile(opts, &plan_job.input, &fs)
3311 };
3312 if opts.time {
3313 say_time(&plan_job.input, started.elapsed(), &mut stderr);
3314 }
3315 failed |= !write_trace(opts, plan_job, started, &result, &mut stderr);
3316 fired.merge(&result.fired);
3317 pressure.merge(&result.pressure);
3318 lowerings.merge(&result.lowerings);
3319 failed |= !write_dumps(&plan_job.input, &result.dumps, &mut stderr);
3320 failed |= !remarks.write(&result.remarks, &mut stderr);
3321 for message in &result.messages {
3322 let _ = writeln!(stderr, "{message}");
3323 }
3324 failed |= !write_temps(plan_job, &result.temps, &mut stderr);
3325 if result.failed() {
3326 failed = true;
3327 continue;
3328 }
3329 if opts.deps.emit {
3330 failed |= !write_deps(opts, plan, plan_job, &result.deps, &mut stderr);
3331 }
3332 let Artifact::Object { bytes, defines } = result.artifact else {
3333 let _ = writeln!(
3334 stderr,
3335 "rucc: internal error: {}: no object file was produced for the archive",
3336 plan_job.input
3337 );
3338 failed = true;
3339 continue;
3340 };
3341 // Under `-save-temps` the plan gave the object a name a person can find, so it is
3342 // written there too. Otherwise it is only ever a member and never a file.
3343 if let Output::File(path) = &plan_job.output {
3344 if let Err(e) = std::fs::write(path, &bytes) {
3345 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3346 failed = true;
3347 }
3348 }
3349 members.push(rucc_archive::Member { name: member.clone(), body: bytes, defines });
3350 }
3351 failed |= !write_coverage(opts, &fired, &mut stderr);
3352 failed |= !write_pressure(opts, &pressure, &mut stderr);
3353 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3354 failed |= !write_lowering(opts, &lowerings, &mut stderr);
3355 }
3356 if failed {
3357 // Nothing is written from a compilation that did not finish, for the reason the link gives:
3358 // an archive missing the file that failed is one a link reports every name of as undefined,
3359 // which is a page of messages about a mistake already reported once.
3360 return 1;
3361 }
3362
3363 let bytes = match rucc_archive::write(flavour, &members) {
3364 Ok(bytes) => bytes,
3365 // Every one of these is a bug here rather than a program's mistake: the names came from the
3366 // object writer and the bodies came from this process.
3367 Err(why) => return complain(format!("the archive could not be written: {why}")),
3368 };
3369 match std::fs::write(&job.output, &bytes) {
3370 Ok(()) => 0,
3371 Err(e) => complain(format!("{}: {e}", job.output)),
3372 }
3373}
3374
3375/// Prints one driver level message and gives back the exit status that goes with it.
3376fn complain(why: impl std::fmt::Display) -> i32 {
3377 let mut stderr = std::io::stderr().lock();
3378 let _ = writeln!(stderr, "rucc: error: {why}");
3379 1
3380}
3381
3382/// Writes what `-Zrule-coverage=FILE` asked for, and says whether it could.
3383///
3384/// Once for the whole command line rather than once per input, because the question is which
3385/// lowering rules this run of the compiler reached and a file per input would leave the reader
3386/// unioning files to find out something one process already knew.
3387///
3388/// A file that could not be written is a failure and not a warning. What asks for this is a
3389/// measurement run, and a measurement that quietly did not happen is worse than one that stopped.
3390fn write_coverage(opts: &Options, fired: &Fired, stderr: &mut impl std::io::Write) -> bool {
3391 let Some(path) = &opts.rule_coverage else { return true };
3392 let Some(table) = coverage::table(opts.target.arch) else {
3393 let _ = writeln!(
3394 stderr,
3395 "rucc: error: there are no lowering rules for {} yet, so there is no coverage of them \
3396 to report",
3397 opts.target
3398 );
3399 return false;
3400 };
3401 match std::fs::write(path, fired.listing(table)) {
3402 Ok(()) => true,
3403 Err(e) => {
3404 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3405 false
3406 }
3407 }
3408}
3409
3410/// Writes what `-Zregister-pressure=FILE` asked for, and says whether it could.
3411///
3412/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3413/// not be written is a failure for the reason it gives too. There is no equivalent of the missing
3414/// rule table here, since every target this compiles for has an allocator, and a run that reached
3415/// no back end at all writes an empty listing rather than nothing: a measurement of a build that
3416/// produced no code is still an answer and it is the honest one.
3417fn write_pressure(opts: &Options, pressure: &Pressure, stderr: &mut impl std::io::Write) -> bool {
3418 let Some(path) = &opts.register_pressure else { return true };
3419 match std::fs::write(path, pressure.listing()) {
3420 Ok(()) => true,
3421 Err(e) => {
3422 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3423 false
3424 }
3425 }
3426}
3427
3428/// Writes what `-Zlowering=FILE` asked for, and says whether it could.
3429///
3430/// Once for the whole command line, for the reason [`write_coverage`] gives, and a file that could
3431/// not be written is a failure for the reason it gives too. A run that reached no back end writes
3432/// an empty listing rather than nothing, the way [`write_pressure`] does and for the same reason.
3433fn write_lowering(opts: &Options, lowerings: &Lowerings, stderr: &mut impl std::io::Write) -> bool {
3434 let Some(path) = &opts.lowering_dump else { return true };
3435 match std::fs::write(path, lowerings.listing()) {
3436 Ok(()) => true,
3437 Err(e) => {
3438 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3439 false
3440 }
3441 }
3442}
3443
3444/// Where the `-fopt-info` remarks go, and how much of the run has already gone there.
3445///
3446/// Standard error by default, and one file for the whole run when `-fopt-info=<file>` named one.
3447/// A file rather than the diagnostic stream is what a harness wants: the corpus in
3448/// `tamnd/rucc-corpus` matches a rejection against what the compiler said on standard error, and
3449/// a few thousand remarks mixed into that would bury it.
3450struct Remarks {
3451 /// The file, if there is one.
3452 file: Option<String>,
3453 /// Whether anything has been written to it yet, which decides between truncating and
3454 /// appending. One file holds the whole run rather than the last input in it.
3455 started: bool,
3456}
3457
3458impl Remarks {
3459 /// Prepares the destination, emptying the file if there is one.
3460 ///
3461 /// Emptied here rather than at the first remark, because a run where no pass had anything to
3462 /// say should leave an empty file and not yesterday's. An absent file and an empty one are
3463 /// different facts and something reading this will act on the difference.
3464 fn new(file: Option<&String>, stderr: &mut impl std::io::Write) -> (Self, bool) {
3465 let mut ok = true;
3466 if let Some(path) = file {
3467 if let Err(e) = std::fs::write(path, "") {
3468 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3469 ok = false;
3470 }
3471 }
3472 (Self { file: file.cloned(), started: false }, ok)
3473 }
3474
3475 /// Writes one input's remarks, and says whether that worked.
3476 ///
3477 /// A file that cannot be written is a failure and not a warning, for the reason
3478 /// [`write_dumps`] gives: remarks that quietly did not arrive look exactly like a compilation
3479 /// where nothing happened.
3480 fn write(&mut self, text: &str, stderr: &mut impl std::io::Write) -> bool {
3481 if text.is_empty() {
3482 return true;
3483 }
3484 let Some(path) = &self.file else {
3485 let _ = write!(stderr, "{text}");
3486 return true;
3487 };
3488 let opened = std::fs::OpenOptions::new()
3489 .write(true)
3490 .append(self.started)
3491 .truncate(!self.started)
3492 .create(true)
3493 .open(path);
3494 self.started = true;
3495 let result =
3496 opened.and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()));
3497 if let Err(e) = result {
3498 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3499 return false;
3500 }
3501 true
3502 }
3503}
3504
3505/// Writes what `-fdump-ir=` asked to see, one file per dump.
3506///
3507/// The name is the input file with the dump's own name and `.ir` after it, so a directory listing
3508/// after a run is the passes in the order they ran, per input. They go in the working directory
3509/// rather than beside the output, because a dump is something a person asked for at a prompt and
3510/// the working directory is where that person is.
3511///
3512/// A file that could not be written is a failure and not a warning, for the reason
3513/// [`write_coverage`] gives: what asked for this is somebody debugging a pass, and a dump that
3514/// quietly did not happen looks exactly like a pass that did not run.
3515fn write_dumps(input: &str, dumps: &[rucc_opt::Dump], stderr: &mut impl std::io::Write) -> bool {
3516 let stem = std::path::Path::new(input)
3517 .file_name()
3518 .map_or_else(|| input.to_owned(), |name| name.to_string_lossy().into_owned());
3519 let mut ok = true;
3520 for dump in dumps {
3521 let path = format!("{stem}.{}.ir", dump.name);
3522 if let Err(e) = std::fs::write(&path, &dump.text) {
3523 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3524 ok = false;
3525 }
3526 }
3527 ok
3528}
3529
3530/// Writes the files `-save-temps` kept, which is nothing at all unless it was given.
3531///
3532/// A file that could not be written is a failure rather than a warning, for the reason
3533/// [`write_dumps`] gives: somebody asked for these by name, and one that quietly did not happen
3534/// looks like a compilation that never went through that step.
3535fn write_temps(job: &Job, temps: &Temps, stderr: &mut impl std::io::Write) -> bool {
3536 let mut ok = true;
3537 let kept = [(job.saved_text(), &temps.preprocessed), (job.saved_asm(), &temps.assembly)];
3538 for (path, text) in kept {
3539 // A step the compilation did not reach has nothing to keep, and a job that is not keeping
3540 // that step has nowhere to put it. Either way there is no file here.
3541 let (Some(path), Some(text)) = (path, text) else { continue };
3542 if let Err(e) = std::fs::write(&path, text) {
3543 let _ = writeln!(stderr, "rucc: error: {path}: {e}");
3544 ok = false;
3545 }
3546 }
3547 ok
3548}
3549
3550/// Appends the file's line to the `-frucc-trace` file, when there is one.
3551///
3552/// Returns whether that went well, and says why on standard error when it did not.
3553fn write_trace(
3554 opts: &Options,
3555 job: &Job,
3556 started: std::time::Instant,
3557 result: &Compiled,
3558 stderr: &mut impl std::io::Write,
3559) -> bool {
3560 let Some(path) = &opts.trace else {
3561 return true;
3562 };
3563 let output = match &job.output {
3564 Output::Stdout => "-",
3565 Output::File(path) | Output::Temporary(path) => path,
3566 };
3567 let record = trace::Record {
3568 input: &job.input,
3569 output,
3570 ok: !result.failed(),
3571 total: started.elapsed(),
3572 timing: &result.timing,
3573 };
3574 match trace::append(path, &record) {
3575 Ok(()) => true,
3576 Err(e) => {
3577 let _ = writeln!(stderr, "rucc: error: {e}");
3578 false
3579 }
3580 }
3581}
3582
3583/// One line of `-time`, which is what a step was called and how long it took.
3584///
3585/// GCC's two numbers are the user and the system time of a subprocess it ran. This compiler runs
3586/// no subprocess for anything but the link, so what is measured here is the wall clock of the
3587/// step and the second column is always zero. The shape of the line is kept because a person
3588/// reading it next to gcc's should not have to work out which column is which.
3589fn say_time(name: &str, took: std::time::Duration, stderr: &mut impl std::io::Write) {
3590 let _ = writeln!(stderr, "# {name} {:.2} {:.2}", took.as_secs_f64(), 0.0);
3591}
3592
3593/// Writes one job's result where the plan said it goes.
3594///
3595/// # Errors
3596///
3597/// Returns the message to print, which names the file when there is one, because "permission
3598/// denied" on its own does not say which file was refused.
3599fn write_out(output: &Output, bytes: &[u8]) -> Result<(), String> {
3600 match output {
3601 Output::Stdout => {
3602 let mut stdout = std::io::stdout().lock();
3603 stdout.write_all(bytes).map_err(|e| format!("writing to standard output: {e}"))
3604 }
3605 Output::File(path) | Output::Temporary(path) => {
3606 std::fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))
3607 }
3608 }
3609}
3610
3611/// The target a program name asks for, the way `aarch64-linux-gnu-gcc` is gcc for that target.
3612///
3613/// `program` is the path the compiler was started as. The name without its directory and without a
3614/// trailing `.exe` has to end in `-rucc`, and what comes before that has to be a target this
3615/// compiler knows, or there is no answer and the name means nothing. A link named `my-rucc` is
3616/// therefore just rucc and not an error.
3617pub fn target_from_program(program: &str) -> Option<String> {
3618 let name = program.rsplit(['/', '\\']).next()?;
3619 let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
3620 let triple = name.strip_suffix("-rucc")?;
3621 triple.parse::<Triple>().ok()?;
3622 Some(triple.to_owned())
3623}
3624
3625/// [`run`] for a compiler started as `program`, which is `argv[0]`.
3626///
3627/// A target taken from the name goes in front of `args`, so a `--target=` written on the command
3628/// line comes later and wins, which is what gcc and clang do with a prefixed name.
3629pub fn run_as(program: &str, args: &[String]) -> i32 {
3630 match target_from_program(program) {
3631 Some(triple) => {
3632 let mut all = Vec::with_capacity(args.len() + 1);
3633 all.push(format!("--target={triple}"));
3634 all.extend_from_slice(args);
3635 run(&all)
3636 }
3637 None => run(args),
3638 }
3639}
3640
3641/// What `--version` prints.
3642///
3643/// The first line is ours and is the one every harness we have reads. The second is for build
3644/// systems that decide what kind of compiler they have by reading this text. Meson takes the GNU
3645/// path only when it finds "Free Software Foundation" here, and otherwise stops with "Unknown
3646/// compiler" before it has asked a single question, which is how the whole of a meson build is
3647/// lost to one sentence. Past that point meson reads the version from `__GNUC__` and asks the
3648/// preprocessor everything else, so the line decides the path and nothing more. It says what is
3649/// true, that rucc speaks the dialect of GCC 16, and it does not claim to be GCC.
3650fn banner() -> String {
3651 format!(
3652 "rucc {VERSION}\nA C compiler for the GNU C dialect of GCC 16 from the Free Software Foundation.\nThis is free software under the Apache License 2.0. There is NO warranty.\n"
3653 )
3654}
3655
3656/// Runs the driver and returns the process exit code.
3657///
3658/// `args` excludes the program name. Output goes to `stdout` and errors to `stderr`, which
3659/// is the one place in the compiler that is true.
3660pub fn run(args: &[String]) -> i32 {
3661 match parse_args(args) {
3662 Ok(Action::Help) => {
3663 print!("{USAGE}");
3664 0
3665 }
3666 Ok(Action::Version) => {
3667 print!("{}", banner());
3668 0
3669 }
3670 Ok(Action::Print(line)) => {
3671 println!("{line}");
3672 0
3673 }
3674 Ok(Action::PrintConfig(opts)) => {
3675 print!("{}", print_config(&opts));
3676 0
3677 }
3678 Ok(Action::PrintPipeline(opts)) => {
3679 print!("{}", print_pipeline(&opts));
3680 0
3681 }
3682 Ok(Action::PrintPlan { opts, plan, link }) => {
3683 print!("{}", plan.render());
3684 // The line as it would be typed, which is the half of `-###` that section 4.3 says
3685 // arrives with the link. It is printed even when the linker is not on this machine,
3686 // because what a build wants from `-###` is what the compiler would do.
3687 if let Some(job) = &plan.link {
3688 match link_line(&opts, &link, job) {
3689 Ok(line) => println!("{line}"),
3690 Err(why) => {
3691 let mut stderr = std::io::stderr().lock();
3692 let _ = writeln!(stderr, "rucc: error: {why}");
3693 return 1;
3694 }
3695 }
3696 }
3697 0
3698 }
3699 Ok(Action::Fetch { what, target, cache }) => {
3700 let kernel = rucc_sysroot::Kernel::for_target(&cache, target)
3701 .map(|_| &rucc_sysroot::KERNEL_HEADERS);
3702 fetch_sysroot(what, kernel, target, &cache)
3703 }
3704 Ok(Action::FetchMsvcSdk { target, accepted, cache }) => {
3705 msvc::fetch_msvc_sdk(target, accepted, &cache)
3706 }
3707 Ok(Action::Compile { opts, plan, link, jobs, verbose, notes }) => {
3708 {
3709 let mut stderr = std::io::stderr().lock();
3710 // Before the plan rather than after it, because a note is about the command line
3711 // and the plan is what the command line was read as, so the reader wants the two
3712 // in that order.
3713 for note in ¬es {
3714 let _ = writeln!(stderr, "rucc: warning: {note}");
3715 }
3716 if verbose {
3717 let _ = write!(stderr, "{}", plan.render());
3718 let _ = writeln!(stderr, "workers: {}", jobs.count());
3719 // What `gcc -v` says about headers, because meson and cmake read it to find the
3720 // system directories.
3721 let _ = write!(stderr, "{}", opts.search.render_gcc());
3722 }
3723 }
3724 if opts.emit == EmitKind::Preprocessed {
3725 return preprocess_all(&opts, &plan);
3726 }
3727 if opts.emit == EmitKind::Archive {
3728 return archive_all(&opts, &plan);
3729 }
3730 if opts.emit != EmitKind::Executable {
3731 return compile_all(&opts, &plan);
3732 }
3733 link_all(&opts, &plan, &link, verbose)
3734 }
3735 Err(e) => {
3736 let mut stderr = std::io::stderr().lock();
3737 let _ = writeln!(stderr, "rucc: error: {e}");
3738 let _ = writeln!(stderr, "rucc: note: run `rucc --help` for usage");
3739 1
3740 }
3741 }
3742}
3743
3744#[cfg(test)]
3745mod tests {
3746 use rucc_session::{
3747 Contract, GnucVersion, IncludeForm, LtoJobs, OptLevel, Partition, Patchable, Visibility,
3748 };
3749
3750 use super::*;
3751
3752 fn args(s: &[&str]) -> Vec<String> {
3753 s.iter().map(|x| (*x).to_owned()).collect()
3754 }
3755
3756 /// A target to write down where the host would otherwise decide, for the tests whose answer
3757 /// would be a different one on a different machine.
3758 ///
3759 /// Most of the tests here never name a target, which is right, because most of what the driver
3760 /// does with a command line is the same wherever it runs and a test that pinned one would be
3761 /// saying so in every case for the sake of the two that need it. The two that need it are the
3762 /// ones whose answer comes off the target rather than off the command line: the name an object
3763 /// gets, which is `a.o` here and `a.obj` on Windows, and whether Microsoft's reading of a
3764 /// nameless member is on, which is off here and on there. Both are the compiler being right, and
3765 /// a test that leaves the target to the host is asking a question with two correct answers.
3766 const LINUX: &str = "--target=x86_64-unknown-linux-gnu";
3767
3768 #[test]
3769 fn a_response_file_is_split_the_way_libiberty_splits_one() {
3770 let words = response_words("-Wl,--as-needed 'a b' \"c d\"\ne\\ f '' \"it's\" g\\\\h\n");
3771 assert_eq!(words, ["-Wl,--as-needed", "a b", "c d", "e f", "", "it's", "g\\h"]);
3772 assert!(response_words(" \n\t").is_empty());
3773 }
3774
3775 #[test]
3776 fn a_response_file_on_the_command_line_is_read_in_its_place() {
3777 let dir = std::env::temp_dir().join(format!("rucc-rsp-{}", std::process::id()));
3778 std::fs::create_dir_all(&dir).unwrap();
3779 let inner = dir.join("inner.rsp");
3780 std::fs::write(&inner, "-lm\n").unwrap();
3781 let outer = dir.join("outer.rsp");
3782 std::fs::write(&outer, format!("-o 'my prog' -Wl,--as-needed @{}\n", inner.display()))
3783 .unwrap();
3784 let line = args(&["x.o", &format!("@{}", outer.display()), "@no-such-file"]);
3785 assert_eq!(
3786 response_files(&line).unwrap(),
3787 args(&["x.o", "-o", "my prog", "-Wl,--as-needed", "-lm", "@no-such-file"])
3788 );
3789 let itself = dir.join("itself.rsp");
3790 std::fs::write(&itself, format!("@{}", itself.display())).unwrap();
3791 let looped = response_files(&args(&[&format!("@{}", itself.display())]));
3792 assert!(looped.is_err(), "a file that names itself should be refused");
3793 std::fs::remove_dir_all(&dir).unwrap();
3794 }
3795
3796 #[test]
3797 fn help_and_version_win_over_everything_else() {
3798 assert_eq!(parse_args(&args(&["-c", "--help", "x.c"])).unwrap(), Action::Help);
3799 assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
3800 }
3801
3802 fn compile(s: &[&str]) -> (Box<Options>, Box<Plan>) {
3803 match parse_args(&args(s)).expect("expected a compilation") {
3804 Action::Compile { opts, plan, .. } => (opts, plan),
3805 other => panic!("expected a compilation, got {other:?}"),
3806 }
3807 }
3808
3809 fn linking(s: &[&str]) -> (Box<LinkOptions>, Box<Plan>) {
3810 match parse_args(&args(s)).expect("expected a compilation") {
3811 Action::Compile { link, plan, .. } => (link, plan),
3812 other => panic!("expected a compilation, got {other:?}"),
3813 }
3814 }
3815
3816 fn notes(s: &[&str]) -> Vec<String> {
3817 match parse_args(&args(s)).expect("expected a compilation") {
3818 Action::Compile { notes, .. } => notes,
3819 other => panic!("expected a compilation, got {other:?}"),
3820 }
3821 }
3822
3823 /// The ordinary command line has nothing to say about itself, which is the property that makes
3824 /// a note worth reading when there is one.
3825 #[test]
3826 fn a_command_line_with_nothing_wrong_with_it_carries_no_notes() {
3827 assert_eq!(notes(&["-c", "a.c"]), Vec::<String>::new());
3828 }
3829
3830 /// A directory that is not there contributes nothing to the search path, so there is no tree to
3831 /// read a release out of and nothing to compare the pin against. Said as a test because this is
3832 /// the shape a hermetic machine takes: the probe reads the disk and every other machine has a
3833 /// different disk, so what can be asserted here is the silence.
3834 #[test]
3835 fn a_named_tree_that_is_not_on_the_machine_is_not_a_release_mismatch() {
3836 let said =
3837 notes(&["--target=x86_64-linux-gnu.2.28", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
3838 assert_eq!(said, Vec::<String>::new());
3839 }
3840
3841 #[test]
3842 fn collects_inputs_and_flags() {
3843 let (opts, plan) = compile(&["-c", "-O2", "-g", "a.c", "b.c"]);
3844 let paths: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
3845 assert_eq!(paths, vec!["a.c", "b.c"]);
3846 assert_eq!(opts.opt_level, OptLevel::O2);
3847 assert_eq!(opts.emit, EmitKind::Object);
3848 assert!(opts.debug_info);
3849 }
3850
3851 /// The unstable options, which are spelled apart from everything else on purpose: what is
3852 /// under `-Z` promises nothing, and a build that reaches for one should have had to say so.
3853 #[test]
3854 fn an_unstable_option_is_taken_and_one_that_does_not_exist_is_refused() {
3855 let (opts, _) = compile(&["-c", "-Zrule-coverage=/tmp/rules.cov", "a.c"]);
3856 assert_eq!(opts.rule_coverage.as_deref(), Some("/tmp/rules.cov"));
3857
3858 let (plain, _) = compile(&["-c", "a.c"]);
3859 assert_eq!(plain.rule_coverage, None, "nothing is measured unless it was asked for");
3860
3861 assert!(parse_args(&args(&["-Zrule-coverage=", "a.c"])).is_err(), "a file with no name");
3862 let unknown = parse_args(&args(&["-Zwhat", "a.c"])).expect_err("there is no such option");
3863 assert!(unknown.message.contains("4.11"), "{}", unknown.message);
3864 }
3865
3866 /// The other measurement written to a file, which reads the same way and fails the same way.
3867 #[test]
3868 fn where_the_register_pressure_goes_is_asked_for_the_same_way() {
3869 let (opts, _) = compile(&["-c", "-O2", "-Zregister-pressure=/tmp/spills.txt", "a.c"]);
3870 assert_eq!(opts.register_pressure.as_deref(), Some("/tmp/spills.txt"));
3871
3872 let (plain, _) = compile(&["-c", "a.c"]);
3873 assert_eq!(plain.register_pressure, None, "nothing is measured unless it was asked for");
3874
3875 assert!(parse_args(&args(&["-Zregister-pressure=", "a.c"])).is_err(), "no file named");
3876 }
3877
3878 /// The third one, which says what the pre-selection lowering group did.
3879 #[test]
3880 fn a_switch_shape_is_forced_by_name_and_only_by_one_it_has() {
3881 let (opts, _) = compile(&["-c", "-O2", "-Zswitch=walk", "a.c"]);
3882 assert_eq!(opts.switch_shape.as_deref(), Some("walk"));
3883 let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3884 assert_eq!(plain.switch_shape, None, "nothing is forced unless it was asked for");
3885 assert!(parse_args(&args(&["-Zswitch=bit-test", "a.c"])).is_err(), "not a shape it forces");
3886 }
3887
3888 #[test]
3889 fn where_the_lowering_dump_goes_is_asked_for_the_same_way() {
3890 let (opts, _) = compile(&["-c", "-O2", "-Zlowering=/tmp/lowering.txt", "a.c"]);
3891 assert_eq!(opts.lowering_dump.as_deref(), Some("/tmp/lowering.txt"));
3892
3893 let (plain, _) = compile(&["-c", "a.c"]);
3894 assert_eq!(plain.lowering_dump, None, "nothing is dumped unless it was asked for");
3895
3896 assert!(parse_args(&args(&["-Zlowering=", "a.c"])).is_err(), "no file named");
3897 }
3898
3899 /// Scheduling, which has the three way answer every optimization flag has: on, off, and
3900 /// nothing said, which is whatever the optimization level asks for. The name is gcc's, and
3901 /// gcc's has a two in it because gcc has a scheduler before allocation and one after and this
3902 /// is the one after.
3903 #[test]
3904 fn scheduling_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
3905 let (on, _) = compile(&["-c", "-O0", "-fschedule-insns2", "a.c"]);
3906 assert_eq!(on.schedule_insns, Some(true));
3907
3908 let (off, _) = compile(&["-c", "-O2", "-fno-schedule-insns2", "a.c"]);
3909 assert_eq!(off.schedule_insns, Some(false));
3910
3911 let (quiet, _) = compile(&["-c", "-O2", "a.c"]);
3912 assert_eq!(quiet.schedule_insns, None, "nothing said, so the level decides");
3913 assert!(quiet.opt_level.schedules(), "and at this level the level says yes");
3914
3915 let (none, _) = compile(&["-c", "a.c"]);
3916 assert!(!none.opt_level.schedules(), "at no optimization it says no");
3917 }
3918
3919 /// Tail calls, which gcc spells as sibling calls and turns on at `-O2` and `-Os`.
3920 #[test]
3921 fn sibling_calls_can_be_turned_on_and_off_and_left_to_the_optimization_level() {
3922 let (on, _) = compile(&["-c", "-O1", "-foptimize-sibling-calls", "a.c"]);
3923 assert_eq!(on.sibling_calls, Some(true));
3924
3925 let (off, _) = compile(&["-c", "-O2", "-fno-optimize-sibling-calls", "a.c"]);
3926 assert_eq!(off.sibling_calls, Some(false));
3927
3928 let (quiet, _) = compile(&["-c", "-Os", "a.c"]);
3929 assert_eq!(quiet.sibling_calls, None, "nothing said, so the level decides");
3930 assert!(quiet.opt_level.sibling_calls(), "and at this level the level says yes");
3931
3932 let (one, _) = compile(&["-c", "-O1", "a.c"]);
3933 assert!(!one.opt_level.sibling_calls(), "gcc leaves them off at -O1");
3934 }
3935
3936 /// Whether the timing model is worth holding an instruction back over, which is a `-Z` because
3937 /// it is a question about a target's description rather than about the program being compiled.
3938 #[test]
3939 fn whether_the_timing_model_is_cycle_accurate_can_be_overridden() {
3940 let (yes, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=yes", "a.c"]);
3941 assert_eq!(yes.cycle_accurate_model, Some(true));
3942
3943 let (no, _) = compile(&["-c", "-O2", "-Zcycle-accurate-model=no", "a.c"]);
3944 assert_eq!(no.cycle_accurate_model, Some(false));
3945
3946 let (plain, _) = compile(&["-c", "-O2", "a.c"]);
3947 assert_eq!(plain.cycle_accurate_model, None, "the target's own answer stands");
3948
3949 let bad = parse_args(&args(&["-Zcycle-accurate-model=maybe", "a.c"]))
3950 .expect_err("it takes yes or no");
3951 assert!(bad.message.contains("yes or no"), "{}", bad.message);
3952 }
3953
3954 #[test]
3955 fn a_bare_dash_o_means_o1_the_way_gcc_reads_it() {
3956 let (opts, _) = compile(&["-O", "a.c"]);
3957 assert_eq!(opts.opt_level, OptLevel::O1);
3958 }
3959
3960 #[test]
3961 fn dash_x_applies_to_later_inputs_only_and_none_stops_it() {
3962 let (_, plan) = compile(&["a.o", "-x", "c", "b.txt", "-x", "none", "c.o"]);
3963 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
3964 assert_eq!(plan.jobs[1].kind, InputKind::C);
3965 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
3966 }
3967
3968 #[test]
3969 fn dash_x_can_be_joined_to_its_language() {
3970 let (_, plan) = compile(&["a.o", "-xc", "b.txt", "-xnone", "c.o"]);
3971 assert_eq!(plan.jobs[0].kind, InputKind::LinkerInput);
3972 assert_eq!(plan.jobs[1].kind, InputKind::C);
3973 assert_eq!(plan.jobs[2].kind, InputKind::LinkerInput);
3974 }
3975
3976 #[test]
3977 fn dash_j_reaches_the_scheduler_and_defaults_to_the_machine() {
3978 let (_, _, jobs) = match parse_args(&args(&["-j4", "a.c"])).unwrap() {
3979 Action::Compile { opts, plan, jobs, .. } => (opts, plan, jobs),
3980 other => panic!("expected a compilation, got {other:?}"),
3981 };
3982 assert_eq!(jobs.count(), 4);
3983
3984 let default = match parse_args(&args(&["a.c"])).unwrap() {
3985 Action::Compile { jobs, .. } => jobs,
3986 other => panic!("expected a compilation, got {other:?}"),
3987 };
3988 assert_eq!(default, Jobs::available());
3989 assert!(parse_args(&args(&["-j0", "a.c"])).is_err());
3990 }
3991
3992 #[test]
3993 fn triple_hash_prints_the_plan_and_runs_nothing() {
3994 let a = parse_args(&args(&["-###", "-c", "a.c"])).unwrap();
3995 let Action::PrintPlan { plan, .. } = a else { panic!("expected a plan dump") };
3996 assert!(plan.render().contains("a.c: preprocess, compile, assemble -> a.o"));
3997 }
3998
3999 #[test]
4000 fn the_flag_that_keeps_the_intermediate_files_has_three_spellings_and_two_meanings() {
4001 // The bare one is `=obj` and not `=cwd`. gcc's manual says the opposite and gcc 16 does
4002 // this, and following the compiler is what makes a build that reads either of them find
4003 // the files where they are.
4004 assert_eq!(compile(&["-c", "-save-temps", "a.c"]).0.save_temps, SaveTemps::Object);
4005 assert_eq!(compile(&["-c", "-save-temps=obj", "a.c"]).0.save_temps, SaveTemps::Object);
4006 assert_eq!(compile(&["-c", "-save-temps=cwd", "a.c"]).0.save_temps, SaveTemps::Cwd);
4007 assert_eq!(compile(&["-c", "a.c"]).0.save_temps, SaveTemps::No);
4008 // The last one on the line decides, the way it does for every other flag with an
4009 // argument, and a keyword that is neither is fatal rather than ignored: a run that kept
4010 // nothing and said nothing looks exactly like one where the files were not produced.
4011 let (opts, _) = compile(&["-c", "-save-temps", "-save-temps=cwd", "a.c"]);
4012 assert_eq!(opts.save_temps, SaveTemps::Cwd);
4013 let e = parse_args(&args(&["-c", "-save-temps=nowhere", "a.c"])).unwrap_err();
4014 assert!(e.message.contains("accepted: cwd, obj"), "{}", e.message);
4015 }
4016
4017 #[test]
4018 fn the_flag_that_times_each_step_reaches_the_options_and_changes_nothing_else() {
4019 let (opts, plan) = compile(&["-c", "-time", "a.c"]);
4020 let (plain, without) = compile(&["-c", "a.c"]);
4021 assert!(opts.time);
4022 assert!(!plain.time);
4023 // Against the same line without the flag rather than against a spelling of the object's
4024 // name, since what the object is called is the host's business and this is not about that.
4025 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4026 }
4027
4028 #[test]
4029 fn dash_x_names_what_it_accepts_when_it_does_not_know_a_language() {
4030 let e = parse_args(&args(&["-x", "fortran", "a.c"])).unwrap_err();
4031 assert!(e.message.contains("assembler-with-cpp"), "{}", e.message);
4032 }
4033
4034 /// What `--fetch` says for a target this release pins nothing for, which today is every target
4035 /// but the three windows-gnu ones, the four musl ones and the eight glibc ones.
4036 #[test]
4037 fn a_fetch_of_a_target_nothing_is_pinned_for_says_so_rather_than_reaching_the_network() {
4038 let e = parse_args(&args(&["--fetch", "x86_64-linux-gnux32"])).unwrap_err();
4039 assert!(e.message.contains("pins no sysroot for x86_64-linux-gnux32"), "{}", e.message);
4040 // And what it does pin, because a release with some rows in the table and a release with
4041 // none are two situations and the second sentence is what tells them apart.
4042 assert!(e.message.contains("x86_64-windows-gnu"), "{}", e.message);
4043 // The joined spelling is the same flag.
4044 let joined = parse_args(&args(&["--fetch=x86_64-linux-gnux32"])).unwrap_err();
4045 assert_eq!(joined, e);
4046 }
4047
4048 /// The two targets a release will never pin, which is a different answer from the one above.
4049 ///
4050 /// Section 13.4. A person who reads "this release pins no sysroot yet" waits for a release that
4051 /// does, and no release of this compiler can ship either of these, so the message names the
4052 /// licence that decides it and what to do instead.
4053 #[test]
4054 fn a_fetch_of_a_target_behind_a_licence_wall_says_so_rather_than_saying_not_yet() {
4055 let e = parse_args(&args(&["--fetch", "aarch64-macos"])).unwrap_err();
4056 assert!(e.message.contains("Xcode licence"), "{}", e.message);
4057 assert!(e.message.contains("there never will be"), "{}", e.message);
4058 assert!(!e.message.contains("tamnd/rucc-cross"), "{}", e.message);
4059
4060 let e = parse_args(&args(&["--fetch", "x86_64-windows-msvc"])).unwrap_err();
4061 assert!(e.message.contains("redistributed"), "{}", e.message);
4062 // The way out of this one is a target rather than a download, and it is the default already.
4063 assert!(e.message.contains("mingw-w64"), "{}", e.message);
4064 // And the mingw-w64 target next to it is ours to ship and published, so the same flag has
4065 // something to get rather than a licence to explain.
4066 let action = parse_args(&args(&["--fetch", "x86_64-windows-gnu"])).expect("it is pinned");
4067 let Action::Fetch { what, .. } = action else { panic!("{action:?}") };
4068 assert_eq!(what.tuple, "x86_64-windows-gnu");
4069 }
4070
4071 #[test]
4072 fn the_other_fetch_takes_a_target_behind_microsofts_wall_and_carries_the_acceptance() {
4073 // Both spellings of the flag, because a flag that takes a tuple gets written both ways.
4074 for line in [
4075 vec!["--fetch-msvc-sdk", "x86_64-windows-msvc"],
4076 vec!["--fetch-msvc-sdk=x86_64-windows-msvc"],
4077 ] {
4078 let action = parse_args(&args(&line)).expect("that is a target behind the wall");
4079 let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4080 panic!("{action:?}")
4081 };
4082 assert_eq!(target.to_canonical_string(), "x86_64-windows-msvc");
4083 // Nothing on the line accepted anything, so nothing did.
4084 assert!(!accepted);
4085 }
4086
4087 // And both spellings of the word, because the prose here uses one and most of the people
4088 // typing this will reach for the other.
4089 for word in ["--accept-licence", "--accept-license"] {
4090 let action = parse_args(&args(&["--fetch-msvc-sdk", "aarch64-windows-msvc", word]))
4091 .expect("that is a target behind the wall");
4092 let Action::FetchMsvcSdk { target, accepted, .. } = action else {
4093 panic!("{action:?}")
4094 };
4095 assert_eq!(target.to_canonical_string(), "aarch64-windows-msvc");
4096 assert!(accepted, "{word} should have been read");
4097 }
4098 }
4099
4100 #[test]
4101 fn the_other_fetch_refuses_the_command_lines_that_do_not_mean_anything() {
4102 // A tuple is what it gets, so a flag with nothing after it is not a command.
4103 let e = parse_args(&args(&["--fetch-msvc-sdk"])).unwrap_err();
4104 assert!(e.message.contains("requires the target"), "{}", e.message);
4105 let e = parse_args(&args(&["--fetch-msvc-sdk", "not-a-target"])).unwrap_err();
4106 assert!(e.message.contains("there is no SDK to get"), "{}", e.message);
4107
4108 // `--offline` forbids every download and this one asks for one, whichever order they came
4109 // in, which is the same answer `--fetch` gives.
4110 for line in [
4111 vec!["--offline", "--fetch-msvc-sdk", "x86_64-windows-msvc"],
4112 vec!["--fetch-msvc-sdk", "x86_64-windows-msvc", "--offline"],
4113 ] {
4114 let e = parse_args(&args(&line)).unwrap_err();
4115 assert!(e.message.contains("two opposite things"), "{}", e.message);
4116 }
4117
4118 // It gets an SDK and compiles nothing, so a file on the same line would be read by nothing.
4119 let e = parse_args(&args(&["--fetch-msvc-sdk", "x86_64-windows-msvc", "a.c"])).unwrap_err();
4120 assert!(e.message.contains("compiles nothing"), "{}", e.message);
4121
4122 // The two fetches are two commands and a line that asked for both asked for neither.
4123 let e = parse_args(&args(&[
4124 "--fetch",
4125 "x86_64-windows-gnu",
4126 "--fetch-msvc-sdk",
4127 "x86_64-windows-msvc",
4128 ]))
4129 .unwrap_err();
4130 assert!(e.message.contains("two different commands"), "{}", e.message);
4131
4132 // And an acceptance with nothing to accept for is a command line that says something about
4133 // a licence no part of it goes near.
4134 let e = parse_args(&args(&["--accept-licence", "-c", "a.c"])).unwrap_err();
4135 assert!(e.message.contains("--fetch-msvc-sdk <tuple> is the command"), "{}", e.message);
4136 }
4137
4138 /// An Apple target on a machine with no SDK, which is section 8.6's other host.
4139 ///
4140 /// Not run on a mac, where the SDK this is about is installed and the compile is the ordinary one
4141 /// that uses it. What the reason says is asserted in `rucc_sysroot::wall` and where it is printed
4142 /// is asserted in `rucc-pp`, so what is left here is that the driver works it out and leaves it
4143 /// where the preprocessor will find it, and that neither way past the wall leaves one behind.
4144 #[test]
4145 fn an_apple_target_with_no_sdk_anywhere_carries_the_licence_rather_than_a_missing_directory() {
4146 if cfg!(target_os = "macos") || std::env::var_os("SDKROOT").is_some() {
4147 return;
4148 }
4149 let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4150 let why = opts.search.missing_system().expect("the wall is the reason there are none");
4151 assert!(why.contains("aarch64-macos needs a macOS SDK"), "{why}");
4152 assert!(why.contains("Xcode licence"), "{why}");
4153 assert!(why.contains("-isysroot"), "{why}");
4154
4155 // A program that includes none of the library needs none of the SDK, which is what section
4156 // 8.6 means by being able to target the platform without one, so there is nothing to explain.
4157 let (opts, _) = compile(&["--target=aarch64-macos", "-nostdinc", "-c", "a.c"]);
4158 assert_eq!(opts.search.missing_system(), None);
4159 // And naming a path is the other way through, whether or not the path is there: a mistyped
4160 // directory is a mistake to report on its own terms rather than a licence to explain.
4161 let (opts, _) = compile(&["--target=aarch64-macos", "-isysroot", "/opt/sdk", "-c", "a.c"]);
4162 assert_eq!(opts.search.missing_system(), None);
4163 }
4164
4165 /// The same wall on the compile side of an MSVC target, where the way past it is a tuple.
4166 ///
4167 /// Not run on Windows, for the same reason the one above is not run on a mac: the wall stands in
4168 /// front of an SDK this machine does not have, and a Windows machine is the kind that does. The
4169 /// driver asks `vswhere` where Visual Studio is and takes the newest kit under it, so on a box
4170 /// with the build tools installed there are headers, no wall and nothing here to be about.
4171 /// `INCLUDE` is the other way a machine has one and is the other half of the guard, since a
4172 /// person can set that anywhere while Visual Studio is only found on the platform it runs on.
4173 #[test]
4174 fn an_msvc_target_with_no_sdk_named_says_which_environment_needs_nothing_installed() {
4175 if cfg!(target_os = "windows") || std::env::var_os("INCLUDE").is_some() {
4176 return;
4177 }
4178 let (opts, _) = compile(&["--target=x86_64-windows-msvc", "-c", "a.c"]);
4179 let why = opts.search.missing_system().expect("the wall is the reason there are none");
4180 assert!(why.contains("the Windows SDK and its universal CRT"), "{why}");
4181 assert!(why.contains("mingw-w64"), "{why}");
4182 // And the mingw-w64 target has its headers from us, so nothing is missing to explain.
4183 let (opts, _) = compile(&["--target=x86_64-windows-gnu", "-c", "a.c"]);
4184 assert_eq!(opts.search.missing_system(), None);
4185 }
4186
4187 #[test]
4188 fn a_fetch_with_no_target_and_a_fetch_of_a_tuple_that_is_not_one_both_say_which() {
4189 let e = parse_args(&args(&["--fetch"])).unwrap_err();
4190 assert!(e.message.contains("--fetch requires"), "{}", e.message);
4191 let e = parse_args(&args(&["--fetch", "sparc64-solaris-gnu"])).unwrap_err();
4192 assert!(e.message.contains("--fetch sparc64-solaris-gnu"), "{}", e.message);
4193 assert!(e.message.contains("no sysroot to get"), "{}", e.message);
4194 }
4195
4196 /// Both flags on one line ask for opposite things, in either order.
4197 #[test]
4198 fn a_fetch_and_offline_together_is_a_refusal_whichever_way_round_they_are_written() {
4199 for line in [
4200 vec!["--offline", "--fetch", "x86_64-linux-musl"],
4201 vec!["--fetch", "x86_64-linux-musl", "--offline"],
4202 ] {
4203 let e = parse_args(&args(&line)).unwrap_err();
4204 assert!(e.message.contains("two opposite things"), "{}", e.message);
4205 }
4206 }
4207
4208 #[test]
4209 fn a_fetch_does_not_compile_anything_and_says_so_when_it_is_handed_a_file() {
4210 let e = parse_args(&args(&["--fetch", "x86_64-linux-musl", "a.c"])).unwrap_err();
4211 assert!(e.message.contains("compiles nothing"), "{}", e.message);
4212 assert!(e.message.contains("a.c"), "{}", e.message);
4213 }
4214
4215 /// `--offline` on its own is accepted and changes nothing, because an ordinary compile
4216 /// downloads nothing with or without it. A build that passes it everywhere is the case this is
4217 /// for, and it must not lose the compilation it was passed beside.
4218 #[test]
4219 fn offline_on_a_compilation_is_the_same_compilation() {
4220 let (opts, plan) = compile(&["-c", "--offline", "a.c"]);
4221 let (plain, without) = compile(&["-c", "a.c"]);
4222 assert_eq!(opts.target, plain.target);
4223 assert_eq!(plan.jobs.len(), without.jobs.len());
4224 assert_eq!(plan.jobs[0].output, without.jobs[0].output);
4225 }
4226
4227 #[test]
4228 fn a_deployment_target_comes_from_the_tuple_or_from_the_flag() {
4229 let version = |v: &str| rucc_tuple::Version::parse(v);
4230 let (opts, _) = compile(&["--target=aarch64-macos.13", "-c", "a.c"]);
4231 assert_eq!(opts.target, "aarch64-apple-darwin".parse().unwrap());
4232 assert_eq!(opts.os_version, version("13"));
4233 // The flag wins over the tuple, as it does under clang, and either spelling of it works.
4234 let (opts, _) =
4235 compile(&["--target=aarch64-macos.13", "-mmacosx-version-min=14.2", "-c", "a.c"]);
4236 assert_eq!(opts.os_version, version("14.2"));
4237 let (opts, _) = compile(&["--target=x86_64-macos", "-mmacos-version-min=12", "-c", "a.c"]);
4238 assert_eq!(opts.os_version, version("12"));
4239 // Nothing said leaves the platform's default to the target description.
4240 let (opts, _) = compile(&["--target=aarch64-macos", "-c", "a.c"]);
4241 assert_eq!(opts.os_version, None);
4242 // A Linux build that always passes the flag is not an Apple build because of it.
4243 let (opts, _) =
4244 compile(&["--target=aarch64-linux-gnu", "-mmacosx-version-min=13", "-c", "a.c"]);
4245 assert_eq!(opts.os_version, None);
4246 let e = parse_args(&args(&["-mmacosx-version-min=thirteen", "a.c"])).unwrap_err();
4247 assert!(e.message.contains("is not a version"), "{}", e.message);
4248 }
4249
4250 #[test]
4251 fn an_unknown_flag_is_an_error_rather_than_a_shrug() {
4252 let e = parse_args(&args(&["-fno-such-thing", "a.c"])).unwrap_err();
4253 assert!(e.message.contains("unknown option"), "{}", e.message);
4254 }
4255
4256 /// `-fpermissive` and the flag that turns it back off, which a build writes beside it when
4257 /// one directory needs the older rules and the rest of the tree does not.
4258 #[test]
4259 fn permissive_reads_in_both_directions_and_the_last_one_wins() {
4260 let (opts, _) = compile(&["-c", "a.c"]);
4261 assert!(!opts.permissive, "off unless it is asked for");
4262
4263 let (opts, _) = compile(&["-c", "-fpermissive", "a.c"]);
4264 assert!(opts.permissive);
4265
4266 let (opts, _) = compile(&["-c", "-fpermissive", "-fno-permissive", "a.c"]);
4267 assert!(!opts.permissive);
4268 }
4269
4270 #[test]
4271 fn asking_for_nested_functions_is_told_why_it_is_not_coming() {
4272 let e = parse_args(&args(&["-fnested-functions", "a.c"])).unwrap_err();
4273 assert!(e.message.contains("trampoline"), "{}", e.message);
4274 assert!(parse_args(&args(&["-fno-nested-functions", "a.c"])).is_ok());
4275 }
4276
4277 #[test]
4278 fn the_flag_every_configure_script_writes_is_taken() {
4279 // All four spellings, because a build writes whichever one its macros picked and a
4280 // compiler that takes three of them is a compiler that fails on the fourth.
4281 for flag in ["-fPIC", "-fpic", "-fPIE", "-fpie"] {
4282 let (opts, _) = compile(&["-c", flag, "a.c"]);
4283 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4284 }
4285 }
4286
4287 #[test]
4288 fn a_table_is_written_unless_the_build_says_nothing_will_walk_it() {
4289 let (opts, _) = compile(&["-c", "a.c"]);
4290 assert!(opts.unwinds(), "the default is off");
4291 let (opts, _) = compile(&["-c", "-fno-asynchronous-unwind-tables", "a.c"]);
4292 assert!(!opts.unwinds(), "the build was not taken at its word");
4293 let (opts, _) = compile(&[
4294 "-c",
4295 "-fno-asynchronous-unwind-tables",
4296 "-fasynchronous-unwind-tables",
4297 "a.c",
4298 ]);
4299 assert!(opts.unwinds(), "the last flag did not win");
4300 // The weaker request, which the same table answers, so a line that asks for a table and
4301 // against an asynchronous one gets one. That is gcc's arrangement and it turns up when a
4302 // build turns the asynchronous one off globally and a directory asks for a table back.
4303 let (opts, _) =
4304 compile(&["-c", "-fno-asynchronous-unwind-tables", "-funwind-tables", "a.c"]);
4305 assert!(opts.unwinds(), "the weaker request was dropped");
4306 let (opts, _) = compile(&["-c", "-fno-unwind-tables", "a.c"]);
4307 assert!(opts.unwinds(), "the weaker negative turned off the stronger request");
4308 let (opts, _) =
4309 compile(&["-c", "-fno-unwind-tables", "-fno-asynchronous-unwind-tables", "a.c"]);
4310 assert!(!opts.unwinds(), "both were turned off and one stayed on");
4311 }
4312
4313 #[test]
4314 fn the_flags_that_describe_what_this_compiler_already_does_are_taken() {
4315 // Every one of these is on a real build line somewhere and every one of them was an
4316 // unknown option. What they have in common is that the answer rucc gives is the answer
4317 // they ask for, so there is nothing to implement and nothing to refuse.
4318 for flag in [
4319 "-fno-common",
4320 "-fstrict-aliasing",
4321 "-fno-strict-aliasing",
4322 "-fdelete-null-pointer-checks",
4323 "-fno-delete-null-pointer-checks",
4324 "-frounding-math",
4325 "-fno-rounding-math",
4326 "-fexcess-precision=standard",
4327 "-fexcess-precision=fast",
4328 "-fexcess-precision=16",
4329 "-pipe",
4330 "-cpp",
4331 "-fdiagnostics-color",
4332 "-fno-diagnostics-color",
4333 "-fdiagnostics-color=always",
4334 "-fdiagnostics-color=never",
4335 "-fdiagnostics-color=auto",
4336 ] {
4337 let (opts, _) = compile(&["-c", flag, "a.c"]);
4338 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4339 }
4340 }
4341
4342 #[test]
4343 fn whether_an_exception_is_looked_at_is_kept_and_defaults_to_gccs_answer() {
4344 let (opts, _) = compile(&["-c", "a.c"]);
4345 assert!(opts.trapping_math, "the default was not gcc's");
4346 let (opts, _) = compile(&["-c", "-fno-trapping-math", "a.c"]);
4347 assert!(!opts.trapping_math);
4348 let (opts, _) = compile(&["-c", "-ftrapping-math", "a.c"]);
4349 assert!(opts.trapping_math, "spelling out the default turned it off");
4350 // The last one written wins, which is how a build line that inherits a flag from one
4351 // place and overrides it in another is read.
4352 let (opts, _) = compile(&["-c", "-fno-trapping-math", "-ftrapping-math", "a.c"]);
4353 assert!(opts.trapping_math);
4354 }
4355
4356 /// The flags a torture program writes on its own `dg-options` line, which is where most of
4357 /// these come from: a program reduced from a miscompilation names the pass that miscompiled
4358 /// it. Eighteen programs in the suite stopped on the driver before anything read them, and
4359 /// tamnd/rucc#1019 is the list.
4360 #[test]
4361 fn no_inline_turns_off_the_inlining_of_a_function_declared_inline() {
4362 let (opts, _) = compile(&["-c", "-O2", "-fno-inline", "a.c"]);
4363 assert_eq!(opts.passes, [(rucc_opt::inline::NAME.to_owned(), false)]);
4364 }
4365
4366 #[test]
4367 fn inlining_a_function_called_once_is_turned_off_and_on_by_its_own_flag() {
4368 for level in ["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz", "-Og"] {
4369 let (opts, _) = compile(&["-c", level, "-fno-inline-functions-called-once", "a.c"]);
4370 assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), false)], "{level}");
4371 let (opts, _) = compile(&["-c", level, "-finline-functions-called-once", "a.c"]);
4372 assert_eq!(opts.passes, [(rucc_opt::inline::ONCE.to_owned(), true)], "{level}");
4373 }
4374 }
4375
4376 #[test]
4377 fn the_flags_that_name_a_pass_of_gccs_own_are_taken_and_dropped() {
4378 for flag in [
4379 "-fno-tree-ccp",
4380 "-fno-tree-dominator-opts",
4381 "-fno-tree-vrp",
4382 "-fno-tree-bit-ccp",
4383 "-fno-tree-coalesce-vars",
4384 "-ftree-vectorize",
4385 "-ftree-loop-distribution",
4386 "-fipa-pta",
4387 "-fmodulo-sched",
4388 "-fno-vect-cost-model",
4389 "-fvect-cost-model=unlimited",
4390 "-fsimd-cost-model=cheap",
4391 "-fexpensive-optimizations",
4392 "-fno-early-inlining",
4393 "-finline-functions",
4394 "-foptimize-strlen",
4395 "-fno-ira-share-spill-slots",
4396 ] {
4397 let (opts, _) = compile(&["-c", flag, "a.c"]);
4398 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4399 assert!(opts.passes.is_empty(), "{flag} named a pass of gcc's and not one of ours");
4400 }
4401 }
4402
4403 /// The two namespaces are taken whole, so a name neither this test nor gcc 16 has heard of
4404 /// goes the same way as the ones above rather than stopping a build on the day gcc adds it.
4405 #[test]
4406 fn a_pass_name_in_either_family_is_taken_whether_or_not_it_is_one_gcc_has() {
4407 for flag in ["-ftree-no-such-pass", "-fno-ipa-no-such-pass"] {
4408 let (opts, _) = compile(&["-c", flag, "a.c"]);
4409 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4410 }
4411 }
4412
4413 /// A pass this compiler has keeps its flag, since the arms that read the registry are above
4414 /// the family arms. `dce` is the one both compilers have a name for, and `execute/pr97421-2.c`
4415 /// is the program that writes it.
4416 #[test]
4417 fn a_pass_name_this_compiler_has_is_still_read_as_a_pass() {
4418 let (opts, _) = compile(&["-c", "-fno-dce", "a.c"]);
4419 assert_eq!(opts.passes, vec![("dce".to_owned(), false)]);
4420 }
4421
4422 /// gcc's name for the unroller reaches the unroller, in both directions. libtommath puts
4423 /// `-funroll-loops` in `CFLAGS` unconditionally, and before this it was an unknown option and
4424 /// the build stopped on its first file.
4425 #[test]
4426 fn the_gcc_spelling_of_the_unroller_turns_the_unroller_on_and_off() {
4427 let (opts, _) = compile(&["-c", "-funroll-loops", "a.c"]);
4428 assert_eq!(opts.passes, vec![("unroll".to_owned(), true)]);
4429 let (opts, _) = compile(&["-c", "-fno-unroll-loops", "a.c"]);
4430 assert_eq!(opts.passes, vec![("unroll".to_owned(), false)]);
4431 }
4432
4433 /// The three transformations that are a module at a time are named by a flag as well, even
4434 /// though none of them is a `rucc_opt::Pass` and so none is reached by the generic arms.
4435 ///
4436 /// A bisection over a miscompilation turns one thing off at a time, and a transformation with
4437 /// no spelling of its own cannot be the one turned off.
4438 #[test]
4439 fn the_transformations_that_are_not_passes_are_still_named_by_a_flag() {
4440 let (opts, _) = compile(&["-c", "-fno-ipa-cp", "-fipa-sra", "-fno-libcall", "a.c"]);
4441 assert_eq!(
4442 opts.passes,
4443 vec![
4444 (rucc_opt::ipcp::NAME.to_owned(), false),
4445 (rucc_opt::ipasra::NAME.to_owned(), true),
4446 (rucc_opt::libcall::NAME.to_owned(), false),
4447 ]
4448 );
4449 let (opts, _) = compile(&["-c", "-flibcall", "a.c"]);
4450 assert_eq!(opts.passes, vec![(rucc_opt::libcall::NAME.to_owned(), true)]);
4451 }
4452
4453 /// Where a function starts is a question this compiler answers, so the flag that asks about it
4454 /// is answered rather than dropped. femtolisp's Makefile writes the bare form on every compile
4455 /// of the project, and before this it was an unknown option and the build stopped on its first
4456 /// file. The numbers are gcc 16's, read off `-S` on x86-64: nothing and the bare form both
4457 /// give `.p2align 4`, `=32` gives 5, `=3` gives 2, and the negative form gives `.align 8`.
4458 #[test]
4459 fn the_alignment_of_a_function_is_a_request_this_compiler_can_answer() {
4460 let (opts, _) = compile(&["-c", "-falign-functions", "a.c"]);
4461 assert_eq!(opts.align_functions, None, "the bare form asks for the default");
4462
4463 let (opts, _) = compile(&["-c", "-falign-functions=32", "a.c"]);
4464 assert_eq!(opts.align_functions, Some(32));
4465
4466 let (opts, _) = compile(&["-c", "-falign-functions=3", "a.c"]);
4467 assert_eq!(opts.align_functions, Some(4), "rounded up rather than refused");
4468
4469 let (opts, _) = compile(&["-c", "-falign-functions=32:8", "a.c"]);
4470 assert_eq!(opts.align_functions, Some(32), "the boundary is the answerable half");
4471
4472 for flag in ["-falign-functions=0", "-falign-functions=1"] {
4473 let (opts, _) = compile(&["-c", flag, "a.c"]);
4474 assert_eq!(opts.align_functions, None, "{flag} means the default");
4475 }
4476
4477 let (opts, _) = compile(&["-c", "-fno-align-functions", "a.c"]);
4478 assert_eq!(opts.align_functions, Some(8), "the smallest boundary the target has");
4479
4480 // The last one on the line wins, which is how gcc reads a repeated flag.
4481 let (opts, _) = compile(&["-c", "-falign-functions=32", "-falign-functions", "a.c"]);
4482 assert_eq!(opts.align_functions, None);
4483
4484 let e = parse_args(&args(&["-c", "-falign-functions=big", "a.c"])).unwrap_err();
4485 assert!(e.message.contains("number of bytes"), "{}", e.message);
4486 }
4487
4488 /// The other three of the family are about padding inside a body, so none of them is about
4489 /// where a function starts. Every spelling of each, since a build writes whichever one its
4490 /// author typed.
4491 #[test]
4492 fn the_alignment_flags_about_the_inside_of_a_body_are_taken_and_say_nothing() {
4493 for flag in [
4494 "-falign-labels",
4495 "-falign-loops",
4496 "-falign-jumps",
4497 "-falign-loops=16",
4498 "-falign-labels=32",
4499 "-fno-align-loops",
4500 "-fno-align-labels",
4501 "-fno-align-jumps",
4502 ] {
4503 let (opts, _) = compile(&["-c", flag, "a.c"]);
4504 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4505 assert_eq!(opts.align_functions, None, "{flag} is not about where a function starts");
4506 }
4507 }
4508
4509 /// The loop flag in either direction is an answer, and a command line that wrote neither
4510 /// leaves the level to decide.
4511 #[test]
4512 fn the_loop_alignment_flag_is_answered_both_ways() {
4513 assert_eq!(compile(&["-c", "-O2", "a.c"]).0.align_loops, None);
4514 assert_eq!(compile(&["-c", "-O0", "-falign-loops", "a.c"]).0.align_loops, Some(true));
4515 assert_eq!(compile(&["-c", "-O2", "-fno-align-loops", "a.c"]).0.align_loops, Some(false));
4516 assert_eq!(compile(&["-c", "-falign-loops=32", "a.c"]).0.align_loops, None, "a number");
4517 }
4518
4519 /// The encoding of the source is not a question about speed, so the one name that describes
4520 /// what the preprocessor does is taken and every other name is refused.
4521 #[test]
4522 fn the_input_charset_is_taken_when_it_names_the_one_that_is_read() {
4523 for flag in ["-finput-charset=utf-8", "-finput-charset=UTF-8", "-finput-charset=utf8"] {
4524 let (opts, _) = compile(&["-c", flag, "a.c"]);
4525 assert_eq!(opts.emit, EmitKind::Object, "{flag}");
4526 }
4527
4528 let e = parse_args(&args(&["-c", "-finput-charset=latin1", "a.c"])).unwrap_err();
4529 assert!(e.message.contains("latin1"), "{}", e.message);
4530 assert!(e.message.contains("UTF-8"), "what is read is worth saying: {}", e.message);
4531 }
4532
4533 /// `-fnon-call-exceptions` turns exceptions on unless `-fexceptions` or `-fno-exceptions` was
4534 /// written, and the one written wins whichever side of it it is on, which is gcc 16's reading.
4535 #[test]
4536 fn exceptions_are_on_when_asked_for_and_non_call_ones_ask_unless_told_not_to() {
4537 let (opts, _) = compile(&["-c", "a.c"]);
4538 assert!(!opts.exceptions && !opts.non_call_exceptions, "gcc's default for C is off");
4539 let (opts, _) = compile(&["-c", "-fexceptions", "a.c"]);
4540 assert!(opts.exceptions && !opts.non_call_exceptions);
4541 let (opts, _) = compile(&["-c", "-fexceptions", "-fno-exceptions", "a.c"]);
4542 assert!(!opts.exceptions);
4543 let (opts, _) = compile(&["-c", "-fnon-call-exceptions", "a.c"]);
4544 assert!(opts.exceptions && opts.non_call_exceptions);
4545 for line in [
4546 ["-fno-exceptions", "-fnon-call-exceptions"],
4547 ["-fnon-call-exceptions", "-fno-exceptions"],
4548 ] {
4549 let (opts, _) = compile(&["-c", line[0], line[1], "a.c"]);
4550 assert!(!opts.exceptions && opts.non_call_exceptions, "{line:?}");
4551 }
4552 let (opts, _) =
4553 compile(&["-c", "-fnon-call-exceptions", "-fno-non-call-exceptions", "a.c"]);
4554 assert!(!opts.exceptions && !opts.non_call_exceptions);
4555 let (opts, _) = compile(&["-c", "-fno-delete-dead-exceptions", "a.c"]);
4556 assert_eq!(opts.emit, EmitKind::Object);
4557 }
4558
4559 /// `-ffast-math` used to be refused beside it and is the family it names now, with each
4560 /// member settable on its own and the last word on each winning, which is gcc's reading.
4561 #[test]
4562 fn fast_math_is_the_family_it_names_and_the_last_word_on_each_member_wins() {
4563 let both = |line: &[&str]| {
4564 let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4565 let (link, _) = linking(&[line, &["a.c"]].concat());
4566 (opts, link)
4567 };
4568 let (opts, link) = both(&[]);
4569 assert_eq!(opts.math, Math::default());
4570 assert!(opts.trapping_math);
4571 assert!(!link.fast_math);
4572
4573 let (opts, link) = both(&["-ffast-math"]);
4574 assert!(opts.math.fast(opts.trapping_math), "{:?}", opts.math);
4575 assert!(!opts.trapping_math, "fast math turns trapping off");
4576 assert!(link.fast_math, "and it links the startup file");
4577
4578 // Taking one member back leaves the rest, and the whole is not fast math any more.
4579 let (opts, link) = both(&["-ffast-math", "-fno-finite-math-only"]);
4580 assert!(!opts.math.finite_only);
4581 assert!(!opts.math.errno && !opts.math.signed_zeros && opts.math.reciprocal);
4582 assert!(!opts.math.fast(opts.trapping_math));
4583 assert!(link.fast_math, "gcc's spec reads the flag and not the fields");
4584
4585 let (opts, _) = both(&["-ffast-math", "-ftrapping-math"]);
4586 assert!(opts.trapping_math);
4587 assert!(!opts.math.fast(opts.trapping_math));
4588 assert!(!opts.math.associative(opts.trapping_math));
4589
4590 let (opts, link) = both(&["-ffast-math", "-fno-fast-math"]);
4591 assert_eq!(opts.math, Math::default());
4592 assert!(opts.trapping_math);
4593 assert!(!link.fast_math);
4594
4595 // A member written alone is only that member.
4596 let (opts, link) = both(&["-fno-math-errno"]);
4597 assert_eq!(opts.math, Math { errno: false, ..Math::default() });
4598 assert!(opts.math.iec_559(opts.trapping_math), "errno is not an IEC 60559 question");
4599 assert!(!link.fast_math);
4600
4601 let (opts, link) = both(&["-funsafe-math-optimizations"]);
4602 assert!(opts.math.unsafe_math && opts.math.associative(opts.trapping_math));
4603 assert!(opts.math.errno && !opts.math.finite_only);
4604 assert!(link.fast_math);
4605 }
4606
4607 /// `-Ofast` is `-O3` with fast math as a default, which a later level and a
4608 /// `-fno-fast-math` on either side of it both take back.
4609 #[test]
4610 fn ofast_is_o3_with_fast_math_as_a_default_a_flag_can_take_back() {
4611 let both = |line: &[&str]| {
4612 let (opts, _) = compile(&[&["-c"], line, &["a.c"]].concat());
4613 let (link, _) = linking(&[line, &["a.c"]].concat());
4614 (opts, link)
4615 };
4616 let (opts, link) = both(&["-Ofast"]);
4617 assert_eq!(opts.opt_level, OptLevel::O3);
4618 assert!(opts.math.fast(opts.trapping_math));
4619 assert!(link.fast_math);
4620
4621 for line in [&["-Ofast", "-O2"][..], &["-fno-fast-math", "-Ofast"]] {
4622 let (opts, _) = both(line);
4623 assert!(!opts.math.fast(opts.trapping_math), "{line:?}");
4624 }
4625
4626 let (_, link) = both(&["-Ofast", "-mno-daz-ftz"]);
4627 assert_eq!(link.daz_ftz, Some(false));
4628 }
4629
4630 /// `-finstrument-functions` used to be refused beside those two, and it is taken now that the
4631 /// hooks are called. The last of it and its negative is the one that counts, as with any pair.
4632 #[test]
4633 fn instrument_functions_is_taken_and_the_last_of_the_pair_wins() {
4634 let (opts, _) = compile(&["-c", "-finstrument-functions", "a.c"]);
4635 assert!(opts.instrument_functions);
4636 let (opts, _) =
4637 compile(&["-c", "-finstrument-functions", "-fno-instrument-functions", "a.c"]);
4638 assert!(!opts.instrument_functions);
4639 }
4640
4641 #[test]
4642 fn asking_the_linker_to_merge_tentative_definitions_is_told_why_it_is_not_coming() {
4643 // The one of that family that is a request rather than a description, and it is a real
4644 // difference: two files each writing `int g;` link under it and do not without it.
4645 let e = parse_args(&args(&["-fcommon", "a.c"])).unwrap_err();
4646 assert!(e.message.contains(".bss"), "{}", e.message);
4647 assert!(e.message.contains("extern"), "the way out is worth saying: {}", e.message);
4648 }
4649
4650 #[test]
4651 fn asking_for_position_dependent_code_is_told_why_it_is_not_coming() {
4652 for flag in ["-fno-pic", "-fno-pie"] {
4653 let e = parse_args(&args(&[flag, "a.c"])).unwrap_err();
4654 assert!(e.message.contains("global offset table"), "{flag}: {}", e.message);
4655 // The one it may have meant, since the two are a letter apart and one of them is
4656 // about linking and is taken.
4657 assert!(e.message.contains("-no-pie"), "{flag}: {}", e.message);
4658 }
4659 }
4660
4661 #[test]
4662 fn a_program_name_with_a_known_target_in_front_of_rucc_picks_that_target() {
4663 let t = |p: &str| target_from_program(p);
4664 assert_eq!(t("aarch64-linux-gnu-rucc").as_deref(), Some("aarch64-linux-gnu"));
4665 assert_eq!(t("/usr/bin/riscv64-linux-musl-rucc").as_deref(), Some("riscv64-linux-musl"));
4666 assert_eq!(t(r"C:\bin\x86_64-windows-gnu-rucc.exe").as_deref(), Some("x86_64-windows-gnu"));
4667 assert_eq!(t("rucc"), None);
4668 assert_eq!(t("/usr/local/bin/rucc"), None);
4669 assert_eq!(t("my-rucc"), None);
4670 assert_eq!(t("sparc64-linux-gnu-rucc"), None);
4671 assert_eq!(t("aarch64-linux-gnu-gcc"), None);
4672 }
4673
4674 #[test]
4675 fn an_unsupported_target_names_itself() {
4676 let e = parse_args(&args(&["--target=sparc64-linux-gnu", "a.c"])).unwrap_err();
4677 assert!(e.message.contains("sparc64"), "{}", e.message);
4678 }
4679
4680 #[test]
4681 fn no_inputs_is_an_error_but_print_config_needs_none() {
4682 assert!(parse_args(&args(&[])).is_err());
4683 assert!(matches!(parse_args(&args(&["--print-config"])), Ok(Action::PrintConfig(_))));
4684 }
4685
4686 #[test]
4687 fn print_config_reports_the_target_it_was_given_not_the_host() {
4688 let a = parse_args(&args(&["--print-config", "--target=riscv64-linux-musl"])).unwrap();
4689 let Action::PrintConfig(opts) = a else { panic!("expected a configuration dump") };
4690 let text = print_config(&opts);
4691 assert!(text.contains("target: riscv64-unknown-linux-musl"), "{text}");
4692 assert!(text.contains("char-signed: false"), "{text}");
4693 assert!(text.contains("object-format: elf"), "{text}");
4694 assert!(text.contains("va-list: void-pointer"), "{text}");
4695 // RISC-V has a register file and this compiler has not written it down yet, and the
4696 // dump says which of those two it is rather than leaving the line out.
4697 assert!(text.contains("registers: none"), "{text}");
4698 assert!(text.contains("timing-model: none"), "{text}");
4699 }
4700
4701 /// The model the schedule was chosen with, which is a receipt anybody comparing two runs of a
4702 /// benchmark needs: two numbers that disagree are usually two models and not two compilers.
4703 #[test]
4704 fn print_config_names_the_model_the_schedule_was_chosen_with() {
4705 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4706 let text = print_config(&opts);
4707 let line = text.lines().find(|l| l.starts_with("timing-model:")).expect("the model");
4708 assert!(line.contains("Skylake"), "{line}");
4709 assert!(line.contains("published"), "a sentence saying where it came from: {line}");
4710 }
4711
4712 #[test]
4713 fn print_config_has_one_key_per_line_and_a_fixed_order() {
4714 let opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
4715 let text = print_config(&opts);
4716 let keys: Vec<&str> =
4717 text.lines().map(|l| l.split(':').next().unwrap_or_default()).collect();
4718 assert_eq!(keys[0], "version");
4719 assert_eq!(keys[1], "target");
4720 assert_eq!(keys.len(), 26);
4721 assert!(text.ends_with('\n'));
4722 }
4723
4724 #[test]
4725 fn the_safety_tier_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4726 let (opts, _) = compile(&["a.c"]);
4727 assert_eq!(opts.safety, rucc_session::Safety::Off);
4728
4729 for (flag, tier) in [
4730 ("-fsafety=detect", rucc_session::Safety::Detect),
4731 ("-fsafety=enforce", rucc_session::Safety::Enforce),
4732 ("-fsafety=kernel", rucc_session::Safety::Kernel),
4733 ("-fsafety=off", rucc_session::Safety::Off),
4734 ] {
4735 let (opts, _) = compile(&[flag, "a.c"]);
4736 assert_eq!(opts.safety, tier, "{flag}");
4737 }
4738
4739 // The last one wins, the way every other repeated flag on this command line does.
4740 let (opts, _) = compile(&["-fsafety=enforce", "-fsafety=off", "a.c"]);
4741 assert_eq!(opts.safety, rucc_session::Safety::Off);
4742
4743 // A misspelled tier is refused rather than ignored. Silently compiling without the
4744 // monitor a build asked for is the one failure mode this feature cannot have.
4745 let e = parse_args(&args(&["-fsafety=on", "a.c"])).unwrap_err();
4746 assert!(e.message.contains("is not a safety tier"), "{}", e.message);
4747 assert!(parse_args(&args(&["-fsafety", "a.c"])).is_err());
4748 }
4749
4750 #[test]
4751 fn the_padding_mode_is_read_off_the_command_line_and_a_wrong_one_is_refused() {
4752 // The default is the one section 9.3 of document 09 gives library code, which is that
4753 // padding does not participate, so a record filled a member at a time is not reported.
4754 let (opts, _) = compile(&["a.c"]);
4755 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4756
4757 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-init=padding", "a.c"]);
4758 assert_eq!(opts.padding, rucc_session::Padding::Tracked);
4759
4760 let (opts, _) = compile(&["-fsafety-init=padding", "-fsafety-init=nopadding", "a.c"]);
4761 assert_eq!(opts.padding, rucc_session::Padding::Ignored);
4762
4763 // The tier is still a tier. A flag whose name starts the same way must not be eaten by
4764 // the one above it, which is the thing worth pinning about a pair of names like these.
4765 let (opts, _) = compile(&["-fsafety-init=padding", "a.c"]);
4766 assert_eq!(opts.safety, rucc_session::Safety::Off);
4767
4768 let e = parse_args(&args(&["-fsafety-init=some", "a.c"])).unwrap_err();
4769 assert!(e.message.contains("is not a padding mode"), "{}", e.message);
4770 }
4771
4772 #[test]
4773 fn whether_a_write_has_to_stay_inside_its_member_is_read_off_the_command_line() {
4774 // Off by default, because a store to allocated storage sets its effective type and C 6.5
4775 // lets a program reuse a buffer as something else. Row S4 is a build opting out of that.
4776 let (opts, _) = compile(&["a.c"]);
4777 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4778
4779 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-subobject", "a.c"]);
4780 assert_eq!(opts.subobject, rucc_session::Subobject::Members);
4781
4782 let (opts, _) = compile(&["-fsafety-subobject", "-fno-safety-subobject", "a.c"]);
4783 assert_eq!(opts.subobject, rucc_session::Subobject::Off);
4784
4785 // It takes no value. The form that would take one is the strict reading of section 9.4,
4786 // which is not written yet, so say so rather than accept a spelling that does nothing.
4787 let e = parse_args(&args(&["-fsafety-subobject=strict", "a.c"])).unwrap_err();
4788 assert!(e.message.contains("tamnd/rucc#967"), "{}", e.message);
4789 }
4790
4791 #[test]
4792 fn whether_two_restrict_pointers_may_meet_is_read_off_the_command_line() {
4793 // Off by default, because the record a block keeps is the union of what each pointer
4794 // reached, so two pointers striding through one array without landing on the same byte are
4795 // reported and by the letter of the standard those are different objects. Row Y8 is a build
4796 // deciding it would rather know.
4797 let (opts, _) = compile(&["a.c"]);
4798 assert_eq!(opts.promise, rucc_session::Promise::Off);
4799
4800 let (opts, _) = compile(&["-fsafety=detect", "-fsafety-restrict", "a.c"]);
4801 assert_eq!(opts.promise, rucc_session::Promise::Blocks);
4802
4803 let (opts, _) = compile(&["-fsafety-restrict", "-fno-safety-restrict", "a.c"]);
4804 assert_eq!(opts.promise, rucc_session::Promise::Off);
4805
4806 // The tier is still a tier, which is the thing worth pinning about a pair of names where
4807 // one is the front of the other.
4808 let (opts, _) = compile(&["-fsafety-restrict", "a.c"]);
4809 assert_eq!(opts.safety, rucc_session::Safety::Off);
4810
4811 let e = parse_args(&args(&["-fsafety-restrict=blocks", "a.c"])).unwrap_err();
4812 assert!(e.message.contains("takes no value"), "{}", e.message);
4813 }
4814
4815 #[test]
4816 fn safety_races_takes_a_mode_and_defaults_to_watching_nothing() {
4817 // Three modes rather than a bare flag, because section 9.5 gives two answers that record
4818 // the same thing and report different classes, so a flag with no value could not say which
4819 // was wanted. Off by default for the reason on `rucc_session::Races`, which is not a cost
4820 // argument: this is the one plane where an edge nobody interposed costs a false report.
4821 let (opts, _) = compile(&["a.c"]);
4822 assert_eq!(opts.races, rucc_session::Races::Off);
4823
4824 let (opts, _) = compile(&["-fsafety-races=metadata", "a.c"]);
4825 assert_eq!(opts.races, rucc_session::Races::Metadata);
4826
4827 let (opts, _) = compile(&["-fsafety-races=pointer", "a.c"]);
4828 assert_eq!(opts.races, rucc_session::Races::Pointer);
4829
4830 // Last one wins, as it does for every other mode flag here.
4831 let (opts, _) = compile(&["-fsafety-races=pointer", "-fno-safety-races", "a.c"]);
4832 assert_eq!(opts.races, rucc_session::Races::Off);
4833
4834 let e = parse_args(&args(&["-fsafety-races=all", "a.c"])).unwrap_err();
4835 assert!(e.message.contains("off, metadata or pointer"), "{}", e.message);
4836 }
4837
4838 #[test]
4839 fn print_pipeline_answers_with_the_passes_the_level_asked_for() {
4840 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4841 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4842 let text = print_pipeline(&opts);
4843 assert!(text.starts_with("level: -O2\n"), "{text}");
4844 assert!(text.contains("fold"), "{text}");
4845
4846 let a = parse_args(&args(&["--print-pipeline"])).unwrap();
4847 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4848 // Two passes run at `-O0` and neither is an optimization. The first moves what
4849 // `__builtin_expect` said onto the branch and takes the instruction away, so that nothing
4850 // past the optimizer has to know the instruction exists. The second removes code nothing
4851 // reaches. See issue 359.
4852 assert!(print_pipeline(&opts).contains("1: expect,"), "{}", print_pipeline(&opts));
4853 assert!(print_pipeline(&opts).contains("2: simplify-cfg,"), "{}", print_pipeline(&opts));
4854
4855 let a = parse_args(&args(&["--print-pipeline", "-fno-simplify-cfg"])).unwrap();
4856 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4857 // The second turns off and the first does not, because nothing below the optimizer lowers
4858 // what it removes, so `-fno-expect` is a compile that stops rather than one that runs.
4859 let text = print_pipeline(&opts);
4860 assert!(text.contains("1: expect,"), "{text}");
4861 assert!(!text.contains("simplify-cfg"), "{text}");
4862 }
4863
4864 #[test]
4865 fn print_pipeline_takes_the_toggles_into_account() {
4866 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fno-fold"])).unwrap();
4867 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4868 let text = print_pipeline(&opts);
4869 // The one that was named is gone and the rest of the level is not, which is the whole
4870 // of what a toggle promises.
4871 assert!(!text.contains("fold"), "{text}");
4872 assert!(text.contains("dce"), "{text}");
4873
4874 // Every pass the compiler has, named off. Built from the registry rather than written
4875 // out, so a pass added later is turned off here too and this keeps testing the thing it
4876 // is about, which is that the toggles can empty a level down to the passes that are not
4877 // optional. Those are named, because a listing that is all of them is a level nobody
4878 // emptied and the assertion would pass while saying nothing.
4879 let mut off = vec!["--print-pipeline".to_owned(), "-O2".to_owned()];
4880 off.extend(rucc_opt::PASSES.iter().map(|p| format!("-fno-{}", p.name())));
4881 let spelled: Vec<&str> = off.iter().map(String::as_str).collect();
4882 let a = parse_args(&args(&spelled)).unwrap();
4883 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4884 let text = print_pipeline(&opts);
4885 let left: Vec<&str> =
4886 rucc_opt::PASSES.iter().filter(|p| p.required()).map(|p| p.name()).collect();
4887 assert_eq!(left, vec!["expect", "constant-p"], "{text}");
4888 for (at, name) in left.iter().enumerate() {
4889 assert!(text.contains(&format!("{}: {name},", at + 1)), "{text}");
4890 }
4891 assert!(!text.contains("dce"), "{text}");
4892 }
4893
4894 #[test]
4895 fn print_pipeline_says_when_a_budget_will_stop_the_run_short() {
4896 let a = parse_args(&args(&["--print-pipeline", "-O2"])).unwrap();
4897 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4898 assert!(!print_pipeline(&opts).contains("global fuel"));
4899
4900 let a = parse_args(&args(&["--print-pipeline", "-O2", "-fpass-fuel-global=4"])).unwrap();
4901 let Action::PrintPipeline(opts) = a else { panic!("expected a pipeline dump") };
4902 let text = print_pipeline(&opts);
4903 // Because the listing is the answer to what this compilation will do, and a run that
4904 // stops after four rewrites is not doing what the level says it does.
4905 assert!(text.contains("global fuel: 4"), "{text}");
4906 }
4907
4908 /// A pass is turned on and off by its own name, and the order the flags were given in is
4909 /// kept, because the last spelling of a name is the one that decides.
4910 #[test]
4911 fn a_pass_is_named_by_dash_f_and_unnamed_by_dash_f_no() {
4912 let (opts, _) = compile(&["-c", "-O0", "-ffold", "-fno-fold", "-ffold", "a.c"]);
4913 assert_eq!(
4914 opts.passes,
4915 [("fold".to_owned(), true), ("fold".to_owned(), false), ("fold".to_owned(), true)]
4916 );
4917
4918 let e = parse_args(&args(&["-fno-such-pass", "a.c"])).unwrap_err();
4919 assert!(e.message.contains("unknown option"), "{}", e.message);
4920 }
4921
4922 #[test]
4923 fn pass_fuel_names_a_pass_and_a_count_and_refuses_anything_else() {
4924 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel=fold=3", "a.c"]);
4925 assert_eq!(opts.pass_fuel, [("fold".to_owned(), 3)]);
4926
4927 let e = parse_args(&args(&["-fpass-fuel=fold", "a.c"])).unwrap_err();
4928 assert!(e.message.contains("<pass>=<count>"), "{}", e.message);
4929 let e = parse_args(&args(&["-fpass-fuel=nosuch=3", "a.c"])).unwrap_err();
4930 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
4931 let e = parse_args(&args(&["-fpass-fuel=fold=lots", "a.c"])).unwrap_err();
4932 assert!(e.message.contains("not a number"), "{}", e.message);
4933 }
4934
4935 #[test]
4936 fn global_pass_fuel_is_a_count_on_its_own_and_defaults_to_no_limit() {
4937 let (opts, _) = compile(&["-c", "-O2", "a.c"]);
4938 assert_eq!(opts.pass_fuel_global, None);
4939
4940 let (opts, _) = compile(&["-c", "-O2", "-fpass-fuel-global=12", "a.c"]);
4941 assert_eq!(opts.pass_fuel_global, Some(12));
4942 // And it is not the per pass flag with a longer name, so neither spelling swallows the
4943 // other.
4944 assert!(opts.pass_fuel.is_empty());
4945
4946 let e = parse_args(&args(&["-fpass-fuel-global=lots", "a.c"])).unwrap_err();
4947 assert!(e.message.contains("not a number"), "{}", e.message);
4948 }
4949
4950 #[test]
4951 fn the_trace_file_is_taken_from_the_flag_and_an_empty_one_is_refused() {
4952 let (opts, _) = compile(&["-c", "a.c"]);
4953 assert_eq!(opts.trace, None);
4954 let (opts, _) = compile(&["-c", "-frucc-trace=/tmp/compile.jsonl", "a.c"]);
4955 assert_eq!(opts.trace.as_deref(), Some("/tmp/compile.jsonl"));
4956 let e = parse_args(&args(&["-frucc-trace=", "a.c"])).unwrap_err();
4957 assert!(e.message.contains("needs a file"), "{}", e.message);
4958 }
4959
4960 #[test]
4961 fn a_gate_names_a_pass_and_optionally_the_functions_it_covers() {
4962 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold", "-fenable-fold=2-4,main", "a.c"]);
4963 assert_eq!(
4964 opts.pass_gates,
4965 [(false, "fold".to_owned()), (true, "fold=2-4,main".to_owned())],
4966 "the order is what decides, so it has to survive the parse"
4967 );
4968
4969 let e = parse_args(&args(&["-fdisable-nosuch", "a.c"])).unwrap_err();
4970 assert!(e.message.contains("--print-pipeline"), "{}", e.message);
4971 let e = parse_args(&args(&["-fenable-fold=9-2", "a.c"])).unwrap_err();
4972 assert!(e.message.contains("ends before it starts"), "{}", e.message);
4973 let e = parse_args(&args(&["-fdisable-fold=", "a.c"])).unwrap_err();
4974 assert!(e.message.contains("is empty"), "{}", e.message);
4975 }
4976
4977 #[test]
4978 fn the_pipeline_listing_says_which_passes_a_gate_touched() {
4979 let (opts, _) = compile(&["-c", "-O2", "-fdisable-fold=main", "a.c"]);
4980 let text = print_pipeline(&opts);
4981 assert!(text.contains("fold, "), "{text}");
4982 assert!(text.contains("[off for main]"), "{text}");
4983 }
4984
4985 /// The spelling is checked while the arguments are read, because a dump that names a pass
4986 /// this compiler does not have is a typo, and a typo found after the compilation has run is
4987 /// found too late to be any use.
4988 #[test]
4989 fn a_dump_is_checked_when_it_is_asked_for_rather_than_when_it_is_taken() {
4990 let (opts, _) = compile(&["-c", "-O2", "-fdump-ir=all", "-fdump-ir=after-fold", "a.c"]);
4991 assert_eq!(opts.dump_ir, ["all", "after-fold"]);
4992
4993 let e = parse_args(&args(&["-fdump-ir=after-nosuch", "a.c"])).unwrap_err();
4994 assert!(e.message.contains("nosuch"), "{}", e.message);
4995 assert!(parse_args(&args(&["-fdump-ir=sideways-fold", "a.c"])).is_err());
4996 }
4997
4998 /// Every spelling `-fopt-info` takes, and the one it does not.
4999 ///
5000 /// The keywords are checked here for the same reason a dump's pass name is: a person who
5001 /// misspelled one gets no output, and no output is also what a compilation where nothing
5002 /// happened looks like. Telling those two apart is the entire reason to reach for this flag.
5003 #[test]
5004 fn opt_info_takes_kinds_and_a_file_and_refuses_a_kind_it_does_not_have() {
5005 let (opts, _) = compile(&["-c", "-O2", "-fopt-info", "a.c"]);
5006 assert_eq!(opts.opt_info, [""], "a bare flag asks for the rewrites");
5007 assert_eq!(opts.opt_info_file, None, "and goes to standard error");
5008
5009 let (opts, _) = compile(&["-c", "-O2", "-fopt-info-missed-note", "a.c"]);
5010 assert_eq!(opts.opt_info, ["missed-note"]);
5011
5012 // Two flags add up rather than the second replacing the first, and the file is the last
5013 // one that named a file, which is how GCC treats both.
5014 let (opts, _) =
5015 compile(&["-c", "-O2", "-fopt-info-missed=one.txt", "-fopt-info-all=two.txt", "a.c"]);
5016 assert_eq!(opts.opt_info, ["missed", "all"]);
5017 assert_eq!(opts.opt_info_file.as_deref(), Some("two.txt"));
5018
5019 let e = parse_args(&args(&["-fopt-info-vectorized", "a.c"])).unwrap_err();
5020 assert!(e.message.contains("vectorized"), "{}", e.message);
5021 assert!(e.message.contains("`missed`"), "{}", e.message);
5022 let e = parse_args(&args(&["-fopt-info-missed=", "a.c"])).unwrap_err();
5023 assert!(e.message.contains("no file"), "{}", e.message);
5024 }
5025
5026 #[test]
5027 fn verify_each_is_unstable_and_off_unless_it_was_asked_for() {
5028 let (opts, _) = compile(&["-c", "-Zverify-each", "a.c"]);
5029 assert!(opts.verify_each);
5030 assert!(!USAGE.contains("verify-each"), "an unstable option stays out of the usage text");
5031 }
5032
5033 #[test]
5034 fn dash_o_needs_an_argument() {
5035 let e = parse_args(&args(&["a.c", "-o"])).unwrap_err();
5036 assert_eq!(e.message, "-o requires an argument");
5037 }
5038
5039 #[test]
5040 fn dash_d_and_dash_u_are_read_joined_or_separated_and_keep_their_order() {
5041 let (opts, _) = compile(&["-DFOO=1", "-D", "BAR", "-UBAZ", "-U", "QUX", "a.c"]);
5042 assert_eq!(opts.defines, ["FOO=1", "BAR"]);
5043 assert_eq!(opts.undefines, ["BAZ", "QUX"]);
5044 }
5045
5046 #[test]
5047 fn the_include_flags_land_on_the_chain_each_one_names() {
5048 // A sysroot with nothing under it, so that the library's own directories are the
5049 // same on every machine this test runs on, which is none of them.
5050 let (opts, _) = compile(&[
5051 "-Ii",
5052 "-iquote",
5053 "q",
5054 "-isystem",
5055 "sys",
5056 "-idirafter",
5057 "after",
5058 "--sysroot=/nowhere-at-all",
5059 "a.c",
5060 ]);
5061 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5062 // The compiler's own headers sit after every `-isystem` and before `-idirafter`,
5063 // which is where GCC puts its own: a directory the user named outranks ours.
5064 assert_eq!(dirs, ["q", "i", "sys", runtime::DIR, "after"]);
5065 assert!(!opts.search.dirs()[1].is_system);
5066 assert!(opts.search.dirs()[2].is_system);
5067 }
5068
5069 #[test]
5070 fn the_librarys_headers_come_after_the_compilers_own_and_go_away_with_them() {
5071 // Which machine this runs on decides what is on the path, so the test is about the
5072 // order rather than about the names: ours is on it, the library's follow it, and
5073 // `-nostdinc` is the one flag that takes both halves of the pair off at once.
5074 let (opts, _) = compile(&["a.c"]);
5075 let dirs = opts.search.dirs();
5076 let ours = dirs.iter().position(|d| d.path.to_str() == Some(runtime::DIR));
5077 assert_eq!(ours, Some(0), "{dirs:?}");
5078 assert!(dirs[1..].iter().all(|d| d.is_system), "{dirs:?}");
5079 let (bare, _) = compile(&["-nostdinc", "a.c"]);
5080 assert!(bare.search.dirs().is_empty(), "{:?}", bare.search.dirs());
5081 }
5082
5083 #[test]
5084 fn a_sysroot_moves_the_librarys_directories_and_nothing_else() {
5085 let (opts, _) = compile(&["-isystem", "sys", "--sysroot=/nowhere-at-all", "a.c"]);
5086 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5087 assert_eq!(dirs, ["sys", runtime::DIR]);
5088 }
5089
5090 #[test]
5091 fn a_cross_compile_reads_the_targets_own_headers_rather_than_the_ones_next_door() {
5092 // The target is not the machine this test runs on wherever it runs, so the answer is the
5093 // same on all of them: the libc's two include directories for that target, the kernel's
5094 // two, and nothing from here. A header read from here is the quiet failure of section 8.5, a
5095 // program that builds on the build machine and is wrong everywhere else.
5096 let (opts, _) = compile(&["--target=riscv64-linux-musl", "-c", "a.c"]);
5097 let dirs: Vec<&std::path::Path> =
5098 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5099 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
5100 let kernel = cache::dir().join("kernel-headers");
5101 assert_eq!(dirs.len(), 5, "{dirs:?}");
5102 assert_eq!(dirs[0], std::path::Path::new(runtime::DIR));
5103 assert_eq!(dirs[1], root.join("include").join("riscv64"));
5104 assert_eq!(dirs[2], root.join("include").join("generic"));
5105 // The kernel's, which are beside the sysroots rather than inside one, because every target
5106 // that shares an architecture reads the same files.
5107 assert_eq!(dirs[3], kernel.join("riscv"));
5108 assert_eq!(dirs[4], kernel.join("generic"));
5109 }
5110
5111 #[test]
5112 fn a_cross_compile_to_something_that_is_not_linux_reads_no_kernel_headers() {
5113 // The other side of the same answer. Windows has its own system headers and no `linux/` at
5114 // all, so the list is the libc's own and the question never arises, which is the `None` that
5115 // `link::cross_kernel` returns rather than a directory nothing would be found in.
5116 //
5117 // The libc's own is one directory rather than two here, because mingw-w64 publishes a single
5118 // header tree for every architecture and `Sysroot::splits_by_arch` says so.
5119 let (opts, _) = compile(&["--target=x86_64-pc-windows-gnu", "-c", "a.c"]);
5120 let dirs: Vec<&std::path::Path> =
5121 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5122 assert_eq!(dirs.len(), 2, "{dirs:?}");
5123 assert!(!dirs.iter().any(|dir| dir.ends_with("kernel-headers")), "{dirs:?}");
5124 }
5125
5126 #[test]
5127 fn the_glibc_version_macro_goes_with_the_bundled_tree_and_with_nothing_else() {
5128 // One tree serves every glibc release, so the release is what the target supplies, and the
5129 // condition is the same one that chose the directories. A host glibc and a tree somebody
5130 // named both define `__GLIBC_MINOR__` in their own `features.h`, and two definitions with
5131 // different values is a warning on every compilation of every file.
5132 //
5133 // The architecture is chosen against this machine's rather than written down, because the
5134 // bundled tree is only in effect for a target that is not this machine. The first version of
5135 // this test said x86_64-linux-gnu, which is a cross compile on a mac and this machine on a
5136 // Linux runner, so it passed here and failed there.
5137 //
5138 // Unless this machine has the distribution's cross packages for it and nothing fetched, and
5139 // then those are the headers and their own `features.h` says the release, as it does for a
5140 // tree somebody named.
5141 let gnu = format!("--target={}-linux-gnu", cross_arch());
5142 let (bundled, _) = compile(&[&gnu, "-c", "a.c"]);
5143 let (link, _) = linking(&[&gnu, "-c", "a.c"]);
5144 let distro = link::distro_cross(bundled.target, &link).is_some();
5145 assert_eq!(bundled.glibc_minor, if distro { None } else { Some(44) });
5146 let pin = format!("{gnu}.2.28");
5147 let (pinned, _) = compile(&[&pin, "-c", "a.c"]);
5148 assert_eq!(pinned.glibc_minor, Some(28));
5149
5150 let (named, _) = compile(&[&gnu, "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5151 assert_eq!(named.glibc_minor, None);
5152 let (none, _) = compile(&[&gnu, "-nostdinc", "-c", "a.c"]);
5153 assert_eq!(none.glibc_minor, None);
5154 let musl = format!("--target={}-linux-musl", cross_arch());
5155 let (musl, _) = compile(&[&musl, "-c", "a.c"]);
5156 assert_eq!(musl.glibc_minor, None);
5157
5158 // And this machine's own target gets nothing, whatever this machine is, because its headers
5159 // come from the machine and its own `features.h` defines the macro. On a glibc Linux box
5160 // that is the case this test had backwards; on a mac it is true for the other reason, which
5161 // is that Darwin is not a glibc target at all.
5162 if let Some(host) = Triple::host() {
5163 let native = format!("--target={}", host.tuple());
5164 let (native, _) = compile(&[&native, "-c", "a.c"]);
5165 assert_eq!(native.glibc_minor, None);
5166 }
5167 }
5168
5169 #[test]
5170 fn a_pinned_release_on_this_machines_own_target_reads_the_bundled_tree() {
5171 // The end to end half of the answer in `link::cross_for`. A release named for this machine's
5172 // own target is a cross compile, so the headers are the bundled tree's and the macro says
5173 // what was asked for rather than what this machine has.
5174 //
5175 // Only on a glibc box, because a release is a glibc release: a mac has no `__GLIBC_MINOR__`
5176 // to get wrong and nothing to pin. That makes this a test the Linux runners carry, which is
5177 // where the case lives.
5178 let Some(host) = Triple::host() else { return };
5179 if host.env != rucc_target::Env::Gnu {
5180 return;
5181 }
5182 let pin = format!("--target={}.2.28", host.tuple());
5183 let (opts, _) = compile(&[&pin, "-c", "a.c"]);
5184 assert_eq!(opts.glibc_minor, Some(28));
5185 let root = cache::dir().join("sysroots").join(format!("{}.2.28", host.tuple()));
5186 let dirs: Vec<&std::path::Path> =
5187 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5188 assert!(dirs.iter().any(|dir| dir.starts_with(&root)), "{dirs:?}");
5189 // And nothing of this machine's, which is the failure this was: a program compiled against
5190 // 2.44 declarations and told it was 2.28.
5191 assert!(!dirs.iter().any(|dir| *dir == std::path::Path::new("/usr/include")), "{dirs:?}");
5192 }
5193
5194 /// An architecture that is not this machine's, out of the three the driver has targets for.
5195 ///
5196 /// A test about the bundled sysroot has to name a target that is not the host, because a target
5197 /// that is the host reads the host's own headers and libraries. Asking which machine this is
5198 /// beats picking a row and hoping, and it is two lines.
5199 fn cross_arch() -> &'static str {
5200 match Triple::host().map(|host| host.arch) {
5201 Some(rucc_target::Arch::X86_64) => "aarch64",
5202 _ => "x86_64",
5203 }
5204 }
5205
5206 #[test]
5207 fn a_glibc_newer_than_the_bundled_tree_is_refused_by_name() {
5208 // Both versions in the message, because the two things a person can do about it are pin a
5209 // release the tree has and name a sysroot that has the one they asked for, and neither is a
5210 // choice they can make without knowing which release the tree is.
5211 //
5212 // Not this machine's architecture, for the reason the test above gives: the refusal is about
5213 // the bundled tree, and the bundled tree is not what a target that is this machine reads.
5214 let target = format!("--target={}-linux-gnu.2.99", cross_arch());
5215 let message = refused(&[&target, "-c", "a.c"]);
5216 assert!(message.contains("asked for glibc 2.99"), "{message}");
5217 assert!(message.contains("bundled headers are glibc 2.44"), "{message}");
5218 assert!(message.contains("--sysroot"), "{message}");
5219 }
5220
5221 #[test]
5222 fn a_sysroot_the_user_named_is_still_what_a_cross_compile_reads() {
5223 // The tree somebody assembled beats the one we would build, on the headers as on the
5224 // libraries. It is empty here, which is why the list comes out short: the directories under
5225 // it are checked for rather than assumed, and a tree that is not there offers nothing.
5226 let (opts, _) =
5227 compile(&["--target=riscv64-linux-musl", "--sysroot=/nowhere-at-all", "-c", "a.c"]);
5228 let dirs: Vec<&std::path::Path> =
5229 opts.search.dirs().iter().map(|d| d.path.as_path()).collect();
5230 assert_eq!(dirs, [std::path::Path::new(runtime::DIR)]);
5231 }
5232
5233 #[test]
5234 fn dash_i_dash_moves_the_bracket_directories_into_the_quoted_chain() {
5235 let (opts, _) =
5236 compile(&["-Iinc1", "-iquote", "inc2", "-I-", "-Iinc3", "-nostdinc", "a.c"]);
5237 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5238 assert_eq!(dirs, ["inc1", "inc2", "inc3"]);
5239 // An angled include sees only what came after the flag.
5240 assert_eq!(opts.search.start(IncludeForm::Angled), 2);
5241 assert!(!opts.search.searches_current_dir());
5242 }
5243
5244 #[test]
5245 fn the_prefix_flags_stick_what_iprefix_said_on_the_front_of_what_follows_it() {
5246 let (opts, _) = compile(&[
5247 "-iprefix",
5248 "/tools/",
5249 "-iwithprefix",
5250 "late",
5251 "-iwithprefixbefore",
5252 "early",
5253 "-iprefix",
5254 "/other/",
5255 "-iwithprefix",
5256 "last",
5257 "-nostdinc",
5258 "a.c",
5259 ]);
5260 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5261 // `-iwithprefixbefore` is an `-I` and the other two are `-isystem`, which is where GCC
5262 // puts them rather than where its manual says it does.
5263 assert_eq!(dirs, ["/tools/early", "/tools/late", "/other/last"]);
5264 assert!(!opts.search.dirs()[0].is_system);
5265 assert!(opts.search.dirs()[1].is_system);
5266 }
5267
5268 #[test]
5269 fn the_files_named_on_the_command_line_keep_their_order_and_which_flag_named_them() {
5270 let (opts, _) =
5271 compile(&["-include", "one.h", "-imacros", "two.h", "-include", "3.h", "a.c"]);
5272 let names: Vec<&str> = opts.preincludes.iter().map(|p| p.name.as_str()).collect();
5273 assert_eq!(names, ["one.h", "two.h", "3.h"]);
5274 assert_eq!(opts.preincludes.iter().filter(|p| p.macros_only).count(), 1);
5275 }
5276
5277 #[test]
5278 fn nostdinc_takes_the_compilers_own_headers_off_the_path() {
5279 let (opts, _) = compile(&["-Ii", "-nostdinc", "a.c"]);
5280 let dirs: Vec<&str> = opts.search.dirs().iter().filter_map(|d| d.path.to_str()).collect();
5281 assert_eq!(dirs, ["i"]);
5282 }
5283
5284 #[test]
5285 fn the_dialect_flags_set_the_language_and_the_extensions_separately() {
5286 let (opts, _) = compile(&["-std=gnu11", "a.c"]);
5287 assert_eq!(opts.std, Std::C11);
5288 assert!(opts.gnu_extensions);
5289
5290 let (opts, _) = compile(&["-std=iso9899:1999", "a.c"]);
5291 assert_eq!(opts.std, Std::C99);
5292 assert!(!opts.gnu_extensions);
5293
5294 let (opts, _) = compile(&["-ansi", "a.c"]);
5295 assert_eq!(opts.std, Std::C89);
5296 assert!(!opts.gnu_extensions);
5297
5298 let (opts, _) = compile(&["-std=gnu2y", "a.c"]);
5299 assert_eq!(opts.std, Std::C2y);
5300 assert!(opts.gnu_extensions);
5301
5302 let e = parse_args(&args(&["-std=c94jr", "a.c"])).unwrap_err();
5303 assert!(e.message.contains("unknown dialect"), "{}", e.message);
5304 }
5305
5306 #[test]
5307 fn the_dump_letters_are_a_family_and_everything_else_beginning_with_d_is_not() {
5308 let (opts, _) = compile(&["-dM", "a.c"]);
5309 assert!(opts.dumps.macros);
5310
5311 // Packed, the way GCC takes them, and a letter in the family we have not written yet
5312 // is accepted and does nothing rather than failing a build.
5313 let (opts, _) = compile(&["-dDM", "a.c"]);
5314 assert!(opts.dumps.macros);
5315 let (opts, _) = compile(&["-dD", "a.c"]);
5316 assert!(!opts.dumps.macros);
5317
5318 let (opts, _) = compile(&["a.c"]);
5319 assert!(!opts.dumps.any());
5320
5321 // `-dumpversion` is a different flag that happens to start the same way, and it is read
5322 // as itself rather than as a dump of nothing.
5323 assert_eq!(printed(&["-dumpversion", "a.c"]), "16");
5324 }
5325
5326 #[test]
5327 fn the_gcc_version_claimed_is_a_flag_and_the_short_spellings_are_the_ones_people_write() {
5328 let (opts, _) = compile(&["a.c"]);
5329 assert_eq!(
5330 opts.gnuc,
5331 GnucVersion { major: 16, minor: 0, patch: 0 },
5332 "the release this compiler is written against, and the earliest one of that series"
5333 );
5334
5335 let (opts, _) = compile(&["-fgnuc-version=15.1.0", "a.c"]);
5336 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 1, patch: 0 });
5337
5338 // A missing component is zero. `gcc -dumpversion` says `15` on a release with no
5339 // patchlevel and a harness that pastes that back has to be understood.
5340 let (opts, _) = compile(&["-fgnuc-version=15", "a.c"]);
5341 assert_eq!(opts.gnuc, GnucVersion { major: 15, minor: 0, patch: 0 });
5342
5343 let (opts, _) = compile(&["-fgnuc-version=13.2", "a.c"]);
5344 assert_eq!(opts.gnuc, GnucVersion { major: 13, minor: 2, patch: 0 });
5345
5346 let e = parse_args(&args(&["-fgnuc-version=15.x", "a.c"])).unwrap_err();
5347 assert!(e.message.contains("minor that is not a number"), "{}", e.message);
5348
5349 let e = parse_args(&args(&["-fgnuc-version=1.2.3.4", "a.c"])).unwrap_err();
5350 assert!(e.message.contains("more than three"), "{}", e.message);
5351 }
5352
5353 #[test]
5354 fn pedantic_has_two_spellings_and_is_not_the_same_knob_as_the_dialect() {
5355 let (opts, _) = compile(&["-std=c17", "-pedantic", "a.c"]);
5356 assert!(opts.pedantic);
5357 assert_eq!(opts.std, Std::C17);
5358
5359 // The `-W` family's name for it, which is what a build that groups its warning flags
5360 // tends to write.
5361 let (opts, _) = compile(&["-Wpedantic", "a.c"]);
5362 assert!(opts.pedantic);
5363
5364 let (opts, _) = compile(&["-std=c17", "a.c"]);
5365 assert!(!opts.pedantic, "a dialect on its own does not diagnose an extension");
5366 }
5367
5368 #[test]
5369 fn dash_p_and_dash_ffreestanding_reach_the_options() {
5370 let (opts, _) = compile(&["-E", "-P", "-ffreestanding", "a.c"]);
5371 assert!(!opts.line_markers);
5372 assert!(!opts.hosted);
5373 assert_eq!(opts.emit, EmitKind::Preprocessed);
5374 }
5375
5376 /// The two ways a build says it means its own function by a name the C library also has.
5377 ///
5378 /// `-fno-builtin` is all of them and `-fno-builtin-<name>` is one, and the second is what a
5379 /// build writes when it means its own `memcpy` and the library's everything else. The name is
5380 /// kept as it was written and not checked against anything, because a program is allowed to
5381 /// mean something by a name this compiler has never heard of.
5382 #[test]
5383 fn the_builtin_flags_are_read_in_both_directions_and_one_name_at_a_time() {
5384 let (opts, _) = compile(&["-c", "a.c"]);
5385 assert!(opts.builtins, "a library name means the library function by default");
5386 assert!(opts.no_builtin.is_empty());
5387
5388 let (opts, _) = compile(&["-c", "-fno-builtin", "a.c"]);
5389 assert!(!opts.builtins);
5390
5391 let (opts, _) = compile(&["-c", "-fno-builtin", "-fbuiltin", "a.c"]);
5392 assert!(opts.builtins, "the last mention decides");
5393
5394 let (opts, _) = compile(&["-c", "-fno-builtin-memcpy", "-fno-builtin-nonesuch", "a.c"]);
5395 assert!(opts.builtins, "one name is not the family");
5396 assert_eq!(opts.no_builtin, vec!["memcpy".to_owned(), "nonesuch".to_owned()]);
5397 }
5398
5399 /// `-fvisibility=`, which is on every cmake project that cares about which names it exports
5400 /// and which was refused as an unknown option until now.
5401 ///
5402 /// Four spellings and three answers. `internal` is hidden plus a promise about never taking
5403 /// the address across a component boundary, and nothing derives anything from that promise
5404 /// here, so it comes out as the weaker of the two rather than as a refusal that stops a build
5405 /// over a distinction this compiler does not make.
5406 #[test]
5407 fn visibility_takes_the_four_spellings_gcc_takes_and_refuses_the_rest() {
5408 let (opts, _) = compile(&["-c", "a.c"]);
5409 assert_eq!(opts.visibility, Visibility::Default, "exported unless something says not");
5410
5411 for (written, wanted) in [
5412 ("default", Visibility::Default),
5413 ("hidden", Visibility::Hidden),
5414 ("internal", Visibility::Hidden),
5415 ("protected", Visibility::Protected),
5416 ] {
5417 let (opts, _) = compile(&["-c", &format!("-fvisibility={written}"), "a.c"]);
5418 assert_eq!(opts.visibility, wanted, "{written}");
5419 }
5420
5421 // The last mention decides, which is what every other flag of this shape does and what a
5422 // build that turns something off for one directory relies on.
5423 let (opts, _) = compile(&["-c", "-fvisibility=hidden", "-fvisibility=default", "a.c"]);
5424 assert_eq!(opts.visibility, Visibility::Default, "the last mention decides");
5425
5426 // A spelling gcc does not take is refused rather than read as the default, because a
5427 // build that meant hidden and got exported is a library with the wrong interface and
5428 // nothing said about it anywhere.
5429 let failed = parse_args(&args(&["-fvisibility=none", "a.c"])).expect_err("refused");
5430 assert!(failed.to_string().contains("is not a visibility"), "{failed}");
5431 }
5432
5433 /// `-ffp-contract=`, which is the one flag in the floating point group that is kept rather than
5434 /// described, and the values are gcc 16's three.
5435 #[test]
5436 fn how_far_a_multiply_and_an_addition_may_be_fused_is_asked_for() {
5437 let (opts, _) = compile(&["-c", "a.c"]);
5438 assert_eq!(opts.fp_contract, Contract::Off, "a licence nobody granted is not assumed");
5439
5440 for (written, wanted) in
5441 [("off", Contract::Off), ("on", Contract::On), ("fast", Contract::Fast)]
5442 {
5443 let (opts, _) = compile(&["-c", &format!("-ffp-contract={written}"), "a.c"]);
5444 assert_eq!(opts.fp_contract, wanted, "{written}");
5445 }
5446
5447 let (opts, _) = compile(&["-c", "-ffp-contract=fast", "-ffp-contract=off", "a.c"]);
5448 assert_eq!(opts.fp_contract, Contract::Off, "the last mention decides");
5449
5450 // Refused rather than read as one of the three, because a build that asked for no fusing
5451 // and was given the default would be one whose numbers change and whose command line says
5452 // they should not. gcc refuses the same spellings and names the same three in its message.
5453 for bad in ["-ffp-contract=none", "-ffp-contract=", "-ffp-contract=Fast"] {
5454 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5455 assert!(failed.to_string().contains("is not a contraction"), "{bad}: {failed}");
5456 }
5457
5458 // And the other one that takes a value, which is taken and kept nowhere: every operation
5459 // here is computed in the type it was written in, so `standard` is what happens and the
5460 // other two are permission to do something this does not do.
5461 let failed = parse_args(&args(&["-fexcess-precision=long", "a.c"])).expect_err("refused");
5462 assert!(failed.to_string().contains("is not an excess precision"), "{failed}");
5463 }
5464
5465 /// The four prefix mapping flags, which are what a distribution passes to get the same bytes
5466 /// out of `/build/pkg-1.2` and out of `/home/someone/pkg-1.2`. Three lists rather than one
5467 /// because gcc has three, and `-ffile-prefix-map=` is the three of them at once.
5468 #[test]
5469 fn a_prefix_mapping_flag_goes_on_the_list_its_spelling_names() {
5470 let (opts, _) = compile(&["-c", "a.c"]);
5471 assert!(opts.prefix_map.macros.is_empty(), "nothing is rewritten unless it is asked for");
5472 assert!(opts.prefix_map.debug.is_empty(), "nor here");
5473 assert!(opts.prefix_map.profile.is_empty(), "nor here");
5474
5475 let (opts, _) = compile(&["-c", "-fmacro-prefix-map=/build=.", "a.c"]);
5476 assert_eq!(opts.prefix_map.macros.apply("/build/a.c"), "./a.c", "the one it names");
5477 assert!(opts.prefix_map.debug.is_empty(), "and not the two it does not");
5478
5479 let (opts, _) = compile(&["-c", "-fdebug-prefix-map=/build=.", "a.c"]);
5480 assert_eq!(opts.prefix_map.debug.apply("/build/a.c"), "./a.c", "the one it names");
5481 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5482
5483 let (opts, _) = compile(&["-c", "-fprofile-prefix-map=/build=.", "a.c"]);
5484 assert_eq!(opts.prefix_map.profile.apply("/build/a.c"), "./a.c", "the one it names");
5485 assert!(opts.prefix_map.macros.is_empty(), "and not the two it does not");
5486
5487 let (opts, _) = compile(&["-c", "-ffile-prefix-map=/build=.", "a.c"]);
5488 for list in [&opts.prefix_map.macros, &opts.prefix_map.debug, &opts.prefix_map.profile] {
5489 assert_eq!(list.apply("/build/a.c"), "./a.c", "all three at once");
5490 }
5491
5492 // Every mention is kept and the last one that matches wins, unlike the flags above whose
5493 // last mention replaces the earlier ones. A build writes one of these per source root and
5494 // expects all of them to be in force, which is the whole point of a list.
5495 let (opts, _) =
5496 compile(&["-c", "-ffile-prefix-map=/a=one", "-ffile-prefix-map=/b=two", "a.c"]);
5497 assert_eq!(opts.prefix_map.macros.apply("/a/x.c"), "one/x.c", "the earlier one still acts");
5498 assert_eq!(opts.prefix_map.macros.apply("/b/x.c"), "two/x.c", "and so does the later one");
5499
5500 // An argument with no `=` is refused rather than ignored, because a build whose paths were
5501 // meant to be rewritten and were not is one that ships the build directory's name and says
5502 // nothing about it. gcc refuses the same thing.
5503 for bad in ["-fmacro-prefix-map=nope", "-ffile-prefix-map=", "-fdebug-prefix-map=/build"] {
5504 let failed = parse_args(&args(&[bad, "a.c"])).expect_err("refused");
5505 assert!(failed.to_string().contains("is not a rewrite for"), "{bad}: {failed}");
5506 }
5507 }
5508
5509 /// `-ffunction-sections` and `-fdata-sections`, which are what make `--gc-sections` able to
5510 /// drop anything: a linker can leave out a section nothing reaches and cannot leave out half of
5511 /// one. A kernel and an embedded image are both linked that way.
5512 ///
5513 /// Two flags rather than one because gcc has two, and a build that asks for one of them and not
5514 /// the other is a build that measured something: splitting the code is nearly free at link time
5515 /// and splitting the data can defeat the linker's ordering of what is next to what.
5516 #[test]
5517 fn a_section_per_function_and_a_section_per_variable_are_asked_for_one_at_a_time() {
5518 let (opts, _) = compile(&["-c", "a.c"]);
5519 assert!(!opts.function_sections, "one text section unless something says otherwise");
5520 assert!(!opts.data_sections);
5521
5522 let (opts, _) = compile(&["-c", "-ffunction-sections", "a.c"]);
5523 assert!(opts.function_sections);
5524 assert!(!opts.data_sections, "one flag is not the other");
5525
5526 let (opts, _) = compile(&["-c", "-fdata-sections", "a.c"]);
5527 assert!(opts.data_sections);
5528 assert!(!opts.function_sections);
5529
5530 // Both directions taken, and the off one is what happens anyway rather than a refusal,
5531 // since a build that writes it is asking for the default.
5532 let (opts, _) = compile(&[
5533 "-c",
5534 "-ffunction-sections",
5535 "-fno-function-sections",
5536 "-fdata-sections",
5537 "-fno-data-sections",
5538 "a.c",
5539 ]);
5540 assert!(!opts.function_sections, "the last mention decides");
5541 assert!(!opts.data_sections, "the last mention decides");
5542 }
5543
5544 /// `-fgnu89-inline`, which is off by default and is not implied by anything on the command
5545 /// line, since the dialect asks for GNU's reading further in rather than through this.
5546 #[test]
5547 fn gnu89_inline_is_off_until_it_is_asked_for_and_the_last_mention_decides() {
5548 let (opts, _) = compile(&["-c", "a.c"]);
5549 assert!(!opts.gnu89_inline, "C's reading of inline by default");
5550
5551 let (opts, _) = compile(&["-c", "-fgnu89-inline", "a.c"]);
5552 assert!(opts.gnu89_inline);
5553
5554 let (opts, _) = compile(&["-c", "-fgnu89-inline", "-fno-gnu89-inline", "a.c"]);
5555 assert!(!opts.gnu89_inline, "the last mention decides");
5556
5557 // The C89 dialects are under GNU's reading whether this was written or not, so the flag
5558 // stays off there and the dialect is what the checker and the macro set both ask. That is
5559 // also why `-std=c89 -fno-gnu89-inline` needs no diagnostic: it asks for the reading the
5560 // dialect already has. gcc refuses that command line, which is measured in the issue.
5561 let (opts, _) = compile(&["-c", "-std=c89", "a.c"]);
5562 assert!(!opts.gnu89_inline);
5563 }
5564
5565 /// Both spellings of both frame flags, since a build that wants one usually writes the
5566 /// other beside it for the one file that has to be compiled the ordinary way.
5567 #[test]
5568 fn the_two_frame_flags_are_read_in_both_directions() {
5569 let (opts, _) = compile(&["-c", "a.c"]);
5570 assert_eq!(opts.frame_pointer, None, "nothing said, so the level decides");
5571 assert!(opts.keeps_frame_pointer(), "and at -O0 gcc keeps one, so this does too");
5572 let (opts, _) = compile(&["-c", "-O1", "a.c"]);
5573 assert!(!opts.keeps_frame_pointer(), "gcc omits it above -O0 and so does this");
5574 assert!(opts.red_zone, "the psABI has one and nothing said not to use it");
5575
5576 let (opts, _) = compile(&["-c", "-fno-omit-frame-pointer", "-mno-red-zone", "a.c"]);
5577 assert_eq!(opts.frame_pointer, Some(true));
5578 assert!(!opts.red_zone);
5579
5580 let (opts, _) = compile(&[
5581 "-c",
5582 "-fno-omit-frame-pointer",
5583 "-fomit-frame-pointer",
5584 "-mno-red-zone",
5585 "-mred-zone",
5586 "a.c",
5587 ]);
5588 assert_eq!(opts.frame_pointer, Some(false), "the last one wins, as it does in gcc");
5589 assert!(!opts.keeps_frame_pointer(), "and it wins over the level too");
5590 assert!(opts.red_zone);
5591 }
5592
5593 /// Four flags rather than one with an argument, which is how gcc spells them, and the negative
5594 /// spelled three ways because a build that turns one off writes whichever it turned on.
5595 #[test]
5596 fn the_stack_protector_is_four_flags_and_the_last_one_wins() {
5597 let (opts, _) = compile(&["-c", "a.c"]);
5598 assert_eq!(opts.protector, Protector::None, "gcc protects nothing unless it was asked");
5599
5600 for (flag, want) in [
5601 ("-fstack-protector", Protector::Buffers),
5602 ("-fstack-protector-strong", Protector::Strong),
5603 ("-fstack-protector-all", Protector::All),
5604 ] {
5605 let (opts, _) = compile(&["-c", flag, "a.c"]);
5606 assert_eq!(opts.protector, want, "{flag}");
5607 }
5608
5609 // What a package build does: the strong one in the global flags and one directory that
5610 // cannot have a protector turning it off on the line after.
5611 for off in ["-fno-stack-protector", "-fno-stack-protector-strong"] {
5612 let (opts, _) = compile(&["-c", "-fstack-protector-strong", off, "a.c"]);
5613 assert_eq!(opts.protector, Protector::None, "{off}");
5614 }
5615 let (opts, _) = compile(&["-c", "-fno-stack-protector", "-fstack-protector-all", "a.c"]);
5616 assert_eq!(opts.protector, Protector::All, "the last one wins either way round");
5617 }
5618
5619 /// A switch rather than a level, because how a frame is taken is one question and which
5620 /// functions get a canary is another, and gcc spells it that way for the same reason.
5621 #[test]
5622 fn taking_a_frame_a_page_at_a_time_is_off_until_it_is_asked_for() {
5623 let (opts, _) = compile(&["-c", "a.c"]);
5624 assert!(!opts.stack_clash, "gcc takes a frame in one subtraction unless it was asked");
5625
5626 let (opts, _) = compile(&["-c", "-fstack-clash-protection", "a.c"]);
5627 assert!(opts.stack_clash);
5628
5629 // The same shape a package build uses for the protector: on in the global flags and off
5630 // for the one directory that cannot have it.
5631 let (opts, _) =
5632 compile(&["-c", "-fstack-clash-protection", "-fno-stack-clash-protection", "a.c"]);
5633 assert!(!opts.stack_clash);
5634 let (opts, _) =
5635 compile(&["-c", "-fno-stack-clash-protection", "-fstack-clash-protection", "a.c"]);
5636 assert!(opts.stack_clash, "the last one wins either way round");
5637
5638 // The two are independent, since one is about the frame and the other about the function.
5639 let (opts, _) =
5640 compile(&["-c", "-fstack-clash-protection", "-fstack-protector-strong", "a.c"]);
5641 assert!(opts.stack_clash);
5642 assert_eq!(opts.protector, Protector::Strong);
5643 }
5644
5645 /// One flag with an argument rather than a family of spellings, because what it asks about is
5646 /// which of the two edges of a control flow transfer is checked and the two are not separate
5647 /// questions to the hardware.
5648 #[test]
5649 fn which_control_flow_edges_are_checked_is_asked_for_by_name() {
5650 let (opts, _) = compile(&["-c", "a.c"]);
5651 assert_eq!(opts.control, Control::None, "gcc's default on the targets this compiler has");
5652
5653 for (arg, want) in [
5654 ("-fcf-protection", Control::Full),
5655 ("-fcf-protection=full", Control::Full),
5656 ("-fcf-protection=branch", Control::Branch),
5657 ("-fcf-protection=return", Control::Return),
5658 ("-fcf-protection=none", Control::None),
5659 ("-fcf-protection=check", Control::Check),
5660 ] {
5661 let (opts, _) = compile(&["-c", arg, "a.c"]);
5662 assert_eq!(opts.control, want, "{arg}");
5663 }
5664
5665 // The shape a package build uses: on in the global flags and off for the one directory
5666 // that cannot have it, whichever of the two spellings of off it reaches for.
5667 let (opts, _) = compile(&["-c", "-fcf-protection=full", "-fno-cf-protection", "a.c"]);
5668 assert_eq!(opts.control, Control::None);
5669 let (opts, _) = compile(&["-c", "-fno-cf-protection", "-fcf-protection=branch", "a.c"]);
5670 assert_eq!(opts.control, Control::Branch, "the last one wins either way round");
5671 }
5672
5673 /// The profiler is asked for by two spellings, and where its hook goes by two more.
5674 ///
5675 /// The two halves are separate on purpose. `-mfentry` on its own says where a call would go and
5676 /// asks for no call, which is what gcc does with it, and a build system that sets it globally
5677 /// and asks for the profile per directory needs that to be true rather than an error.
5678 ///
5679 /// The link is asserted alongside, because the flag changes it too and a build that compiled
5680 /// with it and linked without it is a program that calls the hook everywhere and never writes a
5681 /// profile.
5682 #[test]
5683 fn the_profiler_and_where_its_hook_goes_are_two_separate_questions() {
5684 let (opts, _) = compile(&["-c", "a.c"]);
5685 assert!(!opts.profile);
5686 assert_eq!(opts.hook, Hook::Platform, "neither was named, so the target decides");
5687
5688 for arg in ["-pg", "-p"] {
5689 let (opts, _) = compile(&["-c", arg, "a.c"]);
5690 assert!(opts.profile, "{arg}");
5691 let (link, _) = linking(&[arg, "a.c"]);
5692 assert!(link.profile, "{arg} changes the link as well");
5693 }
5694
5695 for (arg, want) in [("-mfentry", Hook::Early), ("-mno-fentry", Hook::Late)] {
5696 let (opts, _) = compile(&["-c", arg, "a.c"]);
5697 assert_eq!(opts.hook, want, "{arg}");
5698 assert!(!opts.profile, "{arg} asks for no call of its own");
5699 }
5700
5701 let (opts, _) = compile(&["-c", "-mfentry", "-mno-fentry", "-pg", "a.c"]);
5702 assert_eq!(opts.hook, Hook::Late, "the last one wins");
5703 assert!(opts.profile);
5704 }
5705
5706 /// How much room a patcher is promised, which is one number or two.
5707 ///
5708 /// A command line that did not ask is asserted alongside, because the flag has to be written to
5709 /// mean anything and a build that reserved room nobody asked for would grow every function in
5710 /// it for nothing.
5711 #[test]
5712 fn the_room_a_patcher_is_promised_is_a_number_of_bytes_and_where_they_go() {
5713 let (opts, _) = compile(&["-c", "a.c"]);
5714 assert_eq!(opts.patchable, Patchable::default());
5715 assert!(!opts.patchable.any(), "nothing is reserved unless it was asked for");
5716
5717 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=16", "a.c"]);
5718 assert_eq!(opts.patchable, Patchable { total: 16, before: 0 });
5719
5720 let (opts, _) = compile(&["-c", "-fpatchable-function-entry=5,3", "a.c"]);
5721 assert_eq!(opts.patchable, Patchable { total: 5, before: 3 });
5722 assert_eq!(opts.patchable.after(), 2);
5723
5724 // The last one wins, which is what every other flag of this shape does and what a build
5725 // that adds one to a command line it did not write is relying on.
5726 let (opts, _) = compile(&[
5727 "-c",
5728 "-fpatchable-function-entry=5,3",
5729 "-fpatchable-function-entry=2",
5730 "a.c",
5731 ]);
5732 assert_eq!(opts.patchable, Patchable { total: 2, before: 0 });
5733 }
5734
5735 /// And a request nothing could satisfy is refused rather than rounded into one that can be.
5736 #[test]
5737 fn room_in_front_of_the_label_that_is_more_than_the_room_asked_for_is_refused() {
5738 for arg in ["-fpatchable-function-entry=1,2", "-fpatchable-function-entry=x"] {
5739 let e = parse_args(&args(&["-c", arg, "a.c"])).unwrap_err();
5740 assert!(e.message.contains("is not an amount of room to reserve"), "{}", e.message);
5741 }
5742 }
5743
5744 /// What wraps rather than being undefined, which is two questions and three flags.
5745 ///
5746 /// The older flag is the pair of the newer two, which is gcc's own reading of it, so a build
5747 /// that writes `-fno-strict-overflow` gets both and a build that writes one of the others gets
5748 /// only what it asked for.
5749 #[test]
5750 fn what_overflows_rather_than_being_undefined_is_asked_for_two_ways() {
5751 let (opts, _) = compile(&["-c", "a.c"]);
5752 assert_eq!(opts.wrapping, Wrapping::NONE, "nothing wraps unless it was asked for");
5753
5754 let (opts, _) = compile(&["-c", "-fwrapv", "a.c"]);
5755 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5756
5757 let (opts, _) = compile(&["-c", "-fwrapv-pointer", "a.c"]);
5758 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: true, trap: false });
5759
5760 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "a.c"]);
5761 assert_eq!(opts.wrapping, Wrapping::ALL);
5762
5763 // And the last one wins, in both directions. A build that turns one of these on globally
5764 // and off for one directory is relying on that, and so is one that writes the pair and
5765 // then takes half of it back.
5766 let (opts, _) = compile(&["-c", "-fwrapv", "-fno-wrapv", "a.c"]);
5767 assert_eq!(opts.wrapping, Wrapping::NONE);
5768
5769 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fstrict-overflow", "a.c"]);
5770 assert_eq!(opts.wrapping, Wrapping::NONE);
5771
5772 let (opts, _) = compile(&["-c", "-fno-strict-overflow", "-fno-wrapv-pointer", "a.c"]);
5773 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5774 }
5775
5776 /// And the other answer to the signed question cannot be held at the same time as the first.
5777 ///
5778 /// A program cannot both wrap and stop, so writing both is writing a contradiction, and gcc
5779 /// resolves it by letting the last one win rather than by reporting anything. That was measured
5780 /// against gcc 16 rather than read out of the manual, which says nothing about it: `-ftrapv
5781 /// -fwrapv` emits no checked calls and `-fwrapv -ftrapv` emits them.
5782 #[test]
5783 fn a_signed_overflow_that_stops_is_the_other_answer_and_not_a_third_one() {
5784 let (opts, _) = compile(&["-c", "-ftrapv", "a.c"]);
5785 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5786
5787 let (opts, _) = compile(&["-c", "-fwrapv", "-ftrapv", "a.c"]);
5788 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5789
5790 let (opts, _) = compile(&["-c", "-ftrapv", "-fwrapv", "a.c"]);
5791 assert_eq!(opts.wrapping, Wrapping { signed: true, pointer: false, trap: false });
5792
5793 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-strict-overflow", "a.c"]);
5794 assert_eq!(opts.wrapping, Wrapping::ALL);
5795
5796 let (opts, _) = compile(&["-c", "-ftrapv", "-fno-trapv", "a.c"]);
5797 assert_eq!(opts.wrapping, Wrapping::NONE);
5798
5799 // And the flag that says what may be assumed says nothing about what happens, so it leaves
5800 // this alone where it takes the wrapping away. gcc does the same.
5801 let (opts, _) = compile(&["-c", "-ftrapv", "-fstrict-overflow", "a.c"]);
5802 assert_eq!(opts.wrapping, Wrapping { signed: false, pointer: false, trap: true });
5803 }
5804
5805 /// What a plain `char` is, which is four spellings of two answers and nothing by default.
5806 ///
5807 /// Nothing is the target's own answer and has to stay distinct from both of the others, since
5808 /// the same command line means a signed `char` on x86-64 and an unsigned one on Linux's arm64.
5809 /// The negative spellings are the other flag rather than a way of asking for the default, which
5810 /// was measured against gcc 16: `-fno-signed-char` defines `__CHAR_UNSIGNED__` and
5811 /// `-fno-unsigned-char` does not.
5812 #[test]
5813 fn the_signedness_of_a_plain_char_is_asked_for_in_four_ways() {
5814 let (opts, _) = compile(&["-c", "a.c"]);
5815 assert_eq!(opts.char_signed, None);
5816
5817 for flag in ["-fsigned-char", "-fno-unsigned-char"] {
5818 let (opts, _) = compile(&["-c", flag, "a.c"]);
5819 assert_eq!(opts.char_signed, Some(true), "{flag}");
5820 }
5821
5822 for flag in ["-funsigned-char", "-fno-signed-char"] {
5823 let (opts, _) = compile(&["-c", flag, "a.c"]);
5824 assert_eq!(opts.char_signed, Some(false), "{flag}");
5825 }
5826
5827 // And the last one wins, which is what a build that sets one globally and the other for a
5828 // directory relies on.
5829 let (opts, _) = compile(&["-c", "-funsigned-char", "-fsigned-char", "a.c"]);
5830 assert_eq!(opts.char_signed, Some(true));
5831
5832 // And what is asked for reaches the target, because that is what every other part of the
5833 // compiler asks. The triple is one whose own answer is the opposite, so a session that
5834 // ignored the flag would still read as signed here.
5835 let (opts, _) =
5836 compile(&["-c", "--target=aarch64-unknown-linux-gnu", "-fsigned-char", "a.c"]);
5837 assert!(Session::new(*opts).target.char_is_signed);
5838 let (opts, _) = compile(&["-c", "--target=aarch64-unknown-linux-gnu", "a.c"]);
5839 assert!(!Session::new(*opts).target.char_is_signed);
5840 }
5841
5842 /// And the size of an enumeration, which is one question with two spellings.
5843 #[test]
5844 fn the_smallest_enumeration_is_asked_for_and_taken_back() {
5845 let (opts, _) = compile(&["-c", "a.c"]);
5846 assert!(!opts.short_enums);
5847
5848 let (opts, _) = compile(&["-c", "-fshort-enums", "a.c"]);
5849 assert!(opts.short_enums);
5850
5851 let (opts, _) = compile(&["-c", "-fshort-enums", "-fno-short-enums", "a.c"]);
5852 assert!(!opts.short_enums);
5853
5854 let (opts, _) = compile(&["-c", "-fno-short-enums", "-fshort-enums", "a.c"]);
5855 assert!(opts.short_enums);
5856 }
5857
5858 /// And Microsoft's reading of an anonymous member, which the target answers where the command
5859 /// line said nothing. gcc's mingw build has it on and its Linux build has it off, so a header
5860 /// that closes a nameless union with a macro that expands to nothing is read the way the
5861 /// compiler that platform ships would read it.
5862 #[test]
5863 fn the_microsoft_reading_of_a_member_follows_the_target_until_it_is_asked_for() {
5864 // Named rather than left to the host, since the answer this asks for is the one a target
5865 // that is not Windows gives and on a Windows machine the host is not one of those.
5866 let (opts, _) = compile(&[LINUX, "-c", "a.c"]);
5867 assert!(!Session::new(*opts).ms_extensions());
5868
5869 let (opts, _) = compile(&["-c", "--target=x86_64-pc-windows-gnu", "a.c"]);
5870 assert!(Session::new(*opts).ms_extensions());
5871
5872 let (opts, _) = compile(&["-c", "-fms-extensions", "a.c"]);
5873 assert!(Session::new(*opts).ms_extensions());
5874
5875 let (opts, _) =
5876 compile(&["-c", "--target=x86_64-pc-windows-gnu", "-fno-ms-extensions", "a.c"]);
5877 assert!(!Session::new(*opts).ms_extensions());
5878 }
5879
5880 /// And a value nothing means is refused rather than taken for the nearest thing it looks like.
5881 ///
5882 /// `-fcf-protection=all` is the spelling somebody writes from memory, and a compiler that read
5883 /// it as `full` would be guessing, while one that let it fall through to the optimizer's `-f`
5884 /// family would report it as an unknown pass. Neither is the news the build wants.
5885 #[test]
5886 fn a_control_flow_protection_nothing_means_is_refused() {
5887 let e = parse_args(&args(&["-c", "-fcf-protection=all", "a.c"])).unwrap_err();
5888 assert!(e.message.contains("is not a control flow protection"), "{}", e.message);
5889 assert!(e.message.contains("full, branch, return, none or check"), "{}", e.message);
5890 }
5891
5892 #[test]
5893 fn the_link_flags_are_collected_apart_from_the_compilation() {
5894 let (link, _) = linking(&[
5895 "-static",
5896 "-nostartfiles",
5897 "-rdynamic",
5898 "-s",
5899 "-fuse-ld=mold",
5900 "-L/opt/lib",
5901 "-B",
5902 "/opt/tools",
5903 "a.c",
5904 ]);
5905 assert!(link.is_static);
5906 assert!(link.no_startfiles);
5907 assert!(link.export_dynamic);
5908 assert!(link.strip);
5909 assert_eq!(link.use_ld.as_deref(), Some("mold"));
5910 assert_eq!(link.search, vec![PathBuf::from("/opt/lib")]);
5911 assert_eq!(link.prefixes, vec![PathBuf::from("/opt/tools")]);
5912 }
5913
5914 #[test]
5915 fn a_comma_in_dash_wl_separates_two_arguments() {
5916 // The target is written down because the name of the object is derived from it, and `a.o`
5917 // on a Linux host is `a.obj` on a Windows one. What is under test is the splitting of the
5918 // argument, which has nothing to do with either.
5919 let (_, plan) = linking(&[LINUX, "-Wl,-rpath,/opt/lib", "-Xlinker", "--as-needed", "a.c"]);
5920 let link = plan.link.expect("expected a link step");
5921 assert_eq!(
5922 link.inputs,
5923 vec![
5924 link::Item::Linker("-rpath".into()),
5925 link::Item::Linker("/opt/lib".into()),
5926 link::Item::Linker("--as-needed".into()),
5927 link::Item::File("a.o".into()),
5928 ]
5929 );
5930 }
5931
5932 #[test]
5933 fn a_word_for_the_linker_keeps_its_place_among_the_files_too() {
5934 // What libtool writes around a set of convenience archives, and what #1279 was. Both words
5935 // are about the files between them, so the pair collected out of the line and appended to
5936 // the end is two options that bracket nothing and an archive that went in empty.
5937 let (_, plan) = linking(&[
5938 "--target=x86_64-unknown-linux-gnu",
5939 "a.c",
5940 "-Wl,--whole-archive",
5941 "libaesni.a",
5942 "-Wl,--no-whole-archive",
5943 "-lm",
5944 ]);
5945 let link = plan.link.expect("expected a link step");
5946 assert_eq!(
5947 link.inputs,
5948 vec![
5949 link::Item::File("a.o".into()),
5950 link::Item::Linker("--whole-archive".into()),
5951 link::Item::File("libaesni.a".into()),
5952 link::Item::Linker("--no-whole-archive".into()),
5953 link::Item::Library("m".into()),
5954 ]
5955 );
5956 // And it is not a job, because there is nothing to compile in a word for the linker.
5957 assert_eq!(plan.jobs.len(), 2);
5958 }
5959
5960 #[test]
5961 fn a_word_for_the_linker_on_a_dash_c_line_is_dropped_without_a_word() {
5962 // GCC says nothing about one either. `-Wl,` on a compile line is what a build system
5963 // writes when one variable holds the flags for both, and a note here would be a note on
5964 // every compile of every autotools project.
5965 let (_, plan) = linking(&["-c", "-Wl,--as-needed", "a.c"]);
5966 assert!(plan.link.is_none());
5967 assert!(plan.notes.is_empty(), "{:?}", plan.notes);
5968 assert_eq!(plan.jobs.len(), 1);
5969 }
5970
5971 #[test]
5972 fn a_library_keeps_its_place_between_the_objects() {
5973 // Link order is semantic: `-lm` written between two files resolves for the one before
5974 // it and not for the one after, so a library cannot be collected into a list of its own.
5975 // The target is named because the suffix of an object is the target's and this asserts
5976 // on the names: the same command line on a Windows host plans two `.obj` files.
5977 let (_, plan) = linking(&["--target=x86_64-unknown-linux-gnu", "a.c", "-lm", "b.c"]);
5978 let link = plan.link.expect("expected a link step");
5979 assert_eq!(
5980 link.inputs,
5981 vec![
5982 link::Item::File("a.o".into()),
5983 link::Item::Library("m".into()),
5984 link::Item::File("b.o".into()),
5985 ]
5986 );
5987 // And it is not a job, because there is nothing to compile in a library.
5988 assert_eq!(plan.jobs.len(), 2);
5989 }
5990
5991 #[test]
5992 fn a_library_on_a_dash_c_line_is_a_note_rather_than_an_error() {
5993 let (_, plan) = linking(&["-c", "-lm", "a.c"]);
5994 assert!(plan.link.is_none());
5995 assert!(plan.notes.iter().any(|n| n.contains("-lm")), "{:?}", plan.notes);
5996 }
5997
5998 #[test]
5999 fn the_sysroot_reaches_the_linker_as_well_as_the_headers() {
6000 let (link, _) = linking(&["--sysroot=/opt/root", "a.c"]);
6001 assert_eq!(link.sysroot, Some(PathBuf::from("/opt/root")));
6002 }
6003
6004 fn printed(s: &[&str]) -> String {
6005 match parse_args(&args(s)).expect("expected an answer") {
6006 Action::Print(line) => line,
6007 other => panic!("expected an answer, got {other:?}"),
6008 }
6009 }
6010
6011 fn refused(s: &[&str]) -> String {
6012 parse_args(&args(s)).expect_err("expected a refusal").message
6013 }
6014
6015 #[test]
6016 fn a_warning_flag_gcc_knows_is_taken_even_though_nothing_reads_it() {
6017 // The rule in section 4.1, and the reason for it is autoconf: a configure script finds
6018 // out whether a warning flag exists by passing it and looking at the exit status, so a
6019 // compiler that refuses one gcc knows fails a script written for gcc.
6020 let (opts, _) = compile(&["-Wall", "-Wextra", "-Wno-format-truncation", "-c", "a.c"]);
6021 assert!(!opts.warnings_are_errors);
6022 assert!(opts.warnings);
6023 // The two spellings that do mean something are still read.
6024 let (opts, _) = compile(&["-Werror", "-c", "a.c"]);
6025 assert!(opts.warnings_are_errors);
6026 let (opts, _) = compile(&["-w", "-c", "a.c"]);
6027 assert!(!opts.warnings);
6028 // Off without being asked, the way gcc has it off, and both spellings are read.
6029 let (opts, _) = compile(&["-c", "a.c"]);
6030 assert!(!opts.system_header_warnings);
6031 let (opts, _) = compile(&["-Wsystem-headers", "-c", "a.c"]);
6032 assert!(opts.system_header_warnings);
6033 let (opts, _) = compile(&["-Wsystem-headers", "-Wno-system-headers", "-c", "a.c"]);
6034 assert!(!opts.system_header_warnings);
6035 let (opts, _) = compile(&["-pedantic-errors", "-c", "a.c"]);
6036 assert!(opts.pedantic && opts.warnings_are_errors);
6037 }
6038
6039 #[test]
6040 fn a_warning_flag_gcc_refuses_is_refused_here_too() {
6041 // Postgres's meson build probes these, and with rucc taking them it ended up passing four
6042 // clang warnings that the gcc build had dropped.
6043 for flag in ["-Wcast-function-type-strict", "-Wunused-command-line-argument"] {
6044 assert_eq!(refused(&[flag, "-c", "a.c"]), format!("unknown option `{flag}`"));
6045 }
6046 assert_eq!(
6047 refused(&["-Werror=unguarded-availability-new", "-c", "a.c"]),
6048 "`-Werror=unguarded-availability-new`: no option `-Wunguarded-availability-new`"
6049 );
6050 assert!(refused(&["-Wno-error=nonsense", "-c", "a.c"]).contains("no option `-Wnonsense`"));
6051 // gcc takes `-Wno-` of a name it does not know, and says nothing unless something else
6052 // is said, and it takes C++ and Fortran names on a C compile.
6053 for flag in
6054 ["-Wno-cast-function-type-strict", "-Werror=format", "-Wformat=2", "-Wabi-tag", "-W"]
6055 {
6056 compile(&[flag, "-c", "a.c"]);
6057 }
6058 }
6059
6060 #[test]
6061 fn an_argument_for_a_separate_tool_is_refused_rather_than_dropped() {
6062 // Every one of these says something about the output, so the wrong answer is silence.
6063 assert!(refused(&["-Wa,--noexecstack", "-c", "a.c"]).contains("separate assembler"));
6064 assert!(refused(&["-Wp,-C", "-c", "a.c"]).contains("separate assembler"));
6065 assert!(refused(&["-specs=/x", "a.c"]).contains("-specs= is not supported"));
6066 assert!(refused(&["-mcmodel=kernel", "-c", "a.c"]).contains("small code model"));
6067 assert!(refused(&["-gdwarf-4", "-c", "a.c"]).contains("DWARF 5"));
6068 // The word size the target does not have, which is a target this compiler was not asked
6069 // for rather than a flag it does not know.
6070 let no32 = refused(&["--target=x86_64-unknown-linux-gnu", "-m32", "-c", "a.c"]);
6071 assert!(no32.contains("32 bit target"), "{no32}");
6072 }
6073
6074 /// `-gz` and the two spellings of the split, which are the two questions about the shape of
6075 /// the debug output rather than about how much of it there is.
6076 ///
6077 /// Both answers here are about what happens when there is debug information to shape, and
6078 /// there is none yet, so what is being asserted is that the flags are read and remembered
6079 /// rather than that anything changed in the output. That is the whole of what taking them
6080 /// claims, and it is worth a test because the day `rucc-debug` writes a section this is where
6081 /// it comes to find out what the command line said.
6082 #[test]
6083 fn the_shape_of_the_debug_output_is_recorded_even_where_there_is_none_of_it() {
6084 let (opts, _) = compile(&["-c", "a.c"]);
6085 assert_eq!(opts.compress, Compress::None, "uncompressed unless somebody asks");
6086
6087 // Bare `-gz` is `-gz=zlib`, measured against gcc 16 rather than read out of the manual,
6088 // which describes the flag without ever saying which algorithm it picks.
6089 assert_eq!(compile(&["-gz", "-c", "a.c"]).0.compress, Compress::Zlib);
6090 for (spelling, want) in [
6091 ("none", Compress::None),
6092 ("zlib", Compress::Zlib),
6093 ("zlib-gnu", Compress::ZlibGnu),
6094 ("zstd", Compress::Zstd),
6095 ] {
6096 let (opts, _) = compile(&[&format!("-gz={spelling}"), "-c", "a.c"]);
6097 assert_eq!(opts.compress, want, "{spelling}");
6098 }
6099
6100 // A value nothing here has heard of is refused rather than rounded to the nearest one,
6101 // because a build that asked for `zstd` and quietly got `zlib` would ship a file its
6102 // reader may not understand and would have no way of finding out.
6103 for bad in ["-gz=gzip", "-gz="] {
6104 let failed = refused(&[bad, "-c", "a.c"]);
6105 assert!(failed.contains("is not a way to compress"), "{bad}: {failed}");
6106 }
6107
6108 // The split is refused in the direction that would have written a file and taken in the
6109 // direction that describes what happens. A build system that names the `.dwo` as an
6110 // output has to hear about it now rather than at the point the file is missing.
6111 let (opts, _) = compile(&["-gno-split-dwarf", "-g", "-c", "a.c"]);
6112 assert!(opts.debug_info, "the negative spelling says nothing about how much");
6113 let failed = refused(&["-gsplit-dwarf", "-c", "a.c"]);
6114 assert!(failed.contains(".dwo"), "the refusal names the file it would have written");
6115 }
6116
6117 /// The `-flto` family, which is the whole of an optimization this compiler does not do.
6118 ///
6119 /// Taken rather than refused because ignoring it gives a correct program that is slower than
6120 /// it could have been, which is section 4.1's hint about speed. The values are still held to
6121 /// gcc's, so a command line written for clang is told rather than quietly taken.
6122 #[test]
6123 fn the_link_time_family_is_read_and_checked_and_nothing_is_done_about_it() {
6124 let (opts, _) = compile(&["-c", "a.c"]);
6125 assert!(!opts.lto.requested, "nothing asks unless the command line does");
6126
6127 let (opts, _) = compile(&["-flto", "-c", "a.c"]);
6128 assert!(opts.lto.requested);
6129 assert_eq!(opts.lto.jobs, LtoJobs::One, "bare -flto is one process, the way gcc reads it");
6130
6131 // The last of the two directions wins, the same as every other pair of `-f` spellings.
6132 assert!(!compile(&["-flto", "-fno-lto", "-c", "a.c"]).0.lto.requested);
6133 assert!(compile(&["-fno-lto", "-flto", "-c", "a.c"]).0.lto.requested);
6134
6135 // A count is a count, and asking for one implies asking for the optimization.
6136 for (spelling, want) in [
6137 ("auto", LtoJobs::Auto),
6138 ("jobserver", LtoJobs::Jobserver),
6139 ("1", LtoJobs::One),
6140 ("8", LtoJobs::Count(8)),
6141 ] {
6142 let (opts, _) = compile(&[&format!("-flto={spelling}"), "-c", "a.c"]);
6143 assert_eq!(opts.lto.jobs, want, "{spelling}");
6144 assert!(opts.lto.requested, "{spelling} asks for it too");
6145 }
6146
6147 // gcc refuses a zero rather than reading it as `-fno-lto`, and `thin` is clang's spelling
6148 // of a question gcc answers with `-flto-partition=`, so somebody who wrote it meant a
6149 // different compiler and gets told so here rather than getting a serial link.
6150 for bad in ["-flto=0", "-flto=thin", "-flto=full", "-flto=-1"] {
6151 let failed = refused(&[bad, "-c", "a.c"]);
6152 assert!(failed.contains("link time jobs"), "{bad}: {failed}");
6153 }
6154
6155 // How the program is cut up before the work is spread over it.
6156 assert_eq!(compile(&["-c", "a.c"]).0.lto.partition, Partition::Balanced, "gcc's default");
6157 for (spelling, want) in [
6158 ("balanced", Partition::Balanced),
6159 ("1to1", Partition::OneToOne),
6160 ("one", Partition::One),
6161 ("max", Partition::Max),
6162 ("none", Partition::None),
6163 ] {
6164 let (opts, _) = compile(&[&format!("-flto-partition={spelling}"), "-c", "a.c"]);
6165 assert_eq!(opts.lto.partition, want, "{spelling}");
6166 }
6167 assert!(refused(&["-flto-partition=big", "-c", "a.c"]).contains("partitioning model"));
6168
6169 // And how hard the bytecode is compressed on its way into the object, which is zstd's
6170 // range of levels and is the range gcc checks an argument against.
6171 assert_eq!(compile(&["-c", "a.c"]).0.lto.compression, None, "whatever it does by default");
6172 assert_eq!(compile(&["-flto-compression-level=0", "-c", "a.c"]).0.lto.compression, Some(0));
6173 let (opts, _) = compile(&["-flto-compression-level=19", "-c", "a.c"]);
6174 assert_eq!(opts.lto.compression, Some(19));
6175 for bad in ["-flto-compression-level=20", "-flto-compression-level=-1"] {
6176 let failed = refused(&[bad, "-c", "a.c"]);
6177 assert!(failed.contains("compression level"), "{bad}: {failed}");
6178 }
6179
6180 // The two pairs that describe an arrangement rather than ask for one. Every object here
6181 // holds its machine code, so the fat spelling is what already happens and the other is a
6182 // smaller file rather than a different program, and the plugin pair is about a tool the
6183 // design in `spec/09-optimizer.md` never loads.
6184 for taken in [
6185 "-ffat-lto-objects",
6186 "-fno-fat-lto-objects",
6187 "-fuse-linker-plugin",
6188 "-fno-use-linker-plugin",
6189 ] {
6190 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6191 assert!(!opts.lto.requested, "{taken} says nothing about whether to do it");
6192 }
6193 }
6194
6195 /// The profile family, which is the only one here that splits down the middle.
6196 ///
6197 /// Reading a profile is taken and writing one is refused, and the line between them is the one
6198 /// section 4.1 draws: ignoring a request to read the counts gives a correct program that is
6199 /// slower than it could have been, and ignoring a request to write them means a file the build
6200 /// declared as an output never appears.
6201 #[test]
6202 fn reading_a_profile_is_taken_and_writing_one_is_refused() {
6203 let (opts, _) = compile(&["-c", "a.c"]);
6204 assert!(!opts.profile_data.requested, "nothing asks unless the command line does");
6205 assert_eq!(opts.profile_data.path, None);
6206
6207 let (opts, _) = compile(&["-fprofile-use", "-c", "a.c"]);
6208 assert!(opts.profile_data.requested);
6209 assert_eq!(opts.profile_data.path, None, "beside the object, the way gcc looks");
6210
6211 let (opts, _) = compile(&["-fprofile-use=/counts", "-c", "a.c"]);
6212 assert!(opts.profile_data.requested, "naming a path asks for it too");
6213 assert_eq!(opts.profile_data.path.as_deref(), Some("/counts"));
6214
6215 // The last of the two directions wins, the same as every other pair of `-f` spellings.
6216 assert!(
6217 !compile(&["-fprofile-use", "-fno-profile-use", "-c", "a.c"]).0.profile_data.requested
6218 );
6219 assert!(
6220 compile(&["-fno-profile-use", "-fprofile-use", "-c", "a.c"]).0.profile_data.requested
6221 );
6222
6223 // The rest of the reading half, which is where the files are and three answers about what
6224 // to make of what is in them.
6225 let (opts, _) = compile(&[
6226 "-fprofile-dir=/build/profiles",
6227 "-fprofile-abs-path",
6228 "-fprofile-correction",
6229 "-fprofile-partial-training",
6230 "-c",
6231 "a.c",
6232 ]);
6233 assert_eq!(opts.profile_data.dir.as_deref(), Some("/build/profiles"));
6234 assert!(opts.profile_data.absolute);
6235 assert!(opts.profile_data.correction);
6236 assert!(opts.profile_data.partial_training);
6237
6238 // Writing one, which is refused by name. The first four instrument the program and the
6239 // last writes a file beside the object, and a build that got neither and no message would
6240 // go on to optimize against counts that were never gathered.
6241 for writing in [
6242 "-fprofile-generate",
6243 "-fprofile-generate=/build/profiles",
6244 "-fprofile-arcs",
6245 "--coverage",
6246 "-fcondition-coverage",
6247 "-fpath-coverage",
6248 ] {
6249 let failed = refused(&[writing, "-c", "a.c"]);
6250 assert!(failed.contains("instrument"), "{writing}: {failed}");
6251 }
6252 assert!(refused(&["-ftest-coverage", "-c", "a.c"]).contains(".gcno"), "it names the file");
6253
6254 // The negative spellings of the refused half are what already happens, so they are taken.
6255 for taken in ["-fno-profile-generate", "-fno-profile-arcs", "-fno-test-coverage"] {
6256 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6257 assert!(!opts.profile_data.requested, "{taken} asks for nothing");
6258 }
6259
6260 // And the flags that describe the instrumentation that is refused above, which are checked
6261 // and dropped. Checked because a typo is worth finding here rather than on the day the
6262 // instrumentation lands.
6263 for taken in [
6264 "-fprofile-update=single",
6265 "-fprofile-update=atomic",
6266 "-fprofile-update=prefer-atomic",
6267 "-fprofile-reproducible=serial",
6268 "-fprofile-reproducible=parallel-runs",
6269 "-fprofile-reproducible=multithreaded",
6270 "-fprofile-values",
6271 "-fno-profile-values",
6272 "-fprofile-info-section",
6273 "-fprofile-filter-files=a.c",
6274 "-fprofile-exclude-files=b.c",
6275 "-fprofile-note=a.gcno",
6276 ] {
6277 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6278 assert!(!opts.profile_data.requested, "{taken} says nothing about reading one");
6279 }
6280 assert!(refused(&["-fprofile-update=none", "-c", "a.c"]).contains("update method"));
6281 assert!(refused(&["-fprofile-reproducible=any", "-c", "a.c"]).contains("reproducibility"));
6282 }
6283
6284 /// The sanitizers, which are refused by name and are the one family refused for a reason that
6285 /// is not about the bytes.
6286 ///
6287 /// A sanitizer is a promise that the program is watched while it runs, so a build that asked
6288 /// for one and was quietly given a program with no checks in it gets a test suite that passes
6289 /// for the wrong reason rather than a slower program.
6290 #[test]
6291 fn a_sanitizer_that_is_still_asked_for_at_the_end_of_the_line_is_refused_by_name() {
6292 for asked in ["address", "undefined", "thread", "kernel-address", "leak", "memory"] {
6293 let failed = refused(&[&format!("-fsanitize={asked}"), "-c", "a.c"]);
6294 assert!(failed.contains(asked), "the refusal names what was asked for: {failed}");
6295 assert!(failed.contains("-fsafety=detect"), "and the nearest thing: {failed}");
6296 }
6297
6298 // A list is every name in it, and the first one still standing is the one named.
6299 let failed = refused(&["-fsanitize=address,undefined", "-c", "a.c"]);
6300 assert!(failed.contains("address"), "{failed}");
6301
6302 // A name that is not one, which is worth its own message: somebody who wrote `-fsanitize`
6303 // with a typo in it has a different problem from somebody who wrote a real one.
6304 for bad in ["-fsanitize=bogus", "-fsanitize=address,bogus", "-fno-sanitize=bogus"] {
6305 let failed = refused(&[bad, "-c", "a.c"]);
6306 assert!(failed.contains("is not a sanitizer"), "{bad}: {failed}");
6307 }
6308
6309 // gcc takes `all` only in the negative, and so does this.
6310 assert!(refused(&["-fsanitize=all", "-c", "a.c"]).contains("only `-fno-sanitize=all`"));
6311
6312 // Asking and then taking it back is asking for nothing, which is why the answer waits for
6313 // the end of the line. A build whose shared flags turn a check on and whose rule for one
6314 // file turns it off again compiles that file here.
6315 for pair in [
6316 ["-fsanitize=address", "-fno-sanitize=address"],
6317 ["-fsanitize=address,undefined", "-fno-sanitize=all"],
6318 ["-fsanitize=undefined", "-fno-sanitize=undefined"],
6319 ] {
6320 let (opts, _) = compile(&[pair[0], pair[1], "-c", "a.c"]);
6321 assert_eq!(opts.safety, rucc_session::Safety::Off, "{pair:?} asked for nothing");
6322 }
6323 // And the other order still asks, because the last word is the one that counts.
6324 assert!(!refused(&["-fno-sanitize=address", "-fsanitize=address", "-c", "a.c"]).is_empty());
6325
6326 // What a check does when it fires is an answer about checks that are refused, so there is
6327 // nothing left for it to change and it is taken.
6328 for taken in [
6329 "-fsanitize-recover=undefined",
6330 "-fno-sanitize-recover=all",
6331 "-fsanitize-trap=undefined",
6332 "-fno-sanitize-trap=all",
6333 "-fsanitize-undefined-trap-on-error",
6334 "-fsanitize-address-use-after-scope",
6335 "-fno-sanitize-address-use-after-scope",
6336 "-fsanitize-sections=.data",
6337 ] {
6338 let (opts, _) = compile(&[taken, "-c", "a.c"]);
6339 assert_eq!(opts.safety, rucc_session::Safety::Off, "{taken} asks for no checking");
6340 }
6341 assert!(refused(&["-fsanitize-recover=bogus", "-c", "a.c"]).contains("is not a sanitizer"));
6342
6343 // Coverage instrumentation is refused rather than dropped, because a fuzzer with no
6344 // feedback runs blind and never says so.
6345 let failed = refused(&["-fsanitize-coverage=trace-pc", "-c", "a.c"]);
6346 assert!(failed.contains("feedback"), "{failed}");
6347 let failed = refused(&["-fsanitize-coverage=trace-pc-guard", "-c", "a.c"]);
6348 assert!(failed.contains("trace-pc or trace-cmp"), "gcc takes two of them: {failed}");
6349 }
6350
6351 #[test]
6352 fn the_levels_gcc_spells_differently_are_the_levels_they_mean() {
6353 assert_eq!(compile(&["-O", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6354 assert_eq!(compile(&["-Og", "-c", "a.c"]).0.opt_level, OptLevel::O1);
6355 assert_eq!(compile(&["-O2", "-c", "a.c"]).0.opt_level, OptLevel::O2);
6356 }
6357
6358 #[test]
6359 fn the_machine_flags_that_name_what_we_already_do_are_taken_and_the_rest_are_not() {
6360 let line = ["--target=x86_64-unknown-linux-gnu", "-m64", "-march=x86-64-v3"];
6361 let (opts, _) =
6362 compile(&[&line[..], &["-mtune=native", "-mabi=sysv", "-c", "a.c"]].concat());
6363 assert_eq!(opts.target.to_string(), "x86_64-unknown-linux-gnu");
6364 let wrong = refused(&["--target=x86_64-unknown-linux-gnu", "-mabi=ms", "-c", "a.c"]);
6365 assert!(wrong.contains("sysv convention"), "{wrong}");
6366 }
6367
6368 /// Whether a unit built with that command line has the extension called `name`.
6369 fn has(line: &[&str], name: &str) -> bool {
6370 let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6371 let (opts, _) = compile(&[&x86[..], line].concat());
6372 opts.isa.has(rucc_target::Feature::named(name).expect("a feature"))
6373 }
6374
6375 #[test]
6376 fn the_sse_flags_and_the_processor_levels_name_extensions() {
6377 // tamnd/rucc#2003. Every one of these was an unknown option before, and Postgres's
6378 // configure probe for the CRC-32C intrinsics is compiled with the first.
6379 assert!(has(&["-msse4.2"], "sse4.2") && has(&["-msse4.2"], "crc32"));
6380 assert!(has(&["-msse4.2"], "ssse3") && has(&["-msse4.2"], "popcnt"));
6381 assert!(!has(&[], "sse3") && !has(&[], "popcnt"));
6382 assert!(has(&["-mssse3"], "sse3") && !has(&["-mssse3"], "sse4.1"));
6383 assert!(has(&["-msse4"], "sse4.2") && !has(&["-msse4", "-mno-sse4"], "sse4.1"));
6384 assert!(has(&["-mpopcnt"], "popcnt") && !has(&["-mpopcnt"], "sse3"));
6385 assert!(has(&["-mcrc32"], "crc32"));
6386 assert!(has(&["-mxsave"], "xsave") && !has(&["-mxsave", "-mno-xsave"], "xsave"));
6387 assert!(!has(&["-msse4.2", "-mno-popcnt"], "popcnt"));
6388 // A processor supplies what no flag spoke for, whichever order they came in.
6389 assert!(has(&["-march=x86-64-v2"], "sse4.2"));
6390 assert!(!has(&["-march=x86-64-v2", "-mno-sse4.2"], "sse4.2"));
6391 assert!(!has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.2"));
6392 assert!(has(&["-mno-sse4.2", "-march=x86-64-v2"], "sse4.1"));
6393 assert!(!has(&["-march=x86-64-v2", "-march=x86-64"], "sse3"));
6394 // One it has no list for is the baseline, as it was when all of them were.
6395 assert!(!has(&["-march=pentium-m"], "sse3"));
6396 assert!(has(&["-march=x86-64-v3"], "avx2"));
6397 // Turning off what is never on is nothing, and the flag is still gcc's.
6398 assert!(!has(&["-mno-avx512f"], "avx512f"));
6399 }
6400
6401 #[test]
6402 fn an_extension_this_compiler_cannot_provide_for_a_whole_unit_is_refused() {
6403 let x86 = ["--target=x86_64-unknown-linux-gnu", "-c", "a.c"];
6404 let said = refused(&[&x86[..], &["-mavx2"]].concat());
6405 assert!(said.contains("no intrinsics for avx2"), "{said}");
6406 let said = refused(&[&x86[..], &["-mno-sse2"]].concat());
6407 assert!(said.contains("baseline"), "{said}");
6408 assert!(refused(&[&x86[..], &["-msse5"]].concat()).contains("unknown option"));
6409 // No other target has these, whichever side of the target the flag was written on.
6410 let said = refused(&["-msse4.2", "--target=aarch64-linux-gnu", "-c", "a.c"]);
6411 assert!(said.contains("unknown option `-msse4.2`"), "{said}");
6412 let (opts, _) = compile(&["--target=aarch64-linux-gnu", "-march=armv8-a+crc", "-c", "a.c"]);
6413 assert_eq!(opts.isa, rucc_target::Isa::NONE);
6414 }
6415
6416 #[test]
6417 fn the_thread_flag_is_a_macro_and_a_library_and_the_library_goes_last() {
6418 let (opts, plan) = compile(&["-pthread", "-c", "a.c"]);
6419 assert!(opts.defines.iter().any(|d| d == "_REENTRANT"));
6420 // After the input, because a static link takes what it needs from a library when it
6421 // reaches it and not afterwards.
6422 let names: Vec<&str> = plan.jobs.iter().map(|j| j.input.as_str()).collect();
6423 assert_eq!(names, vec!["a.c"]);
6424 }
6425
6426 #[test]
6427 fn the_version_banner_keeps_our_first_line_and_takes_meson_down_the_gnu_path() {
6428 let text = banner();
6429 let mut lines = text.lines();
6430 // Every harness we have reads the first line and nothing else.
6431 assert_eq!(lines.next(), Some(format!("rucc {VERSION}").as_str()));
6432 // The words meson looks for, in `mesonbuild/compilers/detect.py`.
6433 assert!(text.contains("Free Software Foundation"), "{text}");
6434 // GCC's own banner has three lines and so does this one, and the claim is the dialect.
6435 assert!(lines.next().is_some_and(|l| l.contains("GCC 16")), "{text}");
6436 assert!(lines.next().is_some() && lines.next().is_none(), "{text}");
6437 }
6438
6439 #[test]
6440 fn the_questions_a_build_system_asks_before_it_compiles_anything() {
6441 let target = "--target=x86_64-unknown-linux-gnu";
6442 assert_eq!(printed(&[target, "-dumpmachine"]), "x86_64-unknown-linux-gnu");
6443 assert_eq!(printed(&[target, "-dumpversion"]), "16");
6444 assert_eq!(printed(&[target, "-dumpfullversion"]), "16.0.0");
6445 // They follow the release claimed, since that is the one `__GNUC__` says.
6446 assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpversion"]), "15");
6447 assert_eq!(printed(&[target, "-fgnuc-version=15.2", "-dumpfullversion"]), "15.2.0");
6448 assert_eq!(printed(&[target, "-print-multiarch"]), "x86_64-linux-gnu");
6449 // A name nothing holds comes back unchanged, which is GCC's rule and is what makes the
6450 // answer safe to paste into a link line whether or not the file is there.
6451 assert_eq!(printed(&[target, "-print-file-name=no-such-library.a"]), "no-such-library.a");
6452 assert_eq!(printed(&[target, "-print-prog-name=ld"]), "ld");
6453 let dirs = printed(&[target, "-print-search-dirs"]);
6454 assert!(dirs.starts_with("install: "), "{dirs}");
6455 assert!(dirs.contains("\nlibraries: ="), "{dirs}");
6456 }
6457
6458 #[test]
6459 fn the_sysroot_in_effect_is_the_one_the_command_line_named_or_the_one_for_the_target() {
6460 // A tree the user named is the answer whatever the target is, because it is the answer to
6461 // every other question too.
6462 assert_eq!(printed(&["--sysroot=/opt/cross", "-print-sysroot"]), "/opt/cross");
6463
6464 // A target that is no machine this suite runs on is read under the cache, and the answer is
6465 // the root rather than one of the directories under it, since what asks is looking for a
6466 // file of its own.
6467 let root = cache::dir().join("sysroots").join("riscv64-linux-musl");
6468 assert_eq!(
6469 printed(&["--target=riscv64-linux-musl", "-print-sysroot"]),
6470 root.display().to_string()
6471 );
6472
6473 // And a compile for this machine has no sysroot, which is the empty line GCC prints when it
6474 // was configured without one rather than a `/` that would be a claim about the filesystem.
6475 let host = Triple::host().expect("a host this compiler knows");
6476 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot"]), "");
6477 }
6478
6479 #[test]
6480 fn the_provenance_of_a_sysroot_is_the_manifest_it_carries() {
6481 // Section 13.5 wants seven things per input and wants them machine readable, and the manifest
6482 // is the record that already has them, so the flag prints that rather than a second format.
6483 let manifest = "rucc sysroot manifest 3\n\
6484 target\tx86_64-linux-musl\n\
6485 kernel\t6.12\n\
6486 include/generic/stdio.h\tmusl-1.2.5\t\
6487 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6488 0000000000000000000000000000000000000000000000000000000000000000\tmit\t\
6489 bundled\n\
6490 lib/libc.so\tmusl-1.2.5\t\
6491 https://musl.libc.org/releases/musl-1.2.5.tar.gz\t\
6492 1111111111111111111111111111111111111111111111111111111111111111\tmit\t\
6493 generated\n";
6494 let tree = TempTree::new("provenance", &[("manifest", manifest)]);
6495 let sysroot = format!("--sysroot={}", tree.0.display());
6496 // The kernel line of tamnd/rucc#934 is in the answer without anything here naming it, because
6497 // the flag parses the record and renders it again rather than picking fields out of it. That
6498 // is the reason it prints a manifest and not a format of its own.
6499 //
6500 // The answer is the file without its last newline, because whatever prints it adds one. The
6501 // file is what somebody diffs the output against, so the two have to be the same bytes.
6502 assert_eq!(printed(&[&sysroot, "-print-sysroot-provenance"]) + "\n", manifest);
6503
6504 // A tree with no manifest in it is a tree somebody assembled themselves, and nothing here
6505 // knows where any of it came from. Saying nothing is the only honest answer, and a reader can
6506 // tell it from a manifest with no inputs because that one still has its two header lines.
6507 let bare = TempTree::new("provenance-bare", &[]);
6508 assert_eq!(
6509 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-provenance"]),
6510 ""
6511 );
6512
6513 // And a compile for this machine has no sysroot at all, which is the same empty answer
6514 // `-print-sysroot` gives for it.
6515 let host = Triple::host().expect("a host this compiler knows");
6516 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-provenance"]), "");
6517
6518 // And the other spelling, which section 13.5 is the document that writes.
6519 assert_eq!(printed(&[&sysroot, "--print-sysroot-provenance"]) + "\n", manifest);
6520
6521 // tamnd/rucc#1021. The digest of the same tree is the sha256 of that record, so it is one
6522 // line where the provenance is a few hundred, and it is checkable with `sha256sum` because
6523 // the bytes it is over are the bytes of the file. The number here is that hash of the
6524 // fixture above, computed by `sha256sum` rather than by this compiler.
6525 assert_eq!(
6526 printed(&[&sysroot, "-print-sysroot-digest"]),
6527 "d705ae6ebeafeb7fda4bd57cecc7882bf49784b17015664a09cfae25a1b2000a"
6528 );
6529 assert_eq!(
6530 printed(&[&sysroot, "--print-sysroot-digest"]),
6531 printed(&[&sysroot, "-print-sysroot-digest"])
6532 );
6533
6534 // And the two empty answers are empty here too, because a digest of nothing would read as a
6535 // claim about a sysroot rather than as the absence of one.
6536 assert_eq!(
6537 printed(&[&format!("--sysroot={}", bare.0.display()), "-print-sysroot-digest"]),
6538 ""
6539 );
6540 assert_eq!(printed(&[&format!("--target={host}"), "-print-sysroot-digest"]), "");
6541 }
6542
6543 #[test]
6544 fn a_manifest_this_build_cannot_read_is_refused_rather_than_printed() {
6545 // Passing a file we could not parse to whoever asked would make their parser the one that
6546 // finds the problem, and the three uses section 13.5 gives for this are all somebody else
6547 // parsing it.
6548 let tree = TempTree::new(
6549 "provenance-bad",
6550 &[("manifest", "rucc sysroot manifest 3\ntarget\tx86_64-linux-musl\nlib/libc.a\n")],
6551 );
6552 let message =
6553 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-provenance"]);
6554 assert!(message.contains("manifest"), "{message}");
6555 assert!(message.contains("1 fields where an input has six"), "{message}");
6556
6557 // The digest is refused for the same file and for a stronger reason: a hash of bytes this
6558 // build cannot read would be a number that names a record nobody can act on.
6559 let digest =
6560 refused(&[&format!("--sysroot={}", tree.0.display()), "-print-sysroot-digest"]);
6561 assert_eq!(digest, message);
6562 }
6563
6564 #[test]
6565 fn the_two_dependency_flags_that_stop_after_the_rule_stop_after_the_rule() {
6566 let (opts, _) = compile(&["-M", "a.c"]);
6567 assert!(opts.deps.emit && opts.deps.instead_of_compiling);
6568 assert!(opts.deps.system_headers, "plain -M lists them");
6569 assert_eq!(opts.emit, EmitKind::Preprocessed);
6570
6571 // Even where a later flag asked for something else, because the family is a mode and
6572 // the mode is what the run is for.
6573 let (opts, _) = compile(&["-M", "-c", "a.c"]);
6574 assert_eq!(opts.emit, EmitKind::Preprocessed);
6575
6576 let (opts, _) = compile(&["-MM", "a.c"]);
6577 assert!(!opts.deps.system_headers);
6578 }
6579
6580 #[test]
6581 fn the_two_that_end_in_d_leave_the_compilation_alone() {
6582 let (opts, _) = compile(&["-MD", "-c", "a.c"]);
6583 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6584 assert!(opts.deps.system_headers);
6585 assert_eq!(opts.emit, EmitKind::Object);
6586
6587 let (opts, _) = compile(&["-MMD", "-c", "a.c"]);
6588 assert!(opts.deps.emit && !opts.deps.instead_of_compiling);
6589 assert!(!opts.deps.system_headers);
6590 }
6591
6592 #[test]
6593 fn nothing_puts_the_system_headers_back_once_a_flag_has_taken_them_out() {
6594 // GCC's rule, and not an oversight in it. The flag asking for fewer of them is read as
6595 // the answer, because the other one never asked the question.
6596 let (opts, _) = compile(&["-MM", "-M", "a.c"]);
6597 assert!(!opts.deps.system_headers);
6598 let (opts, _) = compile(&["-MD", "-MMD", "-c", "a.c"]);
6599 assert!(!opts.deps.system_headers);
6600 let (opts, _) = compile(&["-MMD", "-MD", "-c", "a.c"]);
6601 assert!(!opts.deps.system_headers);
6602 }
6603
6604 #[test]
6605 fn a_target_arrives_escaped_from_one_flag_and_untouched_from_the_other() {
6606 let (opts, _) = compile(&["-MM", "-MT", "a b.o", "-MQ", "a b.o", "a.c"]);
6607 assert_eq!(opts.deps.targets, vec!["a b.o".to_owned(), "a\\ b.o".to_owned()]);
6608 }
6609
6610 #[test]
6611 fn the_rest_of_the_family_is_a_file_and_a_switch() {
6612 let (opts, _) = compile(&["-MM", "-MF", "dep.d", "-MP", "a.c"]);
6613 assert_eq!(opts.deps.file.as_deref(), Some("dep.d"));
6614 assert!(opts.deps.phony);
6615
6616 for flag in ["-MF", "-MT", "-MQ"] {
6617 let e = parse_args(&args(&[flag])).unwrap_err();
6618 assert!(e.message.contains("requires an argument"), "{}", e.message);
6619 }
6620 }
6621
6622 /// Kbuild's spelling, which is how busybox and the kernel ask for every dependency file.
6623 #[test]
6624 fn a_dependency_file_asked_for_through_the_preprocessor_is_written_where_it_said() {
6625 let (opts, _) = compile(&["-Wp,-MD,applets/.applets.o.d", "-c", "a.c"]);
6626 assert!(opts.deps.emit);
6627 assert!(opts.deps.system_headers);
6628 assert_eq!(opts.deps.file.as_deref(), Some("applets/.applets.o.d"));
6629
6630 let (opts, _) = compile(&["-Wp,-MMD,x.d,-MP,-MT,x.o", "-c", "a.c"]);
6631 assert!(!opts.deps.system_headers);
6632 assert!(opts.deps.phony);
6633 assert_eq!(opts.deps.file.as_deref(), Some("x.d"));
6634 assert_eq!(opts.deps.targets, vec!["x.o".to_owned()]);
6635 }
6636
6637 #[test]
6638 fn a_preprocessor_flag_this_compiler_does_not_read_is_still_refused_whole() {
6639 assert!(refused(&["-Wp,-MD", "-c", "a.c"]).contains("separate assembler"));
6640 assert!(refused(&["-Wp,-MD,x.d,-C", "-c", "a.c"]).contains("-Wp,-MD,x.d,-C"));
6641 }
6642
6643 /// A directory of sources for one test, removed when the test is done with it.
6644 struct TempTree(PathBuf);
6645
6646 impl Drop for TempTree {
6647 fn drop(&mut self) {
6648 let _ = std::fs::remove_dir_all(&self.0);
6649 }
6650 }
6651
6652 impl TempTree {
6653 fn new(name: &str, files: &[(&str, &str)]) -> TempTree {
6654 let dir = std::env::temp_dir().join(format!("rucc-deps-{}-{name}", std::process::id()));
6655 let _ = std::fs::remove_dir_all(&dir);
6656 std::fs::create_dir_all(&dir).expect("temporary directory should be writable");
6657 for (path, text) in files {
6658 let at = dir.join(path);
6659 if let Some(parent) = at.parent() {
6660 std::fs::create_dir_all(parent).expect("creating a subdirectory should work");
6661 }
6662 std::fs::write(&at, text).expect("writing a temporary file should work");
6663 }
6664 TempTree(dir)
6665 }
6666
6667 fn path(&self, name: &str) -> String {
6668 self.0.join(name).to_string_lossy().into_owned()
6669 }
6670 }
6671
6672 #[test]
6673 fn the_rule_names_what_the_includes_found_and_names_each_of_them_once() {
6674 // End to end, because the list comes from the preprocessor and the format comes from
6675 // somewhere else, and a test of either half on its own would pass with the two of them
6676 // wired up backwards.
6677 let tree = TempTree::new(
6678 "found",
6679 &[
6680 ("a.c", "#include \"one.h\"\n#include \"two.h\"\nint main(void) { return X; }\n"),
6681 ("one.h", "#define X 0\n"),
6682 ("two.h", "#include \"one.h\"\n"),
6683 ],
6684 );
6685 let out = tree.path("dep.d");
6686 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6687 assert_eq!(code, 0);
6688
6689 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6690 let names: Vec<&str> = text.split_whitespace().collect();
6691 // The target, the source, and each header once however many times it was reached.
6692 assert_eq!(names.first(), Some(&"a.o:"), "{text}");
6693 assert_eq!(names.iter().filter(|n| n.ends_with("one.h")).count(), 1, "{text}");
6694 assert_eq!(names.iter().filter(|n| n.ends_with("two.h")).count(), 1, "{text}");
6695 // And the `-o` went to the file the rule replaced, which is left empty rather than
6696 // absent because a makefile that named it as a target will look for it.
6697 assert_eq!(std::fs::read(tree.path("a.i")).expect("the output should exist"), b"");
6698 }
6699
6700 #[test]
6701 fn syntax_only_checks_the_file_and_writes_nothing() {
6702 // What meson's `has_header_symbol` probe does: compile with `-fsyntax-only` and read the
6703 // exit status. A good file passes and leaves no output behind, a bad one fails.
6704 let tree = TempTree::new(
6705 "syntax-only",
6706 &[
6707 ("good.c", "int f(int x) { return x + 1; }\n"),
6708 ("bad.c", "int f(void) { return y; }\n"),
6709 ],
6710 );
6711 let (opts, _) = compile(&["-fsyntax-only", "a.c"]);
6712 assert_eq!(opts.emit, EmitKind::SyntaxOnly);
6713
6714 let out = tree.path("good.o");
6715 assert_eq!(run(&args(&["-fsyntax-only", "-o", &out, &tree.path("good.c")])), 0);
6716 assert!(!std::path::Path::new(&out).exists(), "-fsyntax-only wrote {out}");
6717 assert!(!std::path::Path::new(&tree.path("good.s")).exists());
6718 assert_ne!(run(&args(&["-fsyntax-only", &tree.path("bad.c")])), 0);
6719 }
6720
6721 #[test]
6722 fn a_header_that_is_only_reached_under_a_guard_is_still_a_dependency() {
6723 // The multiple-include optimization means the second reach never opens the file. It is
6724 // still a file this translation unit was built from, so it is still in the rule.
6725 let tree = TempTree::new(
6726 "guarded",
6727 &[
6728 ("a.c", "#include \"g.h\"\n#include \"g.h\"\nint main(void) { return 0; }\n"),
6729 ("g.h", "#ifndef G\n#define G\n#endif\n"),
6730 ],
6731 );
6732 let out = tree.path("dep.d");
6733 let code = run(&args(&["-MM", "-MF", &out, "-o", &tree.path("a.i"), &tree.path("a.c")]));
6734 assert_eq!(code, 0);
6735 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6736 assert_eq!(text.split_whitespace().filter(|n| n.ends_with("g.h")).count(), 1, "{text}");
6737 }
6738
6739 #[test]
6740 fn every_imacros_file_is_read_before_every_include_file_whatever_order_they_were_written() {
6741 // Measured against GCC rather than read: the two flags the other way round produce the
6742 // same output byte for byte, so the command line order between the two families does not
6743 // decide anything and the order within one does. The `-include` file here can only see
6744 // the definition if the `-imacros` file that was written after it ran first.
6745 let tree = TempTree::new(
6746 "preinclude",
6747 &[
6748 ("a.c", "int main(void) { return 0; }\n"),
6749 ("i.h", "#ifdef FROM_MACROS\nint saw_it;\n#else\nint missed_it;\n#endif\n"),
6750 ("m.h", "#define FROM_MACROS 1\nint macros_text;\n"),
6751 ],
6752 );
6753 let out = tree.path("a.i");
6754 let code = run(&args(&[
6755 "-E",
6756 "-include",
6757 &tree.path("i.h"),
6758 "-imacros",
6759 &tree.path("m.h"),
6760 "-o",
6761 &out,
6762 &tree.path("a.c"),
6763 ]));
6764 assert_eq!(code, 0);
6765 let text = std::fs::read_to_string(&out).expect("the output should have been written");
6766 assert!(text.contains("saw_it"), "{text}");
6767 // And the text of the `-imacros` file is thrown away, which is the whole difference
6768 // between the two flags.
6769 assert!(!text.contains("macros_text"), "{text}");
6770 }
6771
6772 #[test]
6773 fn a_file_the_command_line_named_is_a_prerequisite_the_same_as_one_a_directive_named() {
6774 let tree = TempTree::new(
6775 "preinclude-deps",
6776 &[
6777 ("a.c", "int main(void) { return 0; }\n"),
6778 ("i.h", "int from_include;\n"),
6779 ("m.h", "#define M 1\n"),
6780 ],
6781 );
6782 let out = tree.path("dep.d");
6783 let code = run(&args(&[
6784 "-MM",
6785 "-MF",
6786 &out,
6787 "-include",
6788 &tree.path("i.h"),
6789 "-imacros",
6790 &tree.path("m.h"),
6791 "-o",
6792 &tree.path("a.i"),
6793 &tree.path("a.c"),
6794 ]));
6795 assert_eq!(code, 0);
6796 let text = std::fs::read_to_string(&out).expect("the rule should have been written");
6797 assert!(text.contains("i.h"), "{text}");
6798 assert!(text.contains("m.h"), "{text}");
6799 }
6800
6801 #[test]
6802 fn a_command_line_include_that_is_nowhere_on_the_path_is_an_error_and_not_a_warning() {
6803 // Including the directory of the source file, which is not on the path for these: the
6804 // command line was not written there, so a name in it is relative to where the compiler
6805 // was run rather than to where the source sits.
6806 let tree = TempTree::new(
6807 "preinclude-missing",
6808 &[("sub/a.c", "int main(void) { return 0; }\n"), ("sub/beside.h", "int x;\n")],
6809 );
6810 let code = run(&args(&["-E", "-include", "beside.h", "-o", "-", &tree.path("sub/a.c")]));
6811 assert_eq!(code, 1);
6812 }
6813
6814 #[test]
6815 fn a_command_line_that_links_names_the_executable_and_not_the_object_it_went_through() {
6816 // The object a link goes through is in a temporary directory and is gone before `make`
6817 // reads any of this, so the rule that named it would be a rule for a file that is never
6818 // there. The target and the file are both the `-o`, which is the executable.
6819 let (opts, plan) = compile(&["-MD", "sub/a.c", "-o", "prog"]);
6820 assert_eq!(plan.output.as_deref(), Some("prog"));
6821 assert_eq!(deps::default_target("sub/a.c", deps_target_output(&opts, &plan)), "prog");
6822 assert_eq!(
6823 deps::default_file(&opts.deps, "sub/a.c", plan.output.as_deref()).as_deref(),
6824 Some("prog.d")
6825 );
6826 }
6827
6828 #[test]
6829 fn the_plan_keeps_the_output_name_because_the_rule_is_written_from_it() {
6830 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c", "-o", "obj/x.o"]);
6831 assert_eq!(plan.output.as_deref(), Some("obj/x.o"));
6832 let (_, plan) = compile(&["-MMD", "-c", "sub/a.c"]);
6833 assert_eq!(plan.output, None);
6834 }
6835
6836 #[test]
6837 fn usage_fits_on_a_screen() {
6838 // Not a style preference. A help text that scrolls is one nobody reads, and this is
6839 // the cheapest way to keep it honest as flags accumulate. The number goes up only when
6840 // a family of flags arrives that has nowhere to share a line, which the two pass gates
6841 // were and which the two fuel flags and `-fsafety=` now are, and it goes up by exactly
6842 // the lines that family took. The four it went up by last are the flags a build system
6843 // passes without being asked to: how much to say, what machine to generate for, threads,
6844 // and the questions `configure` asks before it compiles anything. The one it went up by
6845 // last is the second line of `--emit`, whose kinds are a family that has now outgrown
6846 // one line and has nowhere else to go. The two it went up by last are the dependency
6847 // family, which is eight flags that share nothing with anything above them. The one it
6848 // went up by last is the four spellings of position independent code, which every
6849 // configure script writes and which could only have shared the link line, and that line
6850 // is already four characters short of the limit. The two it went up by last are the rest
6851 // of the include family, which is six more flags that change where a header is looked for
6852 // and two that name a header outright. The one it went up by last is the pair that keeps
6853 // the intermediate files and times the steps, which belong next to the two flags above
6854 // them that are also about watching a compilation rather than changing one. The two it
6855 // went up by last are the section flags and the visibility flag, which are what a build
6856 // that cares about the size of what it ships and about which names it exports writes, and
6857 // the second of them was already taken and only missing from here. The one it went up by
6858 // last is the stack protector, which is four spellings of one question and which every
6859 // distribution puts on every command line it issues, so a build that reads this list
6860 // looking for it and does not find it has to go and read the specification instead. The one
6861 // it went up by last is the profiler, which is two spellings of the request and two of
6862 // where the call goes, and which is about watching a program run rather than about what is
6863 // generated, so it shares its subject with nothing above it. The one it went up by last is
6864 // the room a function opens with for something to be written over it later, which takes an
6865 // argument of its own shape and is what a kernel build asks for, so it fits beside the
6866 // profiler and nothing else. The one it went up by last is what overflows rather than being
6867 // undefined, which is three spellings of two questions and which a kernel build and a great
6868 // deal of code written before the standard settled both pass. The one it went up by last is
6869 // the other answer to the first of those questions, which could not share the line because
6870 // what it asks for is the opposite of what the flags on that line ask for. The one it went
6871 // up by last is the split of the line that lists what this compiler does anyway into that
6872 // and what it assumes anyway, which are two different claims that were sharing a line until
6873 // the second of them got a second flag and the line stopped fitting. The one it went up by
6874 // last is the three flags that change the ABI rather than the code, which have to be given
6875 // to every file in a program or none of them and which therefore belong somewhere a person
6876 // reading this list will see them. The one it went up by last is the floating point group,
6877 // which is two lines rather than one because the first of them is a choice this compiler
6878 // records and the rest are claims about what it does anyway, and putting a real setting on
6879 // the same line as three flags that change nothing would be misleading about both. The one
6880 // it went up by last is the flag that says a write has to stay inside the member it names,
6881 // which is a setting rather than a claim and so cannot share the line above it, that being
6882 // the one that picks a tier. The two it went up by last are the prefix mapping family,
6883 // which is four flags whose whole job is to keep a build's output the same from two
6884 // different directories, and which a person chasing a reproducible build comes here
6885 // looking for by name. The one it went up by last is how the debug sections are compressed
6886 // and whether they go in a file of their own, which are two questions about the shape of
6887 // the debug output, where the line above them is about how much of it there is. The one it
6888 // went up by last is the `restrict` contract, which is a setting for the same reason the
6889 // flag that keeps a write inside its member is and which is the check a person who has been
6890 // bitten by a vectorizer comes here looking for. The one it went up by last is link time
6891 // optimization, which is a whole optimization rather than a flag and which says so on its
6892 // own line, because a build that passes it and reads this looking for what it got is
6893 // asking a question no other line here answers. The one it went up by last is the sysroot,
6894 // which is the question somebody asks when a cross build read a file nobody expected, and
6895 // which has no room on the line above it because the answers there are a path each and this
6896 // one is the root all of them are under. The one it went up by last is what is inside that
6897 // root and where each of it came from, which is a question about a whole tree rather than
6898 // about a path and which is long enough on its own that it could not have shared a line with
6899 // anything. The one it went up by last is the profile family, which splits down the middle
6900 // where no other family here does, so the line has to name the half that is taken and the
6901 // half that is refused or it would be read as taking both. The one it went up by last is
6902 // the sanitizers, which are what somebody reaching for a checked build writes first and
6903 // which belong beside the tier that is the nearest thing here to what they asked for. The
6904 // one it went up by last is the digest of that record, which is the same tree as one number
6905 // and could not share the line above it because that line prints a few hundred lines and
6906 // this one prints sixty four characters, and a reader who wants the short answer is looking
6907 // for it by name rather than reading the long one. The one it went up by last is the
6908 // sysroot fetch, which is the only command here that gets something from somewhere else and
6909 // is therefore the one a person wants to have read before they run it rather than after.
6910 // And the flag beside it that forbids every download, which earns its line by being what a
6911 // build in a sealed environment passes and by meaning something even though an ordinary
6912 // compile downloads nothing either way. The one it went up by last is the other fetch, the
6913 // one behind Microsoft's licence wall, which is a line rather than a paragraph because what
6914 // a person needs from here is that the command exists and that it will not do anything
6915 // until they have read a licence it prints for them.
6916 assert!(USAGE.lines().count() < 73, "usage text has grown past one screen");
6917 }
6918}