rucc-driver 0.10.18

Command line, phase graph and job scheduling 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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
//! The phase graph: what has to happen to each input file, in what order, and where the
//! result goes.
//!
//! Design: `spec/04-driver-and-cli.md` section 4.2.
//!
//! The plan is computed before anything runs and is a plain data structure with no side
//! effects, which is what makes `-###` possible and what makes this testable without a file
//! system. Nothing in here reads a file or spawns a process. Executing the plan is M3, when
//! there is something for the phases to do.

use std::fmt::Write as _;

use rucc_session::{EmitKind, Options, SaveTemps};
use rucc_target::Os;

use crate::link::Item;

/// A step in the compilation of one input.
///
/// The order of the variants is the order of the pipeline, and the derived `Ord` is relied on
/// when a mode flag truncates a sequence. `Compile` covers parsing through code generation,
/// which is one phase from the driver's point of view because nothing between them can be
/// stopped at from the command line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Phase {
    /// Translation phases 1 to 4, producing preprocessed source.
    Preprocess,
    /// Parse, check, optimize and generate code, producing assembly.
    Compile,
    /// Assemble, producing an object file.
    Assemble,
    /// Link the objects into an executable or a shared library.
    Link,
}

impl Phase {
    /// The name used in `-###` output and in diagnostics.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Phase::Preprocess => "preprocess",
            Phase::Compile => "compile",
            Phase::Assemble => "assemble",
            Phase::Link => "link",
        }
    }
}

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

/// What an input file is, which decides where in the pipeline it enters.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InputKind {
    /// C source. Extension `.c`, or `-x c`.
    C,
    /// A header compiled on its own. Extension `.h` with `-x c-header`, or `-x c-header`.
    CHeader,
    /// Already preprocessed C. Extension `.i`, or `-x cpp-output`.
    PreprocessedC,
    /// The IR this compiler prints. Extension `.ir`, or `-x ir`.
    ///
    /// Not a GCC input kind, because GCC has no textual IR. It is here because the IR's
    /// printer and its parser are a pair, and a pair is only known to agree if something reads
    /// back what was written: `rucc --emit=ir a.c -o a.ir` and then `rucc --emit=ir a.ir` are
    /// two files a byte comparison has an opinion about, over whatever code is at hand rather
    /// than over the modules a test happens to build.
    Ir,
    /// Assembly. Extension `.s`, or `-x assembler`.
    Assembler,
    /// Assembly that still needs the preprocessor. Extension `.S` or `.sx`, or
    /// `-x assembler-with-cpp`.
    AssemblerWithCpp,
    /// An object file, an archive or a shared library. Anything the linker takes directly.
    LinkerInput,
}

impl InputKind {
    /// The name `-x` uses for this kind, where one exists.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            InputKind::C => "c",
            InputKind::CHeader => "c-header",
            InputKind::PreprocessedC => "cpp-output",
            InputKind::Ir => "ir",
            InputKind::Assembler => "assembler",
            InputKind::AssemblerWithCpp => "assembler-with-cpp",
            InputKind::LinkerInput => "linker-input",
        }
    }

    /// Parses the argument of `-x`.
    ///
    /// # Errors
    ///
    /// Returns the offending name when it is not one we accept. C++ gets its own message,
    /// because "unknown language c++" reads like an oversight and it is a decision.
    pub fn from_x_arg(name: &str) -> Result<InputKind, XError> {
        match name {
            "c" => Ok(InputKind::C),
            "c-header" => Ok(InputKind::CHeader),
            "cpp-output" | "c-cpp-output" => Ok(InputKind::PreprocessedC),
            "ir" => Ok(InputKind::Ir),
            "assembler" => Ok(InputKind::Assembler),
            "assembler-with-cpp" => Ok(InputKind::AssemblerWithCpp),
            "c++" | "c++-header" | "c++-cpp-output" | "objective-c" | "objective-c++" => {
                Err(XError::Unsupported(name.to_owned()))
            }
            _ => Err(XError::Unknown(name.to_owned())),
        }
    }

    /// Classifies an input by its extension, the way `spec/04-driver-and-cli.md` section 4.2
    /// tabulates it.
    ///
    /// An unrecognized extension is a linker input, which is GCC's behavior and is what makes
    /// `rucc foo.o bar.builtin-suffix` work. The exception is a C++ extension, which is a
    /// hard error rather than a confusing link failure later.
    ///
    /// # Errors
    ///
    /// Returns the extension when it names a language that is permanently out of scope.
    pub fn from_path(path: &str) -> Result<InputKind, XError> {
        let ext = extension(path);
        match ext {
            // Matched case-sensitively on purpose: `.S` and `.s` are different languages and
            // conflating them is a real bug on case-insensitive file systems that GCC also
            // has. The comment is here so the next person does not "fix" it.
            "c" => Ok(InputKind::C),
            "i" => Ok(InputKind::PreprocessedC),
            "ir" => Ok(InputKind::Ir),
            "h" => Ok(InputKind::CHeader),
            "s" => Ok(InputKind::Assembler),
            "S" | "sx" => Ok(InputKind::AssemblerWithCpp),
            "cc" | "cpp" | "cxx" | "c++" | "C" | "hpp" | "hxx" | "ii" | "m" | "mm" => {
                Err(XError::Unsupported(ext.to_owned()))
            }
            _ => Ok(InputKind::LinkerInput),
        }
    }

    /// The full phase sequence for this kind, before any mode flag truncates it.
    fn full_sequence(self) -> &'static [Phase] {
        use Phase::{Assemble, Compile, Link, Preprocess};
        match self {
            InputKind::C | InputKind::CHeader => &[Preprocess, Compile, Assemble, Link],
            InputKind::PreprocessedC | InputKind::Ir => &[Compile, Assemble, Link],
            // Note the gap: assembly with a preprocessor skips `Compile` entirely. This is why
            // the sequence is a list rather than a range over the enum.
            InputKind::AssemblerWithCpp => &[Preprocess, Assemble, Link],
            InputKind::Assembler => &[Assemble, Link],
            InputKind::LinkerInput => &[Link],
        }
    }
}

