linkcell 0.4.1

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 re
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("--cc", help="C compiler for the cc crate (overrides CC)")
    parser.add_argument("--implib")
    parser.add_argument("--out-implib", type=Path)
    parser.add_argument("--depfile", 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()
    # The OpenMP runtime Meson links follows its own C compiler. An
    # activated environment may export a different CC, so this wins.
    if args.cc:
        env["CC"] = args.cc
    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 args.depfile is not None:
        write_depfile(built / (Path(args.static).stem + ".d"), args.out_shared, args.depfile)


def write_depfile(cargo_dep: Path, target: Path, depfile: Path) -> None:
    """Restate Cargo's dep-info for the first Meson output.

    Cargo names its own artifacts as the rule targets. Ninja wants the
    custom target's output, so only the prerequisites are kept. Cargo has
    already escaped spaces in them.
    """
    deps: list[str] = []
    for line in cargo_dep.read_text(encoding="utf-8").splitlines():
        _, sep, rest = line.partition(": ")
        if sep and rest.strip():
            for dep in re.split(r"(?<!\\) +", rest.strip()):
                if dep not in deps:
                    deps.append(dep)
    escaped = str(target).replace(" ", "\\ ")
    depfile.write_text(f"{escaped}: {' '.join(deps)}\n", encoding="utf-8")


if __name__ == "__main__":
    main()