blob: da85cb71bc9e8f785ae7717272c6ed0d22949121 [file] [log] [blame]
Blink Reformat4c46d092018-04-07 15:32:37 +00001#!/usr/bin/env python
2# Copyright (c) 2012 Google Inc. All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met:
7#
8# * Redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer.
10# * Redistributions in binary form must reproduce the above
11# copyright notice, this list of conditions and the following disclaimer
12# in the documentation and/or other materials provided with the
13# distribution.
14# * Neither the name of Google Inc. nor the names of its
15# contributors may be used to endorse or promote products derived from
16# this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30import argparse
31import os
32import os.path as path
33import re
34import shutil
35import subprocess
36import sys
37import tempfile
38
39from build import modular_build
40from build import generate_protocol_externs
41
42import dependency_preprocessor
43import utils
44
45try:
46 import simplejson as json
47except ImportError:
48 import json
49
50is_cygwin = sys.platform == 'cygwin'
51
52
53def popen(arguments):
54 return subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
55
56
57def to_platform_path(filepath):
58 if not is_cygwin:
59 return filepath
60 return re.sub(r'^/cygdrive/(\w)', '\\1:', filepath)
61
62
63def to_platform_path_exact(filepath):
64 if not is_cygwin:
65 return filepath
66 output, _ = popen(['cygpath', '-w', filepath]).communicate()
67 # pylint: disable=E1103
68 return output.strip().replace('\\', '\\\\')
69
70
71scripts_path = path.dirname(path.abspath(__file__))
72devtools_path = path.dirname(scripts_path)
73inspector_path = path.join(path.dirname(devtools_path), 'core', 'inspector')
74# TODO(dgozman): move these checks to v8.
75v8_inspector_path = path.normpath(path.join(path.dirname(devtools_path), os.pardir, os.pardir, os.pardir, 'v8', 'src', 'inspector'))
76devtools_frontend_path = path.join(devtools_path, 'front_end')
77global_externs_file = to_platform_path(path.join(devtools_frontend_path, 'externs.js'))
78protocol_externs_file = path.join(devtools_frontend_path, 'protocol_externs.js')
79runtime_file = to_platform_path(path.join(devtools_frontend_path, 'Runtime.js'))
80
81closure_compiler_jar = to_platform_path(path.join(scripts_path, 'closure', 'compiler.jar'))
82closure_runner_jar = to_platform_path(path.join(scripts_path, 'closure', 'closure_runner', 'closure_runner.jar'))
83jsdoc_validator_jar = to_platform_path(path.join(scripts_path, 'jsdoc_validator', 'jsdoc_validator.jar'))
84
85type_checked_jsdoc_tags_list = ['param', 'return', 'type', 'enum']
86type_checked_jsdoc_tags_or = '|'.join(type_checked_jsdoc_tags_list)
87
88# Basic regex for invalid JsDoc types: an object type name ([A-Z][_A-Za-z0-9.]+[A-Za-z0-9]) not preceded by '!', '?', ':' (this, new), or '.' (object property).
89invalid_type_regex = re.compile(r'@(?:' + type_checked_jsdoc_tags_or +
90 r')\s*\{.*(?<![!?:._A-Za-z0-9])([A-Z][_A-Za-z0-9.]+[A-Za-z0-9])[^/]*\}')
91invalid_type_designator_regex = re.compile(r'@(?:' + type_checked_jsdoc_tags_or + r')\s*.*(?<![{: ])([?!])=?\}')
92invalid_non_object_type_regex = re.compile(r'@(?:' + type_checked_jsdoc_tags_or + r')\s*\{.*(![a-z]+)[^/]*\}')
93error_warning_regex = re.compile(r'WARNING|ERROR')
94loaded_css_regex = re.compile(r'(?:registerRequiredCSS|WebInspector\.View\.createStyleElement)\s*\(\s*"(.+)"\s*\)')
95
96java_build_regex = re.compile(r'\w+ version "(\d+)\.(\d+)')
97
98
99def log_error(message):
100 print 'ERROR: ' + message
101
102
103def error_excepthook(exctype, value, traceback):
104 print 'ERROR:'
105 sys.__excepthook__(exctype, value, traceback)
106
107
108sys.excepthook = error_excepthook
109
110application_descriptors = [
111 'inspector',
112 'toolbox',
113 'integration_test_runner',
114 'formatter_worker',
115 'heap_snapshot_worker',
116]
117
118skipped_namespaces = {
119 'Console', # Closure uses Console as a namespace item so we cannot override it right now.
120 'Gonzales', # third party module defined in front_end/externs.js
121 'Terminal', # third party module defined in front_end/externs.js
122}
123
124
125def has_errors(output):
126 return re.search(error_warning_regex, output) != None
127
128
129class JSDocChecker:
130
131 def __init__(self, descriptors, java_exec):
132 self._error_found = False
133 self._all_files = descriptors.all_compiled_files()
134 self._java_exec = java_exec
135
136 def check(self):
137 print 'Verifying JSDoc comments...'
138 self._verify_jsdoc()
139 self._run_jsdoc_validator()
140 return self._error_found
141
142 def _run_jsdoc_validator(self):
143 files = [to_platform_path(f) for f in self._all_files]
144 file_list = tempfile.NamedTemporaryFile(mode='wt', delete=False)
145 try:
146 file_list.write('\n'.join(files))
147 finally:
148 file_list.close()
149 proc = popen(self._java_exec + ['-jar', jsdoc_validator_jar, '--files-list-name', to_platform_path_exact(file_list.name)])
150 (out, _) = proc.communicate()
151 if out:
152 print('JSDoc validator output:%s%s' % (os.linesep, out))
153 self._error_found = True
154 os.remove(file_list.name)
155
156 def _verify_jsdoc(self):
157 for full_file_name in self._all_files:
158 line_index = 0
159 with open(full_file_name, 'r') as sourceFile:
160 for line in sourceFile:
161 line_index += 1
162 if line.rstrip():
163 self._verify_jsdoc_line(full_file_name, line_index, line)
164
165 def _verify_jsdoc_line(self, file_name, line_index, line):
166
167 def print_error(message, error_position):
168 print '%s:%s: ERROR - %s%s%s%s%s%s' % (file_name, line_index, message, os.linesep, line, os.linesep,
169 ' ' * error_position + '^', os.linesep)
170
171 known_css = {}
172 match = re.search(invalid_type_regex, line)
173 if match:
174 print_error('Type "%s" nullability not marked explicitly with "?" (nullable) or "!" (non-nullable)' % match.group(1),
175 match.start(1))
176 self._error_found = True
177
178 match = re.search(invalid_non_object_type_regex, line)
179 if match:
180 print_error('Non-object type explicitly marked with "!" (non-nullable), which is the default and should be omitted',
181 match.start(1))
182 self._error_found = True
183
184 match = re.search(invalid_type_designator_regex, line)
185 if match:
186 print_error('Type nullability indicator misplaced, should precede type', match.start(1))
187 self._error_found = True
188
189 match = re.search(loaded_css_regex, line)
190 if match:
191 file = path.join(devtools_frontend_path, match.group(1))
192 exists = known_css.get(file)
193 if exists is None:
194 exists = path.isfile(file)
195 known_css[file] = exists
196 if not exists:
197 print_error('Dynamically loaded CSS stylesheet is missing in the source tree', match.start(1))
198 self._error_found = True
199
200
201def find_java():
202 required_major = 1
203 required_minor = 7
204 exec_command = None
205 has_server_jvm = True
206 java_path = utils.which('java')
207
208 if not java_path:
209 print 'NOTE: No Java executable found in $PATH.'
210 sys.exit(1)
211
212 is_ok = False
213 java_version_out, _ = popen([java_path, '-version']).communicate()
214 # pylint: disable=E1103
215 match = re.search(java_build_regex, java_version_out)
216 if match:
217 major = int(match.group(1))
218 minor = int(match.group(2))
Alexei Filippov87e097d2018-11-06 19:18:29 +0000219 is_ok = major > required_major or major == required_major and minor >= required_minor
Blink Reformat4c46d092018-04-07 15:32:37 +0000220 if is_ok:
221 exec_command = [java_path, '-Xms1024m', '-server', '-XX:+TieredCompilation']
222 check_server_proc = popen(exec_command + ['-version'])
223 check_server_proc.communicate()
224 if check_server_proc.returncode != 0:
225 # Not all Java installs have server JVMs.
226 exec_command = exec_command.remove('-server')
227 has_server_jvm = False
228
229 if not is_ok:
230 print 'NOTE: Java executable version %d.%d or above not found in $PATH.' % (required_major, required_minor)
231 sys.exit(1)
232 print 'Java executable: %s%s' % (java_path, '' if has_server_jvm else ' (no server JVM)')
233 return exec_command
234
235
236common_closure_args = [
237 '--summary_detail_level',
238 '3',
239 '--jscomp_error',
240 'visibility',
241 '--jscomp_warning',
242 'missingOverride',
243 '--compilation_level',
244 'SIMPLE_OPTIMIZATIONS',
245 '--warning_level',
246 'VERBOSE',
247 '--language_in=ECMASCRIPT_2017',
248 '--language_out=ES5_STRICT',
249 '--extra_annotation_name',
250 'suppressReceiverCheck',
251 '--extra_annotation_name',
252 'suppressGlobalPropertiesCheck',
253 '--checks-only',
254 '--allow_method_call_decomposing',
255]
256
257
258def check_conditional_dependencies(modules_by_name):
259 errors_found = False
260 for name in modules_by_name:
261 if 'test_runner' in name:
262 continue
263 for dep_name in modules_by_name[name].get('dependencies', []):
264 dependency = modules_by_name[dep_name]
265 if dependency.get('experiment') or dependency.get('condition'):
266 log_error('Module "%s" may not depend on the conditional module "%s"' % (name, dep_name))
267 errors_found = True
268 return errors_found
269
270
271def prepare_closure_frontend_compile(temp_devtools_path, descriptors, namespace_externs_path):
272 temp_frontend_path = path.join(temp_devtools_path, 'front_end')
273 checker = dependency_preprocessor.DependencyPreprocessor(descriptors, temp_frontend_path, devtools_frontend_path)
274 checker.enforce_dependencies()
275
276 command = common_closure_args + [
277 '--externs',
278 to_platform_path(global_externs_file),
279 '--externs',
280 namespace_externs_path,
281 '--js',
282 runtime_file,
283 ]
284
285 all_files = descriptors.all_compiled_files()
286 args = []
287 for file in all_files:
288 args.extend(['--js', file])
289 if "InspectorBackend.js" in file:
290 args.extend(['--js', protocol_externs_file])
291 command += args
292 command = [arg.replace(devtools_frontend_path, temp_frontend_path) for arg in command]
293 compiler_args_file = tempfile.NamedTemporaryFile(mode='wt', delete=False)
294 try:
295 compiler_args_file.write('devtools_frontend %s' % (' '.join(command)))
296 finally:
297 compiler_args_file.close()
298 return compiler_args_file.name
299
300
301def generate_namespace_externs(modules_by_name):
302 special_case_namespaces_path = path.join(path.dirname(path.abspath(__file__)), 'special_case_namespaces.json')
303 with open(special_case_namespaces_path) as json_file:
304 special_case_namespaces = json.load(json_file)
305
306 def map_module_to_namespace(module):
307 return special_case_namespaces.get(module, to_camel_case(module))
308
309 def to_camel_case(snake_string):
310 components = snake_string.split('_')
311 return ''.join(x.title() for x in components)
312
313 all_namespaces = [map_module_to_namespace(module) for module in modules_by_name]
314 namespaces = [namespace for namespace in all_namespaces if namespace not in skipped_namespaces]
315 namespaces.sort()
316 namespace_externs_file = tempfile.NamedTemporaryFile(mode='wt', delete=False)
317 try:
318 for namespace in namespaces:
319 namespace_externs_file.write('/** @const */\n')
320 namespace_externs_file.write('var %s = {};\n' % namespace)
321 finally:
322 namespace_externs_file.close()
323 namespace_externs_path = to_platform_path(namespace_externs_file.name)
324 return namespace_externs_path
325
326
327def main():
328 global protocol_externs_file
329 errors_found = False
330 parser = argparse.ArgumentParser()
331 parser.add_argument('--protocol-externs-file')
332 args, _ = parser.parse_known_args()
333 if args.protocol_externs_file:
334 protocol_externs_file = args.protocol_externs_file
335 else:
336 generate_protocol_externs.generate_protocol_externs(protocol_externs_file,
Alexey Kozyatinskiya8011e02018-04-17 17:49:38 +0000337 path.join(inspector_path, 'browser_protocol.pdl'),
338 path.join(v8_inspector_path, 'js_protocol.pdl'))
Blink Reformat4c46d092018-04-07 15:32:37 +0000339 loader = modular_build.DescriptorLoader(devtools_frontend_path)
340 descriptors = loader.load_applications(application_descriptors)
341 modules_by_name = descriptors.modules
342
343 java_exec = find_java()
344 errors_found |= check_conditional_dependencies(modules_by_name)
345
346 print 'Compiling frontend...'
347 temp_devtools_path = tempfile.mkdtemp()
348 namespace_externs_path = generate_namespace_externs(modules_by_name)
349 compiler_args_file_path = prepare_closure_frontend_compile(temp_devtools_path, descriptors, namespace_externs_path)
350 frontend_compile_proc = popen(
351 java_exec + ['-jar', closure_runner_jar, '--compiler-args-file', to_platform_path_exact(compiler_args_file_path)])
352
353 print 'Compiling devtools_compatibility.js...'
354
355 closure_compiler_command = java_exec + ['-jar', closure_compiler_jar] + common_closure_args
356
357 devtools_js_compile_command = closure_compiler_command + [
358 '--externs', to_platform_path(global_externs_file), '--externs',
359 to_platform_path(path.join(devtools_frontend_path, 'host', 'InspectorFrontendHostAPI.js')),
360 '--jscomp_off=externsValidation', '--js', to_platform_path(path.join(devtools_frontend_path, 'devtools_compatibility.js'))
361 ]
362 devtools_js_compile_proc = popen(devtools_js_compile_command)
363
364 errors_found |= JSDocChecker(descriptors, java_exec).check()
365
366 (devtools_js_compile_out, _) = devtools_js_compile_proc.communicate()
367 print 'devtools_compatibility.js compilation output:%s' % os.linesep, devtools_js_compile_out
368 errors_found |= has_errors(devtools_js_compile_out)
369
370 (frontend_compile_out, _) = frontend_compile_proc.communicate()
371 print 'devtools frontend compilation output:'
372 for line in frontend_compile_out.splitlines():
373 if "@@ START_MODULE" in line or "@@ END_MODULE" in line:
374 continue
375 print line
376 errors_found |= has_errors(frontend_compile_out)
377
378 os.remove(protocol_externs_file)
379 os.remove(namespace_externs_path)
380 os.remove(compiler_args_file_path)
381 shutil.rmtree(temp_devtools_path, True)
382
383 if errors_found:
384 print 'ERRORS DETECTED'
385 sys.exit(1)
386 print 'DONE - compiled without errors'
387
388
389if __name__ == "__main__":
390 main()