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
427 | EmitKind::SyntaxOnly => Phase::Compile,
428 EmitKind::Object => Phase::Assemble,
429 EmitKind::Archive => Phase::Archive,
430 EmitKind::Executable => Phase::Link,
431 }
432}
433
434pub const STDIN: &str = "-";
436
437#[must_use]
442pub fn source_name(path: &str) -> &str {
443 if path == STDIN { "<stdin>" } else { path }
444}
445
446fn extension(path: &str) -> &str {
448 let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
449 match name.rfind('.') {
450 Some(0) | None => "",
452 Some(i) => &name[i + 1..],
453 }
454}
455
456fn file_part(path: &str) -> &str {
458 path.rsplit(['/', '\\']).next().unwrap_or(path)
459}
460
461fn without_extension(path: &str) -> &str {
466 let start = path.rfind(['/', '\\']).map_or(0, |i| i + 1);
467 match path[start..].rfind('.') {
468 Some(0) | None => path,
470 Some(i) => &path[..start + i],
471 }
472}
473
474fn stem(path: &str) -> &str {
477 file_part(without_extension(path))
478}
479
480fn aux_base(opts: &Options, input: &str, output: Option<&str>, collecting: bool) -> String {
492 let named = match output {
493 Some(o) => without_extension(o),
494 None if collecting => stem(default_exe(opts)),
498 None => stem(input),
499 };
500 let named = if opts.save_temps == SaveTemps::Cwd { file_part(named) } else { named };
501 if collecting { format!("{named}-{}", stem(input)) } else { named.to_owned() }
502}
503
504fn suffix_for(phase: Phase, opts: &Options) -> &'static str {
506 match phase {
507 Phase::Preprocess => "i",
508 Phase::Compile => match opts.emit {
512 EmitKind::Tast => "tast",
513 EmitKind::Ir => "ir",
514 EmitKind::MirFinal => "mir",
515 EmitKind::SafetySummary => "safety.json",
519 EmitKind::TypeGranules => "granules.txt",
522 _ => "s",
523 },
524 Phase::Assemble => {
527 if opts.target.os == Os::Windows {
528 "obj"
529 } else {
530 "o"
531 }
532 }
533 Phase::Archive | Phase::Link => "",
536 }
537}
538
539fn default_exe(opts: &Options) -> &'static str {
541 if opts.target.os == Os::Windows { "a.exe" } else { "a.out" }
542}
543
544impl Plan {
545 pub fn new(opts: &Options, inputs: &[Input], output: Option<&str>) -> Result<Plan, PlanError> {
554 if inputs.is_empty() {
555 return Err(plan_err("no input files"));
556 }
557 let last = last_phase(opts.emit);
558 let linking = last == Phase::Link;
559 let archiving = last == Phase::Archive;
560 if archiving && output.is_none() {
564 return Err(plan_err("an archive has no default name, so `--emit=archive` needs `-o`"));
565 }
566 let collecting = linking || archiving;
569
570 let mut kinds = Vec::with_capacity(inputs.len());
571 for input in inputs {
572 if input.role == Role::File && input.path == STDIN && input.forced.is_none() {
577 if opts.emit != EmitKind::Preprocessed {
578 return Err(plan_err("-E or -x required when input is from standard input"));
579 }
580 kinds.push(InputKind::C);
581 continue;
582 }
583 kinds.push(input.kind().map_err(|e| plan_err(format!("{}: {e}", input.path)))?);
584 }
585
586 let producing = if collecting {
591 0
592 } else {
593 kinds
594 .iter()
595 .filter(|k| **k != InputKind::LinkerInput)
596 .filter(|k| k.full_sequence().iter().any(|p| *p <= last))
597 .count()
598 };
599 if output.is_some() && !collecting && producing > 1 {
600 return Err(plan_err("cannot specify -o with multiple inputs when not linking"));
601 }
602
603 let mut notes = Vec::new();
604 let mut jobs = Vec::with_capacity(inputs.len());
605 let mut link_inputs = Vec::new();
606 let mut members = Vec::new();
607
608 for (input, kind) in inputs.iter().zip(kinds) {
609 if input.role == Role::Linker {
615 if linking {
616 link_inputs.push(Item::Linker(input.path.clone()));
617 }
618 continue;
619 }
620
621 if kind == InputKind::LinkerInput {
626 if archiving {
633 let named = input.named();
634 return Err(plan_err(format!(
635 "{named}: an archive is written from the objects this command line \
636 compiles, and the symbol index in it needs the names each member \
637 defines, which this compiler knows for a file it compiled and not for \
638 one it was handed"
639 )));
640 }
641 if linking {
642 link_inputs.push(if input.role == Role::Library {
643 Item::Library(input.path.clone())
644 } else {
645 Item::File(input.path.clone())
646 });
647 } else {
648 notes.push(format!(
651 "{}: linker input unused because linking was not requested",
652 input.named()
653 ));
654 }
655 if input.role == Role::Library {
659 continue;
660 }
661 jobs.push(Job {
662 input: input.path.clone(),
663 kind,
664 phases: Vec::new(),
665 output: Output::File(input.path.clone()),
666 aux_base: None,
667 });
668 continue;
669 }
670
671 let phases: Vec<Phase> =
672 kind.full_sequence().iter().copied().filter(|p| *p <= last).collect();
673 let Some(&final_phase) = phases.last() else {
677 notes.push(format!(
678 "{}: input unused because it enters the pipeline after the last phase \
679 the mode flags asked for",
680 input.path
681 ));
682 jobs.push(Job {
683 input: input.path.clone(),
684 kind,
685 phases,
686 output: Output::File(input.path.clone()),
687 aux_base: None,
688 });
689 continue;
690 };
691 let named = if producing == 1 { output } else { None };
692 let aux = (opts.save_temps.wanted() && final_phase > Phase::Preprocess)
696 .then(|| aux_base(opts, &input.path, output, collecting));
697 let out = if final_phase == Phase::Link || archiving {
698 let ext = suffix_for(Phase::Assemble, opts);
702 match &aux {
703 Some(base) => Output::File(format!("{base}.{ext}")),
704 None => Output::Temporary(format!("{}.{ext}", stem(&input.path))),
705 }
706 } else if opts.emit == EmitKind::SyntaxOnly {
707 Output::Stdout
710 } else if let Some(o) = named {
711 if o == "-" { Output::Stdout } else { Output::File(o.to_owned()) }
716 } else if final_phase == Phase::Preprocess {
717 Output::Stdout
720 } else {
721 Output::File(format!("{}.{}", stem(&input.path), suffix_for(final_phase, opts)))
722 };
723 if let Output::File(path) = &out {
731 if *path == input.path && path != "/dev/null" {
732 return Err(plan_err(format!(
733 "input file `{}` is the same as the output file",
734 input.path
735 )));
736 }
737 }
738
739 if linking {
740 if let Some(p) = out.as_link_input() {
741 link_inputs.push(Item::File(p.to_owned()));
742 }
743 }
744 if archiving {
745 members.push(format!(
749 "{}.{}",
750 stem(&input.path),
751 suffix_for(Phase::Assemble, opts)
752 ));
753 }
754 jobs.push(Job { input: input.path.clone(), kind, phases, output: out, aux_base: aux });
755 }
756
757 let link = linking.then(|| LinkJob {
758 inputs: link_inputs,
759 output: output.unwrap_or(default_exe(opts)).to_owned(),
760 });
761 let archive = archiving.then(|| ArchiveJob {
762 members,
763 output: output.unwrap_or_default().to_owned(),
766 });
767
768 Ok(Plan { jobs, link, archive, notes, output: output.map(str::to_owned) })
769 }
770
771 #[must_use]
777 pub fn render(&self) -> String {
778 let mut out = String::new();
779 for note in &self.notes {
780 let _ = writeln!(out, "note: {note}");
781 }
782 for job in &self.jobs {
783 if job.phases.is_empty() {
787 continue;
788 }
789 let names: Vec<&str> = job.phases.iter().map(|p| p.as_str()).collect();
790 let _ = writeln!(out, "{}: {} -> {}", job.input, names.join(", "), job.output.render());
791 let kept: Vec<String> =
794 [job.saved_text(), job.saved_asm()].into_iter().flatten().collect();
795 if !kept.is_empty() {
796 let _ = writeln!(out, "{}: keeping {}", job.input, kept.join(", "));
797 }
798 }
799 if let Some(link) = &self.link {
800 let names: Vec<String> = link.inputs.iter().map(ToString::to_string).collect();
801 let _ = writeln!(out, "link: {} -> {}", names.join(" "), link.output);
802 }
803 if let Some(archive) = &self.archive {
804 let _ = writeln!(out, "archive: {} -> {}", archive.members.join(" "), archive.output);
805 }
806 out
807 }
808}
809
810#[cfg(test)]
811mod tests {
812 use rucc_session::Options;
813
814 use super::*;
815
816 fn opts(triple: &str) -> Options {
817 Options::new(triple.parse().expect("test triple"))
818 }
819
820 fn linux() -> Options {
821 opts("x86_64-unknown-linux-gnu")
822 }
823
824 fn plan(o: &Options, paths: &[&str], output: Option<&str>) -> Plan {
825 let inputs: Vec<Input> = paths.iter().map(|p| Input::new(*p)).collect();
826 Plan::new(o, &inputs, output).expect("expected a plan")
827 }
828
829 #[test]
830 fn extensions_map_to_the_table_in_the_spec() {
831 assert_eq!(InputKind::from_path("a.c").unwrap(), InputKind::C);
832 assert_eq!(InputKind::from_path("a.i").unwrap(), InputKind::PreprocessedC);
833 assert_eq!(InputKind::from_path("a.ir").unwrap(), InputKind::Ir);
834 assert_eq!(InputKind::from_path("a.h").unwrap(), InputKind::CHeader);
835 assert_eq!(InputKind::from_path("a.s").unwrap(), InputKind::Assembler);
836 assert_eq!(InputKind::from_path("a.S").unwrap(), InputKind::AssemblerWithCpp);
837 assert_eq!(InputKind::from_path("a.sx").unwrap(), InputKind::AssemblerWithCpp);
838 assert_eq!(InputKind::from_path("a.o").unwrap(), InputKind::LinkerInput);
839 assert_eq!(InputKind::from_path("libm.a").unwrap(), InputKind::LinkerInput);
840 assert_eq!(InputKind::from_path("libm.so.6").unwrap(), InputKind::LinkerInput);
841 }
842
843 #[test]
844 fn standard_input_is_c_under_dash_e_and_wants_telling_otherwise() {
845 let mut o = linux();
850 o.emit = EmitKind::Preprocessed;
851 let plan = plan(&o, &["-"], None);
852 assert_eq!(plan.jobs.len(), 1);
853 assert_eq!(plan.jobs[0].kind, InputKind::C);
854 assert_eq!(plan.jobs[0].phases, [Phase::Preprocess]);
855 assert_eq!(plan.jobs[0].output, Output::Stdout);
856
857 let o = linux();
858 let error = Plan::new(&o, &[Input::new("-")], None).expect_err("expected this refused");
859 assert_eq!(error.message, "-E or -x required when input is from standard input");
860
861 let mut o = linux();
864 o.emit = EmitKind::Object;
865 let inputs = [Input { path: "-".to_owned(), forced: Some(InputKind::C), role: Role::File }];
866 let plan = Plan::new(&o, &inputs, None).expect("expected a plan");
867 assert_eq!(plan.jobs[0].kind, InputKind::C);
868 assert_eq!(plan.jobs[0].output, Output::File("-.o".to_owned()));
869 }
870
871 #[test]
872 fn standard_input_is_named_the_way_gcc_names_it_and_a_file_is_named_after_itself() {
873 assert_eq!(source_name("-"), "<stdin>");
874 assert_eq!(source_name("a.c"), "a.c");
875 assert_eq!(source_name("sub/-"), "sub/-");
876 }
877
878 #[test]
879 fn ir_enters_where_preprocessed_c_does_and_needs_no_preprocessor() {
880 assert_eq!(InputKind::from_x_arg("ir").unwrap(), InputKind::Ir);
883 assert_eq!(InputKind::Ir.as_str(), "ir");
884 assert_eq!(InputKind::Ir.full_sequence(), InputKind::PreprocessedC.full_sequence());
885 assert!(!InputKind::Ir.full_sequence().contains(&Phase::Preprocess));
886 }
887
888 #[test]
889 fn an_input_whose_output_has_its_own_name_is_refused_rather_than_written_over() {
890 let mut o = linux();
893 o.emit = EmitKind::Ir;
894 let inputs = [Input::new("a.ir")];
895 let error = Plan::new(&o, &inputs, None).expect_err("expected this to be refused");
896 assert!(error.message.contains("is the same as the output file"), "{error}");
897 assert!(Plan::new(&o, &inputs, Some("b.ir")).is_ok());
900 assert!(Plan::new(&o, &inputs, Some("a.ir")).is_err());
901 let null = Input { forced: Some(InputKind::C), ..Input::new("/dev/null") };
904 assert!(Plan::new(&linux(), &[null], Some("/dev/null")).is_ok());
905 }
906
907 #[test]
908 fn capital_s_and_small_s_are_different_languages() {
909 let hi = InputKind::from_path("a.S").unwrap();
912 let lo = InputKind::from_path("a.s").unwrap();
913 assert_ne!(hi, lo);
914 assert!(hi.full_sequence().contains(&Phase::Preprocess));
915 assert!(!lo.full_sequence().contains(&Phase::Preprocess));
916 }
917
918 #[test]
919 fn a_cplusplus_source_says_why_rather_than_failing_at_link_time() {
920 let e = InputKind::from_path("a.cpp").unwrap_err();
921 assert!(format!("{e}").contains("only ever going to compile C"), "{e}");
922 let e = InputKind::from_x_arg("c++").unwrap_err();
923 assert!(matches!(e, XError::Unsupported(_)), "{e:?}");
924 }
925
926 #[test]
927 fn a_file_with_no_extension_goes_to_the_linker() {
928 assert_eq!(InputKind::from_path("crt1").unwrap(), InputKind::LinkerInput);
929 assert_eq!(InputKind::from_path(".bashrc").unwrap(), InputKind::LinkerInput);
930 }
931
932 #[test]
933 fn the_default_line_compiles_and_links_to_a_out() {
934 let p = plan(&linux(), &["a.c"], None);
935 assert_eq!(
936 p.jobs[0].phases,
937 vec![Phase::Preprocess, Phase::Compile, Phase::Assemble, Phase::Link]
938 );
939 assert_eq!(p.jobs[0].output, Output::Temporary("a.o".into()));
940 let link = p.link.expect("expected a link step");
941 assert_eq!(link.inputs, vec![Item::File("a.o".into())]);
942 assert_eq!(link.output, "a.out");
943 }
944
945 #[test]
946 fn dash_c_stops_at_the_object_and_names_it_after_the_source() {
947 let mut o = linux();
948 o.emit = EmitKind::Object;
949 let p = plan(&o, &["src/a.c", "src/b.c"], None);
950 assert!(p.link.is_none());
951 assert_eq!(p.jobs[0].output, Output::File("a.o".into()));
952 assert_eq!(p.jobs[1].output, Output::File("b.o".into()));
953 assert_eq!(p.jobs[0].phases.last(), Some(&Phase::Assemble));
956 }
957
958 #[test]
959 fn dash_e_writes_to_stdout_unless_it_is_given_a_name() {
960 let mut o = linux();
961 o.emit = EmitKind::Preprocessed;
962 assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::Stdout);
963 assert_eq!(plan(&o, &["a.c"], Some("a.i")).jobs[0].output, Output::File("a.i".into()));
964 }
965
966 #[test]
967 fn a_name_of_one_dash_is_standard_output_and_not_a_file_called_that() {
968 let mut o = linux();
969 o.emit = EmitKind::Preprocessed;
970 assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
971 o.emit = EmitKind::Object;
972 assert_eq!(plan(&o, &["a.c"], Some("-")).jobs[0].output, Output::Stdout);
973 let p = plan(&linux(), &["a.c"], Some("-"));
976 assert_eq!(p.link.expect("a link step").output, "-");
977 }
978
979 #[test]
980 fn dash_s_produces_assembly_named_after_the_source() {
981 let mut o = linux();
982 o.emit = EmitKind::Asm;
983 let p = plan(&o, &["dir/a.c"], None);
984 assert_eq!(p.jobs[0].output, Output::File("a.s".into()));
985 assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Compile]);
986 }
987
988 #[test]
989 fn an_already_preprocessed_file_skips_the_preprocessor() {
990 let p = plan(&linux(), &["a.i"], None);
991 assert_eq!(p.jobs[0].phases, vec![Phase::Compile, Phase::Assemble, Phase::Link]);
992 }
993
994 #[test]
995 fn assembly_with_a_capital_s_is_preprocessed_but_not_compiled() {
996 let p = plan(&linux(), &["a.S"], None);
997 assert_eq!(p.jobs[0].phases, vec![Phase::Preprocess, Phase::Assemble, Phase::Link]);
998 assert!(!p.jobs[0].phases.contains(&Phase::Compile));
999 }
1000
1001 #[test]
1002 fn objects_on_the_line_reach_the_linker_in_the_order_they_were_written() {
1003 let p = plan(&linux(), &["a.o", "b.c", "libm.a"], None);
1006 let link = p.link.expect("expected a link step");
1007 assert_eq!(
1008 link.inputs,
1009 vec![Item::File("a.o".into()), Item::File("b.o".into()), Item::File("libm.a".into()),]
1010 );
1011 }
1012
1013 #[test]
1014 fn an_object_on_a_dash_c_line_is_a_note_rather_than_an_error() {
1015 let mut o = linux();
1017 o.emit = EmitKind::Object;
1018 let p = plan(&o, &["a.c", "b.o"], None);
1019 assert!(p.jobs[1].phases.is_empty());
1020 assert_eq!(p.notes.len(), 1);
1021 assert!(p.notes[0].contains("linker input unused"), "{:?}", p.notes);
1022 }
1023
1024 #[test]
1025 fn dash_o_with_several_compilations_is_rejected() {
1026 let mut o = linux();
1027 o.emit = EmitKind::Object;
1028 let inputs = [Input::new("a.c"), Input::new("b.c")];
1029 let e = Plan::new(&o, &inputs, Some("out.o")).unwrap_err();
1030 assert!(e.message.contains("multiple inputs"), "{}", e.message);
1031 }
1032
1033 #[test]
1034 fn dash_o_with_one_compilation_and_some_objects_is_fine() {
1035 let mut o = linux();
1038 o.emit = EmitKind::Object;
1039 let inputs = [Input::new("a.c"), Input::new("b.o")];
1040 let p = Plan::new(&o, &inputs, Some("out.o")).expect("expected a plan");
1041 assert_eq!(p.jobs[0].output, Output::File("out.o".into()));
1042 }
1043
1044 #[test]
1045 fn dash_x_overrides_the_extension() {
1046 let inputs = [Input { path: "a.txt".into(), forced: Some(InputKind::C), role: Role::File }];
1047 let p = Plan::new(&linux(), &inputs, None).expect("expected a plan");
1048 assert_eq!(p.jobs[0].kind, InputKind::C);
1049 assert_eq!(p.jobs[0].phases.first(), Some(&Phase::Preprocess));
1050 }
1051
1052 #[test]
1053 fn windows_gets_obj_and_a_exe() {
1054 let o = opts("x86_64-pc-windows-msvc");
1055 let p = plan(&o, &["a.c"], None);
1056 assert_eq!(p.jobs[0].output, Output::Temporary("a.obj".into()));
1057 assert_eq!(p.link.expect("expected a link step").output, "a.exe");
1058 }
1059
1060 #[test]
1062 fn an_archive_is_one_file_however_many_inputs_there_are() {
1063 let mut o = linux();
1064 o.emit = EmitKind::Archive;
1065 let p = plan(&o, &["a.c", "sub/b.c"], Some("out/libx.a"));
1066 assert_eq!(p.jobs.len(), 2);
1067 for job in &p.jobs {
1068 assert_eq!(job.phases.last(), Some(&Phase::Assemble), "{}", job.input);
1071 assert!(matches!(job.output, Output::Temporary(_)), "{:?}", job.output);
1072 }
1073 let archive = p.archive.expect("an archive step");
1074 assert_eq!(archive.members, ["a.o", "b.o"]);
1075 assert_eq!(archive.output, "out/libx.a");
1076 assert!(p.link.is_none(), "one command line produces one of the two and not both");
1077 }
1078
1079 #[test]
1080 fn a_member_is_called_what_an_object_is_called_on_this_target() {
1081 let mut o = opts("x86_64-pc-windows-msvc");
1082 o.emit = EmitKind::Archive;
1083 let p = plan(&o, &["a.c"], Some("x.lib"));
1084 assert_eq!(p.archive.expect("an archive step").members, ["a.obj"]);
1085 }
1086
1087 #[test]
1090 fn an_archive_has_no_default_name() {
1091 let mut o = linux();
1092 o.emit = EmitKind::Archive;
1093 let inputs = [Input::new("a.c")];
1094 let error = Plan::new(&o, &inputs, None).expect_err("no name for the archive");
1095 assert!(error.message.contains("needs `-o`"), "{error}");
1096 }
1097
1098 #[test]
1101 fn something_this_compilation_did_not_produce_cannot_go_into_an_archive() {
1102 let mut o = linux();
1103 o.emit = EmitKind::Archive;
1104 for handed in [Input::new("b.o"), Input::library("m")] {
1105 let inputs = [Input::new("a.c"), handed];
1106 let error = Plan::new(&o, &inputs, Some("libx.a")).expect_err("not ours to index");
1107 assert!(error.message.contains("names each member"), "{error}");
1108 }
1109 }
1110
1111 #[test]
1112 fn the_plan_says_what_goes_into_the_archive() {
1113 let mut o = linux();
1114 o.emit = EmitKind::Archive;
1115 let text = plan(&o, &["a.c", "b.c"], Some("libx.a")).render();
1116 assert!(text.contains("archive: a.o b.o -> libx.a"), "{text}");
1117 assert!(!text.contains("link:"), "{text}");
1118 }
1119
1120 #[test]
1121 fn the_intermediate_dumps_stop_where_dash_s_stops() {
1122 for emit in [
1123 EmitKind::Tast,
1124 EmitKind::Ir,
1125 EmitKind::MirFinal,
1126 EmitKind::SafetySummary,
1127 EmitKind::TypeGranules,
1128 ] {
1129 assert_eq!(last_phase(emit), Phase::Compile, "{emit:?}");
1130 }
1131 }
1132
1133 #[test]
1134 fn each_intermediate_dump_is_a_language_of_its_own_and_gets_a_suffix_of_its_own() {
1135 for (emit, name) in [
1138 (EmitKind::Asm, "a.s"),
1139 (EmitKind::Tast, "a.tast"),
1140 (EmitKind::Ir, "a.ir"),
1141 (EmitKind::MirFinal, "a.mir"),
1142 (EmitKind::SafetySummary, "a.safety.json"),
1143 (EmitKind::TypeGranules, "a.granules.txt"),
1144 ] {
1145 let mut o = linux();
1146 o.emit = emit;
1147 assert_eq!(plan(&o, &["a.c"], None).jobs[0].output, Output::File(name.into()));
1148 }
1149 }
1150
1151 #[test]
1152 fn syntax_only_writes_no_file_even_when_given_a_name() {
1153 let mut o = linux();
1154 o.emit = EmitKind::SyntaxOnly;
1155 assert_eq!(last_phase(o.emit), Phase::Compile);
1156 let p = plan(&o, &["a.c", "b.c"], None);
1157 assert!(p.jobs.iter().all(|job| job.output == Output::Stdout), "{:?}", p.jobs);
1158 assert_eq!(plan(&o, &["a.c"], Some("a.o")).jobs[0].output, Output::Stdout);
1159 assert!(!plan(&o, &["a.c"], None).render().contains("link:"));
1160 }
1161
1162 #[test]
1163 fn an_input_that_enters_after_the_last_phase_is_a_note_rather_than_an_error() {
1164 let mut o = linux();
1167 o.emit = EmitKind::Preprocessed;
1168 let p = plan(&o, &["a.c", "b.s"], None);
1169 assert!(p.jobs[1].phases.is_empty());
1170 assert_eq!(p.notes.len(), 1);
1171 assert!(p.notes[0].contains("after the last phase"), "{:?}", p.notes);
1172 let inputs = [Input::new("a.c"), Input::new("b.s")];
1174 assert!(Plan::new(&o, &inputs, Some("out.i")).is_ok());
1175 }
1176
1177 #[test]
1178 fn no_inputs_is_an_error() {
1179 assert!(Plan::new(&linux(), &[], None).is_err());
1180 }
1181
1182 fn keeping(kind: SaveTemps, emit: EmitKind, paths: &[&str], output: Option<&str>) -> Plan {
1184 let mut o = linux();
1185 o.emit = emit;
1186 o.save_temps = kind;
1187 plan(&o, paths, output)
1188 }
1189
1190 fn kept(plan: &Plan, at: usize) -> Vec<String> {
1192 [plan.jobs[at].saved_text(), plan.jobs[at].saved_asm()].into_iter().flatten().collect()
1193 }
1194
1195 #[test]
1196 fn the_files_that_are_kept_land_beside_the_output_and_not_where_the_manual_says() {
1197 let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.c"], Some("out/t.o"));
1201 assert_eq!(kept(&p, 0), vec!["out/t.i", "out/t.s"]);
1202 let p = keeping(SaveTemps::Cwd, EmitKind::Object, &["t.c"], Some("out/t.o"));
1203 assert_eq!(kept(&p, 0), vec!["t.i", "t.s"]);
1204 }
1205
1206 #[test]
1207 fn the_name_comes_off_the_output_rather_than_off_the_input_that_produced_it() {
1208 let p = keeping(SaveTemps::Cwd, EmitKind::Object, &["t.c"], Some("out/x.o"));
1211 assert_eq!(kept(&p, 0), vec!["x.i", "x.s"]);
1212 let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.c"], Some("out/noext"));
1213 assert_eq!(kept(&p, 0), vec!["out/noext.i", "out/noext.s"]);
1214 }
1215
1216 #[test]
1217 fn without_a_name_they_are_called_after_the_input_and_are_where_the_object_would_be() {
1218 for kind in [SaveTemps::Object, SaveTemps::Cwd] {
1221 let p = keeping(kind, EmitKind::Object, &["sub/u.c"], None);
1222 assert_eq!(kept(&p, 0), vec!["u.i", "u.s"], "{kind:?}");
1223 assert_eq!(p.jobs[0].output, Output::File("u.o".into()), "{kind:?}");
1224 }
1225 }
1226
1227 #[test]
1228 fn a_command_line_that_links_names_them_after_the_executable_and_the_input() {
1229 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c", "sub/u.c"], Some("o/p"));
1232 assert_eq!(kept(&p, 0), vec!["o/p-t.i", "o/p-t.s"]);
1233 assert_eq!(kept(&p, 1), vec!["o/p-u.i", "o/p-u.s"]);
1234 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c"], None);
1237 assert_eq!(kept(&p, 0), vec!["a-t.i", "a-t.s"]);
1238 }
1239
1240 #[test]
1241 fn the_object_a_link_reads_is_kept_rather_than_written_where_it_will_be_removed() {
1242 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.c"], Some("out/prog"));
1246 assert_eq!(p.jobs[0].output, Output::File("out/prog-t.o".into()));
1247 let plain = plan(&linux(), &["t.c"], Some("out/prog"));
1248 assert_eq!(plain.jobs[0].output, Output::Temporary("t.o".into()));
1249 }
1250
1251 #[test]
1252 fn a_step_whose_result_is_already_being_written_is_not_kept_a_second_time() {
1253 let p = keeping(SaveTemps::Object, EmitKind::Preprocessed, &["t.c"], None);
1256 assert_eq!(p.jobs[0].aux_base, None);
1257 assert_eq!(kept(&p, 0), Vec::<String>::new());
1258 let p = keeping(SaveTemps::Object, EmitKind::Asm, &["t.c"], None);
1259 assert_eq!(kept(&p, 0), vec!["t.i"]);
1260 }
1261
1262 #[test]
1263 fn an_input_that_arrives_preprocessed_has_no_text_of_its_own_to_keep() {
1264 let p = keeping(SaveTemps::Object, EmitKind::Object, &["t.i"], None);
1267 assert_eq!(kept(&p, 0), vec!["t.s"]);
1268 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["t.o"], None);
1270 assert_eq!(p.jobs[0].aux_base, None);
1271 }
1272
1273 #[test]
1274 fn nothing_is_kept_when_the_flag_was_not_given() {
1275 let p = plan(&linux(), &["t.c"], None);
1276 assert_eq!(p.jobs[0].aux_base, None);
1277 assert_eq!(kept(&p, 0), Vec::<String>::new());
1278 }
1279
1280 #[test]
1281 fn the_rendering_says_what_will_happen() {
1282 let p = plan(&linux(), &["a.c", "b.o"], None);
1283 let text = p.render();
1284 assert!(
1285 text.contains("a.c: preprocess, compile, assemble, link -> a.o (temporary)"),
1286 "{text}"
1287 );
1288 assert!(text.contains("link: a.o b.o -> a.out"), "{text}");
1289 assert_eq!(text.matches("b.o").count(), 1, "{text}");
1291 }
1292
1293 #[test]
1294 fn the_rendering_names_the_files_that_will_be_kept() {
1295 let p = keeping(SaveTemps::Object, EmitKind::Executable, &["a.c"], None);
1298 let text = p.render();
1299 assert!(text.contains("a.c: keeping a-a.i, a-a.s"), "{text}");
1300 assert!(!plan(&linux(), &["a.c"], None).render().contains("keeping"));
1301 }
1302}