Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1075)

Side by Side Diff: content/browser/devtools/protocol/devtools_protocol_handler_generator.py

Issue 642263004: [DevTools] Make generated protocol structs wrappers around DictionaryValue (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fix that will be needed for browser protocol Created 6 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 # Copyright 2014 The Chromium Authors. All rights reserved. 2 # Copyright 2014 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be 3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file. 4 # found in the LICENSE file.
5 5
6 import sys 6 import sys
7 import string 7 import string
8 import json 8 import json
9 9
10 input_json_path = sys.argv[1] 10 input_json_path = sys.argv[1]
(...skipping 18 matching lines...) Expand all
29 29
30 #include "content/browser/devtools/devtools_protocol.h" 30 #include "content/browser/devtools/devtools_protocol.h"
31 #include "content/browser/devtools/protocol/devtools_protocol_client.h" 31 #include "content/browser/devtools/protocol/devtools_protocol_client.h"
32 32
33 namespace content { 33 namespace content {
34 34
35 class DevToolsProtocolHandlerImpl; 35 class DevToolsProtocolHandlerImpl;
36 36
37 namespace devtools { 37 namespace devtools {
38 38
39 template<typename T>
40 base::Value* CreateValue(const T& param) {
41 return new base::FundamentalValue(param);
42 }
43
44 template<class T>
45 base::Value* CreateValue(scoped_ptr<T>& param) {
46 return param.release();
47 }
48
49 template<class T>
50 base::Value* CreateValue(scoped_refptr<T> param) {
51 return param->ToValue().release();
52 }
53
54 template<typename T>
55 base::Value* CreateValue(const std::vector<T> param) {
56 base::ListValue* result = new base::ListValue();
57 for (auto& item : param) {
58 result->Append(CreateValue(item));
59 }
60 return result;
61 }
62
63 template<>
64 base::Value* CreateValue(const std::string& param);
65
39 ${types}\ 66 ${types}\
40 67
41 } // namespace devtools 68 } // namespace devtools
42 69
43 class DevToolsProtocolHandlerImpl : public DevToolsProtocol::Handler { 70 class DevToolsProtocolHandlerImpl : public DevToolsProtocol::Handler {
44 public: 71 public:
45 typedef DevToolsProtocolClient::Response Response; 72 typedef DevToolsProtocolClient::Response Response;
46 typedef DevToolsProtocolClient::ResponseStatus ResponseStatus; 73 typedef DevToolsProtocolClient::ResponseStatus ResponseStatus;
47 74
48 DevToolsProtocolHandlerImpl(); 75 DevToolsProtocolHandlerImpl();
49 virtual ~DevToolsProtocolHandlerImpl(); 76 virtual ~DevToolsProtocolHandlerImpl();
50 77
51 ${setters}\ 78 ${setters}\
52 79
53 private: 80 private:
54 ${friends}\
55
56 ${methods}\ 81 ${methods}\
57 82
58 ${fields}\ 83 ${fields}\
59 }; 84 };
60 85
61 } // namespace content 86 } // namespace content
62 87
63 #endif // CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_HANDLER_IMPL_H_ 88 #endif // CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_HANDLER_IMPL_H_
64 """) 89 """)
65 90
66 tmpl_typedef = string.Template("""\ 91 tmpl_typedef = string.Template("""\
67 namespace ${domain} { 92 namespace ${domain} {
68 typedef ${param_type} ${declared_name}; 93 typedef ${param_type} ${declared_name};
69 } // namespace ${domain} 94 } // namespace ${domain}
70 """) 95 """)
71 96
72 tmpl_struct = string.Template("""\ 97 tmpl_struct = string.Template("""\
73 namespace ${domain} { 98 namespace ${domain} {
74 struct ${declared_name} { 99 template<int MASK>
100 struct ${declared_name}Builder
101 : base::RefCounted<${declared_name}Builder<MASK>> {
75 public: 102 public:
76 ${declared_name}(); 103 enum {
104 kAllSet = 0,
105 ${fields_enum}\
106 };
77 107
78 ${methods}\ 108 ${methods}\
79 109
110 static scoped_refptr<${declared_name}Builder<kNoneSet>> Create() {
111 return new ${declared_name}Builder<kNoneSet>();
112 }
113
114 scoped_ptr<base::DictionaryValue> ToValue() {
115 COMPILE_ASSERT(MASK == kAllSet, required_properties_missing);
116 return make_scoped_ptr(dict_->DeepCopy());
117 }
118
80 private: 119 private:
81 friend class ::content::DevToolsProtocolHandlerImpl; 120 friend struct ${declared_name}Builder<0>;
82 121
83 ${fields}\ 122 ${declared_name}Builder() : dict_(new base::DictionaryValue()) {
123 }
124
125 template<class T> T* ThisAs() {
126 COMPILE_ASSERT(sizeof(*this) == sizeof(T), cannot_cast);
127 return reinterpret_cast<T*>(this);
128 }
129
130 scoped_ptr<base::DictionaryValue> dict_;
84 }; 131 };
132
133 typedef ${declared_name}Builder<0> ${declared_name};
134
85 } // namespace ${domain} 135 } // namespace ${domain}
86 """) 136 """)
87 137
88 tmpl_struct_setter = string.Template("""\ 138 tmpl_builder_setter_req = string.Template("""\
89 void set_${param}(${pass_type} ${param}); 139 scoped_refptr<${declared_name}Builder<MASK & ~k${Param}>>
140 set_${param}(${pass_type} ${param}) {
141 COMPILE_ASSERT(MASK & k${Param}, already_set);
142 dict_->Set("${proto_param}", CreateValue(${param}));
143 return ThisAs<${declared_name}Builder<MASK & ~k${Param}>>();
144 }
90 """) 145 """)
91 146
92 tmpl_struct_field = string.Template("""\ 147 tmpl_builder_setter_opt = string.Template("""\
93 ${param_type} ${param}_; 148 scoped_refptr<${declared_name}Builder<MASK>>
94 bool has_${param}_; 149 set_${param}(${pass_type} ${param}) {
150 dict_->Set("${proto_param}", CreateValue(${param}));
151 return this;
152 }
153 """)
154
155 tmpl_builder_enum = string.Template("""\
156 k${Param} = 1 << ${ordinal},
157 """)
158
159 tmpl_builder_none_set = string.Template("""\
160 kNoneSet = ${all_fields}
95 """) 161 """)
96 162
97 tmpl_enum = string.Template("""\ 163 tmpl_enum = string.Template("""\
98 namespace ${domain} { 164 namespace ${domain} {
99 namespace ${subdomain} { 165 namespace ${subdomain} {
100 ${values}\ 166 ${values}\
101 } // namespace ${subdomain} 167 } // namespace ${subdomain}
102 } // namespace ${domain} 168 } // namespace ${domain}
103 """) 169 """)
104 170
(...skipping 18 matching lines...) Expand all
123 Client(const RawMessageCallback& raw_message_callback); 189 Client(const RawMessageCallback& raw_message_callback);
124 virtual ~Client(); 190 virtual ~Client();
125 191
126 ${methods}\ 192 ${methods}\
127 }; 193 };
128 } // namespace ${domain} 194 } // namespace ${domain}
129 """) 195 """)
130 196
131 tmpl_event = string.Template("""\ 197 tmpl_event = string.Template("""\
132 void ${Command}( 198 void ${Command}(
133 const ${Command}Params& params); 199 scoped_refptr<${Command}Params> params);
134 """) 200 """)
135 201
136 tmpl_response = string.Template("""\ 202 tmpl_response = string.Template("""\
137 void Send${Command}Response( 203 void Send${Command}Response(
138 scoped_refptr<DevToolsProtocol::Command> command, 204 scoped_refptr<DevToolsProtocol::Command> command,
139 const ${Command}Response& params); 205 scoped_refptr<${Command}Response> params);
140 """) 206 """)
141 207
142 tmpl_setter = string.Template("""\ 208 tmpl_setter = string.Template("""\
143 void Set${Domain}Handler( 209 void Set${Domain}Handler(
144 devtools::${domain}::${Domain}Handler* ${domain}_handler); 210 devtools::${domain}::${Domain}Handler* ${domain}_handler);
145 """) 211 """)
146 212
147 tmpl_friend = string.Template("""\
148 friend class devtools::${domain}::Client;
149 """)
150
151 tmpl_callback = string.Template("""\ 213 tmpl_callback = string.Template("""\
152 scoped_refptr<DevToolsProtocol::Response> 214 scoped_refptr<DevToolsProtocol::Response>
153 On${Domain}${Command}( 215 On${Domain}${Command}(
154 scoped_refptr<DevToolsProtocol::Command> command); 216 scoped_refptr<DevToolsProtocol::Command> command);
155 """) 217 """)
156 218
157 tmpl_to_value = string.Template("""\
158 static base::DictionaryValue* ToValue(
159 const devtools::${domain}::${declared_name}& src);
160 """)
161
162 tmpl_field = string.Template("""\ 219 tmpl_field = string.Template("""\
163 devtools::${domain}::${Domain}Handler* ${domain}_handler_; 220 devtools::${domain}::${Domain}Handler* ${domain}_handler_;
164 """) 221 """)
165 222
166 template_cc = string.Template(header + """\ 223 template_cc = string.Template(header + """\
167 224
168 #include "content/browser/devtools/protocol/devtools_protocol_handler_impl.h" 225 #include "content/browser/devtools/protocol/devtools_protocol_handler_impl.h"
169 226
170 #include "base/bind.h" 227 #include "base/bind.h"
171 ${includes}\ 228 ${includes}\
(...skipping 10 matching lines...) Expand all
182 namespace { 239 namespace {
183 240
184 typedef DevToolsProtocolClient::ResponseStatus ResponseStatus; 241 typedef DevToolsProtocolClient::ResponseStatus ResponseStatus;
185 242
186 bool CreateCommonResponse( 243 bool CreateCommonResponse(
187 scoped_refptr<DevToolsProtocol::Command> command, 244 scoped_refptr<DevToolsProtocol::Command> command,
188 const DevToolsProtocolClient::Response& response, 245 const DevToolsProtocolClient::Response& response,
189 scoped_refptr<DevToolsProtocol::Response>* protocol_response) { 246 scoped_refptr<DevToolsProtocol::Response>* protocol_response) {
190 switch (response.status()) { 247 switch (response.status()) {
191 case ResponseStatus::RESPONSE_STATUS_FALLTHROUGH: 248 case ResponseStatus::RESPONSE_STATUS_FALLTHROUGH:
192 *protocol_response = NULL; 249 *protocol_response = nullptr;
193 break; 250 break;
194 case ResponseStatus::RESPONSE_STATUS_OK: 251 case ResponseStatus::RESPONSE_STATUS_OK:
195 return false; 252 return false;
196 case ResponseStatus::RESPONSE_STATUS_INVALID_PARAMS: 253 case ResponseStatus::RESPONSE_STATUS_INVALID_PARAMS:
197 *protocol_response = command->InvalidParamResponse(response.message()); 254 *protocol_response = command->InvalidParamResponse(response.message());
198 break; 255 break;
199 case ResponseStatus::RESPONSE_STATUS_INTERNAL_ERROR: 256 case ResponseStatus::RESPONSE_STATUS_INTERNAL_ERROR:
200 *protocol_response = command->InternalErrorResponse(response.message()); 257 *protocol_response = command->InternalErrorResponse(response.message());
201 break; 258 break;
202 case ResponseStatus::RESPONSE_STATUS_SERVER_ERROR: 259 case ResponseStatus::RESPONSE_STATUS_SERVER_ERROR:
203 *protocol_response = command->ServerErrorResponse(response.message()); 260 *protocol_response = command->ServerErrorResponse(response.message());
204 break; 261 break;
205 } 262 }
206 return true; 263 return true;
207 } 264 }
208 265
209 } // namespace 266 } // namespace
210 267
211 ${methods}\ 268 ${methods}\
212 269
213 namespace devtools { 270 namespace devtools {
214 271
272 template<>
273 base::Value* CreateValue(const std::string& param) {
274 return new base::StringValue(param);
275 }
276
215 ${types}\ 277 ${types}\
216 278
217 } // namespace devtools 279 } // namespace devtools
218 280
219 } // namespace content 281 } // namespace content
220 """) 282 """)
221 283
222 tmpl_include = string.Template("""\ 284 tmpl_include = string.Template("""\
223 #include "content/browser/devtools/protocol/${domain}_handler.h" 285 #include "content/browser/devtools/protocol/${domain}_handler.h"
224 """) 286 """)
225 287
226 tmpl_field_init = string.Template("${domain}_handler_(NULL)") 288 tmpl_field_init = string.Template("${domain}_handler_(nullptr)")
227 289
228 tmpl_setter_impl = string.Template("""\ 290 tmpl_setter_impl = string.Template("""\
229 void DevToolsProtocolHandlerImpl::Set${Domain}Handler( 291 void DevToolsProtocolHandlerImpl::Set${Domain}Handler(
230 devtools::${domain}::${Domain}Handler* ${domain}_handler) { 292 devtools::${domain}::${Domain}Handler* ${domain}_handler) {
231 DCHECK(!${domain}_handler_); 293 DCHECK(!${domain}_handler_);
232 ${domain}_handler_ = ${domain}_handler; 294 ${domain}_handler_ = ${domain}_handler;
233 ${initializations}\ 295 ${initializations}\
234 } 296 }
235 """) 297 """)
236 298
(...skipping 14 matching lines...) Expand all
251 313
252 tmpl_callback_impl = string.Template("""\ 314 tmpl_callback_impl = string.Template("""\
253 scoped_refptr<DevToolsProtocol::Response> 315 scoped_refptr<DevToolsProtocol::Response>
254 DevToolsProtocolHandlerImpl::On${Domain}${Command}( 316 DevToolsProtocolHandlerImpl::On${Domain}${Command}(
255 scoped_refptr<DevToolsProtocol::Command> command) { 317 scoped_refptr<DevToolsProtocol::Command> command) {
256 ${prep}\ 318 ${prep}\
257 Response response = ${domain}_handler_->${Command}(${args}); 319 Response response = ${domain}_handler_->${Command}(${args});
258 scoped_refptr<DevToolsProtocol::Response> protocol_response; 320 scoped_refptr<DevToolsProtocol::Response> protocol_response;
259 if (CreateCommonResponse(command, response, &protocol_response)) 321 if (CreateCommonResponse(command, response, &protocol_response))
260 return protocol_response; 322 return protocol_response;
261 base::DictionaryValue* dict = new base::DictionaryValue(); 323 base::DictionaryValue* result = new base::DictionaryValue();
262 ${wrap}\ 324 ${wrap}\
263 return command->SuccessResponse(dict); 325 return command->SuccessResponse(result);
264 } 326 }
265 """) 327 """)
266 328
329 tmpl_wrap = string.Template("""\
330 result->Set("${proto_param}", devtools::CreateValue(out_${param}));
331 """)
332
267 tmpl_callback_async_impl = string.Template("""\ 333 tmpl_callback_async_impl = string.Template("""\
268 scoped_refptr<DevToolsProtocol::Response> 334 scoped_refptr<DevToolsProtocol::Response>
269 DevToolsProtocolHandlerImpl::On${Domain}${Command}( 335 DevToolsProtocolHandlerImpl::On${Domain}${Command}(
270 scoped_refptr<DevToolsProtocol::Command> command) { 336 scoped_refptr<DevToolsProtocol::Command> command) {
271 ${prep}\ 337 ${prep}\
272 return ${domain}_handler_->${Command}(${args}); 338 return ${domain}_handler_->${Command}(${args});
273 } 339 }
274 """) 340 """)
275 341
276 params_prep = """\ 342 params_prep = """\
277 base::DictionaryValue* params = command->params(); 343 base::DictionaryValue* params = command->params();
278 """ 344 """
279 345
280 tmpl_prep_req = string.Template("""\ 346 tmpl_prep_req = string.Template("""\
281 ${param_type} in_${param}${init}; 347 ${param_type} in_${param}${init};
282 if (!params || 348 if (!params || !params->Get${Type}("${proto_param}", &in_${param}))
283 !params->Get${Type}("${proto_param}", &in_${param}))
284 return command->InvalidParamResponse("${proto_param}"); 349 return command->InvalidParamResponse("${proto_param}");
285 """) 350 """)
286 351
287 tmpl_prep_req_list = string.Template("""\ 352 tmpl_prep_req_list = string.Template("""\
288 base::ListValue* list_${param} = NULL; 353 base::ListValue* list_${param} = nullptr;
289 if (!params || !params->GetList("${proto_param}", &list_${param})) 354 if (!params || !params->GetList("${proto_param}", &list_${param}))
290 return command->InvalidParamResponse("${proto_param}"); 355 return command->InvalidParamResponse("${proto_param}");
291 ${param_type} in_${param}; 356 std::vector<${item_type}> in_${param};
292 for (base::ListValue::const_iterator it = 357 for (base::ListValue::const_iterator it =
293 list_${param}->begin(); it != list_${param}->end(); ++it) { 358 list_${param}->begin(); it != list_${param}->end(); ++it) {
294 ${item_type} item${item_init}; 359 ${item_type} item${item_init};
295 if (!(*it)->GetAs${ItemType}(&item)) 360 if (!(*it)->GetAs${ItemType}(&item))
296 return command->InvalidParamResponse("${proto_param}"); 361 return command->InvalidParamResponse("${proto_param}");
297 in_${param}.push_back(item); 362 in_${param}.push_back(item);
298 } 363 }
299 """) 364 """)
300 365
301 tmpl_prep_opt = string.Template("""\ 366 tmpl_prep_opt = string.Template("""\
302 ${param_type} in_${param}${init}; 367 ${param_type} in_${param}${init};
303 bool ${param}_found = params && params->Get${Type}( 368 bool ${param}_found = params && params->Get${Type}(
304 "${proto_param}", 369 "${proto_param}",
305 &in_${param}); 370 &in_${param});
306 """) 371 """)
307 372
308 tmpl_prep_output = string.Template("""\ 373 tmpl_prep_output = string.Template("""\
309 ${param_type} out_${param}${init}; 374 ${param_type} out_${param}${init};
310 """) 375 """)
311 376
312 tmpl_arg_req = string.Template("in_${param}") 377 tmpl_arg_req = string.Template("in_${param}")
313 378
314 tmpl_arg_opt = string.Template( 379 tmpl_arg_opt = string.Template(
315 "${param}_found ?\n &in_${param} : NULL") 380 "${param}_found ? &in_${param} : nullptr")
316
317 tmpl_arg_output = string.Template("&out_${param}")
318
319 tmpl_to_value_impl = string.Template("""\
320 // static
321 base::DictionaryValue* DevToolsProtocolHandlerImpl::ToValue(
322 const devtools::${domain}::${declared_name}& src) {
323 base::DictionaryValue* dict = new base::DictionaryValue();
324 ${dchecks}\
325 ${wrap}\
326 return dict;
327 }
328 """)
329
330 tmpl_dcheck = string.Template("""\
331 DCHECK(${cond_name});
332 """)
333
334 tmpl_struct_impl = string.Template("""\
335 namespace ${domain} {
336
337 ${declared_name}::${declared_name}()${fields} {
338 }
339
340 ${methods}\
341
342 } // namespace ${domain}
343 """)
344
345 tmpl_struct_field_init = string.Template("has_${param}_(false)")
346
347 tmpl_struct_setter_impl = string.Template("""\
348 void ${declared_name}::set_${param}(
349 ${pass_type} ${param}) {
350 ${param}_ = ${param};
351 has_${param}_ = true;
352 }
353 """)
354 381
355 tmpl_client_impl = string.Template("""\ 382 tmpl_client_impl = string.Template("""\
356 namespace ${domain} { 383 namespace ${domain} {
357 384
358 Client::Client(const RawMessageCallback& raw_message_callback) 385 Client::Client(const RawMessageCallback& raw_message_callback)
359 : DevToolsProtocolClient(raw_message_callback) { 386 : DevToolsProtocolClient(raw_message_callback) {
360 } 387 }
361 388
362 Client::~Client() { 389 Client::~Client() {
363 } 390 }
364 391
365 ${methods}\ 392 ${methods}\
366 393
367 } // namespace ${domain} 394 } // namespace ${domain}
368 """) 395 """)
369 396
370 tmpl_event_impl = string.Template("""\ 397 tmpl_event_impl = string.Template("""\
371 void Client::${Command}( 398 void Client::${Command}(
372 const ${Command}Params& params) { 399 scoped_refptr<${Command}Params> params) {
373 SendNotification("${Domain}.${command}", 400 SendNotification("${Domain}.${command}",
374 DevToolsProtocolHandlerImpl::ToValue(params)); 401 params->ToValue().Pass());
375 } 402 }
376 """) 403 """)
377 404
378 tmpl_response_impl = string.Template("""\ 405 tmpl_response_impl = string.Template("""\
379 void Client::Send${Command}Response( 406 void Client::Send${Command}Response(
380 scoped_refptr<DevToolsProtocol::Command> command, 407 scoped_refptr<DevToolsProtocol::Command> command,
381 const ${Command}Response& params) { 408 scoped_refptr<${Command}Response> params) {
382 SendAsyncResponse( 409 SendAsyncResponse(command->SuccessResponse(params->ToValue().release()));
383 command->SuccessResponse(DevToolsProtocolHandlerImpl::ToValue(params)));
384 } 410 }
385 """) 411 """)
386 412
387 tmpl_wrap = string.Template("""\
388 dict->Set${Type}("${proto_param}", ${var_name});
389 """)
390
391 tmpl_wrap_dict = string.Template("""\
392 dict->Set("${proto_param}",
393 DevToolsProtocolHandlerImpl::ToValue(${var_name}));
394 """)
395
396 tmpl_wrap_obj = string.Template("""\
397 dict->Set("${proto_param}", ${var_name});
398 """)
399
400 tmpl_wrap_list = string.Template("""\
401 base::ListValue* list_${param} = new base::ListValue();
402 for (${param_type}::const_iterator it =
403 ${var_name}.begin(); it != ${var_name}.end(); ++it) {
404 ${append}\
405 }
406 dict->Set("${proto_param}", list_${param});
407 """)
408
409 tmpl_append = string.Template("""\
410 list_${param}->Append${Type}(*it);
411 """)
412
413 tmpl_append_dict = string.Template("""\
414 list_${param}->Append(DevToolsProtocolHandlerImpl::ToValue(*it));
415 """)
416
417 tmpl_append_obj = string.Template("""\
418 list_${param}->Append(*it);
419 """)
420
421 tmpl_wrap_opt = string.Template("""\
422 if (${cond_name})
423 dict->Set${Type}("${proto_param}", ${var_name});
424 """)
425
426 tmpl_typename = string.Template("devtools::${domain}::${declared_name}") 413 tmpl_typename = string.Template("devtools::${domain}::${declared_name}")
427 414
428 def Capitalize(s): 415 def Capitalize(s):
429 return s[:1].upper() + s[1:] 416 return s[:1].upper() + s[1:]
430 417
431 def Decapitalize(s):
432 return s.lower()
433
434 def Uncamelcase(s): 418 def Uncamelcase(s):
435 result = "" 419 result = ""
436 for i, c in enumerate(s): 420 for i, c in enumerate(s):
437 if c.isupper(): 421 if c.isupper():
438 if (i > 0) and ((i < len(s)-1) and s[i+1].islower() or s[i-1].islower()): 422 if (i > 0) and ((i < len(s)-1) and s[i+1].islower() or s[i-1].islower()):
439 result += "_" 423 result += "_"
440 result += c.lower() 424 result += c.lower()
441 else: 425 else:
442 result += c 426 result += c
443 return result 427 return result
444 428
445 types = {} 429 types = {}
446 json_api = json.loads(open(input_json_path, "r").read()) 430 json_api = json.loads(open(input_json_path, "r").read())
447 type_decls = [] 431 type_decls = []
448 type_impls = [] 432 type_impls = []
449 handler_methods = [] 433 handler_methods = []
450 handler_method_impls = [] 434 handler_method_impls = []
451 435
452 for json_domain in json_api["domains"]: 436 for json_domain in json_api["domains"]:
453 if "types" in json_domain: 437 if "types" in json_domain:
454 for json_type in json_domain["types"]: 438 for json_type in json_domain["types"]:
455 types["%s.%s" % (json_domain["domain"], json_type["id"])] = json_type 439 types["%s.%s" % (json_domain["domain"], json_type["id"])] = json_type
456 440
457 def DeclareStruct(json_properties, mapping): 441 def DeclareStruct(json_properties, mapping):
458 methods = [] 442 methods = []
459 fields = [] 443 fields_enum = []
460 fields_init = [] 444 enum_items = []
461 method_impls = [] 445 req_fields_num = 0
462 dchecks = []
463 wrap = []
464 for json_prop in json_properties: 446 for json_prop in json_properties:
465 prop_map = mapping.copy() 447 prop_map = mapping.copy()
466 prop_map["proto_param"] = json_prop["name"] 448 prop_map["proto_param"] = json_prop["name"]
467 prop_map["param"] = Uncamelcase(json_prop["name"]) 449 prop_map["param"] = Uncamelcase(json_prop["name"])
468 prop_map["var_name"] = "src.%s_" % prop_map["param"] 450 prop_map["Param"] = Capitalize(json_prop["name"])
469 prop_map["cond_name"] = "src.has_%s_" % prop_map["param"]
470 ResolveType(json_prop, prop_map) 451 ResolveType(json_prop, prop_map)
471 prop_map["declared_name"] = mapping["declared_name"] 452 prop_map["declared_name"] = mapping["declared_name"]
472 methods.append(tmpl_struct_setter.substitute(prop_map))
473 fields.append(tmpl_struct_field.substitute(prop_map))
474 fields_init.append(tmpl_struct_field_init.substitute(prop_map))
475 method_impls.append(tmpl_struct_setter_impl.substitute(prop_map))
476 if json_prop.get("optional"): 453 if json_prop.get("optional"):
477 if param_map["Type"] in ["List", "Dictionary"]: 454 methods.append(tmpl_builder_setter_opt.substitute(prop_map))
478 # TODO(vkuzkokov) Implement.
479 raise Exception(
480 "Optional array and object properties are not implemented")
481 wrap.append(tmpl_wrap_opt.substitute(prop_map))
482 else: 455 else:
483 dchecks.append(tmpl_dcheck.substitute(prop_map)); 456 methods.append(tmpl_builder_setter_req.substitute(prop_map))
484 if not "wrap" in prop_map: 457 enum_items.append("k%s" % prop_map["Param"]);
485 raise Exception("Arrays of arrays are not implemented") 458 fields_enum.append(tmpl_builder_enum.substitute(prop_map,
486 wrap.append(prop_map["wrap"]) 459 ordinal = req_fields_num))
460 req_fields_num += 1
487 461
462 all_fields = "kAllSet"
463 if len(enum_items) > 0:
464 all_fields = " | ".join(enum_items)
465 fields_enum.append(tmpl_builder_none_set.substitute(mapping,
466 all_fields = all_fields))
488 type_decls.append(tmpl_struct.substitute(mapping, 467 type_decls.append(tmpl_struct.substitute(mapping,
489 methods = "".join(methods), 468 methods = "\n".join(methods),
490 fields = "".join(fields))) 469 fields_enum = "".join(fields_enum)))
491 fields_init_str = ""
492 if len(fields_init) > 0:
493 fields_init_str = "\n : " + (",\n ".join(fields_init))
494 type_impls.append(tmpl_struct_impl.substitute(mapping,
495 fields = fields_init_str,
496 methods = "\n".join(method_impls)))
497 handler_methods.append(tmpl_to_value.substitute(mapping))
498 handler_method_impls.append(tmpl_to_value_impl.substitute(mapping,
499 dchecks = "".join(dchecks),
500 wrap = "".join(wrap)))
501 470
502 def ResolveRef(json, mapping): 471 def ResolveRef(json, mapping):
503 dot_pos = json["$ref"].find(".") 472 dot_pos = json["$ref"].find(".")
504 if dot_pos == -1: 473 if dot_pos == -1:
505 domain_name = mapping["Domain"] 474 domain_name = mapping["Domain"]
506 type_name = json["$ref"] 475 type_name = json["$ref"]
507 else: 476 else:
508 domain_name = json["$ref"][:dot_pos] 477 domain_name = json["$ref"][:dot_pos]
509 type_name = json["$ref"][dot_pos + 1:] 478 type_name = json["$ref"][dot_pos + 1:]
510 json_type = types["%s.%s" % (domain_name, type_name)] 479 json_type = types["%s.%s" % (domain_name, type_name)]
511 mapping["declared_name"] = Capitalize(type_name) 480 mapping["declared_name"] = Capitalize(type_name)
512 mapping["Domain"] = domain_name 481 mapping["Domain"] = domain_name
513 mapping["domain"] = Decapitalize(domain_name) 482 mapping["domain"] = Uncamelcase(domain_name)
514 mapping["param_type"] = tmpl_typename.substitute(mapping) 483 mapping["param_type"] = tmpl_typename.substitute(mapping)
515 if json_type.get("enum"): 484 if json_type.get("enum"):
516 # TODO(vkuzkokov) Implement. Approximate template: 485 # TODO(vkuzkokov) Implement. Approximate template:
517 # namespace ${domain} { const char k${declared_name}${Value}; } 486 # namespace ${domain} { const char k${declared_name}${Value}; }
518 raise Exception("Named enumerations are not implemented") 487 raise Exception("Named enumerations are not implemented")
519 ResolveType(json_type, mapping) 488 ResolveType(json_type, mapping)
520 if not "___struct_declared" in json_type: 489 if not "___struct_declared" in json_type:
521 json_type["___struct_declared"] = True; 490 json_type["___struct_declared"] = True;
522 if (json_type.get("type") == "object") and ("properties" in json_type): 491 if (json_type.get("type") == "object") and ("properties" in json_type):
523 DeclareStruct(json_type["properties"], mapping) 492 DeclareStruct(json_type["properties"], mapping)
524 else: 493 else:
525 type_decls.append(tmpl_typedef.substitute(mapping)) 494 type_decls.append(tmpl_typedef.substitute(mapping))
526 mapping["param_type"] = tmpl_typename.substitute(mapping)
527 495
528 def ResolveArray(json, mapping): 496 def ResolveArray(json, mapping):
529 items_map = mapping.copy() 497 items_map = mapping.copy()
530 ResolveType(json["items"], items_map) 498 ResolveType(json["items"], items_map)
531 mapping["param_type"] = "std::vector<%s>" % items_map["param_type"] 499 mapping["param_type"] = "std::vector<%s>" % items_map["param_type"]
532 mapping["Type"] = "List" 500 mapping["Type"] = "List"
533 if "append" in items_map:
534 mapping["wrap"] = tmpl_wrap_list.substitute(mapping,
535 append = items_map["append"])
536 mapping["pass_type"] = "const %s&" % mapping["param_type"] 501 mapping["pass_type"] = "const %s&" % mapping["param_type"]
537 mapping["prep_req"] = tmpl_prep_req_list.substitute(mapping, 502 mapping["prep_req"] = tmpl_prep_req_list.substitute(mapping,
538 item_type = items_map["param_type"], 503 item_type = items_map["param_type"],
539 item_init = items_map["init"], 504 item_init = items_map["init"],
540 ItemType = items_map["Type"]) 505 ItemType = items_map["Type"])
541 # TODO(vkuzkokov) mapping["append"]: template for array of arrays. 506 mapping["arg_out"] = "&out_%s" % mapping["param"]
542 507
543 def ResolveObject(json, mapping): 508 def ResolveObject(json, mapping):
544 mapping["Type"] = "Dictionary" 509 mapping["Type"] = "Dictionary"
545 if "properties" in json: 510 if "properties" in json:
546 if not "declared_name" in mapping: 511 if not "declared_name" in mapping:
547 mapping["declared_name"] = ("%s%s" % 512 mapping["declared_name"] = ("%s%s" %
548 (mapping["Command"], Capitalize(mapping["proto_param"]))) 513 (mapping["Command"], Capitalize(mapping["proto_param"])))
549 mapping["param_type"] = tmpl_typename.substitute(mapping) 514 mapping["param_type"] = ("scoped_refptr<%s>" %
515 tmpl_typename.substitute(mapping))
550 DeclareStruct(json["properties"], mapping) 516 DeclareStruct(json["properties"], mapping)
551 mapping["append"] = tmpl_append_dict.substitute(mapping) 517 else:
552 mapping["wrap"] = tmpl_wrap_dict.substitute(mapping) 518 mapping["param_type"] = ("scoped_refptr<%s>" %
553 mapping["pass_type"] = "const %s&" % mapping["param_type"] 519 tmpl_typename.substitute(mapping))
520 mapping["pass_type"] = mapping["param_type"]
521 mapping["arg_out"] = "&out_%s" % mapping["param"]
554 else: 522 else:
555 mapping["param_type"] = "base::DictionaryValue*" 523 mapping["param_type"] = "base::DictionaryValue"
556 mapping["append"] = tmpl_append_obj.substitute(mapping) 524 mapping["pass_type"] = "scoped_ptr<base::DictionaryValue>"
557 mapping["wrap"] = tmpl_wrap_obj.substitute(mapping) 525 mapping["arg_out"] = "out_%s.get()" % mapping["param"]
558 mapping["pass_type"] = mapping["param_type"]
559 526
560 def ResolvePrimitive(json, mapping): 527 def ResolvePrimitive(json, mapping):
561 jsonrpc_type = json["type"] 528 jsonrpc_type = json["type"]
562 if jsonrpc_type == "boolean": 529 if jsonrpc_type == "boolean":
563 mapping["param_type"] = "bool" 530 mapping["param_type"] = "bool"
564 mapping["Type"] = "Boolean" 531 mapping["Type"] = "Boolean"
565 mapping["init"] = " = false" 532 mapping["init"] = " = false"
566 elif jsonrpc_type == "integer": 533 elif jsonrpc_type == "integer":
567 mapping["param_type"] = "int" 534 mapping["param_type"] = "int"
568 mapping["Type"] = "Integer" 535 mapping["Type"] = "Integer"
(...skipping 19 matching lines...) Expand all
588 Value = Capitalize(enum_value))) 555 Value = Capitalize(enum_value)))
589 value_defs.append(tmpl_enum_value_def.substitute(mapping, 556 value_defs.append(tmpl_enum_value_def.substitute(mapping,
590 value = enum_value, 557 value = enum_value,
591 Value = Capitalize(enum_value))) 558 Value = Capitalize(enum_value)))
592 type_decls.append(tmpl_enum.substitute(mapping, 559 type_decls.append(tmpl_enum.substitute(mapping,
593 values = "".join(values))) 560 values = "".join(values)))
594 type_impls.append(tmpl_enum.substitute(mapping, 561 type_impls.append(tmpl_enum.substitute(mapping,
595 values = "".join(value_defs))) 562 values = "".join(value_defs)))
596 else: 563 else:
597 raise Exception("Unknown type: %s" % json_type) 564 raise Exception("Unknown type: %s" % json_type)
598 mapping["wrap"] = tmpl_wrap.substitute(mapping)
599 mapping["append"] = tmpl_append.substitute(mapping)
600 mapping["prep_req"] = tmpl_prep_req.substitute(mapping) 565 mapping["prep_req"] = tmpl_prep_req.substitute(mapping)
601 if jsonrpc_type != "string": 566 if jsonrpc_type != "string":
602 mapping["pass_type"] = mapping["param_type"] 567 mapping["pass_type"] = mapping["param_type"]
568 mapping["arg_out"] = "&out_%s" % mapping["param"]
603 569
604 def ResolveType(json, mapping): 570 def ResolveType(json, mapping):
605 mapping["init"] = "" 571 mapping["init"] = ""
606 if "$ref" in json: 572 if "$ref" in json:
607 ResolveRef(json, mapping) 573 ResolveRef(json, mapping)
608 elif "type" in json: 574 elif "type" in json:
609 jsonrpc_type = json["type"] 575 jsonrpc_type = json["type"]
610 if jsonrpc_type == "array": 576 if jsonrpc_type == "array":
611 ResolveArray(json, mapping) 577 ResolveArray(json, mapping)
612 elif jsonrpc_type == "object": 578 elif jsonrpc_type == "object":
613 ResolveObject(json, mapping) 579 ResolveObject(json, mapping)
614 else: 580 else:
615 ResolvePrimitive(json, mapping) 581 ResolvePrimitive(json, mapping)
616 else: 582 else:
617 raise Exception("Unknown type at %s.%s %s" % 583 raise Exception("Unknown type at %s.%s %s" %
618 (mapping["Domain"], mapping["command"], mapping["proto_param"])) 584 (mapping["Domain"], mapping["command"], mapping["proto_param"]))
619 585
620 setters = [] 586 setters = []
621 friends = []
622 fields = [] 587 fields = []
623 588
624 includes = [] 589 includes = []
625 fields_init = [] 590 fields_init = []
626 591
627 for json_domain in json_api["domains"]: 592 for json_domain in json_api["domains"]:
628 domain_map = {} 593 domain_map = {}
629 domain_map["Domain"] = json_domain["domain"] 594 domain_map["Domain"] = json_domain["domain"]
630 domain_map["domain"] = Decapitalize(json_domain["domain"]) 595 domain_map["domain"] = Uncamelcase(json_domain["domain"])
631 596
632 initializations = [] 597 initializations = []
633 client_methods = [] 598 client_methods = []
634 client_method_impls = [] 599 client_method_impls = []
635 domain_empty = True 600 domain_empty = True
636 domain_needs_client = False 601 domain_needs_client = False
637 602
638 if "commands" in json_domain: 603 if "commands" in json_domain:
639 for json_command in json_domain["commands"]: 604 for json_command in json_domain["commands"]:
640 if (not ("handlers" in json_command) or 605 if (not ("handlers" in json_command) or
641 not ("browser" in json_command["handlers"])): 606 not ("browser" in json_command["handlers"])):
642 continue 607 continue
643 domain_empty = False 608 domain_empty = False
644 609
645 command_map = domain_map.copy() 610 command_map = domain_map.copy()
646 command_map["command"] = json_command["name"] 611 command_map["command"] = json_command["name"]
647 command_map["Command"] = Capitalize(json_command["name"]) 612 command_map["Command"] = Capitalize(json_command["name"])
648 613
649 prep = [] 614 prep = []
650 args = [] 615 args = []
651 616
652 if "parameters" in json_command: 617 if "parameters" in json_command:
653 for json_param in json_command["parameters"]: 618 for json_param in json_command["parameters"]:
654 param_map = command_map.copy() 619 param_map = command_map.copy()
655 param_map["proto_param"] = json_param["name"] 620 param_map["proto_param"] = json_param["name"]
656 param_map["param"] = Uncamelcase(json_param["name"]) 621 param_map["param"] = Uncamelcase(json_param["name"])
657 param_map["var_name"] = "in_%s" % param_map["param"]
658 622
659 ResolveType(json_param, param_map) 623 ResolveType(json_param, param_map)
660 if len(prep) == 0: 624 if len(prep) == 0:
661 prep.append(params_prep) 625 prep.append(params_prep)
662 if json_param.get("optional"): 626 if json_param.get("optional"):
663 if param_map["Type"] in ["List", "Dictionary"]: 627 if param_map["Type"] in ["List", "Dictionary"]:
664 # TODO(vkuzkokov) Implement transformation of base::ListValue 628 # TODO(vkuzkokov) Implement transformation of base::ListValue
665 # to std::vector and base::DictonaryValue to struct. 629 # to std::vector and base::DictonaryValue to struct.
666 raise Exception( 630 raise Exception(
667 "Optional array and object parameters are not implemented") 631 "Optional array and object parameters are not implemented")
(...skipping 20 matching lines...) Expand all
688 args = "\n " + ",\n ".join(args))) 652 args = "\n " + ",\n ".join(args)))
689 client_methods.append(tmpl_response.substitute(command_map)) 653 client_methods.append(tmpl_response.substitute(command_map))
690 client_method_impls.append(tmpl_response_impl.substitute(command_map)) 654 client_method_impls.append(tmpl_response_impl.substitute(command_map))
691 else: 655 else:
692 wrap = [] 656 wrap = []
693 if "returns" in json_command: 657 if "returns" in json_command:
694 for json_param in json_command["returns"]: 658 for json_param in json_command["returns"]:
695 param_map = command_map.copy() 659 param_map = command_map.copy()
696 param_map["proto_param"] = json_param["name"] 660 param_map["proto_param"] = json_param["name"]
697 param_map["param"] = Uncamelcase(json_param["name"]) 661 param_map["param"] = Uncamelcase(json_param["name"])
698 param_map["var_name"] = "out_%s" % param_map["param"]
699 662
700 if json_param.get("optional"): 663 if json_param.get("optional"):
701 # TODO(vkuzkokov) Implement Optional<T> for value types. 664 # TODO(vkuzkokov) Implement Optional<T> for value types.
702 raise Exception("Optional return values are not implemented") 665 raise Exception("Optional return values are not implemented")
703 ResolveType(json_param, param_map) 666 ResolveType(json_param, param_map)
704 prep.append(tmpl_prep_output.substitute(param_map)) 667 prep.append(tmpl_prep_output.substitute(param_map))
705 args.append(tmpl_arg_output.substitute(param_map)) 668 args.append(param_map["arg_out"])
706 if not "wrap" in param_map: 669 wrap.append(tmpl_wrap.substitute(param_map))
707 raise Exception("Arrays of arrays are not implemented")
708 wrap.append(param_map["wrap"])
709 670
710 args_str = "" 671 args_str = ""
711 if len(args) > 0: 672 if len(args) > 0:
712 args_str = "\n " + ",\n ".join(args) 673 args_str = "\n " + ",\n ".join(args)
713 handler_method_impls.append(tmpl_callback_impl.substitute(command_map, 674 handler_method_impls.append(tmpl_callback_impl.substitute(command_map,
714 prep = "".join(prep), 675 prep = "".join(prep),
715 args = args_str, 676 args = args_str,
716 wrap = "".join(wrap))) 677 wrap = "".join(wrap)))
717 678
718 initializations.append(tmpl_register.substitute(command_map)) 679 initializations.append(tmpl_register.substitute(command_map))
(...skipping 23 matching lines...) Expand all
742 if domain_empty: 703 if domain_empty:
743 continue 704 continue
744 type_decls.append(tmpl_handler.substitute(domain_map)) 705 type_decls.append(tmpl_handler.substitute(domain_map))
745 setters.append(tmpl_setter.substitute(domain_map)) 706 setters.append(tmpl_setter.substitute(domain_map))
746 fields.append(tmpl_field.substitute(domain_map)) 707 fields.append(tmpl_field.substitute(domain_map))
747 includes.append(tmpl_include.substitute(domain_map)) 708 includes.append(tmpl_include.substitute(domain_map))
748 fields_init.append(tmpl_field_init.substitute(domain_map)) 709 fields_init.append(tmpl_field_init.substitute(domain_map))
749 if domain_needs_client: 710 if domain_needs_client:
750 type_decls.append(tmpl_client.substitute(domain_map, 711 type_decls.append(tmpl_client.substitute(domain_map,
751 methods = "".join(client_methods))) 712 methods = "".join(client_methods)))
752 friends.append(tmpl_friend.substitute(domain_map))
753 initializations.append(tmpl_init_client.substitute(domain_map)) 713 initializations.append(tmpl_init_client.substitute(domain_map))
754 type_impls.append(tmpl_client_impl.substitute(domain_map, 714 type_impls.append(tmpl_client_impl.substitute(domain_map,
755 methods = "\n".join(client_method_impls))) 715 methods = "\n".join(client_method_impls)))
756 handler_method_impls.append(tmpl_setter_impl.substitute(domain_map, 716 handler_method_impls.append(tmpl_setter_impl.substitute(domain_map,
757 initializations = "".join(initializations))) 717 initializations = "".join(initializations)))
758 718
759 719
760 output_h_file = open(output_h_path, "w") 720 output_h_file = open(output_h_path, "w")
761 output_cc_file = open(output_cc_path, "w") 721 output_cc_file = open(output_cc_path, "w")
762 722
763 output_h_file.write(template_h.substitute({}, 723 output_h_file.write(template_h.substitute({},
764 types = "\n".join(type_decls), 724 types = "\n".join(type_decls),
765 setters = "".join(setters), 725 setters = "".join(setters),
766 friends = "".join(friends),
767 methods = "".join(handler_methods), 726 methods = "".join(handler_methods),
768 fields = "".join(fields))) 727 fields = "".join(fields)))
769 output_h_file.close() 728 output_h_file.close()
770 729
771 output_cc_file.write(template_cc.substitute({}, 730 output_cc_file.write(template_cc.substitute({},
772 includes = "".join(sorted(includes)), 731 includes = "".join(sorted(includes)),
773 fields_init = ",\n ".join(fields_init), 732 fields_init = ",\n ".join(fields_init),
774 methods = "\n".join(handler_method_impls), 733 methods = "\n".join(handler_method_impls),
775 types = "\n".join(type_impls))) 734 types = "\n".join(type_impls)))
776 output_cc_file.close() 735 output_cc_file.close()
OLDNEW
« no previous file with comments | « content/browser/devtools/protocol/devtools_protocol_client.cc ('k') | content/browser/devtools/protocol/page_handler.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698