flags.py 4.6 KB

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