/// Why an input or an `-x` argument was rejected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum XError {
    /// A language we do not know at all.
    Unknown(String),
    /// A language we know and will not implement.
    Unsupported(String),
}

impl std::fmt::Display for XError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XError::Unknown(name) => {
                write!(
                    f,
                    "unknown language `{name}`; \
                     accepted: c, c-header, cpp-output, ir, assembler, assembler-with-cpp, none"
                )
            }
            XError::Unsupported(name) => {
                write!(
                    f,
                    "`{name}` is not C, and this compiler is only ever going to compile C; \
                     see the not-in-scope list in spec/00-README.md"
                )
            }
        }
    }
}

impl std::error::Error for XError {}

/// One input file, with the `-x` setting that was in effect where it appeared.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Input {
    /// The path as it was written on the command line, or the name of a `-l` library.
    pub path: String,
    /// The language forced by an earlier `-x`, if any. `-x none` clears it.
    pub forced: Option<InputKind>,
    /// Whether this came from `-l<name>` rather than being a path.
    ///
    /// A library is an input to the link and is held here rather than beside the other link
    /// flags, because where it falls among the objects is what decides whether it is searched
    /// for what they left undefined. A list of objects and a separate list of libraries would
    /// lose exactly that.
    pub library: bool,
}

impl Input {
    /// An input with no `-x` in effect.
    #[must_use]
    pub fn new(path: impl Into<String>) -> Input {
        Input { path: path.into(), forced: None, library: false }
    }

    /// `-l<name>`, which is an input to the link and to nothing else.
    #[must_use]
    pub fn library(name: impl Into<String>) -> Input {
        Input { path: name.into(), forced: None, library: true }
    }

    /// What this input is, taking `-x` into account.
    ///
    /// # Errors
    ///
    /// Returns the extension when it names a language that is out of scope.
    pub fn kind(&self) -> Result<InputKind, XError> {
        if self.library {
            return Ok(InputKind::LinkerInput);
        }
        match self.forced {
            Some(k) => Ok(k),
            None => InputKind::from_path(&self.path),
        }
    }
}

/// Where the result of a job goes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Output {
    /// Standard output, which is where `-E` writes when there is no `-o`.
    Stdout,
    /// A path the user can see and named, or that we derived from the input name.
    File(String),
    /// A file the link step consumes and nothing else ever sees. The name is a hint for
    /// `-###` output; the real path is chosen in a temporary directory at execution time.
    Temporary(String),
}

impl Output {
    fn render(&self) -> String {
        match self {
            Output::Stdout => "-".to_owned(),
            Output::File(p) => p.clone(),
            Output::Temporary(p) => format!("{p} (temporary)"),
        }
    }

    /// The path the link step reads, for an output that feeds it.
    fn as_link_input(&self) -> Option<&str> {
        match self {
            Output::File(p) | Output::Temporary(p) => Some(p),
            Output::Stdout => None,
        }
    }
}

/// Everything that has to happen to one input file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
    /// The input path as written.
    pub input: String,
    /// What we decided it is.
    pub kind: InputKind,
    /// The phases to run, in order. Empty when the input goes straight to the linker.
    pub phases: Vec<Phase>,
    /// Where the last phase writes.
    pub output: Output,
    /// What the files `-save-temps` keeps are called, without the suffix that says which one it
    /// is, or `None` when there is nothing to keep.
    ///
    /// Nothing to keep is the usual case: the flag was not given, or it was and this job has no
    /// step whose result the compilation would have thrown away. `-E -save-temps` is the second
    /// of those, since the preprocessed text is the output and is already being written.
    pub aux_base: Option<String>,
}

impl Job {
    /// Where the preprocessed text goes when `-save-temps` asked for it to be kept.
    ///
    /// `None` when the flag was not given, when the input arrives preprocessed already and there
    /// is no phase 4 to keep the result of, or when the text is this job's own output and is
    /// being written anyway.
    #[must_use]
    pub fn saved_text(&self) -> Option<String> {
        let base = self.aux_base.as_ref()?;
        self.phases.contains(&Phase::Preprocess).then(|| format!("{base}.i"))
    }

