rucc-session 0.7.8

The per-compilation session, options and diagnostic sink for the rucc C compiler.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! The `Session`: the options, the interner and the diagnostic sink that every stage of a
//! single compilation is handed.
//!
//! Design: `spec/03-architecture.md` and `spec/04-driver-and-cli.md`. Layer rank 3, see
//! `spec/18-package-layout.md`.
//!
//! Everything below the driver reaches the outside world through this type and not through
//! `std::fs`, `std::env` or `println!`. That is the whole reason the compiler can be used as
//! a library and tested without spawning a process, and it is enforced by the layer rule
//! rather than by discipline.
//!
//! # Status
//!
//! Options, optimisation levels, emit kinds, diagnostic counting, the source map every span
//! is resolved against, the file system the compiler reads through, the include search path
//! and the headers the compiler itself ships are real. The parallel job model is still a
//! placeholder.
//!
//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
//! explicitly unstable and will change without a major version bump.

#![doc(html_root_url = "https://docs.rs/rucc-session/0.7.8")]

mod fs;
pub mod runtime;

pub use crate::fs::{Dir, FileSystem, Found, IncludeForm, MemoryFileSystem, SearchPath, path_key};

use std::fmt;
use std::str::FromStr;

use rucc_base::Interner;
use rucc_diag::{Diagnostic, Severity, SourceMap};
use rucc_target::{TargetInfo, Triple};

/// An optimisation level.
///
/// `spec/16-performance.md` section 16.4 gives each level a throughput budget and a code
/// quality budget, and the levels exist to make that tradeoff explicit rather than to be a
/// dial. There is no `-O4`, because a level nobody can state the contract for is a level
/// nobody can test.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum OptLevel {
    /// `-O0`. Compile as fast as possible and keep every variable inspectable.
    #[default]
    O0,
    /// `-O1`. The cheap wins, at roughly the cost of `-O0`.
    O1,
    /// `-O2`. The full pipeline. This is the level the code quality claim is about.
    O2,
    /// `-O3`. `-O2` plus the transformations that trade size for speed.
    O3,
    /// `-Os`. Optimise for size, at roughly `-O2` compile time.
    Os,
    /// `-Oz`. Optimise for size, aggressively.
    Oz,
}

impl OptLevel {
    /// The flag that selects this level.
    pub const fn as_flag(self) -> &'static str {
        match self {
            OptLevel::O0 => "-O0",
            OptLevel::O1 => "-O1",
            OptLevel::O2 => "-O2",
            OptLevel::O3 => "-O3",
            OptLevel::Os => "-Os",
            OptLevel::Oz => "-Oz",
        }
    }

    /// Whether this level optimises for size rather than speed.
    pub const fn is_size(self) -> bool {
        matches!(self, OptLevel::Os | OptLevel::Oz)
    }

    /// Whether the middle end runs at all.
    pub const fn runs_optimizer(self) -> bool {
        !matches!(self, OptLevel::O0)
    }
}

impl fmt::Display for OptLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_flag())
    }
}

impl FromStr for OptLevel {
    type Err = ();

    /// Parses the part after `-O`, so `""` is `-O` which GCC treats as `-O1`.
    fn from_str(s: &str) -> Result<Self, ()> {
        Ok(match s {
            "0" => OptLevel::O0,
            "" | "1" => OptLevel::O1,
            "2" => OptLevel::O2,
            // GCC accepts `-O4` and above and treats them as `-O3`. Build systems in the
            // wild do pass them, so matching that is cheaper than being right.
            "3" | "4" | "5" | "6" | "7" | "8" | "9" => OptLevel::O3,
            "s" => OptLevel::Os,
            "z" => OptLevel::Oz,
            _ => return Err(()),
        })
    }
}

