carbon_toolchain.bzl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. # Exceptions. See /LICENSE for license information.
  3. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. """Module extension to configure Carbon's `cc_toolchain`s.
  5. This extension extracts configuration from the Carbon toolchain into
  6. `carbon_detected_variables.bzl`. These values are then used by the
  7. `cc_toolchain` to setup the Carbon toolchain as a viable C++ Bazel toolchain.
  8. """
  9. def _compute_config_vars(repository_ctx, carbon):
  10. """Runs the `carbon` binary to get its config variables."""
  11. exec_result = repository_ctx.execute([carbon, "config", "--json"])
  12. if exec_result.return_code != 0:
  13. fail("Command failed with return code {0}:\n{1}".format(
  14. exec_result.return_code,
  15. exec_result.stderr,
  16. ))
  17. vars = json.decode(exec_result.stdout)
  18. if type(vars) != "dict":
  19. fail("Config JSON decoded to a non-dict value: \n" + exec_result.stdout)
  20. # Turn the values of all the keys in the JSON config results into strings.
  21. # This provides a dictionary suitable for substituting with
  22. # `repository_ctx.template`.
  23. return {key: str(value) for key, value in vars.items()}
  24. def _create_config_repo_impl(repository_ctx):
  25. vars = _compute_config_vars(repository_ctx, repository_ctx.attr._carbon)
  26. repository_ctx.template(
  27. "carbon_detected_variables.bzl",
  28. repository_ctx.attr._template,
  29. vars,
  30. )
  31. repository_ctx.file("BUILD.bazel", """
  32. exports_files(["carbon_detected_variables.bzl"])
  33. """)
  34. _create_config_repo = repository_rule(
  35. implementation = _create_config_repo_impl,
  36. attrs = {
  37. "_carbon": attr.label(
  38. default = "//:carbon-busybox",
  39. allow_single_file = True,
  40. ),
  41. "_template": attr.label(
  42. default = "//bazel:carbon_detected_variables.tpl.bzl",
  43. allow_single_file = True,
  44. ),
  45. },
  46. )
  47. carbon_toolchain_config = module_extension(
  48. implementation =
  49. lambda ctx: _create_config_repo(name = "carbon_toolchain_config"),
  50. )