linkcell 0.4.0

Periodic linked-cell cutoff pairs and k-nearest neighbour search
Documentation
#!/usr/bin/env python3
"""Build linkcell with Cargo and copy its C ABI artifacts for Meson."""

from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import sys
from pathlib import Path


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--cargo", required=True)
    parser.add_argument("--source", type=Path, required=True)
    parser.add_argument("--target", type=Path, required=True)
    parser.add_argument("--profile", choices=("debug", "release"), required=True)
    parser.add_argument("--shared", required=True)
    parser.add_argument("--static", required=True)
    parser.add_argument("--out-shared", type=Path, required=True)
    parser.add_argument("--out-static", type=Path, required=True)
    parser.add_argument("--implib")
    parser.add_argument("--out-implib", type=Path)
    args = parser.parse_args()
    if (args.implib is None) != (args.out_implib is None):
        parser.error("--implib and --out-implib must be supplied together")
    return args


def main() -> None:
    args = parse_args()
    # ThreadSanitizer does not see Rayon's futex join unless std and rayon
    # are rebuilt with the sanitizer. The final C++ link supplies one
    # compiler-rt via -Zexternal-clangrt, so the pool stays multithreaded.
    tsan = os.environ.get("LINKCELL_SANITIZE") == "thread"
    # Pixi's cargo is a real binary, not the rustup proxy, and it is ahead
    # of rustup on PATH. rustup run nightly still leaves that rustc first,
    # so the nightly compiler has to be named by its own path.
    command = [args.cargo]
    command += [
        "rustc",
        "--lib",
        "--manifest-path",
        str(args.source / "Cargo.toml"),
        "--target-dir",
        str(args.target),
        "--features",
        "capi",
    ]
    if tsan:
        command += ["-Zbuild-std", "--target", "x86_64-unknown-linux-gnu"]
    if (args.source / "Cargo.lock").is_file() and not tsan:
        command.append("--locked")
    if args.profile == "release":
        command.append("--release")

    rustc = ["--crate-type=cdylib", "--crate-type=staticlib"]
    if sys.platform.startswith("linux"):
        rustc.append(f"-Clink-arg=-Wl,-soname,{args.shared}")
    elif sys.platform == "darwin":
        rustc.append(f"-Clink-arg=-Wl,-install_name,@rpath/{args.shared}")
    command.extend(["--", *rustc])
    env = os.environ.copy()
    if tsan:
        nightly_cargo = subprocess.check_output(
            ["rustup", "which", "--toolchain", "nightly", "cargo"], text=True
        ).strip()
        nightly_rustc = subprocess.check_output(
            ["rustup", "which", "--toolchain", "nightly", "rustc"], text=True
        ).strip()
        command[0] = nightly_cargo
        env["RUSTC"] = nightly_rustc
        nightly_bin = str(Path(nightly_rustc).parent)
        env["PATH"] = nightly_bin + os.pathsep + env.get("PATH", "")
        extra = "-Zsanitizer=thread -Zexternal-clangrt -Cforce-frame-pointers=yes"
        flags = env.get("RUSTFLAGS", "")
        if "-Zsanitizer=thread" not in flags:
            env["RUSTFLAGS"] = (flags + " " + extra).strip()
    subprocess.check_call(command, env=env)

    built = args.target / args.profile
    if tsan:
        built = args.target / "x86_64-unknown-linux-gnu" / args.profile
    shutil.copy2(built / args.shared, args.out_shared)
    shutil.copy2(built / args.static, args.out_static)
    if args.implib is not None:
        shutil.copy2(built / args.implib, args.out_implib)


if __name__ == "__main__":
    main()