iwyu_apply.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python3
  2. """Removes the includes include-what-you-use calls unused from the engine's .cpp files, and keeps only the removals that
  3. still compile.
  4. iwyu_tool.py -p build-clang -j 6 src/WallpaperEngine > iwyu.txt
  5. tools/analysis/iwyu_apply.py iwyu.txt [-j 8] [--dry-run]
  6. Only "remove" lines of .cpp files count. Left alone on purpose: headers, includes inside #if blocks (IWYU only sees the
  7. active configuration), IWYU pragmas and, without --std, standard library headers (the transitive includes of the
  8. libstdc++ here are not those of Debian 12's, a removal that builds here could break the portable build). Every changed
  9. file is syntax checked with g++ (build/) and clang++ (build-clang/) from their compile_commands.json; a file that fails
  10. is tried again one include at a time. Run clang-format on the result.
  11. --std takes the standard library headers instead of everything else, and also checks each file with Debian 12's g++ 12
  12. (the portable release's compiler, the oldest libstdc++ we build with) in its rootfs under proot: `build-deb12` is a CMake
  13. build dir of the repo made there (/src = the repo, /build), PROOT and the rootfs from tools/distro_rootfs.sh
  14. (~/.local/share/distro-rootfs/debian-12 and build-deb12, proot at ~/.local/share/arch-proot/proot unless PROOT is set).
  15. """
  16. import argparse
  17. import collections
  18. import concurrent.futures as cf
  19. import json
  20. import os
  21. import re
  22. import shlex
  23. import subprocess
  24. from pathlib import Path
  25. ROOT = Path(__file__).resolve().parents[2]
  26. STD_HEADER = re.compile(r'^#include <[^.>]+>$')
  27. BUILDS = ('build', 'build-clang')
  28. ROOTFS = Path.home() / '.local/share/distro-rootfs'
  29. PROOT = os.environ.get('PROOT', str(Path.home() / '.local/share/arch-proot/proot'))
  30. def parse(report):
  31. removals = collections.defaultdict(dict)
  32. current = None
  33. for line in report.read_text(errors='replace').split('\n'):
  34. m = re.match(r'^(/\S+) should remove these lines:$', line)
  35. if m:
  36. current = m.group(1)
  37. continue
  38. if current and line.startswith('- #include'):
  39. m = re.match(r'^- (#include [<"][^>"]+[>"])\s+// lines (\d+)-(\d+)', line)
  40. if m:
  41. removals[current][int(m.group(2)) - 1] = m.group(1)
  42. continue
  43. if current and not line.startswith('- ') and line.strip():
  44. current = None
  45. return removals
  46. def candidates(removals, std):
  47. plan = {}
  48. for path, items in removals.items():
  49. if not path.startswith(str(ROOT / 'src/WallpaperEngine') + '/') or not path.endswith('.cpp'):
  50. continue
  51. lines = Path(path).read_text().split('\n')
  52. depth, conditional = 0, []
  53. for line in lines:
  54. text = line.strip()
  55. if re.match(r'#\s*(if|ifdef|ifndef)\b', text):
  56. depth += 1
  57. conditional.append(depth > 0)
  58. if re.match(r'#\s*endif\b', text):
  59. depth -= 1
  60. keep = [i for i, include in sorted(items.items())
  61. if i < len(lines) and lines[i].split('//')[0].strip() == include and 'IWYU pragma' not in lines[i]
  62. and not conditional[i] and bool(STD_HEADER.match(include)) == std]
  63. if keep:
  64. plan[path] = keep
  65. return plan
  66. def load(build):
  67. return {entry['file']: entry for entry in json.loads((ROOT / build / 'compile_commands.json').read_text())}
  68. def compiles_deb12(entry, path):
  69. args = shlex.split(entry['command'])
  70. args = [a for a in args if not (a.startswith('-W') and not a.startswith('-Wno-'))]
  71. if '-o' in args:
  72. i = args.index('-o')
  73. del args[i:i + 2]
  74. args = [a for a in args if a != '-c']
  75. args.insert(1, '-fsyntax-only')
  76. command = ['bash', str(ROOT / 'tools/distro_rootfs.sh'), 'run', str(ROOTFS / 'debian-12'), '-u', 'sh', '-c',
  77. 'cd /build && ' + shlex.join(args)]
  78. env = dict(os.environ, PROOT=PROOT, BINDS=f'-b {ROOT}:/src -b {ROOTFS / "build-deb12"}:/build')
  79. return subprocess.run(command, env=env, capture_output=True).returncode == 0
  80. def compiles(databases, path, deb12=None):
  81. if deb12 is not None:
  82. entry = deb12.get(path.replace(str(ROOT), '/src', 1))
  83. if entry is None or not compiles_deb12(entry, path):
  84. return False
  85. checked = False
  86. for build in BUILDS:
  87. entry = databases[build].get(path)
  88. if entry is None:
  89. continue
  90. args = shlex.split(entry['command'])
  91. args[0] = 'g++' if build == 'build' else 'clang++'
  92. args = [a for a in args if not (a.startswith('-W') and not a.startswith('-Wno-'))]
  93. if '-o' in args:
  94. i = args.index('-o')
  95. del args[i:i + 2]
  96. args = [a for a in args if a not in ('-c', '-ftime-trace')]
  97. args.insert(1, '-fsyntax-only')
  98. checked = True
  99. if subprocess.run(args, cwd=entry['directory'], capture_output=True).returncode != 0:
  100. return False
  101. return checked
  102. def apply(databases, path, indices, deb12):
  103. file = Path(path)
  104. original = file.read_text()
  105. lines = original.split('\n')
  106. def write(dropped):
  107. file.write_text('\n'.join(line for i, line in enumerate(lines) if i not in dropped))
  108. try:
  109. write(set(indices))
  110. if compiles(databases, path, deb12):
  111. return len(indices)
  112. dropped = set()
  113. for i in indices:
  114. write(dropped | {i})
  115. if compiles(databases, path, deb12):
  116. dropped.add(i)
  117. write(dropped)
  118. return len(dropped)
  119. except BaseException:
  120. file.write_text(original)
  121. raise
  122. def main():
  123. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  124. parser.add_argument('report', type=Path)
  125. parser.add_argument('-j', '--jobs', type=int, default=8)
  126. parser.add_argument('--dry-run', action='store_true')
  127. parser.add_argument('--std', action='store_true', help='standard library headers, also checked with Debian 12')
  128. options = parser.parse_args()
  129. plan = candidates(parse(options.report), options.std)
  130. print(f'{len(plan)} files, {sum(len(v) for v in plan.values())} includes to try')
  131. if options.dry_run:
  132. return
  133. databases = {build: load(build) for build in BUILDS}
  134. deb12 = {entry['file']: entry for entry in json.loads((ROOTFS / 'build-deb12/compile_commands.json').read_text())} if options.std else None
  135. with cf.ThreadPoolExecutor(options.jobs) as pool:
  136. futures = {pool.submit(apply, databases, path, indices, deb12): (path, len(indices)) for path, indices in plan.items()}
  137. removed = 0
  138. for future in cf.as_completed(futures):
  139. path, wanted = futures[future]
  140. count = future.result()
  141. removed += count
  142. print(f'{count}/{wanted} {Path(path).relative_to(ROOT)}')
  143. print(f'{removed} includes removed')
  144. if __name__ == '__main__':
  145. main()