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

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

Powered by Google App Engine
This is Rietveld 408576698