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

Side by Side Diff: mojo/public/tools/bindings/generators/mojom_dart_generator.py

Issue 1539673003: Generate Mojom Types in Dart (Take 2) (Closed) Base URL: https://github.com/domokit/mojo.git@master
Patch Set: Update to master and regenerate mojoms Created 4 years, 11 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 # Copyright 2014 The Chromium Authors. All rights reserved. 1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be 2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file. 3 # found in the LICENSE file.
4 4
5 """Generates dart source files from a mojom.Module.""" 5 """Generates dart source files from a mojom.Module."""
6 6
7 import errno 7 import errno
8 import os 8 import os
9 import re 9 import re
10 import shutil 10 import shutil
(...skipping 105 matching lines...) Expand 10 before | Expand all | Expand 10 after
116 mojom.NULLABLE_DPPIPE: "core.MojoDataPipeProducer", 116 mojom.NULLABLE_DPPIPE: "core.MojoDataPipeProducer",
117 mojom.NULLABLE_MSGPIPE: "core.MojoMessagePipeEndpoint", 117 mojom.NULLABLE_MSGPIPE: "core.MojoMessagePipeEndpoint",
118 mojom.NULLABLE_SHAREDBUFFER: "core.MojoSharedBuffer", 118 mojom.NULLABLE_SHAREDBUFFER: "core.MojoSharedBuffer",
119 mojom.INT64: "int", 119 mojom.INT64: "int",
120 mojom.UINT64: "int", 120 mojom.UINT64: "int",
121 mojom.DOUBLE: "double", 121 mojom.DOUBLE: "double",
122 mojom.STRING: "String", 122 mojom.STRING: "String",
123 mojom.NULLABLE_STRING: "String" 123 mojom.NULLABLE_STRING: "String"
124 } 124 }
125 125
126 _kind_to_mojom_type = {
127 mojom.BOOL: "bool",
128 mojom.INT8: "int8",
129 mojom.UINT8: "uint8",
130 mojom.INT16: "int16",
131 mojom.UINT16: "uint16",
132 mojom.INT32: "int32",
133 mojom.UINT32: "uint32",
134 mojom.FLOAT: "float",
135 mojom.HANDLE: "unspecified",
136 mojom.DCPIPE: "dataPipeConsumer",
137 mojom.DPPIPE: "dataPipeProducer",
138 mojom.MSGPIPE: "messagePipe",
139 mojom.SHAREDBUFFER: "sharedBuffer",
140 mojom.NULLABLE_HANDLE: "unspecified",
141 mojom.NULLABLE_DCPIPE: "dataPipeConsumer",
142 mojom.NULLABLE_DPPIPE: "dataPipeProducer",
143 mojom.NULLABLE_MSGPIPE: "messagePipe",
144 mojom.NULLABLE_SHAREDBUFFER: "sharedBuffer",
145 mojom.INT64: "int64",
146 mojom.UINT64: "uint64",
147 mojom.DOUBLE: "double",
148 mojom.STRING: "string",
149 mojom.NULLABLE_STRING: "string"
150 }
151
126 _spec_to_decode_method = { 152 _spec_to_decode_method = {
127 mojom.BOOL.spec: 'decodeBool', 153 mojom.BOOL.spec: 'decodeBool',
128 mojom.DCPIPE.spec: 'decodeConsumerHandle', 154 mojom.DCPIPE.spec: 'decodeConsumerHandle',
129 mojom.DOUBLE.spec: 'decodeDouble', 155 mojom.DOUBLE.spec: 'decodeDouble',
130 mojom.DPPIPE.spec: 'decodeProducerHandle', 156 mojom.DPPIPE.spec: 'decodeProducerHandle',
131 mojom.FLOAT.spec: 'decodeFloat', 157 mojom.FLOAT.spec: 'decodeFloat',
132 mojom.HANDLE.spec: 'decodeHandle', 158 mojom.HANDLE.spec: 'decodeHandle',
133 mojom.INT16.spec: 'decodeInt16', 159 mojom.INT16.spec: 'decodeInt16',
134 mojom.INT32.spec: 'decodeInt32', 160 mojom.INT32.spec: 'decodeInt32',
135 mojom.INT64.spec: 'decodeInt64', 161 mojom.INT64.spec: 'decodeInt64',
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
168 mojom.NULLABLE_SHAREDBUFFER.spec: 'encodeSharedBufferHandle', 194 mojom.NULLABLE_SHAREDBUFFER.spec: 'encodeSharedBufferHandle',
169 mojom.NULLABLE_STRING.spec: 'encodeString', 195 mojom.NULLABLE_STRING.spec: 'encodeString',
170 mojom.SHAREDBUFFER.spec: 'encodeSharedBufferHandle', 196 mojom.SHAREDBUFFER.spec: 'encodeSharedBufferHandle',
171 mojom.STRING.spec: 'encodeString', 197 mojom.STRING.spec: 'encodeString',
172 mojom.UINT16.spec: 'encodeUint16', 198 mojom.UINT16.spec: 'encodeUint16',
173 mojom.UINT32.spec: 'encodeUint32', 199 mojom.UINT32.spec: 'encodeUint32',
174 mojom.UINT64.spec: 'encodeUint64', 200 mojom.UINT64.spec: 'encodeUint64',
175 mojom.UINT8.spec: 'encodeUint8', 201 mojom.UINT8.spec: 'encodeUint8',
176 } 202 }
177 203
204 # The mojom_types.mojom and service_describer.mojom files are special because
205 # they are used to generate mojom Type's and ServiceDescription implementations.
206 # They need to be imported, unless the file itself is being generated.
207 _service_describer_pkg_short = "service_describer"
208 _service_describer_pkg = "package:mojo/mojo/bindings/types/%s.mojom.dart" % \
209 _service_describer_pkg_short
210 _mojom_types_pkg_short = "mojom_types"
211 _mojom_types_pkg = "package:mojo/mojo/bindings/types/%s.mojom.dart" % \
212 _mojom_types_pkg_short
213
178 def GetDartType(kind): 214 def GetDartType(kind):
179 if kind.imported_from: 215 if kind.imported_from:
180 return kind.imported_from["unique_name"] + "." + GetNameForElement(kind) 216 return kind.imported_from["unique_name"] + "." + GetNameForElement(kind)
181 return GetNameForElement(kind) 217 return GetNameForElement(kind)
182 218
183 def DartDefaultValue(field): 219 def DartDefaultValue(field):
184 if field.default: 220 if field.default:
185 if mojom.IsStructKind(field.kind): 221 if mojom.IsStructKind(field.kind):
186 assert field.default == "default" 222 assert field.default == "default"
187 return "new %s()" % GetDartType(field.kind) 223 return "new %s()" % GetDartType(field.kind)
(...skipping 30 matching lines...) Expand all
218 if mojom.IsMapKind(kind): 254 if mojom.IsMapKind(kind):
219 key_type = DartDeclType(kind.key_kind) 255 key_type = DartDeclType(kind.key_kind)
220 value_type = DartDeclType(kind.value_kind) 256 value_type = DartDeclType(kind.value_kind)
221 return "Map<"+ key_type + ", " + value_type + ">" 257 return "Map<"+ key_type + ", " + value_type + ">"
222 if mojom.IsInterfaceKind(kind) or \ 258 if mojom.IsInterfaceKind(kind) or \
223 mojom.IsInterfaceRequestKind(kind): 259 mojom.IsInterfaceRequestKind(kind):
224 return "Object" 260 return "Object"
225 if mojom.IsEnumKind(kind): 261 if mojom.IsEnumKind(kind):
226 return GetDartType(kind) 262 return GetDartType(kind)
227 263
264 def GetMojomTypeValue(kind, typepkg=''):
zra 2016/01/15 21:01:33 I think it would be more consistent to move this l
alexfandrianto 2016/01/20 00:08:28 Pretty much all the languages use a map for the si
265 if not kind in _kind_to_mojom_type:
266 return ''
267
268 nullable = 'true' if mojom.IsNullableKind(kind) else 'false'
269 w = _kind_to_mojom_type[kind]
270 if kind == mojom.BOOL or kind == mojom.FLOAT or kind == mojom.DOUBLE or \
271 mojom.IsIntegralKind(kind):
272
273 return 'new %sType()..simpleType = %sSimpleType.%s' % (typepkg, typepkg, w)
274 elif mojom.IsAnyHandleKind(kind):
275 return ('new %sType()\n..handleType = (new %sHandleType()' +
276 '\n..kind = %sHandleTypeKind.%s' +
277 '\n..nullable = %s)') % \
278 (typepkg, typepkg, typepkg, w, nullable)
279 elif mojom.IsStringKind(kind):
280 return 'new %sType()\n..stringType = (new %sStringType()..nullable = %s)' \
281 % (typepkg, typepkg, nullable)
282 else:
283 raise Exception('Missing case for kind: %s' % kind)
284
228 def NameToComponent(name): 285 def NameToComponent(name):
229 # insert '_' between anything and a Title name (e.g, HTTPEntry2FooBar -> 286 # insert '_' between anything and a Title name (e.g, HTTPEntry2FooBar ->
230 # HTTP_Entry2_FooBar). Numbers terminate a string of lower-case characters. 287 # HTTP_Entry2_FooBar). Numbers terminate a string of lower-case characters.
231 name = re.sub('([^_])([A-Z][^A-Z1-9_]+)', r'\1_\2', name) 288 name = re.sub('([^_])([A-Z][^A-Z1-9_]+)', r'\1_\2', name)
232 # insert '_' between non upper and start of upper blocks (e.g., 289 # insert '_' between non upper and start of upper blocks (e.g.,
233 # HTTP_Entry2_FooBar -> HTTP_Entry2_Foo_Bar). 290 # HTTP_Entry2_FooBar -> HTTP_Entry2_Foo_Bar).
234 name = re.sub('([^A-Z_])([A-Z])', r'\1_\2', name) 291 name = re.sub('([^A-Z_])([A-Z])', r'\1_\2', name)
235 return [x.lower() for x in name.split('_')] 292 return [x.lower() for x in name.split('_')]
236 293
237 def UpperCamelCase(name): 294 def UpperCamelCase(name):
(...skipping 181 matching lines...) Expand 10 before | Expand all | Expand 10 after
419 476
420 def IsPointerArrayKind(kind): 477 def IsPointerArrayKind(kind):
421 if not mojom.IsArrayKind(kind): 478 if not mojom.IsArrayKind(kind):
422 return False 479 return False
423 sub_kind = kind.kind 480 sub_kind = kind.kind
424 return mojom.IsObjectKind(sub_kind) 481 return mojom.IsObjectKind(sub_kind)
425 482
426 def IsEnumArrayKind(kind): 483 def IsEnumArrayKind(kind):
427 return mojom.IsArrayKind(kind) and mojom.IsEnumKind(kind.kind) 484 return mojom.IsArrayKind(kind) and mojom.IsEnumKind(kind.kind)
428 485
486 def IsImportedKind(kind):
487 return hasattr(kind, 'imported_from') and kind.imported_from
488
429 def ParseStringAttribute(attribute): 489 def ParseStringAttribute(attribute):
430 assert isinstance(attribute, basestring) 490 assert isinstance(attribute, basestring)
431 return attribute 491 return attribute
432 492
433 def GetPackage(module): 493 def GetPackage(module):
434 if module.attributes and 'DartPackage' in module.attributes: 494 if module.attributes and 'DartPackage' in module.attributes:
435 return ParseStringAttribute(module.attributes['DartPackage']) 495 return ParseStringAttribute(module.attributes['DartPackage'])
436 # Default package. 496 # Default package.
437 return 'mojom' 497 return 'mojom'
438 498
499 def GetPackageName(module):
500 return module.name.split('.')[0]
501
439 def GetImportUri(module): 502 def GetImportUri(module):
440 package = GetPackage(module); 503 package = GetPackage(module);
441 elements = module.namespace.split('.') 504 elements = module.namespace.split('.')
442 elements.append("%s" % module.name) 505 elements.append("%s" % module.name)
443 return os.path.join(package, *elements) 506 return os.path.join(package, *elements)
444 507
508 def GetIdentifier(kind):
zra 2016/01/15 21:01:33 This name is too generic for what (I think) this f
alexfandrianto 2016/01/20 00:08:28 This was combined with GetMojomTypeIdentifier belo
509 """Use the kind's module to determine the package and name."""
510 # Note: InterfaceRequest's should use the Interface inside them.
511 if hasattr(kind, 'module'):
512 package = GetPackageName(kind.module)
513 name = kind.name
514 elif mojom.IsInterfaceRequestKind(kind):
515 package = GetPackageName(kind.kind.module)
516 name = kind.kind.name
517 else:
518 # These kinds (e.g., simple kinds, maps, and arrays) lack identifiers.
519 raise Exception('Unexpected kind: %s' % kind)
520
521 return '%s_%s' % (package, name)
522
523 # Returns a string of the form package.path.TypeName - the full identifier
524 # for an element.
525 def GetFullIdentifier(element, exported=True):
526 return '%s.%s' % (element.module.namespace, GetNameForElement(element))
527
528 def RaiseHelper(msg):
529 raise Exception(msg)
530
531 def GetMojomTypeIdentifier(kind):
532 """Get the mojom type's identifier suffix."""
533 # Since this should be unique, it is based on the type's identifier.
534 return "_%s__" % GetIdentifier(kind)
zra 2016/01/15 21:01:33 Why are there trailing underscores?
alexfandrianto 2016/01/20 00:08:28 This has to match between languages, and the Go on
535
445 class Generator(generator.Generator): 536 class Generator(generator.Generator):
446 537
447 dart_filters = { 538 dart_filters = {
448 'array_expected_length': GetArrayExpectedLength, 539 'array_expected_length': GetArrayExpectedLength,
449 'array': GetArrayKind, 540 'array': GetArrayKind,
450 'decode_method': DecodeMethod, 541 'decode_method': DecodeMethod,
451 'default_value': DartDefaultValue, 542 'default_value': DartDefaultValue,
452 'encode_method': EncodeMethod, 543 'encode_method': EncodeMethod,
544 'fullidentifier': GetFullIdentifier,
545 'identifier': GetIdentifier,
546 'mojom_type_value': GetMojomTypeValue,
547 'mojom_type_identifier': GetMojomTypeIdentifier,
548 'is_imported_kind': IsImportedKind,
549 'is_array_kind': mojom.IsArrayKind,
453 'is_map_kind': mojom.IsMapKind, 550 'is_map_kind': mojom.IsMapKind,
454 'is_nullable_kind': mojom.IsNullableKind, 551 'is_nullable_kind': mojom.IsNullableKind,
455 'is_pointer_array_kind': IsPointerArrayKind, 552 'is_pointer_array_kind': IsPointerArrayKind,
456 'is_enum_array_kind': IsEnumArrayKind, 553 'is_enum_array_kind': IsEnumArrayKind,
457 'is_struct_kind': mojom.IsStructKind, 554 'is_struct_kind': mojom.IsStructKind,
458 'is_union_kind': mojom.IsUnionKind, 555 'is_union_kind': mojom.IsUnionKind,
459 'is_enum_kind': mojom.IsEnumKind, 556 'is_enum_kind': mojom.IsEnumKind,
557 'is_interface_kind': mojom.IsInterfaceKind,
558 'is_interface_request_kind': mojom.IsInterfaceRequestKind,
460 'dart_true_false': GetDartTrueFalse, 559 'dart_true_false': GetDartTrueFalse,
461 'dart_type': DartDeclType, 560 'dart_type': DartDeclType,
462 'name': GetNameForElement, 561 'name': GetNameForElement,
463 'interface_response_name': GetInterfaceResponseName, 562 'interface_response_name': GetInterfaceResponseName,
464 'dot_to_underscore': DotToUnderscore, 563 'dot_to_underscore': DotToUnderscore,
465 'is_cloneable_kind': mojom.IsCloneableKind, 564 'is_cloneable_kind': mojom.IsCloneableKind,
565 'upper_camel': UpperCamelCase,
566 'raise': RaiseHelper,
466 } 567 }
467 568
569 # If set to True, then mojom type information will be generated.
570 should_gen_mojom_types = False
571
468 def GetParameters(self, args): 572 def GetParameters(self, args):
469 return { 573 package = GetPackageName(self.module)
574
575 parameters = {
470 "namespace": self.module.namespace, 576 "namespace": self.module.namespace,
471 "imports": self.GetImports(args), 577 "imports": self.GetImports(args),
472 "kinds": self.module.kinds, 578 "kinds": self.module.kinds,
473 "enums": self.module.enums, 579 "enums": self.module.enums,
474 "module": resolver.ResolveConstants(self.module, ExpressionToText), 580 "module": resolver.ResolveConstants(self.module, ExpressionToText),
475 "structs": self.GetStructs() + self.GetStructsFromMethods(), 581 "structs": self.GetStructs() + self.GetStructsFromMethods(),
476 "unions": self.GetUnions(), 582 "unions": self.GetUnions(),
477 "interfaces": self.GetInterfaces(), 583 "interfaces": self.GetInterfaces(),
478 "imported_interfaces": self.GetImportedInterfaces(), 584 "imported_interfaces": self.GetImportedInterfaces(),
479 "imported_from": self.ImportedFrom(), 585 "imported_from": self.ImportedFrom(),
586 "typepkg": '%s.' % _mojom_types_pkg_short,
587 "descpkg": '%s.' % _service_describer_pkg_short,
588 "mojom_types_import": 'import \'%s\' as %s;' % \
589 (_mojom_types_pkg, _mojom_types_pkg_short),
590 "service_describer_import": 'import \'%s\' as %s;' % \
591 (_service_describer_pkg, _service_describer_pkg_short),
592 }
593
594 # If this is the mojom types package, clear the import-related params.
595 if package == _mojom_types_pkg_short:
596 parameters["typepkg"] = ""
597 parameters["mojom_types_import"] = ""
598
599 # If this is the service describer package, clear the import-related params.
600 if package == _service_describer_pkg_short:
601 parameters["descpkg"] = ""
602 parameters["service_describer_import"] = ""
603
604 # If no interfaces were defined, the service describer import isn't needed.
605 if len(self.module.interfaces) == 0:
606 parameters["service_describer_import"] = ""
607
608 return parameters
609
610 def GetGlobals(self):
611 return {
612 'should_gen_mojom_types': self.should_gen_mojom_types,
480 } 613 }
481 614
482 @UseJinja("dart_templates/module.lib.tmpl", filters=dart_filters) 615 @UseJinja("dart_templates/module.lib.tmpl", filters=dart_filters)
483 def GenerateLibModule(self, args): 616 def GenerateLibModule(self, args):
484 return self.GetParameters(args) 617 return self.GetParameters(args)
485 618
486 619
487 def GenerateFiles(self, args): 620 def GenerateFiles(self, args):
621 self.should_gen_mojom_types = "--generate_type_info" in args
622
488 elements = self.module.namespace.split('.') 623 elements = self.module.namespace.split('.')
489 elements.append("%s.dart" % self.module.name) 624 elements.append("%s.dart" % self.module.name)
490 625
491 lib_module = self.GenerateLibModule(args) 626 lib_module = self.GenerateLibModule(args)
492 627
493 # List of packages with checked in bindings. 628 # List of packages with checked in bindings.
494 # TODO(johnmccutchan): Stop generating bindings as part of build system 629 # TODO(johnmccutchan): Stop generating bindings as part of build system
495 # and then remove this. 630 # and then remove this.
496 packages_with_checked_in_bindings = [ 631 packages_with_checked_in_bindings = [
497 '_mojo_for_test_only', 632 '_mojo_for_test_only',
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
561 interface_to_import[name] = each_import["unique_name"] + "." + name 696 interface_to_import[name] = each_import["unique_name"] + "." + name
562 return interface_to_import 697 return interface_to_import
563 698
564 def ImportedFrom(self): 699 def ImportedFrom(self):
565 interface_to_import = {} 700 interface_to_import = {}
566 for each_import in self.module.imports: 701 for each_import in self.module.imports:
567 for each_interface in each_import["module"].interfaces: 702 for each_interface in each_import["module"].interfaces:
568 name = each_interface.name 703 name = each_interface.name
569 interface_to_import[name] = each_import["unique_name"] + "." 704 interface_to_import[name] = each_import["unique_name"] + "."
570 return interface_to_import 705 return interface_to_import
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698