fix_cc_deps.py 11 KB

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