fix_cc_deps.py 9.2 KB

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