fix_cc_deps.py 11 KB

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