/// How much of the memory safety monitor is on, from `-fsafety=`.
///
/// Design: `spec/safe-memory/15-integration.md` section 15.4. One flag rather than a plane at a
/// time, because the tiers of `spec/safe-memory/02-threat-model.md` are the product and the
/// modifiers are how somebody who has read that document departs from one.
///
/// The tiers agree about which accesses are checked and disagree about what happens when a check
/// says no and about how much of the boundary is covered. That is why they are one value here and
/// not three booleans: a build asks for a tier, and everything else follows from it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum Safety {
    /// `-fsafety=off`. No checks and no runtime. The default, and what every existing build gets.
    #[default]
    Off,
    /// `-fsafety=detect`. Tier D: report and carry on, for a test run or a fuzzer.
    Detect,
    /// `-fsafety=enforce`. Tier E: report and stop, for a program that faces the network.
    Enforce,
    /// `-fsafety=kernel`. Tier K: what a kernel can afford, with the allocator and the libc
    /// wrappers taken out because a kernel has neither.
    Kernel,
}

impl Safety {
    /// The spelling this tier is asked for by, without the flag in front of it.
    pub const fn as_str(self) -> &'static str {
        match self {
            Safety::Off => "off",
            Safety::Detect => "detect",
            Safety::Enforce => "enforce",
            Safety::Kernel => "kernel",
        }
    }

    /// Whether checks are inserted at all.
    ///
    /// The three tiers that are not `off` all insert the same checks at this milestone. What
    /// separates them is the reporter and the boundary, which are milestones S2 and S3 in
    /// `spec/safe-memory/16-milestones.md`.
    pub const fn instruments(self) -> bool {
        !matches!(self, Safety::Off)
    }
}

impl fmt::Display for Safety {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Safety {
    type Err = ();

    /// Parses the part after `-fsafety=`.
    fn from_str(s: &str) -> Result<Self, ()> {
        Ok(match s {
            "off" => Safety::Off,
            "detect" => Safety::Detect,
            "enforce" => Safety::Enforce,
            "kernel" => Safety::Kernel,
            _ => return Err(()),
        })
    }
}

/// What the compiler should produce.
///
/// The intermediate forms are not a debugging convenience bolted on later. Every one of them
/// is a documented textual form that round-trips, which is what makes the per-stage testing
/// in `spec/15-testing.md` section 15.2 possible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
// match that needs to change, in this workspace and in anyone else's code. That is
// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
// target is a data change: the compiler tells you every place the data is read.
pub enum EmitKind {
    /// A linked executable. The default.
    #[default]
    Executable,
    /// An object file, `-c`.
    Object,
    /// Assembly text, `-S`.
    Asm,
    /// Preprocessed source, `-E`.
    Preprocessed,
    /// The typed AST, `--emit=tast`.
    Tast,
    /// The IR, `--emit=ir`.
    Ir,
    /// The machine IR after register allocation, `--emit=mir-final`.
    MirFinal,
    /// The safety summary, `--emit=safety-summary`.
    ///
    /// Not an intermediate form of the program the way the three above are. It is the answer to
    /// "what does this build's guarantee actually rest on", which
    /// `spec/safe-memory/07-check-elimination.md` section 7.8 asks for and
    /// `spec/safe-memory/10-boundaries.md` section 10.2 says why.
    SafetySummary,
    /// How the bytes of the translation unit's records fall into granules,
    /// `--emit=type-granules`.
    ///
    /// Not an intermediate form either. It is the measurement
    /// `spec/safe-memory/17-open-questions.md` question 6 asks for, which decides whether the
    /// type plane fits inside Tier D's memory budget, and it needs nothing past the type
    /// checker because it is a question about layouts rather than about code.
    TypeGranules,
}

impl EmitKind {
    /// The name used by `--emit=` and by `--print-config`.
    pub const fn as_str(self) -> &'static str {
        match self {
            EmitKind::Executable => "exe",
            EmitKind::Object => "obj",
            EmitKind::Asm => "asm",
            EmitKind::Preprocessed => "preprocessed",
            EmitKind::Tast => "tast",
            EmitKind::Ir => "ir",
            EmitKind::MirFinal => "mir-final",
            EmitKind::SafetySummary => "safety-summary",
            EmitKind::TypeGranules => "type-granules",
        }
    }
}

