blob: 418361ba70a1098a3691f81d9115089c562b6772 [file] [log] [blame]
Blink Reformat4c46d092018-04-07 15:32:37 +00001#!/usr/bin/env python
2# Copyright (c) 2011 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 os
31import re
32try:
33 import json
34except ImportError:
35 import simplejson as json
36
37type_traits = {
38 "any": "*",
39 "string": "string",
40 "integer": "number",
41 "number": "number",
42 "boolean": "boolean",
43 "array": "!Array<*>",
44 "object": "!Object",
45}
46
47ref_types = {}
48
49
50def full_qualified_type_id(domain_name, type_id):
51 if type_id.find(".") == -1:
52 return "%s.%s" % (domain_name, type_id)
53 return type_id
54
55
56def fix_camel_case(name):
57 prefix = ""
58 if name[0] == "-":
59 prefix = "Negative"
60 name = name[1:]
61 refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name)
62 refined = to_title_case(refined)
63 return prefix + re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upper(), refined)
64
65
66def to_title_case(name):
67 return name[:1].upper() + name[1:]
68
69
70def generate_enum(name, json):
71 enum_members = []
72 for member in json["enum"]:
73 enum_members.append(" %s: \"%s\"" % (fix_camel_case(member), member))
74 return "\n/** @enum {string} */\n%s = {\n%s\n};\n" % (name, (",\n".join(enum_members)))
75
76
77def param_type(domain_name, param):
78 if "type" in param:
79 if param["type"] == "array":
80 items = param["items"]
81 return "!Array<%s>" % param_type(domain_name, items)
82 else:
83 return type_traits[param["type"]]
84 if "$ref" in param:
85 type_id = full_qualified_type_id(domain_name, param["$ref"])
86 if type_id in ref_types:
87 return ref_types[type_id]
88 else:
89 print "Type not found: " + type_id
90 return "!! Type not found: " + type_id
91
92
93def param_name(param):
94 name = param["name"]
95 return name if name != "arguments" else "_arguments"
96
97
98def load_schema(file, domains):
99 input_file = open(file, "r")
100 json_string = input_file.read()
101 parsed_json = json.loads(json_string)
102 domains.extend(parsed_json["domains"])
103
104
105def generate_protocol_externs(output_path, file1, file2):
106 domains = []
107 load_schema(file1, domains)
108 load_schema(file2, domains)
109 output_file = open(output_path, "w")
110
111 for domain in domains:
112 domain_name = domain["domain"]
113 if "types" in domain:
114 for type in domain["types"]:
115 type_id = full_qualified_type_id(domain_name, type["id"])
116 ref_types[type_id] = "Protocol.%s.%s" % (domain_name, type["id"])
117
118 for domain in domains:
119 domain_name = domain["domain"]
120
121 output_file.write("Protocol.%s = {};\n" % domain_name)
122 output_file.write("\n\n/**\n * @constructor\n*/\n")
123 output_file.write("Protocol.%sAgent = function(){};\n" % domain_name)
124
125 if "commands" in domain:
126 for command in domain["commands"]:
127 output_file.write("\n/**\n")
128 params = []
129 in_param_to_type = {}
130 out_param_to_type = {}
131 has_return_value = "returns" in command
132 if "parameters" in command:
133 for in_param in command["parameters"]:
134 in_param_name = param_name(in_param)
135 if "optional" in in_param:
136 in_param_to_type[in_param_name] = "(%s|undefined)" % param_type(domain_name, in_param)
137 params.append("opt_%s" % in_param_name)
138 output_file.write(" * @param {%s=} opt_%s\n" % (param_type(domain_name, in_param), in_param_name))
139 else:
140 in_param_to_type[in_param_name] = param_type(domain_name, in_param)
141 params.append(in_param_name)
142 output_file.write(" * @param {%s} %s\n" % (param_type(domain_name, in_param), in_param_name))
143 returns = []
144 returns.append("?Protocol.Error")
145 if ("error" in command):
146 returns.append("%s=" % param_type(domain_name, command["error"]))
147 if (has_return_value):
148 for out_param in command["returns"]:
149 out_param_type = param_type(domain_name, out_param)
150 out_param_to_type[out_param["name"]] = out_param_type
151 if ("optional" in out_param):
152 returns.append("%s=" % out_param_type)
153 else:
154 returns.append("%s" % out_param_type)
155
156 if has_return_value and len(command["returns"]) > 0:
157 out_param_type = param_type(domain_name, command["returns"][0])
158 if re.match(r"^[!?]", out_param_type[:1]):
159 out_param_type = out_param_type[1:]
160 out_param_type = "?%s" % out_param_type
161 else:
162 out_param_type = "undefined"
163 output_file.write(" * @return {!Promise<%s>}\n" % out_param_type)
164
165 output_file.write(" */\n")
166 output_file.write("Protocol.%sAgent.prototype.%s = function(%s) {};\n" %
167 (domain_name, command["name"], ", ".join(params)))
168
169 request_object_properties = []
170 request_type = "Protocol.%sAgent.%sRequest" % (domain_name, to_title_case(command["name"]))
171 for param in in_param_to_type:
172 request_object_properties.append("%s: %s" % (param, in_param_to_type[param]))
173 if request_object_properties:
174 output_file.write("/** @typedef {!{%s}} */\n" % (", ".join(request_object_properties)))
175 else:
176 output_file.write("/** @typedef {Object|undefined} */\n")
177 output_file.write("%s;\n" % request_type)
178
179 response_object_properties = []
180 response_type = "Protocol.%sAgent.%sResponse" % (domain_name, to_title_case(command["name"]))
181 for param in out_param_to_type:
182 response_object_properties.append("%s: %s" % (param, out_param_to_type[param]))
183 if response_object_properties:
184 output_file.write("/** @typedef {!{%s}} */\n" % (", ".join(response_object_properties)))
185 else:
186 output_file.write("/** @typedef {Object|undefined} */\n")
187 output_file.write("%s;\n" % response_type)
188
189 output_file.write("/**\n")
190 output_file.write(" * @param {!%s} obj\n" % request_type)
191 output_file.write(" * @return {!Promise<!%s>}" % response_type)
192 output_file.write(" */\n")
193 output_file.write("Protocol.%sAgent.prototype.invoke_%s = function(obj) {};\n" %
194 (domain_name, command["name"]))
195
196 if "types" in domain:
197 for type in domain["types"]:
198 if type["type"] == "object":
199 typedef_args = []
200 if "properties" in type:
201 for property in type["properties"]:
202 suffix = ""
203 if ("optional" in property):
204 suffix = "|undefined"
205 if "enum" in property:
206 enum_name = "Protocol.%s.%s%s" % (domain_name, type["id"], to_title_case(property["name"]))
207 output_file.write(generate_enum(enum_name, property))
208 typedef_args.append("%s:(%s%s)" % (property["name"], enum_name, suffix))
209 else:
210 typedef_args.append("%s:(%s%s)" % (property["name"], param_type(domain_name, property), suffix))
211 if (typedef_args):
212 output_file.write("\n/** @typedef {!{%s}} */\nProtocol.%s.%s;\n" %
213 (", ".join(typedef_args), domain_name, type["id"]))
214 else:
215 output_file.write("\n/** @typedef {!Object} */\nProtocol.%s.%s;\n" % (domain_name, type["id"]))
216 elif type["type"] == "string" and "enum" in type:
217 output_file.write(generate_enum("Protocol.%s.%s" % (domain_name, type["id"]), type))
218 elif type["type"] == "array":
219 output_file.write("\n/** @typedef {!Array<!%s>} */\nProtocol.%s.%s;\n" %
220 (param_type(domain_name, type["items"]), domain_name, type["id"]))
221 else:
222 output_file.write("\n/** @typedef {%s} */\nProtocol.%s.%s;\n" %
223 (type_traits[type["type"]], domain_name, type["id"]))
224
225 output_file.write("/** @interface */\n")
226 output_file.write("Protocol.%sDispatcher = function() {};\n" % domain_name)
227 if "events" in domain:
228 for event in domain["events"]:
229 params = []
230 if ("parameters" in event):
231 output_file.write("/**\n")
232 for param in event["parameters"]:
233 if ("optional" in param):
234 params.append("opt_%s" % param["name"])
235 output_file.write(" * @param {%s=} opt_%s\n" % (param_type(domain_name, param), param["name"]))
236 else:
237 params.append(param["name"])
238 output_file.write(" * @param {%s} %s\n" % (param_type(domain_name, param), param["name"]))
239 output_file.write(" */\n")
240 output_file.write("Protocol.%sDispatcher.prototype.%s = function(%s) {};\n" %
241 (domain_name, event["name"], ", ".join(params)))
242
243 for domain in domains:
244 domain_name = domain["domain"]
245 uppercase_length = 0
246 while uppercase_length < len(domain_name) and domain_name[uppercase_length].isupper():
247 uppercase_length += 1
248
249 output_file.write("/** @return {!Protocol.%sAgent}*/\n" % domain_name)
250 output_file.write("Protocol.TargetBase.prototype.%s = function(){};\n" %
251 (domain_name[:uppercase_length].lower() + domain_name[uppercase_length:] + "Agent"))
252
253 output_file.write("/**\n * @param {!Protocol.%sDispatcher} dispatcher\n */\n" % domain_name)
254 output_file.write("Protocol.TargetBase.prototype.register%sDispatcher = function(dispatcher) {}\n" % domain_name)
255
256 output_file.close()
257
258
259if __name__ == "__main__":
260 import sys
261 import os.path
262 program_name = os.path.basename(__file__)
263 if len(sys.argv) < 5 or sys.argv[1] != "-o":
264 sys.stderr.write("Usage: %s -o OUTPUT_FILE INPUT_FILE_1 INPUT_FILE_2\n" % program_name)
265 exit(1)
266 output_path = sys.argv[2]
267 input_path_1 = sys.argv[3]
268 input_path_2 = sys.argv[4]
269 generate_protocol_externs(output_path, input_path_1, input_path_2)