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(
"--library-path",
action="append",
default=[],
help="library directory made visible to the cc crate",
)
parser.add_argument("--implib")
parser.add_argument("--out-implib", type=Path)
parser.add_argument("--depfile", type=Path)
parser.add_argument(
"--openmp",
choices=("true", "false"),
default="true",
help="Compile the fused k-nearest OpenMP region (LINKCELL_OPENMP).",
)
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()
tsan = os.environ.get("LINKCELL_SANITIZE") == "thread"
command = [args.cargo]
if os.environ.get("LINKCELL_CARGO_VERBOSE") == "1":
command.append("-vv")
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()
env["LINKCELL_OPENMP"] = "1" if args.openmp == "true" else "0"
if args.cc:
env["CC"] = args.cc
if args.library_path:
inherited = env.get("LIBRARY_PATH")
paths = [*args.library_path]
if inherited:
paths.append(inherited)
env["LIBRARY_PATH"] = os.pathsep.join(paths)
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:
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()