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

Side by Side Diff: third_party/chrome/tools/cc_generator.py

Issue 12261015: Import chrome idl into third_party (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 7 years, 10 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 | Annotate | Revision Log
« no previous file with comments | « third_party/chrome/tools/README ('k') | third_party/chrome/tools/code.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 from code import Code
6 from model import PropertyType, Type
7 import cpp_util
8 import model
9 import schema_util
10 import sys
11 import util_cc_helper
12
13 class CCGenerator(object):
14 """A .cc generator for a namespace.
15 """
16 def __init__(self, namespace, cpp_type_generator):
17 self._type_helper = cpp_type_generator
18 self._namespace = namespace
19 self._target_namespace = (
20 self._type_helper.GetCppNamespaceName(self._namespace))
21 self._util_cc_helper = (
22 util_cc_helper.UtilCCHelper(self._type_helper))
23
24 def Generate(self):
25 """Generates a Code object with the .cc for a single namespace.
26 """
27 c = Code()
28 (c.Append(cpp_util.CHROMIUM_LICENSE)
29 .Append()
30 .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
31 .Append()
32 .Append(self._util_cc_helper.GetIncludePath())
33 .Append('#include "base/json/json_writer.h"')
34 .Append('#include "base/logging.h"')
35 .Append('#include "base/string_number_conversions.h"')
36 .Append('#include "%s/%s.h"' %
37 (self._namespace.source_file_dir, self._namespace.unix_name))
38 .Cblock(self._type_helper.GenerateIncludes(include_soft=True))
39 .Concat(self._type_helper.GetRootNamespaceStart())
40 .Cblock(self._type_helper.GetNamespaceStart())
41 )
42 if self._namespace.properties:
43 (c.Append('//')
44 .Append('// Properties')
45 .Append('//')
46 .Append()
47 )
48 for property in self._namespace.properties.values():
49 property_code = self._type_helper.GeneratePropertyValues(
50 property,
51 'const %(type)s %(name)s = %(value)s;',
52 nodoc=True)
53 if property_code:
54 c.Cblock(property_code)
55 if self._namespace.types:
56 (c.Append('//')
57 .Append('// Types')
58 .Append('//')
59 .Append()
60 .Cblock(self._GenerateTypes(None, self._namespace.types.values()))
61 )
62 if self._namespace.functions:
63 (c.Append('//')
64 .Append('// Functions')
65 .Append('//')
66 .Append()
67 )
68 for function in self._namespace.functions.values():
69 c.Cblock(self._GenerateFunction(function))
70 if self._namespace.events:
71 (c.Append('//')
72 .Append('// Events')
73 .Append('//')
74 .Append()
75 )
76 for event in self._namespace.events.values():
77 c.Cblock(self._GenerateEvent(event))
78 (c.Concat(self._type_helper.GetNamespaceEnd())
79 .Cblock(self._type_helper.GetRootNamespaceEnd())
80 )
81 return c
82
83 def _GenerateType(self, cpp_namespace, type_):
84 """Generates the function definitions for a type.
85 """
86 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
87 c = Code()
88
89 if type_.functions:
90 # Wrap functions within types in the type's namespace.
91 (c.Append('namespace %s {' % classname)
92 .Append())
93 for function in type_.functions.values():
94 c.Cblock(self._GenerateFunction(function))
95 c.Append('} // namespace %s' % classname)
96 elif type_.property_type == PropertyType.ARRAY:
97 c.Cblock(self._GenerateType(cpp_namespace, type_.item_type))
98 elif (type_.property_type == PropertyType.OBJECT or
99 type_.property_type == PropertyType.CHOICES):
100 if cpp_namespace is None:
101 classname_in_namespace = classname
102 else:
103 classname_in_namespace = '%s::%s' % (cpp_namespace, classname)
104
105 if type_.property_type == PropertyType.OBJECT:
106 c.Cblock(self._GeneratePropertyFunctions(classname_in_namespace,
107 type_.properties.values()))
108 else:
109 c.Cblock(self._GenerateTypes(classname_in_namespace, type_.choices))
110
111 (c.Append('%s::%s()' % (classname_in_namespace, classname))
112 .Cblock(self._GenerateInitializersAndBody(type_))
113 .Append('%s::~%s() {}' % (classname_in_namespace, classname))
114 .Append()
115 )
116 if type_.origin.from_json:
117 c.Cblock(self._GenerateTypePopulate(classname_in_namespace, type_))
118 if type_.origin.from_client:
119 c.Cblock(self._GenerateTypeToValue(classname_in_namespace, type_))
120 elif type_.property_type == PropertyType.ENUM:
121 (c.Cblock(self._GenerateEnumToString(cpp_namespace, type_))
122 .Cblock(self._GenerateEnumFromString(cpp_namespace, type_))
123 )
124
125 return c
126
127 def _GenerateInitializersAndBody(self, type_):
128 items = []
129 for prop in type_.properties.values():
130 if prop.optional:
131 continue
132
133 t = prop.type_
134 if t.property_type == PropertyType.INTEGER:
135 items.append('%s(0)' % prop.unix_name)
136 elif t.property_type == PropertyType.DOUBLE:
137 items.append('%s(0.0)' % prop.unix_name)
138 elif t.property_type == PropertyType.BOOLEAN:
139 items.append('%s(false)' % prop.unix_name)
140 elif t.property_type == PropertyType.BINARY:
141 items.append('%s(NULL)' % prop.unix_name)
142 elif (t.property_type == PropertyType.ANY or
143 t.property_type == PropertyType.ARRAY or
144 t.property_type == PropertyType.CHOICES or
145 t.property_type == PropertyType.ENUM or
146 t.property_type == PropertyType.OBJECT or
147 t.property_type == PropertyType.FUNCTION or
148 t.property_type == PropertyType.REF or
149 t.property_type == PropertyType.STRING):
150 # TODO(miket): It would be nice to initialize CHOICES and ENUM, but we
151 # don't presently have the semantics to indicate which one of a set
152 # should be the default.
153 continue
154 else:
155 raise TypeError(t)
156
157 if items:
158 s = ': %s' % (', '.join(items))
159 else:
160 s = ''
161 s = s + ' {}'
162 return Code().Append(s)
163
164 def _GenerateTypePopulate(self, cpp_namespace, type_):
165 """Generates the function for populating a type given a pointer to it.
166
167 E.g for type "Foo", generates Foo::Populate()
168 """
169 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
170 c = Code()
171 (c.Append('// static')
172 .Append('bool %(namespace)s::Populate(')
173 .Sblock(' const base::Value& value, %(name)s* out) {')
174 )
175 if type_.property_type == PropertyType.CHOICES:
176 for choice in type_.choices:
177 value_type = cpp_util.GetValueType(self._type_helper.FollowRef(choice))
178 (c.Sblock('if (value.IsType(%s)) {' % value_type)
179 .Concat(self._GeneratePopulateVariableFromValue(
180 choice,
181 '(&value)',
182 'out->as_%s' % choice.unix_name,
183 'false',
184 is_ptr=True))
185 .Append('return true;')
186 .Eblock('}')
187 )
188 c.Append('return false;')
189 elif type_.property_type == PropertyType.OBJECT:
190 (c.Append('if (!value.IsType(base::Value::TYPE_DICTIONARY))')
191 .Append(' return false;')
192 )
193 if type_.properties or type_.additional_properties is not None:
194 c.Append('const base::DictionaryValue* dict = '
195 'static_cast<const base::DictionaryValue*>(&value);')
196 for prop in type_.properties.values():
197 c.Concat(self._InitializePropertyToDefault(prop, 'out'))
198 for prop in type_.properties.values():
199 c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out'))
200 if type_.additional_properties is not None:
201 if type_.additional_properties.property_type == PropertyType.ANY:
202 c.Append('out->additional_properties.MergeDictionary(dict);')
203 else:
204 cpp_type = self._type_helper.GetCppType(type_.additional_properties,
205 is_in_container=True)
206 (c.Append('for (base::DictionaryValue::Iterator it(*dict);')
207 .Sblock(' it.HasNext(); it.Advance()) {')
208 .Append('%s tmp;' % cpp_type)
209 .Concat(self._GeneratePopulateVariableFromValue(
210 type_.additional_properties,
211 '(&it.value())',
212 'tmp',
213 'false'))
214 .Append('out->additional_properties[it.key()] = tmp;')
215 .Eblock('}')
216 )
217 c.Append('return true;')
218 (c.Eblock('}')
219 .Substitute({'namespace': cpp_namespace, 'name': classname}))
220 return c
221
222 def _GenerateTypePopulateProperty(self, prop, src, dst):
223 """Generate the code to populate a single property in a type.
224
225 src: base::DictionaryValue*
226 dst: Type*
227 """
228 c = Code()
229 value_var = prop.unix_name + '_value'
230 c.Append('const base::Value* %(value_var)s = NULL;')
231 if prop.optional:
232 (c.Sblock(
233 'if (%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
234 .Concat(self._GeneratePopulatePropertyFromValue(
235 prop, value_var, dst, 'false')))
236 underlying_type = self._type_helper.FollowRef(prop.type_)
237 if underlying_type.property_type == PropertyType.ENUM:
238 (c.Append('} else {')
239 .Append('%%(dst)s->%%(name)s = %s;' %
240 self._type_helper.GetEnumNoneValue(prop.type_)))
241 c.Eblock('}')
242 else:
243 (c.Append(
244 'if (!%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s))')
245 .Append(' return false;')
246 .Concat(self._GeneratePopulatePropertyFromValue(
247 prop, value_var, dst, 'false'))
248 )
249 c.Append()
250 c.Substitute({
251 'value_var': value_var,
252 'key': prop.name,
253 'src': src,
254 'dst': dst,
255 'name': prop.unix_name
256 })
257 return c
258
259 def _GenerateTypeToValue(self, cpp_namespace, type_):
260 """Generates a function that serializes the type into a base::Value.
261 E.g. for type "Foo" generates Foo::ToValue()
262 """
263 if type_.property_type == PropertyType.OBJECT:
264 return self._GenerateObjectTypeToValue(cpp_namespace, type_)
265 elif type_.property_type == PropertyType.CHOICES:
266 return self._GenerateChoiceTypeToValue(cpp_namespace, type_)
267 else:
268 raise ValueError("Unsupported property type %s" % type_.type_)
269
270 def _GenerateObjectTypeToValue(self, cpp_namespace, type_):
271 """Generates a function that serializes an object-representing type
272 into a base::DictionaryValue.
273 """
274 c = Code()
275 (c.Sblock('scoped_ptr<base::DictionaryValue> %s::ToValue() const {' %
276 cpp_namespace)
277 .Append('scoped_ptr<base::DictionaryValue> value('
278 'new base::DictionaryValue());')
279 .Append()
280 )
281
282 for prop in type_.properties.values():
283 if prop.optional:
284 # Optional enum values are generated with a NONE enum value.
285 underlying_type = self._type_helper.FollowRef(prop.type_)
286 if underlying_type.property_type == PropertyType.ENUM:
287 c.Sblock('if (%s != %s) {' %
288 (prop.unix_name,
289 self._type_helper.GetEnumNoneValue(prop.type_)))
290 else:
291 c.Sblock('if (%s.get()) {' % prop.unix_name)
292
293 # ANY is a base::Value which is abstract and cannot be a direct member, so
294 # it will always be a pointer.
295 is_ptr = prop.optional or prop.type_.property_type == PropertyType.ANY
296 c.Append('value->SetWithoutPathExpansion("%s", %s);' % (
297 prop.name,
298 self._CreateValueFromType(prop.type_,
299 'this->%s' % prop.unix_name,
300 is_ptr=is_ptr)))
301
302 if prop.optional:
303 c.Eblock('}');
304
305 if type_.additional_properties is not None:
306 if type_.additional_properties.property_type == PropertyType.ANY:
307 c.Append('value->MergeDictionary(&additional_properties);')
308 else:
309 # Non-copyable types will be wrapped in a linked_ptr for inclusion in
310 # maps, so we need to unwrap them.
311 needs_unwrap = (
312 not self._type_helper.IsCopyable(type_.additional_properties))
313 cpp_type = self._type_helper.GetCppType(type_.additional_properties,
314 is_in_container=True)
315 (c.Sblock('for (std::map<std::string, %s>::const_iterator it =' %
316 cpp_util.PadForGenerics(cpp_type))
317 .Append(' additional_properties.begin();')
318 .Append(' it != additional_properties.end(); ++it) {')
319 .Append('value->SetWithoutPathExpansion(it->first, %s);' %
320 self._CreateValueFromType(
321 type_.additional_properties,
322 '%sit->second' % ('*' if needs_unwrap else '')))
323 .Eblock('}')
324 )
325
326 return (c.Append()
327 .Append('return value.Pass();')
328 .Eblock('}'))
329
330 def _GenerateChoiceTypeToValue(self, cpp_namespace, type_):
331 """Generates a function that serializes a choice-representing type
332 into a base::Value.
333 """
334 c = Code()
335 c.Sblock('scoped_ptr<base::Value> %s::ToValue() const {' % cpp_namespace)
336 c.Append('scoped_ptr<base::Value> result;');
337 for choice in type_.choices:
338 choice_var = 'as_%s' % choice.unix_name
339 (c.Sblock('if (%s) {' % choice_var)
340 .Append('DCHECK(!result) << "Cannot set multiple choices for %s";' %
341 type_.unix_name)
342 .Append('result.reset(%s);' %
343 self._CreateValueFromType(choice, '*%s' % choice_var))
344 .Eblock('}')
345 )
346 (c.Append('DCHECK(result) << "Must set at least one choice for %s";' %
347 type_.unix_name)
348 .Append('return result.Pass();')
349 .Eblock('}')
350 )
351 return c
352
353 def _GenerateFunction(self, function):
354 """Generates the definitions for function structs.
355 """
356 c = Code()
357
358 # TODO(kalman): use function.unix_name not Classname.
359 function_namespace = cpp_util.Classname(function.name)
360 (c.Append('namespace %s {' % function_namespace)
361 .Append()
362 )
363
364 # Params::Populate function
365 if function.params:
366 c.Concat(self._GeneratePropertyFunctions('Params', function.params))
367 (c.Append('Params::Params() {}')
368 .Append('Params::~Params() {}')
369 .Append()
370 .Cblock(self._GenerateFunctionParamsCreate(function))
371 )
372
373 # Results::Create function
374 if function.callback:
375 c.Concat(self._GenerateCreateCallbackArguments('Results',
376 function.callback))
377
378 c.Append('} // namespace %s' % function_namespace)
379 return c
380
381 def _GenerateEvent(self, event):
382 # TODO(kalman): use event.unix_name not Classname.
383 c = Code()
384 event_namespace = cpp_util.Classname(event.name)
385 (c.Append('namespace %s {' % event_namespace)
386 .Append()
387 .Cblock(self._GenerateCreateCallbackArguments(None, event))
388 .Append('} // namespace %s' % event_namespace)
389 )
390 return c
391
392 def _CreateValueFromType(self, type_, var, is_ptr=False):
393 """Creates a base::Value given a type. Generated code passes ownership
394 to caller.
395
396 var: variable or variable*
397
398 E.g for std::string, generate base::Value::CreateStringValue(var)
399 """
400 underlying_type = self._type_helper.FollowRef(type_)
401 if (underlying_type.property_type == PropertyType.CHOICES or
402 underlying_type.property_type == PropertyType.OBJECT):
403 if is_ptr:
404 return '(%s)->ToValue().release()' % var
405 else:
406 return '(%s).ToValue().release()' % var
407 elif (underlying_type.property_type == PropertyType.ANY or
408 underlying_type.property_type == PropertyType.FUNCTION):
409 if is_ptr:
410 vardot = '(%s)->' % var
411 else:
412 vardot = '(%s).' % var
413 return '%sDeepCopy()' % vardot
414 elif underlying_type.property_type == PropertyType.ENUM:
415 return 'base::Value::CreateStringValue(ToString(%s))' % var
416 elif underlying_type.property_type == PropertyType.BINARY:
417 if is_ptr:
418 vardot = var + '->'
419 else:
420 vardot = var + '.'
421 return ('base::BinaryValue::CreateWithCopiedBuffer(%sdata(), %ssize())' %
422 (vardot, vardot))
423 elif underlying_type.property_type == PropertyType.ARRAY:
424 return '%s.release()' % self._util_cc_helper.CreateValueFromArray(
425 underlying_type,
426 var,
427 is_ptr)
428 elif underlying_type.property_type.is_fundamental:
429 if is_ptr:
430 var = '*%s' % var
431 if underlying_type.property_type == PropertyType.STRING:
432 return 'new base::StringValue(%s)' % var
433 else:
434 return 'new base::FundamentalValue(%s)' % var
435 else:
436 raise NotImplementedError('Conversion of %s to base::Value not '
437 'implemented' % repr(type_.type_))
438
439 def _GenerateParamsCheck(self, function, var):
440 """Generates a check for the correct number of arguments when creating
441 Params.
442 """
443 c = Code()
444 num_required = 0
445 for param in function.params:
446 if not param.optional:
447 num_required += 1
448 if num_required == len(function.params):
449 c.Append('if (%(var)s.GetSize() != %(total)d)')
450 elif not num_required:
451 c.Append('if (%(var)s.GetSize() > %(total)d)')
452 else:
453 c.Append('if (%(var)s.GetSize() < %(required)d'
454 ' || %(var)s.GetSize() > %(total)d)')
455 c.Append(' return scoped_ptr<Params>();')
456 c.Substitute({
457 'var': var,
458 'required': num_required,
459 'total': len(function.params),
460 })
461 return c
462
463 def _GenerateFunctionParamsCreate(self, function):
464 """Generate function to create an instance of Params. The generated
465 function takes a base::ListValue of arguments.
466
467 E.g for function "Bar", generate Bar::Params::Create()
468 """
469 c = Code()
470 (c.Append('// static')
471 .Sblock('scoped_ptr<Params> '
472 'Params::Create(const base::ListValue& args) {')
473 .Concat(self._GenerateParamsCheck(function, 'args'))
474 .Append('scoped_ptr<Params> params(new Params());')
475 )
476
477 for param in function.params:
478 c.Concat(self._InitializePropertyToDefault(param, 'params'))
479
480 for i, param in enumerate(function.params):
481 # Any failure will cause this function to return. If any argument is
482 # incorrect or missing, those following it are not processed. Note that
483 # for optional arguments, we allow missing arguments and proceed because
484 # there may be other arguments following it.
485 failure_value = 'scoped_ptr<Params>()'
486 c.Append()
487 value_var = param.unix_name + '_value'
488 (c.Append('const base::Value* %(value_var)s = NULL;')
489 .Append('if (args.Get(%(i)s, &%(value_var)s) &&')
490 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {')
491 .Concat(self._GeneratePopulatePropertyFromValue(
492 param, value_var, 'params', failure_value))
493 .Eblock('}')
494 )
495 if not param.optional:
496 (c.Sblock('else {')
497 .Append('return %s;' % failure_value)
498 .Eblock('}')
499 )
500 c.Substitute({'value_var': value_var, 'i': i})
501 (c.Append()
502 .Append('return params.Pass();')
503 .Eblock('}')
504 .Append()
505 )
506
507 return c
508
509 def _GeneratePopulatePropertyFromValue(self,
510 prop,
511 src_var,
512 dst_class_var,
513 failure_value):
514 """Generates code to populate property |prop| of |dst_class_var| (a
515 pointer) from a Value*. See |_GeneratePopulateVariableFromValue| for
516 semantics.
517 """
518 return self._GeneratePopulateVariableFromValue(prop.type_,
519 src_var,
520 '%s->%s' % (dst_class_var,
521 prop.unix_name),
522 failure_value,
523 is_ptr=prop.optional)
524
525 def _GeneratePopulateVariableFromValue(self,
526 type_,
527 src_var,
528 dst_var,
529 failure_value,
530 is_ptr=False):
531 """Generates code to populate a variable |dst_var| of type |type_| from a
532 Value* at |src_var|. The Value* is assumed to be non-NULL. In the generated
533 code, if |dst_var| fails to be populated then Populate will return
534 |failure_value|.
535 """
536 c = Code()
537 c.Sblock('{')
538
539 underlying_type = self._type_helper.FollowRef(type_)
540
541 if underlying_type.property_type.is_fundamental:
542 if is_ptr:
543 (c.Append('%(cpp_type)s temp;')
544 .Append('if (!%s)' % cpp_util.GetAsFundamentalValue(
545 self._type_helper.FollowRef(type_), src_var, '&temp'))
546 .Append(' return %(failure_value)s;')
547 .Append('%(dst_var)s.reset(new %(cpp_type)s(temp));')
548 )
549 else:
550 (c.Append('if (!%s)' % cpp_util.GetAsFundamentalValue(
551 self._type_helper.FollowRef(type_),
552 src_var,
553 '&%s' % dst_var))
554 .Append(' return %(failure_value)s;')
555 )
556 elif underlying_type.property_type == PropertyType.OBJECT:
557 if is_ptr:
558 (c.Append('const base::DictionaryValue* dictionary = NULL;')
559 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary))')
560 .Append(' return %(failure_value)s;')
561 .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
562 .Append('if (!%(cpp_type)s::Populate(*dictionary, temp.get()))')
563 .Append(' return %(failure_value)s;')
564 .Append('%(dst_var)s = temp.Pass();')
565 )
566 else:
567 (c.Append('const base::DictionaryValue* dictionary = NULL;')
568 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary))')
569 .Append(' return %(failure_value)s;')
570 .Append('if (!%(cpp_type)s::Populate(*dictionary, &%(dst_var)s))')
571 .Append(' return %(failure_value)s;')
572 )
573 elif underlying_type.property_type == PropertyType.FUNCTION:
574 if is_ptr:
575 c.Append('%(dst_var)s.reset(new base::DictionaryValue());')
576 elif underlying_type.property_type == PropertyType.ANY:
577 c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());')
578 elif underlying_type.property_type == PropertyType.ARRAY:
579 # util_cc_helper deals with optional and required arrays
580 (c.Append('const base::ListValue* list = NULL;')
581 .Append('if (!%(src_var)s->GetAsList(&list))')
582 .Append(' return %(failure_value)s;'))
583 item_type = underlying_type.item_type
584 if item_type.property_type == PropertyType.ENUM:
585 c.Concat(self._GenerateListValueToEnumArrayConversion(
586 item_type,
587 'list',
588 dst_var,
589 failure_value,
590 is_ptr=is_ptr))
591 else:
592 (c.Append('if (!%s)' % self._util_cc_helper.PopulateArrayFromList(
593 underlying_type,
594 'list',
595 dst_var,
596 is_ptr))
597 .Append(' return %(failure_value)s;')
598 )
599 elif underlying_type.property_type == PropertyType.CHOICES:
600 if is_ptr:
601 (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
602 .Append('if (!%(cpp_type)s::Populate(*%(src_var)s, temp.get()))')
603 .Append(' return %(failure_value)s;')
604 .Append('%(dst_var)s = temp.Pass();')
605 )
606 else:
607 (c.Append('if (!%(cpp_type)s::Populate(*%(src_var)s, &%(dst_var)s))')
608 .Append(' return %(failure_value)s;')
609 )
610 elif underlying_type.property_type == PropertyType.ENUM:
611 c.Concat(self._GenerateStringToEnumConversion(type_,
612 src_var,
613 dst_var,
614 failure_value))
615 elif underlying_type.property_type == PropertyType.BINARY:
616 (c.Append('if (!%(src_var)s->IsType(%(value_type)s))')
617 .Append(' return %(failure_value)s;')
618 .Append('const base::BinaryValue* binary_value =')
619 .Append(' static_cast<const base::BinaryValue*>(%(src_var)s);')
620 )
621 if is_ptr:
622 (c.Append('%(dst_var)s.reset(')
623 .Append(' new std::string(binary_value->GetBuffer(),')
624 .Append(' binary_value->GetSize()));')
625 )
626 else:
627 (c.Append('%(dst_var)s.assign(binary_value->GetBuffer(),')
628 .Append(' binary_value->GetSize());')
629 )
630 else:
631 raise NotImplementedError(type_)
632
633 sub = {
634 'cpp_type': self._type_helper.GetCppType(type_),
635 'src_var': src_var,
636 'dst_var': dst_var,
637 'failure_value': failure_value,
638 }
639
640 if underlying_type.property_type not in (PropertyType.ANY,
641 PropertyType.CHOICES):
642 sub['value_type'] = cpp_util.GetValueType(underlying_type)
643
644 return c.Eblock('}').Substitute(sub)
645
646 def _GenerateListValueToEnumArrayConversion(self,
647 item_type,
648 src_var,
649 dst_var,
650 failure_value,
651 is_ptr=False):
652 """Returns Code that converts a ListValue of string constants from
653 |src_var| into an array of enums of |type_| in |dst_var|. On failure,
654 returns |failure_value|.
655 """
656 c = Code()
657 accessor = '.'
658 if is_ptr:
659 accessor = '->'
660 cpp_type = self._type_helper.GetCppType(item_type, is_in_container=True)
661 c.Append('%s.reset(new std::vector<%s>);' %
662 (dst_var, cpp_util.PadForGenerics(cpp_type)))
663 (c.Sblock('for (base::ListValue::const_iterator it = %s->begin(); '
664 'it != %s->end(); ++it) {' % (src_var, src_var))
665 .Append('%s tmp;' % self._type_helper.GetCppType(item_type))
666 .Concat(self._GenerateStringToEnumConversion(item_type,
667 '(*it)',
668 'tmp',
669 failure_value))
670 .Append('%s%spush_back(tmp);' % (dst_var, accessor))
671 .Eblock('}')
672 )
673 return c
674
675 def _GenerateStringToEnumConversion(self,
676 type_,
677 src_var,
678 dst_var,
679 failure_value):
680 """Returns Code that converts a string type in |src_var| to an enum with
681 type |type_| in |dst_var|. In the generated code, if |src_var| is not
682 a valid enum name then the function will return |failure_value|.
683 """
684 c = Code()
685 enum_as_string = '%s_as_string' % type_.unix_name
686 (c.Append('std::string %s;' % enum_as_string)
687 .Append('if (!%s->GetAsString(&%s))' % (src_var, enum_as_string))
688 .Append(' return %s;' % failure_value)
689 .Append('%s = Parse%s(%s);' % (dst_var,
690 self._type_helper.GetCppType(type_),
691 enum_as_string))
692 .Append('if (%s == %s)' % (dst_var,
693 self._type_helper.GetEnumNoneValue(type_)))
694 .Append(' return %s;' % failure_value)
695 )
696 return c
697
698 def _GeneratePropertyFunctions(self, namespace, params):
699 """Generates the member functions for a list of parameters.
700 """
701 return self._GenerateTypes(namespace, (param.type_ for param in params))
702
703 def _GenerateTypes(self, namespace, types):
704 """Generates the member functions for a list of types.
705 """
706 c = Code()
707 for type_ in types:
708 c.Cblock(self._GenerateType(namespace, type_))
709 return c
710
711 def _GenerateEnumToString(self, cpp_namespace, type_):
712 """Generates ToString() which gets the string representation of an enum.
713 """
714 c = Code()
715 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
716
717 if cpp_namespace is not None:
718 c.Append('// static')
719 maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
720
721 c.Sblock('std::string %sToString(%s enum_param) {' %
722 (maybe_namespace, classname))
723 c.Sblock('switch (enum_param) {')
724 for enum_value in self._type_helper.FollowRef(type_).enum_values:
725 (c.Append('case %s: ' % self._type_helper.GetEnumValue(type_, enum_value))
726 .Append(' return "%s";' % enum_value))
727 (c.Append('case %s:' % self._type_helper.GetEnumNoneValue(type_))
728 .Append(' return "";')
729 .Eblock('}')
730 .Append('NOTREACHED();')
731 .Append('return "";')
732 .Eblock('}')
733 )
734 return c
735
736 def _GenerateEnumFromString(self, cpp_namespace, type_):
737 """Generates FromClassNameString() which gets an enum from its string
738 representation.
739 """
740 c = Code()
741 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
742
743 if cpp_namespace is not None:
744 c.Append('// static')
745 maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
746
747 c.Sblock('%s%s %sParse%s(const std::string& enum_string) {' %
748 (maybe_namespace, classname, maybe_namespace, classname))
749 for i, enum_value in enumerate(
750 self._type_helper.FollowRef(type_).enum_values):
751 # This is broken up into all ifs with no else ifs because we get
752 # "fatal error C1061: compiler limit : blocks nested too deeply"
753 # on Windows.
754 (c.Append('if (enum_string == "%s")' % enum_value)
755 .Append(' return %s;' %
756 self._type_helper.GetEnumValue(type_, enum_value)))
757 (c.Append('return %s;' % self._type_helper.GetEnumNoneValue(type_))
758 .Eblock('}')
759 )
760 return c
761
762 def _GenerateCreateCallbackArguments(self, function_scope, callback):
763 """Generate all functions to create Value parameters for a callback.
764
765 E.g for function "Bar", generate Bar::Results::Create
766 E.g for event "Baz", generate Baz::Create
767
768 function_scope: the function scope path, e.g. Foo::Bar for the function
769 Foo::Bar::Baz(). May be None if there is no function scope.
770 callback: the Function object we are creating callback arguments for.
771 """
772 c = Code()
773 params = callback.params
774 c.Concat(self._GeneratePropertyFunctions(function_scope, params))
775
776 (c.Sblock('scoped_ptr<base::ListValue> %(function_scope)s'
777 'Create(%(declaration_list)s) {')
778 .Append('scoped_ptr<base::ListValue> create_results('
779 'new base::ListValue());')
780 )
781 declaration_list = []
782 for param in params:
783 declaration_list.append(cpp_util.GetParameterDeclaration(
784 param, self._type_helper.GetCppType(param.type_)))
785 c.Append('create_results->Append(%s);' %
786 self._CreateValueFromType(param.type_, param.unix_name))
787 c.Append('return create_results.Pass();')
788 c.Eblock('}')
789 c.Substitute({
790 'function_scope': ('%s::' % function_scope) if function_scope else '',
791 'declaration_list': ', '.join(declaration_list),
792 'param_names': ', '.join(param.unix_name for param in params)
793 })
794 return c
795
796 def _InitializePropertyToDefault(self, prop, dst):
797 """Initialize a model.Property to its default value inside an object.
798
799 E.g for optional enum "state", generate dst->state = STATE_NONE;
800
801 dst: Type*
802 """
803 c = Code()
804 underlying_type = self._type_helper.FollowRef(prop.type_)
805 if (underlying_type.property_type == PropertyType.ENUM and
806 prop.optional):
807 c.Append('%s->%s = %s;' % (
808 dst,
809 prop.unix_name,
810 self._type_helper.GetEnumNoneValue(prop.type_)))
811 return c
OLDNEW
« no previous file with comments | « third_party/chrome/tools/README ('k') | third_party/chrome/tools/code.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698