clang_completer.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 import server_responses
  23. from ycm import extra_conf_store
  24. from ycm.completers.completer import Completer
  25. from ycm.completers.cpp.flags import Flags
  26. CLANG_FILETYPES = set( [ 'c', 'cpp', 'objc', 'objcpp' ] )
  27. MIN_LINES_IN_FILE_TO_PARSE = 5
  28. PARSING_FILE_MESSAGE = 'Still parsing file, no completions yet.'
  29. NO_COMPILE_FLAGS_MESSAGE = 'Still no compile flags, no completions yet.'
  30. NO_COMPLETIONS_MESSAGE = 'No completions found; errors in the file?'
  31. INVALID_FILE_MESSAGE = 'File is invalid.'
  32. FILE_TOO_SHORT_MESSAGE = (
  33. 'File is less than {} lines long; not compiling.'.format(
  34. MIN_LINES_IN_FILE_TO_PARSE ) )
  35. NO_DIAGNOSTIC_MESSAGE = 'No diagnostic for current line!'
  36. class ClangCompleter( Completer ):
  37. def __init__( self, user_options ):
  38. super( ClangCompleter, self ).__init__( user_options )
  39. self.max_diagnostics_to_display = user_options[
  40. 'max_diagnostics_to_display' ]
  41. self.completer = ycm_core.ClangCompleter()
  42. self.completer.EnableThreading()
  43. self.last_prepared_diagnostics = []
  44. self.parse_future = None
  45. self.flags = Flags()
  46. self.diagnostic_store = None
  47. self._logger = logging.getLogger( __name__ )
  48. # We set this flag when a compilation request comes in while one is already
  49. # in progress. We use this to trigger the pending request after the previous
  50. # one completes (from GetDiagnosticsForCurrentFile because that's the only
  51. # method that knows when the compilation has finished).
  52. self.extra_parse_desired = False
  53. def SupportedFiletypes( self ):
  54. return CLANG_FILETYPES
  55. def GetUnsavedFilesVector( self, request_data ):
  56. files = ycm_core.UnsavedFileVec()
  57. for filename, file_data in request_data[ 'file_data' ].iteritems():
  58. if not ClangAvailableForFiletypes( file_data[ 'filetypes' ] ):
  59. continue
  60. contents = file_data[ 'contents' ]
  61. if not contents or not filename:
  62. continue
  63. unsaved_file = ycm_core.UnsavedFile()
  64. unsaved_file.contents_ = contents
  65. unsaved_file.length_ = len( contents )
  66. unsaved_file.filename_ = filename
  67. files.append( unsaved_file )
  68. return files
  69. def CandidatesForQueryAsync( self, request_data ):
  70. filename = request_data[ 'filepath' ]
  71. if not filename:
  72. return
  73. if self.completer.UpdatingTranslationUnit( filename ):
  74. self.completions_future = None
  75. self._logger.info( PARSING_FILE_MESSAGE )
  76. return server_responses.BuildDisplayMessageResponse(
  77. PARSING_FILE_MESSAGE )
  78. flags = self.flags.FlagsForFile( filename )
  79. if not flags:
  80. self.completions_future = None
  81. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  82. return server_responses.BuildDisplayMessageResponse(
  83. NO_COMPILE_FLAGS_MESSAGE )
  84. # TODO: sanitize query, probably in C++ code
  85. files = ycm_core.UnsavedFileVec()
  86. query = request_data[ 'query' ]
  87. if not query:
  88. files = self.GetUnsavedFilesVector( request_data )
  89. line = request_data[ 'line_num' ] + 1
  90. column = request_data[ 'start_column' ] + 1
  91. self.completions_future = (
  92. self.completer.CandidatesForQueryAndLocationInFileAsync(
  93. query,
  94. filename,
  95. line,
  96. column,
  97. files,
  98. flags ) )
  99. def CandidatesFromStoredRequest( self ):
  100. if not self.completions_future:
  101. return []
  102. results = [ ConvertCompletionData( x ) for x in
  103. self.completions_future.GetResults() ]
  104. if not results:
  105. self._logger.warning( NO_COMPLETIONS_MESSAGE )
  106. raise RuntimeError( NO_COMPLETIONS_MESSAGE )
  107. return results
  108. def DefinedSubcommands( self ):
  109. return [ 'GoToDefinition',
  110. 'GoToDeclaration',
  111. 'GoToDefinitionElseDeclaration',
  112. 'ClearCompilationFlagCache']
  113. def OnUserCommand( self, arguments, request_data ):
  114. if not arguments:
  115. raise ValueError( self.UserCommandsHelpMessage() )
  116. command = arguments[ 0 ]
  117. if command == 'GoToDefinition':
  118. self._GoToDefinition( request_data )
  119. elif command == 'GoToDeclaration':
  120. self._GoToDeclaration( request_data )
  121. elif command == 'GoToDefinitionElseDeclaration':
  122. self._GoToDefinitionElseDeclaration( request_data )
  123. elif command == 'ClearCompilationFlagCache':
  124. self._ClearCompilationFlagCache( request_data )
  125. def _LocationForGoTo( self, goto_function, request_data ):
  126. filename = request_data[ 'filepath' ]
  127. if not filename:
  128. self._logger.warning( INVALID_FILE_MESSAGE )
  129. return server_responses.BuildDisplayMessageResponse(
  130. INVALID_FILE_MESSAGE )
  131. flags = self.flags.FlagsForFile( filename )
  132. if not flags:
  133. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  134. return server_responses.BuildDisplayMessageResponse(
  135. NO_COMPILE_FLAGS_MESSAGE )
  136. files = self.GetUnsavedFilesVector()
  137. line = request_data[ 'line_num' ] + 1
  138. column = request_data[ 'start_column' ] + 1
  139. return getattr( self.completer, goto_function )(
  140. filename,
  141. line,
  142. column,
  143. files,
  144. flags )
  145. def _GoToDefinition( self, request_data ):
  146. location = self._LocationForGoTo( 'GetDefinitionLocation' )
  147. if not location or not location.IsValid():
  148. raise RuntimeError( 'Can\'t jump to definition.' )
  149. return server_responses.BuildGoToResponse( location.filename_,
  150. location.line_number_,
  151. location.column_number_ )
  152. def _GoToDeclaration( self, request_data ):
  153. location = self._LocationForGoTo( 'GetDeclarationLocation' )
  154. if not location or not location.IsValid():
  155. raise RuntimeError( 'Can\'t jump to declaration.' )
  156. return server_responses.BuildGoToResponse( location.filename_,
  157. location.line_number_,
  158. location.column_number_ )
  159. def _GoToDefinitionElseDeclaration( self, request_data ):
  160. location = self._LocationForGoTo( 'GetDefinitionLocation' )
  161. if not location or not location.IsValid():
  162. location = self._LocationForGoTo( 'GetDeclarationLocation' )
  163. if not location or not location.IsValid():
  164. raise RuntimeError( 'Can\'t jump to definition or declaration.' )
  165. return server_responses.BuildGoToResponse( location.filename_,
  166. location.line_number_,
  167. location.column_number_ )
  168. def _ClearCompilationFlagCache( self ):
  169. self.flags.Clear()
  170. def OnFileReadyToParse( self, request_data ):
  171. filename = request_data[ 'filepath' ]
  172. contents = request_data[ 'file_data' ][ filename ][ 'contents' ]
  173. if contents.count( '\n' ) < MIN_LINES_IN_FILE_TO_PARSE:
  174. self.parse_future = None
  175. self._logger.warning( FILE_TOO_SHORT_MESSAGE )
  176. raise ValueError( FILE_TOO_SHORT_MESSAGE )
  177. if not filename:
  178. self._logger.warning( INVALID_FILE_MESSAGE )
  179. return server_responses.BuildDisplayMessageResponse(
  180. INVALID_FILE_MESSAGE )
  181. if self.completer.UpdatingTranslationUnit( filename ):
  182. self.extra_parse_desired = True
  183. return
  184. flags = self.flags.FlagsForFile( filename )
  185. if not flags:
  186. self.parse_future = None
  187. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  188. return server_responses.BuildDisplayMessageResponse(
  189. NO_COMPILE_FLAGS_MESSAGE )
  190. self.parse_future = self.completer.UpdateTranslationUnitAsync(
  191. filename,
  192. self.GetUnsavedFilesVector( request_data ),
  193. flags )
  194. self.extra_parse_desired = False
  195. def OnBufferUnload( self, deleted_buffer_file ):
  196. self.completer.DeleteCachesForFileAsync( deleted_buffer_file )
  197. def DiagnosticsForCurrentFileReady( self ):
  198. if not self.parse_future:
  199. return False
  200. return self.parse_future.ResultsReady()
  201. def GettingCompletions( self, request_data ):
  202. return self.completer.UpdatingTranslationUnit( request_data[ 'filepath' ] )
  203. def GetDiagnosticsForCurrentFile( self, request_data ):
  204. filename = request_data[ 'filepath' ]
  205. if self.DiagnosticsForCurrentFileReady():
  206. diagnostics = self.completer.DiagnosticsForFile( filename )
  207. self.diagnostic_store = DiagnosticsToDiagStructure( diagnostics )
  208. self.last_prepared_diagnostics = [
  209. server_responses.BuildDiagnosticData( x ) for x in
  210. diagnostics[ : self.max_diagnostics_to_display ] ]
  211. self.parse_future = None
  212. if self.extra_parse_desired:
  213. self.OnFileReadyToParse()
  214. return self.last_prepared_diagnostics
  215. def GetDetailedDiagnostic( self, request_data ):
  216. current_line = request_data[ 'line_num' ] + 1
  217. current_column = request_data[ 'column_num' ] + 1
  218. current_file = request_data[ 'filepath' ]
  219. if not self.diagnostic_store:
  220. return server_responses.BuildDisplayMessageResponse(
  221. NO_DIAGNOSTIC_MESSAGE )
  222. diagnostics = self.diagnostic_store[ current_file ][ current_line ]
  223. if not diagnostics:
  224. return server_responses.BuildDisplayMessageResponse(
  225. NO_DIAGNOSTIC_MESSAGE )
  226. closest_diagnostic = None
  227. distance_to_closest_diagnostic = 999
  228. for diagnostic in diagnostics:
  229. distance = abs( current_column - diagnostic.column_number_ )
  230. if distance < distance_to_closest_diagnostic:
  231. distance_to_closest_diagnostic = distance
  232. closest_diagnostic = diagnostic
  233. return server_responses.BuildDisplayMessageResponse(
  234. closest_diagnostic.long_formatted_text_ )
  235. def ShouldUseNow( self, request_data ):
  236. # We don't want to use the Completer API cache, we use one in the C++ code.
  237. return self.ShouldUseNowInner( request_data )
  238. def DebugInfo( self, request_data ):
  239. filename = request_data[ 'filepath' ]
  240. if not filename:
  241. return ''
  242. flags = self.flags.FlagsForFile( filename ) or []
  243. source = extra_conf_store.ModuleFileForSourceFile( filename )
  244. return server_responses.BuildDisplayMessageResponse(
  245. 'Flags for {0} loaded from {1}:\n{2}'.format( filename,
  246. source,
  247. list( flags ) ) )
  248. # TODO: make these functions module-local
  249. # def CompletionDataToDict( completion_data ):
  250. # # see :h complete-items for a description of the dictionary fields
  251. # return {
  252. # 'word' : completion_data.TextToInsertInBuffer(),
  253. # 'abbr' : completion_data.MainCompletionText(),
  254. # 'menu' : completion_data.ExtraMenuInfo(),
  255. # 'kind' : completion_data.kind_,
  256. # 'info' : completion_data.DetailedInfoForPreviewWindow(),
  257. # 'dup' : 1,
  258. # }
  259. # def DiagnosticToDict( diagnostic ):
  260. # # see :h getqflist for a description of the dictionary fields
  261. # return {
  262. # # TODO: wrap the bufnr generation into a function
  263. # 'bufnr' : int( vim.eval( "bufnr('{0}', 1)".format(
  264. # diagnostic.filename_ ) ) ),
  265. # 'lnum' : diagnostic.line_number_,
  266. # 'col' : diagnostic.column_number_,
  267. # 'text' : diagnostic.text_,
  268. # 'type' : diagnostic.kind_,
  269. # 'valid' : 1
  270. # }
  271. def ConvertCompletionData( completion_data ):
  272. return server_responses.BuildCompletionData(
  273. insertion_text = completion_data.TextToInsertInBuffer(),
  274. menu_text = completion_data.MainCompletionText(),
  275. extra_menu_info = completion_data.ExtraMenuInfo(),
  276. kind = completion_data.kind_,
  277. detailed_info = completion_data.DetailedInfoForPreviewWindow() )
  278. def DiagnosticsToDiagStructure( diagnostics ):
  279. structure = defaultdict(lambda : defaultdict(list))
  280. for diagnostic in diagnostics:
  281. structure[ diagnostic.filename_ ][ diagnostic.line_number_ ].append(
  282. diagnostic )
  283. return structure
  284. def ClangAvailableForFiletypes( filetypes ):
  285. return any( [ filetype in CLANG_FILETYPES for filetype in filetypes ] )
  286. def InCFamilyFile( filetypes ):
  287. return ClangAvailableForFiletypes( filetypes )