1#!/usr/bin/env vpython3 2 3# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. 4# 5# Use of this source code is governed by a BSD-style license 6# that can be found in the LICENSE file in the root of the source 7# tree. An additional intellectual property rights grant can be found 8# in the file PATENTS. All contributing project authors may 9# be found in the AUTHORS file in the root of the source tree. 10 11# Autocompletion config for YouCompleteMe in WebRTC. This is just copied from 12# tools/vim in chromium with very minor modifications. 13# 14# USAGE: 15# 16# 1. Install YCM [https://github.com/Valloric/YouCompleteMe] 17# (Googlers should check out [go/ycm]) 18# 19# 2. Create a symbolic link to this file called .ycm_extra_conf.py in the 20# directory above your WebRTC checkout (i.e. next to your .gclient file). 21# 22# cd src 23# ln -rs tools_webrtc/vim/webrtc.ycm_extra_conf.py \ 24# ../.ycm_extra_conf.py 25# 26# 3. (optional) Whitelist the .ycm_extra_conf.py from step #2 by adding the 27# following to your .vimrc: 28# 29# let g:ycm_extra_conf_globlist=['<path to .ycm_extra_conf.py>'] 30# 31# You can also add other .ycm_extra_conf.py files you want to use to this 32# list to prevent excessive prompting each time you visit a directory 33# covered by a config file. 34# 35# 4. Profit 36# 37# 38# Usage notes: 39# 40# * You must use ninja & clang to build WebRTC. 41# 42# * You must have run "gn gen" and built WebRTC recently. 43# 44# 45# Hacking notes: 46# 47# * The purpose of this script is to construct an accurate enough command line 48# for YCM to pass to clang so it can build and extract the symbols. 49# 50# * Right now, we only pull the -I and -D flags. That seems to be sufficient 51# for everything I've used it for. 52# 53# * That whole ninja & clang thing? We could support other configs if someone 54# were willing to write the correct commands and a parser. 55# 56# * This has only been tested on gPrecise. 57 58import os 59import os.path 60import shlex 61import subprocess 62import sys 63 64# Flags from YCM's default config. 65_DEFAULT_FLAGS = [ 66 '-DUSE_CLANG_COMPLETER', 67 '-std=c++11', 68 '-x', 69 'c++', 70] 71 72_HEADER_ALTERNATES = ('.cc', '.cpp', '.c', '.mm', '.m') 73 74_EXTENSION_FLAGS = { 75 '.m': ['-x', 'objective-c'], 76 '.mm': ['-x', 'objective-c++'], 77} 78 79 80def FindWebrtcSrcFromFilename(filename): 81 """Searches for the root of the WebRTC checkout. 82 83 Simply checks parent directories until it finds .gclient and src/. 84 85 Args: 86 filename: (String) Path to source file being edited. 87 88 Returns: 89 (String) Path of 'src/', or None if unable to find. 90 """ 91 curdir = os.path.normpath(os.path.dirname(filename)) 92 while not (os.path.basename(curdir) == 'src' 93 and os.path.exists(os.path.join(curdir, 'DEPS')) and 94 (os.path.exists(os.path.join(curdir, '..', '.gclient')) 95 or os.path.exists(os.path.join(curdir, '.git')))): 96 nextdir = os.path.normpath(os.path.join(curdir, '..')) 97 if nextdir == curdir: 98 return None 99 curdir = nextdir 100 return curdir 101 102 103def GetDefaultSourceFile(webrtc_root, filename): 104 """Returns the default source file to use as an alternative to `filename`. 105 106 Compile flags used to build the default source file is assumed to be a 107 close-enough approximation for building `filename`. 108 109 Args: 110 webrtc_root: (String) Absolute path to the root of WebRTC checkout. 111 filename: (String) Absolute path to the source file. 112 113 Returns: 114 (String) Absolute path to substitute source file. 115 """ 116 if 'test.' in filename: 117 return os.path.join(webrtc_root, 'base', 'logging_unittest.cc') 118 return os.path.join(webrtc_root, 'base', 'logging.cc') 119 120 121def GetNinjaBuildOutputsForSourceFile(out_dir, filename): 122 """Returns a list of build outputs for filename. 123 124 The list is generated by invoking 'ninja -t query' tool to retrieve a list of 125 inputs and outputs of `filename`. This list is then filtered to only include 126 .o and .obj outputs. 127 128 Args: 129 out_dir: (String) Absolute path to ninja build output directory. 130 filename: (String) Absolute path to source file. 131 132 Returns: 133 (List of Strings) List of target names. Will return [] if `filename` doesn't 134 yield any .o or .obj outputs. 135 """ 136 # Ninja needs the path to the source file relative to the output build 137 # directory. 138 rel_filename = os.path.relpath(filename, out_dir) 139 140 p = subprocess.Popen(['ninja', '-C', out_dir, '-t', 'query', rel_filename], 141 stdout=subprocess.PIPE, 142 stderr=subprocess.STDOUT, 143 universal_newlines=True) 144 stdout, _ = p.communicate() 145 if p.returncode != 0: 146 return [] 147 148 # The output looks like: 149 # ../../relative/path/to/source.cc: 150 # outputs: 151 # obj/reative/path/to/target.source.o 152 # obj/some/other/target2.source.o 153 # another/target.txt 154 # 155 outputs_text = stdout.partition('\n outputs:\n')[2] 156 output_lines = [line.strip() for line in outputs_text.split('\n')] 157 return [ 158 target for target in output_lines 159 if target and (target.endswith('.o') or target.endswith('.obj')) 160 ] 161 162 163def GetClangCommandLineForNinjaOutput(out_dir, build_target): 164 """Returns the Clang command line for building `build_target` 165 166 Asks ninja for the list of commands used to build `filename` and returns the 167 final Clang invocation. 168 169 Args: 170 out_dir: (String) Absolute path to ninja build output directory. 171 build_target: (String) A build target understood by ninja 172 173 Returns: 174 (String or None) Clang command line or None if a Clang command line couldn't 175 be determined. 176 """ 177 p = subprocess.Popen( 178 ['ninja', '-v', '-C', out_dir, '-t', 'commands', build_target], 179 stdout=subprocess.PIPE, 180 universal_newlines=True) 181 stdout, _ = p.communicate() 182 if p.returncode != 0: 183 return None 184 185 # Ninja will return multiple build steps for all dependencies up to 186 # `build_target`. The build step we want is the last Clang invocation, which 187 # is expected to be the one that outputs `build_target`. 188 for line in reversed(stdout.split('\n')): 189 if 'clang' in line: 190 return line 191 return None 192 193 194def GetClangCommandLineFromNinjaForSource(out_dir, filename): 195 """Returns a Clang command line used to build `filename`. 196 197 The same source file could be built multiple times using different tool 198 chains. In such cases, this command returns the first Clang invocation. We 199 currently don't prefer one toolchain over another. Hopefully the tool chain 200 corresponding to the Clang command line is compatible with the Clang build 201 used by YCM. 202 203 Args: 204 out_dir: (String) Absolute path to WebRTC checkout. 205 filename: (String) Absolute path to source file. 206 207 Returns: 208 (String or None): Command line for Clang invocation using `filename` as a 209 source. Returns None if no such command line could be found. 210 """ 211 build_targets = GetNinjaBuildOutputsForSourceFile(out_dir, filename) 212 for build_target in build_targets: 213 command_line = GetClangCommandLineForNinjaOutput(out_dir, build_target) 214 if command_line: 215 return command_line 216 return None 217 218 219def GetClangOptionsFromCommandLine(clang_commandline, out_dir, 220 additional_flags): 221 """Extracts relevant command line options from `clang_commandline` 222 223 Args: 224 clang_commandline: (String) Full Clang invocation. 225 out_dir: (String) Absolute path to ninja build directory. Relative paths in 226 the command line are relative to `out_dir`. 227 additional_flags: (List of String) Additional flags to return. 228 229 Returns: 230 (List of Strings) The list of command line flags for this source file. Can 231 be empty. 232 """ 233 clang_flags = [] + additional_flags 234 235 # Parse flags that are important for YCM's purposes. 236 clang_tokens = shlex.split(clang_commandline) 237 for flag_index, flag in enumerate(clang_tokens): 238 if flag.startswith('-I'): 239 # Relative paths need to be resolved, because they're relative to 240 # the output dir, not the source. 241 if flag[2] == '/': 242 clang_flags.append(flag) 243 else: 244 abs_path = os.path.normpath(os.path.join(out_dir, flag[2:])) 245 clang_flags.append('-I' + abs_path) 246 elif flag.startswith('-std'): 247 clang_flags.append(flag) 248 elif flag.startswith('-') and flag[1] in 'DWFfmO': 249 if flag in ['-Wno-deprecated-register', '-Wno-header-guard']: 250 # These flags causes libclang (3.3) to crash. Remove it until 251 # things are fixed. 252 continue 253 clang_flags.append(flag) 254 elif flag == '-isysroot': 255 # On Mac -isysroot <path> is used to find the system headers. 256 # Copy over both flags. 257 if flag_index + 1 < len(clang_tokens): 258 clang_flags.append(flag) 259 clang_flags.append(clang_tokens[flag_index + 1]) 260 elif flag.startswith('--sysroot='): 261 # On Linux we use a sysroot image. 262 sysroot_path = flag.lstrip('--sysroot=') 263 if sysroot_path.startswith('/'): 264 clang_flags.append(flag) 265 else: 266 abs_path = os.path.normpath(os.path.join(out_dir, sysroot_path)) 267 clang_flags.append('--sysroot=' + abs_path) 268 return clang_flags 269 270 271def GetClangOptionsFromNinjaForFilename(webrtc_root, filename): 272 """Returns the Clang command line options needed for building `filename`. 273 274 Command line options are based on the command used by ninja for building 275 `filename`. If `filename` is a .h file, uses its companion .cc or .cpp file. 276 If a suitable companion file can't be located or if ninja doesn't know about 277 `filename`, then uses default source files in WebRTC for determining the 278 commandline. 279 280 Args: 281 webrtc_root: (String) Path to src/. 282 filename: (String) Absolute path to source file being edited. 283 284 Returns: 285 (List of Strings) The list of command line flags for this source file. Can 286 be empty. 287 """ 288 if not webrtc_root: 289 return [] 290 291 # Generally, everyone benefits from including WebRTC's src/, because all of 292 # WebRTC's includes are relative to that. 293 additional_flags = ['-I' + os.path.join(webrtc_root)] 294 295 # Version of Clang used to compile WebRTC can be newer then version of 296 # libclang that YCM uses for completion. So it's possible that YCM's 297 # libclang doesn't know about some used warning options, which causes 298 # compilation warnings (and errors, because of '-Werror'); 299 additional_flags.append('-Wno-unknown-warning-option') 300 301 sys.path.append(os.path.join(webrtc_root, 'tools', 'vim')) 302 from ninja_output import GetNinjaOutputDirectory 303 out_dir = GetNinjaOutputDirectory(webrtc_root) 304 305 basename, extension = os.path.splitext(filename) 306 if extension == '.h': 307 candidates = [basename + ext for ext in _HEADER_ALTERNATES] 308 else: 309 candidates = [filename] 310 311 clang_line = None 312 buildable_extension = extension 313 for candidate in candidates: 314 clang_line = GetClangCommandLineFromNinjaForSource(out_dir, candidate) 315 if clang_line: 316 buildable_extension = os.path.splitext(candidate)[1] 317 break 318 319 additional_flags += _EXTENSION_FLAGS.get(buildable_extension, []) 320 321 if not clang_line: 322 # If ninja didn't know about filename or it's companion files, then try 323 # a default build target. It is possible that the file is new, or 324 # build.ninja is stale. 325 clang_line = GetClangCommandLineFromNinjaForSource( 326 out_dir, GetDefaultSourceFile(webrtc_root, filename)) 327 328 if not clang_line: 329 return additional_flags 330 331 return GetClangOptionsFromCommandLine(clang_line, out_dir, additional_flags) 332 333 334def FlagsForFile(filename): 335 """This is the main entry point for YCM. Its interface is fixed. 336 337 Args: 338 filename: (String) Path to source file being edited. 339 340 Returns: 341 (Dictionary) 342 'flags': (List of Strings) Command line flags. 343 'do_cache': (Boolean) True if the result should be cached. 344 """ 345 abs_filename = os.path.abspath(filename) 346 webrtc_root = FindWebrtcSrcFromFilename(abs_filename) 347 clang_flags = GetClangOptionsFromNinjaForFilename(webrtc_root, abs_filename) 348 349 # If clang_flags could not be determined, then assume that was due to a 350 # transient failure. Preventing YCM from caching the flags allows us to 351 # try to determine the flags again. 352 should_cache_flags_for_file = bool(clang_flags) 353 354 final_flags = _DEFAULT_FLAGS + clang_flags 355 356 return {'flags': final_flags, 'do_cache': should_cache_flags_for_file} 357