2
0

rustc_args.py 2.4 KB

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