flags.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. import ycm_core
  20. import os
  21. from ycm import extra_conf_store
  22. from ycm.utils import ToUtf8IfNeeded
  23. NO_EXTRA_CONF_FILENAME_MESSAGE = ( 'No {0} file detected, so no compile flags '
  24. 'are available. Thus no semantic support for C/C++/ObjC/ObjC++. Go READ THE '
  25. 'DOCS *NOW*, DON\'T file a bug report.' ).format(
  26. extra_conf_store.YCM_EXTRA_CONF_FILENAME )
  27. class Flags( object ):
  28. """Keeps track of the flags necessary to compile a file.
  29. The flags are loaded from user-created python files (hereafter referred to as
  30. 'modules') that contain a method FlagsForFile( filename )."""
  31. def __init__( self ):
  32. # It's caches all the way down...
  33. self.flags_for_file = {}
  34. self.special_clang_flags = _SpecialClangIncludes()
  35. def FlagsForFile( self, filename, add_special_clang_flags = True ):
  36. try:
  37. return self.flags_for_file[ filename ]
  38. except KeyError:
  39. module = extra_conf_store.ModuleForSourceFile( filename )
  40. if not module:
  41. raise RuntimeError( NO_EXTRA_CONF_FILENAME_MESSAGE )
  42. results = module.FlagsForFile( filename )
  43. if not results.get( 'flags_ready', True ):
  44. return None
  45. flags = list( results[ 'flags' ] )
  46. if add_special_clang_flags:
  47. flags += self.special_clang_flags
  48. sanitized_flags = PrepareFlagsForClang( flags, filename )
  49. if results[ 'do_cache' ]:
  50. self.flags_for_file[ filename ] = sanitized_flags
  51. return sanitized_flags
  52. def UserIncludePaths( self, filename ):
  53. flags = self.FlagsForFile( filename, False )
  54. if not flags:
  55. return []
  56. include_paths = []
  57. path_flags = [ '-isystem', '-I', '-iquote' ]
  58. next_flag_is_include_path = False
  59. for flag in flags:
  60. if next_flag_is_include_path:
  61. next_flag_is_include_path = False
  62. include_paths.append( flag )
  63. for path_flag in path_flags:
  64. if flag == path_flag:
  65. next_flag_is_include_path = True
  66. break
  67. if flag.startswith( path_flag ):
  68. path = flag[ len( path_flag ): ]
  69. include_paths.append( path )
  70. return [ x for x in include_paths if x ]
  71. def Clear( self ):
  72. self.flags_for_file.clear()
  73. def PrepareFlagsForClang( flags, filename ):
  74. flags = _RemoveUnusedFlags( flags, filename )
  75. flags = _SanitizeFlags( flags )
  76. return flags
  77. def _SanitizeFlags( flags ):
  78. """Drops unsafe flags. Currently these are only -arch flags; they tend to
  79. crash libclang."""
  80. sanitized_flags = []
  81. saw_arch = False
  82. for i, flag in enumerate( flags ):
  83. if flag == '-arch':
  84. saw_arch = True
  85. continue
  86. elif flag.startswith( '-arch' ):
  87. continue
  88. elif saw_arch:
  89. saw_arch = False
  90. continue
  91. sanitized_flags.append( flag )
  92. vector = ycm_core.StringVec()
  93. for flag in sanitized_flags:
  94. vector.append( ToUtf8IfNeeded( flag ) )
  95. return vector
  96. def _RemoveUnusedFlags( flags, filename ):
  97. """Given an iterable object that produces strings (flags for Clang), removes
  98. the '-c' and '-o' options that Clang does not like to see when it's producing
  99. completions for a file. Also removes the first flag in the list if it does not
  100. start with a '-' (it's highly likely to be the compiler name/path)."""
  101. new_flags = []
  102. # When flags come from the compile_commands.json file, the first flag is
  103. # usually the path to the compiler that should be invoked. We want to strip
  104. # that.
  105. if not flags[ 0 ].startswith( '-' ):
  106. flags = flags[ 1: ]
  107. skip = False
  108. for flag in flags:
  109. if skip:
  110. skip = False
  111. continue
  112. if flag == '-c':
  113. continue
  114. if flag == '-o':
  115. skip = True;
  116. continue
  117. if flag == filename or os.path.realpath( flag ) == filename:
  118. continue
  119. new_flags.append( flag )
  120. return new_flags
  121. def _SpecialClangIncludes():
  122. libclang_dir = os.path.dirname( ycm_core.__file__ )
  123. path_to_includes = os.path.join( libclang_dir, 'clang_includes' )
  124. return [ '-I', path_to_includes ]