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