defs.bzl 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. """Provides rules for building Carbon files using the toolchain."""
  5. load("@rules_cc//cc/common:cc_info.bzl", "CcInfo")
  6. def _runtimes_path(runtimes_target):
  7. path = None
  8. for f in runtimes_target:
  9. if f.short_path.endswith("clang_resource_dir/lib"):
  10. path = f.path
  11. break
  12. if not path:
  13. fail("Could not find the `clang_resource_dir` in target {}".format(runtimes_target.label))
  14. return path[:-len("/clang_resource_dir/lib")]
  15. def _carbon_binary_impl(ctx):
  16. toolchain_driver = ctx.executable.internal_exec_toolchain_driver
  17. toolchain_data = ctx.files.internal_exec_toolchain_data
  18. prebuilt_runtimes = ctx.files.internal_exec_prebuilt_runtimes
  19. # If the exec driver isn't provided, that means we're trying to use a target
  20. # config toolchain, likely to avoid build overhead of two configs.
  21. if toolchain_driver == None:
  22. toolchain_driver = ctx.executable.internal_target_toolchain_driver
  23. toolchain_data = ctx.files.internal_target_toolchain_data
  24. prebuilt_runtimes = ctx.files.internal_target_prebuilt_runtimes
  25. # Pass any C++ flags from our dependencies onto Carbon.
  26. dep_flags = []
  27. dep_hdrs = []
  28. dep_link_flags = []
  29. dep_link_inputs = []
  30. for dep in ctx.attr.deps:
  31. if CcInfo in dep:
  32. cc_info = dep[CcInfo]
  33. # TODO: We should reuse the feature-based flag generation in
  34. # bazel/cc_toolchains here.
  35. dep_flags += ["--clang-arg=-D{0}".format(define) for define in cc_info.compilation_context.defines.to_list()]
  36. dep_flags += ["--clang-arg=-I{0}".format(path) for path in cc_info.compilation_context.includes.to_list()]
  37. dep_flags += ["--clang-arg=-iquote{0}".format(path) for path in cc_info.compilation_context.quote_includes.to_list()]
  38. dep_flags += ["--clang-arg=-isystem{0}".format(path) for path in cc_info.compilation_context.system_includes.to_list()]
  39. dep_hdrs.append(cc_info.compilation_context.headers)
  40. for link_input in cc_info.linking_context.linker_inputs.to_list():
  41. # TODO: `carbon link` doesn't support linker flags yet.
  42. # dep_link_flags += link_input.user_link_flags
  43. dep_link_inputs += link_input.additional_inputs
  44. for lib in link_input.libraries:
  45. dep_link_inputs += [dep for dep in [lib.dynamic_library, lib.static_library] if dep]
  46. dep_link_inputs += lib.objects
  47. if DefaultInfo in dep:
  48. dep_link_inputs += dep[DefaultInfo].files.to_list()
  49. dep_link_flags += [dep.path for dep in dep_link_inputs]
  50. # Build object files for the prelude and for the binary itself.
  51. # TODO: Eventually the prelude should be build as a separate `carbon_library`.
  52. srcs_and_flags = [
  53. (ctx.files.prelude_srcs, ["--no-prelude-import"]),
  54. (ctx.files.srcs, dep_flags),
  55. ]
  56. objs = []
  57. for (srcs, extra_flags) in srcs_and_flags:
  58. for src in srcs:
  59. # Build each source file. For now, we pass all sources to each compile
  60. # because we don't have visibility into dependencies and have no way to
  61. # specify multiple output files. Object code for each input is written
  62. # into the output file in turn, so the final carbon source file
  63. # specified ends up determining the contents of the object file.
  64. #
  65. # TODO: This is a hack; replace with something better once the toolchain
  66. # supports doing so.
  67. #
  68. # TODO: Switch to the `prefix` based rule similar to linking when
  69. # the prelude moves there.
  70. out = ctx.actions.declare_file("_objs/{0}/{1}o".format(
  71. ctx.label.name,
  72. src.short_path.removeprefix(ctx.label.package).removesuffix(src.extension),
  73. ))
  74. objs.append(out)
  75. srcs_reordered = [s for s in srcs if s != src] + [src]
  76. ctx.actions.run(
  77. outputs = [out],
  78. inputs = depset(direct = srcs_reordered, transitive = dep_hdrs),
  79. executable = toolchain_driver,
  80. tools = depset(toolchain_data),
  81. arguments = ["compile", "--output=" + out.path] +
  82. [s.path for s in srcs_reordered] + extra_flags + ctx.attr.flags,
  83. mnemonic = "CarbonCompile",
  84. progress_message = "Compiling " + src.short_path,
  85. )
  86. bin = ctx.actions.declare_file(ctx.label.name)
  87. ctx.actions.run(
  88. outputs = [bin],
  89. inputs = objs + dep_link_inputs,
  90. executable = toolchain_driver,
  91. tools = depset(toolchain_data + prebuilt_runtimes),
  92. arguments = ["--prebuilt-runtimes=" + _runtimes_path(prebuilt_runtimes), "link", "--output=" + bin.path] + ["--"] + dep_link_flags + [o.path for o in objs],
  93. mnemonic = "CarbonLink",
  94. progress_message = "Linking " + bin.short_path,
  95. )
  96. return [DefaultInfo(files = depset([bin]), executable = bin)]
  97. _carbon_binary_internal = rule(
  98. implementation = _carbon_binary_impl,
  99. attrs = {
  100. "deps": attr.label_list(allow_files = True, providers = [[CcInfo]]),
  101. "flags": attr.string_list(),
  102. # The exec config toolchain attributes. These will be `None` when using
  103. # the target config and populated when using the exec config. We have to
  104. # use duplicate attributes here and below to have different `cfg`
  105. # settings, as that isn't `select`-able, and we'll use `select`s when
  106. # populating these.
  107. "internal_exec_prebuilt_runtimes": attr.label(
  108. cfg = "exec",
  109. ),
  110. "internal_exec_toolchain_data": attr.label(
  111. cfg = "exec",
  112. ),
  113. "internal_exec_toolchain_driver": attr.label(
  114. allow_single_file = True,
  115. executable = True,
  116. cfg = "exec",
  117. ),
  118. # The target config toolchain attributes. These will be 'None' when
  119. # using the exec config and populated when using the target config. We
  120. # have to use duplicate attributes here and below to have different
  121. # `cfg` settings, as that isn't `select`-able, and we'll use `select`s
  122. # when populating these.
  123. "internal_target_prebuilt_runtimes": attr.label(
  124. cfg = "target",
  125. ),
  126. "internal_target_toolchain_data": attr.label(
  127. cfg = "target",
  128. ),
  129. "internal_target_toolchain_driver": attr.label(
  130. allow_single_file = True,
  131. executable = True,
  132. cfg = "target",
  133. ),
  134. "prelude_srcs": attr.label_list(allow_files = [".carbon"]),
  135. "srcs": attr.label_list(allow_files = [".carbon"]),
  136. "_cc_toolchain": attr.label(default = "@bazel_tools//tools/cpp:current_cc_toolchain"),
  137. },
  138. executable = True,
  139. )
  140. def carbon_binary(name, srcs, deps = [], flags = [], tags = []):
  141. """Compiles a Carbon binary.
  142. Args:
  143. name: The name of the build target.
  144. srcs: List of Carbon source files to compile.
  145. deps: List of dependencies.
  146. flags: Extra flags to pass to the Carbon compile command.
  147. tags: Tags to apply to the rule.
  148. """
  149. _carbon_binary_internal(
  150. name = name,
  151. srcs = srcs,
  152. prelude_srcs = ["//core:prelude_files"],
  153. deps = deps,
  154. flags = flags,
  155. tags = tags,
  156. # We synthesize two sets of attributes from mirrored `select`s here
  157. # because we want to select on an internal property of these attributes
  158. # but that isn't `select`-able. Instead, we have both attributes and
  159. # `select` which one we use.
  160. internal_exec_toolchain_driver = select({
  161. "//bazel/carbon_rules:use_target_config_carbon_rules_config": None,
  162. "//conditions:default": "//toolchain/install:prefix/bin/carbon",
  163. }),
  164. internal_exec_toolchain_data = select({
  165. "//bazel/carbon_rules:use_target_config_carbon_rules_config": None,
  166. "//conditions:default": "//toolchain/install:install_data",
  167. }),
  168. internal_exec_prebuilt_runtimes = select({
  169. "//bazel/carbon_rules:use_target_config_carbon_rules_config": None,
  170. "//conditions:default": "//toolchain/driver:prebuilt_runtimes",
  171. }),
  172. internal_target_toolchain_driver = select({
  173. "//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:prefix/bin/carbon",
  174. "//conditions:default": None,
  175. }),
  176. internal_target_toolchain_data = select({
  177. "//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:install_data",
  178. "//conditions:default": None,
  179. }),
  180. internal_target_prebuilt_runtimes = select({
  181. "//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/driver:prebuilt_runtimes",
  182. "//conditions:default": None,
  183. }),
  184. )