public inbox for linux-kernel@vger.kernel.org
 help / color / mirror / Atom feed
From: Tamir Duberstein <tamird@kernel.org>
To: "Jesung Yang" <y.j3ms.n@gmail.com>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun.feng@gmail.com>,
	"Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
	 Tamir Duberstein <tamird@kernel.org>,
	 Daniel Almeida <daniel.almeida@collabora.com>
Subject: [PATCH 3/4] scripts: generate_rust_analyzer.py: add type hints
Date: Thu, 22 Jan 2026 12:30:47 -0500	[thread overview]
Message-ID: <20260122-rust-analyzer-types-v1-3-29cc2e91dcd5@kernel.org> (raw)
In-Reply-To: <20260122-rust-analyzer-types-v1-0-29cc2e91dcd5@kernel.org>

Python type hints allow static analysis tools like mypy to detect type
errors during development, improving the developer experience.

Python type hints have been present in the kernel since 2019 at the
latest; see commit 6ebf5866f2e8 ("kunit: tool: add Python wrappers for
running KUnit tests").

Add a subclass of `argparse.Namespace` to get type checking on the CLI
arguments.

Run `mypy --strict scripts/generate_rust_analyzer.py --python-version
3.9` to verify. Note that `mypy` no longer supports python < 3.9.

Tested-by: Daniel Almeida <daniel.almeida@collabora.com>
Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Signed-off-by: Tamir Duberstein <tamird@kernel.org>
---
 scripts/generate_rust_analyzer.py | 130 ++++++++++++++++++++++++++------------
 1 file changed, 90 insertions(+), 40 deletions(-)

diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py
index bc79e4d8e8e7..2723154f207c 100755
--- a/scripts/generate_rust_analyzer.py
+++ b/scripts/generate_rust_analyzer.py
@@ -10,8 +10,9 @@ import os
 import pathlib
 import subprocess
 import sys
+from typing import Dict, Iterable, List, Literal, Optional, TypedDict
 
-def args_crates_cfgs(cfgs):
+def args_crates_cfgs(cfgs: List[str]) -> Dict[str, List[str]]:
     crates_cfgs = {}
     for cfg in cfgs:
         crate, vals = cfg.split("=", 1)
@@ -19,7 +20,43 @@ def args_crates_cfgs(cfgs):
 
     return crates_cfgs
 
-def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edition):
+class Dependency(TypedDict):
+    crate: int
+    name: str
+
+
+class Source(TypedDict):
+    include_dirs: List[str]
+    exclude_dirs: List[str]
+
+
+class Crate(TypedDict):
+    display_name: str
+    root_module: str
+    is_workspace_member: bool
+    deps: List[Dependency]
+    cfg: List[str]
+    edition: str
+    env: Dict[str, str]
+
+
+class ProcMacroCrate(Crate):
+    is_proc_macro: Literal[True]
+    proc_macro_dylib_path: str  # `pathlib.Path` is not JSON serializable.
+
+
+class CrateWithGenerated(Crate):
+    source: Source
+
+
+def generate_crates(
+    srctree: pathlib.Path,
+    objtree: pathlib.Path,
+    sysroot_src: pathlib.Path,
+    external_src: Optional[pathlib.Path],
+    cfgs: List[str],
+    core_edition: str,
+) -> List[Crate]:
     # Generate the configuration list.
     cfg = []
     with open(objtree / "include" / "generated" / "rustc_cfg") as fd:
@@ -31,19 +68,19 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
     # Now fill the crates list -- dependencies need to come first.
     #
     # Avoid O(n^2) iterations by keeping a map of indexes.
-    crates = []
-    crates_indexes = {}
+    crates: List[Crate] = []
+    crates_indexes: Dict[str, int] = {}
     crates_cfgs = args_crates_cfgs(cfgs)
 
     def build_crate(
-        display_name,
-        root_module,
-        deps,
+        display_name: str,
+        root_module: pathlib.Path,
+        deps: List[str],
         *,
-        cfg,
-        is_workspace_member,
-        edition,
-    ):
+        cfg: Optional[List[str]],
+        is_workspace_member: Optional[bool],
+        edition: Optional[str],
+    ) -> Crate:
         cfg = cfg if cfg is not None else []
         is_workspace_member = (
             is_workspace_member if is_workspace_member is not None else True
@@ -62,14 +99,14 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
         }
 
     def append_proc_macro_crate(
-        display_name,
-        root_module,
-        deps,
+        display_name: str,
+        root_module: pathlib.Path,
+        deps: List[str],
         *,
-        cfg=None,
-        is_workspace_member=None,
-        edition=None,
-    ):
+        cfg: Optional[List[str]] = None,
+        is_workspace_member: Optional[bool] = None,
+        edition: Optional[str] = None,
+    ) -> None:
         crate = build_crate(
             display_name,
             root_module,
@@ -95,26 +132,26 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
             .decode("utf-8")
             .strip()
         )
