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