impl FromStr for EmitKind {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, ()> {
        Ok(match s {
            "exe" => EmitKind::Executable,
            "obj" => EmitKind::Object,
            "asm" => EmitKind::Asm,
            "preprocessed" => EmitKind::Preprocessed,
            "tast" => EmitKind::Tast,
            "ir" => EmitKind::Ir,
            "mir-final" => EmitKind::MirFinal,
            "safety-summary" => EmitKind::SafetySummary,
            "type-granules" => EmitKind::TypeGranules,
            _ => return Err(()),
        })
    }
}

/// Which C the source is written in.
///
/// The GNU variants are the same language with `__STRICT_ANSI__` left undefined, so the
/// dialect and the extension question are two fields rather than ten variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum Std {
    /// `-std=c89`, and `-ansi`.
    C89,
    /// `-std=c99`.
    C99,
    /// `-std=c11`.
    C11,
    /// `-std=c17`, which is C11 with the defect reports applied.
    C17,
    /// `-std=c23`. The default, matching current GCC.
    #[default]
    C23,
}

impl Std {
    /// What `__STDC_VERSION__` says, which C89 does not define at all.
    pub const fn stdc_version(self) -> Option<&'static str> {
        match self {
            Std::C89 => None,
            Std::C99 => Some("199901L"),
            Std::C11 => Some("201112L"),
            Std::C17 => Some("201710L"),
            Std::C23 => Some("202311L"),
        }
    }

    /// The name in `-std=`.
    pub const fn as_str(self) -> &'static str {
        match self {
            Std::C89 => "c89",
            Std::C99 => "c99",
            Std::C11 => "c11",
            Std::C17 => "c17",
            Std::C23 => "c23",
        }
    }

    /// Whether this dialect has `_Atomic`, `_Thread_local` and the rest of C11.
    pub const fn has_c11(self) -> bool {
        matches!(self, Std::C11 | Std::C17 | Std::C23)
    }

    /// Reads a `-std=` argument, and says whether the GNU extensions came with it.
    ///
    /// Every alias GCC takes is here, including the `iso9899` spellings and the year based
    /// ones, because a build system that passes `-std=iso9899:1999` is passing what its
    /// author tested against and rejecting it helps nobody. An unknown dialect is `None`
    /// rather than a guess, since guessing means compiling a different language than the one
    /// asked for.
    #[must_use]
    pub fn from_flag(name: &str) -> Option<(Std, bool)> {
        let gnu = name.starts_with("gnu");
        let std = match name {
            "c89" | "c90" | "gnu89" | "gnu90" | "iso9899:1990" | "iso9899:199409" => Std::C89,
            "c99" | "c9x" | "gnu99" | "gnu9x" | "iso9899:1999" | "iso9899:199x" => Std::C99,
            "c11" | "c1x" | "gnu11" | "gnu1x" | "iso9899:2011" => Std::C11,
            "c17" | "c18" | "gnu17" | "gnu18" | "iso9899:2017" | "iso9899:2018" => Std::C17,
            "c23" | "c2x" | "gnu23" | "gnu2x" => Std::C23,
            _ => return None,
        };
        Some((std, gnu))
    }
}

/// The GCC release the compiler claims to be, as `__GNUC__`, `__GNUC_MINOR__` and
/// `__GNUC_PATCHLEVEL__`.
///
/// Design: `spec/04-driver-and-cli.md` section 4.5, which makes this a knob rather than a
/// constant and says to start conservative and raise it as the matrix in `rucc-gnu` fills in.
///
/// The default is seven, which is the lowest claim that gets a modern glibc. glibc gates most
/// of what it hands a caller on `__GNUC_PREREQ`, so the claim decides which half of
/// `sys/cdefs.h` we get, and below seven `bits/floatn-common.h` writes `typedef float _Float32;`
/// over a keyword this compiler already has. Every header that reaches it stops there, which
/// was most of them: on Ubuntu 24.04's glibc 2.39 the claim of 4.2.1 that stood here before got
/// 180 of 214 headers through and seven gets 202, and the amalgamated sqlite goes from four
/// errors to none.
///
/// It is still deliberately low. Claiming a version whose promises have not been kept means
/// being handed syntax the compiler cannot parse, so this moves when there is a measurement
/// saying it can. Thirteen and sixteen were measured alongside seven and came out identical on
/// glibc, on the macOS SDK and on sqlite, so the next move up is cheap; it is a separate one
/// because nothing yet needs it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GnucVersion {
    /// `__GNUC__`.
    pub major: u32,
    /// `__GNUC_MINOR__`.
    pub minor: u32,
    /// `__GNUC_PATCHLEVEL__`.
    pub patch: u32,
}

