1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0 3"""generate_rust_analyzer - Generates the `rust-project.json` file for `rust-analyzer`. 4""" 5 6import argparse 7import json 8import logging 9import os 10import pathlib 11import sys 12 13def args_crates_cfgs(cfgs): 14 crates_cfgs = {} 15 for cfg in cfgs: 16 crate, vals = cfg.split("=", 1) 17 crates_cfgs[crate] = vals.replace("--cfg", "").split() 18 19 return crates_cfgs 20 21def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): 22 # Generate the configuration list. 23 cfg = [] 24 with open(objtree / "include" / "generated" / "rustc_cfg") as fd: 25 for line in fd: 26 line = line.replace("--cfg=", "") 27 line = line.replace("\n", "") 28 cfg.append(line) 29 30 # Now fill the crates list -- dependencies need to come first. 31 # 32 # Avoid O(n^2) iterations by keeping a map of indexes. 33 crates = [] 34 crates_indexes = {} 35 crates_cfgs = args_crates_cfgs(cfgs) 36 37 def append_crate(display_name, root_module, deps, cfg=[], is_workspace_member=True, is_proc_macro=False): 38 crates_indexes[display_name] = len(crates) 39 crates.append({ 40 "display_name": display_name, 41 "root_module": str(root_module), 42 "is_workspace_member": is_workspace_member, 43 "is_proc_macro": is_proc_macro, 44 "deps": [{"crate": crates_indexes[dep], "name": dep} for dep in deps], 45 "cfg": cfg, 46 "edition": "2021", 47 "env": { 48 "RUST_MODFILE": "This is only for rust-analyzer" 49 } 50 }) 51 52 def append_sysroot_crate( 53 display_name, 54 deps, 55 cfg=[], 56 ): 57 append_crate( 58 display_name, 59 sysroot_src / display_name / "src" / "lib.rs", 60 deps, 61 cfg, 62 is_workspace_member=False, 63 ) 64 65 # NB: sysroot crates reexport items from one another so setting up our transitive dependencies 66 # here is important for ensuring that rust-analyzer can resolve symbols. The sources of truth 67 # for this dependency graph are `(sysroot_src / crate / "Cargo.toml" for crate in crates)`. 68 append_sysroot_crate("core", [], cfg=crates_cfgs.get("core", [])) 69 append_sysroot_crate("alloc", ["core"]) 70 append_sysroot_crate("std", ["alloc", "core"]) 71 append_sysroot_crate("proc_macro", ["core", "std"]) 72 73 append_crate( 74 "compiler_builtins", 75 srctree / "rust" / "compiler_builtins.rs", 76 [], 77 ) 78 79 append_crate( 80 "alloc", 81 srctree / "rust" / "alloc" / "lib.rs", 82 ["core", "compiler_builtins"], 83 cfg=crates_cfgs.get("alloc", []), 84 ) 85 86 append_crate( 87 "macros", 88 srctree / "rust" / "macros" / "lib.rs", 89 ["std", "proc_macro"], 90 is_proc_macro=True, 91 ) 92 crates[-1]["proc_macro_dylib_path"] = f"{objtree}/rust/libmacros.so" 93 94 append_crate( 95 "build_error", 96 srctree / "rust" / "build_error.rs", 97 ["core", "compiler_builtins"], 98 ) 99 100 append_crate( 101 "bindings", 102 srctree / "rust"/ "bindings" / "lib.rs", 103 ["core"], 104 cfg=cfg, 105 ) 106 crates[-1]["env"]["OBJTREE"] = str(objtree.resolve(True)) 107 108 append_crate( 109 "kernel", 110 srctree / "rust" / "kernel" / "lib.rs", 111 ["core", "alloc", "macros", "build_error", "bindings"], 112 cfg=cfg, 113 ) 114 crates[-1]["source"] = { 115 "include_dirs": [ 116 str(srctree / "rust" / "kernel"), 117 str(objtree / "rust") 118 ], 119 "exclude_dirs": [], 120 } 121 122 def is_root_crate(build_file, target): 123 try: 124 return f"{target}.o" in open(build_file).read() 125 except FileNotFoundError: 126 return False 127 128 # Then, the rest outside of `rust/`. 129 # 130 # We explicitly mention the top-level folders we want to cover. 131 extra_dirs = map(lambda dir: srctree / dir, ("samples", "drivers")) 132 if external_src is not None: 133 extra_dirs = [external_src] 134 for folder in extra_dirs: 135 for path in folder.rglob("*.rs"): 136 logging.info("Checking %s", path) 137 name = path.name.replace(".rs", "") 138 139 # Skip those that are not crate roots. 140 if not is_root_crate(path.parent / "Makefile", name) and \ 141 not is_root_crate(path.parent / "Kbuild", name): 142 continue 143 144 logging.info("Adding %s", name) 145 append_crate( 146 name, 147 path, 148 ["core", "alloc", "kernel"], 149 cfg=cfg, 150 ) 151 152 return crates 153 154def main(): 155 parser = argparse.ArgumentParser() 156 parser.add_argument('--verbose', '-v', action='store_true') 157 parser.add_argument('--cfgs', action='append', default=[]) 158 parser.add_argument("srctree", type=pathlib.Path) 159 parser.add_argument("objtree", type=pathlib.Path) 160 parser.add_argument("sysroot_src", type=pathlib.Path) 161 parser.add_argument("exttree", type=pathlib.Path, nargs="?") 162 args = parser.parse_args() 163 164 logging.basicConfig( 165 format="[%(asctime)s] [%(levelname)s] %(message)s", 166 level=logging.INFO if args.verbose else logging.WARNING 167 ) 168 169 rust_project = { 170 "crates": generate_crates(args.srctree, args.objtree, args.sysroot_src, args.exttree, args.cfgs), 171 "sysroot_src": str(args.sysroot_src), 172 } 173 174 json.dump(rust_project, sys.stdout, sort_keys=True, indent=4) 175 176if __name__ == "__main__": 177 main() 178