blob: d11f79ae249e14dbd8bee7ea8d3fadaf9978d6c3 [file] [log] [blame]
Christoffer Jansson4e8a7732022-02-08 09:01:12 +01001#!/usr/bin/env vpython3
2
deadbeefdc9200e2017-03-02 21:48:39 -08003# 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
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020023# ln -rs tools_webrtc/vim/webrtc.ycm_extra_conf.py \
deadbeefdc9200e2017-03-02 21:48:39 -080024# ../.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
deadbeefdc9200e2017-03-02 21:48:39 -080058import os
59import os.path
60import shlex
61import subprocess
62import sys
63
64# Flags from YCM's default config.
kjellanderdd460e22017-04-12 12:06:13 -070065_DEFAULT_FLAGS = [
Mirko Bonadei8cc66952020-10-30 10:13:45 +010066 '-DUSE_CLANG_COMPLETER',
67 '-std=c++11',
68 '-x',
69 'c++',
deadbeefdc9200e2017-03-02 21:48:39 -080070]
71
kjellanderdd460e22017-04-12 12:06:13 -070072_HEADER_ALTERNATES = ('.cc', '.cpp', '.c', '.mm', '.m')
deadbeefdc9200e2017-03-02 21:48:39 -080073
kjellanderdd460e22017-04-12 12:06:13 -070074_EXTENSION_FLAGS = {
Mirko Bonadei8cc66952020-10-30 10:13:45 +010075 '.m': ['-x', 'objective-c'],
76 '.mm': ['-x', 'objective-c++'],
deadbeefdc9200e2017-03-02 21:48:39 -080077}
78
Mirko Bonadei8cc66952020-10-30 10:13:45 +010079
deadbeefdc9200e2017-03-02 21:48:39 -080080def FindWebrtcSrcFromFilename(filename):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +010081 """Searches for the root of the WebRTC checkout.
deadbeefdc9200e2017-03-02 21:48:39 -080082
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 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +010091 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
deadbeefdc9200e2017-03-02 21:48:39 -0800101
102
103def GetDefaultSourceFile(webrtc_root, filename):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100104 """Returns the default source file to use as an alternative to `filename`.
deadbeefdc9200e2017-03-02 21:48:39 -0800105
106 Compile flags used to build the default source file is assumed to be a
Artem Titovfad54cb2021-07-27 12:58:56 +0200107 close-enough approximation for building `filename`.
deadbeefdc9200e2017-03-02 21:48:39 -0800108
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 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100116 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')
deadbeefdc9200e2017-03-02 21:48:39 -0800119
120
121def GetNinjaBuildOutputsForSourceFile(out_dir, filename):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100122 """Returns a list of build outputs for filename.
deadbeefdc9200e2017-03-02 21:48:39 -0800123
124 The list is generated by invoking 'ninja -t query' tool to retrieve a list of
Artem Titovfad54cb2021-07-27 12:58:56 +0200125 inputs and outputs of `filename`. This list is then filtered to only include
deadbeefdc9200e2017-03-02 21:48:39 -0800126 .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:
Artem Titovfad54cb2021-07-27 12:58:56 +0200133 (List of Strings) List of target names. Will return [] if `filename` doesn't
deadbeefdc9200e2017-03-02 21:48:39 -0800134 yield any .o or .obj outputs.
135 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100136 # Ninja needs the path to the source file relative to the output build
137 # directory.
138 rel_filename = os.path.relpath(filename, out_dir)
deadbeefdc9200e2017-03-02 21:48:39 -0800139
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100140 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 []
deadbeefdc9200e2017-03-02 21:48:39 -0800147
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100148 # 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 ]
deadbeefdc9200e2017-03-02 21:48:39 -0800161
162
163def GetClangCommandLineForNinjaOutput(out_dir, build_target):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100164 """Returns the Clang command line for building `build_target`
deadbeefdc9200e2017-03-02 21:48:39 -0800165
Artem Titovfad54cb2021-07-27 12:58:56 +0200166 Asks ninja for the list of commands used to build `filename` and returns the
deadbeefdc9200e2017-03-02 21:48:39 -0800167 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 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100177 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:
Mirko Bonadei8cc66952020-10-30 10:13:45 +0100183 return None
deadbeefdc9200e2017-03-02 21:48:39 -0800184
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100185 # 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
deadbeefdc9200e2017-03-02 21:48:39 -0800193
194def GetClangCommandLineFromNinjaForSource(out_dir, filename):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100195 """Returns a Clang command line used to build `filename`.
deadbeefdc9200e2017-03-02 21:48:39 -0800196
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:
Artem Titovfad54cb2021-07-27 12:58:56 +0200208 (String or None): Command line for Clang invocation using `filename` as a
deadbeefdc9200e2017-03-02 21:48:39 -0800209 source. Returns None if no such command line could be found.
210 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100211 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
deadbeefdc9200e2017-03-02 21:48:39 -0800217
218
219def GetClangOptionsFromCommandLine(clang_commandline, out_dir,
220 additional_flags):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100221 """Extracts relevant command line options from `clang_commandline`
deadbeefdc9200e2017-03-02 21:48:39 -0800222
223 Args:
224 clang_commandline: (String) Full Clang invocation.
225 out_dir: (String) Absolute path to ninja build directory. Relative paths in
Artem Titovfad54cb2021-07-27 12:58:56 +0200226 the command line are relative to `out_dir`.
deadbeefdc9200e2017-03-02 21:48:39 -0800227 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 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100233 clang_flags = [] + additional_flags
deadbeefdc9200e2017-03-02 21:48:39 -0800234
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100235 # 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
deadbeefdc9200e2017-03-02 21:48:39 -0800269
270
271def GetClangOptionsFromNinjaForFilename(webrtc_root, filename):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100272 """Returns the Clang command line options needed for building `filename`.
deadbeefdc9200e2017-03-02 21:48:39 -0800273
274 Command line options are based on the command used by ninja for building
Artem Titovfad54cb2021-07-27 12:58:56 +0200275 `filename`. If `filename` is a .h file, uses its companion .cc or .cpp file.
deadbeefdc9200e2017-03-02 21:48:39 -0800276 If a suitable companion file can't be located or if ninja doesn't know about
Artem Titovfad54cb2021-07-27 12:58:56 +0200277 `filename`, then uses default source files in WebRTC for determining the
deadbeefdc9200e2017-03-02 21:48:39 -0800278 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 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100288 if not webrtc_root:
289 return []
deadbeefdc9200e2017-03-02 21:48:39 -0800290
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100291 # 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)]
deadbeefdc9200e2017-03-02 21:48:39 -0800294
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100295 # 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')
deadbeefdc9200e2017-03-02 21:48:39 -0800300
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100301 sys.path.append(os.path.join(webrtc_root, 'tools', 'vim'))
302 from ninja_output import GetNinjaOutputDirectory
303 out_dir = GetNinjaOutputDirectory(webrtc_root)
deadbeefdc9200e2017-03-02 21:48:39 -0800304
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100305 basename, extension = os.path.splitext(filename)
306 if extension == '.h':
307 candidates = [basename + ext for ext in _HEADER_ALTERNATES]
308 else:
309 candidates = [filename]
deadbeefdc9200e2017-03-02 21:48:39 -0800310
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100311 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
deadbeefdc9200e2017-03-02 21:48:39 -0800318
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100319 additional_flags += _EXTENSION_FLAGS.get(buildable_extension, [])
deadbeefdc9200e2017-03-02 21:48:39 -0800320
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100321 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))
deadbeefdc9200e2017-03-02 21:48:39 -0800327
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100328 if not clang_line:
329 return additional_flags
deadbeefdc9200e2017-03-02 21:48:39 -0800330
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100331 return GetClangOptionsFromCommandLine(clang_line, out_dir, additional_flags)
deadbeefdc9200e2017-03-02 21:48:39 -0800332
333
334def FlagsForFile(filename):
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100335 """This is the main entry point for YCM. Its interface is fixed.
deadbeefdc9200e2017-03-02 21:48:39 -0800336
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 """
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100345 abs_filename = os.path.abspath(filename)
346 webrtc_root = FindWebrtcSrcFromFilename(abs_filename)
347 clang_flags = GetClangOptionsFromNinjaForFilename(webrtc_root, abs_filename)
deadbeefdc9200e2017-03-02 21:48:39 -0800348
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100349 # 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)
deadbeefdc9200e2017-03-02 21:48:39 -0800353
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100354 final_flags = _DEFAULT_FLAGS + clang_flags
deadbeefdc9200e2017-03-02 21:48:39 -0800355
Christoffer Jansson4e8a7732022-02-08 09:01:12 +0100356 return {'flags': final_flags, 'do_cache': should_cache_flags_for_file}