impl Default for GnucVersion {
    fn default() -> GnucVersion {
        GnucVersion { major: 7, minor: 0, patch: 0 }
    }
}

impl FromStr for GnucVersion {
    type Err = String;

    /// Reads `-fgnuc-version=`, which is `15`, `15.1` or `15.1.0`.
    ///
    /// The short forms are not a convenience, they are what people write. A missing component
    /// is zero, the same way GCC treats a release with no patchlevel.
    fn from_str(text: &str) -> Result<GnucVersion, String> {
        let mut parts = text.split('.');
        let mut next = |what: &str| -> Result<u32, String> {
            match parts.next() {
                None => Ok(0),
                Some(field) => {
                    field.parse().map_err(|_| format!("`{text}` has a {what} that is not a number"))
                }
            }
        };
        let major = next("major")?;
        let minor = next("minor")?;
        let patch = next("patchlevel")?;
        if parts.next().is_some() {
            return Err(format!("`{text}` has more than three components"));
        }
        Ok(GnucVersion { major, minor, patch })
    }
}

/// What the `-d` family asks to be dumped alongside, or instead of, the preprocessed output.
///
/// Design: `spec/04-driver-and-cli.md` section 4.4.
///
/// GCC spells these as letters packed into one flag, so `-dDI` is two of them, and a letter it
/// does not know is ignored rather than rejected. That last part is deliberate on GCC's side
/// and worth copying: the family is a debugging aid and a build that passes `-dumpbase` should
/// not die on the `-d`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Dumps {
    /// `-dM`. Print the macros that are defined at the end, and nothing else.
    pub macros: bool,
}

impl Dumps {
    /// The letters GCC's preprocessor takes after `-d`.
    ///
    /// `M` is the macros, `D` is the macros in place, `N` is their names only, `I` is the
    /// `#include` lines and `U` is the macros as they are used. Only `M` does anything so far.
    const LETTERS: &'static str = "MDNIU";

    /// Whether `arg` is a flag from this family rather than something else beginning with
    /// `-d`.
    ///
    /// The check is here rather than in the driver so that the set of letters and the set of
    /// flags accepted cannot drift apart. It matters because `-dumpversion` also begins with
    /// `-d`, and a family that swallowed every such flag would turn a flag we have not written
    /// into a dump of nothing.
    #[must_use]
    pub fn is_family(arg: &str) -> bool {
        match arg.strip_prefix("-d") {
            Some("") | None => false,
            Some(letters) => letters.chars().all(|c| Dumps::LETTERS.contains(c)),
        }
    }

    /// Reads the letters after `-d`, ignoring the ones we do not implement yet.
    pub fn add(&mut self, letters: &str) {
        for letter in letters.chars() {
            if letter == 'M' {
                self.macros = true;
            }
        }
    }

    /// Whether anything at all was asked for.
    #[must_use]
    pub const fn any(self) -> bool {
        self.macros
    }
}

