clang_completer.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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, PrepareFlagsForClang
  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. INVALID_FILE_MESSAGE = 'File is invalid.'
  32. NO_COMPLETIONS_MESSAGE = 'No completions found; errors in the file?'
  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._last_prepared_diagnostics = []
  44. self._flags = Flags()
  45. self._diagnostic_store = None
  46. self._logger = logging.getLogger( __name__ )
  47. def SupportedFiletypes( self ):
  48. return CLANG_FILETYPES
  49. def GetUnsavedFilesVector( self, request_data ):
  50. files = ycm_core.UnsavedFileVec()
  51. for filename, file_data in request_data[ 'file_data' ].iteritems():
  52. if not ClangAvailableForFiletypes( file_data[ 'filetypes' ] ):
  53. continue
  54. contents = file_data[ 'contents' ]
  55. if not contents or not filename:
  56. continue
  57. unsaved_file = ycm_core.UnsavedFile()
  58. utf8_contents = ToUtf8IfNeeded( contents )
  59. unsaved_file.contents_ = utf8_contents
  60. unsaved_file.length_ = len( utf8_contents )
  61. unsaved_file.filename_ = ToUtf8IfNeeded( filename )
  62. files.append( unsaved_file )
  63. return files
  64. def ComputeCandidatesInner( self, request_data ):
  65. filename = request_data[ 'filepath' ]
  66. if not filename:
  67. return
  68. if self._completer.UpdatingTranslationUnit( ToUtf8IfNeeded( filename ) ):
  69. self._logger.info( PARSING_FILE_MESSAGE )
  70. raise RuntimeError( PARSING_FILE_MESSAGE )
  71. flags = self._FlagsForRequest( request_data )
  72. if not flags:
  73. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  74. raise RuntimeError( NO_COMPILE_FLAGS_MESSAGE )
  75. files = self.GetUnsavedFilesVector( request_data )
  76. line = request_data[ 'line_num' ] + 1
  77. column = request_data[ 'start_column' ] + 1
  78. results = self._completer.CandidatesForLocationInFile(
  79. ToUtf8IfNeeded( filename ),
  80. line,
  81. column,
  82. files,
  83. flags )
  84. if not results:
  85. self._logger.warning( NO_COMPLETIONS_MESSAGE )
  86. raise RuntimeError( NO_COMPLETIONS_MESSAGE )
  87. return [ ConvertCompletionData( x ) for x in results ]
  88. def DefinedSubcommands( self ):
  89. return [ 'GoToDefinition',
  90. 'GoToDeclaration',
  91. 'GoToDefinitionElseDeclaration',
  92. 'ClearCompilationFlagCache']
  93. def OnUserCommand( self, arguments, request_data ):
  94. if not arguments:
  95. raise ValueError( self.UserCommandsHelpMessage() )
  96. command = arguments[ 0 ]
  97. if command == 'GoToDefinition':
  98. return self._GoToDefinition( request_data )
  99. elif command == 'GoToDeclaration':
  100. return self._GoToDeclaration( request_data )
  101. elif command == 'GoToDefinitionElseDeclaration':
  102. return self._GoToDefinitionElseDeclaration( request_data )
  103. elif command == 'ClearCompilationFlagCache':
  104. return self._ClearCompilationFlagCache()
  105. raise ValueError( self.UserCommandsHelpMessage() )
  106. def _LocationForGoTo( self, goto_function, request_data ):
  107. filename = request_data[ 'filepath' ]
  108. if not filename:
  109. self._logger.warning( INVALID_FILE_MESSAGE )
  110. raise ValueError( INVALID_FILE_MESSAGE )
  111. flags = self._FlagsForRequest( request_data )
  112. if not flags:
  113. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  114. raise ValueError( NO_COMPILE_FLAGS_MESSAGE )
  115. files = self.GetUnsavedFilesVector( request_data )
  116. line = request_data[ 'line_num' ] + 1
  117. column = request_data[ 'column_num' ] + 1
  118. return getattr( self._completer, goto_function )(
  119. ToUtf8IfNeeded( filename ),
  120. line,
  121. column,
  122. files,
  123. flags )
  124. def _GoToDefinition( self, request_data ):
  125. location = self._LocationForGoTo( 'GetDefinitionLocation', request_data )
  126. if not location or not location.IsValid():
  127. raise RuntimeError( 'Can\'t jump to definition.' )
  128. return responses.BuildGoToResponse( location.filename_,
  129. location.line_number_ - 1,
  130. location.column_number_ - 1)
  131. def _GoToDeclaration( self, request_data ):
  132. location = self._LocationForGoTo( 'GetDeclarationLocation', request_data )
  133. if not location or not location.IsValid():
  134. raise RuntimeError( 'Can\'t jump to declaration.' )
  135. return responses.BuildGoToResponse( location.filename_,
  136. location.line_number_ - 1,
  137. location.column_number_ - 1)
  138. def _GoToDefinitionElseDeclaration( self, request_data ):
  139. location = self._LocationForGoTo( 'GetDefinitionLocation', request_data )
  140. if not location or not location.IsValid():
  141. location = self._LocationForGoTo( 'GetDeclarationLocation', request_data )
  142. if not location or not location.IsValid():
  143. raise RuntimeError( 'Can\'t jump to definition or declaration.' )
  144. return responses.BuildGoToResponse( location.filename_,
  145. location.line_number_ - 1,
  146. location.column_number_ - 1)
  147. def _ClearCompilationFlagCache( self ):
  148. self._flags.Clear()
  149. def OnFileReadyToParse( self, request_data ):
  150. filename = request_data[ 'filepath' ]
  151. contents = request_data[ 'file_data' ][ filename ][ 'contents' ]
  152. if contents.count( '\n' ) < MIN_LINES_IN_FILE_TO_PARSE:
  153. self._logger.warning( FILE_TOO_SHORT_MESSAGE )
  154. raise ValueError( FILE_TOO_SHORT_MESSAGE )
  155. if not filename:
  156. self._logger.warning( INVALID_FILE_MESSAGE )
  157. raise ValueError( INVALID_FILE_MESSAGE )
  158. flags = self._FlagsForRequest( request_data )
  159. if not flags:
  160. self._logger.info( NO_COMPILE_FLAGS_MESSAGE )
  161. raise ValueError( NO_COMPILE_FLAGS_MESSAGE )
  162. self._completer.UpdateTranslationUnit(
  163. ToUtf8IfNeeded( filename ),
  164. self.GetUnsavedFilesVector( request_data ),
  165. flags )
  166. def OnBufferUnload( self, request_data ):
  167. self._completer.DeleteCachesForFile(
  168. ToUtf8IfNeeded( request_data[ 'unloaded_buffer' ] ) )
  169. def DiagnosticsForCurrentFileReady( self ):
  170. # if not self.parse_future:
  171. # return False
  172. # return self.parse_future.ResultsReady()
  173. pass
  174. def GettingCompletions( self, request_data ):
  175. return self._completer.UpdatingTranslationUnit(
  176. ToUtf8IfNeeded( request_data[ 'filepath' ] ) )
  177. def GetDiagnosticsForCurrentFile( self, request_data ):
  178. filename = request_data[ 'filepath' ]
  179. if self.DiagnosticsForCurrentFileReady():
  180. diagnostics = self._completer.DiagnosticsForFile(
  181. ToUtf8IfNeeded( filename ) )
  182. self._diagnostic_store = DiagnosticsToDiagStructure( diagnostics )
  183. self._last_prepared_diagnostics = [
  184. responses.BuildDiagnosticData( x ) for x in
  185. diagnostics[ : self._max_diagnostics_to_display ] ]
  186. # self.parse_future = None
  187. # if self.extra_parse_desired:
  188. # self.OnFileReadyToParse( request_data )
  189. return self._last_prepared_diagnostics
  190. def GetDetailedDiagnostic( self, request_data ):
  191. current_line = request_data[ 'line_num' ] + 1
  192. current_column = request_data[ 'column_num' ] + 1
  193. current_file = request_data[ 'filepath' ]
  194. if not self._diagnostic_store:
  195. return responses.BuildDisplayMessageResponse(
  196. NO_DIAGNOSTIC_MESSAGE )
  197. diagnostics = self._diagnostic_store[ current_file ][ current_line ]
  198. if not diagnostics:
  199. return responses.BuildDisplayMessageResponse(
  200. NO_DIAGNOSTIC_MESSAGE )
  201. closest_diagnostic = None
  202. distance_to_closest_diagnostic = 999
  203. for diagnostic in diagnostics:
  204. distance = abs( current_column - diagnostic.column_number_ )
  205. if distance < distance_to_closest_diagnostic:
  206. distance_to_closest_diagnostic = distance
  207. closest_diagnostic = diagnostic
  208. return responses.BuildDisplayMessageResponse(
  209. closest_diagnostic.long_formatted_text_ )
  210. def DebugInfo( self, request_data ):
  211. filename = request_data[ 'filepath' ]
  212. if not filename:
  213. return ''
  214. flags = self._FlagsForRequest( request_data ) or []
  215. source = extra_conf_store.ModuleFileForSourceFile( filename )
  216. return 'Flags for {0} loaded from {1}:\n{2}'.format( filename,
  217. source,
  218. list( flags ) )
  219. def _FlagsForRequest( self, request_data ):
  220. filename = request_data[ 'filepath' ]
  221. if 'compilation_flags' in request_data:
  222. return PrepareFlagsForClang( request_data[ 'compilation_flags' ],
  223. filename )
  224. return self._flags.FlagsForFile( filename )
  225. # TODO: Make this work again
  226. # def DiagnosticToDict( diagnostic ):
  227. # # see :h getqflist for a description of the dictionary fields
  228. # return {
  229. # # TODO: wrap the bufnr generation into a function
  230. # 'bufnr' : int( vim.eval( "bufnr('{0}', 1)".format(
  231. # diagnostic.filename_ ) ) ),
  232. # 'lnum' : diagnostic.line_number_,
  233. # 'col' : diagnostic.column_number_,
  234. # 'text' : diagnostic.text_,
  235. # 'type' : diagnostic.kind_,
  236. # 'valid' : 1
  237. # }
  238. def ConvertCompletionData( completion_data ):
  239. return responses.BuildCompletionData(
  240. insertion_text = completion_data.TextToInsertInBuffer(),
  241. menu_text = completion_data.MainCompletionText(),
  242. extra_menu_info = completion_data.ExtraMenuInfo(),
  243. kind = completion_data.kind_,
  244. detailed_info = completion_data.DetailedInfoForPreviewWindow() )
  245. def DiagnosticsToDiagStructure( diagnostics ):
  246. structure = defaultdict(lambda : defaultdict(list))
  247. for diagnostic in diagnostics:
  248. structure[ diagnostic.filename_ ][ diagnostic.line_number_ ].append(
  249. diagnostic )
  250. return structure
  251. def ClangAvailableForFiletypes( filetypes ):
  252. return any( [ filetype in CLANG_FILETYPES for filetype in filetypes ] )
  253. def InCFamilyFile( filetypes ):
  254. return ClangAvailableForFiletypes( filetypes )