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.9")]
23
24mod fs;
25pub mod runtime;
26
27pub use crate::fs::{Dir, FileSystem, Found, IncludeForm, MemoryFileSystem, SearchPath, path_key};
28
29use std::fmt;
30use std::str::FromStr;
31
32use rucc_base::Interner;
33use rucc_diag::{Diagnostic, Severity, SourceMap};
34use rucc_target::{TargetInfo, Triple};
35
36/// An optimisation level.
37///
38/// `spec/16-performance.md` section 16.4 gives each level a throughput budget and a code
39/// quality budget, and the levels exist to make that tradeoff explicit rather than to be a
40/// dial. There is no `-O4`, because a level nobody can state the contract for is a level
41/// nobody can test.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
43pub enum OptLevel {
44    /// `-O0`. Compile as fast as possible and keep every variable inspectable.
45    #[default]
46    O0,
47    /// `-O1`. The cheap wins, at roughly the cost of `-O0`.
48    O1,
49    /// `-O2`. The full pipeline. This is the level the code quality claim is about.
50    O2,
51    /// `-O3`. `-O2` plus the transformations that trade size for speed.
52    O3,
53    /// `-Os`. Optimise for size, at roughly `-O2` compile time.
54    Os,
55    /// `-Oz`. Optimise for size, aggressively.
56    Oz,
57}
58
59impl OptLevel {
60    /// The flag that selects this level.
61    pub const fn as_flag(self) -> &'static str {
62        match self {
63            OptLevel::O0 => "-O0",
64            OptLevel::O1 => "-O1",
65            OptLevel::O2 => "-O2",
66            OptLevel::O3 => "-O3",
67            OptLevel::Os => "-Os",
68            OptLevel::Oz => "-Oz",
69        }
70    }
71
72    /// Whether this level optimises for size rather than speed.
73    pub const fn is_size(self) -> bool {
74        matches!(self, OptLevel::Os | OptLevel::Oz)
75    }
76
77    /// Whether the middle end runs at all.
78    pub const fn runs_optimizer(self) -> bool {
79        !matches!(self, OptLevel::O0)
80    }
81}
82
83impl fmt::Display for OptLevel {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str(self.as_flag())
86    }
87}
88
89impl FromStr for OptLevel {
90    type Err = ();
91
92    /// Parses the part after `-O`, so `""` is `-O` which GCC treats as `-O1`.
93    fn from_str(s: &str) -> Result<Self, ()> {
94        Ok(match s {
95            "0" => OptLevel::O0,
96            "" | "1" => OptLevel::O1,
97            "2" => OptLevel::O2,
98            // GCC accepts `-O4` and above and treats them as `-O3`. Build systems in the
99            // wild do pass them, so matching that is cheaper than being right.
100            "3" | "4" | "5" | "6" | "7" | "8" | "9" => OptLevel::O3,
101            "s" => OptLevel::Os,
102            "z" => OptLevel::Oz,
103            _ => return Err(()),
104        })
105    }
106}
107
108/// How much of the memory safety monitor is on, from `-fsafety=`.
109///
110/// Design: `spec/safe-memory/15-integration.md` section 15.4. One flag rather than a plane at a
111/// time, because the tiers of `spec/safe-memory/02-threat-model.md` are the product and the
112/// modifiers are how somebody who has read that document departs from one.
113///
114/// The tiers agree about which accesses are checked and disagree about what happens when a check
115/// says no and about how much of the boundary is covered. That is why they are one value here and
116/// not three booleans: a build asks for a tier, and everything else follows from it.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
118pub enum Safety {
119    /// `-fsafety=off`. No checks and no runtime. The default, and what every existing build gets.
120    #[default]
121    Off,
122    /// `-fsafety=detect`. Tier D: report and carry on, for a test run or a fuzzer.
123    Detect,
124    /// `-fsafety=enforce`. Tier E: report and stop, for a program that faces the network.
125    Enforce,
126    /// `-fsafety=kernel`. Tier K: what a kernel can afford, with the allocator and the libc
127    /// wrappers taken out because a kernel has neither.
128    Kernel,
129}
130
131impl Safety {
132    /// The spelling this tier is asked for by, without the flag in front of it.
133    pub const fn as_str(self) -> &'static str {
134        match self {
135            Safety::Off => "off",
136            Safety::Detect => "detect",
137            Safety::Enforce => "enforce",
138            Safety::Kernel => "kernel",
139        }
140    }
141
142    /// Whether checks are inserted at all.
143    ///
144    /// The three tiers that are not `off` all insert the same checks at this milestone. What
145    /// separates them is the reporter and the boundary, which are milestones S2 and S3 in
146    /// `spec/safe-memory/16-milestones.md`.
147    pub const fn instruments(self) -> bool {
148        !matches!(self, Safety::Off)
149    }
150}
151
152impl fmt::Display for Safety {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.write_str(self.as_str())
155    }
156}
157
158impl FromStr for Safety {
159    type Err = ();
160
161    /// Parses the part after `-fsafety=`.
162    fn from_str(s: &str) -> Result<Self, ()> {
163        Ok(match s {
164            "off" => Safety::Off,
165            "detect" => Safety::Detect,
166            "enforce" => Safety::Enforce,
167            "kernel" => Safety::Kernel,
168            _ => return Err(()),
169        })
170    }
171}
172
173/// How far a name reaches outside a shared library when nothing in the source said.
174///
175/// `-fvisibility=`, which is written on every cmake project that cares about its exports and is
176/// the way a library ships a small documented interface instead of every name it happens to
177/// define. The attribute in the source wins wherever one was written, which is what makes the
178/// flag a default rather than an override and what lets `-fvisibility=hidden` be put on a whole
179/// tree and the dozen exported names marked one at a time.
180///
181/// Three answers to four spellings. `internal` is `hidden` plus a promise about never taking the
182/// address across a component boundary, and nothing here derives anything from that promise, so
183/// what it gets is the same symbol with a weaker claim on it.
184#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
185pub enum Visibility {
186    /// `-fvisibility=default`. Exported and interposable, which is what a name gets when the flag
187    /// is not written at all and what gcc does by default too.
188    #[default]
189    Default,
190    /// `-fvisibility=hidden` and `-fvisibility=internal`. Not in the dynamic symbol table.
191    Hidden,
192    /// `-fvisibility=protected`. In the dynamic symbol table, and a reference from inside the
193    /// library binds to the definition inside it.
194    Protected,
195}
196
197impl Visibility {
198    /// The spelling this is asked for by, without the flag in front of it.
199    ///
200    /// One spelling each, so `internal` is not here: it is a way of asking for `hidden` rather
201    /// than an answer of its own.
202    pub const fn as_str(self) -> &'static str {
203        match self {
204            Visibility::Default => "default",
205            Visibility::Hidden => "hidden",
206            Visibility::Protected => "protected",
207        }
208    }
209}
210
211impl fmt::Display for Visibility {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.write_str(self.as_str())
214    }
215}
216
217impl FromStr for Visibility {
218    type Err = ();
219
220    /// Parses the part after `-fvisibility=`.
221    fn from_str(s: &str) -> Result<Self, ()> {
222        Ok(match s {
223            "default" => Visibility::Default,
224            "hidden" | "internal" => Visibility::Hidden,
225            "protected" => Visibility::Protected,
226            _ => return Err(()),
227        })
228    }
229}
230
231/// Which functions get a stack protector, which is what the `-fstack-protector` family asks.
232///
233/// A canary is a word the prologue copies into the frame above everything a local can be written
234/// through, and the epilogue compares it against the copy the runtime still holds before it
235/// returns. A write that runs off the end of a local and keeps going passes the canary on its way
236/// to the return address, so a function that returns with the word changed calls
237/// `__stack_chk_fail` instead of returning at all.
238///
239/// Which functions are worth the slot and the comparison is what the three levels disagree about,
240/// and the middle one is the one that matters: every distribution has built its packages with
241/// `-fstack-protector-strong` for a decade, so a compiler that cannot take the flag cannot be the
242/// `CC` of a package build whatever else it can do.
243#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
244pub enum Protector {
245    /// `-fno-stack-protector`, and what a command line that says nothing gets. gcc's own default
246    /// is the same, and it is the distributions rather than the compiler that turn it on.
247    #[default]
248    None,
249    /// `-fstack-protector`. A function with a local array of at least eight bytes, or one whose
250    /// stack grows while it runs.
251    Buffers,
252    /// `-fstack-protector-strong`. Any of those, and any function with a local array at all, a
253    /// local holding one, or a local whose address is taken.
254    Strong,
255    /// `-fstack-protector-all`. Every function that has a frame.
256    All,
257}
258
259impl Protector {
260    /// The spelling this is asked for by, which is the whole flag rather than a part of one,
261    /// because these are four flags and not one flag with an argument.
262    pub const fn as_str(self) -> &'static str {
263        match self {
264            Protector::None => "-fno-stack-protector",
265            Protector::Buffers => "-fstack-protector",
266            Protector::Strong => "-fstack-protector-strong",
267            Protector::All => "-fstack-protector-all",
268        }
269    }
270}
271
272impl fmt::Display for Protector {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.write_str(self.as_str())
275    }
276}
277
278/// Which of the two position independent questions the output is answering.
279///
280/// Everything this compiler writes is position independent, so this is not about whether there are
281/// absolute addresses in the text. It is about whether the link that reads the object is one that
282/// puts every name in the same program. An executable is such a link and a shared library is not,
283/// and the difference decides how a name is reached: from the instruction pointer where the
284/// distance is a number the linker has, and out of the global offset table where it is not.
285///
286/// The expensive answer is the one that has to be asked for, which is gcc's arrangement and is why
287/// `-fPIC` is on the compile line of every library and nowhere else. A name is only reached the
288/// expensive way when it is one another object may define or replace, so `-fPIC -fvisibility=hidden`
289/// costs no more than an executable does.
290#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
291pub enum Pic {
292    /// `-fPIE`, `-fpie` and nothing at all. The link puts every name in one program, so a name this
293    /// file defines is at a distance from the instruction asking, and a name it declares ends up at
294    /// one too, because the linker answers a reference to a variable defined in a library by making
295    /// room for it here and copying it. That is what a distribution's default build is.
296    #[default]
297    Executable,
298    /// `-fPIC` and `-fpic`. The output may end up in a shared library, where a name the file
299    /// exports is one something loaded earlier may define too, and where a name defined elsewhere
300    /// is not copied in. Both are reached through the global offset table.
301    Library,
302}
303
304impl Pic {
305    /// The spelling this is asked for by, which is the one gcc's manual leads with.
306    pub const fn as_str(self) -> &'static str {
307        match self {
308            Pic::Executable => "-fPIE",
309            Pic::Library => "-fPIC",
310        }
311    }
312}
313
314impl fmt::Display for Pic {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        f.write_str(self.as_str())
317    }
318}
319
320/// What the compiler should produce.
321///
322/// The intermediate forms are not a debugging convenience bolted on later. Every one of them
323/// is a documented textual form that round-trips, which is what makes the per-stage testing
324/// in `spec/15-testing.md` section 15.2 possible.
325#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
326// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
327// match that needs to change, in this workspace and in anyone else's code. That is
328// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
329// target is a data change: the compiler tells you every place the data is read.
330pub enum EmitKind {
331    /// A linked executable. The default.
332    #[default]
333    Executable,
334    /// An object file, `-c`.
335    Object,
336    /// Assembly text, `-S`.
337    Asm,
338    /// Preprocessed source, `-E`.
339    Preprocessed,
340    /// The typed AST, `--emit=tast`.
341    Tast,
342    /// The IR, `--emit=ir`.
343    Ir,
344    /// The machine IR after register allocation, `--emit=mir-final`.
345    MirFinal,
346    /// The safety summary, `--emit=safety-summary`.
347    ///
348    /// Not an intermediate form of the program the way the three above are. It is the answer to
349    /// "what does this build's guarantee actually rest on", which
350    /// `spec/safe-memory/07-check-elimination.md` section 7.8 asks for and
351    /// `spec/safe-memory/10-boundaries.md` section 10.2 says why.
352    SafetySummary,
353    /// How the bytes of the translation unit's records fall into granules,
354    /// `--emit=type-granules`.
355    ///
356    /// Not an intermediate form either. It is the measurement
357    /// `spec/safe-memory/17-open-questions.md` question 6 asks for, which decides whether the
358    /// type plane fits inside Tier D's memory budget, and it needs nothing past the type
359    /// checker because it is a question about layouts rather than about code.
360    TypeGranules,
361}
362
363impl EmitKind {
364    /// The name used by `--emit=` and by `--print-config`.
365    pub const fn as_str(self) -> &'static str {
366        match self {
367            EmitKind::Executable => "exe",
368            EmitKind::Object => "obj",
369            EmitKind::Asm => "asm",
370            EmitKind::Preprocessed => "preprocessed",
371            EmitKind::Tast => "tast",
372            EmitKind::Ir => "ir",
373            EmitKind::MirFinal => "mir-final",
374            EmitKind::SafetySummary => "safety-summary",
375            EmitKind::TypeGranules => "type-granules",
376        }
377    }
378}
379
380impl FromStr for EmitKind {
381    type Err = ();
382
383    fn from_str(s: &str) -> Result<Self, ()> {
384        Ok(match s {
385            "exe" => EmitKind::Executable,
386            "obj" => EmitKind::Object,
387            "asm" => EmitKind::Asm,
388            "preprocessed" => EmitKind::Preprocessed,
389            "tast" => EmitKind::Tast,
390            "ir" => EmitKind::Ir,
391            "mir-final" => EmitKind::MirFinal,
392            "safety-summary" => EmitKind::SafetySummary,
393            "type-granules" => EmitKind::TypeGranules,
394            _ => return Err(()),
395        })
396    }
397}
398
399/// Which C the source is written in.
400///
401/// The GNU variants are the same language with `__STRICT_ANSI__` left undefined, so the
402/// dialect and the extension question are two fields rather than ten variants.
403#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
404pub enum Std {
405    /// `-std=c89`, and `-ansi`.
406    C89,
407    /// `-std=c99`.
408    C99,
409    /// `-std=c11`.
410    C11,
411    /// `-std=c17`, which is C11 with the defect reports applied.
412    C17,
413    /// `-std=c23`. The default, matching current GCC.
414    #[default]
415    C23,
416}
417
418impl Std {
419    /// What `__STDC_VERSION__` says, which C89 does not define at all.
420    pub const fn stdc_version(self) -> Option<&'static str> {
421        match self {
422            Std::C89 => None,
423            Std::C99 => Some("199901L"),
424            Std::C11 => Some("201112L"),
425            Std::C17 => Some("201710L"),
426            Std::C23 => Some("202311L"),
427        }
428    }
429
430    /// The name in `-std=`.
431    pub const fn as_str(self) -> &'static str {
432        match self {
433            Std::C89 => "c89",
434            Std::C99 => "c99",
435            Std::C11 => "c11",
436            Std::C17 => "c17",
437            Std::C23 => "c23",
438        }
439    }
440
441    /// Whether this dialect has `_Atomic`, `_Thread_local` and the rest of C11.
442    pub const fn has_c11(self) -> bool {
443        matches!(self, Std::C11 | Std::C17 | Std::C23)
444    }
445
446    /// Reads a `-std=` argument, and says whether the GNU extensions came with it.
447    ///
448    /// Every alias GCC takes is here, including the `iso9899` spellings and the year based
449    /// ones, because a build system that passes `-std=iso9899:1999` is passing what its
450    /// author tested against and rejecting it helps nobody. An unknown dialect is `None`
451    /// rather than a guess, since guessing means compiling a different language than the one
452    /// asked for.
453    #[must_use]
454    pub fn from_flag(name: &str) -> Option<(Std, bool)> {
455        let gnu = name.starts_with("gnu");
456        let std = match name {
457            "c89" | "c90" | "gnu89" | "gnu90" | "iso9899:1990" | "iso9899:199409" => Std::C89,
458            "c99" | "c9x" | "gnu99" | "gnu9x" | "iso9899:1999" | "iso9899:199x" => Std::C99,
459            "c11" | "c1x" | "gnu11" | "gnu1x" | "iso9899:2011" => Std::C11,
460            "c17" | "c18" | "gnu17" | "gnu18" | "iso9899:2017" | "iso9899:2018" => Std::C17,
461            "c23" | "c2x" | "gnu23" | "gnu2x" => Std::C23,
462            _ => return None,
463        };
464        Some((std, gnu))
465    }
466}
467
468/// The GCC release the compiler claims to be, as `__GNUC__`, `__GNUC_MINOR__` and
469/// `__GNUC_PATCHLEVEL__`.
470///
471/// Design: `spec/04-driver-and-cli.md` section 4.5, which makes this a knob rather than a
472/// constant and says to start conservative and raise it as the matrix in `rucc-gnu` fills in.
473///
474/// The default is seven, which is the lowest claim that gets a modern glibc. glibc gates most
475/// of what it hands a caller on `__GNUC_PREREQ`, so the claim decides which half of
476/// `sys/cdefs.h` we get, and below seven `bits/floatn-common.h` writes `typedef float _Float32;`
477/// over a keyword this compiler already has. Every header that reaches it stops there, which
478/// was most of them: on Ubuntu 24.04's glibc 2.39 the claim of 4.2.1 that stood here before got
479/// 180 of 214 headers through and seven gets 202, and the amalgamated sqlite goes from four
480/// errors to none.
481///
482/// It is still deliberately low. Claiming a version whose promises have not been kept means
483/// being handed syntax the compiler cannot parse, so this moves when there is a measurement
484/// saying it can. Thirteen and sixteen were measured alongside seven and came out identical on
485/// glibc, on the macOS SDK and on sqlite, so the next move up is cheap; it is a separate one
486/// because nothing yet needs it.
487#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
488pub struct GnucVersion {
489    /// `__GNUC__`.
490    pub major: u32,
491    /// `__GNUC_MINOR__`.
492    pub minor: u32,
493    /// `__GNUC_PATCHLEVEL__`.
494    pub patch: u32,
495}
496
497impl Default for GnucVersion {
498    fn default() -> GnucVersion {
499        GnucVersion { major: 7, minor: 0, patch: 0 }
500    }
501}
502
503impl FromStr for GnucVersion {
504    type Err = String;
505
506    /// Reads `-fgnuc-version=`, which is `15`, `15.1` or `15.1.0`.
507    ///
508    /// The short forms are not a convenience, they are what people write. A missing component
509    /// is zero, the same way GCC treats a release with no patchlevel.
510    fn from_str(text: &str) -> Result<GnucVersion, String> {
511        let mut parts = text.split('.');
512        let mut next = |what: &str| -> Result<u32, String> {
513            match parts.next() {
514                None => Ok(0),
515                Some(field) => {
516                    field.parse().map_err(|_| format!("`{text}` has a {what} that is not a number"))
517                }
518            }
519        };
520        let major = next("major")?;
521        let minor = next("minor")?;
522        let patch = next("patchlevel")?;
523        if parts.next().is_some() {
524            return Err(format!("`{text}` has more than three components"));
525        }
526        Ok(GnucVersion { major, minor, patch })
527    }
528}
529
530/// What the `-d` family asks to be dumped alongside, or instead of, the preprocessed output.
531///
532/// Design: `spec/04-driver-and-cli.md` section 4.4.
533///
534/// GCC spells these as letters packed into one flag, so `-dDI` is two of them, and a letter it
535/// does not know is ignored rather than rejected. That last part is deliberate on GCC's side
536/// and worth copying: the family is a debugging aid and a build that passes `-dumpbase` should
537/// not die on the `-d`.
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
539pub struct Dumps {
540    /// `-dM`. Print the macros that are defined at the end, and nothing else.
541    pub macros: bool,
542}
543
544impl Dumps {
545    /// The letters GCC's preprocessor takes after `-d`.
546    ///
547    /// `M` is the macros, `D` is the macros in place, `N` is their names only, `I` is the
548    /// `#include` lines and `U` is the macros as they are used. Only `M` does anything so far.
549    const LETTERS: &'static str = "MDNIU";
550
551    /// Whether `arg` is a flag from this family rather than something else beginning with
552    /// `-d`.
553    ///
554    /// The check is here rather than in the driver so that the set of letters and the set of
555    /// flags accepted cannot drift apart. It matters because `-dumpversion` also begins with
556    /// `-d`, and a family that swallowed every such flag would turn a flag we have not written
557    /// into a dump of nothing.
558    #[must_use]
559    pub fn is_family(arg: &str) -> bool {
560        match arg.strip_prefix("-d") {
561            Some("") | None => false,
562            Some(letters) => letters.chars().all(|c| Dumps::LETTERS.contains(c)),
563        }
564    }
565
566    /// Reads the letters after `-d`, ignoring the ones we do not implement yet.
567    pub fn add(&mut self, letters: &str) {
568        for letter in letters.chars() {
569            if letter == 'M' {
570                self.macros = true;
571            }
572        }
573    }
574
575    /// Whether anything at all was asked for.
576    #[must_use]
577    pub const fn any(self) -> bool {
578        self.macros
579    }
580}
581
582/// A file `-imacros` or `-include` named, read before the source file.
583///
584/// Design: `spec/04-driver-and-cli.md` section 4.4.
585///
586/// The flag a build reaches for when a whole tree has to see a definition that is not in any of
587/// its files. The kernel builds every object with `-include` of its own configuration header, and
588/// a configure script that has produced a `config.h` gets it into a third party source tree the
589/// same way, without a patch.
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub struct Preinclude {
592    /// The name as it was written, which is looked for the way a quoted include is looked for.
593    pub name: String,
594    /// Whether only the definitions it makes are wanted, which is what `-imacros` asks for.
595    ///
596    /// The text of an `-imacros` file is read and thrown away, so a header full of declarations
597    /// contributes its macros and nothing else. That is what makes it usable on a file that has
598    /// already been included by the source: the definitions arrive early and the declarations do
599    /// not arrive twice.
600    pub macros_only: bool,
601}
602
603/// What the `-M` family asks for, which is a make rule saying what a source file was built from.
604///
605/// Design: `spec/04-driver-and-cli.md` section 4.4.
606///
607/// This is a compiler flag rather than a separate tool because the answer is the set of files the
608/// preprocessor opened, and nothing outside the preprocessor knows what that was. A build system
609/// that generates its own makefiles asks for it on every compilation, which is why section 4.4
610/// calls the family required rather than convenient.
611#[derive(Debug, Clone, PartialEq, Eq)]
612pub struct Deps {
613    /// Whether a rule is produced at all, which is any of `-M`, `-MM`, `-MD` and `-MMD`.
614    pub emit: bool,
615    /// Whether the rule is produced instead of compiling, which is `-M` and `-MM` and not the
616    /// two that end in `D`.
617    ///
618    /// The split is GCC's and it is about who reads the answer. The two that stop after the rule
619    /// write it to standard output for a person, and the two that do not write it to a file
620    /// beside the object for `make` to include on the next run.
621    pub instead_of_compiling: bool,
622    /// Whether a header found in a system directory is listed, which `-MM` and `-MMD` turn off.
623    ///
624    /// A build that lists them is a build that rebuilds the world when the C library is updated,
625    /// which is either what somebody wanted or the reason they reached for the other spelling.
626    ///
627    /// On unless a flag turned it off, and nothing turns it back on. That is GCC's behaviour and
628    /// not an oversight: `-MM -M` leaves the system headers out, because the flag that asks for
629    /// fewer of them is read as the answer to a question the other one never asked.
630    pub system_headers: bool,
631    /// Where the rule is written, from `-MF`, with `-` meaning standard output.
632    ///
633    /// `None` is the default, which is standard output when the rule replaces the compilation and
634    /// the output file with a `.d` suffix when it does not.
635    pub file: Option<String>,
636    /// What the rule's targets are, from `-MT` and `-MQ`, in the order they were given.
637    ///
638    /// Already escaped, because that is the whole of the difference between the two flags: `-MQ`
639    /// escapes what it is given and `-MT` writes it through untouched. Empty means the target is
640    /// worked out from the output file, which is what a build that passes neither expects.
641    pub targets: Vec<String>,
642    /// Whether every prerequisite except the source gets a target of its own with no recipe,
643    /// from `-MP`.
644    ///
645    /// This is what stops `make` failing outright when a header is deleted. Without it the old
646    /// rule names a file that is gone and no rule makes it, and the build stops on a header that
647    /// nothing needs any more.
648    pub phony: bool,
649}
650
651impl Default for Deps {
652    fn default() -> Deps {
653        Deps {
654            emit: false,
655            instead_of_compiling: false,
656            system_headers: true,
657            file: None,
658            targets: Vec::new(),
659            phony: false,
660        }
661    }
662}
663
664/// Whether `-save-temps` was given and where it puts the files it keeps.
665///
666/// Design: `spec/04-driver-and-cli.md` section 4.10.
667///
668/// The flag is how a build gets at the preprocessed source of the file that failed without running
669/// the compiler a second time under different flags, which is the one way to be sure the text being
670/// read is the text that was compiled. A bug report against a compiler is usually a preprocessed
671/// file and nothing else, and this is where that file comes from.
672#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
673pub enum SaveTemps {
674    /// Not asked for, and nothing is kept.
675    #[default]
676    No,
677    /// Beside the file the compilation produced, which is `-save-temps=obj`.
678    ///
679    /// This is what the bare `-save-temps` does as well. GCC's manual says the bare spelling is
680    /// `-save-temps=cwd`, and gcc 16 does not do that: `-save-temps -c a.c -o out/a.o` leaves
681    /// `out/a.i` and `out/a.s` rather than `a.i` and `a.s`. The measurement is what is followed
682    /// here, because a build that reads the manual and a build that reads the compiler both end up
683    /// looking for the files where the compiler put them.
684    Object,
685    /// In the working directory, which is `-save-temps=cwd`.
686    Cwd,
687}
688
689impl SaveTemps {
690    /// Whether anything is kept at all.
691    #[must_use]
692    pub const fn wanted(self) -> bool {
693        !matches!(self, SaveTemps::No)
694    }
695}
696
697impl FromStr for SaveTemps {
698    type Err = String;
699
700    /// Reads what came after the `=`, which is the only part that varies.
701    ///
702    /// # Errors
703    ///
704    /// Returns the offending word. GCC treats an unknown one as fatal rather than ignoring it,
705    /// which is right: a misspelled keyword here means the files a person went looking for are not
706    /// written and nothing said so.
707    fn from_str(s: &str) -> Result<SaveTemps, String> {
708        match s {
709            "obj" => Ok(SaveTemps::Object),
710            "cwd" => Ok(SaveTemps::Cwd),
711            _ => Err(format!("`{s}` is not a -save-temps option; accepted: cwd, obj")),
712        }
713    }
714}
715
716/// Everything a compilation was asked to do.
717///
718/// Options are a plain value with no interior mutability, so a caller can build one, clone
719/// it, tweak one field and run a second compilation, which is exactly what the differential
720/// testing in `spec/15-testing.md` needs.
721#[derive(Debug, Clone, PartialEq, Eq)]
722#[non_exhaustive]
723pub struct Options {
724    /// The target to generate code for.
725    pub target: Triple,
726    /// The optimisation level.
727    pub opt_level: OptLevel,
728    /// How much of the memory safety monitor is on, from `-fsafety=`.
729    ///
730    /// Off unless it was asked for. A program built without the flag is compiled by exactly the
731    /// pipeline it was compiled by before the monitor existed, which is the only way the feature
732    /// can be developed in the open without every build paying for it.
733    pub safety: Safety,
734    /// What to produce.
735    pub emit: EmitKind,
736    /// Whether to emit debug information.
737    pub debug_info: bool,
738    /// Whether every function keeps a frame pointer, from `-fno-omit-frame-pointer`.
739    ///
740    /// Off by default, which is what gcc does at every level above `-O0` and what leaves the
741    /// register free for the allocator. A profiler that walks the stack by following saved frame
742    /// pointers needs it on, and so does any code a debugger has to unwind without unwind tables.
743    pub frame_pointer: bool,
744    /// Whether the red zone may be used, from `-mno-red-zone` turned around.
745    ///
746    /// The 128 bytes below the stack pointer that the System V psABI promises no signal handler
747    /// will touch, which lets a small leaf function keep its locals without moving the stack
748    /// pointer at all. A kernel turns this off, because an interrupt taken on the kernel stack
749    /// makes the promise false, and every kernel build in the wild passes `-mno-red-zone` for
750    /// exactly that reason. A convention without a red zone ignores this.
751    pub red_zone: bool,
752    /// Which functions get a stack protector, from the `-fstack-protector` family.
753    pub protector: Protector,
754    /// Whether warnings are errors.
755    pub warnings_are_errors: bool,
756    /// Whether a warning is raised at all, which is `-w` turned around.
757    ///
758    /// A build that passes this has decided it does not want to hear about anything that is not
759    /// fatal, and the flag is dropped at the one place every diagnostic goes through rather than
760    /// tested at each site that raises one. `-w` beats `-Werror` where both are given, because a
761    /// warning that was never raised cannot be promoted.
762    pub warnings: bool,
763    /// How many diagnostics to print before giving up. Past a certain point the output is
764    /// noise from a single earlier mistake, and GCC's default of no limit is not a kindness.
765    pub error_limit: u32,
766    /// The dialect, from `-std=`.
767    pub std: Std,
768    /// Whether the GNU extensions are on, which is `-std=gnu23` rather than `-std=c23`.
769    pub gnu_extensions: bool,
770    /// Whether `-pedantic` was given, which is what turns a use of an extension from silence
771    /// into a diagnostic. It is not the same knob as the dialect: `-std=c17 -pedantic` warns
772    /// about a construct that `-std=c17` alone accepts without a word.
773    pub pedantic: bool,
774    /// Whether `-fpermissive` was given, which turns the rules gcc 14 promoted from errors back
775    /// into warnings.
776    ///
777    /// Six of them, all about code written before the language settled: a declaration with no
778    /// type in it, a call to a function nothing declared, a parameter in an old style definition
779    /// with no type, a pointer made from an integer, a pointer assigned from a pointer to
780    /// something else, and a `return` whose value disagrees with what was promised. The flag says
781    /// nothing about any other diagnostic, and it does not say to compile something different: a
782    /// program it accepts is compiled the way the rule it broke says it means.
783    pub permissive: bool,
784    /// Whether the whole unit is under GNU's reading of `inline` rather than C's, which is
785    /// `-fgnu89-inline`.
786    ///
787    /// Under C's reading a definition every file-scope declaration wrote `inline` for and none
788    /// wrote `extern` for emits nothing, and under GNU's it is the definition alone that decides
789    /// and `extern inline` is the one that emits nothing. The C89 dialects are under GNU's
790    /// whatever this says, since that is where the older reading came from, so this is the flag a
791    /// program written against it reaches for when it is being compiled under a later dialect.
792    pub gnu89_inline: bool,
793    /// What a name that nothing in the source said anything about reaches, from `-fvisibility=`.
794    pub visibility: Visibility,
795    /// Whether the object may end up in a shared library, from `-fPIC` and `-fPIE`.
796    pub pic: Pic,
797    /// Whether a definition in this unit may be replaced at load time by one in another object,
798    /// from `-fsemantic-interposition` and `-fno-semantic-interposition`.
799    ///
800    /// True is the honest answer and is gcc's default, because that is what an exported name in a
801    /// shared library means: the dynamic linker takes the first definition it finds in load order,
802    /// so a function this unit defines and calls may not be the one that runs. Everything the
803    /// optimizer reads off a body has to stop at a name like that.
804    ///
805    /// False is a promise the build makes, and every distribution makes it, because otherwise a
806    /// library cannot inline its own functions into each other. It is a promise rather than a
807    /// deduction: nothing checks it, and a program that then interposes one of those names gets a
808    /// mixture of the two definitions. It says nothing about `-fPIE`, where no name is replaceable
809    /// to begin with, and it says nothing about how an address is reached, which is the separate
810    /// question `-fPIC` decides.
811    pub interposition: bool,
812    /// Whether a function is described to an unwinder at every instruction, from
813    /// `-fasynchronous-unwind-tables` and `-fno-asynchronous-unwind-tables`.
814    ///
815    /// True is the default, which is gcc's wherever anything reads the table, and the reason is
816    /// that the programs that read it are not the ones being compiled. C++ exceptions,
817    /// `backtrace`, a profiler sampling a stack and a crash handler printing one all walk frames
818    /// belonging to code that knew nothing about them, so a unit that opts out stops a walk that
819    /// started somewhere else.
820    ///
821    /// What `asynchronous` asks for on top of a table is that the answer is right at every
822    /// instruction and not only where a call is, because a signal can arrive anywhere, including
823    /// the middle of a prologue. Rows come off the prologue as it is built here, so that is the
824    /// only kind of table there is to write and the weaker request below is answered with it.
825    ///
826    /// False is for a build that knows nothing will ever walk it, which in practice is a kernel or
827    /// a freestanding image, and what it saves is the section rather than any instruction.
828    pub async_unwind_tables: bool,
829    /// Whether a function is described to an unwinder at all, from `-funwind-tables` and
830    /// `-fno-unwind-tables`.
831    ///
832    /// The weaker of the two requests and off by default, because the one above is on and implies
833    /// it. A table is written when either of them is standing, which is what [`Self::unwinds`]
834    /// answers and is how gcc resolves a line that asks for a table and against an asynchronous
835    /// one.
836    ///
837    /// Neither of them is about anything but ELF. Mach-O and COFF have their own arrangements and
838    /// neither is written yet, so on those targets nothing reads these.
839    pub unwind_tables: bool,
840    /// Whether each function gets a section of its own, from `-ffunction-sections`.
841    ///
842    /// A linker can leave out a section nothing reaches and cannot leave out half of one, so this
843    /// is what makes `--gc-sections` able to drop a function this file defines and nothing calls.
844    /// A kernel and an embedded image are both linked that way and are both a good deal larger
845    /// without it, and the cost is one section header per function.
846    pub function_sections: bool,
847    /// Whether each variable gets a section of its own, from `-fdata-sections`.
848    ///
849    /// The same bargain for the data, and a separate flag because gcc has two of them: a build
850    /// that wants one and not the other is a build that measured something. Splitting the data can
851    /// cost more than it saves, since two variables a loop reads together are no longer certain to
852    /// land in the same page.
853    pub data_sections: bool,
854    /// The GCC release claimed, from `-fgnuc-version=`.
855    pub gnuc: GnucVersion,
856    /// Whether there is a standard library, which is `-ffreestanding` turned around.
857    pub hosted: bool,
858    /// Whether a call to a C library function written under its own plain name may be taken to
859    /// mean that function, which is `-fno-builtin` turned around.
860    ///
861    /// The names are reserved, so `llabs` is the library's `llabs` and the compiler is allowed to
862    /// know what it does. A program that means something else by one of them is the reason the
863    /// flag exists, and `-ffreestanding` turns it off as well, because a freestanding program has
864    /// no C library for the name to be the name of. The `__builtin_` spellings are not affected by
865    /// either, since the prefix is the program saying which function it means.
866    pub builtins: bool,
867    /// The names `-fno-builtin-<name>` took away one at a time, without the prefix.
868    ///
869    /// A build that means its own `memcpy` and the library's everything else writes this rather
870    /// than the whole flag, which is what the kernel does for a handful of names.
871    pub no_builtin: Vec<String>,
872    /// `-D` in command line order. `FOO` means `FOO=1`, as GCC has it.
873    pub defines: Vec<String>,
874    /// `-U` in command line order, applied after the defines because `-U` wins.
875    pub undefines: Vec<String>,
876    /// Where a header is looked for.
877    pub search: SearchPath,
878    /// What `-imacros` and `-include` named, in command line order.
879    pub preincludes: Vec<Preinclude>,
880    /// Whether `-E` writes line markers, which `-P` turns off.
881    pub line_markers: bool,
882    /// What the `-d` family asks for.
883    pub dumps: Dumps,
884    /// What the `-M` family asks for.
885    pub deps: Deps,
886    /// Whether the intermediate files are kept, from `-save-temps`.
887    pub save_temps: SaveTemps,
888    /// Whether each step says how long it took, from `-time`.
889    pub time: bool,
890    /// What `-f<pass>` and `-fno-<pass>` said about an optimizer pass, in the order the command
891    /// line said it, so that the last mention of a pass is the one that decides.
892    ///
893    /// The pipeline the level chose is the starting point and this is what is added to and taken
894    /// away from it. The names are checked against the pass list while the arguments are parsed,
895    /// so anything in here is a pass the compiler has.
896    pub passes: Vec<(String, bool)>,
897    /// What `-fpass-fuel=<pass>=<n>` limited a pass to, by pass name.
898    ///
899    /// A pass with an entry here performs exactly that many transformations and then stops
900    /// transforming, which is what bisects a miscompilation to one rewrite. See section 9.10 of
901    /// `spec/09-optimizer.md`.
902    pub pass_fuel: Vec<(String, u32)>,
903    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
904    ///
905    /// The outer of the two searches in section 4.5 of `spec/optimizer/04-pass-manager.md`.
906    /// Halving this says which pass holds the bad rewrite, and halving `-fpass-fuel` for that
907    /// pass says which rewrite it is. Where both are given, a pass is stopped by whichever of
908    /// the two is tighter.
909    pub pass_fuel_global: Option<u32>,
910    /// What `-fdisable-<pass>[=<range>]` and `-fenable-<pass>[=<range>]` said, in the order the
911    /// command line said it, with `true` for the enabling half.
912    ///
913    /// A rule covers the functions it names and nothing else, and the last rule that covers a
914    /// function is the one that decides for it, so the order has to survive. This is the second
915    /// half of the bisection interface in section 41.6 of `spec/optimizer/41-correctness.md`:
916    /// `-fpass-fuel` finds the rewrite and this finds the function. The pass names are checked
917    /// against the pass list while the arguments are parsed.
918    pub pass_gates: Vec<(bool, String)>,
919    /// What `-fdump-ir=` asked to see, as it was written, which is `all`, `before-<pass>` or
920    /// `after-<pass>`.
921    pub dump_ir: Vec<String>,
922    /// What `-fopt-info` asked to hear about, as the keywords were written, with the leading
923    /// hyphen taken off, so a bare `-fopt-info` is the empty string in here.
924    ///
925    /// The keywords are `optimized`, `missed`, `note` and `all`, and two flags add up rather than
926    /// the second replacing the first. Checked while the arguments are parsed, so anything in
927    /// here is a spelling the optimizer understands. See section 42.2 of
928    /// `spec/optimizer/42-measurement.md` for why `missed` is the one that earns the feature.
929    pub opt_info: Vec<String>,
930    /// Where `-fopt-info=<file>` sends the remarks, or `None` for standard error.
931    ///
932    /// One file for the whole run rather than one per input, the way GCC does it, and the last
933    /// one on the command line is the one that decides. A harness that wants the remarks kept
934    /// away from the diagnostics gives a file, which is what the corpus in `tamnd/rucc-corpus`
935    /// does with GCC so that a rejection can still be matched against the diagnostic stream.
936    pub opt_info_file: Option<String>,
937    /// Whether the IR verifier runs after every pass that changed anything.
938    ///
939    /// On in a debug build without being asked, since that is where a broken pass should be
940    /// caught. `-Zverify-each` turns it on in a release build, which is what CI wants.
941    pub verify_each: bool,
942    /// Where `-Zrule-coverage=FILE` writes which lowering rules fired, if it was given.
943    ///
944    /// A measurement rather than a thing a build asks for, which is why it is spelled with a `-Z`
945    /// the way an unstable option is everywhere else: it is here for the harness in
946    /// `tamnd/rucc-compat` to union over a corpus and report, and nothing about the code that comes
947    /// out changes when it is on. One file per run of the compiler, holding the whole rule set with
948    /// the rules this run reached marked, whatever the run compiled and however many files it was.
949    pub rule_coverage: Option<String>,
950    /// Where `-Zregister-pressure=FILE` writes what the allocator had to put on the stack.
951    ///
952    /// A measurement and spelled with a `-Z` for the same reason as the one above: nothing about
953    /// the code that comes out changes when it is on. One file per run of the compiler, one line
954    /// per function, holding how many values went to the stack and how many stores and reloads
955    /// that cost. What reads it is `cargo xtask pressure`, which compiles the benchmarks in
956    /// `bench/safety` with the monitor off and on and reports the difference, since
957    /// `spec/safe-memory/13-performance.md` section 13.1 asks for that number and section 5.2.1
958    /// says why: a capability in flight is four words, and if materializing one spills something
959    /// else in a hot loop then check elimination cannot save it.
960    pub register_pressure: Option<String>,
961}
962
963impl Options {
964    /// Default options for `target`.
965    pub fn new(target: Triple) -> Self {
966        Self {
967            target,
968            opt_level: OptLevel::default(),
969            safety: Safety::default(),
970            emit: EmitKind::default(),
971            debug_info: false,
972            frame_pointer: false,
973            red_zone: true,
974            protector: Protector::default(),
975            warnings_are_errors: false,
976            warnings: true,
977            error_limit: 20,
978            std: Std::default(),
979            gnu_extensions: true,
980            pedantic: false,
981            permissive: false,
982            gnu89_inline: false,
983            visibility: Visibility::default(),
984            pic: Pic::default(),
985            interposition: true,
986            async_unwind_tables: true,
987            unwind_tables: false,
988            function_sections: false,
989            data_sections: false,
990            gnuc: GnucVersion::default(),
991            hosted: true,
992            builtins: true,
993            no_builtin: Vec::new(),
994            defines: Vec::new(),
995            undefines: Vec::new(),
996            search: SearchPath::new(),
997            preincludes: Vec::new(),
998            line_markers: true,
999            dumps: Dumps::default(),
1000            deps: Deps::default(),
1001            save_temps: SaveTemps::default(),
1002            time: false,
1003            passes: Vec::new(),
1004            pass_fuel: Vec::new(),
1005            pass_fuel_global: None,
1006            pass_gates: Vec::new(),
1007            dump_ir: Vec::new(),
1008            opt_info: Vec::new(),
1009            opt_info_file: None,
1010            verify_each: cfg!(debug_assertions),
1011            rule_coverage: None,
1012            register_pressure: None,
1013        }
1014    }
1015
1016    /// Whether a function in this unit is described to an unwinder.
1017    ///
1018    /// Either request is answered with the same table, so what decides is whether either of them
1019    /// is standing. Asked here rather than worked out at the two places that write a table, since
1020    /// those two writing different answers for one function is what `spec/11-asm-objects-debug.md`
1021    /// section 11.1 says must not be possible.
1022    #[must_use]
1023    pub const fn unwinds(&self) -> bool {
1024        self.async_unwind_tables || self.unwind_tables
1025    }
1026}
1027
1028/// One compilation.
1029///
1030/// Holds the options, the string interner and the diagnostics raised so far. Passing a
1031/// `&mut Session` is how a stage reports a problem, and the return value of a stage says
1032/// what it produced, never whether it succeeded: that question is answered by
1033/// [`Session::has_errors`].
1034#[derive(Debug)]
1035pub struct Session {
1036    /// What this compilation was asked to do.
1037    pub opts: Options,
1038    /// Everything known about the target.
1039    pub target: TargetInfo,
1040    /// The one interner for the compilation.
1041    pub interner: Interner,
1042    /// Every file read during the compilation, and the flat coordinate space their spans
1043    /// live in.
1044    ///
1045    /// This is on the session rather than passed around separately because a span is only
1046    /// meaningful against the map that issued it, and one map per compilation is the rule
1047    /// that makes that true by construction.
1048    pub sources: SourceMap,
1049    diagnostics: Vec<Diagnostic>,
1050    error_count: u32,
1051    warning_count: u32,
1052}
1053
1054impl Session {
1055    /// A session for `opts`.
1056    pub fn new(opts: Options) -> Self {
1057        let target = TargetInfo::new(opts.target);
1058        Self {
1059            opts,
1060            target,
1061            interner: Interner::with_capacity(1024),
1062            sources: SourceMap::new(),
1063            diagnostics: Vec::new(),
1064            error_count: 0,
1065            warning_count: 0,
1066        }
1067    }
1068
1069    /// Records a diagnostic.
1070    ///
1071    /// Under `-Werror` a warning is promoted here, once, rather than at every site that
1072    /// raises one, and under `-w` it is dropped here for the same reason. A warning that `-w`
1073    /// dropped is not counted, so `-w -Werror` compiles rather than failing on a warning
1074    /// nobody was going to see.
1075    pub fn emit(&mut self, mut diag: Diagnostic) {
1076        if !self.opts.warnings && diag.severity == Severity::Warning {
1077            return;
1078        }
1079        if self.opts.warnings_are_errors && diag.severity == Severity::Warning {
1080            diag.severity = Severity::Error;
1081        }
1082        match diag.severity {
1083            Severity::Error | Severity::Ice => self.error_count += 1,
1084            Severity::Warning => self.warning_count += 1,
1085            Severity::Note | Severity::Help => {}
1086        }
1087        self.diagnostics.push(diag);
1088    }
1089
1090    /// Everything raised so far, in the order it was raised.
1091    pub fn diagnostics(&self) -> &[Diagnostic] {
1092        &self.diagnostics
1093    }
1094
1095    /// Whether anything fatal has been raised.
1096    pub fn has_errors(&self) -> bool {
1097        self.error_count > 0
1098    }
1099
1100    /// How many errors have been raised.
1101    pub fn error_count(&self) -> u32 {
1102        self.error_count
1103    }
1104
1105    /// How many warnings have been raised.
1106    pub fn warning_count(&self) -> u32 {
1107        self.warning_count
1108    }
1109
1110    /// Whether the error limit has been reached and the caller should stop.
1111    pub fn error_limit_reached(&self) -> bool {
1112        self.opts.error_limit != 0 && self.error_count >= self.opts.error_limit
1113    }
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118    use super::*;
1119
1120    fn session() -> Session {
1121        Session::new(Options::new("x86_64-unknown-linux-gnu".parse().unwrap()))
1122    }
1123
1124    #[test]
1125    fn a_version_claim_reads_the_way_gcc_prints_one() {
1126        // `gcc -dumpfullversion` gives all three, `gcc -dumpversion` gives one, and both are
1127        // things a script pastes straight into a flag.
1128        let all = |v: &str| v.parse::<GnucVersion>().unwrap();
1129        assert_eq!(all("15.1.0"), GnucVersion { major: 15, minor: 1, patch: 0 });
1130        assert_eq!(all("15"), GnucVersion { major: 15, minor: 0, patch: 0 });
1131        assert_eq!(all("4.2"), GnucVersion { major: 4, minor: 2, patch: 0 });
1132        assert!("".parse::<GnucVersion>().is_err());
1133        assert!("15.".parse::<GnucVersion>().is_err(), "a trailing dot is a typo, not a zero");
1134        assert!("1.2.3.4".parse::<GnucVersion>().is_err());
1135    }
1136
1137    #[test]
1138    fn optimisation_levels_parse_the_way_gcc_spells_them() {
1139        assert_eq!("".parse::<OptLevel>().unwrap(), OptLevel::O1);
1140        assert_eq!("0".parse::<OptLevel>().unwrap(), OptLevel::O0);
1141        assert_eq!("2".parse::<OptLevel>().unwrap(), OptLevel::O2);
1142        assert_eq!("9".parse::<OptLevel>().unwrap(), OptLevel::O3);
1143        assert_eq!("s".parse::<OptLevel>().unwrap(), OptLevel::Os);
1144        assert!("q".parse::<OptLevel>().is_err());
1145    }
1146
1147    #[test]
1148    fn only_o0_skips_the_optimizer() {
1149        assert!(!OptLevel::O0.runs_optimizer());
1150        assert!(OptLevel::O1.runs_optimizer());
1151        assert!(OptLevel::Oz.runs_optimizer());
1152    }
1153
1154    #[test]
1155    fn the_safety_tiers_round_trip_and_nothing_else_is_one() {
1156        for tier in [Safety::Off, Safety::Detect, Safety::Enforce, Safety::Kernel] {
1157            assert_eq!(tier.as_str().parse::<Safety>().unwrap(), tier);
1158        }
1159        // `on` is the obvious thing to try and it is not a tier, because which tier somebody
1160        // means by it is the whole question document 02 answers.
1161        assert!("on".parse::<Safety>().is_err());
1162        assert!("".parse::<Safety>().is_err());
1163    }
1164
1165    #[test]
1166    fn the_two_places_the_intermediate_files_can_go_are_the_two_words_that_are_taken() {
1167        assert_eq!("obj".parse::<SaveTemps>().unwrap(), SaveTemps::Object);
1168        assert_eq!("cwd".parse::<SaveTemps>().unwrap(), SaveTemps::Cwd);
1169        // The names of the two flags that mean the same thing as `=obj` are not themselves
1170        // arguments of it, and neither is silence.
1171        assert!("obj,cwd".parse::<SaveTemps>().is_err());
1172        assert!("".parse::<SaveTemps>().is_err());
1173        // Nothing is kept unless something asked, and both of the words that ask do ask.
1174        assert_eq!(SaveTemps::default(), SaveTemps::No);
1175        assert!(!SaveTemps::No.wanted());
1176        assert!(SaveTemps::Object.wanted());
1177        assert!(SaveTemps::Cwd.wanted());
1178    }
1179
1180    #[test]
1181    fn a_build_that_did_not_ask_for_the_monitor_does_not_get_it() {
1182        assert_eq!(Safety::default(), Safety::Off);
1183        assert!(!Safety::Off.instruments());
1184        assert!(Safety::Detect.instruments());
1185        assert!(Safety::Enforce.instruments());
1186        assert!(Safety::Kernel.instruments());
1187    }
1188
1189    #[test]
1190    fn emit_kinds_round_trip_through_their_names() {
1191        for k in [
1192            EmitKind::Executable,
1193            EmitKind::Object,
1194            EmitKind::Asm,
1195            EmitKind::Preprocessed,
1196            EmitKind::Tast,
1197            EmitKind::Ir,
1198            EmitKind::MirFinal,
1199        ] {
1200            assert_eq!(k.as_str().parse::<EmitKind>().unwrap(), k);
1201        }
1202    }
1203
1204    #[test]
1205    fn errors_are_counted_and_warnings_are_not() {
1206        let mut s = session();
1207        s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
1208        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
1209        assert_eq!(s.error_count(), 1);
1210        assert_eq!(s.warning_count(), 1);
1211        assert!(s.has_errors());
1212        assert_eq!(s.diagnostics().len(), 2);
1213    }
1214
1215    #[test]
1216    fn werror_promotes_once_at_the_sink() {
1217        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1218        opts.warnings_are_errors = true;
1219        let mut s = Session::new(opts);
1220        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
1221        assert_eq!(s.error_count(), 1);
1222        assert_eq!(s.warning_count(), 0);
1223        assert_eq!(s.diagnostics()[0].severity, Severity::Error);
1224    }
1225
1226    #[test]
1227    fn the_error_limit_can_be_switched_off() {
1228        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1229        opts.error_limit = 0;
1230        let mut s = Session::new(opts);
1231        for _ in 0..100 {
1232            s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
1233        }
1234        assert!(!s.error_limit_reached());
1235    }
1236
1237    #[test]
1238    fn the_session_carries_the_source_map_spans_are_resolved_against() {
1239        let mut s = session();
1240        let file = s.sources.add("a.c", b"int x;\n".to_vec()).unwrap();
1241        let start = s.sources.file(file).start;
1242        assert_eq!(s.sources.render_position(start + 4), "a.c:1:5");
1243    }
1244
1245    #[test]
1246    fn the_session_carries_the_resolved_target() {
1247        let s = session();
1248        assert_eq!(s.target.pointer_width, 64);
1249        assert!(s.target.char_is_signed);
1250    }
1251}