xref: /third_party/node/deps/v8/.ycm_extra_conf.py (revision 1cb0ef41)
1# 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++14',
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    base = filename[:-6] if filename.endswith('-inl.h') else filename[:-2]
107    for alternate in [base + e for e in ['.cc', '.cpp']]:
108      if os.path.exists(alternate):
109        filename = alternate
110        break
111    else:
112      # If this is a standalone .h file with no source, we ask ninja for the
113      # compile flags of some generic cc file ('src/utils/utils.cc'). This
114      # should contain most/all of the interesting flags for other targets too.
115      filename = os.path.join(v8_root, 'src', 'utils', 'utils.cc')
116
117  sys.path.append(os.path.join(v8_root, 'tools', 'vim'))
118  from ninja_output import GetNinjaOutputDirectory
119  out_dir = os.path.realpath(GetNinjaOutputDirectory(v8_root))
120
121  # Ninja needs the path to the source file relative to the output build
122  # directory.
123  rel_filename = os.path.relpath(os.path.realpath(filename), out_dir)
124
125  # Ask ninja how it would build our source file.
126  p = subprocess.Popen(['ninja', '-v', '-C', out_dir, '-t',
127                        'commands', rel_filename + '^'],
128                       stdout=subprocess.PIPE)
129  stdout, stderr = p.communicate()
130  if p.returncode:
131    return v8_flags
132
133  # Ninja might execute several commands to build something. We want the last
134  # clang command.
135  clang_line = None
136  for line in reversed(stdout.decode('utf-8').splitlines()):
137    if 'clang' in line:
138      clang_line = line
139      break
140  else:
141    return v8_flags
142
143  # Parse flags that are important for YCM's purposes.
144  for flag in clang_line.split(' '):
145    if flag.startswith('-I'):
146      # Relative paths need to be resolved, because they're relative to the
147      # output dir, not the source.
148      if flag[2] == '/':
149        v8_flags.append(flag)
150      else:
151        abs_path = os.path.normpath(os.path.join(out_dir, flag[2:]))
152        v8_flags.append('-I' + abs_path)
153    elif flag.startswith('-std'):
154      v8_flags.append(flag)
155    elif flag.startswith('-') and flag[1] in 'DWFfmO':
156      if flag == '-Wno-deprecated-register' or flag == '-Wno-header-guard':
157        # These flags causes libclang (3.3) to crash. Remove it until things
158        # are fixed.
159        continue
160      v8_flags.append(flag)
161
162  return v8_flags
163
164
165def FlagsForFile(filename):
166  """This is the main entry point for YCM. Its interface is fixed.
167
168  Args:
169    filename: (String) Path to source file being edited.
170
171  Returns:
172    (Dictionary)
173      'flags': (List of Strings) Command line flags.
174      'do_cache': (Boolean) True if the result should be cached.
175  """
176  v8_root = FindV8SrcFromFilename(filename)
177  v8_flags = GetClangCommandFromNinjaForFilename(v8_root, filename)
178  final_flags = flags + v8_flags
179  return {
180    'flags': final_flags,
181    'do_cache': True
182  }
183