blob: fe55bab883091b07ded0c00c6b2d78ef985a77a3 [file]
#!/usr/bin/env fuchsia-vendored-python
# Copyright 2025 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Discovers and merges rust-project.json files from GN and Bazel builds.
This script is intended to be used as a `rust-analyzer.discoverConfig` script in
VSCode. It reads the `rust-project.json` generated by GN. This script
does NOT change any files on disk, it prints the merged rust-project.json to
stdout to be consumed by rust-analyzer.
"""
import argparse
import datetime
import json
import os
import sys
import typing as T
from pathlib import Path
_SCRIPT_DIR = Path(__file__).parent
_BUILD_BAZEL_SCRIPTS = _SCRIPT_DIR / ".." / ".." / "build" / "bazel" / "scripts"
sys.path.insert(0, str(_BUILD_BAZEL_SCRIPTS))
import bazel_rust_analyzer_utils
# Set this to True to debug operations locally in this script.
#
# If True:
# - Debug information will be written to _DEBUG_FILE.
# - The last merged rust-project.json will be written to _DEBUG_RUST_PROJECT_JSON.
_DEBUG = False
_DEBUG_FILE = "/tmp/fuchsia_discover_rust_project.log"
_DEBUG_RUST_PROJECT_JSON = "/tmp/fuchsia_discover_rust_project_last.json"
def normalize_crate_target(crate: dict[str, T.Any]) -> None:
target = crate.get("target")
if not target:
return
# Non-standard target triples (such as Zircon kernel GN toolchain names
# e.g., "kernel_arm64.lk_debug_level_2") cause rustc --print cfg to fail
# when invoked by rust-analyzer. Convert them to valid Rust target triples.
if target.startswith("kernel_"):
for arg in crate.get("compiler_args", []):
if "--clang-target=" in arg:
clang_target = arg.split("--clang-target=")[1]
if clang_target.startswith("riscv64"):
crate["target"] = "riscv64gc-unknown-fuchsia"
else:
crate["target"] = clang_target
return
if "arm64" in target:
crate["target"] = "aarch64-unknown-fuchsia"
elif "x64" in target:
crate["target"] = "x86_64-unknown-fuchsia"
elif "riscv64" in target:
crate["target"] = "riscv64gc-unknown-fuchsia"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--workspace-dir", type=Path, required=True)
parser.add_argument("--discover-args", type=str, required=True)
args = parser.parse_args()
discoverArgs = json.loads(args.discover_args)
source = Path(discoverArgs["path"])
if _DEBUG:
with open(_DEBUG_FILE, "a") as f:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"[{timestamp}] discover_args: {discoverArgs}\n")
gn_rust_project_json = args.workspace_dir / "rust-project.json"
with open(gn_rust_project_json, "r") as f:
gn_rust_project = json.load(f)
# Amend the GN rust project to consider everything not in
# //third_party/rust_crates as part of the workspace.
for crate in gn_rust_project["crates"]:
if "is_workspace_member" not in crate:
crate["is_workspace_member"] = not crate["label"].startswith(
"//third_party/rust_crates"
)
normalize_crate_target(crate)
label = crate.get("label", "")
root_module = crate.get("root_module", "")
if "zircon/kernel" in label or "zircon/kernel" in root_module:
kernel_src_dir = str(args.workspace_dir / "zircon" / "kernel")
if "source" not in crate or crate["source"] is None:
crate["source"] = {"include_dirs": [], "exclude_dirs": []}
if kernel_src_dir not in crate["source"].get("include_dirs", []):
crate["source"].setdefault("include_dirs", []).append(
kernel_src_dir
)
if os.environ.get("FX_RA_EXPERIMENTS_ENABLED"):
crates_for_file = bazel_rust_analyzer_utils.find_crates_for_file(
source, gn_rust_project["crates"]
)
if len(crates_for_file) != 0:
discovered_project = {
k: v for k, v in gn_rust_project.items() if k != "crates"
}
discovered_project[
"crates"
] = bazel_rust_analyzer_utils.get_crates_and_dependencies(
crates_for_file, gn_rust_project["crates"]
)
else:
discovered_project = gn_rust_project
# No matching crate found, return everything.
if _DEBUG:
with open(_DEBUG_FILE, "a") as f:
timestamp = datetime.datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
)
f.write(
f"[{timestamp}] File {source} does not belong to any crate from merged rust-project.json.\n"
)
else:
discovered_project = gn_rust_project
if _DEBUG:
with open(_DEBUG_RUST_PROJECT_JSON, "w") as f:
json.dump(discovered_project, f, indent=2)
discover_config_result = {
"kind": "finished",
"buildfile": str(args.workspace_dir / "BUILD.gn"),
"project": discovered_project,
}
print(json.dumps(discover_config_result))
return 0
if __name__ == "__main__":
sys.exit(main())