1use std::fmt::Write as _;
12
13use rucc_session::{EmitKind, Options, SaveTemps};
14use rucc_target::Os;
15
16use crate::link::Item;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum Phase {
26 Preprocess,
28 Compile,
30 Assemble,
32 Archive,
39 Link,
41}
42
43impl Phase {
44 #[must_use]
46 pub fn as_str(self) -> &'static str {
47 match self {
48 Phase::Preprocess => "preprocess",
49 Phase::Compile => "compile",
50 Phase::Assemble => "assemble",
51 Phase::Archive => "archive",
52 Phase::Link => "link",
53 }
54 }
55}
56
57impl std::fmt::Display for Phase {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 f.write_str(self.as_str())
60 }
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65pub enum InputKind {
66 C,
68 CHeader,
70 PreprocessedC,
72 Ir,
80 Assembler,
82 AssemblerWithCpp,
85 LinkerInput,
87}
88
89impl InputKind {
90 #[must_use]
92 pub fn as_str(self) -> &'static str {
93 match self {
94 InputKind::C => "c",
95 InputKind::CHeader => "c-header",
96 InputKind::PreprocessedC => "cpp-output",
97 InputKind::Ir => "ir",
98 InputKind::Assembler => "assembler",
99 InputKind::AssemblerWithCpp => "assembler-with-cpp",
100 InputKind::LinkerInput => "linker-input",
101 }
102 }
103
104 pub fn from_x_arg(name: &str) -> Result<InputKind, XError> {
111 match name {
112 "c" => Ok(InputKind::C),
113 "c-header" => Ok(InputKind::CHeader),
114 "cpp-output" | "c-cpp-output" => Ok(InputKind::PreprocessedC),
115 "ir" => Ok(InputKind::Ir),
116 "assembler" => Ok(InputKind::Assembler),
117 "assembler-with-cpp" => Ok(InputKind::AssemblerWithCpp),
118 "c++" | "c++-header" | "c++-cpp-output" | "objective-c" | "objective-c++" => {
119 Err(XError::Unsupported(name.to_owned()))
120 }
121 _ => Err(XError::Unknown(name.to_owned())),
122 }
123 }
124
125 pub fn from_path(path: &str) -> Result<InputKind, XError> {
136 let ext = extension(path);
137 match ext {
138 "c" => Ok(InputKind::C),
142 "i" => Ok(InputKind::PreprocessedC),
143 "ir" => Ok(InputKind::Ir),
144 "h" => Ok(InputKind::CHeader),
145 "s" => Ok(InputKind::Assembler),
146 "S" | "sx" => Ok(InputKind::AssemblerWithCpp),
147 "cc" | "cpp" | "cxx" | "c++" | "C" | "hpp" | "hxx" | "ii" | "m" | "mm" => {
148 Err(XError::Unsupported(ext.to_owned()))
149 }
150 _ => Ok(InputKind::LinkerInput),
151 }
152 }
153
154 fn full_sequence(self) -> &'static [Phase] {
156 use Phase::{Assemble, Compile, Link, Preprocess};
157 match self {
158 InputKind::C | InputKind::CHeader => &[Preprocess, Compile, Assemble, Link],
159 InputKind::PreprocessedC | InputKind::Ir => &[Compile, Assemble, Link],
160 InputKind::AssemblerWithCpp => &[Preprocess, Assemble, Link],
163 InputKind::Assembler => &[Assemble, Link],
164 InputKind::LinkerInput => &[Link],
165 }
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
171pub enum XError {
172 Unknown(String),
174 Unsupported(String),
176}
177
178impl std::fmt::Display for XError {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 match self {
181 XError::Unknown(name) => {
182 write!(
183 f,
184 "unknown language `{name}`; \
185 accepted: c, c-header, cpp-output, ir, assembler, assembler-with-cpp, none"
186 )
187 }
188 XError::Unsupported(name) => {
189 write!(
190 f,
191 "`{name}` is not C, and this compiler is only ever going to compile C; \
192 see the not-in-scope list in spec/00-README.md"
193 )
194 }
195 }
196 }
197}
198
199impl std::error::Error for XError {}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Role {
211 File,
213 Library,
215 Linker,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct Input {
222 pub path: String,
225 pub forced: Option<InputKind>,
227 pub role: Role,
229}
230
231impl Input {
232 #[must_use]
234 pub fn new(path: impl Into<String>) -> Input {
235 Input { path: path.into(), forced: None, role: Role::File }
236 }
237
238 #[must_use]
240 pub fn library(name: impl Into<String>) -> Input {
241 Input { path: name.into(), forced: None, role: Role::Library }
242 }
243
244 #[must_use]
246 pub fn linker(arg: impl Into<String>) -> Input {
247 Input { path: arg.into(), forced: None, role: Role::Linker }
248 }
249
250 #[must_use]
252 pub fn named(&self) -> String {
253 match self.role {
254 Role::File => self.path.clone(),
255 Role::Library => format!("-l{}", self.path),
256 Role::Linker => format!("-Wl,{}", self.path),
257 }
258 }
259
260 pub fn kind(&self) -> Result<InputKind, XError> {
266 if self.role != Role::File {
267 return Ok(InputKind::LinkerInput);
268 }
269 match self.forced {
270 Some(k) => Ok(k),
271 None => InputKind::from_path(&self.path),
272 }
273 }
274}
275
276#[derive(Debug, Clone, PartialEq, Eq)]
278pub enum Output {
279 Stdout,
281 File(String),
283 Temporary(String),
286}
287
288impl Output {
289 fn render(&self) -> String {
290 match self {
291 Output::Stdout => "-".to_owned(),
292 Output::File(p) => p.clone(),
293 Output::Temporary(p) => format!("{p} (temporary)"),
294 }
295 }
296
297 fn as_link_input(&self) -> Option<&str> {
299 match self {
300 Output::File(p) | Output::Temporary(p) => Some(p),
301 Output::Stdout => None,
302 }
303 }
304}
305
306#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct Job {
309 pub input: String,
311 pub kind: InputKind,
313 pub phases: Vec<Phase>,
315 pub output: Output,
317 pub aux_base: Option<String>,
324}
325
326impl Job {
327 #[must_use]
333 pub fn saved_text(&self) -> Option<String> {
334 let base = self.aux_base.as_ref()?;
335 self.phases.contains(&Phase::Preprocess).then(|| format!("{base}.i"))
336 }
337
338 #[must_use]
343 pub fn saved_asm(&self) -> Option<String> {
344 let base = self.aux_base.as_ref()?;
345 let past = self.phases.last().is_some_and(|last| *last > Phase::Compile);
346 (past && self.phases.contains(&Phase::Compile)).then(|| format!("{base}.s"))
347 }
348}
349
350#[derive(Debug, Clone, PartialEq, Eq)]
352pub struct LinkJob {
353 pub inputs: Vec<Item>,
355 pub output: String,
357}
358
359#[derive(Debug, Clone, PartialEq, Eq)]
361pub struct ArchiveJob {
362 pub members: Vec<String>,
369 pub output: String,
371}
372
373#[derive(Debug, Clone, PartialEq, Eq)]
375pub struct Plan {
376 pub jobs: Vec<Job>,
378 pub link: Option<LinkJob>,
380 pub archive: Option<ArchiveJob>,
383 pub notes: Vec<String>,
386 pub output: Option<String>,
392}
393
394#[derive(Debug, Clone, PartialEq, Eq)]
396pub struct PlanError {
397 pub message: String,
399}
400
401impl std::fmt::Display for PlanError {
402 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403 f.write_str(&self.message)
404 }
405}
406
407impl std::error::Error for PlanError {}
408
409fn plan_err(message: impl Into<String>) -> PlanError {
410 PlanError { message: message.into() }
411}
412
413#[must_use]
418pub fn last_phase(emit: EmitKind) -> Phase {
419 match emit {
420 EmitKind::Preprocessed => Phase::Preprocess,
421 EmitKind::Asm
422 | EmitKind::Tast
423 | EmitKind::Ir
424 | EmitKind::MirFinal
425 | EmitKind::SafetySummary
426 | EmitKind::TypeGranules => Phase::Compile,
427 EmitKind::Object => Phase::Assemble,
428 EmitKind::Archive => Phase::Archive,
429 EmitKind::Executable => Phase::Link,
430 }
431}
432
433pub const STDIN: &str = "-";
435
436#[must_use]
441pub fn source_name(path: &str) -> &str {
442 if path == STDIN { "<stdin>" } else { path }
443}
444
445fn extension(path: &str) -> &str {
447 let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
448 match name.rfind('.') {
449 Some(0) | None => "",
451 Some(i) => &name[i + 1..],
452 }
453}
454
455fn file_part(path: &str) -> &str {
457 path.rsplit(['/', '\\']).next().unwrap_or(path)
458}
459
460fn without_extension(path: &str) -> &str {
465 let start = path.rfind(['/', '\\']).map_or(0, |i| i + 1);
466 match path[start..].rfind('.') {
467 Some(0) | None => path,
469 Some(i) => &path[..start + i],
470 }
471}
472
473fn stem(path: &str) -> &str {
476 file_part(without_extension(path))
477}
478
479fn aux_base(opts: &Options, input: &str, output: Option<&str>, collecting: bool) -> String {
491 let named = match output {
492 Some(o) => without_extension(o),
493 None if collecting => stem(default_exe(opts)),
497 None => stem(input),
498 };
499 let named = if opts.save_temps == SaveTemps::Cwd { file_part(named) } else { named };
500 if collecting { format!("{named}-{}", stem(input)) } else { named.to_owned() }
501}
502
503fn suffix_for(phase: Phase, opts: &Options) -> &'static str {
505 match phase {
506 Phase::Preprocess => "i",
507 Phase::Compile => match opts.emit {
511 EmitKind::Tast => "tast",
512 EmitKind::Ir => "ir",
513 EmitKind::MirFinal => "mir",
514 EmitKind::SafetySummary => "safety.json",
518 EmitKind::TypeGranules => "granules.txt",
521 _ => "s",
522 },
523 Phase::Assemble => {
526 if opts.target.os == Os::Windows {
527 "obj"
528 } else {
529 "o"
530 }
531 }
532 Phase::Archive | Phase::Link => "",
535 }
536}
537
538fn default_exe(opts: &Options) -> &'static str {
540 if opts.target.os == Os::Windows { "a.exe" } else { "a.out" }
541}
542
543impl Plan {
544 pub fn new(opts: &Options, inputs: &[Input], output: Option<&str>) -> Result<Plan, PlanError> {
553 if inputs.is_empty() {
554 return Err(plan_err("no input files"));
555 }
556 let last = last_phase(opts.emit);
557 let linking = last == Phase::Link;
558 let archiving = last == Phase::Archive;
559 if archiving && output.is_none() {
563 return Err(plan_err("an archive has no default name, so `--emit=archive` needs `-o`"));
564 }
565 let collecting = linking || archiving;
568
569 let mut kinds = Vec::with_capacity(inputs.len());
570 for input in inputs {
571 if input.role == Role::File && input.path == STDIN && input.forced.is_none() {
576 if opts.emit != EmitKind::Preprocessed {
577 return Err(plan_err("-E or -x required when input is from standard input"));
578 }
579 kinds.push(InputKind::C);
580 continue;
581 }
582 kinds.push(input.kind().map_err(|e| plan_err(format!("{}: {e}", input.path)))?);
583 }
584
585 let producing = if collecting {
590 0
591 } else {
592 kinds
593 .iter()
594 .filter(|k| **k != InputKind::LinkerInput)
595 .filter(|k| k.full_sequence().iter().any(|p| *p <= last))
596 .count()
597 };
598 if output.is_some() && !collecting && producing > 1 {
599 return Err(plan_err("cannot specify -o with multiple inputs when not linking"));
600 }
601
602 let mut notes = Vec::new();
603 let mut jobs = Vec::with_capacity(inputs.len());
604 let mut link_inputs = Vec::new();
605 let mut members = Vec::new();
606
607 for (input, kind) in inputs.iter().zip(kinds) {
608 if input.role == Role::Linker {
614 if linking {
615 link_inputs.push(Item::Linker(input.path.clone()));
616 }
617 continue;
618 }
619
620 if kind == InputKind::LinkerInput {
625 if archiving {
632 let named = input.named();
633 return Err(plan_err(format!(
634 "{named}: an archive is written from the objects this command line \
635 compiles, and the symbol index in it needs the names each member \
636 defines, which this compiler knows for a file it compiled and not for \
637 one it was handed"
638 )));
639 }
640 if linking {
641 link_inputs.push(if input.role == Role::Library {
642 Item::Library(input.path.clone())
643 } else {
644 Item::File(input.path.clone())
645 });
646 } else {
647 notes.push(format!(
650 "{}: linker input unused because linking was not requested",
651 input.named()
652 ));
653 }
654 if input.role == Role::Library {
658 continue;
659 }
660 jobs.push(Job {
661 input: input.path.clone(),
662 kind,
663 phases: Vec::new(),
664 output: Output::File(input.path.clone()),
665 aux_base: None,
666 });
667 continue;
668 }
669
670 let phases: Vec<Phase> =
671 kind.full_sequence().iter().copied().filter(|p| *p <= last).collect();
672 let Some(&final_phase) = phases.last() else {
676 notes.push(format!(
677 "{}: input unused because it enters the pipeline after the last phase \
678 the mode flags asked for",
679 input.path
680 ));
681 jobs.push(Job {
682 input: input.path.clone(),
683 kind,
684 phases,
685 output: Output::File(input.path.clone()),
686 aux_base: None,
687 });
688 continue;
689 };
690 let named = if producing == 1 { output } else { None };
691 let aux = (opts.save_temps.wanted() && final_phase > Phase::Preprocess)
695 .then(|| aux_base(opts, &input.path, output, collecting));
696 let out = if final_phase == Phase::Link || archiving {
697 let ext = suffix_for(Phase::Assemble, opts);
701 match &aux {
702 Some(base) => Output::File(format!("{base}.{ext}")),
703 None => Output::Temporary(format!("{}.{ext}", stem(&input.path))),
704 }
705 } else if let Some(o) = named {
706 if o == "-" { Output::Stdout } else { Output::File(o.to_owned()) }
711 } else if final_phase == Phase::Preprocess {
712 Output::Stdout
715 } else {
716 Output::File(format!("{}.{}", stem(&input.path), suffix_for(final_phase, opts)))
717 };
718 if let Output::File(path) = &out {
723 if *path == input.path {
724 return Err(plan_err(format!(
725 "input file `{}` is the same as the output file",
726 input.path
727 )));
728 }
729 }
730
731 if linking {
732 if let Some(p) = out.as_link_input() {
733 link_inputs.push(Item::File(p.to_owned()));
734 }
735 }
736 if archiving {
737 members.push(format!(
741 "{}.{}",
742 stem(&input.path),
743 suffix_for(Phase::Assemble, opts)
744 ));
745 }
746 jobs.push(Job { input: input.path.clone(), kind, phases, output: out, aux_base: aux });
747 }
748
749 let link = linking.then(|| LinkJob {
750 inputs: link_inputs,
751 output: output.unwrap_or(default_exe(opts)).to_owned(),
752 });
753 let archive = archiving.then(|| ArchiveJob {
754 members,
755 output: output.unwrap_or_default().to_owned(),
758 });
759
760 Ok(Plan { jobs, link, archive, notes, output: output.map(str::to_owned) })
761 }
762
763 #[must_use]
769 pub fn render(&self) -> String {
770 let mut out = String::new();
771 for note in &self.notes {
772 let _ = writeln!(out, "note: {note}");
773 }
774 for job in &self.jobs {
775 if job.phases.is_empty() {
779 continue;
780 }
781 let names: Vec<&str> = job.phases.iter().map(|p| p.as_str()).collect();
782 let _ = writeln!(out, "{}: {} -> {}", job.input, names.join(", "), job.output.render());
783 let kept: Vec<String> =
786 [job.saved_text(), job.saved_asm()].into_iter().flatten().collect();
787 if !kept.is_empty() {
788 let _ = writeln!(out, "{}: keeping {}", job.input, kept.join(", "));
789 }
790 }
791 if let Some(link) = &self.link {
792 let names: Vec<String> = link.inputs.iter().map(ToString::to_string).collect();
793 let _ = writeln!(out, "link: {} -> {}", names.join(" "), link.output);
794 }
795 if let Some(archive) = &self.archive {
796 let _ = writeln!(out, "archive: {} -> {}", archive.members.join(" "), archive.output);
797 }
798 out
799 }
800}
801
802#[cfg(test)]
803mod tests {
804 use rucc_session::Options;
805
806 use super::*;
807
808 fn opts(triple: &str) -> Options {
809 Options::new(triple.parse().expect("test triple"))
810 }
811
812 fn linux() -> Options {
813 opts("x86_64-unknown-linux-gnu")
814 }
815
816 fn plan(o: &Options, paths: &[&str], output: Option<&str>) -> Plan {
817 let inputs: Vec<Input> = paths.iter().map(|p| Input::new(*p)).collect();
818 Plan::new(o, &inputs, output).expect("expected a plan")
819 }
820
821 #[test]
822 fn extensions_map_to_the_table_in_the_spec() {
823 assert_eq!(InputKind::from_path("a.c").unwrap(), InputKind::C);
824 assert_eq!(InputKind::from_path("a.i").unwrap(), InputKind::PreprocessedC);
825 assert_eq!(InputKind::from_path("a.ir").unwrap(), InputKind::Ir);
826 assert_eq!(InputKind::from_path("a.h").unwrap(), InputKind::CHeader);
827 assert_eq!(InputKind::from_path("a.s").unwrap(), InputKind::Assembler);
828 assert_eq!(InputKind::from_path("a.S").unwrap(), InputKind::AssemblerWithCpp);
829 assert_eq!(InputKind::from_path("a.sx").unwrap(), InputKind::AssemblerWithCpp);
830 assert_eq!(InputKind::from_path("a.o").unwrap(), InputKind::LinkerInput);
831 assert_eq!(InputKind::from_path("libm.a").unwrap(), InputKind::LinkerInput);
832 assert_eq!(InputKind::from_path("libm.so.6").unwrap(), InputKind::LinkerInput);
833 }
834
835 #[test]
836 fn standard_input_is_c_under_dash_e_and_wants_telling_otherwise() {
837 let mut o = linux();
842 o.emit = EmitKind::Preprocessed;
843 let plan = plan(&o, &["-"], None);
844 assert_eq!(plan.jobs.len(), 1);
845 assert_eq!(plan.jobs[0].kind, InputKind::C);
846 assert_eq!(plan.jobs[0].phases, [Phase::Preprocess]);
847 assert_eq!(plan.jobs[0].output, Output::Stdout);
848
849 let o = linux();
850 let error = Plan::new(&o, &[Input::new("-")], None).expect_err("expected this refused");
851 assert_eq!(error.message, "-E or -x required when input is from standard input");
852
853 let mut o = linux();
856 o.emit = EmitKind::Object;
857 let inputs = [Input { path: "-".to_owned(), forced: Some(InputKind::C), role: Role::File }];
858 let plan = Plan::new(&o, &inputs, None).expect("expected a plan");
859 assert_eq!(plan.jobs[0].kind, InputKind::C);
860 assert_eq!(plan.jobs[0].output, Output::File("-.o".to_owned()));
861 }
862
863 #[test]
864 fn standard_input_is_named_the_way_gcc_names_it_and_a_file_is_named_after_itself() {
865 assert_eq!(source_name("-"), "<stdin>");
866 assert_eq!(source_name("a.c"), "a.c");
867 assert_eq!(source_name("sub/-"), "sub/-");
868 }
869
870 #[test]
871 fn ir_enters_where_preprocessed_c_does_and_needs_no_preprocessor() {
872 assert_eq!(InputKind::from_x_arg("ir").unwrap(), InputKind::Ir);
875 assert_eq!(InputKind::Ir.as_str(), "ir");
876 assert_eq!(InputKind::Ir.full_sequence(), InputKind::PreprocessedC.full_sequence());
877 assert!(!InputKind::Ir.full_sequence().contains(&Phase::Preprocess));
878 }
879
880 #[test]
881 fn an_input_whose_output_has_its_own_name_is_refused_rather_than_written_over() {
882 let mut o = linux();
885 o.emit = EmitKind::Ir;
886 let inputs = [Input::new("a.ir")];
887 let error = Plan::new(&o, &inputs, None).expect_err("expected this to be refused");
888 assert!(error.message.contains("is the same as the output file"), "{error}");
889 assert!(Plan::new(&o, &inputs, Some("b.ir")).is_ok());
892 assert!(Plan::new(&o, &inputs, Some("a.ir")).is_err());
893 }
894
895 #[test]
896 fn capital_s_and_small_s_are_different_languages() {
897 let hi = InputKind::from_path("a.S").unwrap();
900 let lo = InputKind::from_path("a.s").unwrap();
901 assert_ne!(hi, lo);
902 assert!(hi.full_sequence().contains(&Phase::Preprocess));
903 assert!(!lo.full_sequence().contains(&Phase::Preprocess));
904 }
905
906 #[test]
907 fn a_cplusplus_source_says_why_rather_than_failing_at_link_time() {
908 let e = InputKind::from_path("a.cpp").unwrap_err();
909 assert!(format!("{e}").contains("only ever going to compile C"), "{e}");
910 let e = InputKind::from_x_arg("c++").unwrap_err();
911 assert!(matches!(e, XError::Unsupported(_)), "{e:?}");
912 }
913
914 #[test]
915 fn a_file_with_no_extension_goes_to_the_linker() {
916 assert_eq!(InputKind::from_path("crt1").unwrap(), InputKind::LinkerInput);
917 assert_eq!(InputKind::from_path(".bashrc").unwrap(), InputKind::LinkerInput);
918 }
919
920 #[test]
921 fn the_default_line_compiles_and_links_to_a_out() {
922 let p = plan(&linux(), &["a.c"], None);
923 assert_eq!(
924 p.jobs[0].phases,
925 vec![Phase::Preprocess, Phase::Compile, Phase::Assemble, Phase::Link]
926 );
927 assert_eq!(p.jobs[0].output, Output::Temporary("a.o".into()));
928 let link = p.link.expect("expected a link step");
929 assert_eq!(link.inputs, vec![Item::File("a.o".into())]);
930 assert_eq!(link.output, "a.out");
931 }
932
933 #[test]
934 fn dash_c_stops_at_the_object_and_names_it_after_the_source() {
935 let mut o = linux();
936 o.emit = EmitKind::Object;
937 let p = plan(&o, &["src/a.c", "src/b.c"], None);
938 assert!(p.link.is_none());
939 assert_eq!(p.jobs[0].output, Output::File("a.o".into()));
940 assert_eq!(p.jobs[1].output, Output::File("b.o".into()));
941 assert_eq!(p.jobs[0].phases.last(), Some(&Phase::Assemble));
944 }
945
946 #[test]
947 fn dash_e_writes_to_stdout_unless_it_is_given_a_name() {
948 let mut o = linux();
949 o.emit = EmitKind::Preprocessed;
950 assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::Stdout);
951 assert_eq!(plan(&o, &["a.c"], Some("a.i")).jobs[0].output, Output::File("a.i".into()));
952 }
953
954 #[test]
955 fn a_name_of_one_dash_is_standard_output_and_not_a_file_called_that() {
956 let mut o = linux();
957 o.emit = EmitKind::Preprocessed;
958 assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
959 o.emit = EmitKind::Object;
960 assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
961 let p = plan(&linux(), &["a.c"], Some("-"));
964 assert_eq!(p.link.expect("a link step").output, "-");
965 }
966
967 #[test]
968 fn dash_s_produces_assembly_named_after_the_source() {
969 let mut o = linux();
970 o.emit = EmitKind::Asm;
971 let p = plan(&o, &["dir/a.c"], None);
972 assert_eq!(p.jobs[0].output, Output::File("a.s".into()));
973 assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Compile]);
974 }
975
976 #[test]
977 fn an_already_preprocessed_file_skips_the_preprocessor() {
978 let p = plan(&linux(), &["a.i"], None);
979 assert_eq!(p.jobs[0].phases, vec![Phase::Compile, Phase::Assemble, Phase::Link]);
980 }
981
982 #[test]
983 fn assembly_with_a_capital_s_is_preprocessed_but_not_compiled() {
984 let p = plan(&linux(), &["a.S"], None);
985 assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Assemble, Phase::Link]);
986 assert!(!p.jobs[0].phases.contains(&Phase::Compile));
987 }
988
989 #[test]
990 fn objects_on_the_line_reach_the_linker_in_the_order_they_were_written() {
991 let p = plan(&linux(), &["a.o", "b.c", "libm.a"], None);
994 let link = p.link.expect("expected a link step");
995 assert_eq!(
996 link.inputs,
997 vec![Item::File("a.o".into()), Item::File("b.o".into()), Item::File("libm.a".into()),]
998 );
999 }
1000
1001 #[test]
1002 fn an_object_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1003 let mut o = linux();
1005 o.emit = EmitKind::Object;
1006 let p = plan(&o, &["a.c", "b.o"], None);
1007 assert!(p.jobs[1].phases.is_empty());
1008 assert_eq!(p.notes.len(), 1);
1009 assert!(p.notes[0].contains("linker input unused"), "{:?}", p.notes);
1010 }
1011
1012 #[test]
1013 fn dash_o_with_several_compilations_is_rejected() {
1014 let mut o = linux();
1015 o.emit = EmitKind::Object;
1016 let inputs = [Input::new("a.c"), Input::new("b.c")];
1017 let e = Plan::new(&o, &inputs, Some("out.o")).unwrap_err();
1018 assert!(e.message.contains("multiple inputs"), "{}", e.message);
1019 }
1020
1021 #[test]
1022 fn dash_o_with_one_compilation_and_some_objects_is_fine() {
1023 let mut o = linux();
1026 o.emit = EmitKind::Object;
1027 let inputs = [Input::new("a.c"), Input::new("b.o")];
1028 let p = Plan::new(&o, &inputs, Some("out.o")).expect("expected a plan");
1029 assert_eq!(p.jobs[0].output, Output::File("out.o".into()));
1030 }
1031
1032 #[test]
1033 fn dash_x_overrides_the_extension() {
1034 let inputs = [Input { path: "a.txt".into(), forced: Some(InputKind::C), role: Role::File }];
1035 let p = Plan::new(&linux(), &inputs, None).expect("expected a plan");
1036 assert_eq!(p.jobs[0].kind, InputKind::C);
1037 assert_eq!(p.jobs[0].phases.first(), Some(&Phase::Preprocess));
1038 }
1039
1040 #[test]
1041 fn windows_gets_obj_and_a_exe() {
1042 let o = opts("x86_64-pc-windows-msvc");
1043 let p = plan(&o, &["a.c"], None);
1044 assert_eq!(p.jobs[0].output, Output::Temporary("a.obj".into()));
1045 assert_eq!(p.link.expect("expected a link step").output, "a.exe");
1046 }
1047
1048 #[test]
1050 fn an_archive_is_one_file_however_many_inputs_there_are() {
1051 let mut o = linux();
1052 o.emit = EmitKind::Archive;
1053 let p = plan(&o, &["a.c", "sub/b.c"], Some("out/libx.a"));
1054 assert_eq!(p.jobs.len(), 2);
1055 for job in &p.jobs {
1056 assert_eq!(job.phases.last(), Some(&Phase::Assemble), "{}", job.input);
1059 assert!(matches!(job.output, Output::Temporary(_)), "{:?}", job.output);
1060 }
1061 let archive = p.archive.expect("an archive step");
1062 assert_eq!(archive.members, ["a.o", "b.o"]);
1063 assert_eq!(archive.output, "out/libx.a");
1064 assert!(p.link.is_none(), "one command line produces one of the two and not both");
1065 }
1066
1067 #[test]
1068 fn a_member_is_called_what_an_object_is_called_on_this_target() {
1069 let mut o = opts("x86_64-pc-windows-msvc");
1070 o.emit = EmitKind::Archive;
1071 let p = plan(&o, &["a.c"], Some("x.lib"));
1072 assert_eq!(p.archive.expect("an archive step").members, ["a.obj"]);
1073 }
1074
1075 #[test]
1078 fn an_archive_has_no_default_name() {
1079 let mut o = linux();
1080 o.emit = EmitKind::Archive;
1081 let inputs = [Input::new("a.c")];
1082 let error = Plan::new(&o, &inputs, None).expect_err("no name for the archive");
1083 assert!(error.message.contains("needs `-o`"), "{error}");
1084 }
1085
1086 #[test]
1089 fn something_this_compilation_did_not_produce_cannot_go_into_an_archive() {
1090 let mut o = linux();
1091 o.emit = EmitKind::Archive;
1092 for handed in [Input::new("b.o"), Input::library("m")] {
1093 let inputs = [Input::new("a.c"), handed];
1094 let error = Plan::new(&o, &inputs, Some("libx.a")).expect_err("not ours to index");
1095 assert!(error.message.contains("names each member"), "{error}");
1096 }
1097 }
1098
1099 #[test]
1100 fn the_plan_says_what_goes_into_the_archive() {
1101 let mut o = linux();
1102 o.emit = EmitKind::Archive;
1103 let text = plan(&o, &["a.c", "b.c"], Some("libx.a")).render();
1104 assert!(text.contains("archive: a.o b.o -> libx.a"), "{text}");
1105 assert!(!text.contains("link:"), "{text}");
1106 }
1107
1108 #[test]
1109 fn the_intermediate_dumps_stop_where_dash_s_stops() {
1110 for emit in [
1111 EmitKind::Tast,
1112 EmitKind::Ir,
1113 EmitKind::MirFinal,
1114 EmitKind::SafetySummary,
1115 EmitKind::TypeGranules,
1116 ] {
1117 assert_eq!(last_phase(emit), Phase::Compile, "{emit:?}");
1118 }
1119 }
1120
1121 #[test]
1122 fn each_intermediate_dump_is_a_language_of_its_own_and_gets_a_suffix_of_its_own() {
1123 for (emit, name) in [
1126 (EmitKind::Asm, "a.s"),
1127 (EmitKind::Tast, "a.tast"),
1128 (EmitKind::Ir, "a.ir"),
1129 (EmitKind::MirFinal, "a.mir"),
1130 (EmitKind::SafetySummary, "a.safety.json"),
1131 (EmitKind::TypeGranules, "a.granules.txt"),
1132 ] {
1133 let mut o = linux();
1134 o.emit = emit;
1135 assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::File(name.into()));
1136 }
1137 }
1138
1139 #[test]
1140 fn an_input_that_enters_after_the_last_phase_is_a_note_rather_than_an_error() {
1141 let mut o = linux();
1144 o.emit = EmitKind::Preprocessed;
1145 let p = plan(&o, &["a.c", "b.s"], None);
1146 assert!(p.jobs[1].phases.is_empty());
1147 assert_eq!(p.notes.len(), 1);
1148 assert!(p.notes[0].contains("after the last phase"), "{:?}", p.notes);
1149 let inputs = [Input::new("a.c"), Input::new("b.s")];
1151 assert!(Plan::new(&o, &inputs, Some("out.i")).is_ok());
1152 }
1153
1154 #[test]
1155 fn no_inputs_is_an_error() {
1156 assert!(Plan::new(&linux(), &[], None).is_err());
1157 }
1158
1159 fn keeping(kind: SaveTemps, emit: EmitKind, paths: &[&str], output: Option<&str>) -> Plan {
1161 let mut o = linux();
1162 o.emit = emit;
1163 o.save_temps = kind;
1164 plan(&o, paths, output)
1165 }
1166
1167 fn kept(plan: &Plan, at: usize) -> Vec<String> {
1169 [plan.jobs[at].saved_text(), plan.jobs[at].saved_asm()].into_iter().flatten().collect()
1170 }
1171
1172 #[test]
1173 fn the_files_that_are_kept_land_beside_the_output_and_not_where_the_manual_says() {
1174 let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.c"], Some("out/t.o"));
1178 assert_eq!(kept(&p, 0), vec!["out/t.i", "out/t.s"]);
1179 let p = keeping(SaveTemps::Cwd, EmitKind::Object, &["t.c"], Some("out/t.o"));
1180 assert_eq!(kept(&p, 0), vec!["t.i", "t.s"]);
1181 }
1182
1183 #[test]
1184 fn the_name_comes_off_the_output_rather_than_off_the_input_that_produced_it() {
1185 let p = keeping(SaveTemps::Cwd, EmitKind::Object, &["t.c"], Some("out/x.o"));
1188 assert_eq!(kept(&p, 0), vec!["x.i", "x.s"]);
1189 let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.c"], Some("out/noext"));
1190 assert_eq!(kept(&p, 0), vec!["out/noext.i", "out/noext.s"]);
1191 }
1192
1193 #[test]
1194 fn without_a_name_they_are_called_after_the_input_and_are_where_the_object_would_be() {
1195 for kind in [SaveTemps::Object, SaveTemps::Cwd] {
1198 let p = keeping(kind, EmitKind::Object, &["sub/u.c"], None);
1199 assert_eq!(kept(&p, 0), vec!["u.i", "u.s"], "{kind:?}");
1200 assert_eq!(p.jobs[0].output, Output::File("u.o".into()), "{kind:?}");
1201 }
1202 }
1203
1204 #[test]
1205 fn a_command_line_that_links_names_them_after_the_executable_and_the_input() {
1206 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c", "sub/u.c"], Some("o/p"));
1209 assert_eq!(kept(&p, 0), vec!["o/p-t.i", "o/p-t.s"]);
1210 assert_eq!(kept(&p, 1), vec!["o/p-u.i", "o/p-u.s"]);
1211 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c"], None);
1214 assert_eq!(kept(&p, 0), vec!["a-t.i", "a-t.s"]);
1215 }
1216
1217 #[test]
1218 fn the_object_a_link_reads_is_kept_rather_than_written_where_it_will_be_removed() {
1219 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c"], Some("out/prog"));
1223 assert_eq!(p.jobs[0].output, Output::File("out/prog-t.o".into()));
1224 let plain = plan(&linux(), &["t.c"], Some("out/prog"));
1225 assert_eq!(plain.jobs[0].output, Output::Temporary("t.o".into()));
1226 }
1227
1228 #[test]
1229 fn a_step_whose_result_is_already_being_written_is_not_kept_a_second_time() {
1230 let p = keeping(SaveTemps::Object, EmitKind::Preprocessed, &["t.c"], None);
1233 assert_eq!(p.jobs[0].aux_base, None);
1234 assert_eq!(kept(&p, 0), Vec::<String>::new());
1235 let p = keeping(SaveTemps::Object, EmitKind::Asm, &["t.c"], None);
1236 assert_eq!(kept(&p, 0), vec!["t.i"]);
1237 }
1238
1239 #[test]
1240 fn an_input_that_arrives_preprocessed_has_no_text_of_its_own_to_keep() {
1241 let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.i"], None);
1244 assert_eq!(kept(&p, 0), vec!["t.s"]);
1245 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.o"], None);
1247 assert_eq!(p.jobs[0].aux_base, None);
1248 }
1249
1250 #[test]
1251 fn nothing_is_kept_when_the_flag_was_not_given() {
1252 let p = plan(&linux(), &["t.c"], None);
1253 assert_eq!(p.jobs[0].aux_base, None);
1254 assert_eq!(kept(&p, 0), Vec::<String>::new());
1255 }
1256
1257 #[test]
1258 fn the_rendering_says_what_will_happen() {
1259 let p = plan(&linux(), &["a.c", "b.o"], None);
1260 let text = p.render();
1261 assert!(
1262 text.contains("a.c: preprocess, compile, assemble, link -> a.o (temporary)"),
1263 "{text}"
1264 );
1265 assert!(text.contains("link: a.o b.o -> a.out"), "{text}");
1266 assert_eq!(text.matches("b.o").count(), 1, "{text}");
1268 }
1269
1270 #[test]
1271 fn the_rendering_names_the_files_that_will_be_kept() {
1272 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["a.c"], None);
1275 let text = p.render();
1276 assert!(text.contains("a.c: keeping a-a.i, a-a.s"), "{text}");
1277 assert!(!plan(&linux(), &["a.c"], None).render().contains("keeping"));
1278 }
1279}