fix_cc_deps.py 10 KB

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