blob: a451d9f31c34b0bfbb705fb069e0c4298128d7f9 [file] [log] [blame]
Ben Murdochf91f0612016-11-29 16:50:11 +00001# Copyright 2015 the V8 project authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5# Autocompletion config for YouCompleteMe in V8.
6#
7# USAGE:
8#
9# 1. Install YCM [https://github.com/Valloric/YouCompleteMe]
10# (Googlers should check out [go/ycm])
11#
12# 2. Profit
13#
14#
15# Usage notes:
16#
17# * You must use ninja & clang to build V8.
18#
19# * You must have run gyp_v8 and built V8 recently.
20#
21#
22# Hacking notes:
23#
24# * The purpose of this script is to construct an accurate enough command line
25# for YCM to pass to clang so it can build and extract the symbols.
26#
27# * Right now, we only pull the -I and -D flags. That seems to be sufficient
28# for everything I've used it for.
29#
30# * That whole ninja & clang thing? We could support other configs if someone
31# were willing to write the correct commands and a parser.
32#
33# * This has only been tested on gTrusty.
34
35
36import os
37import os.path
38import subprocess
39import sys
40
41
42# Flags from YCM's default config.
43flags = [
44'-DUSE_CLANG_COMPLETER',
45'-std=gnu++11',
46'-x',
47'c++',
48]
49
50
51def PathExists(*args):
52 return os.path.exists(os.path.join(*args))
53
54
55def FindV8SrcFromFilename(filename):
56 """Searches for the root of the V8 checkout.
57
58 Simply checks parent directories until it finds .gclient and v8/.
59
60 Args:
61 filename: (String) Path to source file being edited.
62
63 Returns:
64 (String) Path of 'v8/', or None if unable to find.
65 """
66 curdir = os.path.normpath(os.path.dirname(filename))
67 while not (PathExists(curdir, 'v8') and PathExists(curdir, 'v8', 'DEPS')
68 and (PathExists(curdir, '.gclient')
69 or PathExists(curdir, 'v8', '.git'))):
70 nextdir = os.path.normpath(os.path.join(curdir, '..'))
71 if nextdir == curdir:
72 return None
73 curdir = nextdir
74 return os.path.join(curdir, 'v8')
75
76
77def GetClangCommandFromNinjaForFilename(v8_root, filename):
78 """Returns the command line to build |filename|.
79
80 Asks ninja how it would build the source file. If the specified file is a
81 header, tries to find its companion source file first.
82
83 Args:
84 v8_root: (String) Path to v8/.
85 filename: (String) Path to source file being edited.
86
87 Returns:
88 (List of Strings) Command line arguments for clang.
89 """
90 if not v8_root:
91 return []
92
93 # Generally, everyone benefits from including V8's root, because all of
94 # V8's includes are relative to that.
95 v8_flags = ['-I' + os.path.join(v8_root)]
96
97 # Version of Clang used to compile V8 can be newer then version of
98 # libclang that YCM uses for completion. So it's possible that YCM's libclang
99 # doesn't know about some used warning options, which causes compilation
100 # warnings (and errors, because of '-Werror');
101 v8_flags.append('-Wno-unknown-warning-option')
102
103 # Header files can't be built. Instead, try to match a header file to its
104 # corresponding source file.
105 if filename.endswith('.h'):
106 alternates = ['.cc', '.cpp']
107 for alt_extension in alternates:
108 alt_name = filename[:-2] + alt_extension
109 if os.path.exists(alt_name):
110 filename = alt_name
111 break
112 else:
113 if filename.endswith('-inl.h'):
114 for alt_extension in alternates:
115 alt_name = filename[:-6] + alt_extension
116 if os.path.exists(alt_name):
117 filename = alt_name
118 break;
119 else:
120 # If this is a standalone -inl.h file with no source, the best we can
121 # do is try to use the default flags.
122 return v8_flags
123 else:
124 # If this is a standalone .h file with no source, the best we can do is
125 # try to use the default flags.
126 return v8_flags
127
128 sys.path.append(os.path.join(v8_root, 'tools', 'ninja'))
129 from ninja_output import GetNinjaOutputDirectory
130 out_dir = os.path.realpath(GetNinjaOutputDirectory(v8_root))
131
132 # Ninja needs the path to the source file relative to the output build
133 # directory.
134 rel_filename = os.path.relpath(os.path.realpath(filename), out_dir)
135
136 # Ask ninja how it would build our source file.
137 p = subprocess.Popen(['ninja', '-v', '-C', out_dir, '-t',
138 'commands', rel_filename + '^'],
139 stdout=subprocess.PIPE)
140 stdout, stderr = p.communicate()
141 if p.returncode:
142 return v8_flags
143
144 # Ninja might execute several commands to build something. We want the last
145 # clang command.
146 clang_line = None
147 for line in reversed(stdout.split('\n')):
148 if 'clang' in line:
149 clang_line = line
150 break
151 else:
152 return v8_flags
153
154 # Parse flags that are important for YCM's purposes.
155 for flag in clang_line.split(' '):
156 if flag.startswith('-I'):
157 # Relative paths need to be resolved, because they're relative to the
158 # output dir, not the source.
159 if flag[2] == '/':
160 v8_flags.append(flag)
161 else:
162 abs_path = os.path.normpath(os.path.join(out_dir, flag[2:]))
163 v8_flags.append('-I' + abs_path)
164 elif flag.startswith('-std'):
165 v8_flags.append(flag)
166 elif flag.startswith('-') and flag[1] in 'DWFfmO':
167 if flag == '-Wno-deprecated-register' or flag == '-Wno-header-guard':
168 # These flags causes libclang (3.3) to crash. Remove it until things
169 # are fixed.
170 continue
171 v8_flags.append(flag)
172
173 return v8_flags
174
175
176def FlagsForFile(filename):
177 """This is the main entry point for YCM. Its interface is fixed.
178
179 Args:
180 filename: (String) Path to source file being edited.
181
182 Returns:
183 (Dictionary)
184 'flags': (List of Strings) Command line flags.
185 'do_cache': (Boolean) True if the result should be cached.
186 """
187 v8_root = FindV8SrcFromFilename(filename)
188 v8_flags = GetClangCommandFromNinjaForFilename(v8_root, filename)
189 final_flags = flags + v8_flags
190 return {
191 'flags': final_flags,
192 'do_cache': True
193 }