c0de6486aa26797fcd701a52f9a259a7b7d3eb47
[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 import sys
44
45
46 # Flags from YCM's default config.
47 flags = [
48 '-DUSE_CLANG_COMPLETER',
49 '-std=c++11',
50 '-x',
51 'c++',
52 ]
53
54
55 def PathExists(*args):
56   return os.path.exists(os.path.join(*args))
57
58
59 def FindChromeSrcFromFilename(filename):
60   """Searches for the root of the Chromium checkout.
61
62   Simply checks parent directories until it finds .gclient and src/.
63
64   Args:
65     filename: (String) Path to source file being edited.
66
67   Returns:
68     (String) Path of 'src/', or None if unable to find.
69   """
70   curdir = os.path.normpath(os.path.dirname(filename))
71   while not (PathExists(curdir, 'src') and PathExists(curdir, 'src', 'DEPS')
72              and (PathExists(curdir, '.gclient')
73                   or PathExists(curdir, 'src', '.git'))):
74     nextdir = os.path.normpath(os.path.join(curdir, '..'))
75     if nextdir == curdir:
76       return None
77     curdir = nextdir
78   return os.path.join(curdir, 'src')
79
80
81 def GetClangCommandFromNinjaForFilename(chrome_root, filename):
82   """Returns the command line to build |filename|.
83
84   Asks ninja how it would build the source file. If the specified file is a
85   header, tries to find its companion source file first.
86
87   Args:
88     chrome_root: (String) Path to src/.
89     filename: (String) Path to source file being edited.
90
91   Returns:
92     (List of Strings) Command line arguments for clang.
93   """
94   if not chrome_root:
95     return []
96
97   # Generally, everyone benefits from including Chromium's src/, because all of
98   # Chromium's includes are relative to that.
99   chrome_flags = ['-I' + os.path.join(chrome_root)]
100
101   # Version of Clang used to compile Chromium can be newer then version of
102   # libclang that YCM uses for completion. So it's possible that YCM's libclang
103   # doesn't know about some used warning options, which causes compilation
104   # warnings (and errors, because of '-Werror');
105   chrome_flags.append('-Wno-unknown-warning-option')
106
107   # Default file to get a reasonable approximation of the flags for a Blink
108   # file.
109   blink_root = os.path.join(chrome_root, 'third_party', 'WebKit')
110   default_blink_file = os.path.join(blink_root, 'Source', 'core', 'Init.cpp')
111
112   # Header files can't be built. Instead, try to match a header file to its
113   # corresponding source file.
114   if filename.endswith('.h'):
115     # Add config.h to Blink headers, which won't have it by default.
116     if filename.startswith(blink_root):
117       chrome_flags.append('-include')
118       chrome_flags.append(os.path.join(blink_root, 'Source', 'config.h'))
119
120     alternates = ['.cc', '.cpp']
121     for alt_extension in alternates:
122       alt_name = filename[:-2] + alt_extension
123       if os.path.exists(alt_name):
124         filename = alt_name
125         break
126     else:
127       if filename.startswith(blink_root):
128         # If this is a Blink file, we can at least try to get a reasonable
129         # approximation.
130         filename = default_blink_file
131       else:
132         # If this is a standalone .h file with no source, the best we can do is
133         # try to use the default flags.
134         return chrome_flags
135
136   sys.path.append(os.path.join(chrome_root, 'tools', 'vim'))
137   from ninja_output import GetNinjaOutputDirectory
138   out_dir = os.path.realpath(GetNinjaOutputDirectory(chrome_root))
139
140   # Ninja needs the path to the source file relative to the output build
141   # directory.
142   rel_filename = os.path.relpath(os.path.realpath(filename), out_dir)
143
144   # Ask ninja how it would build our source file.
145   p = subprocess.Popen(['ninja', '-v', '-C', out_dir, '-t',
146                         'commands', rel_filename + '^'],
147                        stdout=subprocess.PIPE)
148   stdout, stderr = p.communicate()
149   if p.returncode:
150     return chrome_flags
151
152   # Ninja might execute several commands to build something. We want the last
153   # clang command.
154   clang_line = None
155   for line in reversed(stdout.split('\n')):
156     if 'clang' in line:
157       clang_line = line
158       break
159   else:
160     return chrome_flags
161
162   # Parse flags that are important for YCM's purposes.
163   for flag in clang_line.split(' '):
164     if flag.startswith('-I'):
165       # Relative paths need to be resolved, because they're relative to the
166       # output dir, not the source.
167       if flag[2] == '/':
168         chrome_flags.append(flag)
169       else:
170         abs_path = os.path.normpath(os.path.join(out_dir, flag[2:]))
171         chrome_flags.append('-I' + abs_path)
172     elif flag.startswith('-std'):
173       chrome_flags.append(flag)
174     elif flag.startswith('-') and flag[1] in 'DWFfmO':
175       if flag == '-Wno-deprecated-register' or flag == '-Wno-header-guard':
176         # These flags causes libclang (3.3) to crash. Remove it until things
177         # are fixed.
178         continue
179       chrome_flags.append(flag)
180
181   return chrome_flags
182
183
184 def FlagsForFile(filename):
185   """This is the main entry point for YCM. Its interface is fixed.
186
187   Args:
188     filename: (String) Path to source file being edited.
189
190   Returns:
191     (Dictionary)
192       'flags': (List of Strings) Command line flags.
193       'do_cache': (Boolean) True if the result should be cached.
194   """
195   chrome_root = FindChromeSrcFromFilename(filename)
196   chrome_flags = GetClangCommandFromNinjaForFilename(chrome_root,
197                                                      filename)
198   final_flags = flags + chrome_flags
199
200   return {
201     'flags': final_flags,
202     'do_cache': True
203   }