fix_cc_deps.py 11 KB

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