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