fix_cc_deps.py 11 KB

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