    /// Where the assembly goes when `-save-temps` asked for it to be kept.
    ///
    /// `None` for the same reasons, the last of them being `-S`: the assembly is the output
    /// there, and a copy of it under a second name is a file nobody asked for.
    #[must_use]
    pub fn saved_asm(&self) -> Option<String> {
        let base = self.aux_base.as_ref()?;
        let past = self.phases.last().is_some_and(|last| *last > Phase::Compile);
        (past && self.phases.contains(&Phase::Compile)).then(|| format!("{base}.s"))
    }
}

/// The link step, when there is one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkJob {
    /// Objects and libraries, in command line order, because link order is semantic.
    pub inputs: Vec<Item>,
    /// The executable.
    pub output: String,
}

/// The whole plan for one invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
    /// One per input, in command line order.
    pub jobs: Vec<Job>,
    /// The link step, or `None` when a mode flag stopped short of it.
    pub link: Option<LinkJob>,
    /// Things worth saying under `-v` that are not errors, such as an object file passed on a
    /// command line that is not linking.
    pub notes: Vec<String>,
    /// The argument of `-o` as it was written, if it was given.
    ///
    /// Kept alongside the paths it produced because the `-M` family needs the name rather than
    /// the path: a make rule whose target is the object the build asked for is one the build
    /// can read back, and a rule naming a temporary directory is one nothing will ever match.
    pub output: Option<String>,
}

/// Why a command line could not be turned into a plan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanError {
    /// Lowercase, no trailing period, the same shape as every other diagnostic.
    pub message: String,
}

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

impl std::error::Error for PlanError {}

fn plan_err(message: impl Into<String>) -> PlanError {
    PlanError { message: message.into() }
}

/// The last phase that runs, given what the user asked to be emitted.
///
/// `--emit=tast` and the other intermediate dumps stop where `-S` stops, because they are
/// produced inside the compile phase and there is nothing after them to run.
#[must_use]
pub fn last_phase(emit: EmitKind) -> Phase {
    match emit {
        EmitKind::Preprocessed => Phase::Preprocess,
        EmitKind::Asm
        | EmitKind::Tast
        | EmitKind::Ir
        | EmitKind::MirFinal
        | EmitKind::SafetySummary
        | EmitKind::TypeGranules => Phase::Compile,
        EmitKind::Object => Phase::Assemble,
        EmitKind::Executable => Phase::Link,
    }
}

/// The extension of a path, without the dot, or the empty string when there is none.
fn extension(path: &str) -> &str {
    let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
    match name.rfind('.') {
        // A leading dot is a hidden file, not an extension, and `.` and `..` are not inputs.
        Some(0) | None => "",
        Some(i) => &name[i + 1..],
    }
}

/// The last component of a path, which is the whole of it when there is no directory in it.
fn file_part(path: &str) -> &str {
    path.rsplit(['/', '\\']).next().unwrap_or(path)
}

/// The path with its extension taken off and its directory left on.
///
/// This is what a name derived from `-o` is built on, since `-o out/a.o` puts the files that go
/// beside the object in `out` and not in the working directory.
fn without_extension(path: &str) -> &str {
    let start = path.rfind(['/', '\\']).map_or(0, |i| i + 1);
    match path[start..].rfind('.') {
        // A leading dot is a hidden file, not an extension, and `.` and `..` are not inputs.
        Some(0) | None => path,
        Some(i) => &path[..start + i],
    }
}

/// The path without its extension, keeping any directory part off, because GCC writes the
/// output into the current directory rather than next to the source.
fn stem(path: &str) -> &str {
    file_part(without_extension(path))
}

/// The name the files `-save-temps` keeps are built from, without the suffix that says which
/// one it is.
///
/// GCC calls this the auxiliary base name, and it is the name of the file the compilation
/// produces with the extension taken off: `-c a.c -o out/a.o` keeps `out/a.i` and `out/a.s`. A
/// command line that links has one output for however many inputs, so the input's own name goes
/// on the end and `a.c` under `-o out/prog` becomes `out/prog-a`. `-save-temps=cwd` is the same
/// name with the directory taken off, which is the only thing the two spellings disagree about.
fn aux_base(opts: &Options, input: &str, output: Option<&str>, linking: bool) -> String {
    let named = match output {
        Some(o) => without_extension(o),
        // No `-o`, so the job worked its own name out, and a worked out name has no directory in
        // it: the object of `sub/a.c` is `a.o` in the working directory, so what is kept beside
        // it is in the working directory too.
        None if linking => stem(default_exe(opts)),
        None => stem(input),
    };
    let named = if opts.save_temps == SaveTemps::Cwd { file_part(named) } else { named };
    if linking { format!("{named}-{}", stem(input)) } else { named.to_owned() }
}

/// The suffix a phase's output carries, for this target.
fn suffix_for(phase: Phase, opts: &Options) -> &'static str {
    match phase {
        Phase::Preprocess => "i",
        // The compile phase is where every intermediate dump comes out, and each of them is a
        // different language, so each gets a name of its own. `rucc --emit=tast a.c` writing
        // `a.s` would be a file that neither an assembler nor a reader could make sense of.
        Phase::Compile => match opts.emit {
            EmitKind::Tast => "tast",
            EmitKind::Ir => "ir",
            EmitKind::MirFinal => "mir",
            // Two extensions rather than one, because the content is JSON and a tool that reads
            // JSON should be able to tell by looking, and because `a.json` next to `a.c` says
            // nothing about which of a build's several JSON files it is.
            EmitKind::SafetySummary => "safety.json",
            // Two extensions for the same reason, and text rather than JSON because this one
            // is read by a person once and not by a build every time.
            EmitKind::TypeGranules => "granules.txt",
            _ => "s",
        },
        // MSVC-targeted builds expect `.obj`, and build systems written for that target look
        // for it by name.
        Phase::Assemble => {
            if opts.target.os == Os::Windows {
                "obj"
            } else {
                "o"
            }
        }
        Phase::Link => "",
    }
}

/// The default name of the linked output, which is GCC's `a.out` everywhere but Windows.
fn default_exe(opts: &Options) -> &'static str {
    if opts.target.os == Os::Windows { "a.exe" } else { "a.out" }
}

impl Plan {
    /// Builds the plan for one invocation.
    ///
    /// `output` is the argument of `-o`, if it was given.
    ///
    /// # Errors
    ///
    /// Returns a message when the inputs and the mode flags do not describe a compilation:
    /// an out of scope language, `-o` naming one file for several outputs, or nothing to do.
    pub fn new(opts: &Options, inputs: &[Input], output: Option<&str>) -> Result<Plan, PlanError> {
        if inputs.is_empty() {
            return Err(plan_err("no input files"));
        }
        let last = last_phase(opts.emit);
        let linking = last == Phase::Link;

        let mut kinds = Vec::with_capacity(inputs.len());
        for input in inputs {
            kinds.push(input.kind().map_err(|e| plan_err(format!("{}: {e}", input.path)))?);
        }

        // How many inputs actually write an output of their own. A `.o` on a `-c` line
        // produces nothing, and neither does a `.s` on an `-E` line, so neither may count
        // toward the `-o` check below. When linking there is exactly one output and it is the
        // executable, so nothing counts.
        let producing = if linking {
            0
        } else {
            kinds
                .iter()
                .filter(|k| **k != InputKind::LinkerInput)
                .filter(|k| k.full_sequence().iter().any(|p| *p <= last))
                .count()
        };
        if output.is_some() && !linking && producing > 1 {
            return Err(plan_err("cannot specify -o with multiple inputs when not linking"));
        }

        let mut notes = Vec::new();
        let mut jobs = Vec::with_capacity(inputs.len());
        let mut link_inputs = Vec::new();

        for (input, kind) in inputs.iter().zip(kinds) {
            // An object, an archive or a shared library has nothing done to it. It reaches the
            // linker under the name it was written with, and its name is not derived from
            // anything, which is why this case is separate rather than falling out of the
            // sequence below. Deriving it would rewrite `libm.a` into `libm.o`.
            if kind == InputKind::LinkerInput {
                if linking {
                    link_inputs.push(if input.library {
                        Item::Library(input.path.clone())
                    } else {
                        Item::File(input.path.clone())
                    });
                } else {
                    // GCC warns and carries on here, and configure scripts rely on that, so
                    // this is a note rather than an error.
                    notes.push(format!(
                        "{}: linker input unused because linking was not requested",
                        if input.library {
                            format!("-l{}", input.path)
                        } else {
                            input.path.clone()
                        }
                    ));
                }
                // A library is not a file this compilation does anything to, so it gets no job.
                // One would print a line under `-###` saying nothing happens to it, next to the
                // note above already saying so.
                if input.library {
                    continue;
                }
                jobs.push(Job {
                    input: input.path.clone(),
                    kind,
                    phases: Vec::new(),
                    output: Output::File(input.path.clone()),
                    aux_base: None,
                });
                continue;
            }

            let phases: Vec<Phase> =
                kind.full_sequence().iter().copied().filter(|p| *p <= last).collect();
            // `rucc -E a.s` lands here: assembly enters at `Assemble`, which is past where
            // `-E` stops, so there is no phase left to run. GCC carries on rather than
            // failing, and so do we.
            let Some(&final_phase) = phases.last() else {
                notes.push(format!(
                    "{}: input unused because it enters the pipeline after the last phase \
                     the mode flags asked for",
                    input.path
                ));
                jobs.push(Job {
                    input: input.path.clone(),
                    kind,
                    phases,
                    output: Output::File(input.path.clone()),
                    aux_base: None,
                });
                continue;
            };
            let named = if producing == 1 { output } else { None };
            // A job that stops at the preprocessed text has nothing to keep, since that text is
            // what it writes. Everything past it does: the text and, once there is a back end
            // step after it, the assembly.
            let aux = (opts.save_temps.wanted() && final_phase > Phase::Preprocess)
                .then(|| aux_base(opts, &input.path, output, linking));
            let out = if final_phase == Phase::Link {
                // The job stops at the object, and the link step below takes it from here. Under
                // `-save-temps` the object is one of the files being kept, so it is written where
                // the person can see it rather than in a directory that goes away.
                let ext = suffix_for(Phase::Assemble, opts);
                match &aux {
                    Some(base) => Output::File(format!("{base}.{ext}")),
                    None => Output::Temporary(format!("{}.{ext}", stem(&input.path))),
                }
            } else if let Some(o) = named {
                // `-o -` is standard output rather than a file of that name, which is what gcc
                // does for everything it compiles, the object file included. Its link step is
                // the exception and writes a file called `-`, because the name goes to the
                // linker and the linker takes it literally.
                if o == "-" { Output::Stdout } else { Output::File(o.to_owned()) }
            } else if final_phase == Phase::Preprocess {
                // `-E` writes to standard output unless it was given a name, which is the one
                // place where the default is not a file.
                Output::Stdout
            } else {
                Output::File(format!("{}.{}", stem(&input.path), suffix_for(final_phase, opts)))
            };
            // An input whose output has the name it has itself would be read and then written
            // over, and what it held would be gone. GCC compares the two names the way they
            // were written and so does this, which catches `rucc --emit=ir a.ir` and leaves
            // the same file reached by two different paths to the file system.
            if let Output::File(path) = &out {
                if *path == input.path {
                    return Err(plan_err(format!(
                        "input file `{}` is the same as the output file",
                        input.path
                    )));
                }
            }

            if linking {
                if let Some(p) = out.as_link_input() {
                    link_inputs.push(Item::File(p.to_owned()));
                }
            }
            jobs.push(Job { input: input.path.clone(), kind, phases, output: out, aux_base: aux });
        }

        let link = linking.then(|| LinkJob {
            inputs: link_inputs,
            output: output.unwrap_or(default_exe(opts)).to_owned(),
        });

        Ok(Plan { jobs, link, notes, output: output.map(str::to_owned) })
    }