-        proc_macro_crate = {
+        proc_macro_crate: ProcMacroCrate = {
             **crate,
             "is_proc_macro": True,
             "proc_macro_dylib_path": str(objtree / "rust" / proc_macro_dylib_name),
         }
         return register_crate(proc_macro_crate)
 
-    def register_crate(crate):
+    def register_crate(crate: Crate) -> None:
         crates_indexes[crate["display_name"]] = len(crates)
         crates.append(crate)
 
     def append_crate(
-        display_name,
-        root_module,
-        deps,
+        display_name: str,
+        root_module: pathlib.Path,
+        deps: List[str],
         *,
-        cfg=None,
-        is_workspace_member=None,
-        edition=None,
-    ):
+        cfg: Optional[List[str]] = None,
+        is_workspace_member: Optional[bool] = None,
+        edition: Optional[str] = None,
+    ) -> None:
         return register_crate(
             build_crate(
                 display_name,
@@ -127,12 +164,12 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
         )
 
     def append_sysroot_crate(
-        display_name,
-        deps,
+        display_name: str,
+        deps: List[str],
         *,
-        cfg=None,
-        edition=None,
-    ):
+        cfg: Optional[List[str]] = None,
+        edition: Optional[str] = None,
+    ) -> None:
         return append_crate(
             display_name,
             sysroot_src / display_name / "src" / "lib.rs",
@@ -210,9 +247,9 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
     )
 
     def append_crate_with_generated(
-        display_name,
-        deps,
-    ):
+        display_name: str,
+        deps: List[str],
+    ) -> None:
         crate = build_crate(
             display_name,
             srctree / "rust"/ display_name / "lib.rs",
@@ -222,7 +259,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
             edition=None,
         )
         crate["env"]["OBJTREE"] = str(objtree.resolve(True))
-        crate_with_generated = {
+        crate_with_generated: CrateWithGenerated = {
             **crate,
             "source": {
                 "include_dirs": [
@@ -238,7 +275,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
     append_crate_with_generated("uapi", ["core", "ffi", "pin_init"])
     append_crate_with_generated("kernel", ["core", "macros", "build_error", "pin_init", "ffi", "bindings", "uapi"])
 
-    def is_root_crate(build_file, target):
+    def is_root_crate(build_file: pathlib.Path, target: str) -> bool:
         try:
             return f"{target}.o" in open(build_file).read()
         except FileNotFoundError:
@@ -247,7 +284,9 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
     # Then, the rest outside of `rust/`.
     #
     # We explicitly mention the top-level folders we want to cover.
-    extra_dirs = map(lambda dir: srctree / dir, ("samples", "drivers"))
+    extra_dirs: Iterable[pathlib.Path] = (
+        srctree / dir for dir in ("samples", "drivers")
+    )
     if external_src is not None:
         extra_dirs = [external_src]
     for folder in extra_dirs:
@@ -270,7 +309,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs, core_edit
 
     return crates
 
-def main():
+def main() -> None:
     parser = argparse.ArgumentParser()
     parser.add_argument('--verbose', '-v', action='store_true')
     parser.add_argument('--cfgs', action='append', default=[])
@@ -280,7 +319,18 @@ def main():
     parser.add_argument("sysroot", type=pathlib.Path)
     parser.add_argument("sysroot_src", type=pathlib.Path)
     parser.add_argument("exttree", type=pathlib.Path, nargs="?")
-    args = parser.parse_args()
+
+    class Args(argparse.Namespace):
+        verbose: bool
+        cfgs: List[str]
+        srctree: pathlib.Path
+        objtree: pathlib.Path
+        sysroot: pathlib.Path
+        sysroot_src: pathlib.Path
+        exttree: Optional[pathlib.Path]
+        core_edition: str
+
+    args = parser.parse_args(namespace=Args())
 
     logging.basicConfig(
         format="[%(asctime)s] [%(levelname)s] %(message)s",

-- 
2.52.0


  parent reply	other threads:[~2026-01-22 17:30 UTC|newest]

Thread overview: 13+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-01-22 17:30 [PATCH 0/4] scripts: generate_rust_analyzer.py: tidy and add type hints Tamir Duberstein
2026-01-22 17:30 ` [PATCH 1/4] scripts: generate_rust_analyzer.py: extract `{build,register}_crate` Tamir Duberstein
2026-01-22 17:30 ` [PATCH 2/4] scripts: generate_rust_analyzer.py: drop `"is_proc_macro": false` Tamir Duberstein
2026-01-22 17:30 ` Tamir Duberstein [this message]
2026-01-22 17:30 ` [PATCH 4/4] scripts: generate_rust_analyzer.py: identify crates explicitly Tamir Duberstein
2026-01-28  6:06 ` [PATCH 0/4] scripts: generate_rust_analyzer.py: tidy and add type hints Jesung Yang
2026-01-30 19:56 ` Tamir Duberstein
2026-01-30 20:11   ` Miguel Ojeda
2026-01-30 20:24     ` Tamir Duberstein
2026-01-30 20:31       ` Tamir Duberstein
2026-01-30 20:42         ` Miguel Ojeda
2026-03-02 16:23           ` Tamir Duberstein
2026-01-30 20:32       ` Miguel Ojeda

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260122-rust-analyzer-types-v1-3-29cc2e91dcd5@kernel.org \
    --to=tamird@kernel.org \
    --cc=a.hindborg@kernel.org \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=gary@garyguo.net \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tmgross@umich.edu \
    --cc=y.j3ms.n@gmail.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox