fix_cc_deps.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #!/usr/bin/env python3
  2. """Automatically fixes bazel C++ dependencies.
  3. Bazel has some support for detecting when an include refers to a missing
  4. dependency. However, the ideal state is that a given build target depends
  5. directly on all #include'd headers, and Bazel doesn't enforce that. This
  6. automates the addition for technical correctness.
  7. """
  8. __copyright__ = """
  9. Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  10. Exceptions. See /LICENSE for license information.
  11. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  12. """
  13. import re
  14. import subprocess
  15. from typing import Callable, Dict, List, NamedTuple, Set, Tuple
  16. from xml.etree import ElementTree
  17. import scripts_utils # type: ignore
  18. # Maps external repository names to a method translating bazel labels to file
  19. # paths for that repository.
  20. EXTERNAL_REPOS: Dict[str, Callable[[str], str]] = {
  21. # @llvm-project//llvm:include/llvm/Support/Error.h ->
  22. # llvm/Support/Error.h
  23. "@llvm-project": lambda x: re.sub("^(.*:(lib|include))/", "", x),
  24. # @com_google_protobuf//:src/google/protobuf/descriptor.h ->
  25. # google/protobuf/descriptor.h
  26. "@com_google_protobuf": lambda x: re.sub("^(.*:src)/", "", x),
  27. # @com_google_libprotobuf_mutator//:src/libfuzzer/libfuzzer_macro.h ->
  28. # libprotobuf_mutator/src/libfuzzer/libfuzzer_macro.h
  29. "@com_google_libprotobuf_mutator": lambda x: re.sub(
  30. "^(.*:)", "libprotobuf_mutator/", x
  31. ),
  32. }
  33. # TODO: proto rules are aspect-based and their generated files don't show up in
  34. # `bazel query` output.
  35. # Try using `bazel cquery --output=starlark` to print `target.files`.
  36. # For protobuf, need to add support for `alias` rule kind.
  37. IGNORE_HEADER_REGEX = re.compile("^(.*\\.pb\\.h)|(.*google/protobuf/.*)$")
  38. class Rule(NamedTuple):
  39. # For cc_* rules:
  40. # The hdrs + textual_hdrs attributes, as relative paths to the file.
  41. hdrs: Set[str]
  42. # The srcs attribute, as relative paths to the file.
  43. srcs: Set[str]
  44. # The deps attribute, as full bazel labels.
  45. deps: Set[str]
  46. # For genrules:
  47. # The outs attribute, as relative paths to the file.
  48. outs: Set[str]
  49. def remap_file(label: str) -> str:
  50. """Remaps a bazel label to a file."""
  51. repo, _, path = label.partition("//")
  52. if not repo:
  53. return path.replace(":", "/")
  54. assert repo in EXTERNAL_REPOS, repo
  55. return EXTERNAL_REPOS[repo](path)
  56. exit(f"Don't know how to remap label '{label}'")
  57. def get_bazel_list(list_child: ElementTree.Element, is_file: bool) -> Set[str]:
  58. """Returns the contents of a bazel list.
  59. The return will normally be the full label, unless `is_file` is set, in
  60. which case the label will be translated to the underlying file.
  61. """
  62. results: Set[str] = set()
  63. for label in list_child:
  64. assert label.tag in ("label", "output"), label.tag
  65. value = label.attrib["value"]
  66. if is_file:
  67. value = remap_file(value)
  68. results.add(value)
  69. return results
  70. def get_rules(bazel: str, targets: str, keep_going: bool) -> Dict[str, Rule]:
  71. """Queries the specified targets, returning the found rules.
  72. keep_going will be set to true for external repositories, where sometimes we
  73. see query errors.
  74. The return maps rule names to rule data.
  75. """
  76. args = [
  77. bazel,
  78. "query",
  79. "--output=xml",
  80. f"kind('(cc_binary|cc_library|cc_test|genrule)', set({targets}))",
  81. ]
  82. if keep_going:
  83. args.append("--keep_going")
  84. p = subprocess.run(
  85. args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8"
  86. )
  87. # 3 indicates incomplete results from --keep_going, which is fine here.
  88. if p.returncode not in {0, 3}:
  89. print(p.stderr)
  90. exit(f"bazel query returned {p.returncode}")
  91. rules: Dict[str, Rule] = {}
  92. for rule_xml in ElementTree.fromstring(p.stdout):
  93. assert rule_xml.tag == "rule", rule_xml.tag
  94. rule_name = rule_xml.attrib["name"]
  95. hdrs: Set[str] = set()
  96. srcs: Set[str] = set()
  97. deps: Set[str] = set()
  98. outs: Set[str] = set()
  99. rule_class = rule_xml.attrib["class"]
  100. for list_child in rule_xml.findall("list"):
  101. list_name = list_child.attrib["name"]
  102. if rule_class in ("cc_library", "cc_binary", "cc_test"):
  103. if list_name in ("hdrs", "textual_hdrs"):
  104. hdrs = hdrs.union(get_bazel_list(list_child, True))
  105. elif list_name == "srcs":
  106. srcs = get_bazel_list(list_child, True)
  107. elif list_name == "deps":
  108. deps = get_bazel_list(list_child, False)
  109. elif rule_class == "genrule":
  110. if list_name == "outs":
  111. outs = get_bazel_list(list_child, True)
  112. else:
  113. exit(f"unexpected rule type: {rule_class}")
  114. rules[rule_name] = Rule(hdrs, srcs, deps, outs)
  115. return rules
  116. def map_headers(
  117. header_to_rule_map: Dict[str, Set[str]], rules: Dict[str, Rule]
  118. ) -> None:
  119. """Accumulates headers provided by rules into the map.
  120. The map maps header paths to rule names.
  121. """
  122. for rule_name, rule in rules.items():
  123. for header in rule.hdrs:
  124. if header in header_to_rule_map:
  125. header_to_rule_map[header].add(rule_name)
  126. else:
  127. header_to_rule_map[header] = {rule_name}
  128. def get_missing_deps(
  129. header_to_rule_map: Dict[str, Set[str]],
  130. generated_files: Set[str],
  131. rule: Rule,
  132. ) -> Tuple[Set[str], bool]:
  133. """Returns missing dependencies for the rule.
  134. On return, the set is dependency labels that should be added; the bool
  135. indicates whether some where omitted due to ambiguity.
  136. """
  137. missing_deps: Set[str] = set()
  138. ambiguous = False
  139. rule_files = rule.hdrs.union(rule.srcs)
  140. for source_file in rule_files:
  141. if source_file in generated_files:
  142. continue
  143. with open(source_file, "r") as f:
  144. for header in re.findall(
  145. r'^#include "([^"]+)"', f.read(), re.MULTILINE
  146. ):
  147. if header in rule_files:
  148. continue
  149. if header not in header_to_rule_map:
  150. if IGNORE_HEADER_REGEX.match(header):
  151. print(
  152. f"Ignored missing #include '{header}' in "
  153. f"'{source_file}'"
  154. )
  155. continue
  156. else:
  157. exit(
  158. f"Missing rule for #include '{header}' in "
  159. f"'{source_file}'"
  160. )
  161. dep_choices = header_to_rule_map[header]
  162. if not dep_choices.intersection(rule.deps):
  163. if len(dep_choices) > 1:
  164. print(
  165. f"Ambiguous dependency choice for #include "
  166. f"'{header}' in '{source_file}': "
  167. f"{', '.join(dep_choices)}"
  168. )
  169. ambiguous = True
  170. # Use the single dep without removing it.
  171. missing_deps.add(next(iter(dep_choices)))
  172. return missing_deps, ambiguous
  173. def main() -> None:
  174. scripts_utils.chdir_repo_root()
  175. bazel = scripts_utils.locate_bazel()
  176. print("Querying bazel for Carbon targets...")
  177. carbon_rules = get_rules(bazel, "//...", False)
  178. print("Querying bazel for external targets...")
  179. external_repo_query = " ".join([f"{repo}//..." for repo in EXTERNAL_REPOS])
  180. external_rules = get_rules(bazel, external_repo_query, True)
  181. print("Building header map...")
  182. header_to_rule_map: Dict[str, Set[str]] = {}
  183. map_headers(header_to_rule_map, carbon_rules)
  184. map_headers(header_to_rule_map, external_rules)
  185. print("Building generated file list...")
  186. generated_files: Set[str] = set()
  187. for rule in carbon_rules.values():
  188. generated_files = generated_files.union(rule.outs)
  189. print("Parsing headers from source files...")
  190. all_missing_deps: List[Tuple[str, Set[str]]] = []
  191. any_ambiguous = False
  192. for rule_name, rule in carbon_rules.items():
  193. missing_deps, ambiguous = get_missing_deps(
  194. header_to_rule_map, generated_files, rule
  195. )
  196. if missing_deps:
  197. all_missing_deps.append((rule_name, missing_deps))
  198. if ambiguous:
  199. any_ambiguous = True
  200. if any_ambiguous:
  201. exit("Stopping due to ambiguous dependency choices.")
  202. if all_missing_deps:
  203. print("Checking buildozer availability...")
  204. buildozer = scripts_utils.get_release(scripts_utils.Release.BUILDOZER)
  205. print("Fixing dependencies...")
  206. SEPARATOR = "\n- "
  207. for rule_name, missing_deps in sorted(all_missing_deps):
  208. friendly_missing_deps = SEPARATOR.join(missing_deps)
  209. print(
  210. f"Adding deps to {rule_name}:{SEPARATOR}{friendly_missing_deps}"
  211. )
  212. args = [
  213. buildozer,
  214. f"add deps {' '.join(missing_deps)}",
  215. rule_name,
  216. ]
  217. subprocess.check_call(args)
  218. print("Done!")
  219. if __name__ == "__main__":
  220. main()