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

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

Powered by Google App Engine
This is Rietveld 408576698