/// Everything a compilation was asked to do.
///
/// Options are a plain value with no interior mutability, so a caller can build one, clone
/// it, tweak one field and run a second compilation, which is exactly what the differential
/// testing in `spec/15-testing.md` needs.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Options {
    /// The target to generate code for.
    pub target: Triple,
    /// The optimisation level.
    pub opt_level: OptLevel,
    /// How much of the memory safety monitor is on, from `-fsafety=`.
    ///
    /// Off unless it was asked for. A program built without the flag is compiled by exactly the
    /// pipeline it was compiled by before the monitor existed, which is the only way the feature
    /// can be developed in the open without every build paying for it.
    pub safety: Safety,
    /// What to produce.
    pub emit: EmitKind,
    /// Whether to emit debug information.
    pub debug_info: bool,
    /// Whether every function keeps a frame pointer, from `-fno-omit-frame-pointer`.
    ///
    /// Off by default, which is what gcc does at every level above `-O0` and what leaves the
    /// register free for the allocator. A profiler that walks the stack by following saved frame
    /// pointers needs it on, and so does any code a debugger has to unwind without unwind tables.
    pub frame_pointer: bool,
    /// Whether the red zone may be used, from `-mno-red-zone` turned around.
    ///
    /// The 128 bytes below the stack pointer that the System V psABI promises no signal handler
    /// will touch, which lets a small leaf function keep its locals without moving the stack
    /// pointer at all. A kernel turns this off, because an interrupt taken on the kernel stack
    /// makes the promise false, and every kernel build in the wild passes `-mno-red-zone` for
    /// exactly that reason. A convention without a red zone ignores this.
    pub red_zone: bool,
    /// Whether warnings are errors.
    pub warnings_are_errors: bool,
    /// Whether a warning is raised at all, which is `-w` turned around.
    ///
    /// A build that passes this has decided it does not want to hear about anything that is not
    /// fatal, and the flag is dropped at the one place every diagnostic goes through rather than
    /// tested at each site that raises one. `-w` beats `-Werror` where both are given, because a
    /// warning that was never raised cannot be promoted.
    pub warnings: bool,
    /// How many diagnostics to print before giving up. Past a certain point the output is
    /// noise from a single earlier mistake, and GCC's default of no limit is not a kindness.
    pub error_limit: u32,
    /// The dialect, from `-std=`.
    pub std: Std,
    /// Whether the GNU extensions are on, which is `-std=gnu23` rather than `-std=c23`.
    pub gnu_extensions: bool,
    /// Whether `-pedantic` was given, which is what turns a use of an extension from silence
    /// into a diagnostic. It is not the same knob as the dialect: `-std=c17 -pedantic` warns
    /// about a construct that `-std=c17` alone accepts without a word.
    pub pedantic: bool,
    /// Whether the whole unit is under GNU's reading of `inline` rather than C's, which is
    /// `-fgnu89-inline`.
    ///
    /// Under C's reading a definition every file-scope declaration wrote `inline` for and none
    /// wrote `extern` for emits nothing, and under GNU's it is the definition alone that decides
    /// and `extern inline` is the one that emits nothing. The C89 dialects are under GNU's
    /// whatever this says, since that is where the older reading came from, so this is the flag a
    /// program written against it reaches for when it is being compiled under a later dialect.
    pub gnu89_inline: bool,
    /// The GCC release claimed, from `-fgnuc-version=`.
    pub gnuc: GnucVersion,
    /// Whether there is a standard library, which is `-ffreestanding` turned around.
    pub hosted: bool,
    /// Whether a call to a C library function written under its own plain name may be taken to
    /// mean that function, which is `-fno-builtin` turned around.
    ///
    /// The names are reserved, so `llabs` is the library's `llabs` and the compiler is allowed to
    /// know what it does. A program that means something else by one of them is the reason the
    /// flag exists, and `-ffreestanding` turns it off as well, because a freestanding program has
    /// no C library for the name to be the name of. The `__builtin_` spellings are not affected by
    /// either, since the prefix is the program saying which function it means.
    pub builtins: bool,
    /// The names `-fno-builtin-<name>` took away one at a time, without the prefix.
    ///
    /// A build that means its own `memcpy` and the library's everything else writes this rather
    /// than the whole flag, which is what the kernel does for a handful of names.
    pub no_builtin: Vec<String>,
    /// `-D` in command line order. `FOO` means `FOO=1`, as GCC has it.
    pub defines: Vec<String>,
    /// `-U` in command line order, applied after the defines because `-U` wins.
    pub undefines: Vec<String>,
    /// Where a header is looked for.
    pub search: SearchPath,
    /// Whether `-E` writes line markers, which `-P` turns off.
    pub line_markers: bool,
    /// What the `-d` family asks for.
    pub dumps: Dumps,
    /// What `-f<pass>` and `-fno-<pass>` said about an optimizer pass, in the order the command
    /// line said it, so that the last mention of a pass is the one that decides.
    ///
    /// The pipeline the level chose is the starting point and this is what is added to and taken
    /// away from it. The names are checked against the pass list while the arguments are parsed,
    /// so anything in here is a pass the compiler has.
    pub passes: Vec<(String, bool)>,
    /// What `-fpass-fuel=<pass>=<n>` limited a pass to, by pass name.
    ///
    /// A pass with an entry here performs exactly that many transformations and then stops
    /// transforming, which is what bisects a miscompilation to one rewrite. See section 9.10 of
    /// `spec/09-optimizer.md`.
    pub pass_fuel: Vec<(String, u32)>,
    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
    ///
    /// The outer of the two searches in section 4.5 of `spec/optimizer/04-pass-manager.md`.
    /// Halving this says which pass holds the bad rewrite, and halving `-fpass-fuel` for that
    /// pass says which rewrite it is. Where both are given, a pass is stopped by whichever of
    /// the two is tighter.
    pub pass_fuel_global: Option<u32>,
    /// What `-fdisable-<pass>[=<range>]` and `-fenable-<pass>[=<range>]` said, in the order the
    /// command line said it, with `true` for the enabling half.
    ///
    /// A rule covers the functions it names and nothing else, and the last rule that covers a
    /// function is the one that decides for it, so the order has to survive. This is the second
    /// half of the bisection interface in section 41.6 of `spec/optimizer/41-correctness.md`:
    /// `-fpass-fuel` finds the rewrite and this finds the function. The pass names are checked
    /// against the pass list while the arguments are parsed.
    pub pass_gates: Vec<(bool, String)>,
    /// What `-fdump-ir=` asked to see, as it was written, which is `all`, `before-<pass>` or
    /// `after-<pass>`.
    pub dump_ir: Vec<String>,
    /// What `-fopt-info` asked to hear about, as the keywords were written, with the leading
    /// hyphen taken off, so a bare `-fopt-info` is the empty string in here.
    ///
    /// The keywords are `optimized`, `missed`, `note` and `all`, and two flags add up rather than
    /// the second replacing the first. Checked while the arguments are parsed, so anything in
    /// here is a spelling the optimizer understands. See section 42.2 of
    /// `spec/optimizer/42-measurement.md` for why `missed` is the one that earns the feature.
    pub opt_info: Vec<String>,
    /// Where `-fopt-info=<file>` sends the remarks, or `None` for standard error.
    ///
    /// One file for the whole run rather than one per input, the way GCC does it, and the last
    /// one on the command line is the one that decides. A harness that wants the remarks kept
    /// away from the diagnostics gives a file, which is what the corpus in `tamnd/rucc-corpus`
    /// does with GCC so that a rejection can still be matched against the diagnostic stream.
    pub opt_info_file: Option<String>,
    /// Whether the IR verifier runs after every pass that changed anything.
    ///
    /// On in a debug build without being asked, since that is where a broken pass should be
    /// caught. `-Zverify-each` turns it on in a release build, which is what CI wants.
    pub verify_each: bool,
    /// Where `-Zrule-coverage=FILE` writes which lowering rules fired, if it was given.
    ///
    /// A measurement rather than a thing a build asks for, which is why it is spelled with a `-Z`
    /// the way an unstable option is everywhere else: it is here for the harness in
    /// `tamnd/rucc-compat` to union over a corpus and report, and nothing about the code that comes
    /// out changes when it is on. One file per run of the compiler, holding the whole rule set with
    /// the rules this run reached marked, whatever the run compiled and however many files it was.
    pub rule_coverage: Option<String>,
}

