clang_completer.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io>
  4. #
  5. # This file is part of YouCompleteMe.
  6. #
  7. # YouCompleteMe is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # YouCompleteMe is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  19. from collections import defaultdict
  20. import ycm_core
  21. import logging
  22. from ycm.server import responses
  23. from ycm import extra_conf_store
  24. from ycm.utils import ToUtf8IfNeeded
  25. from ycm.completers.completer import Completer
  26. from ycm.completers.cpp.flags import Flags
  27. CLANG_FILETYPES = set( [ 'c', 'cpp', 'objc', 'objcpp' ] )
  28. MIN_LINES_IN_FILE_TO_PARSE = 5
  29. PARSING_FILE_MESSAGE = 'Still parsing file, no completions yet.'
  30. NO_COMPILE_FLAGS_MESSAGE = 'Still no compile flags, no completions yet.'
  31. NO_COMPLETIONS_MESSAGE = 'No completions found; errors in the file?'
  32. INVALID_FILE_MESSAGE = 'File is invalid.'
  33. FILE_TOO_SHORT_MESSAGE = (
  34. 'File is less than {} lines long; not compiling.'.format(
  35. MIN_LINES_IN_FILE_TO_PARSE ) )
  36. NO_DIAGNOSTIC_MESSAGE = 'No diagnostic for current line!'
  37. class ClangCompleter( Completer ):
  38. def __init__( self, user_options ):
  39. super( ClangCompleter, self ).__init__( user_options )
  40. self.max_diagnostics_to_display = user_options[
  41. 'max_diagnostics_to_display' ]
  42. self.completer = ycm_core.ClangCompleter()
  43. self.completer.EnableThreading()
  44. self.last_prepared_diagnostics = []
  45. self.parse_future = None
  46. self.flags = Flags()
  47. self.diagnostic_store = None
  48. self._logger = logging.getLogger( __name__ )
  49. # We set this flag when a compilation request comes in while one is already
  50. # in progress. We use this to trigger the pending request after the previous
  51. # one completes (from GetDiagnosticsForCurrentFile because that's the only
  52. # method that knows when the compilation has finished).
  53. # TODO: Remove this now that we have multiple threads in the server; the
  54. # subsequent requests that want to parse will just block until the current
  55. # parse is done and will then proceed.
  56. self.extra_parse_desired = False
  57. def SupportedFiletypes( self ):
  58. return CLANG_FILETYPES
  59. def GetUnsavedFilesVector( self, request_data ):
  60. files = ycm_core.UnsavedFileVec()
  61. for filename, file_data in request_data[ 'file_data' ].iteritems():
  62. if not ClangAvailableForFiletypes( file_data[ 'filetypes' ] ):
  63. continue
  64. contents = file_data[ 'contents' ]
  65. if not contents or not filename:
  66. continue
  67. unsaved_file = ycm_core.UnsavedFile()
  68. utf8_contents = ToUtf8IfNeeded( contents )
  69. unsaved_file.contents_ = utf8_contents
  70. unsaved_file.length_ = len( utf8_contents )
  71. unsaved_file.filename_ = ToUtf8IfNeeded( filename )
  72. files.append( unsaved_file )
  73. return files
  74. def CandidatesForQueryAsync( self, request_data ):
  75. filename = request_data[ 'filepath' ]
  76. if not filename:
  77. return
  78. if self.completer.UpdatingTranslationUnit( ToUtf8IfNeeded( filename ) ):
  79. self.completions_future = None
  80. self._logger.info( PARSING_FILE_MESSAGE )
  81. return responses.BuildDisplayMessageResponse(
  82. PARSING_FILE_MESSAGE )
  83. flags = self.flags.FlagsForFile( filename )
  84. if not flags:
  85. self.completions_future = None
  86. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  87. return responses.BuildDisplayMessageResponse(
  88. NO_COMPILE_FLAGS_MESSAGE )
  89. # TODO: sanitize query, probably in C++ code
  90. files = ycm_core.UnsavedFileVec()
  91. query = request_data[ 'query' ]
  92. if not query:
  93. files = self.GetUnsavedFilesVector( request_data )
  94. line = request_data[ 'line_num' ] + 1
  95. column = request_data[ 'start_column' ] + 1
  96. self.completions_future = (
  97. self.completer.CandidatesForQueryAndLocationInFileAsync(
  98. ToUtf8IfNeeded( query ),
  99. ToUtf8IfNeeded( filename ),
  100. line,
  101. column,
  102. files,
  103. flags ) )
  104. def CandidatesFromStoredRequest( self ):
  105. if not self.completions_future:
  106. return []
  107. results = [ ConvertCompletionData( x ) for x in
  108. self.completions_future.GetResults() ]
  109. if not results:
  110. self._logger.warning( NO_COMPLETIONS_MESSAGE )
  111. raise RuntimeError( NO_COMPLETIONS_MESSAGE )
  112. return results
  113. def DefinedSubcommands( self ):
  114. return [ 'GoToDefinition',
  115. 'GoToDeclaration',
  116. 'GoToDefinitionElseDeclaration',
  117. 'ClearCompilationFlagCache']
  118. def OnUserCommand( self, arguments, request_data ):
  119. if not arguments:
  120. raise ValueError( self.UserCommandsHelpMessage() )
  121. command = arguments[ 0 ]
  122. if command == 'GoToDefinition':
  123. return self._GoToDefinition( request_data )
  124. elif command == 'GoToDeclaration':
  125. return self._GoToDeclaration( request_data )
  126. elif command == 'GoToDefinitionElseDeclaration':
  127. return self._GoToDefinitionElseDeclaration( request_data )
  128. elif command == 'ClearCompilationFlagCache':
  129. return self._ClearCompilationFlagCache( request_data )
  130. raise ValueError( self.UserCommandsHelpMessage() )
  131. def _LocationForGoTo( self, goto_function, request_data ):
  132. filename = request_data[ 'filepath' ]
  133. if not filename:
  134. self._logger.warning( INVALID_FILE_MESSAGE )
  135. return responses.BuildDisplayMessageResponse(
  136. INVALID_FILE_MESSAGE )
  137. flags = self.flags.FlagsForFile( filename )
  138. if not flags:
  139. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  140. return responses.BuildDisplayMessageResponse(
  141. NO_COMPILE_FLAGS_MESSAGE )
  142. files = self.GetUnsavedFilesVector( request_data )
  143. line = request_data[ 'line_num' ] + 1
  144. column = request_data[ 'column_num' ] + 1
  145. return getattr( self.completer, goto_function )(
  146. ToUtf8IfNeeded( filename ),
  147. line,
  148. column,
  149. files,
  150. flags )
  151. def _GoToDefinition( self, request_data ):
  152. location = self._LocationForGoTo( 'GetDefinitionLocation', request_data )
  153. if not location or not location.IsValid():
  154. raise RuntimeError( 'Can\'t jump to definition.' )
  155. return responses.BuildGoToResponse( location.filename_,
  156. location.line_number_,
  157. location.column_number_ )
  158. def _GoToDeclaration( self, request_data ):
  159. location = self._LocationForGoTo( 'GetDeclarationLocation', request_data )
  160. if not location or not location.IsValid():
  161. raise RuntimeError( 'Can\'t jump to declaration.' )
  162. return responses.BuildGoToResponse( location.filename_,
  163. location.line_number_,
  164. location.column_number_ )
  165. def _GoToDefinitionElseDeclaration( self, request_data ):
  166. location = self._LocationForGoTo( 'GetDefinitionLocation', request_data )
  167. if not location or not location.IsValid():
  168. location = self._LocationForGoTo( 'GetDeclarationLocation', request_data )
  169. if not location or not location.IsValid():
  170. raise RuntimeError( 'Can\'t jump to definition or declaration.' )
  171. return responses.BuildGoToResponse( location.filename_,
  172. location.line_number_,
  173. location.column_number_ )
  174. def _ClearCompilationFlagCache( self ):
  175. self.flags.Clear()
  176. def OnFileReadyToParse( self, request_data ):
  177. filename = request_data[ 'filepath' ]
  178. contents = request_data[ 'file_data' ][ filename ][ 'contents' ]
  179. if contents.count( '\n' ) < MIN_LINES_IN_FILE_TO_PARSE:
  180. self.parse_future = None
  181. self._logger.warning( FILE_TOO_SHORT_MESSAGE )
  182. raise ValueError( FILE_TOO_SHORT_MESSAGE )
  183. if not filename:
  184. self._logger.warning( INVALID_FILE_MESSAGE )
  185. return responses.BuildDisplayMessageResponse(
  186. INVALID_FILE_MESSAGE )
  187. if self.completer.UpdatingTranslationUnit( ToUtf8IfNeeded( filename ) ):
  188. self.extra_parse_desired = True
  189. return
  190. flags = self.flags.FlagsForFile( filename )
  191. if not flags:
  192. self.parse_future = None
  193. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  194. return responses.BuildDisplayMessageResponse(
  195. NO_COMPILE_FLAGS_MESSAGE )
  196. self.parse_future = self.completer.UpdateTranslationUnitAsync(
  197. ToUtf8IfNeeded( filename ),
  198. self.GetUnsavedFilesVector( request_data ),
  199. flags )
  200. self.extra_parse_desired = False
  201. def OnBufferUnload( self, request_data ):
  202. self.completer.DeleteCachesForFileAsync(
  203. ToUtf8IfNeeded( request_data[ 'unloaded_buffer' ] ) )
  204. def DiagnosticsForCurrentFileReady( self ):
  205. if not self.parse_future:
  206. return False
  207. return self.parse_future.ResultsReady()
  208. def GettingCompletions( self, request_data ):
  209. return self.completer.UpdatingTranslationUnit(
  210. ToUtf8IfNeeded( request_data[ 'filepath' ] ) )
  211. def GetDiagnosticsForCurrentFile( self, request_data ):
  212. filename = request_data[ 'filepath' ]
  213. if self.DiagnosticsForCurrentFileReady():
  214. diagnostics = self.completer.DiagnosticsForFile(
  215. ToUtf8IfNeeded( filename ) )
  216. self.diagnostic_store = DiagnosticsToDiagStructure( diagnostics )
  217. self.last_prepared_diagnostics = [
  218. responses.BuildDiagnosticData( x ) for x in
  219. diagnostics[ : self.max_diagnostics_to_display ] ]
  220. self.parse_future = None
  221. if self.extra_parse_desired:
  222. self.OnFileReadyToParse( request_data )
  223. return self.last_prepared_diagnostics
  224. def GetDetailedDiagnostic( self, request_data ):
  225. current_line = request_data[ 'line_num' ] + 1
  226. current_column = request_data[ 'column_num' ] + 1
  227. current_file = request_data[ 'filepath' ]
  228. if not self.diagnostic_store:
  229. return responses.BuildDisplayMessageResponse(
  230. NO_DIAGNOSTIC_MESSAGE )
  231. diagnostics = self.diagnostic_store[ current_file ][ current_line ]
  232. if not diagnostics:
  233. return responses.BuildDisplayMessageResponse(
  234. NO_DIAGNOSTIC_MESSAGE )
  235. closest_diagnostic = None
  236. distance_to_closest_diagnostic = 999
  237. for diagnostic in diagnostics:
  238. distance = abs( current_column - diagnostic.column_number_ )
  239. if distance < distance_to_closest_diagnostic:
  240. distance_to_closest_diagnostic = distance
  241. closest_diagnostic = diagnostic
  242. return responses.BuildDisplayMessageResponse(
  243. closest_diagnostic.long_formatted_text_ )
  244. def ShouldUseNow( self, request_data ):
  245. # We don't want to use the Completer API cache, we use one in the C++ code.
  246. return self.ShouldUseNowInner( request_data )
  247. def DebugInfo( self, request_data ):
  248. filename = request_data[ 'filepath' ]
  249. if not filename:
  250. return ''
  251. flags = self.flags.FlagsForFile( filename ) or []
  252. source = extra_conf_store.ModuleFileForSourceFile( filename )
  253. return responses.BuildDisplayMessageResponse(
  254. 'Flags for {0} loaded from {1}:\n{2}'.format( filename,
  255. source,
  256. list( flags ) ) )
  257. # TODO: Make this work again
  258. # def DiagnosticToDict( diagnostic ):
  259. # # see :h getqflist for a description of the dictionary fields
  260. # return {
  261. # # TODO: wrap the bufnr generation into a function
  262. # 'bufnr' : int( vim.eval( "bufnr('{0}', 1)".format(
  263. # diagnostic.filename_ ) ) ),
  264. # 'lnum' : diagnostic.line_number_,
  265. # 'col' : diagnostic.column_number_,
  266. # 'text' : diagnostic.text_,
  267. # 'type' : diagnostic.kind_,
  268. # 'valid' : 1
  269. # }
  270. def ConvertCompletionData( completion_data ):
  271. return responses.BuildCompletionData(
  272. insertion_text = completion_data.TextToInsertInBuffer(),
  273. menu_text = completion_data.MainCompletionText(),
  274. extra_menu_info = completion_data.ExtraMenuInfo(),
  275. kind = completion_data.kind_,
  276. detailed_info = completion_data.DetailedInfoForPreviewWindow() )
  277. def DiagnosticsToDiagStructure( diagnostics ):
  278. structure = defaultdict(lambda : defaultdict(list))
  279. for diagnostic in diagnostics:
  280. structure[ diagnostic.filename_ ][ diagnostic.line_number_ ].append(
  281. diagnostic )
  282. return structure
  283. def ClangAvailableForFiletypes( filetypes ):
  284. return any( [ filetype in CLANG_FILETYPES for filetype in filetypes ] )
  285. def InCFamilyFile( filetypes ):
  286. return ClangAvailableForFiletypes( filetypes )