clang_completer.py 11 KB

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