impl Options {
    /// Default options for `target`.
    pub fn new(target: Triple) -> Self {
        Self {
            target,
            opt_level: OptLevel::default(),
            safety: Safety::default(),
            emit: EmitKind::default(),
            debug_info: false,
            frame_pointer: false,
            red_zone: true,
            warnings_are_errors: false,
            warnings: true,
            error_limit: 20,
            std: Std::default(),
            gnu_extensions: true,
            pedantic: false,
            gnu89_inline: false,
            gnuc: GnucVersion::default(),
            hosted: true,
            builtins: true,
            no_builtin: Vec::new(),
            defines: Vec::new(),
            undefines: Vec::new(),
            search: SearchPath::new(),
            line_markers: true,
            dumps: Dumps::default(),
            passes: Vec::new(),
            pass_fuel: Vec::new(),
            pass_fuel_global: None,
            pass_gates: Vec::new(),
            dump_ir: Vec::new(),
            opt_info: Vec::new(),
            opt_info_file: None,
            verify_each: cfg!(debug_assertions),
            rule_coverage: None,
        }
    }
}

/// One compilation.
///
/// Holds the options, the string interner and the diagnostics raised so far. Passing a
/// `&mut Session` is how a stage reports a problem, and the return value of a stage says
/// what it produced, never whether it succeeded: that question is answered by
/// [`Session::has_errors`].
#[derive(Debug)]
pub struct Session {
    /// What this compilation was asked to do.
    pub opts: Options,
    /// Everything known about the target.
    pub target: TargetInfo,
    /// The one interner for the compilation.
    pub interner: Interner,
    /// Every file read during the compilation, and the flat coordinate space their spans
    /// live in.
    ///
    /// This is on the session rather than passed around separately because a span is only
    /// meaningful against the map that issued it, and one map per compilation is the rule
    /// that makes that true by construction.
    pub sources: SourceMap,
    diagnostics: Vec<Diagnostic>,
    error_count: u32,
    warning_count: u32,
}

