Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / tools / vim / chromium.ycm_extra_conf.py
1 # Copyright (c) 2012 The Chromium 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 Chromium.
6 #
7 # USAGE:
8 #
9 #   1. Install YCM [https://github.com/Valloric/YouCompleteMe]
10 #          (Googlers should check out [go/ycm])
11 #
12 #   2. Point to this config file in your .vimrc:
13 #          let g:ycm_global_ycm_extra_conf =
14 #              '<chrome_depot>/src/tools/vim/chromium.ycm_extra_conf.py'
15 #
16 #   3. Profit
17 #
18 #
19 # Usage notes:
20 #
21 #   * You must use ninja & clang to build Chromium.
22 #
23 #   * You must have run gyp_chromium and built Chromium recently.
24 #
25 #
26 # Hacking notes:
27 #
28 #   * The purpose of this script is to construct an accurate enough command line
29 #     for YCM to pass to clang so it can build and extract the symbols.
30 #
31 #   * Right now, we only pull the -I and -D flags. That seems to be sufficient
32 #     for everything I've used it for.
33 #
34 #   * That whole ninja & clang thing? We could support other configs if someone
35 #     were willing to write the correct commands and a parser.
36 #
37 #   * This has only been tested on gPrecise.
38
39
40 import os
41 import os.path
42 import subprocess
43
44
45 # Flags from YCM's default config.
46 flags = [
47 '-DUSE_CLANG_COMPLETER',
48 '-std=c++11',
49 '-x',
50 'c++',
51 ]
52
53
54 def PathExists(*args):
55   return os.path.exists(os.path.join(*args))
56
57
58 def FindChromeSrcFromFilename(filename):
59   """Searches for the root of the Chromium checkout.
60
61   Simply checks parent directories until it finds .gclient and src/.
62
63   Args:
64     filename: (String) Path to source file being edited.
65
66   Returns:
67     (String) Path of 'src/', or None if unable to find.
68   """
69   curdir = os.path.normpath(os.path.dirname(filename))
70   while not (PathExists(curdir, 'src') and PathExists(curdir, 'src', 'DEPS')
71              and (PathExists(curdir, '.gclient')
72                   or PathExists(curdir, 'src', '.git'))):
73     nextdir = os.path.normpath(os.path.join(curdir, '..'))
74     if nextdir == curdir:
75       return None
76     curdir = nextdir
77   return os.path.join(curdir, 'src')
78
79
80 # Largely copied from ninja-build.vim (guess_configuration)
81 def GetNinjaOutputDirectory(chrome_root):
82   """Returns <chrome_root>/<output_dir>/(Release|Debug).
83
84   The configuration chosen is the one most recently generated/built. Detects
85   a custom output_dir specified by GYP_GENERATOR_FLAGS."""
86
87   output_dir = 'out'
88   generator_flags = os.getenv('GYP_GENERATOR_FLAGS', '').split(' ')
89   for flag in generator_flags:
90     name_value = flag.split('=', 1)
91     if len(name_value) == 2 and name_value[0] == 'output_dir':
92       output_dir = name_value[1]
93
94   root = os.path.join(chrome_root, output_dir)
95   debug_path = os.path.join(root, 'Debug')
96   release_path = os.path.join(root, 'Release')
97
98   def is_release_15s_newer(test_path):
99     try:
100       debug_mtime = os.path.getmtime(os.path.join(debug_path, test_path))
101     except os.error:
102       debug_mtime = 0
103     try:
104       rel_mtime = os.path.getmtime(os.path.join(release_path, test_path))
105     except os.error:
106       rel_mtime = 0
107     return rel_mtime - debug_mtime >= 15
108
109   if is_release_15s_newer('build.ninja') or is_release_15s_newer('protoc'):
110     return release_path
111   return debug_path
112
113
114 def GetClangCommandFromNinjaForFilename(chrome_root, filename):
115   """Returns the command line to build |filename|.
116
117   Asks ninja how it would build the source file. If the specified file is a
118   header, tries to find its companion source file first.
119
120   Args:
121     chrome_root: (String) Path to src/.
122     filename: (String) Path to source file being edited.
123
124   Returns:
125     (List of Strings) Command line arguments for clang.
126   """
127   if not chrome_root:
128     return []
129
130   # Generally, everyone benefits from including Chromium's src/, because all of
131   # Chromium's includes are relative to that.
132   chrome_flags = ['-I' + os.path.join(chrome_root)]
133
134   # Version of Clang used to compile Chromium can be newer then version of
135   # libclang that YCM uses for completion. So it's possible that YCM's libclang
136   # doesn't know about some used warning options, which causes compilation
137   # warnings (and errors, because of '-Werror');
138   chrome_flags.append('-Wno-unknown-warning-option')
139
140   # Default file to get a reasonable approximation of the flags for a Blink
141   # file.
142   blink_root = os.path.join(chrome_root, 'third_party', 'WebKit')
143   default_blink_file = os.path.join(blink_root, 'Source', 'core', 'Init.cpp')
144
145   # Header files can't be built. Instead, try to match a header file to its
146   # corresponding source file.
147   if filename.endswith('.h'):
148     # Add config.h to Blink headers, which won't have it by default.
149     if filename.startswith(blink_root):
150       chrome_flags.append('-include')
151       chrome_flags.append(os.path.join(blink_root, 'Source', 'config.h'))
152
153     alternates = ['.cc', '.cpp']
154     for alt_extension in alternates:
155       alt_name = filename[:-2] + alt_extension
156       if os.path.exists(alt_name):
157         filename = alt_name
158         break
159     else:
160       if filename.startswith(blink_root):
161         # If this is a Blink file, we can at least try to get a reasonable
162         # approximation.
163         filename = default_blink_file
164       else:
165         # If this is a standalone .h file with no source, the best we can do is
166         # try to use the default flags.
167         return chrome_flags
168
169   out_dir = os.path.realpath(GetNinjaOutputDirectory(chrome_root))
170
171   # Ninja needs the path to the source file relative to the output build
172   # directory.
173   rel_filename = os.path.relpath(os.path.realpath(filename), out_dir)
174
175   # Ask ninja how it would build our source file.
176   p = subprocess.Popen(['ninja', '-v', '-C', out_dir, '-t',
177                         'commands', rel_filename + '^'],
178                        stdout=subprocess.PIPE)
179   stdout, stderr = p.communicate()
180   if p.returncode:
181     return chrome_flags
182
183   # Ninja might execute several commands to build something. We want the last
184   # clang command.
185   clang_line = None
186   for line in reversed(stdout.split('\n')):
187     if 'clang' in line:
188       clang_line = line
189       break
190   else:
191     return chrome_flags
192
193   # Parse flags that are important for YCM's purposes.
194   for flag in clang_line.split(' '):
195     if flag.startswith('-I'):
196       # Relative paths need to be resolved, because they're relative to the
197       # output dir, not the source.
198       if flag[2] == '/':
199         chrome_flags.append(flag)
200       else:
201         abs_path = os.path.normpath(os.path.join(out_dir, flag[2:]))
202         chrome_flags.append('-I' + abs_path)
203     elif flag.startswith('-std'):
204       chrome_flags.append(flag)
205     elif flag.startswith('-') and flag[1] in 'DWFfmO':
206       if flag == '-Wno-deprecated-register' or flag == '-Wno-header-guard':
207         # These flags causes libclang (3.3) to crash. Remove it until things
208         # are fixed.
209         continue
210       chrome_flags.append(flag)
211
212   return chrome_flags
213
214
215 def FlagsForFile(filename):
216   """This is the main entry point for YCM. Its interface is fixed.
217
218   Args:
219     filename: (String) Path to source file being edited.
220
221   Returns:
222     (Dictionary)
223       'flags': (List of Strings) Command line flags.
224       'do_cache': (Boolean) True if the result should be cached.
225   """
226   chrome_root = FindChromeSrcFromFilename(filename)
227   chrome_flags = GetClangCommandFromNinjaForFilename(chrome_root,
228                                                      filename)
229   final_flags = flags + chrome_flags
230
231   return {
232     'flags': final_flags,
233     'do_cache': True
234   }