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