Skip to main content

cuno_toolchain/flags/
archive.rs

1//! Making a static library from objects: the tool beside each compiler's
2//! driver, its arguments and the file it writes, row by row from
3//! `docs/en/specs/build.md`, "Building a library".
4
5use std::ffi::OsString;
6use std::path::{Path, PathBuf};
7
8use crate::compiler::CompilerKind;
9
10/// The tool that makes a static library from objects compiled by
11/// `program`: the toolset's `lib.exe` beside cl, LLVM's `llvm-lib` beside
12/// either Clang (which builds for the MSVC ABI), and the `ar` beside GCC.
13/// Taken from beside the driver, so it is the copy of the toolchain the
14/// compile used, whichever copy was chosen.
15pub fn archiver(kind: CompilerKind, program: &Path) -> PathBuf {
16    let name = match kind {
17        CompilerKind::Msvc => "lib",
18        CompilerKind::Clang | CompilerKind::ClangCl => "llvm-lib",
19        CompilerKind::Gcc => "ar",
20    };
21    let mut name = OsString::from(name);
22    if let Some(ext) = program.extension() {
23        name.push(".");
24        name.push(ext);
25    }
26    program.with_file_name(name)
27}
28
29/// The file name of the static library `name` built with `kind`:
30/// `<name>.lib` for the compilers that build for the MSVC ABI, and
31/// `lib<name>.a` for GCC.
32pub fn static_library_file(kind: CompilerKind, name: &str) -> String {
33    match kind {
34        CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => format!("{name}.lib"),
35        CompilerKind::Gcc => format!("lib{name}.a"),
36    }
37}
38
39/// The file names of a shared library (`docs/en/specs/build.md`, "Building
40/// a library").
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct SharedLibraryFiles {
43    /// The DLL.
44    pub dll: String,
45    /// Its import library.
46    pub import: String,
47    /// Its program database. GCC writes none, and is never given it.
48    pub pdb: String,
49}
50
51/// The files of the shared library `name` built with `kind`.
52pub fn shared_library_files(kind: CompilerKind, name: &str) -> SharedLibraryFiles {
53    let import = match kind {
54        CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => format!("{name}.lib"),
55        CompilerKind::Gcc => format!("lib{name}.dll.a"),
56    };
57    SharedLibraryFiles {
58        dll: format!("{name}.dll"),
59        import,
60        pdb: format!("{name}.pdb"),
61    }
62}
63
64/// The [`archiver`]'s arguments to make `library` from `objects`, in that
65/// order. `ar` adds to an archive that is already there: whoever runs this
66/// removes `library` first.
67pub fn archive_args(kind: CompilerKind, objects: &[PathBuf], library: &Path) -> Vec<OsString> {
68    let mut out = OsString::from("/OUT:");
69    out.push(library);
70    let mut args: Vec<OsString> = match kind {
71        // lib.exe prints its banner unless told not to; llvm-lib prints none.
72        CompilerKind::Msvc => vec!["/NOLOGO".into(), out],
73        CompilerKind::Clang | CompilerKind::ClangCl => vec![out],
74        CompilerKind::Gcc => vec!["rcs".into(), library.into()],
75    };
76    args.extend(objects.iter().map(OsString::from));
77    args
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    /// Each compiler's tool, file name and arguments, as the table in
85    /// build.md, "Building a library", gives them.
86    ///
87    /// Mutation: give clang `lib.exe` or GCC `<name>.lib`, give llvm-lib
88    /// `/NOLOGO` or lib.exe none, or put the objects before the output; this
89    /// test fails.
90    #[test]
91    fn each_compiler_archives_with_the_tool_beside_it() {
92        let objects = [PathBuf::from("a.obj"), PathBuf::from("b.obj")];
93        let cases = [
94            (
95                CompilerKind::Msvc,
96                "cl.exe",
97                "lib.exe",
98                "m.lib",
99                &["/NOLOGO", "/OUT:out", "a.obj", "b.obj"][..],
100            ),
101            (
102                CompilerKind::ClangCl,
103                "clang-cl.exe",
104                "llvm-lib.exe",
105                "m.lib",
106                &["/OUT:out", "a.obj", "b.obj"][..],
107            ),
108            (
109                CompilerKind::Clang,
110                "clang.exe",
111                "llvm-lib.exe",
112                "m.lib",
113                &["/OUT:out", "a.obj", "b.obj"][..],
114            ),
115            (
116                CompilerKind::Gcc,
117                "gcc.exe",
118                "ar.exe",
119                "libm.a",
120                &["rcs", "out", "a.obj", "b.obj"][..],
121            ),
122        ];
123        let dir = Path::new("bin");
124        for (kind, driver, tool, file, args) in cases {
125            assert_eq!(
126                archiver(kind, &dir.join(driver)),
127                dir.join(tool),
128                "{kind:?}"
129            );
130            assert_eq!(static_library_file(kind, "m"), file, "{kind:?}");
131            let got = archive_args(kind, &objects, Path::new("out"));
132            assert_eq!(
133                got,
134                args.iter().map(OsString::from).collect::<Vec<_>>(),
135                "{kind:?}"
136            );
137        }
138    }
139
140    /// A DLL is `<name>.dll` everywhere; its import library is `<name>.lib`
141    /// for the MSVC ABI and `lib<name>.dll.a` for GCC.
142    ///
143    /// Mutation: give GCC `<name>.lib` or the MSVC ABI `lib<name>.dll.a`;
144    /// this test fails.
145    #[test]
146    fn a_shared_library_is_a_dll_and_its_import_library() {
147        for kind in [
148            CompilerKind::Msvc,
149            CompilerKind::Clang,
150            CompilerKind::ClangCl,
151        ] {
152            assert_eq!(
153                shared_library_files(kind, "m"),
154                SharedLibraryFiles {
155                    dll: "m.dll".into(),
156                    import: "m.lib".into(),
157                    pdb: "m.pdb".into(),
158                }
159            );
160        }
161        assert_eq!(
162            shared_library_files(CompilerKind::Gcc, "m"),
163            SharedLibraryFiles {
164                dll: "m.dll".into(),
165                import: "libm.dll.a".into(),
166                pdb: "m.pdb".into(),
167            }
168        );
169    }
170
171    /// A driver with no extension names a tool with none.
172    ///
173    /// Mutation: always add `.exe`; this test fails.
174    #[test]
175    fn a_driver_without_an_extension_names_a_tool_without_one() {
176        assert_eq!(
177            archiver(CompilerKind::Gcc, Path::new("/usr/bin/gcc")),
178            Path::new("/usr/bin/ar")
179        );
180    }
181}