impl Session {
    /// A session for `opts`.
    pub fn new(opts: Options) -> Self {
        let target = TargetInfo::new(opts.target);
        Self {
            opts,
            target,
            interner: Interner::with_capacity(1024),
            sources: SourceMap::new(),
            diagnostics: Vec::new(),
            error_count: 0,
            warning_count: 0,
        }
    }

    /// Records a diagnostic.
    ///
    /// Under `-Werror` a warning is promoted here, once, rather than at every site that
    /// raises one, and under `-w` it is dropped here for the same reason. A warning that `-w`
    /// dropped is not counted, so `-w -Werror` compiles rather than failing on a warning
    /// nobody was going to see.
    pub fn emit(&mut self, mut diag: Diagnostic) {
        if !self.opts.warnings && diag.severity == Severity::Warning {
            return;
        }
        if self.opts.warnings_are_errors && diag.severity == Severity::Warning {
            diag.severity = Severity::Error;
        }
        match diag.severity {
            Severity::Error | Severity::Ice => self.error_count += 1,
            Severity::Warning => self.warning_count += 1,
            Severity::Note | Severity::Help => {}
        }
        self.diagnostics.push(diag);
    }

    /// Everything raised so far, in the order it was raised.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Whether anything fatal has been raised.
    pub fn has_errors(&self) -> bool {
        self.error_count > 0
    }

    /// How many errors have been raised.
    pub fn error_count(&self) -> u32 {
        self.error_count
    }

    /// How many warnings have been raised.
    pub fn warning_count(&self) -> u32 {
        self.warning_count
    }

