Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / WebKit / Source / devtools / scripts / CodeGeneratorFrontend.py
blobb17252ddb13c0a74749b4e4354f981bcfcf56957
1 #!/usr/bin/env python
2 # Copyright (c) 2011 Google Inc. All rights reserved.
3 # Copyright (c) 2012 Intel Corporation. All rights reserved.
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
7 # met:
9 # * Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # * Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following disclaimer
13 # in the documentation and/or other materials provided with the
14 # distribution.
15 # * Neither the name of Google Inc. nor the names of its
16 # contributors may be used to endorse or promote products derived from
17 # this software without specific prior written permission.
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 import os.path
32 import sys
33 import string
34 import optparse
35 import re
36 try:
37 import json
38 except ImportError:
39 import simplejson as json
41 cmdline_parser = optparse.OptionParser()
42 cmdline_parser.add_option("--output_js_dir")
44 try:
45 arg_options, arg_values = cmdline_parser.parse_args()
46 if (len(arg_values) != 1):
47 raise Exception("Exactly one plain argument expected (found %s)" % len(arg_values))
48 input_json_filename = arg_values[0]
49 output_js_dirname = arg_options.output_js_dir
50 if not output_js_dirname:
51 raise Exception("Output .js directory must be specified")
52 except Exception:
53 # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html
54 exc = sys.exc_info()[1]
55 sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc)
56 sys.stderr.write("Usage: <script> protocol.json --output_js_dir <output_js_dir>\n")
57 exit(1)
60 def fix_camel_case(name):
61 refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name)
62 refined = to_title_case(refined)
63 return re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upper(), refined)
66 def to_title_case(name):
67 return name[:1].upper() + name[1:]
70 class RawTypes(object):
71 @staticmethod
72 def get_js(json_type):
73 if json_type == "boolean":
74 return "boolean"
75 elif json_type == "string":
76 return "string"
77 elif json_type == "array":
78 return "object"
79 elif json_type == "object":
80 return "object"
81 elif json_type == "integer":
82 return "number"
83 elif json_type == "number":
84 return "number"
85 elif json_type == "any":
86 raise Exception("Unsupported")
87 else:
88 raise Exception("Unknown type: %s" % json_type)
91 class TypeData(object):
92 def __init__(self, json_type):
93 if "type" not in json_type:
94 raise Exception("Unknown type")
95 json_type_name = json_type["type"]
96 self.raw_type_js_ = RawTypes.get_js(json_type_name)
98 def get_raw_type_js(self):
99 return self.raw_type_js_
102 class TypeMap:
103 def __init__(self, api):
104 self.map_ = {}
105 for json_domain in api["domains"]:
106 domain_name = json_domain["domain"]
108 domain_map = {}
109 self.map_[domain_name] = domain_map
111 if "types" in json_domain:
112 for json_type in json_domain["types"]:
113 type_name = json_type["id"]
114 type_data = TypeData(json_type)
115 domain_map[type_name] = type_data
117 def get(self, domain_name, type_name):
118 return self.map_[domain_name][type_name]
121 def resolve_param_raw_type_js(json_parameter, scope_domain_name):
122 if "$ref" in json_parameter:
123 json_ref = json_parameter["$ref"]
124 return get_ref_data_js(json_ref, scope_domain_name)
125 elif "type" in json_parameter:
126 json_type = json_parameter["type"]
127 return RawTypes.get_js(json_type)
128 else:
129 raise Exception("Unknown type")
132 def get_ref_data_js(json_ref, scope_domain_name):
133 dot_pos = json_ref.find(".")
134 if dot_pos == -1:
135 domain_name = scope_domain_name
136 type_name = json_ref
137 else:
138 domain_name = json_ref[:dot_pos]
139 type_name = json_ref[dot_pos + 1:]
141 return type_map.get(domain_name, type_name).get_raw_type_js()
144 input_file = open(input_json_filename, "r")
145 json_string = input_file.read()
146 json_api = json.loads(json_string)
149 class Templates:
150 def get_this_script_path_(absolute_path):
151 absolute_path = os.path.abspath(absolute_path)
152 components = []
154 def fill_recursive(path_part, depth):
155 if depth <= 0 or path_part == '/':
156 return
157 fill_recursive(os.path.dirname(path_part), depth - 1)
158 components.append(os.path.basename(path_part))
160 # Typical path is /Source/WebCore/inspector/CodeGeneratorInspector.py
161 # Let's take 4 components from the real path then.
162 fill_recursive(absolute_path, 4)
164 return "/".join(components)
166 file_header_ = ("// File is generated by %s\n\n" % get_this_script_path_(sys.argv[0]) +
167 """// Copyright (c) 2011 The Chromium Authors. All rights reserved.
168 // Use of this source code is governed by a BSD-style license that can be
169 // found in the LICENSE file.
170 """)
172 backend_js = string.Template(file_header_ + """
174 $domainInitializers
175 """)
178 type_map = TypeMap(json_api)
181 class Generator:
182 backend_js_domain_initializer_list = []
184 @staticmethod
185 def go():
186 for json_domain in json_api["domains"]:
187 domain_name = json_domain["domain"]
188 domain_name_lower = domain_name.lower()
190 Generator.backend_js_domain_initializer_list.append("// %s.\n" % domain_name)
192 if "types" in json_domain:
193 for json_type in json_domain["types"]:
194 if "type" in json_type and json_type["type"] == "string" and "enum" in json_type:
195 enum_name = "%s.%s" % (domain_name, json_type["id"])
196 Generator.process_enum(json_type, enum_name)
197 elif json_type["type"] == "object":
198 if "properties" in json_type:
199 for json_property in json_type["properties"]:
200 if "type" in json_property and json_property["type"] == "string" and "enum" in json_property:
201 enum_name = "%s.%s%s" % (domain_name, json_type["id"], to_title_case(json_property["name"]))
202 Generator.process_enum(json_property, enum_name)
204 if "events" in json_domain:
205 for json_event in json_domain["events"]:
206 Generator.process_event(json_event, domain_name)
208 if "commands" in json_domain:
209 for json_command in json_domain["commands"]:
210 Generator.process_command(json_command, domain_name)
212 Generator.backend_js_domain_initializer_list.append("\n")
214 @staticmethod
215 def process_enum(json_enum, enum_name):
216 enum_members = []
217 for member in json_enum["enum"]:
218 enum_members.append("%s: \"%s\"" % (fix_camel_case(member), member))
220 Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEnum(\"%s\", {%s});\n" % (
221 enum_name, ", ".join(enum_members)))
223 @staticmethod
224 def process_event(json_event, domain_name):
225 event_name = json_event["name"]
227 json_parameters = json_event.get("parameters")
229 backend_js_event_param_list = []
230 if json_parameters:
231 for parameter in json_parameters:
232 parameter_name = parameter["name"]
233 backend_js_event_param_list.append("\"%s\"" % parameter_name)
235 Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEvent(\"%s.%s\", [%s]);\n" % (
236 domain_name, event_name, ", ".join(backend_js_event_param_list)))
238 @staticmethod
239 def process_command(json_command, domain_name):
240 json_command_name = json_command["name"]
242 js_parameters_text = ""
243 if "parameters" in json_command:
244 json_params = json_command["parameters"]
245 js_param_list = []
247 for json_parameter in json_params:
248 json_param_name = json_parameter["name"]
249 js_bind_type = resolve_param_raw_type_js(json_parameter, domain_name)
251 optional = json_parameter.get("optional")
254 js_param_text = "{\"name\": \"%s\", \"type\": \"%s\", \"optional\": %s}" % (
255 json_param_name,
256 js_bind_type,
257 ("true" if ("optional" in json_parameter and json_parameter["optional"]) else "false"))
259 js_param_list.append(js_param_text)
261 js_parameters_text = ", ".join(js_param_list)
264 backend_js_reply_param_list = []
265 if "returns" in json_command:
266 for json_return in json_command["returns"]:
267 json_return_name = json_return["name"]
268 backend_js_reply_param_list.append("\"%s\"" % json_return_name)
270 js_reply_list = "[%s]" % ", ".join(backend_js_reply_param_list)
271 if "error" in json_command:
272 has_error_data_param = "true"
273 else:
274 has_error_data_param = "false"
276 Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerCommand(\"%s.%s\", [%s], %s, %s);\n" % (domain_name, json_command_name, js_parameters_text, js_reply_list, has_error_data_param))
278 Generator.go()
280 backend_js_file = open(output_js_dirname + "/InspectorBackendCommands.js", "w")
282 backend_js_file.write(Templates.backend_js.substitute(None,
283 domainInitializers="".join(Generator.backend_js_domain_initializer_list)))
285 backend_js_file.close()