fix_cc_deps.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. "@boost.unordered": ExternalRepo(
  52. lambda x: re.sub("^(.*:include)/", "", x),
  53. ":boost.unordered",
  54. use_system_include=True,
  55. ),
  56. }
  57. IGNORE_SOURCE_FILE_REGEX = re.compile(
  58. r"^(third_party/clangd.*|common/version.*\.cpp"
  59. r"|.*_autogen_manifest\.cpp"
  60. r"|toolchain/base/llvm_tools.def"
  61. r"|toolchain/base/runtimes_build_info.h)$"
  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 in ("tree_sitter_cc_library", "cc_library_wrapper"):
  139. # Note that `cc_library_wrapper` isn't a general rule, it is a
  140. # specialized rule from inside LLVM wrapping some of its
  141. # dependencies and injecting configuration macro defines.
  142. continue
  143. else:
  144. exit(f"unexpected rule type: {rule_class}")
  145. rules[rule_name] = Rule(hdrs, srcs, deps, outs)
  146. return rules
  147. def map_headers(
  148. header_to_rule_map: dict[str, RuleChoice], rules: dict[str, Rule]
  149. ) -> None:
  150. """Accumulates headers provided by rules into the map.
  151. The map maps header paths to rule names.
  152. """
  153. for rule_name, rule in rules.items():
  154. repo, _, path = rule_name.partition("//")
  155. use_system_include = False
  156. if repo in EXTERNAL_REPOS:
  157. use_system_include = EXTERNAL_REPOS[repo].use_system_include
  158. for header in rule.hdrs:
  159. if header in header_to_rule_map:
  160. header_to_rule_map[header].rules.add(rule_name)
  161. if (
  162. use_system_include
  163. != header_to_rule_map[header].use_system_include
  164. ):
  165. exit(
  166. "Unexpected use_system_include inconsistency in "
  167. f"{header_to_rule_map[header]}"
  168. )
  169. else:
  170. header_to_rule_map[header] = RuleChoice(
  171. use_system_include, {rule_name}
  172. )
  173. def get_missing_deps(
  174. header_to_rule_map: dict[str, RuleChoice],
  175. generated_files: set[str],
  176. rule: Rule,
  177. ) -> tuple[set[str], bool]:
  178. """Returns missing dependencies for the rule.
  179. On return, the set is dependency labels that should be added; the bool
  180. indicates whether some where omitted due to ambiguity.
  181. """
  182. missing_deps: set[str] = set()
  183. ambiguous = False
  184. rule_files = rule.hdrs.union(rule.srcs)
  185. for source_file in rule_files:
  186. if source_file in generated_files:
  187. continue
  188. if IGNORE_SOURCE_FILE_REGEX.match(source_file):
  189. continue
  190. with open(source_file, "r") as f:
  191. file_content = f.read()
  192. file_content_changed = False
  193. for header_groups in re.findall(
  194. r'^(#include (?:(["<])([^">]+)[">]))',
  195. file_content,
  196. re.MULTILINE,
  197. ):
  198. full_include, include_open, header = header_groups
  199. is_system_include = include_open == "<"
  200. if header in rule_files:
  201. continue
  202. if header not in header_to_rule_map:
  203. if is_system_include:
  204. # Don't error for unexpected system includes.
  205. continue
  206. exit(
  207. f"Missing rule for " f"'{full_include}' in '{source_file}'"
  208. )
  209. rule_choice = header_to_rule_map[header]
  210. if not rule_choice.rules.intersection(rule.deps):
  211. if len(rule_choice.rules) > 1:
  212. print(
  213. f"Ambiguous dependency choice for "
  214. f"'{full_include}' in '{source_file}': "
  215. f"{', '.join(rule_choice.rules)}"
  216. )
  217. ambiguous = True
  218. # Use the single dep without removing it.
  219. missing_deps.add(next(iter(rule_choice.rules)))
  220. # If the include style should change, update file content.
  221. if is_system_include != rule_choice.use_system_include:
  222. if rule_choice.use_system_include:
  223. new_include = f"#include <{header}>"
  224. else:
  225. new_include = f'#include "{header}"'
  226. print(
  227. f"Fixing include format in '{source_file}': "
  228. f"'{full_include}' to '{new_include}'"
  229. )
  230. file_content = file_content.replace(full_include, new_include)
  231. file_content_changed = True
  232. if file_content_changed:
  233. with open(source_file, "w") as f:
  234. f.write(file_content)
  235. return missing_deps, ambiguous
  236. def main() -> None:
  237. scripts_utils.chdir_repo_root()
  238. bazel = scripts_utils.locate_bazel()
  239. print("Querying bazel for Carbon targets...")
  240. carbon_rules = get_rules(bazel, "//...", False)
  241. print("Querying bazel for external targets...")
  242. external_repo_query = " ".join(
  243. [f"{repo}//{EXTERNAL_REPOS[repo].target}" for repo in EXTERNAL_REPOS]
  244. )
  245. external_rules = get_rules(bazel, external_repo_query, True)
  246. print("Building header map...")
  247. header_to_rule_map: dict[str, RuleChoice] = {}
  248. map_headers(header_to_rule_map, carbon_rules)
  249. map_headers(header_to_rule_map, external_rules)
  250. print("Building generated file list...")
  251. generated_files: set[str] = set()
  252. for rule in carbon_rules.values():
  253. generated_files = generated_files.union(rule.outs)
  254. print("Parsing headers from source files...")
  255. all_missing_deps: list[tuple[str, set[str]]] = []
  256. any_ambiguous = False
  257. for rule_name, rule in carbon_rules.items():
  258. missing_deps, ambiguous = get_missing_deps(
  259. header_to_rule_map, generated_files, rule
  260. )
  261. if missing_deps:
  262. all_missing_deps.append((rule_name, missing_deps))
  263. if ambiguous:
  264. any_ambiguous = True
  265. if any_ambiguous:
  266. exit("Stopping due to ambiguous dependency choices.")
  267. if all_missing_deps:
  268. print("Checking buildozer availability...")
  269. buildozer = scripts_utils.get_release(scripts_utils.Release.BUILDOZER)
  270. print("Fixing dependencies...")
  271. SEPARATOR = "\n- "
  272. for rule_name, missing_deps in sorted(all_missing_deps):
  273. friendly_missing_deps = SEPARATOR.join(missing_deps)
  274. print(
  275. f"Adding deps to {rule_name}:{SEPARATOR}{friendly_missing_deps}"
  276. )
  277. args = [
  278. buildozer,
  279. f"add deps {' '.join(missing_deps)}",
  280. rule_name,
  281. ]
  282. subprocess.check_call(args)
  283. print("Done!")
  284. if __name__ == "__main__":
  285. main()