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.3")]
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/// What the compiler should produce.
232///
233/// The intermediate forms are not a debugging convenience bolted on later. Every one of them
234/// is a documented textual form that round-trips, which is what makes the per-stage testing
235/// in `spec/15-testing.md` section 15.2 possible.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
237// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
238// match that needs to change, in this workspace and in anyone else's code. That is
239// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
240// target is a data change: the compiler tells you every place the data is read.
241pub enum EmitKind {
242    /// A linked executable. The default.
243    #[default]
244    Executable,
245    /// An object file, `-c`.
246    Object,
247    /// Assembly text, `-S`.
248    Asm,
249    /// Preprocessed source, `-E`.
250    Preprocessed,
251    /// The typed AST, `--emit=tast`.
252    Tast,
253    /// The IR, `--emit=ir`.
254    Ir,
255    /// The machine IR after register allocation, `--emit=mir-final`.
256    MirFinal,
257    /// The safety summary, `--emit=safety-summary`.
258    ///
259    /// Not an intermediate form of the program the way the three above are. It is the answer to
260    /// "what does this build's guarantee actually rest on", which
261    /// `spec/safe-memory/07-check-elimination.md` section 7.8 asks for and
262    /// `spec/safe-memory/10-boundaries.md` section 10.2 says why.
263    SafetySummary,
264    /// How the bytes of the translation unit's records fall into granules,
265    /// `--emit=type-granules`.
266    ///
267    /// Not an intermediate form either. It is the measurement
268    /// `spec/safe-memory/17-open-questions.md` question 6 asks for, which decides whether the
269    /// type plane fits inside Tier D's memory budget, and it needs nothing past the type
270    /// checker because it is a question about layouts rather than about code.
271    TypeGranules,
272}
273
274impl EmitKind {
275    /// The name used by `--emit=` and by `--print-config`.
276    pub const fn as_str(self) -> &'static str {
277        match self {
278            EmitKind::Executable => "exe",
279            EmitKind::Object => "obj",
280            EmitKind::Asm => "asm",
281            EmitKind::Preprocessed => "preprocessed",
282            EmitKind::Tast => "tast",
283            EmitKind::Ir => "ir",
284            EmitKind::MirFinal => "mir-final",
285            EmitKind::SafetySummary => "safety-summary",
286            EmitKind::TypeGranules => "type-granules",
287        }
288    }
289}
290
291impl FromStr for EmitKind {
292    type Err = ();
293
294    fn from_str(s: &str) -> Result<Self, ()> {
295        Ok(match s {
296            "exe" => EmitKind::Executable,
297            "obj" => EmitKind::Object,
298            "asm" => EmitKind::Asm,
299            "preprocessed" => EmitKind::Preprocessed,
300            "tast" => EmitKind::Tast,
301            "ir" => EmitKind::Ir,
302            "mir-final" => EmitKind::MirFinal,
303            "safety-summary" => EmitKind::SafetySummary,
304            "type-granules" => EmitKind::TypeGranules,
305            _ => return Err(()),
306        })
307    }
308}
309
310/// Which C the source is written in.
311///
312/// The GNU variants are the same language with `__STRICT_ANSI__` left undefined, so the
313/// dialect and the extension question are two fields rather than ten variants.
314#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
315pub enum Std {
316    /// `-std=c89`, and `-ansi`.
317    C89,
318    /// `-std=c99`.
319    C99,
320    /// `-std=c11`.
321    C11,
322    /// `-std=c17`, which is C11 with the defect reports applied.
323    C17,
324    /// `-std=c23`. The default, matching current GCC.
325    #[default]
326    C23,
327}
328
329impl Std {
330    /// What `__STDC_VERSION__` says, which C89 does not define at all.
331    pub const fn stdc_version(self) -> Option<&'static str> {
332        match self {
333            Std::C89 => None,
334            Std::C99 => Some("199901L"),
335            Std::C11 => Some("201112L"),
336            Std::C17 => Some("201710L"),
337            Std::C23 => Some("202311L"),
338        }
339    }
340
341    /// The name in `-std=`.
342    pub const fn as_str(self) -> &'static str {
343        match self {
344            Std::C89 => "c89",
345            Std::C99 => "c99",
346            Std::C11 => "c11",
347            Std::C17 => "c17",
348            Std::C23 => "c23",
349        }
350    }
351
352    /// Whether this dialect has `_Atomic`, `_Thread_local` and the rest of C11.
353    pub const fn has_c11(self) -> bool {
354        matches!(self, Std::C11 | Std::C17 | Std::C23)
355    }
356
357    /// Reads a `-std=` argument, and says whether the GNU extensions came with it.
358    ///
359    /// Every alias GCC takes is here, including the `iso9899` spellings and the year based
360    /// ones, because a build system that passes `-std=iso9899:1999` is passing what its
361    /// author tested against and rejecting it helps nobody. An unknown dialect is `None`
362    /// rather than a guess, since guessing means compiling a different language than the one
363    /// asked for.
364    #[must_use]
365    pub fn from_flag(name: &str) -> Option<(Std, bool)> {
366        let gnu = name.starts_with("gnu");
367        let std = match name {
368            "c89" | "c90" | "gnu89" | "gnu90" | "iso9899:1990" | "iso9899:199409" => Std::C89,
369            "c99" | "c9x" | "gnu99" | "gnu9x" | "iso9899:1999" | "iso9899:199x" => Std::C99,
370            "c11" | "c1x" | "gnu11" | "gnu1x" | "iso9899:2011" => Std::C11,
371            "c17" | "c18" | "gnu17" | "gnu18" | "iso9899:2017" | "iso9899:2018" => Std::C17,
372            "c23" | "c2x" | "gnu23" | "gnu2x" => Std::C23,
373            _ => return None,
374        };
375        Some((std, gnu))
376    }
377}
378
379/// The GCC release the compiler claims to be, as `__GNUC__`, `__GNUC_MINOR__` and
380/// `__GNUC_PATCHLEVEL__`.
381///
382/// Design: `spec/04-driver-and-cli.md` section 4.5, which makes this a knob rather than a
383/// constant and says to start conservative and raise it as the matrix in `rucc-gnu` fills in.
384///
385/// The default is seven, which is the lowest claim that gets a modern glibc. glibc gates most
386/// of what it hands a caller on `__GNUC_PREREQ`, so the claim decides which half of
387/// `sys/cdefs.h` we get, and below seven `bits/floatn-common.h` writes `typedef float _Float32;`
388/// over a keyword this compiler already has. Every header that reaches it stops there, which
389/// was most of them: on Ubuntu 24.04's glibc 2.39 the claim of 4.2.1 that stood here before got
390/// 180 of 214 headers through and seven gets 202, and the amalgamated sqlite goes from four
391/// errors to none.
392///
393/// It is still deliberately low. Claiming a version whose promises have not been kept means
394/// being handed syntax the compiler cannot parse, so this moves when there is a measurement
395/// saying it can. Thirteen and sixteen were measured alongside seven and came out identical on
396/// glibc, on the macOS SDK and on sqlite, so the next move up is cheap; it is a separate one
397/// because nothing yet needs it.
398#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
399pub struct GnucVersion {
400    /// `__GNUC__`.
401    pub major: u32,
402    /// `__GNUC_MINOR__`.
403    pub minor: u32,
404    /// `__GNUC_PATCHLEVEL__`.
405    pub patch: u32,
406}
407
408impl Default for GnucVersion {
409    fn default() -> GnucVersion {
410        GnucVersion { major: 7, minor: 0, patch: 0 }
411    }
412}
413
414impl FromStr for GnucVersion {
415    type Err = String;
416
417    /// Reads `-fgnuc-version=`, which is `15`, `15.1` or `15.1.0`.
418    ///
419    /// The short forms are not a convenience, they are what people write. A missing component
420    /// is zero, the same way GCC treats a release with no patchlevel.
421    fn from_str(text: &str) -> Result<GnucVersion, String> {
422        let mut parts = text.split('.');
423        let mut next = |what: &str| -> Result<u32, String> {
424            match parts.next() {
425                None => Ok(0),
426                Some(field) => {
427                    field.parse().map_err(|_| format!("`{text}` has a {what} that is not a number"))
428                }
429            }
430        };
431        let major = next("major")?;
432        let minor = next("minor")?;
433        let patch = next("patchlevel")?;
434        if parts.next().is_some() {
435            return Err(format!("`{text}` has more than three components"));
436        }
437        Ok(GnucVersion { major, minor, patch })
438    }
439}
440
441/// What the `-d` family asks to be dumped alongside, or instead of, the preprocessed output.
442///
443/// Design: `spec/04-driver-and-cli.md` section 4.4.
444///
445/// GCC spells these as letters packed into one flag, so `-dDI` is two of them, and a letter it
446/// does not know is ignored rather than rejected. That last part is deliberate on GCC's side
447/// and worth copying: the family is a debugging aid and a build that passes `-dumpbase` should
448/// not die on the `-d`.
449#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
450pub struct Dumps {
451    /// `-dM`. Print the macros that are defined at the end, and nothing else.
452    pub macros: bool,
453}
454
455impl Dumps {
456    /// The letters GCC's preprocessor takes after `-d`.
457    ///
458    /// `M` is the macros, `D` is the macros in place, `N` is their names only, `I` is the
459    /// `#include` lines and `U` is the macros as they are used. Only `M` does anything so far.
460    const LETTERS: &'static str = "MDNIU";
461
462    /// Whether `arg` is a flag from this family rather than something else beginning with
463    /// `-d`.
464    ///
465    /// The check is here rather than in the driver so that the set of letters and the set of
466    /// flags accepted cannot drift apart. It matters because `-dumpversion` also begins with
467    /// `-d`, and a family that swallowed every such flag would turn a flag we have not written
468    /// into a dump of nothing.
469    #[must_use]
470    pub fn is_family(arg: &str) -> bool {
471        match arg.strip_prefix("-d") {
472            Some("") | None => false,
473            Some(letters) => letters.chars().all(|c| Dumps::LETTERS.contains(c)),
474        }
475    }
476
477    /// Reads the letters after `-d`, ignoring the ones we do not implement yet.
478    pub fn add(&mut self, letters: &str) {
479        for letter in letters.chars() {
480            if letter == 'M' {
481                self.macros = true;
482            }
483        }
484    }
485
486    /// Whether anything at all was asked for.
487    #[must_use]
488    pub const fn any(self) -> bool {
489        self.macros
490    }
491}
492
493/// A file `-imacros` or `-include` named, read before the source file.
494///
495/// Design: `spec/04-driver-and-cli.md` section 4.4.
496///
497/// The flag a build reaches for when a whole tree has to see a definition that is not in any of
498/// its files. The kernel builds every object with `-include` of its own configuration header, and
499/// a configure script that has produced a `config.h` gets it into a third party source tree the
500/// same way, without a patch.
501#[derive(Debug, Clone, PartialEq, Eq)]
502pub struct Preinclude {
503    /// The name as it was written, which is looked for the way a quoted include is looked for.
504    pub name: String,
505    /// Whether only the definitions it makes are wanted, which is what `-imacros` asks for.
506    ///
507    /// The text of an `-imacros` file is read and thrown away, so a header full of declarations
508    /// contributes its macros and nothing else. That is what makes it usable on a file that has
509    /// already been included by the source: the definitions arrive early and the declarations do
510    /// not arrive twice.
511    pub macros_only: bool,
512}
513
514/// What the `-M` family asks for, which is a make rule saying what a source file was built from.
515///
516/// Design: `spec/04-driver-and-cli.md` section 4.4.
517///
518/// This is a compiler flag rather than a separate tool because the answer is the set of files the
519/// preprocessor opened, and nothing outside the preprocessor knows what that was. A build system
520/// that generates its own makefiles asks for it on every compilation, which is why section 4.4
521/// calls the family required rather than convenient.
522#[derive(Debug, Clone, PartialEq, Eq)]
523pub struct Deps {
524    /// Whether a rule is produced at all, which is any of `-M`, `-MM`, `-MD` and `-MMD`.
525    pub emit: bool,
526    /// Whether the rule is produced instead of compiling, which is `-M` and `-MM` and not the
527    /// two that end in `D`.
528    ///
529    /// The split is GCC's and it is about who reads the answer. The two that stop after the rule
530    /// write it to standard output for a person, and the two that do not write it to a file
531    /// beside the object for `make` to include on the next run.
532    pub instead_of_compiling: bool,
533    /// Whether a header found in a system directory is listed, which `-MM` and `-MMD` turn off.
534    ///
535    /// A build that lists them is a build that rebuilds the world when the C library is updated,
536    /// which is either what somebody wanted or the reason they reached for the other spelling.
537    ///
538    /// On unless a flag turned it off, and nothing turns it back on. That is GCC's behaviour and
539    /// not an oversight: `-MM -M` leaves the system headers out, because the flag that asks for
540    /// fewer of them is read as the answer to a question the other one never asked.
541    pub system_headers: bool,
542    /// Where the rule is written, from `-MF`, with `-` meaning standard output.
543    ///
544    /// `None` is the default, which is standard output when the rule replaces the compilation and
545    /// the output file with a `.d` suffix when it does not.
546    pub file: Option<String>,
547    /// What the rule's targets are, from `-MT` and `-MQ`, in the order they were given.
548    ///
549    /// Already escaped, because that is the whole of the difference between the two flags: `-MQ`
550    /// escapes what it is given and `-MT` writes it through untouched. Empty means the target is
551    /// worked out from the output file, which is what a build that passes neither expects.
552    pub targets: Vec<String>,
553    /// Whether every prerequisite except the source gets a target of its own with no recipe,
554    /// from `-MP`.
555    ///
556    /// This is what stops `make` failing outright when a header is deleted. Without it the old
557    /// rule names a file that is gone and no rule makes it, and the build stops on a header that
558    /// nothing needs any more.
559    pub phony: bool,
560}
561
562impl Default for Deps {
563    fn default() -> Deps {
564        Deps {
565            emit: false,
566            instead_of_compiling: false,
567            system_headers: true,
568            file: None,
569            targets: Vec::new(),
570            phony: false,
571        }
572    }
573}
574
575/// Whether `-save-temps` was given and where it puts the files it keeps.
576///
577/// Design: `spec/04-driver-and-cli.md` section 4.10.
578///
579/// The flag is how a build gets at the preprocessed source of the file that failed without running
580/// the compiler a second time under different flags, which is the one way to be sure the text being
581/// read is the text that was compiled. A bug report against a compiler is usually a preprocessed
582/// file and nothing else, and this is where that file comes from.
583#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
584pub enum SaveTemps {
585    /// Not asked for, and nothing is kept.
586    #[default]
587    No,
588    /// Beside the file the compilation produced, which is `-save-temps=obj`.
589    ///
590    /// This is what the bare `-save-temps` does as well. GCC's manual says the bare spelling is
591    /// `-save-temps=cwd`, and gcc 16 does not do that: `-save-temps -c a.c -o out/a.o` leaves
592    /// `out/a.i` and `out/a.s` rather than `a.i` and `a.s`. The measurement is what is followed
593    /// here, because a build that reads the manual and a build that reads the compiler both end up
594    /// looking for the files where the compiler put them.
595    Object,
596    /// In the working directory, which is `-save-temps=cwd`.
597    Cwd,
598}
599
600impl SaveTemps {
601    /// Whether anything is kept at all.
602    #[must_use]
603    pub const fn wanted(self) -> bool {
604        !matches!(self, SaveTemps::No)
605    }
606}
607
608impl FromStr for SaveTemps {
609    type Err = String;
610
611    /// Reads what came after the `=`, which is the only part that varies.
612    ///
613    /// # Errors
614    ///
615    /// Returns the offending word. GCC treats an unknown one as fatal rather than ignoring it,
616    /// which is right: a misspelled keyword here means the files a person went looking for are not
617    /// written and nothing said so.
618    fn from_str(s: &str) -> Result<SaveTemps, String> {
619        match s {
620            "obj" => Ok(SaveTemps::Object),
621            "cwd" => Ok(SaveTemps::Cwd),
622            _ => Err(format!("`{s}` is not a -save-temps option; accepted: cwd, obj")),
623        }
624    }
625}
626
627/// Everything a compilation was asked to do.
628///
629/// Options are a plain value with no interior mutability, so a caller can build one, clone
630/// it, tweak one field and run a second compilation, which is exactly what the differential
631/// testing in `spec/15-testing.md` needs.
632#[derive(Debug, Clone, PartialEq, Eq)]
633#[non_exhaustive]
634pub struct Options {
635    /// The target to generate code for.
636    pub target: Triple,
637    /// The optimisation level.
638    pub opt_level: OptLevel,
639    /// How much of the memory safety monitor is on, from `-fsafety=`.
640    ///
641    /// Off unless it was asked for. A program built without the flag is compiled by exactly the
642    /// pipeline it was compiled by before the monitor existed, which is the only way the feature
643    /// can be developed in the open without every build paying for it.
644    pub safety: Safety,
645    /// What to produce.
646    pub emit: EmitKind,
647    /// Whether to emit debug information.
648    pub debug_info: bool,
649    /// Whether every function keeps a frame pointer, from `-fno-omit-frame-pointer`.
650    ///
651    /// Off by default, which is what gcc does at every level above `-O0` and what leaves the
652    /// register free for the allocator. A profiler that walks the stack by following saved frame
653    /// pointers needs it on, and so does any code a debugger has to unwind without unwind tables.
654    pub frame_pointer: bool,
655    /// Whether the red zone may be used, from `-mno-red-zone` turned around.
656    ///
657    /// The 128 bytes below the stack pointer that the System V psABI promises no signal handler
658    /// will touch, which lets a small leaf function keep its locals without moving the stack
659    /// pointer at all. A kernel turns this off, because an interrupt taken on the kernel stack
660    /// makes the promise false, and every kernel build in the wild passes `-mno-red-zone` for
661    /// exactly that reason. A convention without a red zone ignores this.
662    pub red_zone: bool,
663    /// Whether warnings are errors.
664    pub warnings_are_errors: bool,
665    /// Whether a warning is raised at all, which is `-w` turned around.
666    ///
667    /// A build that passes this has decided it does not want to hear about anything that is not
668    /// fatal, and the flag is dropped at the one place every diagnostic goes through rather than
669    /// tested at each site that raises one. `-w` beats `-Werror` where both are given, because a
670    /// warning that was never raised cannot be promoted.
671    pub warnings: bool,
672    /// How many diagnostics to print before giving up. Past a certain point the output is
673    /// noise from a single earlier mistake, and GCC's default of no limit is not a kindness.
674    pub error_limit: u32,
675    /// The dialect, from `-std=`.
676    pub std: Std,
677    /// Whether the GNU extensions are on, which is `-std=gnu23` rather than `-std=c23`.
678    pub gnu_extensions: bool,
679    /// Whether `-pedantic` was given, which is what turns a use of an extension from silence
680    /// into a diagnostic. It is not the same knob as the dialect: `-std=c17 -pedantic` warns
681    /// about a construct that `-std=c17` alone accepts without a word.
682    pub pedantic: bool,
683    /// Whether `-fpermissive` was given, which turns the rules gcc 14 promoted from errors back
684    /// into warnings.
685    ///
686    /// Six of them, all about code written before the language settled: a declaration with no
687    /// type in it, a call to a function nothing declared, a parameter in an old style definition
688    /// with no type, a pointer made from an integer, a pointer assigned from a pointer to
689    /// something else, and a `return` whose value disagrees with what was promised. The flag says
690    /// nothing about any other diagnostic, and it does not say to compile something different: a
691    /// program it accepts is compiled the way the rule it broke says it means.
692    pub permissive: bool,
693    /// Whether the whole unit is under GNU's reading of `inline` rather than C's, which is
694    /// `-fgnu89-inline`.
695    ///
696    /// Under C's reading a definition every file-scope declaration wrote `inline` for and none
697    /// wrote `extern` for emits nothing, and under GNU's it is the definition alone that decides
698    /// and `extern inline` is the one that emits nothing. The C89 dialects are under GNU's
699    /// whatever this says, since that is where the older reading came from, so this is the flag a
700    /// program written against it reaches for when it is being compiled under a later dialect.
701    pub gnu89_inline: bool,
702    /// What a name that nothing in the source said anything about reaches, from `-fvisibility=`.
703    pub visibility: Visibility,
704    /// The GCC release claimed, from `-fgnuc-version=`.
705    pub gnuc: GnucVersion,
706    /// Whether there is a standard library, which is `-ffreestanding` turned around.
707    pub hosted: bool,
708    /// Whether a call to a C library function written under its own plain name may be taken to
709    /// mean that function, which is `-fno-builtin` turned around.
710    ///
711    /// The names are reserved, so `llabs` is the library's `llabs` and the compiler is allowed to
712    /// know what it does. A program that means something else by one of them is the reason the
713    /// flag exists, and `-ffreestanding` turns it off as well, because a freestanding program has
714    /// no C library for the name to be the name of. The `__builtin_` spellings are not affected by
715    /// either, since the prefix is the program saying which function it means.
716    pub builtins: bool,
717    /// The names `-fno-builtin-<name>` took away one at a time, without the prefix.
718    ///
719    /// A build that means its own `memcpy` and the library's everything else writes this rather
720    /// than the whole flag, which is what the kernel does for a handful of names.
721    pub no_builtin: Vec<String>,
722    /// `-D` in command line order. `FOO` means `FOO=1`, as GCC has it.
723    pub defines: Vec<String>,
724    /// `-U` in command line order, applied after the defines because `-U` wins.
725    pub undefines: Vec<String>,
726    /// Where a header is looked for.
727    pub search: SearchPath,
728    /// What `-imacros` and `-include` named, in command line order.
729    pub preincludes: Vec<Preinclude>,
730    /// Whether `-E` writes line markers, which `-P` turns off.
731    pub line_markers: bool,
732    /// What the `-d` family asks for.
733    pub dumps: Dumps,
734    /// What the `-M` family asks for.
735    pub deps: Deps,
736    /// Whether the intermediate files are kept, from `-save-temps`.
737    pub save_temps: SaveTemps,
738    /// Whether each step says how long it took, from `-time`.
739    pub time: bool,
740    /// What `-f<pass>` and `-fno-<pass>` said about an optimizer pass, in the order the command
741    /// line said it, so that the last mention of a pass is the one that decides.
742    ///
743    /// The pipeline the level chose is the starting point and this is what is added to and taken
744    /// away from it. The names are checked against the pass list while the arguments are parsed,
745    /// so anything in here is a pass the compiler has.
746    pub passes: Vec<(String, bool)>,
747    /// What `-fpass-fuel=<pass>=<n>` limited a pass to, by pass name.
748    ///
749    /// A pass with an entry here performs exactly that many transformations and then stops
750    /// transforming, which is what bisects a miscompilation to one rewrite. See section 9.10 of
751    /// `spec/09-optimizer.md`.
752    pub pass_fuel: Vec<(String, u32)>,
753    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
754    ///
755    /// The outer of the two searches in section 4.5 of `spec/optimizer/04-pass-manager.md`.
756    /// Halving this says which pass holds the bad rewrite, and halving `-fpass-fuel` for that
757    /// pass says which rewrite it is. Where both are given, a pass is stopped by whichever of
758    /// the two is tighter.
759    pub pass_fuel_global: Option<u32>,
760    /// What `-fdisable-<pass>[=<range>]` and `-fenable-<pass>[=<range>]` said, in the order the
761    /// command line said it, with `true` for the enabling half.
762    ///
763    /// A rule covers the functions it names and nothing else, and the last rule that covers a
764    /// function is the one that decides for it, so the order has to survive. This is the second
765    /// half of the bisection interface in section 41.6 of `spec/optimizer/41-correctness.md`:
766    /// `-fpass-fuel` finds the rewrite and this finds the function. The pass names are checked
767    /// against the pass list while the arguments are parsed.
768    pub pass_gates: Vec<(bool, String)>,
769    /// What `-fdump-ir=` asked to see, as it was written, which is `all`, `before-<pass>` or
770    /// `after-<pass>`.
771    pub dump_ir: Vec<String>,
772    /// What `-fopt-info` asked to hear about, as the keywords were written, with the leading
773    /// hyphen taken off, so a bare `-fopt-info` is the empty string in here.
774    ///
775    /// The keywords are `optimized`, `missed`, `note` and `all`, and two flags add up rather than
776    /// the second replacing the first. Checked while the arguments are parsed, so anything in
777    /// here is a spelling the optimizer understands. See section 42.2 of
778    /// `spec/optimizer/42-measurement.md` for why `missed` is the one that earns the feature.
779    pub opt_info: Vec<String>,
780    /// Where `-fopt-info=<file>` sends the remarks, or `None` for standard error.
781    ///
782    /// One file for the whole run rather than one per input, the way GCC does it, and the last
783    /// one on the command line is the one that decides. A harness that wants the remarks kept
784    /// away from the diagnostics gives a file, which is what the corpus in `tamnd/rucc-corpus`
785    /// does with GCC so that a rejection can still be matched against the diagnostic stream.
786    pub opt_info_file: Option<String>,
787    /// Whether the IR verifier runs after every pass that changed anything.
788    ///
789    /// On in a debug build without being asked, since that is where a broken pass should be
790    /// caught. `-Zverify-each` turns it on in a release build, which is what CI wants.
791    pub verify_each: bool,
792    /// Where `-Zrule-coverage=FILE` writes which lowering rules fired, if it was given.
793    ///
794    /// A measurement rather than a thing a build asks for, which is why it is spelled with a `-Z`
795    /// the way an unstable option is everywhere else: it is here for the harness in
796    /// `tamnd/rucc-compat` to union over a corpus and report, and nothing about the code that comes
797    /// out changes when it is on. One file per run of the compiler, holding the whole rule set with
798    /// the rules this run reached marked, whatever the run compiled and however many files it was.
799    pub rule_coverage: Option<String>,
800}
801
802impl Options {
803    /// Default options for `target`.
804    pub fn new(target: Triple) -> Self {
805        Self {
806            target,
807            opt_level: OptLevel::default(),
808            safety: Safety::default(),
809            emit: EmitKind::default(),
810            debug_info: false,
811            frame_pointer: false,
812            red_zone: true,
813            warnings_are_errors: false,
814            warnings: true,
815            error_limit: 20,
816            std: Std::default(),
817            gnu_extensions: true,
818            pedantic: false,
819            permissive: false,
820            gnu89_inline: false,
821            visibility: Visibility::default(),
822            gnuc: GnucVersion::default(),
823            hosted: true,
824            builtins: true,
825            no_builtin: Vec::new(),
826            defines: Vec::new(),
827            undefines: Vec::new(),
828            search: SearchPath::new(),
829            preincludes: Vec::new(),
830            line_markers: true,
831            dumps: Dumps::default(),
832            deps: Deps::default(),
833            save_temps: SaveTemps::default(),
834            time: false,
835            passes: Vec::new(),
836            pass_fuel: Vec::new(),
837            pass_fuel_global: None,
838            pass_gates: Vec::new(),
839            dump_ir: Vec::new(),
840            opt_info: Vec::new(),
841            opt_info_file: None,
842            verify_each: cfg!(debug_assertions),
843            rule_coverage: None,
844        }
845    }
846}
847
848/// One compilation.
849///
850/// Holds the options, the string interner and the diagnostics raised so far. Passing a
851/// `&mut Session` is how a stage reports a problem, and the return value of a stage says
852/// what it produced, never whether it succeeded: that question is answered by
853/// [`Session::has_errors`].
854#[derive(Debug)]
855pub struct Session {
856    /// What this compilation was asked to do.
857    pub opts: Options,
858    /// Everything known about the target.
859    pub target: TargetInfo,
860    /// The one interner for the compilation.
861    pub interner: Interner,
862    /// Every file read during the compilation, and the flat coordinate space their spans
863    /// live in.
864    ///
865    /// This is on the session rather than passed around separately because a span is only
866    /// meaningful against the map that issued it, and one map per compilation is the rule
867    /// that makes that true by construction.
868    pub sources: SourceMap,
869    diagnostics: Vec<Diagnostic>,
870    error_count: u32,
871    warning_count: u32,
872}
873
874impl Session {
875    /// A session for `opts`.
876    pub fn new(opts: Options) -> Self {
877        let target = TargetInfo::new(opts.target);
878        Self {
879            opts,
880            target,
881            interner: Interner::with_capacity(1024),
882            sources: SourceMap::new(),
883            diagnostics: Vec::new(),
884            error_count: 0,
885            warning_count: 0,
886        }
887    }
888
889    /// Records a diagnostic.
890    ///
891    /// Under `-Werror` a warning is promoted here, once, rather than at every site that
892    /// raises one, and under `-w` it is dropped here for the same reason. A warning that `-w`
893    /// dropped is not counted, so `-w -Werror` compiles rather than failing on a warning
894    /// nobody was going to see.
895    pub fn emit(&mut self, mut diag: Diagnostic) {
896        if !self.opts.warnings && diag.severity == Severity::Warning {
897            return;
898        }
899        if self.opts.warnings_are_errors && diag.severity == Severity::Warning {
900            diag.severity = Severity::Error;
901        }
902        match diag.severity {
903            Severity::Error | Severity::Ice => self.error_count += 1,
904            Severity::Warning => self.warning_count += 1,
905            Severity::Note | Severity::Help => {}
906        }
907        self.diagnostics.push(diag);
908    }
909
910    /// Everything raised so far, in the order it was raised.
911    pub fn diagnostics(&self) -> &[Diagnostic] {
912        &self.diagnostics
913    }
914
915    /// Whether anything fatal has been raised.
916    pub fn has_errors(&self) -> bool {
917        self.error_count > 0
918    }
919
920    /// How many errors have been raised.
921    pub fn error_count(&self) -> u32 {
922        self.error_count
923    }
924
925    /// How many warnings have been raised.
926    pub fn warning_count(&self) -> u32 {
927        self.warning_count
928    }
929
930    /// Whether the error limit has been reached and the caller should stop.
931    pub fn error_limit_reached(&self) -> bool {
932        self.opts.error_limit != 0 && self.error_count >= self.opts.error_limit
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    use super::*;
939
940    fn session() -> Session {
941        Session::new(Options::new("x86_64-unknown-linux-gnu".parse().unwrap()))
942    }
943
944    #[test]
945    fn a_version_claim_reads_the_way_gcc_prints_one() {
946        // `gcc -dumpfullversion` gives all three, `gcc -dumpversion` gives one, and both are
947        // things a script pastes straight into a flag.
948        let all = |v: &str| v.parse::<GnucVersion>().unwrap();
949        assert_eq!(all("15.1.0"), GnucVersion { major: 15, minor: 1, patch: 0 });
950        assert_eq!(all("15"), GnucVersion { major: 15, minor: 0, patch: 0 });
951        assert_eq!(all("4.2"), GnucVersion { major: 4, minor: 2, patch: 0 });
952        assert!("".parse::<GnucVersion>().is_err());
953        assert!("15.".parse::<GnucVersion>().is_err(), "a trailing dot is a typo, not a zero");
954        assert!("1.2.3.4".parse::<GnucVersion>().is_err());
955    }
956
957    #[test]
958    fn optimisation_levels_parse_the_way_gcc_spells_them() {
959        assert_eq!("".parse::<OptLevel>().unwrap(), OptLevel::O1);
960        assert_eq!("0".parse::<OptLevel>().unwrap(), OptLevel::O0);
961        assert_eq!("2".parse::<OptLevel>().unwrap(), OptLevel::O2);
962        assert_eq!("9".parse::<OptLevel>().unwrap(), OptLevel::O3);
963        assert_eq!("s".parse::<OptLevel>().unwrap(), OptLevel::Os);
964        assert!("q".parse::<OptLevel>().is_err());
965    }
966
967    #[test]
968    fn only_o0_skips_the_optimizer() {
969        assert!(!OptLevel::O0.runs_optimizer());
970        assert!(OptLevel::O1.runs_optimizer());
971        assert!(OptLevel::Oz.runs_optimizer());
972    }
973
974    #[test]
975    fn the_safety_tiers_round_trip_and_nothing_else_is_one() {
976        for tier in [Safety::Off, Safety::Detect, Safety::Enforce, Safety::Kernel] {
977            assert_eq!(tier.as_str().parse::<Safety>().unwrap(), tier);
978        }
979        // `on` is the obvious thing to try and it is not a tier, because which tier somebody
980        // means by it is the whole question document 02 answers.
981        assert!("on".parse::<Safety>().is_err());
982        assert!("".parse::<Safety>().is_err());
983    }
984
985    #[test]
986    fn the_two_places_the_intermediate_files_can_go_are_the_two_words_that_are_taken() {
987        assert_eq!("obj".parse::<SaveTemps>().unwrap(), SaveTemps::Object);
988        assert_eq!("cwd".parse::<SaveTemps>().unwrap(), SaveTemps::Cwd);
989        // The names of the two flags that mean the same thing as `=obj` are not themselves
990        // arguments of it, and neither is silence.
991        assert!("obj,cwd".parse::<SaveTemps>().is_err());
992        assert!("".parse::<SaveTemps>().is_err());
993        // Nothing is kept unless something asked, and both of the words that ask do ask.
994        assert_eq!(SaveTemps::default(), SaveTemps::No);
995        assert!(!SaveTemps::No.wanted());
996        assert!(SaveTemps::Object.wanted());
997        assert!(SaveTemps::Cwd.wanted());
998    }
999
1000    #[test]
1001    fn a_build_that_did_not_ask_for_the_monitor_does_not_get_it() {
1002        assert_eq!(Safety::default(), Safety::Off);
1003        assert!(!Safety::Off.instruments());
1004        assert!(Safety::Detect.instruments());
1005        assert!(Safety::Enforce.instruments());
1006        assert!(Safety::Kernel.instruments());
1007    }
1008
1009    #[test]
1010    fn emit_kinds_round_trip_through_their_names() {
1011        for k in [
1012            EmitKind::Executable,
1013            EmitKind::Object,
1014            EmitKind::Asm,
1015            EmitKind::Preprocessed,
1016            EmitKind::Tast,
1017            EmitKind::Ir,
1018            EmitKind::MirFinal,
1019        ] {
1020            assert_eq!(k.as_str().parse::<EmitKind>().unwrap(), k);
1021        }
1022    }
1023
1024    #[test]
1025    fn errors_are_counted_and_warnings_are_not() {
1026        let mut s = session();
1027        s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
1028        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
1029        assert_eq!(s.error_count(), 1);
1030        assert_eq!(s.warning_count(), 1);
1031        assert!(s.has_errors());
1032        assert_eq!(s.diagnostics().len(), 2);
1033    }
1034
1035    #[test]
1036    fn werror_promotes_once_at_the_sink() {
1037        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1038        opts.warnings_are_errors = true;
1039        let mut s = Session::new(opts);
1040        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
1041        assert_eq!(s.error_count(), 1);
1042        assert_eq!(s.warning_count(), 0);
1043        assert_eq!(s.diagnostics()[0].severity, Severity::Error);
1044    }
1045
1046    #[test]
1047    fn the_error_limit_can_be_switched_off() {
1048        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
1049        opts.error_limit = 0;
1050        let mut s = Session::new(opts);
1051        for _ in 0..100 {
1052            s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
1053        }
1054        assert!(!s.error_limit_reached());
1055    }
1056
1057    #[test]
1058    fn the_session_carries_the_source_map_spans_are_resolved_against() {
1059        let mut s = session();
1060        let file = s.sources.add("a.c", b"int x;\n".to_vec()).unwrap();
1061        let start = s.sources.file(file).start;
1062        assert_eq!(s.sources.render_position(start + 4), "a.c:1:5");
1063    }
1064
1065    #[test]
1066    fn the_session_carries_the_resolved_target() {
1067        let s = session();
1068        assert_eq!(s.target.pointer_width, 64);
1069        assert!(s.target.char_is_signed);
1070    }
1071}