1#!/usr/bin/env python 2# Copyright (c) 2011 Google Inc. All rights reserved. 3# Copyright (c) 2012 Intel Corporation. All rights reserved. 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions are 7# met: 8# 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. 18# 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. 30 31import os.path 32import sys 33import string 34import optparse 35import re 36try: 37 import json 38except ImportError: 39 import simplejson as json 40 41cmdline_parser = optparse.OptionParser() 42cmdline_parser.add_option("--output_js_dir") 43 44try: 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") 52except 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) 58 59 60def 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) 64 65 66def to_title_case(name): 67 return name[:1].upper() + name[1:] 68 69 70class 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) 89 90 91class 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) 97 98 def get_raw_type_js(self): 99 return self.raw_type_js_ 100 101 102class TypeMap: 103 def __init__(self, api): 104 self.map_ = {} 105 for json_domain in api["domains"]: 106 domain_name = json_domain["domain"] 107 108 domain_map = {} 109 self.map_[domain_name] = domain_map 110 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 116 117 def get(self, domain_name, type_name): 118 return self.map_[domain_name][type_name] 119 120 121def 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") 130 131 132def 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:] 140 141 return type_map.get(domain_name, type_name).get_raw_type_js() 142 143 144input_file = open(input_json_filename, "r") 145json_string = input_file.read() 146json_api = json.loads(json_string) 147 148 149class Templates: 150 def get_this_script_path_(absolute_path): 151 absolute_path = os.path.abspath(absolute_path) 152 components = [] 153 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)) 159 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) 163 164 return "/".join(components) 165 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""") 171 172 backend_js = string.Template(file_header_ + """ 173 174$domainInitializers 175""") 176 177 178type_map = TypeMap(json_api) 179 180 181class Generator: 182 backend_js_domain_initializer_list = [] 183 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() 189 190 Generator.backend_js_domain_initializer_list.append("// %s.\n" % domain_name) 191 Generator.backend_js_domain_initializer_list.append("InspectorBackend.register%sDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, \"%s\");\n" % (domain_name, domain_name)) 192 193 if "types" in json_domain: 194 for json_type in json_domain["types"]: 195 if "type" in json_type and json_type["type"] == "string" and "enum" in json_type: 196 enum_name = "%s.%s" % (domain_name, json_type["id"]) 197 Generator.process_enum(json_type, enum_name) 198 elif json_type["type"] == "object": 199 if "properties" in json_type: 200 for json_property in json_type["properties"]: 201 if "type" in json_property and json_property["type"] == "string" and "enum" in json_property: 202 enum_name = "%s.%s%s" % (domain_name, json_type["id"], to_title_case(json_property["name"])) 203 Generator.process_enum(json_property, enum_name) 204 205 if "events" in json_domain: 206 for json_event in json_domain["events"]: 207 Generator.process_event(json_event, domain_name) 208 209 if "commands" in json_domain: 210 for json_command in json_domain["commands"]: 211 Generator.process_command(json_command, domain_name) 212 213 Generator.backend_js_domain_initializer_list.append("\n") 214 215 @staticmethod 216 def process_enum(json_enum, enum_name): 217 enum_members = [] 218 for member in json_enum["enum"]: 219 enum_members.append("%s: \"%s\"" % (fix_camel_case(member), member)) 220 221 Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEnum(\"%s\", {%s});\n" % ( 222 enum_name, ", ".join(enum_members))) 223 224 @staticmethod 225 def process_event(json_event, domain_name): 226 event_name = json_event["name"] 227 228 json_parameters = json_event.get("parameters") 229 230 backend_js_event_param_list = [] 231 if json_parameters: 232 for parameter in json_parameters: 233 parameter_name = parameter["name"] 234 backend_js_event_param_list.append("\"%s\"" % parameter_name) 235 236 Generator.backend_js_domain_initializer_list.append("InspectorBackend.registerEvent(\"%s.%s\", [%s]);\n" % ( 237 domain_name, event_name, ", ".join(backend_js_event_param_list))) 238 239 @staticmethod 240 def process_command(json_command, domain_name): 241 json_command_name = json_command["name"] 242 243 js_parameters_text = "" 244 if "parameters" in json_command: 245 json_params = json_command["parameters"] 246 js_param_list = [] 247 248 for json_parameter in json_params: 249 json_param_name = json_parameter["name"] 250 js_bind_type = resolve_param_raw_type_js(json_parameter, domain_name) 251 252 optional = json_parameter.get("optional") 253 254 255 js_param_text = "{\"name\": \"%s\", \"type\": \"%s\", \"optional\": %s}" % ( 256 json_param_name, 257 js_bind_type, 258 ("true" if ("optional" in json_parameter and json_parameter["optional"]) else "false")) 259 260 js_param_list.append(js_param_text) 261 262 js_parameters_text = ", ".join(js_param_list) 263 264 265 backend_js_reply_param_list = [] 266 if "returns" in json_command: 267 for json_return in json_command["returns"]: 268 json_return_name = json_return["name"] 269 backend_js_reply_param_list.append("\"%s\"" % json_return_name) 270 271 js_reply_list = "[%s]" % ", ".join(backend_js_reply_param_list) 272 if "error" in json_command: 273 has_error_data_param = "true" 274 else: 275 has_error_data_param = "false" 276 277 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 279Generator.go() 280 281backend_js_file = open(output_js_dirname + "/InspectorBackendCommands.js", "w") 282 283backend_js_file.write(Templates.backend_js.substitute(None, 284 domainInitializers="".join(Generator.backend_js_domain_initializer_list))) 285 286backend_js_file.close() 287