xref: /openbmc/qemu/scripts/rust/rustc_args.py (revision feb58e3b)
1#!/usr/bin/env python3
2
3"""Generate rustc arguments for meson rust builds.
4
5This program generates --cfg compile flags for the configuration headers passed
6as arguments.
7
8Copyright (c) 2024 Linaro Ltd.
9
10Authors:
11 Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
12
13This program is free software; you can redistribute it and/or modify
14it under the terms of the GNU General Public License as published by
15the Free Software Foundation; either version 2 of the License, or
16(at your option) any later version.
17
18This program is distributed in the hope that it will be useful,
19but WITHOUT ANY WARRANTY; without even the implied warranty of
20MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21GNU General Public License for more details.
22
23You should have received a copy of the GNU General Public License
24along with this program.  If not, see <http://www.gnu.org/licenses/>.
25"""
26
27import argparse
28import logging
29
30from typing import List
31
32
33def generate_cfg_flags(header: str) -> List[str]:
34    """Converts defines from config[..].h headers to rustc --cfg flags."""
35
36    def cfg_name(name: str) -> str:
37        """Filter function for C #defines"""
38        if (
39            name.startswith("CONFIG_")
40            or name.startswith("TARGET_")
41            or name.startswith("HAVE_")
42        ):
43            return name
44        return ""
45
46    with open(header, encoding="utf-8") as cfg:
47        config = [l.split()[1:] for l in cfg if l.startswith("#define")]
48
49    cfg_list = []
50    for cfg in config:
51        name = cfg_name(cfg[0])
52        if not name:
53            continue
54        if len(cfg) >= 2 and cfg[1] != "1":
55            continue
56        cfg_list.append("--cfg")
57        cfg_list.append(name)
58    return cfg_list
59
60
61def main() -> None:
62    # pylint: disable=missing-function-docstring
63    parser = argparse.ArgumentParser()
64    parser.add_argument("-v", "--verbose", action="store_true")
65    parser.add_argument(
66        "--config-headers",
67        metavar="CONFIG_HEADER",
68        action="append",
69        dest="config_headers",
70        help="paths to any configuration C headers (*.h files), if any",
71        required=False,
72        default=[],
73    )
74    args = parser.parse_args()
75    if args.verbose:
76        logging.basicConfig(level=logging.DEBUG)
77    logging.debug("args: %s", args)
78    for header in args.config_headers:
79        for tok in generate_cfg_flags(header):
80            print(tok)
81
82
83if __name__ == "__main__":
84    main()
85