    /// Renders the plan the way `-###` prints it.
    ///
    /// One line per job, then the link line. This is meant to be read next to `gcc -###`
    /// output when a build behaves differently under the two compilers, so it says what will
    /// happen rather than how it is represented.
    #[must_use]
    pub fn render(&self) -> String {
        let mut out = String::new();
        for note in &self.notes {
            let _ = writeln!(out, "note: {note}");
        }
        for job in &self.jobs {
            // A linker input has no phases of its own. It shows up in the link line below, or
            // in a note above when there is no link line, and repeating it here would suggest
            // something happens to it.
            if job.phases.is_empty() {
                continue;
            }
            let names: Vec<&str> = job.phases.iter().map(|p| p.as_str()).collect();
            let _ = writeln!(out, "{}: {} -> {}", job.input, names.join(", "), job.output.render());
            // The files `-save-temps` keeps, which are as much a part of what will happen as the
            // output is and are the only reason the flag was passed.
            let kept: Vec<String> =
                [job.saved_text(), job.saved_asm()].into_iter().flatten().collect();
            if !kept.is_empty() {
                let _ = writeln!(out, "{}: keeping {}", job.input, kept.join(", "));
            }
        }
        if let Some(link) = &self.link {
            let names: Vec<String> = link.inputs.iter().map(ToString::to_string).collect();
            let _ = writeln!(out, "link: {} -> {}", names.join(" "), link.output);
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use rucc_session::Options;

    use super::*;

    fn opts(triple: &str) -> Options {
        Options::new(triple.parse().expect("test triple"))
    }

    fn linux() -> Options {
        opts("x86_64-unknown-linux-gnu")
    }

    fn plan(o: &Options, paths: &[&str], output: Option<&str>) -> Plan {
        let inputs: Vec<Input> = paths.iter().map(|p| Input::new(*p)).collect();
        Plan::new(o, &inputs, output).expect("expected a plan")
    }

    #[test]
    fn extensions_map_to_the_table_in_the_spec() {
        assert_eq!(InputKind::from_path("a.c").unwrap(), InputKind::C);
        assert_eq!(InputKind::from_path("a.i").unwrap(), InputKind::PreprocessedC);
        assert_eq!(InputKind::from_path("a.ir").unwrap(), InputKind::Ir);
        assert_eq!(InputKind::from_path("a.h").unwrap(), InputKind::CHeader);
        assert_eq!(InputKind::from_path("a.s").unwrap(), InputKind::Assembler);
        assert_eq!(InputKind::from_path("a.S").unwrap(), InputKind::AssemblerWithCpp);
        assert_eq!(InputKind::from_path("a.sx").unwrap(), InputKind::AssemblerWithCpp);
        assert_eq!(InputKind::from_path("a.o").unwrap(), InputKind::LinkerInput);
        assert_eq!(InputKind::from_path("libm.a").unwrap(), InputKind::LinkerInput);
        assert_eq!(InputKind::from_path("libm.so.6").unwrap(), InputKind::LinkerInput);
    }

    #[test]
    fn ir_enters_where_preprocessed_c_does_and_needs_no_preprocessor() {
        // It is the compiler's own output coming back in, so the phases in front of the walk
        // have already happened to it and the ones after it are the ones still to run.
        assert_eq!(InputKind::from_x_arg("ir").unwrap(), InputKind::Ir);
        assert_eq!(InputKind::Ir.as_str(), "ir");
        assert_eq!(InputKind::Ir.full_sequence(), InputKind::PreprocessedC.full_sequence());
        assert!(!InputKind::Ir.full_sequence().contains(&Phase::Preprocess));
    }

    #[test]
    fn an_input_whose_output_has_its_own_name_is_refused_rather_than_written_over() {
        // `rucc --emit=ir a.ir` would read the file and then write the result over it, and
        // what it held would be gone.
        let mut o = linux();
        o.emit = EmitKind::Ir;
        let inputs = [Input::new("a.ir")];
        let error = Plan::new(&o, &inputs, None).expect_err("expected this to be refused");
        assert!(error.message.contains("is the same as the output file"), "{error}");
        // Naming it something else is fine, and so is the same name reached through `-o`
        // being refused for the same reason.
        assert!(Plan::new(&o, &inputs, Some("b.ir")).is_ok());
        assert!(Plan::new(&o, &inputs, Some("a.ir")).is_err());
    }

    #[test]
    fn capital_s_and_small_s_are_different_languages() {
        // On a case-insensitive file system it is tempting to fold these together. They are
        // not the same: one runs the preprocessor and one does not.
        let hi = InputKind::from_path("a.S").unwrap();
        let lo = InputKind::from_path("a.s").unwrap();
        assert_ne!(hi, lo);
        assert!(hi.full_sequence().contains(&Phase::Preprocess));
        assert!(!lo.full_sequence().contains(&Phase::Preprocess));
    }

    #[test]
    fn a_cplusplus_source_says_why_rather_than_failing_at_link_time() {
        let e = InputKind::from_path("a.cpp").unwrap_err();
        assert!(format!("{e}").contains("only ever going to compile C"), "{e}");
        let e = InputKind::from_x_arg("c++").unwrap_err();
        assert!(matches!(e, XError::Unsupported(_)), "{e:?}");
    }

    #[test]
    fn a_file_with_no_extension_goes_to_the_linker() {
        assert_eq!(InputKind::from_path("crt1").unwrap(), InputKind::LinkerInput);
        assert_eq!(InputKind::from_path(".bashrc").unwrap(), InputKind::LinkerInput);
    }

    #[test]
    fn the_default_line_compiles_and_links_to_a_out() {
        let p = plan(&linux(), &["a.c"], None);
        assert_eq!(
            p.jobs[0].phases,
            vec![Phase::Preprocess, Phase::Compile, Phase::Assemble, Phase::Link]
        );
        assert_eq!(p.jobs[0].output, Output::Temporary("a.o".into()));
        let link = p.link.expect("expected a link step");
        assert_eq!(link.inputs, vec![Item::File("a.o".into())]);
        assert_eq!(link.output, "a.out");
    }

    #[test]
    fn dash_c_stops_at_the_object_and_names_it_after_the_source() {
        let mut o = linux();
        o.emit = EmitKind::Object;
        let p = plan(&o, &["src/a.c", "src/b.c"], None);
        assert!(p.link.is_none());
        assert_eq!(p.jobs[0].output, Output::File("a.o".into()));
        assert_eq!(p.jobs[1].output, Output::File("b.o".into()));
        // Next to the source is what people expect and it is not what GCC does. The object
        // lands in the current directory.
        assert_eq!(p.jobs[0].phases.last(), Some(&Phase::Assemble));
    }

    #[test]
    fn dash_e_writes_to_stdout_unless_it_is_given_a_name() {
        let mut o = linux();
        o.emit = EmitKind::Preprocessed;
        assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::Stdout);
        assert_eq!(plan(&o, &["a.c"], Some("a.i")).jobs[0].output, Output::File("a.i".into()));
    }

    #[test]
    fn a_name_of_one_dash_is_standard_output_and_not_a_file_called_that() {
        let mut o = linux();
        o.emit = EmitKind::Preprocessed;
        assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
        o.emit = EmitKind::Object;
        assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
        // The linker is handed the name and makes a file of it, which is gcc's behaviour and
        // is the one place the dash is not standard output.
        let p = plan(&linux(), &["a.c"], Some("-"));
        assert_eq!(p.link.expect("a link step").output, "-");
    }

    #[test]
    fn dash_s_produces_assembly_named_after_the_source() {
        let mut o = linux();
        o.emit = EmitKind::Asm;
        let p = plan(&o, &["dir/a.c"], None);
        assert_eq!(p.jobs[0].output, Output::File("a.s".into()));
        assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Compile]);
    }

    #[test]
    fn an_already_preprocessed_file_skips_the_preprocessor() {
        let p = plan(&linux(), &["a.i"], None);
        assert_eq!(p.jobs[0].phases, vec![Phase::Compile, Phase::Assemble, Phase::Link]);
    }

    #[test]
    fn assembly_with_a_capital_s_is_preprocessed_but_not_compiled() {
        let p = plan(&linux(), &["a.S"], None);
        assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Assemble, Phase::Link]);
        assert!(!p.jobs[0].phases.contains(&Phase::Compile));
    }

    #[test]
    fn objects_on_the_line_reach_the_linker_in_the_order_they_were_written() {
        // Link order is semantic. A plan that reorders it is a plan that produces a different
        // program, and the failure would be a missing symbol nobody could explain.
        let p = plan(&linux(), &["a.o", "b.c", "libm.a"], None);
        let link = p.link.expect("expected a link step");
        assert_eq!(
            link.inputs,
            vec![Item::File("a.o".into()), Item::File("b.o".into()), Item::File("libm.a".into()),]
        );
    }

    #[test]
    fn an_object_on_a_dash_c_line_is_a_note_rather_than_an_error() {
        // Configure scripts do this. Erroring here fails builds that work under GCC.
        let mut o = linux();
        o.emit = EmitKind::Object;
        let p = plan(&o, &["a.c", "b.o"], None);
        assert!(p.jobs[1].phases.is_empty());
        assert_eq!(p.notes.len(), 1);
        assert!(p.notes[0].contains("linker input unused"), "{:?}", p.notes);
    }

    #[test]
    fn dash_o_with_several_compilations_is_rejected() {
        let mut o = linux();
        o.emit = EmitKind::Object;
        let inputs = [Input::new("a.c"), Input::new("b.c")];
        let e = Plan::new(&o, &inputs, Some("out.o")).unwrap_err();
        assert!(e.message.contains("multiple inputs"), "{}", e.message);
    }

    #[test]
    fn dash_o_with_one_compilation_and_some_objects_is_fine() {
        // `rucc -c -o out.o a.c b.o` has exactly one thing to write, so the check above must
        // not count the object.
        let mut o = linux();
        o.emit = EmitKind::Object;
        let inputs = [Input::new("a.c"), Input::new("b.o")];
        let p = Plan::new(&o, &inputs, Some("out.o")).expect("expected a plan");
        assert_eq!(p.jobs[0].output, Output::File("out.o".into()));
    }

    #[test]
    fn dash_x_overrides_the_extension() {
        let inputs = [Input { path: "a.txt".into(), forced: Some(InputKind::C), library: false }];
        let p = Plan::new(&linux(), &inputs, None).expect("expected a plan");
        assert_eq!(p.jobs[0].kind, InputKind::C);
        assert_eq!(p.jobs[0].phases.first(), Some(&Phase::Preprocess));
    }

    #[test]
    fn windows_gets_obj_and_a_exe() {
        let o = opts("x86_64-pc-windows-msvc");
        let p = plan(&o, &["a.c"], None);
        assert_eq!(p.jobs[0].output, Output::Temporary("a.obj".into()));
        assert_eq!(p.link.expect("expected a link step").output, "a.exe");
    }

    #[test]
    fn the_intermediate_dumps_stop_where_dash_s_stops() {
        for emit in [
            EmitKind::Tast,
            EmitKind::Ir,
            EmitKind::MirFinal,
            EmitKind::SafetySummary,
            EmitKind::TypeGranules,
        ] {
            assert_eq!(last_phase(emit), Phase::Compile, "{emit:?}");
        }
    }

    #[test]
    fn each_intermediate_dump_is_a_language_of_its_own_and_gets_a_suffix_of_its_own() {
        // They all come out of the compile phase and none of them is assembly, so writing any
        // of them to `a.s` would leave a file that neither an assembler nor a reader can use.
        for (emit, name) in [
            (EmitKind::Asm, "a.s"),
            (EmitKind::Tast, "a.tast"),
            (EmitKind::Ir, "a.ir"),
            (EmitKind::MirFinal, "a.mir"),
            (EmitKind::SafetySummary, "a.safety.json"),
            (EmitKind::TypeGranules, "a.granules.txt"),
        ] {
            let mut o = linux();
            o.emit = emit;
            assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::File(name.into()));
        }
    }

    #[test]
    fn an_input_that_enters_after_the_last_phase_is_a_note_rather_than_an_error() {
        // `rucc -E a.s` has nothing to preprocess. GCC carries on, and a configure script
        // that probes with a mixed input list depends on that.
        let mut o = linux();
        o.emit = EmitKind::Preprocessed;
        let p = plan(&o, &["a.c", "b.s"], None);
        assert!(p.jobs[1].phases.is_empty());
        assert_eq!(p.notes.len(), 1);
        assert!(p.notes[0].contains("after the last phase"), "{:?}", p.notes);
        // And it must not count against `-o`, because only one file is being written.
        let inputs = [Input::new("a.c"), Input::new("b.s")];
        assert!(Plan::new(&o, &inputs, Some("out.i")).is_ok());
    }

    #[test]
    fn no_inputs_is_an_error() {
        assert!(Plan::new(&linux(), &[], None).is_err());
    }

    /// The plan for `paths` under `-save-temps` in the spelling `kind`.
    fn keeping(kind: SaveTemps, emit: EmitKind, paths: &[&str], output: Option<&str>) -> Plan {
        let mut o = linux();
        o.emit = emit;
        o.save_temps = kind;
        plan(&o, paths, output)
    }

    /// What one job of that plan keeps, in the order the files are produced.
    fn kept(plan: &Plan, at: usize) -> Vec<String> {
        [plan.jobs[at].saved_text(), plan.jobs[at].saved_asm()].into_iter().flatten().collect()
    }

    #[test]
    fn the_files_that_are_kept_land_beside_the_output_and_not_where_the_manual_says() {
        // gcc 16's bare `-save-temps` is `-save-temps=obj`, whatever its manual says, so
        // `-o out/t.o` puts them in `out` and not in the working directory. Both spellings are
        // here because the whole of the difference between them is the directory.
        let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.c"], Some("out/t.o"));
        assert_eq!(kept(&p, 0), vec!["out/t.i", "out/t.s"]);
        let p = keeping(SaveTemps::Cwd, EmitKind::Object, &["t.c"], Some("out/t.o"));
        assert_eq!(kept(&p, 0), vec!["t.i", "t.s"]);
    }

    #[test]
    fn the_name_comes_off_the_output_rather_than_off_the_input_that_produced_it() {
        // `-o out/x.o` keeps `x.i` and not `t.i`, and an output with no extension on it keeps
        // the whole of the name it was given.
        let p = keeping(SaveTemps::Cwd, EmitKind::Object, &["t.c"], Some("out/x.o"));
        assert_eq!(kept(&p, 0), vec!["x.i", "x.s"]);
        let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.c"], Some("out/noext"));
        assert_eq!(kept(&p, 0), vec!["out/noext.i", "out/noext.s"]);
    }

    #[test]
    fn without_a_name_they_are_called_after_the_input_and_are_where_the_object_would_be() {
        // The object of `sub/u.c` is `u.o` in the working directory, so what is kept beside it
        // is in the working directory as well, under both spellings.
        for kind in [SaveTemps::Object, SaveTemps::Cwd] {
            let p = keeping(kind, EmitKind::Object, &["sub/u.c"], None);
            assert_eq!(kept(&p, 0), vec!["u.i", "u.s"], "{kind:?}");
            assert_eq!(p.jobs[0].output, Output::File("u.o".into()), "{kind:?}");
        }
    }

    #[test]
    fn a_command_line_that_links_names_them_after_the_executable_and_the_input() {
        // One output for however many inputs, so the input's own name goes on the end and two
        // files that would otherwise both be `prog.i` are two files.
        let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c", "sub/u.c"], Some("o/p"));
        assert_eq!(kept(&p, 0), vec!["o/p-t.i", "o/p-t.s"]);
        assert_eq!(kept(&p, 1), vec!["o/p-u.i", "o/p-u.s"]);
        // With no `-o` the executable is `a.out`, and the `a` of it is what the files are named
        // from, which is where `a-t.i` comes from on a command line nobody wrote an `a` on.
        let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c"], None);
        assert_eq!(kept(&p, 0), vec!["a-t.i", "a-t.s"]);
    }

    #[test]
    fn the_object_a_link_reads_is_kept_rather_than_written_where_it_will_be_removed() {
        // Without the flag it goes in a directory that is gone by the end of the run, and that
        // is the one thing `-save-temps` cannot leave true: the object is one of the files it
        // was asked to keep.
        let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c"], Some("out/prog"));
        assert_eq!(p.jobs[0].output, Output::File("out/prog-t.o".into()));
        let plain = plan(&linux(), &["t.c"], Some("out/prog"));
        assert_eq!(plain.jobs[0].output, Output::Temporary("t.o".into()));
    }

    #[test]
    fn a_step_whose_result_is_already_being_written_is_not_kept_a_second_time() {
        // `-E` writes the preprocessed text, so there is nothing left over to keep, and `-S`
        // writes the assembly and keeps only the text that came before it.
        let p = keeping(SaveTemps::Object, EmitKind::Preprocessed, &["t.c"], None);
        assert_eq!(p.jobs[0].aux_base, None);
        assert_eq!(kept(&p, 0), Vec::<String>::new());
        let p = keeping(SaveTemps::Object, EmitKind::Asm, &["t.c"], None);
        assert_eq!(kept(&p, 0), vec!["t.i"]);
    }

    #[test]
    fn an_input_that_arrives_preprocessed_has_no_text_of_its_own_to_keep() {
        // There is no phase 4 to keep the result of, and the file the compilation read is the
        // one that would have been written, which is already on the disk under its own name.
        let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.i"], None);
        assert_eq!(kept(&p, 0), vec!["t.s"]);
        // And an input the linker takes directly goes through no step at all.
        let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.o"], None);
        assert_eq!(p.jobs[0].aux_base, None);
    }

    #[test]
    fn nothing_is_kept_when_the_flag_was_not_given() {
        let p = plan(&linux(), &["t.c"], None);
        assert_eq!(p.jobs[0].aux_base, None);
        assert_eq!(kept(&p, 0), Vec::<String>::new());
    }

    #[test]
    fn the_rendering_says_what_will_happen() {
        let p = plan(&linux(), &["a.c", "b.o"], None);
        let text = p.render();
        assert!(
            text.contains("a.c: preprocess, compile, assemble, link -> a.o (temporary)"),
            "{text}"
        );
        assert!(text.contains("link: a.o b.o -> a.out"), "{text}");
        // The object has nothing done to it, so it appears once, in the link line.
        assert_eq!(text.matches("b.o").count(), 1, "{text}");
    }

    #[test]
    fn the_rendering_names_the_files_that_will_be_kept() {
        // `-###` is what will happen, and under `-save-temps` two more files being written is
        // part of that. It is also the only way to see the names without running a compilation.
        let p = keeping(SaveTemps::Object, EmitKind::Executable, &["a.c"], None);
        let text = p.render();
        assert!(text.contains("a.c: keeping a-a.i, a-a.s"), "{text}");
        assert!(!plan(&linux(), &["a.c"], None).render().contains("keeping"));
    }
}