PageRenderTime 125ms CodeModel.GetById 24ms RepoModel.GetById 11ms app.codeStats 0ms

/share/clang/clang-include-fixer.py

https://gitlab.com/Alioth-Project/clang-r445002
Python | 219 lines | 176 code | 17 blank | 26 comment | 19 complexity | 6e3bc0dd6fa2caf1086164c7ab42983a MD5 | raw file
  1. # This file is a minimal clang-include-fixer vim-integration. To install:
  2. # - Change 'binary' if clang-include-fixer is not on the path (see below).
  3. # - Add to your .vimrc:
  4. #
  5. # noremap <leader>cf :pyf path/to/llvm/source/tools/clang/tools/extra/clang-include-fixer/tool/clang-include-fixer.py<cr>
  6. #
  7. # This enables clang-include-fixer for NORMAL and VISUAL mode. Change
  8. # "<leader>cf" to another binding if you need clang-include-fixer on a
  9. # different key.
  10. #
  11. # To set up clang-include-fixer, see
  12. # http://clang.llvm.org/extra/clang-include-fixer.html
  13. #
  14. # With this integration you can press the bound key and clang-include-fixer will
  15. # be run on the current buffer.
  16. #
  17. # It operates on the current, potentially unsaved buffer and does not create
  18. # or save any files. To revert a fix, just undo.
  19. from __future__ import print_function
  20. import argparse
  21. import difflib
  22. import json
  23. import re
  24. import subprocess
  25. import vim
  26. # set g:clang_include_fixer_path to the path to clang-include-fixer if it is not
  27. # on the path.
  28. # Change this to the full path if clang-include-fixer is not on the path.
  29. binary = 'clang-include-fixer'
  30. if vim.eval('exists("g:clang_include_fixer_path")') == "1":
  31. binary = vim.eval('g:clang_include_fixer_path')
  32. maximum_suggested_headers = 3
  33. if vim.eval('exists("g:clang_include_fixer_maximum_suggested_headers")') == "1":
  34. maximum_suggested_headers = max(
  35. 1,
  36. vim.eval('g:clang_include_fixer_maximum_suggested_headers'))
  37. increment_num = 5
  38. if vim.eval('exists("g:clang_include_fixer_increment_num")') == "1":
  39. increment_num = max(
  40. 1,
  41. vim.eval('g:clang_include_fixer_increment_num'))
  42. jump_to_include = False
  43. if vim.eval('exists("g:clang_include_fixer_jump_to_include")') == "1":
  44. jump_to_include = vim.eval('g:clang_include_fixer_jump_to_include') != "0"
  45. query_mode = False
  46. if vim.eval('exists("g:clang_include_fixer_query_mode")') == "1":
  47. query_mode = vim.eval('g:clang_include_fixer_query_mode') != "0"
  48. def GetUserSelection(message, headers, maximum_suggested_headers):
  49. eval_message = message + '\n'
  50. for idx, header in enumerate(headers[0:maximum_suggested_headers]):
  51. eval_message += "({0}). {1}\n".format(idx + 1, header)
  52. eval_message += "Enter (q) to quit;"
  53. if maximum_suggested_headers < len(headers):
  54. eval_message += " (m) to show {0} more candidates.".format(
  55. min(increment_num, len(headers) - maximum_suggested_headers))
  56. eval_message += "\nSelect (default 1): "
  57. res = vim.eval("input('{0}')".format(eval_message))
  58. if res == '':
  59. # choose the top ranked header by default
  60. idx = 1
  61. elif res == 'q':
  62. raise Exception(' Insertion cancelled...')
  63. elif res == 'm':
  64. return GetUserSelection(message,
  65. headers, maximum_suggested_headers + increment_num)
  66. else:
  67. try:
  68. idx = int(res)
  69. if idx <= 0 or idx > len(headers):
  70. raise Exception()
  71. except Exception:
  72. # Show a new prompt on invalid option instead of aborting so that users
  73. # don't need to wait for another clang-include-fixer run.
  74. print("Invalid option: {}".format(res), file=sys.stderr)
  75. return GetUserSelection(message, headers, maximum_suggested_headers)
  76. return headers[idx - 1]
  77. def execute(command, text):
  78. # Avoid flashing a cmd prompt on Windows.
  79. startupinfo = None
  80. if sys.platform.startswith('win32'):
  81. startupinfo = subprocess.STARTUPINFO()
  82. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  83. startupinfo.wShowWindow = subprocess.SW_HIDE
  84. p = subprocess.Popen(command,
  85. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  86. stdin=subprocess.PIPE, startupinfo=startupinfo)
  87. return p.communicate(input=text.encode('utf-8'))
  88. def InsertHeaderToVimBuffer(header, text):
  89. command = [binary, "-stdin", "-insert-header=" + json.dumps(header),
  90. vim.current.buffer.name]
  91. stdout, stderr = execute(command, text)
  92. if stderr:
  93. raise Exception(stderr)
  94. if stdout:
  95. lines = stdout.splitlines()
  96. sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
  97. line_num = None
  98. for op in reversed(sequence.get_opcodes()):
  99. if op[0] != 'equal':
  100. vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
  101. if op[0] == 'insert':
  102. # line_num in vim is 1-based.
  103. line_num = op[1] + 1
  104. if jump_to_include and line_num:
  105. vim.current.window.cursor = (line_num, 0)
  106. # The vim internal implementation (expand("cword"/"cWORD")) doesn't support
  107. # our use case very well, we re-implement our own one.
  108. def get_symbol_under_cursor():
  109. line = vim.eval("line(\".\")")
  110. # column number in vim is 1-based.
  111. col = int(vim.eval("col(\".\")")) - 1
  112. line_text = vim.eval("getline({0})".format(line))
  113. if len(line_text) == 0: return ""
  114. symbol_pos_begin = col
  115. p = re.compile('[a-zA-Z0-9:_]')
  116. while symbol_pos_begin >= 0 and p.match(line_text[symbol_pos_begin]):
  117. symbol_pos_begin -= 1
  118. symbol_pos_end = col
  119. while symbol_pos_end < len(line_text) and p.match(line_text[symbol_pos_end]):
  120. symbol_pos_end += 1
  121. return line_text[symbol_pos_begin+1:symbol_pos_end]
  122. def main():
  123. parser = argparse.ArgumentParser(
  124. description='Vim integration for clang-include-fixer')
  125. parser.add_argument('-db', default='yaml',
  126. help='clang-include-fixer input format.')
  127. parser.add_argument('-input', default='',
  128. help='String to initialize the database.')
  129. # Don't throw exception when parsing unknown arguments to make the script
  130. # work in neovim.
  131. # Neovim (at least v0.2.1) somehow mangles the sys.argv in a weird way: it
  132. # will pass additional arguments (e.g. "-c script_host.py") to sys.argv,
  133. # which makes the script fail.
  134. args, _ = parser.parse_known_args()
  135. # Get the current text.
  136. buf = vim.current.buffer
  137. text = '\n'.join(buf)
  138. if query_mode:
  139. symbol = get_symbol_under_cursor()
  140. if len(symbol) == 0:
  141. print("Skip querying empty symbol.")
  142. return
  143. command = [binary, "-stdin", "-query-symbol="+get_symbol_under_cursor(),
  144. "-db=" + args.db, "-input=" + args.input,
  145. vim.current.buffer.name]
  146. else:
  147. # Run command to get all headers.
  148. command = [binary, "-stdin", "-output-headers", "-db=" + args.db,
  149. "-input=" + args.input, vim.current.buffer.name]
  150. stdout, stderr = execute(command, text)
  151. if stderr:
  152. print("Error while running clang-include-fixer: {}".format(stderr),
  153. file=sys.stderr)
  154. return
  155. include_fixer_context = json.loads(stdout)
  156. query_symbol_infos = include_fixer_context["QuerySymbolInfos"]
  157. if not query_symbol_infos:
  158. print("The file is fine, no need to add a header.")
  159. return
  160. symbol = query_symbol_infos[0]["RawIdentifier"]
  161. # The header_infos is already sorted by clang-include-fixer.
  162. header_infos = include_fixer_context["HeaderInfos"]
  163. # Deduplicate headers while keeping the order, so that the same header would
  164. # not be suggested twice.
  165. unique_headers = []
  166. seen = set()
  167. for header_info in header_infos:
  168. header = header_info["Header"]
  169. if header not in seen:
  170. seen.add(header)
  171. unique_headers.append(header)
  172. if not unique_headers:
  173. print("Couldn't find a header for {0}.".format(symbol))
  174. return
  175. try:
  176. selected = unique_headers[0]
  177. inserted_header_infos = header_infos
  178. if len(unique_headers) > 1:
  179. selected = GetUserSelection(
  180. "choose a header file for {0}.".format(symbol),
  181. unique_headers, maximum_suggested_headers)
  182. inserted_header_infos = [
  183. header for header in header_infos if header["Header"] == selected]
  184. include_fixer_context["HeaderInfos"] = inserted_header_infos
  185. InsertHeaderToVimBuffer(include_fixer_context, text)
  186. print("Added #include {0} for {1}.".format(selected, symbol))
  187. except Exception as error:
  188. print(error, file=sys.stderr)
  189. return
  190. if __name__ == '__main__':
  191. main()