cuno-toolchain 0.3.0

Compiler abstraction, detection, per-compiler implementations, and flag translation.
Documentation
//! Making a static library from objects: the tool beside each compiler's
//! driver, its arguments and the file it writes, row by row from
//! `docs/en/specs/build.md`, "Building a library".

use std::ffi::OsString;
use std::path::{Path, PathBuf};

use crate::compiler::CompilerKind;

/// The tool that makes a static library from objects compiled by
/// `program`: the toolset's `lib.exe` beside cl, LLVM's `llvm-lib` beside
/// either Clang (which builds for the MSVC ABI), and the `ar` beside GCC.
/// Taken from beside the driver, so it is the copy of the toolchain the
/// compile used, whichever copy was chosen.
pub fn archiver(kind: CompilerKind, program: &Path) -> PathBuf {
    let name = match kind {
        CompilerKind::Msvc => "lib",
        CompilerKind::Clang | CompilerKind::ClangCl => "llvm-lib",
        CompilerKind::Gcc => "ar",
    };
    let mut name = OsString::from(name);
    if let Some(ext) = program.extension() {
        name.push(".");
        name.push(ext);
    }
    program.with_file_name(name)
}

/// The file name of the static library `name` built with `kind`:
/// `<name>.lib` for the compilers that build for the MSVC ABI, and
/// `lib<name>.a` for GCC.
pub fn static_library_file(kind: CompilerKind, name: &str) -> String {
    match kind {
        CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => format!("{name}.lib"),
        CompilerKind::Gcc => format!("lib{name}.a"),
    }
}

/// The file names of a shared library (`docs/en/specs/build.md`, "Building
/// a library").
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SharedLibraryFiles {
    /// The DLL.
    pub dll: String,
    /// Its import library.
    pub import: String,
    /// Its program database. GCC writes none, and is never given it.
    pub pdb: String,
}

/// The files of the shared library `name` built with `kind`.
pub fn shared_library_files(kind: CompilerKind, name: &str) -> SharedLibraryFiles {
    let import = match kind {
        CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => format!("{name}.lib"),
        CompilerKind::Gcc => format!("lib{name}.dll.a"),
    };
    SharedLibraryFiles {
        dll: format!("{name}.dll"),
        import,
        pdb: format!("{name}.pdb"),
    }
}

/// The [`archiver`]'s arguments to make `library` from `objects`, in that
/// order. `ar` adds to an archive that is already there: whoever runs this
/// removes `library` first.
pub fn archive_args(kind: CompilerKind, objects: &[PathBuf], library: &Path) -> Vec<OsString> {
    let mut out = OsString::from("/OUT:");
    out.push(library);
    let mut args: Vec<OsString> = match kind {
        // lib.exe prints its banner unless told not to; llvm-lib prints none.
        CompilerKind::Msvc => vec!["/NOLOGO".into(), out],
        CompilerKind::Clang | CompilerKind::ClangCl => vec![out],
        CompilerKind::Gcc => vec!["rcs".into(), library.into()],
    };
    args.extend(objects.iter().map(OsString::from));
    args
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Each compiler's tool, file name and arguments, as the table in
    /// build.md, "Building a library", gives them.
    ///
    /// Mutation: give clang `lib.exe` or GCC `<name>.lib`, give llvm-lib
    /// `/NOLOGO` or lib.exe none, or put the objects before the output; this
    /// test fails.
    #[test]
    fn each_compiler_archives_with_the_tool_beside_it() {
        let objects = [PathBuf::from("a.obj"), PathBuf::from("b.obj")];
        let cases = [
            (
                CompilerKind::Msvc,
                "cl.exe",
                "lib.exe",
                "m.lib",
                &["/NOLOGO", "/OUT:out", "a.obj", "b.obj"][..],
            ),
            (
                CompilerKind::ClangCl,
                "clang-cl.exe",
                "llvm-lib.exe",
                "m.lib",
                &["/OUT:out", "a.obj", "b.obj"][..],
            ),
            (
                CompilerKind::Clang,
                "clang.exe",
                "llvm-lib.exe",
                "m.lib",
                &["/OUT:out", "a.obj", "b.obj"][..],
            ),
            (
                CompilerKind::Gcc,
                "gcc.exe",
                "ar.exe",
                "libm.a",
                &["rcs", "out", "a.obj", "b.obj"][..],
            ),
        ];
        let dir = Path::new("bin");
        for (kind, driver, tool, file, args) in cases {
            assert_eq!(
                archiver(kind, &dir.join(driver)),
                dir.join(tool),
                "{kind:?}"
            );
            assert_eq!(static_library_file(kind, "m"), file, "{kind:?}");
            let got = archive_args(kind, &objects, Path::new("out"));
            assert_eq!(
                got,
                args.iter().map(OsString::from).collect::<Vec<_>>(),
                "{kind:?}"
            );
        }
    }

    /// A DLL is `<name>.dll` everywhere; its import library is `<name>.lib`
    /// for the MSVC ABI and `lib<name>.dll.a` for GCC.
    ///
    /// Mutation: give GCC `<name>.lib` or the MSVC ABI `lib<name>.dll.a`;
    /// this test fails.
    #[test]
    fn a_shared_library_is_a_dll_and_its_import_library() {
        for kind in [
            CompilerKind::Msvc,
            CompilerKind::Clang,
            CompilerKind::ClangCl,
        ] {
            assert_eq!(
                shared_library_files(kind, "m"),
                SharedLibraryFiles {
                    dll: "m.dll".into(),
                    import: "m.lib".into(),
                    pdb: "m.pdb".into(),
                }
            );
        }
        assert_eq!(
            shared_library_files(CompilerKind::Gcc, "m"),
            SharedLibraryFiles {
                dll: "m.dll".into(),
                import: "libm.dll.a".into(),
                pdb: "m.pdb".into(),
            }
        );
    }

    /// A driver with no extension names a tool with none.
    ///
    /// Mutation: always add `.exe`; this test fails.
    #[test]
    fn a_driver_without_an_extension_names_a_tool_without_one() {
        assert_eq!(
            archiver(CompilerKind::Gcc, Path::new("/usr/bin/gcc")),
            Path::new("/usr/bin/ar")
        );
    }
}