clang_completer.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 vim
  21. import ycm_core
  22. from ycm import vimsupport
  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. class ClangCompleter( Completer ):
  28. def __init__( self, user_options ):
  29. super( ClangCompleter, self ).__init__( user_options )
  30. self.max_diagnostics_to_display = user_options[
  31. 'max_diagnostics_to_display' ]
  32. self.completer = ycm_core.ClangCompleter()
  33. self.completer.EnableThreading()
  34. self.contents_holder = []
  35. self.filename_holder = []
  36. self.last_prepared_diagnostics = []
  37. self.parse_future = None
  38. self.flags = Flags()
  39. self.diagnostic_store = None
  40. # We set this flag when a compilation request comes in while one is already
  41. # in progress. We use this to trigger the pending request after the previous
  42. # one completes (from GetDiagnosticsForCurrentFile because that's the only
  43. # method that knows when the compilation has finished).
  44. self.extra_parse_desired = False
  45. def SupportedFiletypes( self ):
  46. return CLANG_FILETYPES
  47. def GetUnsavedFilesVector( self ):
  48. # CAREFUL HERE! For UnsavedFile filename and contents we are referring
  49. # directly to Python-allocated and -managed memory since we are accepting
  50. # pointers to data members of python objects. We need to ensure that those
  51. # objects outlive our UnsavedFile objects. This is why we need the
  52. # contents_holder and filename_holder lists, to make sure the string objects
  53. # are still around when we call CandidatesForQueryAndLocationInFile. We do
  54. # this to avoid an extra copy of the entire file contents.
  55. files = ycm_core.UnsavedFileVec()
  56. self.contents_holder = []
  57. self.filename_holder = []
  58. for buffer in vimsupport.GetUnsavedBuffers():
  59. if not ClangAvailableForBuffer( buffer ):
  60. continue
  61. contents = '\n'.join( buffer )
  62. name = buffer.name
  63. if not contents or not name:
  64. continue
  65. self.contents_holder.append( contents )
  66. self.filename_holder.append( name )
  67. unsaved_file = ycm_core.UnsavedFile()
  68. unsaved_file.contents_ = self.contents_holder[ -1 ]
  69. unsaved_file.length_ = len( self.contents_holder[ -1 ] )
  70. unsaved_file.filename_ = self.filename_holder[ -1 ]
  71. files.append( unsaved_file )
  72. return files
  73. def CandidatesForQueryAsync( self, query, start_column ):
  74. filename = vim.current.buffer.name
  75. if not filename:
  76. return
  77. if self.completer.UpdatingTranslationUnit( filename ):
  78. vimsupport.PostVimMessage( 'Still parsing file, no completions yet.' )
  79. self.completions_future = None
  80. return
  81. flags = self.flags.FlagsForFile( filename )
  82. if not flags:
  83. vimsupport.PostVimMessage( 'Still no compile flags, no completions yet.' )
  84. self.completions_future = None
  85. return
  86. # TODO: sanitize query, probably in C++ code
  87. files = ycm_core.UnsavedFileVec()
  88. if not query:
  89. files = self.GetUnsavedFilesVector()
  90. line, _ = vim.current.window.cursor
  91. column = start_column + 1
  92. self.completions_future = (
  93. self.completer.CandidatesForQueryAndLocationInFileAsync(
  94. query,
  95. filename,
  96. line,
  97. column,
  98. files,
  99. flags ) )
  100. def CandidatesFromStoredRequest( self ):
  101. if not self.completions_future:
  102. return []
  103. results = [ CompletionDataToDict( x ) for x in
  104. self.completions_future.GetResults() ]
  105. if not results:
  106. vimsupport.PostVimMessage( 'No completions found; errors in the file?' )
  107. return results
  108. def DefinedSubcommands( self ):
  109. return [ 'GoToDefinition',
  110. 'GoToDeclaration',
  111. 'GoToDefinitionElseDeclaration',
  112. 'ClearCompilationFlagCache']
  113. def OnUserCommand( self, arguments ):
  114. if not arguments:
  115. self.EchoUserCommandsHelpMessage()
  116. return
  117. command = arguments[ 0 ]
  118. if command == 'GoToDefinition':
  119. self._GoToDefinition()
  120. elif command == 'GoToDeclaration':
  121. self._GoToDeclaration()
  122. elif command == 'GoToDefinitionElseDeclaration':
  123. self._GoToDefinitionElseDeclaration()
  124. elif command == 'ClearCompilationFlagCache':
  125. self._ClearCompilationFlagCache()
  126. def _LocationForGoTo( self, goto_function ):
  127. filename = vim.current.buffer.name
  128. if not filename:
  129. return None
  130. flags = self.flags.FlagsForFile( filename )
  131. if not flags:
  132. vimsupport.PostVimMessage( 'Still no compile flags, can\'t compile.' )
  133. return None
  134. files = self.GetUnsavedFilesVector()
  135. line, column = vimsupport.CurrentLineAndColumn()
  136. # Making the line & column 1-based instead of 0-based
  137. line += 1
  138. column += 1
  139. return getattr( self.completer, goto_function )(
  140. filename,
  141. line,
  142. column,
  143. files,
  144. flags )
  145. def _GoToDefinition( self ):
  146. location = self._LocationForGoTo( 'GetDefinitionLocation' )
  147. if not location or not location.IsValid():
  148. vimsupport.PostVimMessage( 'Can\'t jump to definition.' )
  149. return
  150. vimsupport.JumpToLocation( location.filename_,
  151. location.line_number_,
  152. location.column_number_ )
  153. def _GoToDeclaration( self ):
  154. location = self._LocationForGoTo( 'GetDeclarationLocation' )
  155. if not location or not location.IsValid():
  156. vimsupport.PostVimMessage( 'Can\'t jump to declaration.' )
  157. return
  158. vimsupport.JumpToLocation( location.filename_,
  159. location.line_number_,
  160. location.column_number_ )
  161. def _GoToDefinitionElseDeclaration( self ):
  162. location = self._LocationForGoTo( 'GetDefinitionLocation' )
  163. if not location or not location.IsValid():
  164. location = self._LocationForGoTo( 'GetDeclarationLocation' )
  165. if not location or not location.IsValid():
  166. vimsupport.PostVimMessage( 'Can\'t jump to definition or declaration.' )
  167. return
  168. vimsupport.JumpToLocation( location.filename_,
  169. location.line_number_,
  170. location.column_number_ )
  171. def _ClearCompilationFlagCache( self ):
  172. self.flags.Clear()
  173. def OnFileReadyToParse( self ):
  174. if vimsupport.NumLinesInBuffer( vim.current.buffer ) < 5:
  175. self.parse_future = None
  176. return
  177. filename = vim.current.buffer.name
  178. if not filename:
  179. return
  180. if self.completer.UpdatingTranslationUnit( filename ):
  181. self.extra_parse_desired = True
  182. return
  183. flags = self.flags.FlagsForFile( filename )
  184. if not flags:
  185. self.parse_future = None
  186. return
  187. self.parse_future = self.completer.UpdateTranslationUnitAsync(
  188. filename,
  189. self.GetUnsavedFilesVector(),
  190. flags )
  191. self.extra_parse_desired = False
  192. def OnBufferUnload( self, deleted_buffer_file ):
  193. self.completer.DeleteCachesForFileAsync( deleted_buffer_file )
  194. def DiagnosticsForCurrentFileReady( self ):
  195. if not self.parse_future:
  196. return False
  197. return self.parse_future.ResultsReady()
  198. def GettingCompletions( self ):
  199. return self.completer.UpdatingTranslationUnit( vim.current.buffer.name )
  200. def GetDiagnosticsForCurrentFile( self ):
  201. if self.DiagnosticsForCurrentFileReady():
  202. diagnostics = self.completer.DiagnosticsForFile( vim.current.buffer.name )
  203. self.diagnostic_store = DiagnosticsToDiagStructure( diagnostics )
  204. self.last_prepared_diagnostics = [ DiagnosticToDict( x ) for x in
  205. diagnostics[ : self.max_diagnostics_to_display ] ]
  206. self.parse_future = None
  207. if self.extra_parse_desired:
  208. self.OnFileReadyToParse()
  209. return self.last_prepared_diagnostics
  210. def ShowDetailedDiagnostic( self ):
  211. current_line, current_column = vimsupport.CurrentLineAndColumn()
  212. # CurrentLineAndColumn() numbers are 0-based, clang numbers are 1-based
  213. current_line += 1
  214. current_column += 1
  215. current_file = vim.current.buffer.name
  216. if not self.diagnostic_store:
  217. vimsupport.PostVimMessage( "No diagnostic for current line!" )
  218. return
  219. diagnostics = self.diagnostic_store[ current_file ][ current_line ]
  220. if not diagnostics:
  221. vimsupport.PostVimMessage( "No diagnostic for current line!" )
  222. return
  223. closest_diagnostic = None
  224. distance_to_closest_diagnostic = 999
  225. for diagnostic in diagnostics:
  226. distance = abs( current_column - diagnostic.column_number_ )
  227. if distance < distance_to_closest_diagnostic:
  228. distance_to_closest_diagnostic = distance
  229. closest_diagnostic = diagnostic
  230. vimsupport.EchoText( closest_diagnostic.long_formatted_text_ )
  231. def ShouldUseNow( self, start_column, current_line ):
  232. # We don't want to use the Completer API cache, we use one in the C++ code.
  233. return self.ShouldUseNowInner( start_column, current_line )
  234. def DebugInfo( self ):
  235. filename = vim.current.buffer.name
  236. if not filename:
  237. return ''
  238. flags = self.flags.FlagsForFile( filename ) or []
  239. source = extra_conf_store.ModuleFileForSourceFile( filename )
  240. return 'Flags for {0} loaded from {1}:\n{2}'.format( filename,
  241. source,
  242. list( flags ) )
  243. # TODO: make these functions module-local
  244. def CompletionDataToDict( completion_data ):
  245. # see :h complete-items for a description of the dictionary fields
  246. return {
  247. 'word' : completion_data.TextToInsertInBuffer(),
  248. 'abbr' : completion_data.MainCompletionText(),
  249. 'menu' : completion_data.ExtraMenuInfo(),
  250. 'kind' : completion_data.kind_,
  251. 'info' : completion_data.DetailedInfoForPreviewWindow(),
  252. 'dup' : 1,
  253. }
  254. def DiagnosticToDict( diagnostic ):
  255. # see :h getqflist for a description of the dictionary fields
  256. return {
  257. # TODO: wrap the bufnr generation into a function
  258. 'bufnr' : int( vim.eval( "bufnr('{0}', 1)".format(
  259. diagnostic.filename_ ) ) ),
  260. 'lnum' : diagnostic.line_number_,
  261. 'col' : diagnostic.column_number_,
  262. 'text' : diagnostic.text_,
  263. 'type' : diagnostic.kind_,
  264. 'valid' : 1
  265. }
  266. def DiagnosticsToDiagStructure( diagnostics ):
  267. structure = defaultdict(lambda : defaultdict(list))
  268. for diagnostic in diagnostics:
  269. structure[ diagnostic.filename_ ][ diagnostic.line_number_ ].append(
  270. diagnostic )
  271. return structure
  272. def ClangAvailableForBuffer( buffer_object ):
  273. filetypes = vimsupport.FiletypesForBuffer( buffer_object )
  274. return any( [ filetype in CLANG_FILETYPES for filetype in filetypes ] )
  275. def InCFamilyFile():
  276. return any( [ filetype in CLANG_FILETYPES for filetype in
  277. vimsupport.CurrentFiletypes() ] )