Skip to main content

rucc_driver/
phase.rs

1//! The phase graph: what has to happen to each input file, in what order, and where the
2//! result goes.
3//!
4//! Design: `spec/04-driver-and-cli.md` section 4.2.
5//!
6//! The plan is computed before anything runs and is a plain data structure with no side
7//! effects, which is what makes `-###` possible and what makes this testable without a file
8//! system. Nothing in here reads a file or spawns a process. Executing the plan is M3, when
9//! there is something for the phases to do.
10
11use std::fmt::Write as _;
12
13use rucc_session::{EmitKind, Options};
14use rucc_target::Os;
15
16use crate::link::Item;
17
18/// A step in the compilation of one input.
19///
20/// The order of the variants is the order of the pipeline, and the derived `Ord` is relied on
21/// when a mode flag truncates a sequence. `Compile` covers parsing through code generation,
22/// which is one phase from the driver's point of view because nothing between them can be
23/// stopped at from the command line.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum Phase {
26    /// Translation phases 1 to 4, producing preprocessed source.
27    Preprocess,
28    /// Parse, check, optimize and generate code, producing assembly.
29    Compile,
30    /// Assemble, producing an object file.
31    Assemble,
32    /// Link the objects into an executable or a shared library.
33    Link,
34}
35
36impl Phase {
37    /// The name used in `-###` output and in diagnostics.
38    #[must_use]
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Phase::Preprocess => "preprocess",
42            Phase::Compile => "compile",
43            Phase::Assemble => "assemble",
44            Phase::Link => "link",
45        }
46    }
47}
48
49impl std::fmt::Display for Phase {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.write_str(self.as_str())
52    }
53}
54
55/// What an input file is, which decides where in the pipeline it enters.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57pub enum InputKind {
58    /// C source. Extension `.c`, or `-x c`.
59    C,
60    /// A header compiled on its own. Extension `.h` with `-x c-header`, or `-x c-header`.
61    CHeader,
62    /// Already preprocessed C. Extension `.i`, or `-x cpp-output`.
63    PreprocessedC,
64    /// The IR this compiler prints. Extension `.ir`, or `-x ir`.
65    ///
66    /// Not a GCC input kind, because GCC has no textual IR. It is here because the IR's
67    /// printer and its parser are a pair, and a pair is only known to agree if something reads
68    /// back what was written: `rucc --emit=ir a.c -o a.ir` and then `rucc --emit=ir a.ir` are
69    /// two files a byte comparison has an opinion about, over whatever code is at hand rather
70    /// than over the modules a test happens to build.
71    Ir,
72    /// Assembly. Extension `.s`, or `-x assembler`.
73    Assembler,
74    /// Assembly that still needs the preprocessor. Extension `.S` or `.sx`, or
75    /// `-x assembler-with-cpp`.
76    AssemblerWithCpp,
77    /// An object file, an archive or a shared library. Anything the linker takes directly.
78    LinkerInput,
79}
80
81impl InputKind {
82    /// The name `-x` uses for this kind, where one exists.
83    #[must_use]
84    pub fn as_str(self) -> &'static str {
85        match self {
86            InputKind::C => "c",
87            InputKind::CHeader => "c-header",
88            InputKind::PreprocessedC => "cpp-output",
89            InputKind::Ir => "ir",
90            InputKind::Assembler => "assembler",
91            InputKind::AssemblerWithCpp => "assembler-with-cpp",
92            InputKind::LinkerInput => "linker-input",
93        }
94    }
95
96    /// Parses the argument of `-x`.
97    ///
98    /// # Errors
99    ///
100    /// Returns the offending name when it is not one we accept. C++ gets its own message,
101    /// because "unknown language c++" reads like an oversight and it is a decision.
102    pub fn from_x_arg(name: &str) -> Result<InputKind, XError> {
103        match name {
104            "c" => Ok(InputKind::C),
105            "c-header" => Ok(InputKind::CHeader),
106            "cpp-output" | "c-cpp-output" => Ok(InputKind::PreprocessedC),
107            "ir" => Ok(InputKind::Ir),
108            "assembler" => Ok(InputKind::Assembler),
109            "assembler-with-cpp" => Ok(InputKind::AssemblerWithCpp),
110            "c++" | "c++-header" | "c++-cpp-output" | "objective-c" | "objective-c++" => {
111                Err(XError::Unsupported(name.to_owned()))
112            }
113            _ => Err(XError::Unknown(name.to_owned())),
114        }
115    }
116
117    /// Classifies an input by its extension, the way `spec/04-driver-and-cli.md` section 4.2
118    /// tabulates it.
119    ///
120    /// An unrecognized extension is a linker input, which is GCC's behavior and is what makes
121    /// `rucc foo.o bar.builtin-suffix` work. The exception is a C++ extension, which is a
122    /// hard error rather than a confusing link failure later.
123    ///
124    /// # Errors
125    ///
126    /// Returns the extension when it names a language that is permanently out of scope.
127    pub fn from_path(path: &str) -> Result<InputKind, XError> {
128        let ext = extension(path);
129        match ext {
130            // Matched case-sensitively on purpose: `.S` and `.s` are different languages and
131            // conflating them is a real bug on case-insensitive file systems that GCC also
132            // has. The comment is here so the next person does not "fix" it.
133            "c" => Ok(InputKind::C),
134            "i" => Ok(InputKind::PreprocessedC),
135            "ir" => Ok(InputKind::Ir),
136            "h" => Ok(InputKind::CHeader),
137            "s" => Ok(InputKind::Assembler),
138            "S" | "sx" => Ok(InputKind::AssemblerWithCpp),
139            "cc" | "cpp" | "cxx" | "c++" | "C" | "hpp" | "hxx" | "ii" | "m" | "mm" => {
140                Err(XError::Unsupported(ext.to_owned()))
141            }
142            _ => Ok(InputKind::LinkerInput),
143        }
144    }
145
146    /// The full phase sequence for this kind, before any mode flag truncates it.
147    fn full_sequence(self) -> &'static [Phase] {
148        use Phase::{Assemble, Compile, Link, Preprocess};
149        match self {
150            InputKind::C | InputKind::CHeader => &[Preprocess, Compile, Assemble, Link],
151            InputKind::PreprocessedC | InputKind::Ir => &[Compile, Assemble, Link],
152            // Note the gap: assembly with a preprocessor skips `Compile` entirely. This is why
153            // the sequence is a list rather than a range over the enum.
154            InputKind::AssemblerWithCpp => &[Preprocess, Assemble, Link],
155            InputKind::Assembler => &[Assemble, Link],
156            InputKind::LinkerInput => &[Link],
157        }
158    }
159}
160
161/// Why an input or an `-x` argument was rejected.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum XError {
164    /// A language we do not know at all.
165    Unknown(String),
166    /// A language we know and will not implement.
167    Unsupported(String),
168}
169
170impl std::fmt::Display for XError {
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        match self {
173            XError::Unknown(name) => {
174                write!(
175                    f,
176                    "unknown language `{name}`; \
177                     accepted: c, c-header, cpp-output, ir, assembler, assembler-with-cpp, none"
178                )
179            }
180            XError::Unsupported(name) => {
181                write!(
182                    f,
183                    "`{name}` is not C, and this compiler is only ever going to compile C; \
184                     see the not-in-scope list in spec/00-README.md"
185                )
186            }
187        }
188    }
189}
190
191impl std::error::Error for XError {}
192
193/// One input file, with the `-x` setting that was in effect where it appeared.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct Input {
196    /// The path as it was written on the command line, or the name of a `-l` library.
197    pub path: String,
198    /// The language forced by an earlier `-x`, if any. `-x none` clears it.
199    pub forced: Option<InputKind>,
200    /// Whether this came from `-l<name>` rather than being a path.
201    ///
202    /// A library is an input to the link and is held here rather than beside the other link
203    /// flags, because where it falls among the objects is what decides whether it is searched
204    /// for what they left undefined. A list of objects and a separate list of libraries would
205    /// lose exactly that.
206    pub library: bool,
207}
208
209impl Input {
210    /// An input with no `-x` in effect.
211    #[must_use]
212    pub fn new(path: impl Into<String>) -> Input {
213        Input { path: path.into(), forced: None, library: false }
214    }
215
216    /// `-l<name>`, which is an input to the link and to nothing else.
217    #[must_use]
218    pub fn library(name: impl Into<String>) -> Input {
219        Input { path: name.into(), forced: None, library: true }
220    }
221
222    /// What this input is, taking `-x` into account.
223    ///
224    /// # Errors
225    ///
226    /// Returns the extension when it names a language that is out of scope.
227    pub fn kind(&self) -> Result<InputKind, XError> {
228        if self.library {
229            return Ok(InputKind::LinkerInput);
230        }
231        match self.forced {
232            Some(k) => Ok(k),
233            None => InputKind::from_path(&self.path),
234        }
235    }
236}
237
238/// Where the result of a job goes.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub enum Output {
241    /// Standard output, which is where `-E` writes when there is no `-o`.
242    Stdout,
243    /// A path the user can see and named, or that we derived from the input name.
244    File(String),
245    /// A file the link step consumes and nothing else ever sees. The name is a hint for
246    /// `-###` output; the real path is chosen in a temporary directory at execution time.
247    Temporary(String),
248}
249
250impl Output {
251    fn render(&self) -> String {
252        match self {
253            Output::Stdout => "-".to_owned(),
254            Output::File(p) => p.clone(),
255            Output::Temporary(p) => format!("{p} (temporary)"),
256        }
257    }
258
259    /// The path the link step reads, for an output that feeds it.
260    fn as_link_input(&self) -> Option<&str> {
261        match self {
262            Output::File(p) | Output::Temporary(p) => Some(p),
263            Output::Stdout => None,
264        }
265    }
266}
267
268/// Everything that has to happen to one input file.
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct Job {
271    /// The input path as written.
272    pub input: String,
273    /// What we decided it is.
274    pub kind: InputKind,
275    /// The phases to run, in order. Empty when the input goes straight to the linker.
276    pub phases: Vec<Phase>,
277    /// Where the last phase writes.
278    pub output: Output,
279}
280
281/// The link step, when there is one.
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct LinkJob {
284    /// Objects and libraries, in command line order, because link order is semantic.
285    pub inputs: Vec<Item>,
286    /// The executable.
287    pub output: String,
288}
289
290/// The whole plan for one invocation.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct Plan {
293    /// One per input, in command line order.
294    pub jobs: Vec<Job>,
295    /// The link step, or `None` when a mode flag stopped short of it.
296    pub link: Option<LinkJob>,
297    /// Things worth saying under `-v` that are not errors, such as an object file passed on a
298    /// command line that is not linking.
299    pub notes: Vec<String>,
300}
301
302/// Why a command line could not be turned into a plan.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct PlanError {
305    /// Lowercase, no trailing period, the same shape as every other diagnostic.
306    pub message: String,
307}
308
309impl std::fmt::Display for PlanError {
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        f.write_str(&self.message)
312    }
313}
314
315impl std::error::Error for PlanError {}
316
317fn plan_err(message: impl Into<String>) -> PlanError {
318    PlanError { message: message.into() }
319}
320
321/// The last phase that runs, given what the user asked to be emitted.
322///
323/// `--emit=tast` and the other intermediate dumps stop where `-S` stops, because they are
324/// produced inside the compile phase and there is nothing after them to run.
325#[must_use]
326pub fn last_phase(emit: EmitKind) -> Phase {
327    match emit {
328        EmitKind::Preprocessed => Phase::Preprocess,
329        EmitKind::Asm
330        | EmitKind::Tast
331        | EmitKind::Ir
332        | EmitKind::MirFinal
333        | EmitKind::SafetySummary
334        | EmitKind::TypeGranules => Phase::Compile,
335        EmitKind::Object => Phase::Assemble,
336        EmitKind::Executable => Phase::Link,
337    }
338}
339
340/// The extension of a path, without the dot, or the empty string when there is none.
341fn extension(path: &str) -> &str {
342    let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
343    match name.rfind('.') {
344        // A leading dot is a hidden file, not an extension, and `.` and `..` are not inputs.
345        Some(0) | None => "",
346        Some(i) => &name[i + 1..],
347    }
348}
349
350/// The path without its extension, keeping any directory part off, because GCC writes the
351/// output into the current directory rather than next to the source.
352fn stem(path: &str) -> &str {
353    let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
354    match name.rfind('.') {
355        Some(0) | None => name,
356        Some(i) => &name[..i],
357    }
358}
359
360/// The suffix a phase's output carries, for this target.
361fn suffix_for(phase: Phase, opts: &Options) -> &'static str {
362    match phase {
363        Phase::Preprocess => "i",
364        // The compile phase is where every intermediate dump comes out, and each of them is a
365        // different language, so each gets a name of its own. `rucc --emit=tast a.c` writing
366        // `a.s` would be a file that neither an assembler nor a reader could make sense of.
367        Phase::Compile => match opts.emit {
368            EmitKind::Tast => "tast",
369            EmitKind::Ir => "ir",
370            EmitKind::MirFinal => "mir",
371            // Two extensions rather than one, because the content is JSON and a tool that reads
372            // JSON should be able to tell by looking, and because `a.json` next to `a.c` says
373            // nothing about which of a build's several JSON files it is.
374            EmitKind::SafetySummary => "safety.json",
375            // Two extensions for the same reason, and text rather than JSON because this one
376            // is read by a person once and not by a build every time.
377            EmitKind::TypeGranules => "granules.txt",
378            _ => "s",
379        },
380        // MSVC-targeted builds expect `.obj`, and build systems written for that target look
381        // for it by name.
382        Phase::Assemble => {
383            if opts.target.os == Os::Windows {
384                "obj"
385            } else {
386                "o"
387            }
388        }
389        Phase::Link => "",
390    }
391}
392
393/// The default name of the linked output, which is GCC's `a.out` everywhere but Windows.
394fn default_exe(opts: &Options) -> &'static str {
395    if opts.target.os == Os::Windows { "a.exe" } else { "a.out" }
396}
397
398impl Plan {
399    /// Builds the plan for one invocation.
400    ///
401    /// `output` is the argument of `-o`, if it was given.
402    ///
403    /// # Errors
404    ///
405    /// Returns a message when the inputs and the mode flags do not describe a compilation:
406    /// an out of scope language, `-o` naming one file for several outputs, or nothing to do.
407    pub fn new(opts: &Options, inputs: &[Input], output: Option<&str>) -> Result<Plan, PlanError> {
408        if inputs.is_empty() {
409            return Err(plan_err("no input files"));
410        }
411        let last = last_phase(opts.emit);
412        let linking = last == Phase::Link;
413
414        let mut kinds = Vec::with_capacity(inputs.len());
415        for input in inputs {
416            kinds.push(input.kind().map_err(|e| plan_err(format!("{}: {e}", input.path)))?);
417        }
418
419        // How many inputs actually write an output of their own. A `.o` on a `-c` line
420        // produces nothing, and neither does a `.s` on an `-E` line, so neither may count
421        // toward the `-o` check below. When linking there is exactly one output and it is the
422        // executable, so nothing counts.
423        let producing = if linking {
424            0
425        } else {
426            kinds
427                .iter()
428                .filter(|k| **k != InputKind::LinkerInput)
429                .filter(|k| k.full_sequence().iter().any(|p| *p <= last))
430                .count()
431        };
432        if output.is_some() && !linking && producing > 1 {
433            return Err(plan_err("cannot specify -o with multiple inputs when not linking"));
434        }
435
436        let mut notes = Vec::new();
437        let mut jobs = Vec::with_capacity(inputs.len());
438        let mut link_inputs = Vec::new();
439
440        for (input, kind) in inputs.iter().zip(kinds) {
441            // An object, an archive or a shared library has nothing done to it. It reaches the
442            // linker under the name it was written with, and its name is not derived from
443            // anything, which is why this case is separate rather than falling out of the
444            // sequence below. Deriving it would rewrite `libm.a` into `libm.o`.
445            if kind == InputKind::LinkerInput {
446                if linking {
447                    link_inputs.push(if input.library {
448                        Item::Library(input.path.clone())
449                    } else {
450                        Item::File(input.path.clone())
451                    });
452                } else {
453                    // GCC warns and carries on here, and configure scripts rely on that, so
454                    // this is a note rather than an error.
455                    notes.push(format!(
456                        "{}: linker input unused because linking was not requested",
457                        if input.library {
458                            format!("-l{}", input.path)
459                        } else {
460                            input.path.clone()
461                        }
462                    ));
463                }
464                // A library is not a file this compilation does anything to, so it gets no job.
465                // One would print a line under `-###` saying nothing happens to it, next to the
466                // note above already saying so.
467                if input.library {
468                    continue;
469                }
470                jobs.push(Job {
471                    input: input.path.clone(),
472                    kind,
473                    phases: Vec::new(),
474                    output: Output::File(input.path.clone()),
475                });
476                continue;
477            }
478
479            let phases: Vec<Phase> =
480                kind.full_sequence().iter().copied().filter(|p| *p <= last).collect();
481            // `rucc -E a.s` lands here: assembly enters at `Assemble`, which is past where
482            // `-E` stops, so there is no phase left to run. GCC carries on rather than
483            // failing, and so do we.
484            let Some(&final_phase) = phases.last() else {
485                notes.push(format!(
486                    "{}: input unused because it enters the pipeline after the last phase \
487                     the mode flags asked for",
488                    input.path
489                ));
490                jobs.push(Job {
491                    input: input.path.clone(),
492                    kind,
493                    phases,
494                    output: Output::File(input.path.clone()),
495                });
496                continue;
497            };
498            let named = if producing == 1 { output } else { None };
499            let out = if final_phase == Phase::Link {
500                // The job stops at the object, and the link step below takes it from here.
501                let ext = suffix_for(Phase::Assemble, opts);
502                Output::Temporary(format!("{}.{ext}", stem(&input.path)))
503            } else if let Some(o) = named {
504                // `-o -` is standard output rather than a file of that name, which is what gcc
505                // does for everything it compiles, the object file included. Its link step is
506                // the exception and writes a file called `-`, because the name goes to the
507                // linker and the linker takes it literally.
508                if o == "-" { Output::Stdout } else { Output::File(o.to_owned()) }
509            } else if final_phase == Phase::Preprocess {
510                // `-E` writes to standard output unless it was given a name, which is the one
511                // place where the default is not a file.
512                Output::Stdout
513            } else {
514                Output::File(format!("{}.{}", stem(&input.path), suffix_for(final_phase, opts)))
515            };
516            // An input whose output has the name it has itself would be read and then written
517            // over, and what it held would be gone. GCC compares the two names the way they
518            // were written and so does this, which catches `rucc --emit=ir a.ir` and leaves
519            // the same file reached by two different paths to the file system.
520            if let Output::File(path) = &out {
521                if *path == input.path {
522                    return Err(plan_err(format!(
523                        "input file `{}` is the same as the output file",
524                        input.path
525                    )));
526                }
527            }
528
529            if linking {
530                if let Some(p) = out.as_link_input() {
531                    link_inputs.push(Item::File(p.to_owned()));
532                }
533            }
534            jobs.push(Job { input: input.path.clone(), kind, phases, output: out });
535        }
536
537        let link = linking.then(|| LinkJob {
538            inputs: link_inputs,
539            output: output.unwrap_or(default_exe(opts)).to_owned(),
540        });
541
542        Ok(Plan { jobs, link, notes })
543    }
544
545    /// Renders the plan the way `-###` prints it.
546    ///
547    /// One line per job, then the link line. This is meant to be read next to `gcc -###`
548    /// output when a build behaves differently under the two compilers, so it says what will
549    /// happen rather than how it is represented.
550    #[must_use]
551    pub fn render(&self) -> String {
552        let mut out = String::new();
553        for note in &self.notes {
554            let _ = writeln!(out, "note: {note}");
555        }
556        for job in &self.jobs {
557            // A linker input has no phases of its own. It shows up in the link line below, or
558            // in a note above when there is no link line, and repeating it here would suggest
559            // something happens to it.
560            if job.phases.is_empty() {
561                continue;
562            }
563            let names: Vec<&str> = job.phases.iter().map(|p| p.as_str()).collect();
564            let _ = writeln!(out, "{}: {} -> {}", job.input, names.join(", "), job.output.render());
565        }
566        if let Some(link) = &self.link {
567            let names: Vec<String> = link.inputs.iter().map(ToString::to_string).collect();
568            let _ = writeln!(out, "link: {} -> {}", names.join(" "), link.output);
569        }
570        out
571    }
572}
573
574#[cfg(test)]
575mod tests {
576    use rucc_session::Options;
577
578    use super::*;
579
580    fn opts(triple: &str) -> Options {
581        Options::new(triple.parse().expect("test triple"))
582    }
583
584    fn linux() -> Options {
585        opts("x86_64-unknown-linux-gnu")
586    }
587
588    fn plan(o: &Options, paths: &[&str], output: Option<&str>) -> Plan {
589        let inputs: Vec<Input> = paths.iter().map(|p| Input::new(*p)).collect();
590        Plan::new(o, &inputs, output).expect("expected a plan")
591    }
592
593    #[test]
594    fn extensions_map_to_the_table_in_the_spec() {
595        assert_eq!(InputKind::from_path("a.c").unwrap(), InputKind::C);
596        assert_eq!(InputKind::from_path("a.i").unwrap(), InputKind::PreprocessedC);
597        assert_eq!(InputKind::from_path("a.ir").unwrap(), InputKind::Ir);
598        assert_eq!(InputKind::from_path("a.h").unwrap(), InputKind::CHeader);
599        assert_eq!(InputKind::from_path("a.s").unwrap(), InputKind::Assembler);
600        assert_eq!(InputKind::from_path("a.S").unwrap(), InputKind::AssemblerWithCpp);
601        assert_eq!(InputKind::from_path("a.sx").unwrap(), InputKind::AssemblerWithCpp);
602        assert_eq!(InputKind::from_path("a.o").unwrap(), InputKind::LinkerInput);
603        assert_eq!(InputKind::from_path("libm.a").unwrap(), InputKind::LinkerInput);
604        assert_eq!(InputKind::from_path("libm.so.6").unwrap(), InputKind::LinkerInput);
605    }
606
607    #[test]
608    fn ir_enters_where_preprocessed_c_does_and_needs_no_preprocessor() {
609        // It is the compiler's own output coming back in, so the phases in front of the walk
610        // have already happened to it and the ones after it are the ones still to run.
611        assert_eq!(InputKind::from_x_arg("ir").unwrap(), InputKind::Ir);
612        assert_eq!(InputKind::Ir.as_str(), "ir");
613        assert_eq!(InputKind::Ir.full_sequence(), InputKind::PreprocessedC.full_sequence());
614        assert!(!InputKind::Ir.full_sequence().contains(&Phase::Preprocess));
615    }
616
617    #[test]
618    fn an_input_whose_output_has_its_own_name_is_refused_rather_than_written_over() {
619        // `rucc --emit=ir a.ir` would read the file and then write the result over it, and
620        // what it held would be gone.
621        let mut o = linux();
622        o.emit = EmitKind::Ir;
623        let inputs = [Input::new("a.ir")];
624        let error = Plan::new(&o, &inputs, None).expect_err("expected this to be refused");
625        assert!(error.message.contains("is the same as the output file"), "{error}");
626        // Naming it something else is fine, and so is the same name reached through `-o`
627        // being refused for the same reason.
628        assert!(Plan::new(&o, &inputs, Some("b.ir")).is_ok());
629        assert!(Plan::new(&o, &inputs, Some("a.ir")).is_err());
630    }
631
632    #[test]
633    fn capital_s_and_small_s_are_different_languages() {
634        // On a case-insensitive file system it is tempting to fold these together. They are
635        // not the same: one runs the preprocessor and one does not.
636        let hi = InputKind::from_path("a.S").unwrap();
637        let lo = InputKind::from_path("a.s").unwrap();
638        assert_ne!(hi, lo);
639        assert!(hi.full_sequence().contains(&Phase::Preprocess));
640        assert!(!lo.full_sequence().contains(&Phase::Preprocess));
641    }
642
643    #[test]
644    fn a_cplusplus_source_says_why_rather_than_failing_at_link_time() {
645        let e = InputKind::from_path("a.cpp").unwrap_err();
646        assert!(format!("{e}").contains("only ever going to compile C"), "{e}");
647        let e = InputKind::from_x_arg("c++").unwrap_err();
648        assert!(matches!(e, XError::Unsupported(_)), "{e:?}");
649    }
650
651    #[test]
652    fn a_file_with_no_extension_goes_to_the_linker() {
653        assert_eq!(InputKind::from_path("crt1").unwrap(), InputKind::LinkerInput);
654        assert_eq!(InputKind::from_path(".bashrc").unwrap(), InputKind::LinkerInput);
655    }
656
657    #[test]
658    fn the_default_line_compiles_and_links_to_a_out() {
659        let p = plan(&linux(), &["a.c"], None);
660        assert_eq!(
661            p.jobs[0].phases,
662            vec![Phase::Preprocess, Phase::Compile, Phase::Assemble, Phase::Link]
663        );
664        assert_eq!(p.jobs[0].output, Output::Temporary("a.o".into()));
665        let link = p.link.expect("expected a link step");
666        assert_eq!(link.inputs, vec![Item::File("a.o".into())]);
667        assert_eq!(link.output, "a.out");
668    }
669
670    #[test]
671    fn dash_c_stops_at_the_object_and_names_it_after_the_source() {
672        let mut o = linux();
673        o.emit = EmitKind::Object;
674        let p = plan(&o, &["src/a.c", "src/b.c"], None);
675        assert!(p.link.is_none());
676        assert_eq!(p.jobs[0].output, Output::File("a.o".into()));
677        assert_eq!(p.jobs[1].output, Output::File("b.o".into()));
678        // Next to the source is what people expect and it is not what GCC does. The object
679        // lands in the current directory.
680        assert_eq!(p.jobs[0].phases.last(), Some(&Phase::Assemble));
681    }
682
683    #[test]
684    fn dash_e_writes_to_stdout_unless_it_is_given_a_name() {
685        let mut o = linux();
686        o.emit = EmitKind::Preprocessed;
687        assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::Stdout);
688        assert_eq!(plan(&o, &["a.c"], Some("a.i")).jobs[0].output, Output::File("a.i".into()));
689    }
690
691    #[test]
692    fn a_name_of_one_dash_is_standard_output_and_not_a_file_called_that() {
693        let mut o = linux();
694        o.emit = EmitKind::Preprocessed;
695        assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
696        o.emit = EmitKind::Object;
697        assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
698        // The linker is handed the name and makes a file of it, which is gcc's behaviour and
699        // is the one place the dash is not standard output.
700        let p = plan(&linux(), &["a.c"], Some("-"));
701        assert_eq!(p.link.expect("a link step").output, "-");
702    }
703
704    #[test]
705    fn dash_s_produces_assembly_named_after_the_source() {
706        let mut o = linux();
707        o.emit = EmitKind::Asm;
708        let p = plan(&o, &["dir/a.c"], None);
709        assert_eq!(p.jobs[0].output, Output::File("a.s".into()));
710        assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Compile]);
711    }
712
713    #[test]
714    fn an_already_preprocessed_file_skips_the_preprocessor() {
715        let p = plan(&linux(), &["a.i"], None);
716        assert_eq!(p.jobs[0].phases, vec![Phase::Compile, Phase::Assemble, Phase::Link]);
717    }
718
719    #[test]
720    fn assembly_with_a_capital_s_is_preprocessed_but_not_compiled() {
721        let p = plan(&linux(), &["a.S"], None);
722        assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Assemble, Phase::Link]);
723        assert!(!p.jobs[0].phases.contains(&Phase::Compile));
724    }
725
726    #[test]
727    fn objects_on_the_line_reach_the_linker_in_the_order_they_were_written() {
728        // Link order is semantic. A plan that reorders it is a plan that produces a different
729        // program, and the failure would be a missing symbol nobody could explain.
730        let p = plan(&linux(), &["a.o", "b.c", "libm.a"], None);
731        let link = p.link.expect("expected a link step");
732        assert_eq!(
733            link.inputs,
734            vec![Item::File("a.o".into()), Item::File("b.o".into()), Item::File("libm.a".into()),]
735        );
736    }
737
738    #[test]
739    fn an_object_on_a_dash_c_line_is_a_note_rather_than_an_error() {
740        // Configure scripts do this. Erroring here fails builds that work under GCC.
741        let mut o = linux();
742        o.emit = EmitKind::Object;
743        let p = plan(&o, &["a.c", "b.o"], None);
744        assert!(p.jobs[1].phases.is_empty());
745        assert_eq!(p.notes.len(), 1);
746        assert!(p.notes[0].contains("linker input unused"), "{:?}", p.notes);
747    }
748
749    #[test]
750    fn dash_o_with_several_compilations_is_rejected() {
751        let mut o = linux();
752        o.emit = EmitKind::Object;
753        let inputs = [Input::new("a.c"), Input::new("b.c")];
754        let e = Plan::new(&o, &inputs, Some("out.o")).unwrap_err();
755        assert!(e.message.contains("multiple inputs"), "{}", e.message);
756    }
757
758    #[test]
759    fn dash_o_with_one_compilation_and_some_objects_is_fine() {
760        // `rucc -c -o out.o a.c b.o` has exactly one thing to write, so the check above must
761        // not count the object.
762        let mut o = linux();
763        o.emit = EmitKind::Object;
764        let inputs = [Input::new("a.c"), Input::new("b.o")];
765        let p = Plan::new(&o, &inputs, Some("out.o")).expect("expected a plan");
766        assert_eq!(p.jobs[0].output, Output::File("out.o".into()));
767    }
768
769    #[test]
770    fn dash_x_overrides_the_extension() {
771        let inputs = [Input { path: "a.txt".into(), forced: Some(InputKind::C), library: false }];
772        let p = Plan::new(&linux(), &inputs, None).expect("expected a plan");
773        assert_eq!(p.jobs[0].kind, InputKind::C);
774        assert_eq!(p.jobs[0].phases.first(), Some(&Phase::Preprocess));
775    }
776
777    #[test]
778    fn windows_gets_obj_and_a_exe() {
779        let o = opts("x86_64-pc-windows-msvc");
780        let p = plan(&o, &["a.c"], None);
781        assert_eq!(p.jobs[0].output, Output::Temporary("a.obj".into()));
782        assert_eq!(p.link.expect("expected a link step").output, "a.exe");
783    }
784
785    #[test]
786    fn the_intermediate_dumps_stop_where_dash_s_stops() {
787        for emit in [
788            EmitKind::Tast,
789            EmitKind::Ir,
790            EmitKind::MirFinal,
791            EmitKind::SafetySummary,
792            EmitKind::TypeGranules,
793        ] {
794            assert_eq!(last_phase(emit), Phase::Compile, "{emit:?}");
795        }
796    }
797
798    #[test]
799    fn each_intermediate_dump_is_a_language_of_its_own_and_gets_a_suffix_of_its_own() {
800        // They all come out of the compile phase and none of them is assembly, so writing any
801        // of them to `a.s` would leave a file that neither an assembler nor a reader can use.
802        for (emit, name) in [
803            (EmitKind::Asm, "a.s"),
804            (EmitKind::Tast, "a.tast"),
805            (EmitKind::Ir, "a.ir"),
806            (EmitKind::MirFinal, "a.mir"),
807            (EmitKind::SafetySummary, "a.safety.json"),
808            (EmitKind::TypeGranules, "a.granules.txt"),
809        ] {
810            let mut o = linux();
811            o.emit = emit;
812            assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::File(name.into()));
813        }
814    }
815
816    #[test]
817    fn an_input_that_enters_after_the_last_phase_is_a_note_rather_than_an_error() {
818        // `rucc -E a.s` has nothing to preprocess. GCC carries on, and a configure script
819        // that probes with a mixed input list depends on that.
820        let mut o = linux();
821        o.emit = EmitKind::Preprocessed;
822        let p = plan(&o, &["a.c", "b.s"], None);
823        assert!(p.jobs[1].phases.is_empty());
824        assert_eq!(p.notes.len(), 1);
825        assert!(p.notes[0].contains("after the last phase"), "{:?}", p.notes);
826        // And it must not count against `-o`, because only one file is being written.
827        let inputs = [Input::new("a.c"), Input::new("b.s")];
828        assert!(Plan::new(&o, &inputs, Some("out.i")).is_ok());
829    }
830
831    #[test]
832    fn no_inputs_is_an_error() {
833        assert!(Plan::new(&linux(), &[], None).is_err());
834    }
835
836    #[test]
837    fn the_rendering_says_what_will_happen() {
838        let p = plan(&linux(), &["a.c", "b.o"], None);
839        let text = p.render();
840        assert!(
841            text.contains("a.c: preprocess, compile, assemble, link -> a.o (temporary)"),
842            "{text}"
843        );
844        assert!(text.contains("link: a.o b.o -> a.out"), "{text}");
845        // The object has nothing done to it, so it appears once, in the link line.
846        assert_eq!(text.matches("b.o").count(), 1, "{text}");
847    }
848}