    /// Whether the error limit has been reached and the caller should stop.
    pub fn error_limit_reached(&self) -> bool {
        self.opts.error_limit != 0 && self.error_count >= self.opts.error_limit
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn session() -> Session {
        Session::new(Options::new("x86_64-unknown-linux-gnu".parse().unwrap()))
    }

    #[test]
    fn a_version_claim_reads_the_way_gcc_prints_one() {
        // `gcc -dumpfullversion` gives all three, `gcc -dumpversion` gives one, and both are
        // things a script pastes straight into a flag.
        let all = |v: &str| v.parse::<GnucVersion>().unwrap();
        assert_eq!(all("15.1.0"), GnucVersion { major: 15, minor: 1, patch: 0 });
        assert_eq!(all("15"), GnucVersion { major: 15, minor: 0, patch: 0 });
        assert_eq!(all("4.2"), GnucVersion { major: 4, minor: 2, patch: 0 });
        assert!("".parse::<GnucVersion>().is_err());
        assert!("15.".parse::<GnucVersion>().is_err(), "a trailing dot is a typo, not a zero");
        assert!("1.2.3.4".parse::<GnucVersion>().is_err());
    }

    #[test]
    fn optimisation_levels_parse_the_way_gcc_spells_them() {
        assert_eq!("".parse::<OptLevel>().unwrap(), OptLevel::O1);
        assert_eq!("0".parse::<OptLevel>().unwrap(), OptLevel::O0);
        assert_eq!("2".parse::<OptLevel>().unwrap(), OptLevel::O2);
        assert_eq!("9".parse::<OptLevel>().unwrap(), OptLevel::O3);
        assert_eq!("s".parse::<OptLevel>().unwrap(), OptLevel::Os);
        assert!("q".parse::<OptLevel>().is_err());
    }

    #[test]
    fn only_o0_skips_the_optimizer() {
        assert!(!OptLevel::O0.runs_optimizer());
        assert!(OptLevel::O1.runs_optimizer());
        assert!(OptLevel::Oz.runs_optimizer());
    }

    #[test]
    fn the_safety_tiers_round_trip_and_nothing_else_is_one() {
        for tier in [Safety::Off, Safety::Detect, Safety::Enforce, Safety::Kernel] {
            assert_eq!(tier.as_str().parse::<Safety>().unwrap(), tier);
        }
        // `on` is the obvious thing to try and it is not a tier, because which tier somebody
        // means by it is the whole question document 02 answers.
        assert!("on".parse::<Safety>().is_err());
        assert!("".parse::<Safety>().is_err());
    }

    #[test]
    fn a_build_that_did_not_ask_for_the_monitor_does_not_get_it() {
        assert_eq!(Safety::default(), Safety::Off);
        assert!(!Safety::Off.instruments());
        assert!(Safety::Detect.instruments());
        assert!(Safety::Enforce.instruments());
        assert!(Safety::Kernel.instruments());
    }

    #[test]
    fn emit_kinds_round_trip_through_their_names() {
        for k in [
            EmitKind::Executable,
            EmitKind::Object,
            EmitKind::Asm,
            EmitKind::Preprocessed,
            EmitKind::Tast,
            EmitKind::Ir,
            EmitKind::MirFinal,
        ] {
            assert_eq!(k.as_str().parse::<EmitKind>().unwrap(), k);
        }
    }

    #[test]
    fn errors_are_counted_and_warnings_are_not() {
        let mut s = session();
        s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
        assert_eq!(s.error_count(), 1);
        assert_eq!(s.warning_count(), 1);
        assert!(s.has_errors());
        assert_eq!(s.diagnostics().len(), 2);
    }

    #[test]
    fn werror_promotes_once_at_the_sink() {
        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
        opts.warnings_are_errors = true;
        let mut s = Session::new(opts);
        s.emit(Diagnostic::warning("hmm", rucc_diag::Span::DUMMY));
        assert_eq!(s.error_count(), 1);
        assert_eq!(s.warning_count(), 0);
        assert_eq!(s.diagnostics()[0].severity, Severity::Error);
    }

    #[test]
    fn the_error_limit_can_be_switched_off() {
        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse().unwrap());
        opts.error_limit = 0;
        let mut s = Session::new(opts);
        for _ in 0..100 {
            s.emit(Diagnostic::error("no", rucc_diag::Span::DUMMY));
        }
        assert!(!s.error_limit_reached());
    }

    #[test]
    fn the_session_carries_the_source_map_spans_are_resolved_against() {
        let mut s = session();
        let file = s.sources.add("a.c", b"int x;\n".to_vec()).unwrap();
        let start = s.sources.file(file).start;
        assert_eq!(s.sources.render_position(start + 4), "a.c:1:5");
    }

    #[test]
    fn the_session_carries_the_resolved_target() {
        let s = session();
        assert_eq!(s.target.pointer_width, 64);
        assert!(s.target.char_is_signed);
    }
}