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 3, 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.5.2")]
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/// What the compiler should produce.
174///
175/// The intermediate forms are not a debugging convenience bolted on later. Every one of them
176/// is a documented textual form that round-trips, which is what makes the per-stage testing
177/// in `spec/15-testing.md` section 15.2 possible.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
179// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
180// match that needs to change, in this workspace and in anyone else's code. That is
181// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
182// target is a data change: the compiler tells you every place the data is read.
183pub enum EmitKind {
184    /// A linked executable. The default.
185    #[default]
186    Executable,
187    /// An object file, `-c`.
188    Object,
189    /// Assembly text, `-S`.
190    Asm,
191    /// Preprocessed source, `-E`.
192    Preprocessed,
193    /// The typed AST, `--emit=tast`.
194    Tast,
195    /// The IR, `--emit=ir`.
196    Ir,
197    /// The machine IR after register allocation, `--emit=mir-final`.
198    MirFinal,
199}
200
201impl EmitKind {
202    /// The name used by `--emit=` and by `--print-config`.
203    pub const fn as_str(self) -> &'static str {
204        match self {
205            EmitKind::Executable => "exe",
206            EmitKind::Object => "obj",
207            EmitKind::Asm => "asm",
208            EmitKind::Preprocessed => "preprocessed",
209            EmitKind::Tast => "tast",
210            EmitKind::Ir => "ir",
211            EmitKind::MirFinal => "mir-final",
212        }
213    }
214}
215
216impl FromStr for EmitKind {
217    type Err = ();
218
219    fn from_str(s: &str) -> Result<Self, ()> {
220        Ok(match s {
221            "exe" => EmitKind::Executable,
222            "obj" => EmitKind::Object,
223            "asm" => EmitKind::Asm,
224            "preprocessed" => EmitKind::Preprocessed,
225            "tast" => EmitKind::Tast,
226            "ir" => EmitKind::Ir,
227            "mir-final" => EmitKind::MirFinal,
228            _ => return Err(()),
229        })
230    }
231}
232
233/// Which C the source is written in.
234///
235/// The GNU variants are the same language with `__STRICT_ANSI__` left undefined, so the
236/// dialect and the extension question are two fields rather than ten variants.
237#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
238pub enum Std {
239    /// `-std=c89`, and `-ansi`.
240    C89,
241    /// `-std=c99`.
242    C99,
243    /// `-std=c11`.
244    C11,
245    /// `-std=c17`, which is C11 with the defect reports applied.
246    C17,
247    /// `-std=c23`. The default, matching current GCC.
248    #[default]
249    C23,
250}
251
252impl Std {
253    /// What `__STDC_VERSION__` says, which C89 does not define at all.
254    pub const fn stdc_version(self) -> Option<&'static str> {
255        match self {
256            Std::C89 => None,
257            Std::C99 => Some("199901L"),
258            Std::C11 => Some("201112L"),
259            Std::C17 => Some("201710L"),
260            Std::C23 => Some("202311L"),
261        }
262    }
263
264    /// The name in `-std=`.
265    pub const fn as_str(self) -> &'static str {
266        match self {
267            Std::C89 => "c89",
268            Std::C99 => "c99",
269            Std::C11 => "c11",
270            Std::C17 => "c17",
271            Std::C23 => "c23",
272        }
273    }
274
275    /// Whether this dialect has `_Atomic`, `_Thread_local` and the rest of C11.
276    pub const fn has_c11(self) -> bool {
277        matches!(self, Std::C11 | Std::C17 | Std::C23)
278    }
279
280    /// Reads a `-std=` argument, and says whether the GNU extensions came with it.
281    ///
282    /// Every alias GCC takes is here, including the `iso9899` spellings and the year based
283    /// ones, because a build system that passes `-std=iso9899:1999` is passing what its
284    /// author tested against and rejecting it helps nobody. An unknown dialect is `None`
285    /// rather than a guess, since guessing means compiling a different language than the one
286    /// asked for.
287    #[must_use]
288    pub fn from_flag(name: &str) -> Option<(Std, bool)> {
289        let gnu = name.starts_with("gnu");
290        let std = match name {
291            "c89" | "c90" | "gnu89" | "gnu90" | "iso9899:1990" | "iso9899:199409" => Std::C89,
292            "c99" | "c9x" | "gnu99" | "gnu9x" | "iso9899:1999" | "iso9899:199x" => Std::C99,
293            "c11" | "c1x" | "gnu11" | "gnu1x" | "iso9899:2011" => Std::C11,
294            "c17" | "c18" | "gnu17" | "gnu18" | "iso9899:2017" | "iso9899:2018" => Std::C17,
295            "c23" | "c2x" | "gnu23" | "gnu2x" => Std::C23,
296            _ => return None,
297        };
298        Some((std, gnu))
299    }
300}
301
302/// The GCC release the compiler claims to be, as `__GNUC__`, `__GNUC_MINOR__` and
303/// `__GNUC_PATCHLEVEL__`.
304///
305/// Design: `spec/04-driver-and-cli.md` section 4.5, which makes this a knob rather than a
306/// constant and says to start conservative and raise it as the matrix in `rucc-gnu` fills in.
307///
308/// The default is seven, which is the lowest claim that gets a modern glibc. glibc gates most
309/// of what it hands a caller on `__GNUC_PREREQ`, so the claim decides which half of
310/// `sys/cdefs.h` we get, and below seven `bits/floatn-common.h` writes `typedef float _Float32;`
311/// over a keyword this compiler already has. Every header that reaches it stops there, which
312/// was most of them: on Ubuntu 24.04's glibc 2.39 the claim of 4.2.1 that stood here before got
313/// 180 of 214 headers through and seven gets 202, and the amalgamated sqlite goes from four
314/// errors to none.
315///
316/// It is still deliberately low. Claiming a version whose promises have not been kept means
317/// being handed syntax the compiler cannot parse, so this moves when there is a measurement
318/// saying it can. Thirteen and sixteen were measured alongside seven and came out identical on
319/// glibc, on the macOS SDK and on sqlite, so the next move up is cheap; it is a separate one
320/// because nothing yet needs it.
321#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
322pub struct GnucVersion {
323    /// `__GNUC__`.
324    pub major: u32,
325    /// `__GNUC_MINOR__`.
326    pub minor: u32,
327    /// `__GNUC_PATCHLEVEL__`.
328    pub patch: u32,
329}
330
331impl Default for GnucVersion {
332    fn default() -> GnucVersion {
333        GnucVersion { major: 7, minor: 0, patch: 0 }
334    }
335}
336
337impl FromStr for GnucVersion {
338    type Err = String;
339
340    /// Reads `-fgnuc-version=`, which is `15`, `15.1` or `15.1.0`.
341    ///
342    /// The short forms are not a convenience, they are what people write. A missing component
343    /// is zero, the same way GCC treats a release with no patchlevel.
344    fn from_str(text: &str) -> Result<GnucVersion, String> {
345        let mut parts = text.split('.');
346        let mut next = |what: &str| -> Result<u32, String> {
347            match parts.next() {
348                None => Ok(0),
349                Some(field) => {
350                    field.parse().map_err(|_| format!("`{text}` has a {what} that is not a number"))
351                }
352            }
353        };
354        let major = next("major")?;
355        let minor = next("minor")?;
356        let patch = next("patchlevel")?;
357        if parts.next().is_some() {
358            return Err(format!("`{text}` has more than three components"));
359        }
360        Ok(GnucVersion { major, minor, patch })
361    }
362}
363
364/// What the `-d` family asks to be dumped alongside, or instead of, the preprocessed output.
365///
366/// Design: `spec/04-driver-and-cli.md` section 4.4.
367///
368/// GCC spells these as letters packed into one flag, so `-dDI` is two of them, and a letter it
369/// does not know is ignored rather than rejected. That last part is deliberate on GCC's side
370/// and worth copying: the family is a debugging aid and a build that passes `-dumpbase` should
371/// not die on the `-d`.
372#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
373pub struct Dumps {
374    /// `-dM`. Print the macros that are defined at the end, and nothing else.
375    pub macros: bool,
376}
377
378impl Dumps {
379    /// The letters GCC's preprocessor takes after `-d`.
380    ///
381    /// `M` is the macros, `D` is the macros in place, `N` is their names only, `I` is the
382    /// `#include` lines and `U` is the macros as they are used. Only `M` does anything so far.
383    const LETTERS: &'static str = "MDNIU";
384
385    /// Whether `arg` is a flag from this family rather than something else beginning with
386    /// `-d`.
387    ///
388    /// The check is here rather than in the driver so that the set of letters and the set of
389    /// flags accepted cannot drift apart. It matters because `-dumpversion` also begins with
390    /// `-d`, and a family that swallowed every such flag would turn a flag we have not written
391    /// into a dump of nothing.
392    #[must_use]
393    pub fn is_family(arg: &str) -> bool {
394        match arg.strip_prefix("-d") {
395            Some("") | None => false,
396            Some(letters) => letters.chars().all(|c| Dumps::LETTERS.contains(c)),
397        }
398    }
399
400    /// Reads the letters after `-d`, ignoring the ones we do not implement yet.
401    pub fn add(&mut self, letters: &str) {
402        for letter in letters.chars() {
403            if letter == 'M' {
404                self.macros = true;
405            }
406        }
407    }
408
409    /// Whether anything at all was asked for.
410    #[must_use]
411    pub const fn any(self) -> bool {
412        self.macros
413    }
414}
415
416/// Everything a compilation was asked to do.
417///
418/// Options are a plain value with no interior mutability, so a caller can build one, clone
419/// it, tweak one field and run a second compilation, which is exactly what the differential
420/// testing in `spec/15-testing.md` needs.
421#[derive(Debug, Clone, PartialEq, Eq)]
422#[non_exhaustive]
423pub struct Options {
424    /// The target to generate code for.
425    pub target: Triple,
426    /// The optimisation level.
427    pub opt_level: OptLevel,
428    /// How much of the memory safety monitor is on, from `-fsafety=`.
429    ///
430    /// Off unless it was asked for. A program built without the flag is compiled by exactly the
431    /// pipeline it was compiled by before the monitor existed, which is the only way the feature
432    /// can be developed in the open without every build paying for it.
433    pub safety: Safety,
434    /// What to produce.
435    pub emit: EmitKind,
436    /// Whether to emit debug information.
437    pub debug_info: bool,
438    /// Whether every function keeps a frame pointer, from `-fno-omit-frame-pointer`.
439    ///
440    /// Off by default, which is what gcc does at every level above `-O0` and what leaves the
441    /// register free for the allocator. A profiler that walks the stack by following saved frame
442    /// pointers needs it on, and so does any code a debugger has to unwind without unwind tables.
443    pub frame_pointer: bool,
444    /// Whether the red zone may be used, from `-mno-red-zone` turned around.
445    ///
446    /// The 128 bytes below the stack pointer that the System V psABI promises no signal handler
447    /// will touch, which lets a small leaf function keep its locals without moving the stack
448    /// pointer at all. A kernel turns this off, because an interrupt taken on the kernel stack
449    /// makes the promise false, and every kernel build in the wild passes `-mno-red-zone` for
450    /// exactly that reason. A convention without a red zone ignores this.
451    pub red_zone: bool,
452    /// Whether warnings are errors.
453    pub warnings_are_errors: bool,
454    /// Whether a warning is raised at all, which is `-w` turned around.
455    ///
456    /// A build that passes this has decided it does not want to hear about anything that is not
457    /// fatal, and the flag is dropped at the one place every diagnostic goes through rather than
458    /// tested at each site that raises one. `-w` beats `-Werror` where both are given, because a
459    /// warning that was never raised cannot be promoted.
460    pub warnings: bool,
461    /// How many diagnostics to print before giving up. Past a certain point the output is
462    /// noise from a single earlier mistake, and GCC's default of no limit is not a kindness.
463    pub error_limit: u32,
464    /// The dialect, from `-std=`.
465    pub std: Std,
466    /// Whether the GNU extensions are on, which is `-std=gnu23` rather than `-std=c23`.
467    pub gnu_extensions: bool,
468    /// Whether `-pedantic` was given, which is what turns a use of an extension from silence
469    /// into a diagnostic. It is not the same knob as the dialect: `-std=c17 -pedantic` warns
470    /// about a construct that `-std=c17` alone accepts without a word.
471    pub pedantic: bool,
472    /// The GCC release claimed, from `-fgnuc-version=`.
473    pub gnuc: GnucVersion,
474    /// Whether there is a standard library, which is `-ffreestanding` turned around.
475    pub hosted: bool,
476    /// Whether a call to a C library function written under its own plain name may be taken to
477    /// mean that function, which is `-fno-builtin` turned around.
478    ///
479    /// The names are reserved, so `llabs` is the library's `llabs` and the compiler is allowed to
480    /// know what it does. A program that means something else by one of them is the reason the
481    /// flag exists, and `-ffreestanding` turns it off as well, because a freestanding program has
482    /// no C library for the name to be the name of. The `__builtin_` spellings are not affected by
483    /// either, since the prefix is the program saying which function it means.
484    pub builtins: bool,
485    /// The names `-fno-builtin-<name>` took away one at a time, without the prefix.
486    ///
487    /// A build that means its own `memcpy` and the library's everything else writes this rather
488    /// than the whole flag, which is what the kernel does for a handful of names.
489    pub no_builtin: Vec<String>,
490    /// `-D` in command line order. `FOO` means `FOO=1`, as GCC has it.
491    pub defines: Vec<String>,
492    /// `-U` in command line order, applied after the defines because `-U` wins.
493    pub undefines: Vec<String>,
494    /// Where a header is looked for.
495    pub search: SearchPath,
496    /// Whether `-E` writes line markers, which `-P` turns off.
497    pub line_markers: bool,
498    /// What the `-d` family asks for.
499    pub dumps: Dumps,
500    /// What `-f<pass>` and `-fno-<pass>` said about an optimizer pass, in the order the command
501    /// line said it, so that the last mention of a pass is the one that decides.
502    ///
503    /// The pipeline the level chose is the starting point and this is what is added to and taken
504    /// away from it. The names are checked against the pass list while the arguments are parsed,
505    /// so anything in here is a pass the compiler has.
506    pub passes: Vec<(String, bool)>,
507    /// What `-fpass-fuel=<pass>=<n>` limited a pass to, by pass name.
508    ///
509    /// A pass with an entry here performs exactly that many transformations and then stops
510    /// transforming, which is what bisects a miscompilation to one rewrite. See section 9.10 of
511    /// `spec/09-optimizer.md`.
512    pub pass_fuel: Vec<(String, u32)>,
513    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
514    ///
515    /// The outer of the two searches in section 4.5 of `spec/optimizer/04-pass-manager.md`.
516    /// Halving this says which pass holds the bad rewrite, and halving `-fpass-fuel` for that
517    /// pass says which rewrite it is. Where both are given, a pass is stopped by whichever of
518    /// the two is tighter.
519    pub pass_fuel_global: Option<u32>,
520    /// What `-fdisable-<pass>[=<range>]` and `-fenable-<pass>[=<range>]` said, in the order the
521    /// command line said it, with `true` for the enabling half.
522    ///
523    /// A rule covers the functions it names and nothing else, and the last rule that covers a
524    /// function is the one that decides for it, so the order has to survive. This is the second
525    /// half of the bisection interface in section 41.6 of `spec/optimizer/41-correctness.md`:
526    /// `-fpass-fuel` finds the rewrite and this finds the function. The pass names are checked
527    /// against the pass list while the arguments are parsed.
528    pub pass_gates: Vec<(bool, String)>,
529    /// What `-fdump-ir=` asked to see, as it was written, which is `all`, `before-<pass>` or
530    /// `after-<pass>`.
531    pub dump_ir: Vec<String>,
532    /// What `-fopt-info` asked to hear about, as the keywords were written, with the leading
533    /// hyphen taken off, so a bare `-fopt-info` is the empty string in here.
534    ///
535    /// The keywords are `optimized`, `missed`, `note` and `all`, and two flags add up rather than
536    /// the second replacing the first. Checked while the arguments are parsed, so anything in
537    /// here is a spelling the optimizer understands. See section 42.2 of
538    /// `spec/optimizer/42-measurement.md` for why `missed` is the one that earns the feature.
539    pub opt_info: Vec<String>,
540    /// Where `-fopt-info=<file>` sends the remarks, or `None` for standard error.
541    ///
542    /// One file for the whole run rather than one per input, the way GCC does it, and the last
543    /// one on the command line is the one that decides. A harness that wants the remarks kept
544    /// away from the diagnostics gives a file, which is what the corpus in `tamnd/rucc-corpus`
545    /// does with GCC so that a rejection can still be matched against the diagnostic stream.
546    pub opt_info_file: Option<String>,
547    /// Whether the IR verifier runs after every pass that changed anything.
548    ///
549    /// On in a debug build without being asked, since that is where a broken pass should be
550    /// caught. `-Zverify-each` turns it on in a release build, which is what CI wants.
551    pub verify_each: bool,
552    /// Where `-Zrule-coverage=FILE` writes which lowering rules fired, if it was given.
553    ///
554    /// A measurement rather than a thing a build asks for, which is why it is spelled with a `-Z`
555    /// the way an unstable option is everywhere else: it is here for the harness in
556    /// `tamnd/rucc-compat` to union over a corpus and report, and nothing about the code that comes
557    /// out changes when it is on. One file per run of the compiler, holding the whole rule set with
558    /// the rules this run reached marked, whatever the run compiled and however many files it was.
559    pub rule_coverage: Option<String>,
560}
561
562impl Options {
563    /// Default options for `target`.
564    pub fn new(target: Triple) -> Self {
565        Self {
566            target,
567            opt_level: OptLevel::default(),
568            safety: Safety::default(),
569            emit: EmitKind::default(),
570            debug_info: false,
571            frame_pointer: false,
572            red_zone: true,
573            warnings_are_errors: false,
574            warnings: true,
575            error_limit: 20,
576            std: Std::default(),
577            gnu_extensions: true,
578            pedantic: false,
579            gnuc: GnucVersion::default(),
580            hosted: true,
581            builtins: true,
582            no_builtin: Vec::new(),
583            defines: Vec::new(),
584            undefines: Vec::new(),
585            search: SearchPath::new(),
586            line_markers: true,
587            dumps: Dumps::default(),
588            passes: Vec::new(),
589            pass_fuel: Vec::new(),
590            pass_fuel_global: None,
591            pass_gates: Vec::new(),
592            dump_ir: Vec::new(),
593            opt_info: Vec::new(),
594            opt_info_file: None,
595            verify_each: cfg!(debug_assertions),
596            rule_coverage: None,
597        }
598    }
599}
600
601/// One compilation.
602///
603/// Holds the options, the string interner and the diagnostics raised so far. Passing a
604/// `&mut Session` is how a stage reports a problem, and the return value of a stage says
605/// what it produced, never whether it succeeded: that question is answered by
606/// [`Session::has_errors`].
607#[derive(Debug)]
608pub struct Session {
609    /// What this compilation was asked to do.
610    pub opts: Options,
611    /// Everything known about the target.
612    pub target: TargetInfo,
613    /// The one interner for the compilation.
614    pub interner: Interner,
615    /// Every file read during the compilation, and the flat coordinate space their spans
616    /// live in.
617    ///
618    /// This is on the session rather than passed around separately because a span is only
619    /// meaningful against the map that issued it, and one map per compilation is the rule
620    /// that makes that true by construction.
621    pub sources: SourceMap,
622    diagnostics: Vec<Diagnostic>,
623    error_count: u32,
624    warning_count: u32,
625}
626
627impl Session {
628    /// A session for `opts`.
629    pub fn new(opts: Options) -> Self {
630        let target = TargetInfo::new(opts.target);
631        Self {
632            opts,
633            target,
634            interner: Interner::with_capacity(1024),
635            sources: SourceMap::new(),
636            diagnostics: Vec::new(),
637            error_count: 0,
638            warning_count: 0,
639        }
640    }
641
642    /// Records a diagnostic.
643    ///
644    /// Under `-Werror` a warning is promoted here, once, rather than at every site that
645    /// raises one, and under `-w` it is dropped here for the same reason. A warning that `-w`
646    /// dropped is not counted, so `-w -Werror` compiles rather than failing on a warning
647    /// nobody was going to see.
648    pub fn emit(&mut self, mut diag: Diagnostic) {
649        if !self.opts.warnings && diag.severity == Severity::Warning {
650            return;
651        }
652        if self.opts.warnings_are_errors && diag.severity == Severity::Warning {
653            diag.severity = Severity::Error;
654        }
655        match diag.severity {
656            Severity::Error | Severity::Ice => self.error_count += 1,
657            Severity::Warning => self.warning_count += 1,
658            Severity::Note | Severity::Help => {}
659        }
660        self.diagnostics.push(diag);
661    }
662
663    /// Everything raised so far, in the order it was raised.
664    pub fn diagnostics(&self) -> &[Diagnostic] {
665        &self.diagnostics
666    }
667
668    /// Whether anything fatal has been raised.
669    pub fn has_errors(&self) -> bool {
670        self.error_count > 0
671    }
672
673    /// How many errors have been raised.
674    pub fn error_count(&self) -> u32 {
675        self.error_count
676    }
677
678    /// How many warnings have been raised.
679    pub fn warning_count(&self) -> u32 {
680        self.warning_count
681    }
682
683    /// Whether the error limit has been reached and the caller should stop.
684    pub fn error_limit_reached(&self) -> bool {
685        self.opts.error_limit != 0 && self.error_count >= self.opts.error_limit
686    }
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692
693    fn session() -> Session {
694        Session::new(Options::new("x86_64-unknown-linux-gnu".parse().unwrap()))
695    }
696
697    #[test]
698    fn a_version_claim_reads_the_way_gcc_prints_one() {
699        // `gcc -dumpfullversion` gives all three, `gcc -dumpversion` gives one, and both are
700        // things a script pastes straight into a flag.
701        let all = |v: &str| v.parse::<GnucVersion>().unwrap();
702        assert_eq!(all("15.1.0"), GnucVersion { major: 15, minor: 1, patch: 0 });
703        assert_eq!(all("15"), GnucVersion { major: 15, minor: 0, patch: 0 });
704        assert_eq!(all("4.2"), GnucVersion { major: 4, minor: 2, patch: 0 });
705        assert!("".parse::<GnucVersion>().is_err());
706        assert!("15.".parse::<GnucVersion>().is_err(), "a trailing dot is a typo, not a zero");
707        assert!("1.2.3.4".parse::<GnucVersion>().is_err());
708    }
709
710    #[test]
711    fn optimisation_levels_parse_the_way_gcc_spells_them() {
712        assert_eq!("".parse::<OptLevel>().unwrap(), OptLevel::O1);
713        assert_eq!("0".parse::<OptLevel>().unwrap(), OptLevel::O0);
714        assert_eq!("2".parse::<OptLevel>().unwrap(), OptLevel::O2);
715        assert_eq!("9".parse::<OptLevel>().unwrap(), OptLevel::O3);
716        assert_eq!("s".parse::<OptLevel>().unwrap(), OptLevel::Os);
717        assert!("q".parse::<OptLevel>().is_err());
718    }
719
720    #[test]
721    fn only_o0_skips_the_optimizer() {
722        assert!(!OptLevel::O0.runs_optimizer());
723        assert!(OptLevel::O1.runs_optimizer());
724        assert!(OptLevel::Oz.runs_optimizer());
725    }
726
727    #[test]
728    fn the_safety_tiers_round_trip_and_nothing_else_is_one() {
729        for tier in [Safety::Off, Safety::Detect, Safety::Enforce, Safety::Kernel] {
730            assert_eq!(tier.as_str().parse::<Safety>().unwrap(), tier);
731        }
732        // `on` is the obvious thing to try and it is not a tier, because which tier somebody
733        // means by it is the whole question document 02 answers.
734        assert!("on".parse::<Safety>().is_err());
735        assert!("".parse::<Safety>().is_err());
736    }
737
738    #[test]
739    fn a_build_that_did_not_ask_for_the_monitor_does_not_get_it() {
740        assert_eq!(Safety::default(), Safety::Off);
741        assert!(!Safety::Off.instruments());
742        assert!(Safety::Detect.instruments());
743        assert!(Safety::Enforce.instruments());
744        assert!(Safety::Kernel.instruments());
745    }
746
747    #[test]
748    fn emit_kinds_round_trip_through_their_names() {
749        for k in [
750            EmitKind::Executable,
751            EmitKind::Object,
752            EmitKind::Asm,
753            EmitKind::Preprocessed,
754            EmitKind::Tast,
755            EmitKind::Ir,
756            EmitKind::MirFinal,
757        ] {
758            assert_eq!(k.as_str().parse::<EmitKind>().unwrap(), k);
759        }
760    }
761
762    #[test]
763    fn errors_are_counted_and_warnings_are_not() {
764        let mut s = session();
765        s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
766        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
767        assert_eq!(s.error_count(), 1);
768        assert_eq!(s.warning_count(), 1);
769        assert!(s.has_errors());
770        assert_eq!(s.diagnostics().len(), 2);
771    }
772
773    #[test]
774    fn werror_promotes_once_at_the_sink() {
775        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
776        opts.warnings_are_errors = true;
777        let mut s = Session::new(opts);
778        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
779        assert_eq!(s.error_count(), 1);
780        assert_eq!(s.warning_count(), 0);
781        assert_eq!(s.diagnostics()[0].severity, Severity::Error);
782    }
783
784    #[test]
785    fn the_error_limit_can_be_switched_off() {
786        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
787        opts.error_limit = 0;
788        let mut s = Session::new(opts);
789        for _ in 0..100 {
790            s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
791        }
792        assert!(!s.error_limit_reached());
793    }
794
795    #[test]
796    fn the_session_carries_the_source_map_spans_are_resolved_against() {
797        let mut s = session();
798        let file = s.sources.add("a.c", b"int x;\n".to_vec()).unwrap();
799        let start = s.sources.file(file).start;
800        assert_eq!(s.sources.render_position(start + 4), "a.c:1:5");
801    }
802
803    #[test]
804    fn the_session_carries_the_resolved_target() {
805        let s = session();
806        assert_eq!(s.target.pointer_width, 64);
807        assert!(s.target.char_is_signed);
808    }
809}