Skip to main content

rucc_session/
lib.rs

1//! The `Session`: the options, the interner and the diagnostic sink that every stage of a
2//! single compilation is handed.
3//!
4//! Design: `spec/03-architecture.md` and `spec/04-driver-and-cli.md`. Layer rank 4, see
5//! `spec/18-package-layout.md`.
6//!
7//! Everything below the driver reaches the outside world through this type and not through
8//! `std::fs`, `std::env` or `println!`. That is the whole reason the compiler can be used as
9//! a library and tested without spawning a process, and it is enforced by the layer rule
10//! rather than by discipline.
11//!
12//! # Status
13//!
14//! Options, optimisation levels, emit kinds, diagnostic counting, the source map every span
15//! is resolved against, the file system the compiler reads through, the include search path
16//! and the headers the compiler itself ships are real. The parallel job model is still a
17//! placeholder.
18//!
19//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
20//! explicitly unstable and will change without a major version bump.
21
22#![doc(html_root_url = "https://docs.rs/rucc-session/0.10.77")]
23
24mod fs;
25pub mod runtime;
26
27pub use crate::fs::{Dir, FileSystem, Found, IncludeForm, MemoryFileSystem, SearchPath, path_key};
28
29use std::borrow::Cow;
30use std::fmt;
31use std::str::FromStr;
32
33use rucc_base::Interner;
34use rucc_diag::{Diagnostic, Severity, SourceMap};
35use rucc_target::{Os, TargetInfo, Triple};
36
37/// An optimisation level.
38///
39/// `spec/16-performance.md` section 16.4 gives each level a throughput budget and a code
40/// quality budget, and the levels exist to make that tradeoff explicit rather than to be a
41/// dial. There is no `-O4`, because a level nobody can state the contract for is a level
42/// nobody can test.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
44pub enum OptLevel {
45    /// `-O0`. Compile as fast as possible and keep every variable inspectable.
46    #[default]
47    O0,
48    /// `-O1`. The cheap wins, at roughly the cost of `-O0`.
49    O1,
50    /// `-O2`. The full pipeline. This is the level the code quality claim is about.
51    O2,
52    /// `-O3`. `-O2` plus the transformations that trade size for speed.
53    O3,
54    /// `-Os`. Optimise for size, at roughly `-O2` compile time.
55    Os,
56    /// `-Oz`. Optimise for size, aggressively.
57    Oz,
58}
59
60impl OptLevel {
61    /// The flag that selects this level.
62    pub const fn as_flag(self) -> &'static str {
63        match self {
64            OptLevel::O0 => "-O0",
65            OptLevel::O1 => "-O1",
66            OptLevel::O2 => "-O2",
67            OptLevel::O3 => "-O3",
68            OptLevel::Os => "-Os",
69            OptLevel::Oz => "-Oz",
70        }
71    }
72
73    /// Whether this level optimises for size rather than speed.
74    pub const fn is_size(self) -> bool {
75        matches!(self, OptLevel::Os | OptLevel::Oz)
76    }
77
78    /// Whether the middle end runs at all.
79    pub const fn runs_optimizer(self) -> bool {
80        !matches!(self, OptLevel::O0)
81    }
82
83    /// Whether the instructions of a block are put in the order the machine finishes soonest.
84    ///
85    /// `spec/optimizer/38-scheduling-and-layout.md` section 38.6 says `-O2` and above, and gcc
86    /// turns `-fschedule-insns2` on at the two size levels as well, which costs nothing: a
87    /// schedule is a permutation of instructions that were all going to be written anyway, so it
88    /// is the one optimization here that cannot make a function larger.
89    pub const fn schedules(self) -> bool {
90        !matches!(self, OptLevel::O0 | OptLevel::O1)
91    }
92}
93
94impl fmt::Display for OptLevel {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(self.as_flag())
97    }
98}
99
100impl FromStr for OptLevel {
101    type Err = ();
102
103    /// Parses the part after `-O`, so `""` is `-O` which GCC treats as `-O1`.
104    fn from_str(s: &str) -> Result<Self, ()> {
105        Ok(match s {
106            "0" => OptLevel::O0,
107            "" | "1" => OptLevel::O1,
108            "2" => OptLevel::O2,
109            // GCC accepts `-O4` and above and treats them as `-O3`. Build systems in the
110            // wild do pass them, so matching that is cheaper than being right.
111            "3" | "4" | "5" | "6" | "7" | "8" | "9" => OptLevel::O3,
112            "s" => OptLevel::Os,
113            "z" => OptLevel::Oz,
114            _ => return Err(()),
115        })
116    }
117}
118
119/// How much of the memory safety monitor is on, from `-fsafety=`.
120///
121/// Design: `spec/safe-memory/15-integration.md` section 15.4. One flag rather than a plane at a
122/// time, because the tiers of `spec/safe-memory/02-threat-model.md` are the product and the
123/// modifiers are how somebody who has read that document departs from one.
124///
125/// The tiers agree about which accesses are checked and disagree about what happens when a check
126/// says no and about how much of the boundary is covered. That is why they are one value here and
127/// not three booleans: a build asks for a tier, and everything else follows from it.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
129pub enum Safety {
130    /// `-fsafety=off`. No checks and no runtime. The default, and what every existing build gets.
131    #[default]
132    Off,
133    /// `-fsafety=detect`. Tier D: report and carry on, for a test run or a fuzzer.
134    Detect,
135    /// `-fsafety=enforce`. Tier E: report and stop, for a program that faces the network.
136    Enforce,
137    /// `-fsafety=kernel`. Tier K: what a kernel can afford, with the allocator and the libc
138    /// wrappers taken out because a kernel has neither.
139    Kernel,
140}
141
142impl Safety {
143    /// The spelling this tier is asked for by, without the flag in front of it.
144    pub const fn as_str(self) -> &'static str {
145        match self {
146            Safety::Off => "off",
147            Safety::Detect => "detect",
148            Safety::Enforce => "enforce",
149            Safety::Kernel => "kernel",
150        }
151    }
152
153    /// Whether checks are inserted at all.
154    ///
155    /// The three tiers that are not `off` all insert the same checks at this milestone. What
156    /// separates them is the reporter and the boundary, which are milestones S2 and S3 in
157    /// `spec/safe-memory/16-milestones.md`.
158    pub const fn instruments(self) -> bool {
159        !matches!(self, Safety::Off)
160    }
161}
162
163impl fmt::Display for Safety {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.write_str(self.as_str())
166    }
167}
168
169impl FromStr for Safety {
170    type Err = ();
171
172    /// Parses the part after `-fsafety=`.
173    fn from_str(s: &str) -> Result<Self, ()> {
174        Ok(match s {
175            "off" => Safety::Off,
176            "detect" => Safety::Detect,
177            "enforce" => Safety::Enforce,
178            "kernel" => Safety::Kernel,
179            _ => return Err(()),
180        })
181    }
182}
183
184/// Whether padding participates in the init plane, from `-fsafety-init=`.
185///
186/// Design: `spec/safe-memory/09-type-init-and-races.md` section 9.3.
187///
188/// The correct rule is that a store which writes an object as a whole initializes it as a whole,
189/// padding included, and that a fill done a member at a time leaves the padding alone. That rule
190/// reports a structure filled member by member and then hashed, compared or written to a file,
191/// and it is right to: that is CWE-200 and it is the kernel infoleak KMSAN was built to find.
192///
193/// It is also every third program in a userspace corpus, where the bytes never leave the process
194/// and nobody is hunting an infoleak. So section 9.3 makes it a flag and splits the default:
195/// padding participates for the kernel profile, where the leak is the thing being looked for, and
196/// does not for library code, where it would be a torrent of reports about programs nobody is
197/// worried about. Document 12's scoreboard reports the two configurations separately for the same
198/// reason.
199#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
200pub enum Padding {
201    /// `-fsafety-init=nopadding`. A store through a member says the padding after it holds
202    /// something too, so a record filled a member at a time comes out entirely written.
203    #[default]
204    Ignored,
205    /// `-fsafety-init=padding`. A store through a member says only what it wrote, which is
206    /// section 9.3's rule and is what makes the infoleak visible.
207    Tracked,
208}
209
210impl Padding {
211    /// The spelling this is asked for by, without the flag in front of it.
212    pub const fn as_str(self) -> &'static str {
213        match self {
214            Padding::Ignored => "nopadding",
215            Padding::Tracked => "padding",
216        }
217    }
218}
219
220impl fmt::Display for Padding {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        f.write_str(self.as_str())
223    }
224}
225
226impl FromStr for Padding {
227    type Err = ();
228
229    /// Parses the part after `-fsafety-init=`.
230    fn from_str(s: &str) -> Result<Self, ()> {
231        Ok(match s {
232            "nopadding" => Padding::Ignored,
233            "padding" => Padding::Tracked,
234            _ => return Err(()),
235        })
236    }
237}
238
239/// Whether an access has to stay inside the member it names, from `-fsafety-subobject`.
240///
241/// Design: `spec/safe-memory/09-type-init-and-races.md` section 9.4, which is row S4 of document
242/// 03 and is the class Fil-C, CHERI by default and ARM MTE all miss. Their metadata is per
243/// allocation and a member is not an allocation, so an overflow from one member of a structure
244/// into the next is invisible to all three. The type plane is byte granular, so it is not
245/// invisible here.
246///
247/// A flag rather than a default because of what a store means. C 6.5 says a store to allocated
248/// storage sets that storage's effective type, so a write that leaves one member and lands in the
249/// next is, read literally, a program retyping bytes it owns. Every buffer that gets reused for a
250/// second kind of value does the same thing on purpose. So the question a store asks is only asked
251/// when somebody has said they want it asked, and what they get in return is the write half of
252/// S4 that nothing else catches.
253///
254/// The read half is not behind this and never was: a read that disagrees with the plane is
255/// judgement J1 at every tier, because reading bytes back through a type they were not stored
256/// through is undefined however the pointer got there.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
258pub enum Subobject {
259    /// No `-fsafety-subobject`. A store records what it wrote and is asked nothing.
260    #[default]
261    Off,
262    /// `-fsafety-subobject`. A store asks the plane whether the bytes it is about to write agree
263    /// with the type it writes them through, which catches an overflow out of a member into a
264    /// member of a different type.
265    ///
266    /// Two adjacent members of the same type are indistinguishable to this, which section 9.4
267    /// states plainly: `struct { int a; int b; }` overflowing from `a` into `b` writes `int` over
268    /// `int` and there is nothing for the plane to disagree with. That is what
269    /// `-fsafety-subobject=strict` is for and it is not here yet.
270    Members,
271}
272
273impl Subobject {
274    /// The spelling this is asked for by, without the flag in front of it.
275    pub const fn as_str(self) -> &'static str {
276        match self {
277            Subobject::Off => "off",
278            Subobject::Members => "members",
279        }
280    }
281
282    /// Whether a store asks the type plane anything.
283    pub const fn asks(self) -> bool {
284        matches!(self, Subobject::Members)
285    }
286}
287
288impl fmt::Display for Subobject {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        f.write_str(self.as_str())
291    }
292}
293
294/// Whether pointer races are watched, from `-fsafety-races=`.
295///
296/// Design: `spec/safe-memory/09-type-init-and-races.md` section 9.5, which is document 03's C1
297/// through C4 and is judgement J9 of document 04 section 4.4. A thread counts its own metadata
298/// stores, a store through a pointer shaped slot leaves that count in the epoch plane, and an
299/// access that finds a count from another thread which nothing it has done orders is a race that
300/// really happened in the interleaving that really ran.
301///
302/// A flag rather than a default, and the reason is not cost. It is that this is the one plane in
303/// the compiler where instrumentation nobody wrote costs a false report instead of a missed one.
304/// Every ordering the monitor has was carried by a synchronization edge somebody interposed, so two
305/// threads that an edge nobody saw really did join look exactly like two threads nothing joined.
306/// The edges that are calls are interposed already, and the ordering that is not a call at all is
307/// emitted by this pass beside the checks: an atomic that publishes gets a `meta_release` in front
308/// of it and one that takes gets a `meta_acquire` after it. A bare `atomic_thread_fence` gets the
309/// same pair with no key, since it orders against every thread rather than against an object and so
310/// has no address an edge could be keyed on, and the runtime holds one clock for every fence in the
311/// program rather than a table.
312///
313/// Which is also why the default stays [`Races::Off`] after the flag works. Turning it on is a
314/// decision about a program, not about a build.
315#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
316pub enum Races {
317    /// `-fsafety-races=off`. Nothing records into the epoch plane and nothing asks it anything.
318    #[default]
319    Off,
320    /// `-fsafety-races=metadata`. The classes that produce a wrong pointer rather than a wrong
321    /// number, which section 9.5 lists as C1, C3 and C4, and which Tier E carries.
322    Metadata,
323    /// `-fsafety-races=pointer`. The same, and C2 as well, which is a race on a pointer word
324    /// reported in its own right rather than only used to decide one of the other three.
325    Pointer,
326}
327
328impl Races {
329    /// The spelling this is asked for by, without the flag in front of it.
330    pub const fn as_str(self) -> &'static str {
331        match self {
332            Races::Off => "off",
333            Races::Metadata => "metadata",
334            Races::Pointer => "pointer",
335        }
336    }
337
338    /// Whether a store through a pointer shaped slot records which thread made it, and asks first
339    /// whether another thread got there with nothing in between.
340    ///
341    /// Both of the modes that are not off. Every class section 9.5 lists is decided by comparing
342    /// against a stamp a store left behind, so both of them record, and the question a store puts
343    /// is C3, the metadata race, which both of them report.
344    pub const fn records(self) -> bool {
345        !matches!(self, Races::Off)
346    }
347
348    /// Whether a load of a pointer asks the same question, which is where the two modes differ.
349    ///
350    /// C2 of section 9.5, the general pointer word race, which the section lists apart from the
351    /// other three because it is the class reported in its own right rather than used to decide one
352    /// of them. Tier E carries `metadata` and not this, so a build that wants every race a load can
353    /// see has to ask for it by name.
354    pub const fn reads(self) -> bool {
355        matches!(self, Races::Pointer)
356    }
357}
358
359impl fmt::Display for Races {
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        f.write_str(self.as_str())
362    }
363}
364
365impl FromStr for Races {
366    type Err = ();
367
368    /// Parses the part after `-fsafety-races=`.
369    fn from_str(s: &str) -> Result<Self, ()> {
370        Ok(match s {
371            "off" => Races::Off,
372            "metadata" => Races::Metadata,
373            "pointer" => Races::Pointer,
374            _ => return Err(()),
375        })
376    }
377}
378
379/// Whether the `restrict` contract is checked, from `-fsafety-restrict`.
380///
381/// Design: `spec/safe-memory/09-type-init-and-races.md` section 9.6, which is row Y8 of document
382/// 03 and is judgement J8. C 6.7.3.1 says that if an object reachable through a `restrict` pointer
383/// declared in a block is modified anywhere in that block, every access to that object in that
384/// block goes through that pointer. Nothing about one access decides it, which is why document 04
385/// section 4.6 keeps it out of J1.
386///
387/// A flag rather than a default for two reasons, and neither of them is the one
388/// [`Subobject`] has. The first is cost, and it is a bad distribution rather than a large number:
389/// an access inside a block that declares `restrict` pointers pays a scan of that block's record,
390/// and blocks that declare them are the numeric kernels and the `mem` functions, which is exactly
391/// where the hot loops are. Code with no `restrict` in it pays nothing at all. The second is that
392/// the record is the union of what each pointer reached, so two pointers striding through one array
393/// without ever landing on the same byte are reported, and by the letter of the standard those are
394/// different objects and that is not a violation.
395///
396/// The second one is not an imprecision to apologise for. This check exists because a violated
397/// `restrict` is a miscompilation, and what the optimizer acts on is that the ranges are disjoint,
398/// so a program the union rule reports is a program the optimizer is entitled to break. It is
399/// still a report about a program the standard permits, which is a decision that belongs to the
400/// build rather than to this compiler.
401#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
402pub enum Promise {
403    /// No `-fsafety-restrict`. An access says which `restrict` pointer it went through, because
404    /// the alias analysis reads that, and nothing asks whether two of them met.
405    #[default]
406    Off,
407    /// `-fsafety-restrict`. Every block that declares `restrict` pointers keeps a record of what
408    /// each of them reached, and every access through one asks whether another got there first.
409    Blocks,
410}
411
412impl Promise {
413    /// The spelling this is asked for by, without the flag in front of it.
414    pub const fn as_str(self) -> &'static str {
415        match self {
416            Promise::Off => "off",
417            Promise::Blocks => "blocks",
418        }
419    }
420
421    /// Whether a block keeps a record and an access asks about it.
422    pub const fn checks(self) -> bool {
423        matches!(self, Promise::Blocks)
424    }
425}
426
427impl fmt::Display for Promise {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        f.write_str(self.as_str())
430    }
431}
432
433/// How far a name reaches outside a shared library when nothing in the source said.
434///
435/// `-fvisibility=`, which is written on every cmake project that cares about its exports and is
436/// the way a library ships a small documented interface instead of every name it happens to
437/// define. The attribute in the source wins wherever one was written, which is what makes the
438/// flag a default rather than an override and what lets `-fvisibility=hidden` be put on a whole
439/// tree and the dozen exported names marked one at a time.
440///
441/// Three answers to four spellings. `internal` is `hidden` plus a promise about never taking the
442/// address across a component boundary, and nothing here derives anything from that promise, so
443/// what it gets is the same symbol with a weaker claim on it.
444#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
445pub enum Visibility {
446    /// `-fvisibility=default`. Exported and interposable, which is what a name gets when the flag
447    /// is not written at all and what gcc does by default too.
448    #[default]
449    Default,
450    /// `-fvisibility=hidden` and `-fvisibility=internal`. Not in the dynamic symbol table.
451    Hidden,
452    /// `-fvisibility=protected`. In the dynamic symbol table, and a reference from inside the
453    /// library binds to the definition inside it.
454    Protected,
455}
456
457impl Visibility {
458    /// The spelling this is asked for by, without the flag in front of it.
459    ///
460    /// One spelling each, so `internal` is not here: it is a way of asking for `hidden` rather
461    /// than an answer of its own.
462    pub const fn as_str(self) -> &'static str {
463        match self {
464            Visibility::Default => "default",
465            Visibility::Hidden => "hidden",
466            Visibility::Protected => "protected",
467        }
468    }
469}
470
471impl fmt::Display for Visibility {
472    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473        f.write_str(self.as_str())
474    }
475}
476
477impl FromStr for Visibility {
478    type Err = ();
479
480    /// Parses the part after `-fvisibility=`.
481    fn from_str(s: &str) -> Result<Self, ()> {
482        Ok(match s {
483            "default" => Visibility::Default,
484            "hidden" | "internal" => Visibility::Hidden,
485            "protected" => Visibility::Protected,
486            _ => return Err(()),
487        })
488    }
489}
490
491/// How the debug sections are compressed, which is what `-gz` asks.
492///
493/// Debug information is much larger than the code it describes and almost never read, so an ELF
494/// section holding it may be stored compressed: the section keeps its name, gains the
495/// `SHF_COMPRESSED` flag and starts with a header saying what it decompresses to, and every reader
496/// that understands the flag unpacks it on the way in. A distribution that ships debug symbols for
497/// everything it builds saves more from this than from anything else it passes.
498///
499/// Nothing here compresses one yet, so every answer produces the same bytes and an object built
500/// with `-gz=zstd` is identical to one built without the flag. There are sections to compress now,
501/// which makes this a flag waiting on a compressor rather than one waiting on a producer, and
502/// `crates/rucc-debug` is where that is written down.
503#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
504pub enum Compress {
505    /// `-gz=none`, and what a command line that says nothing gets. gcc's default is the same.
506    #[default]
507    None,
508    /// `-gz` and `-gz=zlib`. The ELF way, with the `SHF_COMPRESSED` flag and an `Elf64_Chdr` in
509    /// front of the data. Bare `-gz` means this one, which is worth knowing because the manual
510    /// describes the flag without saying so.
511    Zlib,
512    /// `-gz=zlib-gnu`. The older way, where the section is renamed from `.debug_info` to
513    /// `.zdebug_info` and carries `ZLIB` and a length instead of a real header. Kept because
514    /// binutils still reads it and some build systems still ask for it by name.
515    ZlibGnu,
516    /// `-gz=zstd`. The same arrangement as `Zlib` with a different algorithm in the header, which
517    /// packs debug information smaller and unpacks it faster.
518    Zstd,
519}
520
521impl Compress {
522    /// The spelling this is asked for by, without the `-gz=` in front of it.
523    pub const fn as_str(self) -> &'static str {
524        match self {
525            Compress::None => "none",
526            Compress::Zlib => "zlib",
527            Compress::ZlibGnu => "zlib-gnu",
528            Compress::Zstd => "zstd",
529        }
530    }
531}
532
533impl fmt::Display for Compress {
534    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
535        f.write_str(self.as_str())
536    }
537}
538
539impl FromStr for Compress {
540    type Err = ();
541
542    /// Parses the part after `-gz=`. Bare `-gz` is not this function's business because there is
543    /// nothing after the flag to hand it.
544    fn from_str(s: &str) -> Result<Self, ()> {
545        Ok(match s {
546            "none" => Compress::None,
547            "zlib" => Compress::Zlib,
548            "zlib-gnu" => Compress::ZlibGnu,
549            "zstd" => Compress::Zstd,
550            _ => return Err(()),
551        })
552    }
553}
554
555/// How many processes the link time work is spread over, which is what `-flto=` takes.
556///
557/// Named for the flag rather than for what it counts, because `Jobs` in the driver is already the
558/// answer to how many files are compiled at once and the two numbers are not the same number.
559///
560/// The link time half of link time optimization is where all of the time goes, because it is the
561/// half that has the whole program in front of it, and gcc's answer is to cut the program into
562/// pieces and generate code for the pieces at once. This says how many at once.
563#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
564pub enum LtoJobs {
565    /// Bare `-flto`, and `-flto=1`. One process, which is what gcc does when the flag is written
566    /// without a number after it.
567    #[default]
568    One,
569    /// `-flto=auto`. As many as the machine has, worked out when the link runs.
570    Auto,
571    /// `-flto=jobserver`. As many as `make` is willing to hand out, asked for through the
572    /// jobserver pipe it puts in the environment, which is the only answer that does not fight
573    /// with the rest of a parallel build for the same cores.
574    Jobserver,
575    /// `-flto=<n>`. Exactly that many. gcc refuses a zero, so this is never one.
576    Count(u32),
577}
578
579impl FromStr for LtoJobs {
580    type Err = ();
581
582    /// Parses the part after `-flto=`. A number has to be positive, which is gcc's rule: `-flto=0`
583    /// is refused rather than read as `-fno-lto`.
584    fn from_str(s: &str) -> Result<Self, ()> {
585        Ok(match s {
586            "auto" => LtoJobs::Auto,
587            "jobserver" => LtoJobs::Jobserver,
588            _ => match s.parse::<u32>() {
589                Ok(1) => LtoJobs::One,
590                Ok(n) if n > 1 => LtoJobs::Count(n),
591                _ => return Err(()),
592            },
593        })
594    }
595}
596
597impl fmt::Display for LtoJobs {
598    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
599        match self {
600            LtoJobs::One => f.write_str("1"),
601            LtoJobs::Auto => f.write_str("auto"),
602            LtoJobs::Jobserver => f.write_str("jobserver"),
603            LtoJobs::Count(n) => write!(f, "{n}"),
604        }
605    }
606}
607
608/// How the program is cut up before the link time work is spread over it, from `-flto-partition=`.
609///
610/// A partition is a set of functions that are generated together, and where the cuts fall decides
611/// both how well the work spreads and how much is visible from inside one piece. The names are
612/// gcc's and so are the shapes: one piece per input file, pieces balanced by size, one piece for
613/// the whole program, a piece per function, or no partitioning at all.
614#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
615pub enum Partition {
616    /// `-flto-partition=balanced`, and what gcc does when nothing asks. Pieces of roughly equal
617    /// size, which is the answer that spreads the work best and is why it is the default.
618    #[default]
619    Balanced,
620    /// `-flto-partition=1to1`. One piece per input file, which keeps the generated code in the
621    /// same order the inputs were in and is what a build comparing two outputs wants.
622    OneToOne,
623    /// `-flto-partition=one`. The whole program in one piece, which is the most the optimizer can
624    /// see at once and the least the work can be spread over.
625    One,
626    /// `-flto-partition=max`. A piece per function, which is the other end of the same trade.
627    Max,
628    /// `-flto-partition=none`. No partitioning, and no streaming back out to be generated in
629    /// pieces either.
630    None,
631}
632
633impl Partition {
634    /// The spelling this is asked for by, without the `-flto-partition=` in front of it.
635    pub const fn as_str(self) -> &'static str {
636        match self {
637            Partition::Balanced => "balanced",
638            Partition::OneToOne => "1to1",
639            Partition::One => "one",
640            Partition::Max => "max",
641            Partition::None => "none",
642        }
643    }
644}
645
646impl fmt::Display for Partition {
647    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
648        f.write_str(self.as_str())
649    }
650}
651
652impl FromStr for Partition {
653    type Err = ();
654
655    /// Parses the part after `-flto-partition=`.
656    fn from_str(s: &str) -> Result<Self, ()> {
657        Ok(match s {
658            "balanced" => Partition::Balanced,
659            "1to1" => Partition::OneToOne,
660            "one" => Partition::One,
661            "max" => Partition::Max,
662            "none" => Partition::None,
663            _ => return Err(()),
664        })
665    }
666}
667
668/// What the `-flto` family asked for, which is a whole optimization this compiler does not do yet.
669///
670/// Link time optimization is the optimizer run once over the whole program instead of once per
671/// translation unit, which is the only way an inliner ever sees across a file boundary and is
672/// where most of what is left on the table after `-O2` is. `spec/09-optimizer.md` says how it will
673/// work here: the IR goes into a section of the object, the driver finds those sections at link
674/// time, merges them into one module and generates code with everything visible.
675///
676/// None of that exists, so the whole family is read, checked and recorded rather than acted on.
677/// That is a different answer from the one `-gsplit-dwarf` gets in the same specification, and the
678/// difference is what ignoring each of them does. Ignoring `-gsplit-dwarf` means a file a build
679/// asked for never appears. Ignoring this means a program that is correct and slower than it could
680/// have been, which is what section 4.1 means by a hint about speed, and which is also what every
681/// compilation at `-O0` already is.
682///
683/// The other half of the argument is about the object. gcc's `-flto` object holds the bytecode and
684/// no machine code at all, so it is only useful to a link that knows about it; the objects here
685/// always hold the code, which is what `-ffat-lto-objects` asks gcc for. So a build that passes
686/// `-flto` to this compiler gets objects that are strictly more usable than the ones it would have
687/// got, rather than different ones.
688#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
689pub struct Lto {
690    /// Whether the last of `-flto` and `-fno-lto` on the command line was the first of the two.
691    pub requested: bool,
692    /// How many processes to spread the link time work over.
693    pub jobs: LtoJobs,
694    /// How the program is cut up before the work is spread.
695    pub partition: Partition,
696    /// How hard to compress the IR on its way into the object, from `-flto-compression-level=`,
697    /// where `None` means whatever the compressor does when nobody says. Between 0 and 19, which
698    /// is zstd's range and is the range gcc checks against.
699    pub compression: Option<u8>,
700}
701
702/// What the profile reading half of the `-fprofile` family asked for.
703///
704/// A profile is a count per edge, gathered by running a build of the program that was instrumented
705/// to count, and read back on a second compilation so that the optimizer knows which way each
706/// branch actually went. It is worth more than any single optimization, because almost everything
707/// the optimizer decides is a guess about a frequency that the counts simply state.
708///
709/// Nothing here reads one yet, so this is recorded rather than acted on, and the family splits in
710/// two rather than being taken or refused as a whole. The half recorded here is the half that only
711/// costs speed when it is ignored: a build that asks to read a profile and is not read one gets the
712/// program it would have got anyway, which is what section 4.1 means by a hint about speed. The
713/// other half writes files, and that half is refused by the driver rather than landing here, on the
714/// same reading `-gsplit-dwarf` gets: a program instrumented by `-fprofile-generate` writes a
715/// `.gcda` when it runs and `-ftest-coverage` writes a `.gcno` beside the object, and ignoring
716/// either means a build waits for a file that never arrives and then quietly optimizes against no
717/// counts at all.
718///
719/// gcc's own measurement is the argument for the split. `-fprofile-use` on a file with no counts
720/// beside it produces an object byte for byte identical to the one no flag produces, and warns; the
721/// same file under `-fprofile-generate` grows from 71 bytes of code to 375 with 296 bytes of
722/// counters beside it. So one half of the family is already a no-op in gcc when there is nothing to
723/// read, and the other half is never one.
724#[derive(Debug, Clone, PartialEq, Eq, Default)]
725pub struct Profile {
726    /// Whether the last of `-fprofile-use` and `-fno-profile-use` on the command line was the
727    /// first of the two.
728    pub requested: bool,
729    /// Where to read the counts from, from `-fprofile-use=<path>`, where `None` means beside the
730    /// object the way gcc looks when nobody says. A directory or a file, which is gcc's rule and
731    /// is not something this can tell apart without looking at the filesystem.
732    pub path: Option<String>,
733    /// Where the whole family's files live, from `-fprofile-dir=`. Separate from `path` because
734    /// gcc keeps them separate: this one moves the counts for the generating half as well.
735    pub dir: Option<String>,
736    /// Whether the path recorded in those files is made absolute, from `-fprofile-abs-path`. It is
737    /// what a build with several object directories under one source tree needs so that two files
738    /// of the same name do not land on one set of counts.
739    pub absolute: bool,
740    /// Whether counts that do not add up are repaired rather than refused, from
741    /// `-fprofile-correction`. A program that forked or was killed while it ran leaves counts that
742    /// no single execution could have produced, and this says to make the best of them.
743    pub correction: bool,
744    /// Whether the parts of the program the training run never reached are optimized as if they
745    /// were cold rather than as if nothing were known about them, from `-fprofile-partial-training`.
746    pub partial_training: bool,
747}
748
749/// Which functions get a stack protector, which is what the `-fstack-protector` family asks.
750///
751/// A canary is a word the prologue copies into the frame above everything a local can be written
752/// through, and the epilogue compares it against the copy the runtime still holds before it
753/// returns. A write that runs off the end of a local and keeps going passes the canary on its way
754/// to the return address, so a function that returns with the word changed calls
755/// `__stack_chk_fail` instead of returning at all.
756///
757/// Which functions are worth the slot and the comparison is what the three levels disagree about,
758/// and the middle one is the one that matters: every distribution has built its packages with
759/// `-fstack-protector-strong` for a decade, so a compiler that cannot take the flag cannot be the
760/// `CC` of a package build whatever else it can do.
761#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
762pub enum Protector {
763    /// `-fno-stack-protector`, and what a command line that says nothing gets. gcc's own default
764    /// is the same, and it is the distributions rather than the compiler that turn it on.
765    #[default]
766    None,
767    /// `-fstack-protector`. A function with a local array of at least eight bytes, or one whose
768    /// stack grows while it runs.
769    Buffers,
770    /// `-fstack-protector-strong`. Any of those, and any function with a local array at all, a
771    /// local holding one, or a local whose address is taken.
772    Strong,
773    /// `-fstack-protector-all`. Every function that has a frame.
774    All,
775}
776
777/// What overflows rather than being undefined, from `-fwrapv` and its relatives.
778///
779/// C says a signed addition that overflows and a pointer that walks off the end of the object it
780/// points into are both undefined, and an optimizer that believes it reads a great deal into every
781/// loop: that a counter going up one at a time never turns round, that an index widened to an
782/// address may be widened before the arithmetic rather than after, that a bound is reached. These
783/// flags withdraw exactly that. They do not make the program mean something else, they make it mean
784/// less, and the code that asks for them is code that overflows on purpose and wants the answer the
785/// machine gives rather than the answer the standard declines to give.
786///
787/// Two of them because gcc has two, and a build that wants one usually wants the other. Signed
788/// arithmetic and pointer arithmetic are separate assumptions and a kernel turns both off.
789///
790/// `-ftrapv` is the third answer to the first question and is here for that reason. Undefined,
791/// wrapping and stopping are the three things a signed overflow can be, and a command line picks
792/// one of them: the last of `-fwrapv` and `-ftrapv` wins, which is gcc's behaviour and what makes
793/// them one field rather than two that can both be set.
794#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
795pub struct Wrapping {
796    /// Whether signed arithmetic wraps, from `-fwrapv`.
797    pub signed: bool,
798    /// Whether pointer arithmetic wraps, from `-fwrapv-pointer`.
799    pub pointer: bool,
800    /// Whether a signed overflow stops the program instead, from `-ftrapv`.
801    ///
802    /// Never set at the same time as [`Wrapping::signed`], since a program cannot both wrap and
803    /// stop, and the driver is what keeps that true by clearing each when the other is asked for.
804    pub trap: bool,
805}
806
807impl Wrapping {
808    /// Both of them, which is what `-fno-strict-overflow` asks for.
809    ///
810    /// gcc says so itself: its help text for `-fstrict-overflow` reads "negated as `-fwrapv`
811    /// `-fwrapv-pointer`", so the older flag is a name for the pair rather than a third knob. And
812    /// asking for wrapping is asking for not stopping, so this is the whole answer and not two
813    /// thirds of one.
814    pub const ALL: Self = Self { signed: true, pointer: true, trap: false };
815
816    /// Neither, which is the default and what a command line that says nothing about any of this
817    /// gets.
818    pub const NONE: Self = Self { signed: false, pointer: false, trap: false };
819}
820
821/// A list of `old=new` rewrites to apply to a path before it is written into the output, which is
822/// what the `-f*-prefix-map=` family asks for.
823///
824/// The point of them is a build whose output does not depend on where it was built. A path is the
825/// last thing in an object that a second machine cannot reproduce: two people who check out the
826/// same commit and run the same compiler get the same instructions and different `__FILE__`
827/// strings, and a distribution that wants to prove its binaries came from its sources has to make
828/// that difference go away. So the build says what its root is called, and every path that would
829/// name the real one names that instead.
830///
831/// The rule is a plain string prefix and nothing more, which is worth saying because it looks like
832/// it ought to be about directories. gcc compares the characters, so `s=B` turns `sub/h.h` into
833/// `Bub/h.h`, and an empty `old` matches everything and puts `new` in front of it. The path
834/// compared against is the one the search found, so a header reached through a relative `-I` is
835/// mapped as a relative path and the same header reached through an absolute one is mapped as an
836/// absolute path.
837#[derive(Debug, Clone, Default, PartialEq, Eq)]
838pub struct PrefixMap {
839    /// The rewrites, in the order the command line gave them.
840    entries: Vec<(String, String)>,
841}
842
843impl PrefixMap {
844    /// No rewrites, which is what a command line that says nothing about this gets.
845    #[must_use]
846    pub fn new() -> Self {
847        Self::default()
848    }
849
850    /// Whether nothing was asked for, which is the case worth not spending anything on.
851    #[must_use]
852    pub fn is_empty(&self) -> bool {
853        self.entries.is_empty()
854    }
855
856    /// Adds a rewrite, which is what one flag on the command line is.
857    pub fn push(&mut self, old: impl Into<String>, new: impl Into<String>) {
858        self.entries.push((old.into(), new.into()));
859    }
860
861    /// The two halves of one flag's argument, split at the last `=` rather than the first.
862    ///
863    /// That is where gcc splits it, and it is the answer that makes a path containing an `=`
864    /// mappable: `-ffile-prefix-map=/home/a=b=/src` maps the directory `/home/a=b`. The cost is
865    /// that a replacement cannot contain one, which is the rarer thing to want. `None` when there
866    /// is no `=` at all, which gcc refuses rather than reading as a mapping to nothing.
867    #[must_use]
868    pub fn split(arg: &str) -> Option<(&str, &str)> {
869        arg.rsplit_once('=')
870    }
871
872    /// `path` with the last rewrite that matches it applied, or `path` where none does.
873    ///
874    /// The last rather than the first, because that is gcc's answer and because it is the one a
875    /// build relies on: a mapping set for the whole project and a narrower one set for one
876    /// directory is a command line where the second is meant to win.
877    #[must_use]
878    pub fn apply<'a>(&self, path: &'a str) -> Cow<'a, str> {
879        for (old, new) in self.entries.iter().rev() {
880            if let Some(rest) = path.strip_prefix(old.as_str()) {
881                return Cow::Owned(format!("{new}{rest}"));
882            }
883        }
884        Cow::Borrowed(path)
885    }
886}
887
888/// The three answers to the question the `-f*-prefix-map=` family asks, which is one question
889/// asked about three kinds of output.
890///
891/// They are separate because gcc's flags are separate and a build uses that: a distribution maps
892/// its debug paths to something a debugger can find the sources under and leaves `__FILE__` alone,
893/// or maps `__FILE__` so that an assertion message does not name a build directory and leaves the
894/// debug info pointing at the real tree. `-ffile-prefix-map=` is the shorthand for all three and is
895/// what a build that simply wants to be reproducible writes.
896#[derive(Debug, Clone, Default, PartialEq, Eq)]
897pub struct PrefixMaps {
898    /// What `__FILE__` and `__BASE_FILE__` are rewritten by, from `-fmacro-prefix-map=`.
899    ///
900    /// The only one of the three this compiler acts on today, because it is the only one whose
901    /// output exists: `__FILE__` is a string literal in the binary and an assertion message a user
902    /// reads.
903    pub macros: PrefixMap,
904    /// What a path in the debug info is rewritten by, from `-fdebug-prefix-map=`.
905    ///
906    /// Read by the driver rather than by `rucc-debug`, because the driver is the layer where a path
907    /// is still a path and by the time one reaches the DWARF writer it is a string in a table that
908    /// nothing is allowed to reinterpret. Every path that reaches the line table goes through it,
909    /// the unit's own name and the directory it was compiled in among them.
910    pub debug: PrefixMap,
911    /// What a path in the profile data is rewritten by, from `-fprofile-prefix-map=`.
912    ///
913    /// Nothing reads this yet either, and for the same reason: there is no profile data.
914    pub profile: PrefixMap,
915}
916
917/// How far a multiply and an addition may be fused into one rounding, from `-ffp-contract=`.
918///
919/// A fused multiply add computes `a * b + c` with one rounding instead of two, which is both
920/// faster and closer to the exact answer, and is therefore a different answer. C lets an
921/// implementation do it within one expression and lets a program turn it off with the
922/// `FP_CONTRACT` pragma, gcc does it across a whole function by default, and code that cares about
923/// reproducing a result bit for bit turns it off everywhere.
924///
925/// This is the command line's answer to that question, and it is carried into the IR as an
926/// attribute on each function so that the code generator still has it by the time it would matter.
927/// It is a separate question from the flag on one instruction: a licence granted to an expression
928/// the optimizer has since taken apart is a licence about operations that no longer sit together,
929/// and only the function level answer survives that.
930#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
931pub enum Contract {
932    /// `-ffp-contract=off`. Never, so every rounding the source asked for happens.
933    ///
934    /// The default here, which is not gcc's. gcc defaults to `fast` under its own dialects and to
935    /// `off` under a strict `-std=`, and the reason the default is this one anyway is that nothing
936    /// in this compiler fuses anything: the two settings are the same program today, and of the two
937    /// this is the one that does not write a licence nobody reads onto every function in the file.
938    /// The day the code generator learns to fuse, the default moves to gcc's, and that is a change
939    /// to the code generator rather than to this flag.
940    #[default]
941    Off,
942    /// `-ffp-contract=on`. Within one expression, which is what C allows an implementation to do
943    /// without being asked.
944    On,
945    /// `-ffp-contract=fast`. Anywhere in the function, across statements and across whatever the
946    /// optimizer has rearranged, which is what gcc does under its own dialects.
947    Fast,
948}
949
950impl Contract {
951    /// The spelling after the `=`.
952    pub const fn as_str(self) -> &'static str {
953        match self {
954            Contract::Off => "off",
955            Contract::On => "on",
956            Contract::Fast => "fast",
957        }
958    }
959}
960
961impl fmt::Display for Contract {
962    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
963        f.write_str(self.as_str())
964    }
965}
966
967impl FromStr for Contract {
968    type Err = ();
969
970    fn from_str(s: &str) -> Result<Self, ()> {
971        Ok(match s {
972            "off" => Contract::Off,
973            "on" => Contract::On,
974            "fast" => Contract::Fast,
975            _ => return Err(()),
976        })
977    }
978}
979
980impl Protector {
981    /// The spelling this is asked for by, which is the whole flag rather than a part of one,
982    /// because these are four flags and not one flag with an argument.
983    pub const fn as_str(self) -> &'static str {
984        match self {
985            Protector::None => "-fno-stack-protector",
986            Protector::Buffers => "-fstack-protector",
987            Protector::Strong => "-fstack-protector-strong",
988            Protector::All => "-fstack-protector-all",
989        }
990    }
991}
992
993impl fmt::Display for Protector {
994    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
995        f.write_str(self.as_str())
996    }
997}
998
999/// Which control flow transfers are checked, which is what `-fcf-protection=` asks.
1000///
1001/// Two mechanisms and one flag, because the hardware turns them on together and a program built
1002/// for one and not the other is a program with a hole in whichever half was left out. The forward
1003/// edge is an indirect call or jump, and it is checked by a landing pad at every address one is
1004/// allowed to arrive at, so a corrupted function pointer reaches somewhere somebody meant rather
1005/// than any byte of the program. The backward edge is a return, and it is checked against a second
1006/// copy of the return address the program cannot write to, which needs no instructions at all: the
1007/// machine keeps the copy and the loader turns it on.
1008///
1009/// Which is why the marker matters as much as the code. An object says in a note which halves it
1010/// was built for, the linker takes the intersection over every input, and the loader turns on what
1011/// survives. One object built without the note is enough to turn the whole program's protection
1012/// off, so the note goes in even for a mode that changes no instruction.
1013#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
1014pub enum Control {
1015    /// `-fcf-protection=none` and `-fno-cf-protection`, and what a command line that says nothing
1016    /// gets. gcc's own default is the same on the targets this compiler has a back end for.
1017    #[default]
1018    None,
1019    /// `-fcf-protection=branch`. The forward edge alone: a landing pad at every function, and a
1020    /// note that asks for the check on indirect transfers and not on returns.
1021    Branch,
1022    /// `-fcf-protection=return`. The backward edge alone, which is the note and nothing else,
1023    /// since the copy of the return address is the machine's own and no instruction maintains it.
1024    Return,
1025    /// `-fcf-protection=full`, and what the bare `-fcf-protection` means. Both halves.
1026    Full,
1027    /// `-fcf-protection=check`. Asks that the compilation be checked for compatibility with the
1028    /// mode rather than built in it, so nothing is instrumented and no note is written, which is
1029    /// exactly what gcc emits for it.
1030    Check,
1031}
1032
1033impl Control {
1034    /// Whether a landing pad goes at the top of every function.
1035    #[must_use]
1036    pub const fn branch(self) -> bool {
1037        matches!(self, Control::Branch | Control::Full)
1038    }
1039
1040    /// Whether returns are asked to be checked against the machine's own copy.
1041    #[must_use]
1042    pub const fn ret(self) -> bool {
1043        matches!(self, Control::Return | Control::Full)
1044    }
1045
1046    /// Whether anything at all is asked for, which is what decides whether the file says what it
1047    /// was built for.
1048    ///
1049    /// False for the two modes that build nothing. [`Control::None`] asks for nothing and
1050    /// [`Control::Check`] asks that the compilation be looked at rather than changed, and gcc
1051    /// writes no note for either.
1052    #[must_use]
1053    pub const fn any(self) -> bool {
1054        self.branch() || self.ret()
1055    }
1056
1057    /// What the argument was spelled as, which is the part after the equals sign.
1058    pub const fn as_str(self) -> &'static str {
1059        match self {
1060            Control::None => "none",
1061            Control::Branch => "branch",
1062            Control::Return => "return",
1063            Control::Full => "full",
1064            Control::Check => "check",
1065        }
1066    }
1067}
1068
1069impl fmt::Display for Control {
1070    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1071        f.write_str(self.as_str())
1072    }
1073}
1074
1075impl FromStr for Control {
1076    type Err = ();
1077
1078    /// Parses the part after `-fcf-protection=`.
1079    fn from_str(s: &str) -> Result<Self, ()> {
1080        Ok(match s {
1081            "none" => Control::None,
1082            "branch" => Control::Branch,
1083            "return" => Control::Return,
1084            "full" => Control::Full,
1085            "check" => Control::Check,
1086            _ => return Err(()),
1087        })
1088    }
1089}
1090
1091/// Where the call `-pg` puts at the top of every function goes, which `-mfentry` chooses.
1092///
1093/// Two conventions for one job, and the difference is what the hook can see when it runs. See
1094/// [`rucc_target::Trace`] for what each of them is and why a kernel needs the earlier one.
1095///
1096/// A third answer, because a command line that named neither has not asked a question: the
1097/// platform's own answer is the one it gets, and that is a fact about the target rather than about
1098/// the flags, so it is settled where the target is known and not here.
1099#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
1100pub enum Hook {
1101    /// Whichever the platform puts first, which is what a command line that said neither gets.
1102    #[default]
1103    Platform,
1104    /// `-mfentry`. In front of the prologue, so the return address is the top thing on the stack
1105    /// and the arguments are still where the call left them.
1106    Early,
1107    /// `-mno-fentry`. Once the frame is taken, so the hook can walk back through the frame pointer,
1108    /// which is why a function that has this one is given a frame pointer whatever else was said.
1109    Late,
1110}
1111
1112impl Hook {
1113    /// That answer as it is written on a command line, which is what `--print-config` reports.
1114    #[must_use]
1115    pub const fn as_str(self) -> &'static str {
1116        match self {
1117            Hook::Platform => "platform",
1118            Hook::Early => "fentry",
1119            Hook::Late => "mcount",
1120        }
1121    }
1122
1123    /// Whether the call goes in front of the prologue, given what the platform puts first.
1124    #[must_use]
1125    pub const fn early(self, fentry: bool) -> bool {
1126        match self {
1127            Hook::Platform => fentry,
1128            Hook::Early => true,
1129            Hook::Late => false,
1130        }
1131    }
1132}
1133
1134impl fmt::Display for Hook {
1135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136        f.write_str(self.as_str())
1137    }
1138}
1139
1140/// How much room at the top of every function is reserved for somebody to write over later, which
1141/// `-fpatchable-function-entry=` asks for.
1142///
1143/// Room rather than instructions. What goes there is a run of the shortest instruction the machine
1144/// has that does nothing, and the point of them is that they are never executed for long: a tracer
1145/// or a live patcher overwrites them with a jump or a call once the program is running, and what it
1146/// needs from the compiler is a known address, a known number of bytes, and a promise that nothing
1147/// in the function jumps into the middle of them.
1148///
1149/// Two numbers because the room can be on either side of the function's own label, and the two
1150/// sides are not the same thing. Room after the label is room inside the function, which is what a
1151/// patcher that redirects a call into the function wants. Room in front of the label is outside it,
1152/// so what goes there is reached only by something that already knows the address, and a patcher
1153/// that wants somewhere to put a whole instruction it can reach from the first one needs it.
1154///
1155/// The address recorded for the function is the start of the room, which is the front of the part
1156/// before the label when there is one and the front of the part after it when there is not.
1157#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
1158pub struct Patchable {
1159    /// How many bytes in total, which is the first number and the one a command line must give.
1160    pub total: u32,
1161    /// How many of them go in front of the function's own label, which is the second number and is
1162    /// zero on a command line that gave one number.
1163    pub before: u32,
1164}
1165
1166impl Patchable {
1167    /// Whether any room at all was asked for, which is what decides whether a function gets a
1168    /// record.
1169    ///
1170    /// `=0` is a command line that asked for none, and gcc accepts it and writes nothing, so the
1171    /// question is about the number rather than about whether the flag was written.
1172    #[must_use]
1173    pub const fn any(self) -> bool {
1174        self.total > 0
1175    }
1176
1177    /// How many bytes go after the function's own label, which is the rest of them.
1178    #[must_use]
1179    pub const fn after(self) -> u32 {
1180        self.total - self.before
1181    }
1182}
1183
1184impl FromStr for Patchable {
1185    type Err = ();
1186
1187    /// Parses the part after `-fpatchable-function-entry=`, which is a number or two of them.
1188    ///
1189    /// A second number larger than the first is refused rather than clamped, because it asks for
1190    /// more room in front of the label than there is room at all and there is no reading of that a
1191    /// caller meant. So is a third, and so is anything that is not a number, which is what gcc does
1192    /// with each of them.
1193    fn from_str(s: &str) -> Result<Self, ()> {
1194        let (total, before) = match s.split_once(',') {
1195            Some((total, before)) => (total, before),
1196            None => (s, "0"),
1197        };
1198        let total: u32 = total.parse().map_err(|_| ())?;
1199        let before: u32 = before.parse().map_err(|_| ())?;
1200        if before > total {
1201            return Err(());
1202        }
1203        Ok(Patchable { total, before })
1204    }
1205}
1206
1207impl fmt::Display for Patchable {
1208    /// Written the way it was asked for, which is one number when the second is zero.
1209    ///
1210    /// Not because the two forms mean different things, they do not, but because that is the form
1211    /// a command line reaching for this feature writes and reading back what was written is what
1212    /// `--print-config` is for.
1213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1214        match self.before {
1215            0 => write!(f, "{}", self.total),
1216            before => write!(f, "{},{before}", self.total),
1217        }
1218    }
1219}
1220
1221/// Which of the two position independent questions the output is answering.
1222///
1223/// Everything this compiler writes is position independent, so this is not about whether there are
1224/// absolute addresses in the text. It is about whether the link that reads the object is one that
1225/// puts every name in the same program. An executable is such a link and a shared library is not,
1226/// and the difference decides how a name is reached: from the instruction pointer where the
1227/// distance is a number the linker has, and out of the global offset table where it is not.
1228///
1229/// The expensive answer is the one that has to be asked for, which is gcc's arrangement and is why
1230/// `-fPIC` is on the compile line of every library and nowhere else. A name is only reached the
1231/// expensive way when it is one another object may define or replace, so `-fPIC -fvisibility=hidden`
1232/// costs no more than an executable does.
1233#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
1234pub enum Pic {
1235    /// `-fPIE`, `-fpie` and nothing at all. The link puts every name in one program, so a name this
1236    /// file defines is at a distance from the instruction asking, and a name it declares ends up at
1237    /// one too, because the linker answers a reference to a variable defined in a library by making
1238    /// room for it here and copying it. That is what a distribution's default build is.
1239    #[default]
1240    Executable,
1241    /// `-fPIC` and `-fpic`. The output may end up in a shared library, where a name the file
1242    /// exports is one something loaded earlier may define too, and where a name defined elsewhere
1243    /// is not copied in. Both are reached through the global offset table.
1244    Library,
1245}
1246
1247impl Pic {
1248    /// The spelling this is asked for by, which is the one gcc's manual leads with.
1249    pub const fn as_str(self) -> &'static str {
1250        match self {
1251            Pic::Executable => "-fPIE",
1252            Pic::Library => "-fPIC",
1253        }
1254    }
1255}
1256
1257impl fmt::Display for Pic {
1258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1259        f.write_str(self.as_str())
1260    }
1261}
1262
1263/// What the compiler should produce.
1264///
1265/// The intermediate forms are not a debugging convenience bolted on later. Every one of them
1266/// is a documented textual form that round-trips, which is what makes the per-stage testing
1267/// in `spec/15-testing.md` section 15.2 possible.
1268#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1269// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
1270// match that needs to change, in this workspace and in anyone else's code. That is
1271// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
1272// target is a data change: the compiler tells you every place the data is read.
1273pub enum EmitKind {
1274    /// A linked executable. The default.
1275    #[default]
1276    Executable,
1277    /// An object file, `-c`.
1278    Object,
1279    /// A static library holding the objects of every input, `--emit=archive`.
1280    ///
1281    /// Not a GCC mode, because GCC has `ar` beside it and we have said we ship a toolchain rather
1282    /// than half of one. What needs it first is `cargo xtask builtins`, which has to turn a
1283    /// directory of C files into the `librucc_builtins.a` a cross link looks for, for a target
1284    /// whose machine may have no `ar` that knows the format.
1285    ///
1286    /// It is a mode of the compiler rather than a second program because of the symbol index. A
1287    /// static link resolves through it, so writing one means knowing what each member defines, and
1288    /// the compiler has just finished compiling them. An `ar` would have to read the objects back
1289    /// to find out the same thing.
1290    Archive,
1291    /// Assembly text, `-S`.
1292    Asm,
1293    /// Preprocessed source, `-E`.
1294    Preprocessed,
1295    /// The typed AST, `--emit=tast`.
1296    Tast,
1297    /// The IR, `--emit=ir`.
1298    Ir,
1299    /// The machine IR after register allocation, `--emit=mir-final`.
1300    MirFinal,
1301    /// The safety summary, `--emit=safety-summary`.
1302    ///
1303    /// Not an intermediate form of the program the way the three above are. It is the answer to
1304    /// "what does this build's guarantee actually rest on", which
1305    /// `spec/safe-memory/07-check-elimination.md` section 7.8 asks for and
1306    /// `spec/safe-memory/10-boundaries.md` section 10.2 says why.
1307    SafetySummary,
1308    /// How the bytes of the translation unit's records fall into granules,
1309    /// `--emit=type-granules`.
1310    ///
1311    /// Not an intermediate form either. It is the measurement
1312    /// `spec/safe-memory/17-open-questions.md` question 6 asks for, which decides whether the
1313    /// type plane fits inside Tier D's memory budget, and it needs nothing past the type
1314    /// checker because it is a question about layouts rather than about code.
1315    TypeGranules,
1316}
1317
1318impl EmitKind {
1319    /// The name used by `--emit=` and by `--print-config`.
1320    pub const fn as_str(self) -> &'static str {
1321        match self {
1322            EmitKind::Executable => "exe",
1323            EmitKind::Object => "obj",
1324            EmitKind::Archive => "archive",
1325            EmitKind::Asm => "asm",
1326            EmitKind::Preprocessed => "preprocessed",
1327            EmitKind::Tast => "tast",
1328            EmitKind::Ir => "ir",
1329            EmitKind::MirFinal => "mir-final",
1330            EmitKind::SafetySummary => "safety-summary",
1331            EmitKind::TypeGranules => "type-granules",
1332        }
1333    }
1334}
1335
1336impl FromStr for EmitKind {
1337    type Err = ();
1338
1339    fn from_str(s: &str) -> Result<Self, ()> {
1340        Ok(match s {
1341            "exe" => EmitKind::Executable,
1342            "obj" => EmitKind::Object,
1343            "archive" => EmitKind::Archive,
1344            "asm" => EmitKind::Asm,
1345            "preprocessed" => EmitKind::Preprocessed,
1346            "tast" => EmitKind::Tast,
1347            "ir" => EmitKind::Ir,
1348            "mir-final" => EmitKind::MirFinal,
1349            "safety-summary" => EmitKind::SafetySummary,
1350            "type-granules" => EmitKind::TypeGranules,
1351            _ => return Err(()),
1352        })
1353    }
1354}
1355
1356/// Which C the source is written in.
1357///
1358/// The GNU variants are the same language with `__STRICT_ANSI__` left undefined, so the
1359/// dialect and the extension question are two fields rather than ten variants.
1360#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
1361pub enum Std {
1362    /// `-std=c89`, and `-ansi`.
1363    C89,
1364    /// `-std=c99`.
1365    C99,
1366    /// `-std=c11`.
1367    C11,
1368    /// `-std=c17`, which is C11 with the defect reports applied.
1369    C17,
1370    /// `-std=c23`. The default, matching current GCC.
1371    #[default]
1372    C23,
1373    /// `-std=c2y`, the draft after C23, which gcc 16 takes and reports as `202500L`. It is C23
1374    /// with whatever the next standard has added so far, and the one addition anything here reads
1375    /// yet is the four unsigned absolute value functions under their plain names.
1376    C2y,
1377}
1378
1379impl Std {
1380    /// What `__STDC_VERSION__` says, which C89 does not define at all.
1381    pub const fn stdc_version(self) -> Option<&'static str> {
1382        match self {
1383            Std::C89 => None,
1384            Std::C99 => Some("199901L"),
1385            Std::C11 => Some("201112L"),
1386            Std::C17 => Some("201710L"),
1387            Std::C23 => Some("202311L"),
1388            Std::C2y => Some("202500L"),
1389        }
1390    }
1391
1392    /// The name in `-std=`.
1393    pub const fn as_str(self) -> &'static str {
1394        match self {
1395            Std::C89 => "c89",
1396            Std::C99 => "c99",
1397            Std::C11 => "c11",
1398            Std::C17 => "c17",
1399            Std::C23 => "c23",
1400            Std::C2y => "c2y",
1401        }
1402    }
1403
1404    /// Whether this dialect has `_Atomic`, `_Thread_local` and the rest of C11.
1405    pub const fn has_c11(self) -> bool {
1406        matches!(self, Std::C11 | Std::C17 | Std::C23 | Std::C2y)
1407    }
1408
1409    /// Reads a `-std=` argument, and says whether the GNU extensions came with it.
1410    ///
1411    /// Every alias GCC takes is here, including the `iso9899` spellings and the year based
1412    /// ones, because a build system that passes `-std=iso9899:1999` is passing what its
1413    /// author tested against and rejecting it helps nobody. An unknown dialect is `None`
1414    /// rather than a guess, since guessing means compiling a different language than the one
1415    /// asked for.
1416    #[must_use]
1417    pub fn from_flag(name: &str) -> Option<(Std, bool)> {
1418        let gnu = name.starts_with("gnu");
1419        let std = match name {
1420            "c89" | "c90" | "gnu89" | "gnu90" | "iso9899:1990" | "iso9899:199409" => Std::C89,
1421            "c99" | "c9x" | "gnu99" | "gnu9x" | "iso9899:1999" | "iso9899:199x" => Std::C99,
1422            "c11" | "c1x" | "gnu11" | "gnu1x" | "iso9899:2011" => Std::C11,
1423            "c17" | "c18" | "gnu17" | "gnu18" | "iso9899:2017" | "iso9899:2018" => Std::C17,
1424            "c23" | "c2x" | "gnu23" | "gnu2x" => Std::C23,
1425            "c2y" | "gnu2y" => Std::C2y,
1426            _ => return None,
1427        };
1428        Some((std, gnu))
1429    }
1430}
1431
1432/// The GCC release the compiler claims to be, as `__GNUC__`, `__GNUC_MINOR__` and
1433/// `__GNUC_PATCHLEVEL__`.
1434///
1435/// Design: `spec/04-driver-and-cli.md` section 4.5, which makes this a knob rather than a
1436/// constant and says to start conservative and raise it as the matrix in `rucc-gnu` fills in.
1437///
1438/// The default is sixteen, which is the release this compiler is written against. glibc gates
1439/// most of what it hands a caller on `__GNUC_PREREQ`, so the claim decides which half of
1440/// `sys/cdefs.h` we get, and a project does the same thing to itself: it asks what compiler this
1441/// is and writes different code depending on the answer. The claim is therefore not a boast, it
1442/// is the sentence that selects which of a program's own branches gets compiled, and claiming an
1443/// old release means compiling the code that release needed rather than the code this compiler
1444/// wants.
1445///
1446/// It stood at seven for a long time, and seven was the right number then. Below seven
1447/// `bits/floatn-common.h` writes `typedef float _Float32;` over a keyword this compiler already
1448/// has and every header that reaches it stops there, so moving from 4.2.1 to seven took Ubuntu
1449/// 24.04's glibc 2.39 from 180 of 214 headers to 202 and took the amalgamated sqlite from four
1450/// errors to none. What kept it at seven after that was that nothing needed more, and claiming a
1451/// version whose promises have not been kept means being handed syntax the compiler cannot parse.
1452///
1453/// What needed more was micropython. Its `py/nlrx64.c` asks for `__GNUC__ >= 8` before it writes
1454/// `__attribute__((naked))`, and at seven it took the gcc 7 path instead and handed this compiler
1455/// an ordinary function ending in a bare `jmp`, which is refused and ought to be. The naked
1456/// function it writes at eight and above compiles here, byte for byte what gcc 16 emits, and had
1457/// compiled for a week without micropython ever reaching it.
1458///
1459/// The measurement that moved it is the real corpus at the rung the claim could break: fifty six
1460/// projects across rungs zero through three, built at `-O2` with the claim at seven and again at
1461/// sixteen, on gcc 16.0.1 and glibc. Fifty of fifty six passed both times, and it was the same
1462/// fifty both times, with the same four not passing for the same four reasons. Nothing regressed
1463/// and nothing started working by accident. Thirteen and sixteen had already been measured
1464/// identical to seven on glibc, on the macOS SDK and on sqlite when seven was chosen, so this
1465/// confirms on real builds what the header sweep said.
1466///
1467/// Sixteen point zero rather than the point release on any particular machine, because
1468/// `__GNUC_PREREQ(16, 1)` is a promise about a specific release and the honest claim is the
1469/// earliest one in the series whose promises this compiler means to keep.
1470#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1471pub struct GnucVersion {
1472    /// `__GNUC__`.
1473    pub major: u32,
1474    /// `__GNUC_MINOR__`.
1475    pub minor: u32,
1476    /// `__GNUC_PATCHLEVEL__`.
1477    pub patch: u32,
1478}
1479
1480impl Default for GnucVersion {
1481    fn default() -> GnucVersion {
1482        GnucVersion { major: 16, minor: 0, patch: 0 }
1483    }
1484}
1485
1486impl FromStr for GnucVersion {
1487    type Err = String;
1488
1489    /// Reads `-fgnuc-version=`, which is `15`, `15.1` or `15.1.0`.
1490    ///
1491    /// The short forms are not a convenience, they are what people write. A missing component
1492    /// is zero, the same way GCC treats a release with no patchlevel.
1493    fn from_str(text: &str) -> Result<GnucVersion, String> {
1494        let mut parts = text.split('.');
1495        let mut next = |what: &str| -> Result<u32, String> {
1496            match parts.next() {
1497                None => Ok(0),
1498                Some(field) => {
1499                    field.parse().map_err(|_| format!("`{text}` has a {what} that is not a number"))
1500                }
1501            }
1502        };
1503        let major = next("major")?;
1504        let minor = next("minor")?;
1505        let patch = next("patchlevel")?;
1506        if parts.next().is_some() {
1507            return Err(format!("`{text}` has more than three components"));
1508        }
1509        Ok(GnucVersion { major, minor, patch })
1510    }
1511}
1512
1513/// What the `-d` family asks to be dumped alongside, or instead of, the preprocessed output.
1514///
1515/// Design: `spec/04-driver-and-cli.md` section 4.4.
1516///
1517/// GCC spells these as letters packed into one flag, so `-dDI` is two of them, and a letter it
1518/// does not know is ignored rather than rejected. That last part is deliberate on GCC's side
1519/// and worth copying: the family is a debugging aid and a build that passes `-dumpbase` should
1520/// not die on the `-d`.
1521#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1522pub struct Dumps {
1523    /// `-dM`. Print the macros that are defined at the end, and nothing else.
1524    pub macros: bool,
1525}
1526
1527impl Dumps {
1528    /// The letters GCC's preprocessor takes after `-d`.
1529    ///
1530    /// `M` is the macros, `D` is the macros in place, `N` is their names only, `I` is the
1531    /// `#include` lines and `U` is the macros as they are used. Only `M` does anything so far.
1532    const LETTERS: &'static str = "MDNIU";
1533
1534    /// Whether `arg` is a flag from this family rather than something else beginning with
1535    /// `-d`.
1536    ///
1537    /// The check is here rather than in the driver so that the set of letters and the set of
1538    /// flags accepted cannot drift apart. It matters because `-dumpversion` also begins with
1539    /// `-d`, and a family that swallowed every such flag would turn a flag we have not written
1540    /// into a dump of nothing.
1541    #[must_use]
1542    pub fn is_family(arg: &str) -> bool {
1543        match arg.strip_prefix("-d") {
1544            Some("") | None => false,
1545            Some(letters) => letters.chars().all(|c| Dumps::LETTERS.contains(c)),
1546        }
1547    }
1548
1549    /// Reads the letters after `-d`, ignoring the ones we do not implement yet.
1550    pub fn add(&mut self, letters: &str) {
1551        for letter in letters.chars() {
1552            if letter == 'M' {
1553                self.macros = true;
1554            }
1555        }
1556    }
1557
1558    /// Whether anything at all was asked for.
1559    #[must_use]
1560    pub const fn any(self) -> bool {
1561        self.macros
1562    }
1563}
1564
1565/// A file `-imacros` or `-include` named, read before the source file.
1566///
1567/// Design: `spec/04-driver-and-cli.md` section 4.4.
1568///
1569/// The flag a build reaches for when a whole tree has to see a definition that is not in any of
1570/// its files. The kernel builds every object with `-include` of its own configuration header, and
1571/// a configure script that has produced a `config.h` gets it into a third party source tree the
1572/// same way, without a patch.
1573#[derive(Debug, Clone, PartialEq, Eq)]
1574pub struct Preinclude {
1575    /// The name as it was written, which is looked for the way a quoted include is looked for.
1576    pub name: String,
1577    /// Whether only the definitions it makes are wanted, which is what `-imacros` asks for.
1578    ///
1579    /// The text of an `-imacros` file is read and thrown away, so a header full of declarations
1580    /// contributes its macros and nothing else. That is what makes it usable on a file that has
1581    /// already been included by the source: the definitions arrive early and the declarations do
1582    /// not arrive twice.
1583    pub macros_only: bool,
1584}
1585
1586/// What the `-M` family asks for, which is a make rule saying what a source file was built from.
1587///
1588/// Design: `spec/04-driver-and-cli.md` section 4.4.
1589///
1590/// This is a compiler flag rather than a separate tool because the answer is the set of files the
1591/// preprocessor opened, and nothing outside the preprocessor knows what that was. A build system
1592/// that generates its own makefiles asks for it on every compilation, which is why section 4.4
1593/// calls the family required rather than convenient.
1594#[derive(Debug, Clone, PartialEq, Eq)]
1595pub struct Deps {
1596    /// Whether a rule is produced at all, which is any of `-M`, `-MM`, `-MD` and `-MMD`.
1597    pub emit: bool,
1598    /// Whether the rule is produced instead of compiling, which is `-M` and `-MM` and not the
1599    /// two that end in `D`.
1600    ///
1601    /// The split is GCC's and it is about who reads the answer. The two that stop after the rule
1602    /// write it to standard output for a person, and the two that do not write it to a file
1603    /// beside the object for `make` to include on the next run.
1604    pub instead_of_compiling: bool,
1605    /// Whether a header found in a system directory is listed, which `-MM` and `-MMD` turn off.
1606    ///
1607    /// A build that lists them is a build that rebuilds the world when the C library is updated,
1608    /// which is either what somebody wanted or the reason they reached for the other spelling.
1609    ///
1610    /// On unless a flag turned it off, and nothing turns it back on. That is GCC's behaviour and
1611    /// not an oversight: `-MM -M` leaves the system headers out, because the flag that asks for
1612    /// fewer of them is read as the answer to a question the other one never asked.
1613    pub system_headers: bool,
1614    /// Where the rule is written, from `-MF`, with `-` meaning standard output.
1615    ///
1616    /// `None` is the default, which is standard output when the rule replaces the compilation and
1617    /// the output file with a `.d` suffix when it does not.
1618    pub file: Option<String>,
1619    /// What the rule's targets are, from `-MT` and `-MQ`, in the order they were given.
1620    ///
1621    /// Already escaped, because that is the whole of the difference between the two flags: `-MQ`
1622    /// escapes what it is given and `-MT` writes it through untouched. Empty means the target is
1623    /// worked out from the output file, which is what a build that passes neither expects.
1624    pub targets: Vec<String>,
1625    /// Whether every prerequisite except the source gets a target of its own with no recipe,
1626    /// from `-MP`.
1627    ///
1628    /// This is what stops `make` failing outright when a header is deleted. Without it the old
1629    /// rule names a file that is gone and no rule makes it, and the build stops on a header that
1630    /// nothing needs any more.
1631    pub phony: bool,
1632}
1633
1634impl Default for Deps {
1635    fn default() -> Deps {
1636        Deps {
1637            emit: false,
1638            instead_of_compiling: false,
1639            system_headers: true,
1640            file: None,
1641            targets: Vec::new(),
1642            phony: false,
1643        }
1644    }
1645}
1646
1647/// Whether `-save-temps` was given and where it puts the files it keeps.
1648///
1649/// Design: `spec/04-driver-and-cli.md` section 4.10.
1650///
1651/// The flag is how a build gets at the preprocessed source of the file that failed without running
1652/// the compiler a second time under different flags, which is the one way to be sure the text being
1653/// read is the text that was compiled. A bug report against a compiler is usually a preprocessed
1654/// file and nothing else, and this is where that file comes from.
1655#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1656pub enum SaveTemps {
1657    /// Not asked for, and nothing is kept.
1658    #[default]
1659    No,
1660    /// Beside the file the compilation produced, which is `-save-temps=obj`.
1661    ///
1662    /// This is what the bare `-save-temps` does as well. GCC's manual says the bare spelling is
1663    /// `-save-temps=cwd`, and gcc 16 does not do that: `-save-temps -c a.c -o out/a.o` leaves
1664    /// `out/a.i` and `out/a.s` rather than `a.i` and `a.s`. The measurement is what is followed
1665    /// here, because a build that reads the manual and a build that reads the compiler both end up
1666    /// looking for the files where the compiler put them.
1667    Object,
1668    /// In the working directory, which is `-save-temps=cwd`.
1669    Cwd,
1670}
1671
1672impl SaveTemps {
1673    /// Whether anything is kept at all.
1674    #[must_use]
1675    pub const fn wanted(self) -> bool {
1676        !matches!(self, SaveTemps::No)
1677    }
1678}
1679
1680impl FromStr for SaveTemps {
1681    type Err = String;
1682
1683    /// Reads what came after the `=`, which is the only part that varies.
1684    ///
1685    /// # Errors
1686    ///
1687    /// Returns the offending word. GCC treats an unknown one as fatal rather than ignoring it,
1688    /// which is right: a misspelled keyword here means the files a person went looking for are not
1689    /// written and nothing said so.
1690    fn from_str(s: &str) -> Result<SaveTemps, String> {
1691        match s {
1692            "obj" => Ok(SaveTemps::Object),
1693            "cwd" => Ok(SaveTemps::Cwd),
1694            _ => Err(format!("`{s}` is not a -save-temps option; accepted: cwd, obj")),
1695        }
1696    }
1697}
1698
1699/// Everything a compilation was asked to do.
1700///
1701/// Options are a plain value with no interior mutability, so a caller can build one, clone
1702/// it, tweak one field and run a second compilation, which is exactly what the differential
1703/// testing in `spec/15-testing.md` needs.
1704#[derive(Debug, Clone, PartialEq, Eq)]
1705#[non_exhaustive]
1706pub struct Options {
1707    /// The target to generate code for.
1708    pub target: Triple,
1709    /// The optimisation level.
1710    pub opt_level: OptLevel,
1711    /// How much of the memory safety monitor is on, from `-fsafety=`.
1712    ///
1713    /// Off unless it was asked for. A program built without the flag is compiled by exactly the
1714    /// pipeline it was compiled by before the monitor existed, which is the only way the feature
1715    /// can be developed in the open without every build paying for it.
1716    pub safety: Safety,
1717    /// Whether padding participates in the init plane, from `-fsafety-init=`.
1718    ///
1719    /// Means nothing unless `safety` asked for a tier. The default is the one section 9.3 gives
1720    /// library code, which is that it does not, so a record filled a member at a time is not
1721    /// reported when something later reads it whole.
1722    pub padding: Padding,
1723    /// Whether an access has to stay inside the member it names, from `-fsafety-subobject`.
1724    ///
1725    /// Means nothing unless `safety` asked for a tier. Off by default, which section 9.4 argues
1726    /// for: this is the row most likely to fire on code that is doing what its author meant.
1727    pub subobject: Subobject,
1728    /// Whether the `restrict` contract is checked, from `-fsafety-restrict`.
1729    ///
1730    /// Means nothing unless `safety` asked for a tier. Off by default, which section 9.6 argues
1731    /// for: the cost lands entirely inside the loops `restrict` is written for.
1732    pub promise: Promise,
1733    /// Whether pointer races are watched, from `-fsafety-races=`.
1734    ///
1735    /// Means nothing unless `safety` asked for a tier. Off by default, and [`Races`] says why that
1736    /// one is not a cost argument like the others.
1737    pub races: Races,
1738    /// What to produce.
1739    pub emit: EmitKind,
1740    /// Whether to emit debug information.
1741    pub debug_info: bool,
1742    /// The directory the compiler ran in, which is what `DW_AT_comp_dir` says.
1743    ///
1744    /// A debugger joins it onto every file name in the line table that is relative, and the names
1745    /// in there are the ones the command line gave, so a build invoked as `rucc -g a/b.c` produces
1746    /// nothing a debugger can open without it. It is asked of the process by the driver rather than
1747    /// read here, so that a caller that is not a command line gets to say what it was and so that a
1748    /// test does not depend on where it was run from. [`None`] when the process could not say, which
1749    /// is written out as a single dot.
1750    pub working_dir: Option<String>,
1751    /// How the debug sections are compressed, from `-gz`.
1752    ///
1753    /// Nothing reads this yet, because nothing compresses a debug section yet. There are sections
1754    /// to compress now, so what this is waiting on is the compressor rather than the producer.
1755    pub compress: Compress,
1756    /// What the `-flto` family asked for, which nothing does yet.
1757    pub lto: Lto,
1758    /// What the profile reading half of the `-fprofile` family asked for, which nothing reads yet.
1759    ///
1760    /// Named for the data rather than for the flag, because `profile` next door is already the
1761    /// answer to whether `-pg` asked for a call to a profiler on the way into every function, and
1762    /// the two are different questions about the same word.
1763    pub profile_data: Profile,
1764    /// Whether every function keeps a frame pointer, from `-fno-omit-frame-pointer`.
1765    ///
1766    /// Off by default, which is what gcc does at every level above `-O0` and what leaves the
1767    /// register free for the allocator. A profiler that walks the stack by following saved frame
1768    /// pointers needs it on, and so does any code a debugger has to unwind without unwind tables.
1769    pub frame_pointer: bool,
1770    /// Whether the red zone may be used, from `-mno-red-zone` turned around.
1771    ///
1772    /// The 128 bytes below the stack pointer that the System V psABI promises no signal handler
1773    /// will touch, which lets a small leaf function keep its locals without moving the stack
1774    /// pointer at all. A kernel turns this off, because an interrupt taken on the kernel stack
1775    /// makes the promise false, and every kernel build in the wild passes `-mno-red-zone` for
1776    /// exactly that reason. A convention without a red zone ignores this.
1777    pub red_zone: bool,
1778    /// Whether the blocks of a function are put in the order their weights say rather than in the
1779    /// order the shape of the graph gives, from `-freorder-blocks` and `-fno-reorder-blocks`.
1780    ///
1781    /// `None` is a command line that said neither, which is nearly every one, and then the level
1782    /// decides: on above `-O0`, which is where gcc turns it on. It is a three way answer rather
1783    /// than a `bool` because `-O2 -fno-reorder-blocks` and `-O0` have to be different things and
1784    /// a `bool` set from the level could not tell them apart.
1785    pub reorder_blocks: Option<bool>,
1786    /// Whether the instructions of a block are put in the order the machine finishes soonest, from
1787    /// `-fschedule-insns2` and `-fno-schedule-insns2`.
1788    ///
1789    /// `None` is a command line that said neither, and then the level decides: on from `-O2`,
1790    /// which is where gcc turns it on. Three way rather than a `bool` for the reason
1791    /// `reorder_blocks` above is.
1792    ///
1793    /// gcc's name, and gcc's `2` in it, which is the one that runs after the registers are handed
1794    /// out. `-fschedule-insns` without it is the pass before allocation, which rucc does not have:
1795    /// `spec/optimizer/38-scheduling-and-layout.md` section 38.6 decides on one scheduler and puts
1796    /// it after allocation, and section 38.8 owes the measurement that would justify a second.
1797    pub schedule_insns: Option<bool>,
1798    /// Whether the target's timing model is believed about the machine's units as well as about
1799    /// its latencies, from `-Zcycle-accurate-model=`.
1800    ///
1801    /// `None` is a command line that said neither, and then the model's own answer decides. gcc
1802    /// spells this `--param=cycle-accurate-model=`, `Init(1)`, and describes it as whether the
1803    /// scheduling description "is mostly a cycle-accurate model of the target processor". No model
1804    /// in this compiler is, every one of them says so, and this is how a person measuring the cost
1805    /// of that can compile the same program both ways.
1806    pub cycle_accurate_model: Option<bool>,
1807    /// Whether two things in a frame that are never both wanted may be the same bytes, from
1808    /// `-fstack-reuse=`.
1809    ///
1810    /// `None` is a command line that did not write the flag, and then the level decides: on above
1811    /// `-O0`, off at it, so that a person stepping through unoptimized code sees every local in a
1812    /// place of its own. Three way rather than a `bool` for the reason `reorder_blocks` above is,
1813    /// which is that `-O2 -fstack-reuse=none` and `-O0` have to be different things.
1814    ///
1815    /// gcc's flag takes `all`, `named_vars` or `none`. The first two are the same answer here: what
1816    /// rucc shares is a local whose address provably stays inside the function, which is narrower
1817    /// than either of gcc's and is contained in both.
1818    pub stack_reuse: Option<bool>,
1819    /// Which functions get a stack protector, from the `-fstack-protector` family.
1820    pub protector: Protector,
1821    /// Whether a prologue takes its frame a page at a time, from `-fstack-clash-protection`.
1822    ///
1823    /// An operating system leaves one page unmapped below every stack so that a stack growing
1824    /// into it faults. A function whose frame is larger than that page moves the stack pointer
1825    /// clean over it in one subtraction and can then write below it, into whatever the program
1826    /// mapped next, which is a way of reaching one allocation from another that costs an attacker
1827    /// nothing but a large local array. A prologue that takes the frame a page at a time and
1828    /// writes to each page as it arrives faults on the first one that is not there.
1829    ///
1830    /// Off by default, which is gcc's default. Distributions that build with it build everything
1831    /// with it, because the hole is in whichever function was left out.
1832    pub stack_clash: bool,
1833    /// Which control flow transfers are checked, from `-fcf-protection=`.
1834    ///
1835    /// See [`Control`]. Off by default, which is gcc's default on these targets, and on again in
1836    /// every distribution's global flags for the same reason the stack protector is.
1837    pub control: Control,
1838    /// Whether every function calls a profiler's hook on the way in, from `-pg` and `-p`.
1839    ///
1840    /// A profiler wants a count of which function called which, and the moment a function is
1841    /// entered is the only place a compiler can hand it one. It changes the link as well as the
1842    /// code, since the counts have to be started before `main` and written out after it, and the
1843    /// start file that does that is a different one.
1844    ///
1845    /// A tracer wants the same call for a different reason. The hook is one instruction the kernel
1846    /// can overwrite while the program runs, which is what makes a function traceable without
1847    /// rebuilding it, and it is why Linux is built this way rather than to be profiled.
1848    pub profile: bool,
1849    /// Where that call goes, from `-mfentry` and `-mno-fentry`.
1850    ///
1851    /// See [`Hook`]. Read even on a command line that did not ask for the call, since gcc accepts
1852    /// the flag on its own and does nothing with it.
1853    pub hook: Hook,
1854    /// How much room every function opens with for somebody to write over later, from
1855    /// `-fpatchable-function-entry=`.
1856    ///
1857    /// See [`Patchable`]. A kernel asks for this so that a function can be traced without being
1858    /// rebuilt: the room is a known number of bytes at a known address, and the addresses are
1859    /// collected into a section of their own so that whatever does the patching can find every one
1860    /// of them without reading the symbol table.
1861    pub patchable: Patchable,
1862    /// What happens rather than nothing being defined when arithmetic overflows, from `-fwrapv`,
1863    /// `-fwrapv-pointer`, `-fno-strict-overflow` and `-ftrapv`.
1864    ///
1865    /// See [`Wrapping`]. Nothing wraps and nothing stops by default, which is what C says and what
1866    /// lets the optimizer read a loop counter as a number rather than as a number that may turn
1867    /// round.
1868    pub wrapping: Wrapping,
1869    /// What a plain `char` is, from `-fsigned-char` and `-funsigned-char`, with nothing meaning
1870    /// the answer the target's ABI gives.
1871    ///
1872    /// Plain `char` is a third type either way, distinct from both `signed char` and
1873    /// `unsigned char` in every place a type is compared, and this says which of the two it has
1874    /// the range of. Changing it changes the ABI, so it is a decision about the whole program
1875    /// rather than about one file, and `__CHAR_UNSIGNED__` is defined when the answer is unsigned
1876    /// so that a header can see what was decided.
1877    pub char_signed: Option<bool>,
1878    /// Whether an enumeration nothing wrote an underlying type for is represented in the smallest
1879    /// integer type that holds its enumerators, from `-fshort-enums`.
1880    ///
1881    /// The default is `int` or wider, which is what C says and what every psABI in the table
1882    /// expects. This makes it `char` or wider instead, so `enum { A }` is one byte, and that
1883    /// changes the size and the alignment of anything holding one. It is here because a great deal
1884    /// of embedded C and every ARM EABI object is built with it, and mixing the two answers in one
1885    /// program is a silent disagreement about layout rather than a link error.
1886    pub short_enums: bool,
1887    /// Whether Microsoft's reading of an anonymous member is taken, from `-fms-extensions` and
1888    /// `-fno-ms-extensions`, with the target deciding when neither was written.
1889    ///
1890    /// C takes a `struct` or a `union` member with neither a tag nor a name as anonymous, and
1891    /// Microsoft's rule takes one written with a tag or named through a typedef as well. The
1892    /// default is on for a Windows target and off everywhere else, which is what gcc does: its
1893    /// mingw build has the flag on without being asked and its Linux build has it off. The
1894    /// Windows headers need it, because `<objidl.h>` and the rest close a nameless union with
1895    /// `} DUMMYUNIONNAME;` and the macro expands to nothing.
1896    pub ms_extensions: Option<bool>,
1897    /// Whether an access names the type it goes through, from `-fstrict-aliasing` and
1898    /// `-fno-strict-aliasing`.
1899    ///
1900    /// On, which is gcc's answer at every level above `-O0` and is what C 6.5 paragraph 7 already
1901    /// says. Clearing it makes the front end leave the type off every load and every store, and an
1902    /// access with no type on it is one the alias analysis has no type based reason to separate
1903    /// from any other, which is what the flag asks for.
1904    pub strict_aliasing: bool,
1905    /// How far a multiply and an addition may be fused into one rounding, from `-ffp-contract=`.
1906    ///
1907    /// See [`Contract`]. Most of the floating point flags have nowhere to be kept, because they
1908    /// withdraw licences that nothing here takes in the first place: no arithmetic in a function
1909    /// body is folded at any level, so a flag saying the rounding mode may have changed describes
1910    /// what already happens. This one and [`Options::trapping_math`] are the two that have
1911    /// somewhere to go.
1912    pub fp_contract: Contract,
1913    /// Whether an operation may raise an exception the program then looks at, from
1914    /// `-ftrapping-math` and `-fno-trapping-math`.
1915    ///
1916    /// On, which is gcc's default. What clearing it licenses here is one thing: the conversion of
1917    /// a constant floating value to an integer type it does not fit in. Left to the hardware that
1918    /// conversion is one instruction and the answer is the integer indefinite value, which is what
1919    /// both compilers give by default. gcc folds it under this flag instead, to the nearest end of
1920    /// the integer's range, and the difference is visible because the conversion is undefined
1921    /// behaviour rather than a value, so neither answer is wrong and the one a program was written
1922    /// against is gcc's.
1923    pub trapping_math: bool,
1924    /// What a path is rewritten by before it is written into the output, from the
1925    /// `-f*-prefix-map=` family.
1926    ///
1927    /// See [`PrefixMaps`]. This is what makes a build reproducible from a different directory, and
1928    /// it is three lists rather than one because gcc has three flags and a build uses them apart.
1929    pub prefix_map: PrefixMaps,
1930    /// Whether warnings are errors.
1931    pub warnings_are_errors: bool,
1932    /// Whether a warning is raised at all, which is `-w` turned around.
1933    ///
1934    /// A build that passes this has decided it does not want to hear about anything that is not
1935    /// fatal, and the flag is dropped at the one place every diagnostic goes through rather than
1936    /// tested at each site that raises one. `-w` beats `-Werror` where both are given, because a
1937    /// warning that was never raised cannot be promoted.
1938    pub warnings: bool,
1939    /// Whether a warning about something in a header that came with the machine is printed, which
1940    /// is `-Wsystem-headers` and is off the way gcc has it off.
1941    ///
1942    /// The person compiling did not write the file and cannot change it, so a warning about it is
1943    /// noise, and under `-Werror` it is a build that stops on a line nobody in the project typed.
1944    /// It is worth having the flag rather than nothing at all, because somebody porting a header
1945    /// or reading what a new compiler thinks of one does want to hear all of it.
1946    pub system_header_warnings: bool,
1947    /// How many diagnostics to print before giving up. Past a certain point the output is
1948    /// noise from a single earlier mistake, and GCC's default of no limit is not a kindness.
1949    pub error_limit: u32,
1950    /// The dialect, from `-std=`.
1951    pub std: Std,
1952    /// Whether the GNU extensions are on, which is `-std=gnu23` rather than `-std=c23`.
1953    pub gnu_extensions: bool,
1954    /// Whether `-pedantic` was given, which is what turns a use of an extension from silence
1955    /// into a diagnostic. It is not the same knob as the dialect: `-std=c17 -pedantic` warns
1956    /// about a construct that `-std=c17` alone accepts without a word.
1957    pub pedantic: bool,
1958    /// Whether `-fpermissive` was given, which turns the rules gcc 14 promoted from errors back
1959    /// into warnings.
1960    ///
1961    /// Six of them, all about code written before the language settled: a declaration with no
1962    /// type in it, a call to a function nothing declared, a parameter in an old style definition
1963    /// with no type, a pointer made from an integer, a pointer assigned from a pointer to
1964    /// something else, and a `return` whose value disagrees with what was promised. The flag says
1965    /// nothing about any other diagnostic, and it does not say to compile something different: a
1966    /// program it accepts is compiled the way the rule it broke says it means.
1967    pub permissive: bool,
1968    /// Whether the whole unit is under GNU's reading of `inline` rather than C's, which is
1969    /// `-fgnu89-inline`.
1970    ///
1971    /// Under C's reading a definition every file-scope declaration wrote `inline` for and none
1972    /// wrote `extern` for emits nothing, and under GNU's it is the definition alone that decides
1973    /// and `extern inline` is the one that emits nothing. The C89 dialects are under GNU's
1974    /// whatever this says, since that is where the older reading came from, so this is the flag a
1975    /// program written against it reaches for when it is being compiled under a later dialect.
1976    pub gnu89_inline: bool,
1977    /// What a name that nothing in the source said anything about reaches, from `-fvisibility=`.
1978    pub visibility: Visibility,
1979    /// What every function is aligned to unless it asked for more itself, from
1980    /// `-falign-functions` and `-fno-align-functions`.
1981    ///
1982    /// `None` is the target's own answer, which is `rucc_object::FUNC_ALIGN`, and it is what a
1983    /// bare `-falign-functions` asks for as well, since gcc's bare form means the default and the
1984    /// default on this target is the same sixteen bytes. A number is a floor rather than a
1985    /// setting: a function carrying `__attribute__((aligned(N)))` keeps the larger of the two,
1986    /// because the attribute is a statement about that function and this is a preference about
1987    /// the unit.
1988    pub align_functions: Option<u32>,
1989    /// Whether the object may end up in a shared library, from `-fPIC` and `-fPIE`.
1990    pub pic: Pic,
1991    /// Whether a definition in this unit may be replaced at load time by one in another object,
1992    /// from `-fsemantic-interposition` and `-fno-semantic-interposition`.
1993    ///
1994    /// True is the honest answer and is gcc's default, because that is what an exported name in a
1995    /// shared library means: the dynamic linker takes the first definition it finds in load order,
1996    /// so a function this unit defines and calls may not be the one that runs. Everything the
1997    /// optimizer reads off a body has to stop at a name like that.
1998    ///
1999    /// False is a promise the build makes, and every distribution makes it, because otherwise a
2000    /// library cannot inline its own functions into each other. It is a promise rather than a
2001    /// deduction: nothing checks it, and a program that then interposes one of those names gets a
2002    /// mixture of the two definitions. It says nothing about `-fPIE`, where no name is replaceable
2003    /// to begin with, and it says nothing about how an address is reached, which is the separate
2004    /// question `-fPIC` decides.
2005    pub interposition: bool,
2006    /// Whether a function is described to an unwinder at every instruction, from
2007    /// `-fasynchronous-unwind-tables` and `-fno-asynchronous-unwind-tables`.
2008    ///
2009    /// True is the default, which is gcc's wherever anything reads the table, and the reason is
2010    /// that the programs that read it are not the ones being compiled. C++ exceptions,
2011    /// `backtrace`, a profiler sampling a stack and a crash handler printing one all walk frames
2012    /// belonging to code that knew nothing about them, so a unit that opts out stops a walk that
2013    /// started somewhere else.
2014    ///
2015    /// What `asynchronous` asks for on top of a table is that the answer is right at every
2016    /// instruction and not only where a call is, because a signal can arrive anywhere, including
2017    /// the middle of a prologue. Rows come off the prologue as it is built here, so that is the
2018    /// only kind of table there is to write and the weaker request below is answered with it.
2019    ///
2020    /// False is for a build that knows nothing will ever walk it, which in practice is a kernel or
2021    /// a freestanding image, and what it saves is the section rather than any instruction.
2022    pub async_unwind_tables: bool,
2023    /// Whether a function is described to an unwinder at all, from `-funwind-tables` and
2024    /// `-fno-unwind-tables`.
2025    ///
2026    /// The weaker of the two requests and off by default, because the one above is on and implies
2027    /// it. A table is written when either of them is standing, which is what [`Self::unwinds`]
2028    /// answers and is how gcc resolves a line that asks for a table and against an asynchronous
2029    /// one.
2030    ///
2031    /// Neither of them is about anything but ELF. Mach-O and COFF have their own arrangements and
2032    /// neither is written yet, so on those targets nothing reads these.
2033    pub unwind_tables: bool,
2034    /// Whether each function gets a section of its own, from `-ffunction-sections`.
2035    ///
2036    /// A linker can leave out a section nothing reaches and cannot leave out half of one, so this
2037    /// is what makes `--gc-sections` able to drop a function this file defines and nothing calls.
2038    /// A kernel and an embedded image are both linked that way and are both a good deal larger
2039    /// without it, and the cost is one section header per function.
2040    pub function_sections: bool,
2041    /// Whether each variable gets a section of its own, from `-fdata-sections`.
2042    ///
2043    /// The same bargain for the data, and a separate flag because gcc has two of them: a build
2044    /// that wants one and not the other is a build that measured something. Splitting the data can
2045    /// cost more than it saves, since two variables a loop reads together are no longer certain to
2046    /// land in the same page.
2047    pub data_sections: bool,
2048    /// The GCC release claimed, from `-fgnuc-version=`.
2049    pub gnuc: GnucVersion,
2050    /// Whether there is a standard library, which is `-ffreestanding` turned around.
2051    pub hosted: bool,
2052    /// Whether a call to a C library function written under its own plain name may be taken to
2053    /// mean that function, which is `-fno-builtin` turned around.
2054    ///
2055    /// The names are reserved, so `llabs` is the library's `llabs` and the compiler is allowed to
2056    /// know what it does. A program that means something else by one of them is the reason the
2057    /// flag exists, and `-ffreestanding` turns it off as well, because a freestanding program has
2058    /// no C library for the name to be the name of. The `__builtin_` spellings are not affected by
2059    /// either, since the prefix is the program saying which function it means.
2060    pub builtins: bool,
2061    /// The names `-fno-builtin-<name>` took away one at a time, without the prefix.
2062    ///
2063    /// A build that means its own `memcpy` and the library's everything else writes this rather
2064    /// than the whole flag, which is what the kernel does for a handful of names.
2065    pub no_builtin: Vec<String>,
2066    /// The glibc release the headers on the search path are, as the minor number alone.
2067    ///
2068    /// `Some` means two things together: this is a glibc target, and step 3 of
2069    /// `spec/cross-compile/08-sysroots.md` section 8.5 resolved to the tree we bundle. Then the
2070    /// compiler defines `__GLIBC_MINOR__`, because one tree serves every version and the version is
2071    /// the part of it the target supplies. `__GLIBC__` is not ours to define either way, since it is
2072    /// in the tree and a real `features.h` defines it too.
2073    ///
2074    /// `None` is every other case, and the cases matter more than the value. A host glibc's
2075    /// `features.h` defines the macro itself, and a tree the user named has a `features.h` of its
2076    /// own, so defining it as well would be two definitions with different values, which is a
2077    /// warning on every compilation of every file. A musl or mingw target has no such macro at all.
2078    pub glibc_minor: Option<u32>,
2079    /// `-D` in command line order. `FOO` means `FOO=1`, as GCC has it.
2080    pub defines: Vec<String>,
2081    /// `-U` in command line order, applied after the defines because `-U` wins.
2082    pub undefines: Vec<String>,
2083    /// Where a header is looked for.
2084    pub search: SearchPath,
2085    /// What `-imacros` and `-include` named, in command line order.
2086    pub preincludes: Vec<Preinclude>,
2087    /// Whether `-E` writes line markers, which `-P` turns off.
2088    pub line_markers: bool,
2089    /// What the `-d` family asks for.
2090    pub dumps: Dumps,
2091    /// What the `-M` family asks for.
2092    pub deps: Deps,
2093    /// Whether the intermediate files are kept, from `-save-temps`.
2094    pub save_temps: SaveTemps,
2095    /// Whether each step says how long it took, from `-time`.
2096    pub time: bool,
2097    /// What `-f<pass>` and `-fno-<pass>` said about an optimizer pass, in the order the command
2098    /// line said it, so that the last mention of a pass is the one that decides.
2099    ///
2100    /// The pipeline the level chose is the starting point and this is what is added to and taken
2101    /// away from it. The names are checked against the pass list while the arguments are parsed,
2102    /// so anything in here is a pass the compiler has.
2103    pub passes: Vec<(String, bool)>,
2104    /// What `-fpass-fuel=<pass>=<n>` limited a pass to, by pass name.
2105    ///
2106    /// A pass with an entry here performs exactly that many transformations and then stops
2107    /// transforming, which is what bisects a miscompilation to one rewrite. See section 9.10 of
2108    /// `spec/09-optimizer.md`.
2109    pub pass_fuel: Vec<(String, u32)>,
2110    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
2111    ///
2112    /// The outer of the two searches in section 4.5 of `spec/optimizer/04-pass-manager.md`.
2113    /// Halving this says which pass holds the bad rewrite, and halving `-fpass-fuel` for that
2114    /// pass says which rewrite it is. Where both are given, a pass is stopped by whichever of
2115    /// the two is tighter.
2116    pub pass_fuel_global: Option<u32>,
2117    /// What `-fdisable-<pass>[=<range>]` and `-fenable-<pass>[=<range>]` said, in the order the
2118    /// command line said it, with `true` for the enabling half.
2119    ///
2120    /// A rule covers the functions it names and nothing else, and the last rule that covers a
2121    /// function is the one that decides for it, so the order has to survive. This is the second
2122    /// half of the bisection interface in section 41.6 of `spec/optimizer/41-correctness.md`:
2123    /// `-fpass-fuel` finds the rewrite and this finds the function. The pass names are checked
2124    /// against the pass list while the arguments are parsed.
2125    pub pass_gates: Vec<(bool, String)>,
2126    /// What `-fdump-ir=` asked to see, as it was written, which is `all`, `before-<pass>` or
2127    /// `after-<pass>`.
2128    pub dump_ir: Vec<String>,
2129    /// What `-fopt-info` asked to hear about, as the keywords were written, with the leading
2130    /// hyphen taken off, so a bare `-fopt-info` is the empty string in here.
2131    ///
2132    /// The keywords are `optimized`, `missed`, `note` and `all`, and two flags add up rather than
2133    /// the second replacing the first. Checked while the arguments are parsed, so anything in
2134    /// here is a spelling the optimizer understands. See section 42.2 of
2135    /// `spec/optimizer/42-measurement.md` for why `missed` is the one that earns the feature.
2136    pub opt_info: Vec<String>,
2137    /// Where `-fopt-info=<file>` sends the remarks, or `None` for standard error.
2138    ///
2139    /// One file for the whole run rather than one per input, the way GCC does it, and the last
2140    /// one on the command line is the one that decides. A harness that wants the remarks kept
2141    /// away from the diagnostics gives a file, which is what the corpus in `tamnd/rucc-corpus`
2142    /// does with GCC so that a rejection can still be matched against the diagnostic stream.
2143    pub opt_info_file: Option<String>,
2144    /// Whether the IR verifier runs after every pass that changed anything.
2145    ///
2146    /// On in a debug build without being asked, since that is where a broken pass should be
2147    /// caught. `-Zverify-each` turns it on in a release build, which is what CI wants.
2148    pub verify_each: bool,
2149    /// Where `-Zrule-coverage=FILE` writes which lowering rules fired, if it was given.
2150    ///
2151    /// A measurement rather than a thing a build asks for, which is why it is spelled with a `-Z`
2152    /// the way an unstable option is everywhere else: it is here for the harness in
2153    /// `tamnd/rucc-compat` to union over a corpus and report, and nothing about the code that comes
2154    /// out changes when it is on. One file per run of the compiler, holding the whole rule set with
2155    /// the rules this run reached marked, whatever the run compiled and however many files it was.
2156    pub rule_coverage: Option<String>,
2157    /// Where `-Zregister-pressure=FILE` writes what the allocator had to put on the stack.
2158    ///
2159    /// A measurement and spelled with a `-Z` for the same reason as the one above: nothing about
2160    /// the code that comes out changes when it is on. One file per run of the compiler, one line
2161    /// per function, holding how many values went to the stack and how many stores and reloads
2162    /// that cost. What reads it is `cargo xtask pressure`, which compiles the benchmarks in
2163    /// `bench/safety` with the monitor off and on and reports the difference, since
2164    /// `spec/safe-memory/13-performance.md` section 13.1 asks for that number and section 5.2.1
2165    /// says why: a capability in flight is four words, and if materializing one spills something
2166    /// else in a hot loop then check elimination cannot save it.
2167    pub register_pressure: Option<String>,
2168    /// Where `-Zlowering=FILE` writes what the pre-selection lowering group did.
2169    ///
2170    /// A measurement and spelled with a `-Z` for the same reason as the two above: nothing about
2171    /// the code that comes out changes when it is on. One file per run of the compiler, one block
2172    /// per function, holding every member of the group in the order it ran and what each of them
2173    /// found and left behind. What it is read for is a function that came out of the back end in a
2174    /// shape somebody did not expect, since the block says which lowering changed it, and what it
2175    /// is read for after that is a construct the selector refused by name, since the block says
2176    /// whether the step that answers for that construct was offered it and walked away.
2177    pub lowering_dump: Option<String>,
2178}
2179
2180impl Options {
2181    /// Default options for `target`.
2182    pub fn new(target: Triple) -> Self {
2183        Self {
2184            target,
2185            opt_level: OptLevel::default(),
2186            safety: Safety::default(),
2187            padding: Padding::default(),
2188            subobject: Subobject::default(),
2189            promise: Promise::default(),
2190            races: Races::default(),
2191            emit: EmitKind::default(),
2192            debug_info: false,
2193            working_dir: None,
2194            compress: Compress::None,
2195            lto: Lto::default(),
2196            profile_data: Profile::default(),
2197            frame_pointer: false,
2198            red_zone: true,
2199            reorder_blocks: None,
2200            schedule_insns: None,
2201            cycle_accurate_model: None,
2202            stack_reuse: None,
2203            protector: Protector::default(),
2204            stack_clash: false,
2205            control: Control::default(),
2206            profile: false,
2207            hook: Hook::default(),
2208            patchable: Patchable::default(),
2209            wrapping: Wrapping::NONE,
2210            char_signed: None,
2211            short_enums: false,
2212            ms_extensions: None,
2213            strict_aliasing: true,
2214            fp_contract: Contract::Off,
2215            trapping_math: true,
2216            prefix_map: PrefixMaps::default(),
2217            warnings_are_errors: false,
2218            warnings: true,
2219            system_header_warnings: false,
2220            error_limit: 20,
2221            std: Std::default(),
2222            gnu_extensions: true,
2223            pedantic: false,
2224            permissive: false,
2225            gnu89_inline: false,
2226            visibility: Visibility::default(),
2227            align_functions: None,
2228            pic: Pic::default(),
2229            interposition: true,
2230            async_unwind_tables: true,
2231            unwind_tables: false,
2232            function_sections: false,
2233            data_sections: false,
2234            gnuc: GnucVersion::default(),
2235            hosted: true,
2236            builtins: true,
2237            no_builtin: Vec::new(),
2238            glibc_minor: None,
2239            defines: Vec::new(),
2240            undefines: Vec::new(),
2241            search: SearchPath::new(),
2242            preincludes: Vec::new(),
2243            line_markers: true,
2244            dumps: Dumps::default(),
2245            deps: Deps::default(),
2246            save_temps: SaveTemps::default(),
2247            time: false,
2248            passes: Vec::new(),
2249            pass_fuel: Vec::new(),
2250            pass_fuel_global: None,
2251            pass_gates: Vec::new(),
2252            dump_ir: Vec::new(),
2253            opt_info: Vec::new(),
2254            opt_info_file: None,
2255            verify_each: cfg!(debug_assertions),
2256            rule_coverage: None,
2257            register_pressure: None,
2258            lowering_dump: None,
2259        }
2260    }
2261
2262    /// Whether a function in this unit is described to an unwinder.
2263    ///
2264    /// Either request is answered with the same table, so what decides is whether either of them
2265    /// is standing. Asked here rather than worked out at the two places that write a table, since
2266    /// those two writing different answers for one function is what `spec/11-asm-objects-debug.md`
2267    /// section 11.1 says must not be possible.
2268    #[must_use]
2269    pub const fn unwinds(&self) -> bool {
2270        self.async_unwind_tables || self.unwind_tables
2271    }
2272}
2273
2274/// One compilation.
2275///
2276/// Holds the options, the string interner and the diagnostics raised so far. Passing a
2277/// `&mut Session` is how a stage reports a problem, and the return value of a stage says
2278/// what it produced, never whether it succeeded: that question is answered by
2279/// [`Session::has_errors`].
2280#[derive(Debug)]
2281pub struct Session {
2282    /// What this compilation was asked to do.
2283    pub opts: Options,
2284    /// Everything known about the target.
2285    pub target: TargetInfo,
2286    /// The one interner for the compilation.
2287    pub interner: Interner,
2288    /// Every file read during the compilation, and the flat coordinate space their spans
2289    /// live in.
2290    ///
2291    /// This is on the session rather than passed around separately because a span is only
2292    /// meaningful against the map that issued it, and one map per compilation is the rule
2293    /// that makes that true by construction.
2294    pub sources: SourceMap,
2295    diagnostics: Vec<Diagnostic>,
2296    error_count: u32,
2297    warning_count: u32,
2298}
2299
2300impl Session {
2301    /// A session for `opts`.
2302    ///
2303    /// The command line's answer about plain `char` is put into the target here rather than
2304    /// carried beside it, because every place that asks what a `char` is asks the target, and two
2305    /// answers to one question is how a front end ends up disagreeing with its own back end.
2306    pub fn new(opts: Options) -> Self {
2307        let mut target = TargetInfo::new(opts.target);
2308        if let Some(signed) = opts.char_signed {
2309            target.char_is_signed = signed;
2310        }
2311        Self {
2312            opts,
2313            target,
2314            interner: Interner::with_capacity(1024),
2315            sources: SourceMap::new(),
2316            diagnostics: Vec::new(),
2317            error_count: 0,
2318            warning_count: 0,
2319        }
2320    }
2321
2322    /// Whether Microsoft's reading of an anonymous member is taken.
2323    ///
2324    /// The command line answers where it said anything, and the target answers otherwise: gcc's
2325    /// mingw build has the flag on without being asked for it and its Linux build has it off, and
2326    /// a header written for one of the two is read by whichever compiler the platform ships.
2327    #[must_use]
2328    pub fn ms_extensions(&self) -> bool {
2329        self.opts.ms_extensions.unwrap_or(self.opts.target.os == Os::Windows)
2330    }
2331
2332    /// Records a diagnostic.
2333    ///
2334    /// Under `-Werror` a warning is promoted here, once, rather than at every site that
2335    /// raises one, and under `-w` it is dropped here for the same reason. A warning that `-w`
2336    /// dropped is not counted, so `-w -Werror` compiles rather than failing on a warning
2337    /// nobody was going to see. A warning about a line in a header that came with the machine is
2338    /// dropped here too, which is what `-Wsystem-headers` turns off, and dropping it before the
2339    /// promotion is what keeps `-Werror` from stopping a build on somebody else's header.
2340    pub fn emit(&mut self, mut diag: Diagnostic) {
2341        if rucc_diag::dropped(
2342            &diag,
2343            &self.sources,
2344            self.opts.warnings,
2345            self.opts.system_header_warnings,
2346        ) {
2347            return;
2348        }
2349        if self.opts.warnings_are_errors && diag.severity == Severity::Warning {
2350            diag.severity = Severity::Error;
2351        }
2352        match diag.severity {
2353            Severity::Error | Severity::Ice => self.error_count += 1,
2354            Severity::Warning => self.warning_count += 1,
2355            Severity::Note | Severity::Help => {}
2356        }
2357        self.diagnostics.push(diag);
2358    }
2359
2360    /// Everything raised so far, in the order it was raised.
2361    pub fn diagnostics(&self) -> &[Diagnostic] {
2362        &self.diagnostics
2363    }
2364
2365    /// Whether anything fatal has been raised.
2366    pub fn has_errors(&self) -> bool {
2367        self.error_count > 0
2368    }
2369
2370    /// How many errors have been raised.
2371    pub fn error_count(&self) -> u32 {
2372        self.error_count
2373    }
2374
2375    /// How many warnings have been raised.
2376    pub fn warning_count(&self) -> u32 {
2377        self.warning_count
2378    }
2379
2380    /// Whether the error limit has been reached and the caller should stop.
2381    pub fn error_limit_reached(&self) -> bool {
2382        self.opts.error_limit != 0 && self.error_count >= self.opts.error_limit
2383    }
2384}
2385
2386#[cfg(test)]
2387mod tests {
2388    use super::*;
2389
2390    fn session() -> Session {
2391        Session::new(Options::new("x86_64-unknown-linux-gnu".parse().unwrap()))
2392    }
2393
2394    #[test]
2395    fn a_version_claim_reads_the_way_gcc_prints_one() {
2396        // `gcc -dumpfullversion` gives all three, `gcc -dumpversion` gives one, and both are
2397        // things a script pastes straight into a flag.
2398        let all = |v: &str| v.parse::<GnucVersion>().unwrap();
2399        assert_eq!(all("15.1.0"), GnucVersion { major: 15, minor: 1, patch: 0 });
2400        assert_eq!(all("15"), GnucVersion { major: 15, minor: 0, patch: 0 });
2401        assert_eq!(all("4.2"), GnucVersion { major: 4, minor: 2, patch: 0 });
2402        assert!("".parse::<GnucVersion>().is_err());
2403        assert!("15.".parse::<GnucVersion>().is_err(), "a trailing dot is a typo, not a zero");
2404        assert!("1.2.3.4".parse::<GnucVersion>().is_err());
2405    }
2406
2407    #[test]
2408    fn a_prefix_map_rewrites_the_front_of_a_path_and_nothing_else() {
2409        let map = |pairs: &[(&str, &str)]| {
2410            let mut map = PrefixMap::new();
2411            for &(old, new) in pairs {
2412                map.push(old, new);
2413            }
2414            map
2415        };
2416        assert!(PrefixMap::new().is_empty());
2417        assert_eq!(PrefixMap::new().apply("sub/h.h"), "sub/h.h");
2418
2419        let one = map(&[("sub", "SUB")]);
2420        assert_eq!(one.apply("sub/h.h"), "SUB/h.h");
2421        assert_eq!(one.apply("a.c"), "a.c", "a path the mapping does not start");
2422        assert_eq!(one.apply("x/sub/h.h"), "x/sub/h.h", "the middle of a path is not the front");
2423
2424        // Characters rather than directories, which is what gcc compares and is worth a test of
2425        // its own because it is the part that looks like it ought to be otherwise.
2426        assert_eq!(map(&[("s", "B")]).apply("sub/h.h"), "Bub/h.h");
2427        assert_eq!(map(&[("sub/", "SUB/")]).apply("sub/h.h"), "SUB/h.h");
2428        assert_eq!(map(&[("sub", "")]).apply("sub/h.h"), "/h.h", "mapping to nothing");
2429        assert_eq!(map(&[("", "PRE")]).apply("a.c"), "PREa.c", "an empty old is in front of all");
2430
2431        // The last one that matches wins, whether or not the two ask about the same prefix, which
2432        // is what a project wide mapping plus a narrower one for a directory relies on.
2433        assert_eq!(map(&[("sub", "ONE"), ("sub", "TWO")]).apply("sub/h.h"), "TWO/h.h");
2434        assert_eq!(map(&[("sub", "A"), ("s", "B")]).apply("sub/h.h"), "Bub/h.h");
2435        assert_eq!(map(&[("s", "B"), ("sub", "A")]).apply("sub/h.h"), "A/h.h");
2436        assert_eq!(map(&[("nope", "X"), ("sub", "A")]).apply("sub/h.h"), "A/h.h");
2437    }
2438
2439    #[test]
2440    fn the_argument_is_split_at_the_last_equals_sign() {
2441        assert_eq!(PrefixMap::split("old=new"), Some(("old", "new")));
2442        assert_eq!(PrefixMap::split("=new"), Some(("", "new")), "an empty old is allowed");
2443        assert_eq!(PrefixMap::split("old="), Some(("old", "")), "and so is an empty new");
2444        // The last rather than the first, so a directory whose name has an `=` in it can be
2445        // mapped and a replacement whose name has one cannot. That is gcc's choice of which of
2446        // the two to make possible, and it is the right way round.
2447        assert_eq!(PrefixMap::split("/home/a=b=/src"), Some(("/home/a=b", "/src")));
2448        assert_eq!(PrefixMap::split("nope"), None);
2449    }
2450
2451    #[test]
2452    fn optimisation_levels_parse_the_way_gcc_spells_them() {
2453        assert_eq!("".parse::<OptLevel>().unwrap(), OptLevel::O1);
2454        assert_eq!("0".parse::<OptLevel>().unwrap(), OptLevel::O0);
2455        assert_eq!("2".parse::<OptLevel>().unwrap(), OptLevel::O2);
2456        assert_eq!("9".parse::<OptLevel>().unwrap(), OptLevel::O3);
2457        assert_eq!("s".parse::<OptLevel>().unwrap(), OptLevel::Os);
2458        assert!("q".parse::<OptLevel>().is_err());
2459    }
2460
2461    #[test]
2462    fn only_o0_skips_the_optimizer() {
2463        assert!(!OptLevel::O0.runs_optimizer());
2464        assert!(OptLevel::O1.runs_optimizer());
2465        assert!(OptLevel::Oz.runs_optimizer());
2466    }
2467
2468    #[test]
2469    fn the_safety_tiers_round_trip_and_nothing_else_is_one() {
2470        for tier in [Safety::Off, Safety::Detect, Safety::Enforce, Safety::Kernel] {
2471            assert_eq!(tier.as_str().parse::<Safety>().unwrap(), tier);
2472        }
2473        // `on` is the obvious thing to try and it is not a tier, because which tier somebody
2474        // means by it is the whole question document 02 answers.
2475        assert!("on".parse::<Safety>().is_err());
2476        assert!("".parse::<Safety>().is_err());
2477    }
2478
2479    #[test]
2480    fn room_for_a_patcher_is_written_the_way_it_was_asked_for() {
2481        for (written, total, before) in
2482            [("0", 0, 0), ("2", 2, 0), ("16", 16, 0), ("5,3", 5, 3), ("3,3", 3, 3)]
2483        {
2484            let room: Patchable = written.parse().unwrap();
2485            assert_eq!(room, Patchable { total, before });
2486            assert_eq!(room.to_string(), written);
2487            assert_eq!(room.after(), total - before);
2488            assert_eq!(room.any(), total > 0);
2489        }
2490        // A second number of zero is the same request as no second number, and it is written back
2491        // the shorter way, which is the way somebody reaching for the flag writes it.
2492        assert_eq!("2,0".parse::<Patchable>().unwrap().to_string(), "2");
2493    }
2494
2495    #[test]
2496    fn more_room_in_front_of_the_label_than_there_is_room_at_all_is_refused() {
2497        // Rather than clamped, because there is no reading of it a caller meant. gcc says the same
2498        // about each of these.
2499        assert!("1,2".parse::<Patchable>().is_err());
2500        assert!("1,2,3".parse::<Patchable>().is_err());
2501        assert!("a".parse::<Patchable>().is_err());
2502        assert!("".parse::<Patchable>().is_err());
2503        assert!("-1".parse::<Patchable>().is_err());
2504    }
2505
2506    #[test]
2507    fn the_two_places_the_intermediate_files_can_go_are_the_two_words_that_are_taken() {
2508        assert_eq!("obj".parse::<SaveTemps>().unwrap(), SaveTemps::Object);
2509        assert_eq!("cwd".parse::<SaveTemps>().unwrap(), SaveTemps::Cwd);
2510        // The names of the two flags that mean the same thing as `=obj` are not themselves
2511        // arguments of it, and neither is silence.
2512        assert!("obj,cwd".parse::<SaveTemps>().is_err());
2513        assert!("".parse::<SaveTemps>().is_err());
2514        // Nothing is kept unless something asked, and both of the words that ask do ask.
2515        assert_eq!(SaveTemps::default(), SaveTemps::No);
2516        assert!(!SaveTemps::No.wanted());
2517        assert!(SaveTemps::Object.wanted());
2518        assert!(SaveTemps::Cwd.wanted());
2519    }
2520
2521    #[test]
2522    fn a_build_that_did_not_ask_for_the_monitor_does_not_get_it() {
2523        assert_eq!(Safety::default(), Safety::Off);
2524        assert!(!Safety::Off.instruments());
2525        assert!(Safety::Detect.instruments());
2526        assert!(Safety::Enforce.instruments());
2527        assert!(Safety::Kernel.instruments());
2528    }
2529
2530    #[test]
2531    fn emit_kinds_round_trip_through_their_names() {
2532        for k in [
2533            EmitKind::Executable,
2534            EmitKind::Object,
2535            EmitKind::Asm,
2536            EmitKind::Preprocessed,
2537            EmitKind::Tast,
2538            EmitKind::Ir,
2539            EmitKind::MirFinal,
2540        ] {
2541            assert_eq!(k.as_str().parse::<EmitKind>().unwrap(), k);
2542        }
2543    }
2544
2545    #[test]
2546    fn errors_are_counted_and_warnings_are_not() {
2547        let mut s = session();
2548        s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
2549        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
2550        assert_eq!(s.error_count(), 1);
2551        assert_eq!(s.warning_count(), 1);
2552        assert!(s.has_errors());
2553        assert_eq!(s.diagnostics().len(), 2);
2554    }
2555
2556    #[test]
2557    fn werror_promotes_once_at_the_sink() {
2558        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
2559        opts.warnings_are_errors = true;
2560        let mut s = Session::new(opts);
2561        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
2562        assert_eq!(s.error_count(), 1);
2563        assert_eq!(s.warning_count(), 0);
2564        assert_eq!(s.diagnostics()[0].severity, Severity::Error);
2565    }
2566
2567    #[test]
2568    fn the_error_limit_can_be_switched_off() {
2569        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
2570        opts.error_limit = 0;
2571        let mut s = Session::new(opts);
2572        for _ in 0..100 {
2573            s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
2574        }
2575        assert!(!s.error_limit_reached());
2576    }
2577
2578    #[test]
2579    fn the_session_carries_the_source_map_spans_are_resolved_against() {
2580        let mut s = session();
2581        let file = s.sources.add("a.c", b"int x;\n".to_vec()).unwrap();
2582        let start = s.sources.file(file).start;
2583        assert_eq!(s.sources.render_position(start + 4), "a.c:1:5");
2584    }
2585
2586    #[test]
2587    fn the_session_carries_the_resolved_target() {
2588        let s = session();
2589        assert_eq!(s.target.pointer_width, 64);
2590        assert!(s.target.char_is_signed);
2591    }
2592}