Linux Audio

Check our new training course

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