1#!/usr/bin/env python
2
3"""Script to sort the top-most block of #include lines.
4
5Assumes the LLVM coding conventions.
6
7Currently, this script only bothers sorting the llvm/... headers. Patches
8welcome for more functionality, and sorting other header groups.
9"""
10
11import argparse
12import os
13
14def sort_includes(f):
15  """Sort the #include lines of a specific file."""
16
17  # Skip files which are under INPUTS trees or test trees.
18  if 'INPUTS/' in f.name or 'test/' in f.name:
19    return
20
21  ext = os.path.splitext(f.name)[1]
22  if ext not in ['.cpp', '.c', '.h', '.inc', '.def']:
23    return
24
25  lines = f.readlines()
26  look_for_api_header = ext in ['.cpp', '.c']
27  found_headers = False
28  headers_begin = 0
29  headers_end = 0
30  api_headers = []
31  local_headers = []
32  subproject_headers = []
33  llvm_headers = []
34  system_headers = []
35  for (i, l) in enumerate(lines):
36    if l.strip() == '':
37      continue
38    if l.startswith('#include'):
39      if not found_headers:
40        headers_begin = i
41        found_headers = True
42      headers_end = i
43      header = l[len('#include'):].lstrip()
44      if look_for_api_header and header.startswith('"'):
45        api_headers.append(header)
46        look_for_api_header = False
47        continue
48      if (header.startswith('<') or header.startswith('"gtest/') or
49          header.startswith('"isl/') or header.startswith('"json/')):
50        system_headers.append(header)
51        continue
52      if (header.startswith('"clang/') or header.startswith('"clang-c/') or
53          header.startswith('"polly/')):
54        subproject_headers.append(header)
55        continue
56      if (header.startswith('"llvm/') or header.startswith('"llvm-c/')):
57        llvm_headers.append(header)
58        continue
59      local_headers.append(header)
60      continue
61
62    # Only allow comments and #defines prior to any includes. If either are
63    # mixed with includes, the order might be sensitive.
64    if found_headers:
65      break
66    if l.startswith('//') or l.startswith('#define') or l.startswith('#ifndef'):
67      continue
68    break
69  if not found_headers:
70    return
71
72  local_headers = sorted(set(local_headers))
73  subproject_headers = sorted(set(subproject_headers))
74  llvm_headers = sorted(set(llvm_headers))
75  system_headers = sorted(set(system_headers))
76  headers = api_headers + local_headers + subproject_headers + llvm_headers + system_headers
77  header_lines = ['#include ' + h for h in headers]
78  lines = lines[:headers_begin] + header_lines + lines[headers_end + 1:]
79
80  f.seek(0)
81  f.truncate()
82  f.writelines(lines)
83
84def main():
85  parser = argparse.ArgumentParser(description=__doc__)
86  parser.add_argument('files', nargs='+', type=argparse.FileType('r+'),
87                      help='the source files to sort includes within')
88  args = parser.parse_args()
89  for f in args.files:
90    sort_includes(f)
91
92if __name__ == '__main__':
93  main()
94