OLD | NEW |
1 # Protocol Buffers - Google's data interchange format | 1 # Protocol Buffers - Google's data interchange format |
2 # Copyright 2008 Google Inc. All rights reserved. | 2 # Copyright 2008 Google Inc. All rights reserved. |
3 # https://developers.google.com/protocol-buffers/ | 3 # http://code.google.com/p/protobuf/ |
4 # | 4 # |
5 # Redistribution and use in source and binary forms, with or without | 5 # Redistribution and use in source and binary forms, with or without |
6 # modification, are permitted provided that the following conditions are | 6 # modification, are permitted provided that the following conditions are |
7 # met: | 7 # met: |
8 # | 8 # |
9 # * Redistributions of source code must retain the above copyright | 9 # * Redistributions of source code must retain the above copyright |
10 # notice, this list of conditions and the following disclaimer. | 10 # notice, this list of conditions and the following disclaimer. |
11 # * Redistributions in binary form must reproduce the above | 11 # * Redistributions in binary form must reproduce the above |
12 # copyright notice, this list of conditions and the following disclaimer | 12 # copyright notice, this list of conditions and the following disclaimer |
13 # in the documentation and/or other materials provided with the | 13 # in the documentation and/or other materials provided with the |
14 # distribution. | 14 # distribution. |
15 # * Neither the name of Google Inc. nor the names of its | 15 # * Neither the name of Google Inc. nor the names of its |
16 # contributors may be used to endorse or promote products derived from | 16 # contributors may be used to endorse or promote products derived from |
17 # this software without specific prior written permission. | 17 # this software without specific prior written permission. |
18 # | 18 # |
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | 19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | 20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | 22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | 24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | 27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | 29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
30 | 30 |
31 # Needs to stay compatible with Python 2.5 due to GAE. | |
32 # | |
33 # Copyright 2007 Google Inc. All Rights Reserved. | |
34 | |
35 """Descriptors essentially contain exactly the information found in a .proto | 31 """Descriptors essentially contain exactly the information found in a .proto |
36 file, in types that make this information accessible in Python. | 32 file, in types that make this information accessible in Python. |
37 """ | 33 """ |
38 | 34 |
39 __author__ = 'robinson@google.com (Will Robinson)' | 35 __author__ = 'robinson@google.com (Will Robinson)' |
40 | 36 |
| 37 |
41 from google.protobuf.internal import api_implementation | 38 from google.protobuf.internal import api_implementation |
42 | 39 |
43 | 40 |
44 _USE_C_DESCRIPTORS = False | |
45 if api_implementation.Type() == 'cpp': | 41 if api_implementation.Type() == 'cpp': |
46 # Used by MakeDescriptor in cpp mode | 42 if api_implementation.Version() == 2: |
47 import os | 43 from google.protobuf.internal.cpp import _message |
48 import uuid | 44 else: |
49 from google.protobuf.pyext import _message | 45 from google.protobuf.internal import cpp_message |
50 _USE_C_DESCRIPTORS = getattr(_message, '_USE_C_DESCRIPTORS', False) | |
51 | 46 |
52 | 47 |
53 class Error(Exception): | 48 class Error(Exception): |
54 """Base error for this module.""" | 49 """Base error for this module.""" |
55 | 50 |
56 | 51 |
57 class TypeTransformationError(Error): | 52 class TypeTransformationError(Error): |
58 """Error transforming between python proto type and corresponding C++ type.""" | 53 """Error transforming between python proto type and corresponding C++ type.""" |
59 | 54 |
60 | 55 |
61 if _USE_C_DESCRIPTORS: | |
62 # This metaclass allows to override the behavior of code like | |
63 # isinstance(my_descriptor, FieldDescriptor) | |
64 # and make it return True when the descriptor is an instance of the extension | |
65 # type written in C++. | |
66 class DescriptorMetaclass(type): | |
67 def __instancecheck__(cls, obj): | |
68 if super(DescriptorMetaclass, cls).__instancecheck__(obj): | |
69 return True | |
70 if isinstance(obj, cls._C_DESCRIPTOR_CLASS): | |
71 return True | |
72 return False | |
73 else: | |
74 # The standard metaclass; nothing changes. | |
75 DescriptorMetaclass = type | |
76 | |
77 | |
78 class DescriptorBase(object): | 56 class DescriptorBase(object): |
79 | 57 |
80 """Descriptors base class. | 58 """Descriptors base class. |
81 | 59 |
82 This class is the base of all descriptor classes. It provides common options | 60 This class is the base of all descriptor classes. It provides common options |
83 related functionality. | 61 related functionaility. |
84 | 62 |
85 Attributes: | 63 Attributes: |
86 has_options: True if the descriptor has non-default options. Usually it | 64 has_options: True if the descriptor has non-default options. Usually it |
87 is not necessary to read this -- just call GetOptions() which will | 65 is not necessary to read this -- just call GetOptions() which will |
88 happily return the default instance. However, it's sometimes useful | 66 happily return the default instance. However, it's sometimes useful |
89 for efficiency, and also useful inside the protobuf implementation to | 67 for efficiency, and also useful inside the protobuf implementation to |
90 avoid some bootstrapping issues. | 68 avoid some bootstrapping issues. |
91 """ | 69 """ |
92 | 70 |
93 __metaclass__ = DescriptorMetaclass | |
94 if _USE_C_DESCRIPTORS: | |
95 # The class, or tuple of classes, that are considered as "virtual | |
96 # subclasses" of this descriptor class. | |
97 _C_DESCRIPTOR_CLASS = () | |
98 | |
99 def __init__(self, options, options_class_name): | 71 def __init__(self, options, options_class_name): |
100 """Initialize the descriptor given its options message and the name of the | 72 """Initialize the descriptor given its options message and the name of the |
101 class of the options message. The name of the class is required in case | 73 class of the options message. The name of the class is required in case |
102 the options message is None and has to be created. | 74 the options message is None and has to be created. |
103 """ | 75 """ |
104 self._options = options | 76 self._options = options |
105 self._options_class_name = options_class_name | 77 self._options_class_name = options_class_name |
106 | 78 |
107 # Does this descriptor have non-default options? | 79 # Does this descriptor have non-default options? |
108 self.has_options = options is not None | 80 self.has_options = options is not None |
(...skipping 129 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
238 from enum value name to EnumValueDescriptor for that value. | 210 from enum value name to EnumValueDescriptor for that value. |
239 | 211 |
240 extensions: (list of FieldDescriptor) All extensions defined directly | 212 extensions: (list of FieldDescriptor) All extensions defined directly |
241 within this message type (NOT within a nested type). | 213 within this message type (NOT within a nested type). |
242 extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor | 214 extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor |
243 objects as |extensions|, but indexed by "name" attribute of each | 215 objects as |extensions|, but indexed by "name" attribute of each |
244 FieldDescriptor. | 216 FieldDescriptor. |
245 | 217 |
246 is_extendable: Does this type define any extension ranges? | 218 is_extendable: Does this type define any extension ranges? |
247 | 219 |
248 oneofs: (list of OneofDescriptor) The list of descriptors for oneof fields | 220 options: (descriptor_pb2.MessageOptions) Protocol message options or None |
249 in this message. | 221 to use default message options. |
250 oneofs_by_name: (dict str -> OneofDescriptor) Same objects as in |oneofs|, | |
251 but indexed by "name" attribute. | |
252 | 222 |
253 file: (FileDescriptor) Reference to file descriptor. | 223 file: (FileDescriptor) Reference to file descriptor. |
254 """ | 224 """ |
255 | 225 |
256 if _USE_C_DESCRIPTORS: | |
257 _C_DESCRIPTOR_CLASS = _message.Descriptor | |
258 | |
259 def __new__(cls, name, full_name, filename, containing_type, fields, | |
260 nested_types, enum_types, extensions, options=None, | |
261 is_extendable=True, extension_ranges=None, oneofs=None, | |
262 file=None, serialized_start=None, serialized_end=None, | |
263 syntax=None): | |
264 _message.Message._CheckCalledFromGeneratedFile() | |
265 return _message.default_pool.FindMessageTypeByName(full_name) | |
266 | |
267 # NOTE(tmarek): The file argument redefining a builtin is nothing we can | |
268 # fix right now since we don't know how many clients already rely on the | |
269 # name of the argument. | |
270 def __init__(self, name, full_name, filename, containing_type, fields, | 226 def __init__(self, name, full_name, filename, containing_type, fields, |
271 nested_types, enum_types, extensions, options=None, | 227 nested_types, enum_types, extensions, options=None, |
272 is_extendable=True, extension_ranges=None, oneofs=None, | 228 is_extendable=True, extension_ranges=None, file=None, |
273 file=None, serialized_start=None, serialized_end=None, | 229 serialized_start=None, serialized_end=None): |
274 syntax=None): # pylint:disable=redefined-builtin | |
275 """Arguments to __init__() are as described in the description | 230 """Arguments to __init__() are as described in the description |
276 of Descriptor fields above. | 231 of Descriptor fields above. |
277 | 232 |
278 Note that filename is an obsolete argument, that is not used anymore. | 233 Note that filename is an obsolete argument, that is not used anymore. |
279 Please use file.name to access this as an attribute. | 234 Please use file.name to access this as an attribute. |
280 """ | 235 """ |
281 super(Descriptor, self).__init__( | 236 super(Descriptor, self).__init__( |
282 options, 'MessageOptions', name, full_name, file, | 237 options, 'MessageOptions', name, full_name, file, |
283 containing_type, serialized_start=serialized_start, | 238 containing_type, serialized_start=serialized_start, |
284 serialized_end=serialized_end) | 239 serialized_end=serialized_start) |
285 | 240 |
286 # We have fields in addition to fields_by_name and fields_by_number, | 241 # We have fields in addition to fields_by_name and fields_by_number, |
287 # so that: | 242 # so that: |
288 # 1. Clients can index fields by "order in which they're listed." | 243 # 1. Clients can index fields by "order in which they're listed." |
289 # 2. Clients can easily iterate over all fields with the terse | 244 # 2. Clients can easily iterate over all fields with the terse |
290 # syntax: for f in descriptor.fields: ... | 245 # syntax: for f in descriptor.fields: ... |
291 self.fields = fields | 246 self.fields = fields |
292 for field in self.fields: | 247 for field in self.fields: |
293 field.containing_type = self | 248 field.containing_type = self |
294 self.fields_by_number = dict((f.number, f) for f in fields) | 249 self.fields_by_number = dict((f.number, f) for f in fields) |
295 self.fields_by_name = dict((f.name, f) for f in fields) | 250 self.fields_by_name = dict((f.name, f) for f in fields) |
296 | 251 |
297 self.nested_types = nested_types | 252 self.nested_types = nested_types |
298 for nested_type in nested_types: | |
299 nested_type.containing_type = self | |
300 self.nested_types_by_name = dict((t.name, t) for t in nested_types) | 253 self.nested_types_by_name = dict((t.name, t) for t in nested_types) |
301 | 254 |
302 self.enum_types = enum_types | 255 self.enum_types = enum_types |
303 for enum_type in self.enum_types: | 256 for enum_type in self.enum_types: |
304 enum_type.containing_type = self | 257 enum_type.containing_type = self |
305 self.enum_types_by_name = dict((t.name, t) for t in enum_types) | 258 self.enum_types_by_name = dict((t.name, t) for t in enum_types) |
306 self.enum_values_by_name = dict( | 259 self.enum_values_by_name = dict( |
307 (v.name, v) for t in enum_types for v in t.values) | 260 (v.name, v) for t in enum_types for v in t.values) |
308 | 261 |
309 self.extensions = extensions | 262 self.extensions = extensions |
310 for extension in self.extensions: | 263 for extension in self.extensions: |
311 extension.extension_scope = self | 264 extension.extension_scope = self |
312 self.extensions_by_name = dict((f.name, f) for f in extensions) | 265 self.extensions_by_name = dict((f.name, f) for f in extensions) |
313 self.is_extendable = is_extendable | 266 self.is_extendable = is_extendable |
314 self.extension_ranges = extension_ranges | 267 self.extension_ranges = extension_ranges |
315 self.oneofs = oneofs if oneofs is not None else [] | 268 |
316 self.oneofs_by_name = dict((o.name, o) for o in self.oneofs) | 269 self._serialized_start = serialized_start |
317 for oneof in self.oneofs: | 270 self._serialized_end = serialized_end |
318 oneof.containing_type = self | |
319 self.syntax = syntax or "proto2" | |
320 | 271 |
321 def EnumValueName(self, enum, value): | 272 def EnumValueName(self, enum, value): |
322 """Returns the string name of an enum value. | 273 """Returns the string name of an enum value. |
323 | 274 |
324 This is just a small helper method to simplify a common operation. | 275 This is just a small helper method to simplify a common operation. |
325 | 276 |
326 Args: | 277 Args: |
327 enum: string name of the Enum. | 278 enum: string name of the Enum. |
328 value: int, value of the enum. | 279 value: int, value of the enum. |
329 | 280 |
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
395 enum_type: (EnumDescriptor) If this field contains an enum, a | 346 enum_type: (EnumDescriptor) If this field contains an enum, a |
396 descriptor of that enum. Otherwise, this is None. | 347 descriptor of that enum. Otherwise, this is None. |
397 | 348 |
398 is_extension: True iff this describes an extension field. | 349 is_extension: True iff this describes an extension field. |
399 extension_scope: (Descriptor) Only meaningful if is_extension is True. | 350 extension_scope: (Descriptor) Only meaningful if is_extension is True. |
400 Gives the message that immediately contains this extension field. | 351 Gives the message that immediately contains this extension field. |
401 Will be None iff we're a top-level (file-level) extension field. | 352 Will be None iff we're a top-level (file-level) extension field. |
402 | 353 |
403 options: (descriptor_pb2.FieldOptions) Protocol message field options or | 354 options: (descriptor_pb2.FieldOptions) Protocol message field options or |
404 None to use default field options. | 355 None to use default field options. |
405 | |
406 containing_oneof: (OneofDescriptor) If the field is a member of a oneof | |
407 union, contains its descriptor. Otherwise, None. | |
408 """ | 356 """ |
409 | 357 |
410 # Must be consistent with C++ FieldDescriptor::Type enum in | 358 # Must be consistent with C++ FieldDescriptor::Type enum in |
411 # descriptor.h. | 359 # descriptor.h. |
412 # | 360 # |
413 # TODO(robinson): Find a way to eliminate this repetition. | 361 # TODO(robinson): Find a way to eliminate this repetition. |
414 TYPE_DOUBLE = 1 | 362 TYPE_DOUBLE = 1 |
415 TYPE_FLOAT = 2 | 363 TYPE_FLOAT = 2 |
416 TYPE_INT64 = 3 | 364 TYPE_INT64 = 3 |
417 TYPE_UINT64 = 4 | 365 TYPE_UINT64 = 4 |
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
470 | 418 |
471 # Must be consistent with C++ FieldDescriptor::Label enum in | 419 # Must be consistent with C++ FieldDescriptor::Label enum in |
472 # descriptor.h. | 420 # descriptor.h. |
473 # | 421 # |
474 # TODO(robinson): Find a way to eliminate this repetition. | 422 # TODO(robinson): Find a way to eliminate this repetition. |
475 LABEL_OPTIONAL = 1 | 423 LABEL_OPTIONAL = 1 |
476 LABEL_REQUIRED = 2 | 424 LABEL_REQUIRED = 2 |
477 LABEL_REPEATED = 3 | 425 LABEL_REPEATED = 3 |
478 MAX_LABEL = 3 | 426 MAX_LABEL = 3 |
479 | 427 |
480 # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber, | |
481 # and kLastReservedNumber in descriptor.h | |
482 MAX_FIELD_NUMBER = (1 << 29) - 1 | |
483 FIRST_RESERVED_FIELD_NUMBER = 19000 | |
484 LAST_RESERVED_FIELD_NUMBER = 19999 | |
485 | |
486 if _USE_C_DESCRIPTORS: | |
487 _C_DESCRIPTOR_CLASS = _message.FieldDescriptor | |
488 | |
489 def __new__(cls, name, full_name, index, number, type, cpp_type, label, | |
490 default_value, message_type, enum_type, containing_type, | |
491 is_extension, extension_scope, options=None, | |
492 has_default_value=True, containing_oneof=None): | |
493 _message.Message._CheckCalledFromGeneratedFile() | |
494 if is_extension: | |
495 return _message.default_pool.FindExtensionByName(full_name) | |
496 else: | |
497 return _message.default_pool.FindFieldByName(full_name) | |
498 | |
499 def __init__(self, name, full_name, index, number, type, cpp_type, label, | 428 def __init__(self, name, full_name, index, number, type, cpp_type, label, |
500 default_value, message_type, enum_type, containing_type, | 429 default_value, message_type, enum_type, containing_type, |
501 is_extension, extension_scope, options=None, | 430 is_extension, extension_scope, options=None, |
502 has_default_value=True, containing_oneof=None): | 431 has_default_value=True): |
503 """The arguments are as described in the description of FieldDescriptor | 432 """The arguments are as described in the description of FieldDescriptor |
504 attributes above. | 433 attributes above. |
505 | 434 |
506 Note that containing_type may be None, and may be set later if necessary | 435 Note that containing_type may be None, and may be set later if necessary |
507 (to deal with circular references between message types, for example). | 436 (to deal with circular references between message types, for example). |
508 Likewise for extension_scope. | 437 Likewise for extension_scope. |
509 """ | 438 """ |
510 super(FieldDescriptor, self).__init__(options, 'FieldOptions') | 439 super(FieldDescriptor, self).__init__(options, 'FieldOptions') |
511 self.name = name | 440 self.name = name |
512 self.full_name = full_name | 441 self.full_name = full_name |
513 self.index = index | 442 self.index = index |
514 self.number = number | 443 self.number = number |
515 self.type = type | 444 self.type = type |
516 self.cpp_type = cpp_type | 445 self.cpp_type = cpp_type |
517 self.label = label | 446 self.label = label |
518 self.has_default_value = has_default_value | 447 self.has_default_value = has_default_value |
519 self.default_value = default_value | 448 self.default_value = default_value |
520 self.containing_type = containing_type | 449 self.containing_type = containing_type |
521 self.message_type = message_type | 450 self.message_type = message_type |
522 self.enum_type = enum_type | 451 self.enum_type = enum_type |
523 self.is_extension = is_extension | 452 self.is_extension = is_extension |
524 self.extension_scope = extension_scope | 453 self.extension_scope = extension_scope |
525 self.containing_oneof = containing_oneof | |
526 if api_implementation.Type() == 'cpp': | 454 if api_implementation.Type() == 'cpp': |
527 if is_extension: | 455 if is_extension: |
528 self._cdescriptor = _message.default_pool.FindExtensionByName(full_name) | 456 if api_implementation.Version() == 2: |
| 457 self._cdescriptor = _message.GetExtensionDescriptor(full_name) |
| 458 else: |
| 459 self._cdescriptor = cpp_message.GetExtensionDescriptor(full_name) |
529 else: | 460 else: |
530 self._cdescriptor = _message.default_pool.FindFieldByName(full_name) | 461 if api_implementation.Version() == 2: |
| 462 self._cdescriptor = _message.GetFieldDescriptor(full_name) |
| 463 else: |
| 464 self._cdescriptor = cpp_message.GetFieldDescriptor(full_name) |
531 else: | 465 else: |
532 self._cdescriptor = None | 466 self._cdescriptor = None |
533 | 467 |
534 @staticmethod | 468 @staticmethod |
535 def ProtoTypeToCppProtoType(proto_type): | 469 def ProtoTypeToCppProtoType(proto_type): |
536 """Converts from a Python proto type to a C++ Proto Type. | 470 """Converts from a Python proto type to a C++ Proto Type. |
537 | 471 |
538 The Python ProtocolBuffer classes specify both the 'Python' datatype and the | 472 The Python ProtocolBuffer classes specify both the 'Python' datatype and the |
539 'C++' datatype - and they're not the same. This helper method should | 473 'C++' datatype - and they're not the same. This helper method should |
540 translate from one to another. | 474 translate from one to another. |
(...skipping 29 matching lines...) Expand all Loading... |
570 but indexed by the "number" field of each EnumValueDescriptor. | 504 but indexed by the "number" field of each EnumValueDescriptor. |
571 containing_type: (Descriptor) Descriptor of the immediate containing | 505 containing_type: (Descriptor) Descriptor of the immediate containing |
572 type of this enum, or None if this is an enum defined at the | 506 type of this enum, or None if this is an enum defined at the |
573 top level in a .proto file. Set by Descriptor's constructor | 507 top level in a .proto file. Set by Descriptor's constructor |
574 if we're passed into one. | 508 if we're passed into one. |
575 file: (FileDescriptor) Reference to file descriptor. | 509 file: (FileDescriptor) Reference to file descriptor. |
576 options: (descriptor_pb2.EnumOptions) Enum options message or | 510 options: (descriptor_pb2.EnumOptions) Enum options message or |
577 None to use default enum options. | 511 None to use default enum options. |
578 """ | 512 """ |
579 | 513 |
580 if _USE_C_DESCRIPTORS: | |
581 _C_DESCRIPTOR_CLASS = _message.EnumDescriptor | |
582 | |
583 def __new__(cls, name, full_name, filename, values, | |
584 containing_type=None, options=None, file=None, | |
585 serialized_start=None, serialized_end=None): | |
586 _message.Message._CheckCalledFromGeneratedFile() | |
587 return _message.default_pool.FindEnumTypeByName(full_name) | |
588 | |
589 def __init__(self, name, full_name, filename, values, | 514 def __init__(self, name, full_name, filename, values, |
590 containing_type=None, options=None, file=None, | 515 containing_type=None, options=None, file=None, |
591 serialized_start=None, serialized_end=None): | 516 serialized_start=None, serialized_end=None): |
592 """Arguments are as described in the attribute description above. | 517 """Arguments are as described in the attribute description above. |
593 | 518 |
594 Note that filename is an obsolete argument, that is not used anymore. | 519 Note that filename is an obsolete argument, that is not used anymore. |
595 Please use file.name to access this as an attribute. | 520 Please use file.name to access this as an attribute. |
596 """ | 521 """ |
597 super(EnumDescriptor, self).__init__( | 522 super(EnumDescriptor, self).__init__( |
598 options, 'EnumOptions', name, full_name, file, | 523 options, 'EnumOptions', name, full_name, file, |
599 containing_type, serialized_start=serialized_start, | 524 containing_type, serialized_start=serialized_start, |
600 serialized_end=serialized_end) | 525 serialized_end=serialized_start) |
601 | 526 |
602 self.values = values | 527 self.values = values |
603 for value in self.values: | 528 for value in self.values: |
604 value.type = self | 529 value.type = self |
605 self.values_by_name = dict((v.name, v) for v in values) | 530 self.values_by_name = dict((v.name, v) for v in values) |
606 self.values_by_number = dict((v.number, v) for v in values) | 531 self.values_by_number = dict((v.number, v) for v in values) |
607 | 532 |
| 533 self._serialized_start = serialized_start |
| 534 self._serialized_end = serialized_end |
| 535 |
608 def CopyToProto(self, proto): | 536 def CopyToProto(self, proto): |
609 """Copies this to a descriptor_pb2.EnumDescriptorProto. | 537 """Copies this to a descriptor_pb2.EnumDescriptorProto. |
610 | 538 |
611 Args: | 539 Args: |
612 proto: An empty descriptor_pb2.EnumDescriptorProto. | 540 proto: An empty descriptor_pb2.EnumDescriptorProto. |
613 """ | 541 """ |
614 # This function is overriden to give a better doc comment. | 542 # This function is overriden to give a better doc comment. |
615 super(EnumDescriptor, self).CopyToProto(proto) | 543 super(EnumDescriptor, self).CopyToProto(proto) |
616 | 544 |
617 | 545 |
618 class EnumValueDescriptor(DescriptorBase): | 546 class EnumValueDescriptor(DescriptorBase): |
619 | 547 |
620 """Descriptor for a single value within an enum. | 548 """Descriptor for a single value within an enum. |
621 | 549 |
622 name: (str) Name of this value. | 550 name: (str) Name of this value. |
623 index: (int) Dense, 0-indexed index giving the order that this | 551 index: (int) Dense, 0-indexed index giving the order that this |
624 value appears textually within its enum in the .proto file. | 552 value appears textually within its enum in the .proto file. |
625 number: (int) Actual number assigned to this enum value. | 553 number: (int) Actual number assigned to this enum value. |
626 type: (EnumDescriptor) EnumDescriptor to which this value | 554 type: (EnumDescriptor) EnumDescriptor to which this value |
627 belongs. Set by EnumDescriptor's constructor if we're | 555 belongs. Set by EnumDescriptor's constructor if we're |
628 passed into one. | 556 passed into one. |
629 options: (descriptor_pb2.EnumValueOptions) Enum value options message or | 557 options: (descriptor_pb2.EnumValueOptions) Enum value options message or |
630 None to use default enum value options options. | 558 None to use default enum value options options. |
631 """ | 559 """ |
632 | 560 |
633 if _USE_C_DESCRIPTORS: | |
634 _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor | |
635 | |
636 def __new__(cls, name, index, number, type=None, options=None): | |
637 _message.Message._CheckCalledFromGeneratedFile() | |
638 # There is no way we can build a complete EnumValueDescriptor with the | |
639 # given parameters (the name of the Enum is not known, for example). | |
640 # Fortunately generated files just pass it to the EnumDescriptor() | |
641 # constructor, which will ignore it, so returning None is good enough. | |
642 return None | |
643 | |
644 def __init__(self, name, index, number, type=None, options=None): | 561 def __init__(self, name, index, number, type=None, options=None): |
645 """Arguments are as described in the attribute description above.""" | 562 """Arguments are as described in the attribute description above.""" |
646 super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions') | 563 super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions') |
647 self.name = name | 564 self.name = name |
648 self.index = index | 565 self.index = index |
649 self.number = number | 566 self.number = number |
650 self.type = type | 567 self.type = type |
651 | 568 |
652 | 569 |
653 class OneofDescriptor(object): | |
654 """Descriptor for a oneof field. | |
655 | |
656 name: (str) Name of the oneof field. | |
657 full_name: (str) Full name of the oneof field, including package name. | |
658 index: (int) 0-based index giving the order of the oneof field inside | |
659 its containing type. | |
660 containing_type: (Descriptor) Descriptor of the protocol message | |
661 type that contains this field. Set by the Descriptor constructor | |
662 if we're passed into one. | |
663 fields: (list of FieldDescriptor) The list of field descriptors this | |
664 oneof can contain. | |
665 """ | |
666 | |
667 if _USE_C_DESCRIPTORS: | |
668 _C_DESCRIPTOR_CLASS = _message.OneofDescriptor | |
669 | |
670 def __new__(cls, name, full_name, index, containing_type, fields): | |
671 _message.Message._CheckCalledFromGeneratedFile() | |
672 return _message.default_pool.FindOneofByName(full_name) | |
673 | |
674 def __init__(self, name, full_name, index, containing_type, fields): | |
675 """Arguments are as described in the attribute description above.""" | |
676 self.name = name | |
677 self.full_name = full_name | |
678 self.index = index | |
679 self.containing_type = containing_type | |
680 self.fields = fields | |
681 | |
682 | |
683 class ServiceDescriptor(_NestedDescriptorBase): | 570 class ServiceDescriptor(_NestedDescriptorBase): |
684 | 571 |
685 """Descriptor for a service. | 572 """Descriptor for a service. |
686 | 573 |
687 name: (str) Name of the service. | 574 name: (str) Name of the service. |
688 full_name: (str) Full name of the service, including package name. | 575 full_name: (str) Full name of the service, including package name. |
689 index: (int) 0-indexed index giving the order that this services | 576 index: (int) 0-indexed index giving the order that this services |
690 definition appears withing the .proto file. | 577 definition appears withing the .proto file. |
691 methods: (list of MethodDescriptor) List of methods provided by this | 578 methods: (list of MethodDescriptor) List of methods provided by this |
692 service. | 579 service. |
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
751 self.full_name = full_name | 638 self.full_name = full_name |
752 self.index = index | 639 self.index = index |
753 self.containing_service = containing_service | 640 self.containing_service = containing_service |
754 self.input_type = input_type | 641 self.input_type = input_type |
755 self.output_type = output_type | 642 self.output_type = output_type |
756 | 643 |
757 | 644 |
758 class FileDescriptor(DescriptorBase): | 645 class FileDescriptor(DescriptorBase): |
759 """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto. | 646 """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto. |
760 | 647 |
761 Note that enum_types_by_name, extensions_by_name, and dependencies | |
762 fields are only set by the message_factory module, and not by the | |
763 generated proto code. | |
764 | |
765 name: name of file, relative to root of source tree. | 648 name: name of file, relative to root of source tree. |
766 package: name of the package | 649 package: name of the package |
767 syntax: string indicating syntax of the file (can be "proto2" or "proto3") | |
768 serialized_pb: (str) Byte string of serialized | 650 serialized_pb: (str) Byte string of serialized |
769 descriptor_pb2.FileDescriptorProto. | 651 descriptor_pb2.FileDescriptorProto. |
770 dependencies: List of other FileDescriptors this FileDescriptor depends on. | |
771 message_types_by_name: Dict of message names of their descriptors. | |
772 enum_types_by_name: Dict of enum names and their descriptors. | |
773 extensions_by_name: Dict of extension names and their descriptors. | |
774 """ | 652 """ |
775 | 653 |
776 if _USE_C_DESCRIPTORS: | 654 def __init__(self, name, package, options=None, serialized_pb=None): |
777 _C_DESCRIPTOR_CLASS = _message.FileDescriptor | |
778 | |
779 def __new__(cls, name, package, options=None, serialized_pb=None, | |
780 dependencies=None, syntax=None): | |
781 # FileDescriptor() is called from various places, not only from generated | |
782 # files, to register dynamic proto files and messages. | |
783 if serialized_pb: | |
784 return _message.default_pool.AddSerializedFile(serialized_pb) | |
785 else: | |
786 return super(FileDescriptor, cls).__new__(cls) | |
787 | |
788 def __init__(self, name, package, options=None, serialized_pb=None, | |
789 dependencies=None, syntax=None): | |
790 """Constructor.""" | 655 """Constructor.""" |
791 super(FileDescriptor, self).__init__(options, 'FileOptions') | 656 super(FileDescriptor, self).__init__(options, 'FileOptions') |
792 | 657 |
793 self.message_types_by_name = {} | 658 self.message_types_by_name = {} |
794 self.name = name | 659 self.name = name |
795 self.package = package | 660 self.package = package |
796 self.syntax = syntax or "proto2" | |
797 self.serialized_pb = serialized_pb | 661 self.serialized_pb = serialized_pb |
798 | |
799 self.enum_types_by_name = {} | |
800 self.extensions_by_name = {} | |
801 self.dependencies = (dependencies or []) | |
802 | |
803 if (api_implementation.Type() == 'cpp' and | 662 if (api_implementation.Type() == 'cpp' and |
804 self.serialized_pb is not None): | 663 self.serialized_pb is not None): |
805 _message.default_pool.AddSerializedFile(self.serialized_pb) | 664 if api_implementation.Version() == 2: |
| 665 _message.BuildFile(self.serialized_pb) |
| 666 else: |
| 667 cpp_message.BuildFile(self.serialized_pb) |
806 | 668 |
807 def CopyToProto(self, proto): | 669 def CopyToProto(self, proto): |
808 """Copies this to a descriptor_pb2.FileDescriptorProto. | 670 """Copies this to a descriptor_pb2.FileDescriptorProto. |
809 | 671 |
810 Args: | 672 Args: |
811 proto: An empty descriptor_pb2.FileDescriptorProto. | 673 proto: An empty descriptor_pb2.FileDescriptorProto. |
812 """ | 674 """ |
813 proto.ParseFromString(self.serialized_pb) | 675 proto.ParseFromString(self.serialized_pb) |
814 | 676 |
815 | 677 |
816 def _ParseOptions(message, string): | 678 def _ParseOptions(message, string): |
817 """Parses serialized options. | 679 """Parses serialized options. |
818 | 680 |
819 This helper function is used to parse serialized options in generated | 681 This helper function is used to parse serialized options in generated |
820 proto2 files. It must not be used outside proto2. | 682 proto2 files. It must not be used outside proto2. |
821 """ | 683 """ |
822 message.ParseFromString(string) | 684 message.ParseFromString(string) |
823 return message | 685 return message |
824 | 686 |
825 | 687 |
826 def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True, | 688 def MakeDescriptor(desc_proto, package=''): |
827 syntax=None): | |
828 """Make a protobuf Descriptor given a DescriptorProto protobuf. | 689 """Make a protobuf Descriptor given a DescriptorProto protobuf. |
829 | 690 |
830 Handles nested descriptors. Note that this is limited to the scope of defining | |
831 a message inside of another message. Composite fields can currently only be | |
832 resolved if the message is defined in the same scope as the field. | |
833 | |
834 Args: | 691 Args: |
835 desc_proto: The descriptor_pb2.DescriptorProto protobuf message. | 692 desc_proto: The descriptor_pb2.DescriptorProto protobuf message. |
836 package: Optional package name for the new message Descriptor (string). | 693 package: Optional package name for the new message Descriptor (string). |
837 build_file_if_cpp: Update the C++ descriptor pool if api matches. | 694 |
838 Set to False on recursion, so no duplicates are created. | |
839 syntax: The syntax/semantics that should be used. Set to "proto3" to get | |
840 proto3 field presence semantics. | |
841 Returns: | 695 Returns: |
842 A Descriptor for protobuf messages. | 696 A Descriptor for protobuf messages. |
843 """ | 697 """ |
844 if api_implementation.Type() == 'cpp' and build_file_if_cpp: | |
845 # The C++ implementation requires all descriptors to be backed by the same | |
846 # definition in the C++ descriptor pool. To do this, we build a | |
847 # FileDescriptorProto with the same definition as this descriptor and build | |
848 # it into the pool. | |
849 from google.protobuf import descriptor_pb2 | |
850 file_descriptor_proto = descriptor_pb2.FileDescriptorProto() | |
851 file_descriptor_proto.message_type.add().MergeFrom(desc_proto) | |
852 | |
853 # Generate a random name for this proto file to prevent conflicts with any | |
854 # imported ones. We need to specify a file name so the descriptor pool | |
855 # accepts our FileDescriptorProto, but it is not important what that file | |
856 # name is actually set to. | |
857 proto_name = str(uuid.uuid4()) | |
858 | |
859 if package: | |
860 file_descriptor_proto.name = os.path.join(package.replace('.', '/'), | |
861 proto_name + '.proto') | |
862 file_descriptor_proto.package = package | |
863 else: | |
864 file_descriptor_proto.name = proto_name + '.proto' | |
865 | |
866 _message.default_pool.Add(file_descriptor_proto) | |
867 result = _message.default_pool.FindFileByName(file_descriptor_proto.name) | |
868 | |
869 if _USE_C_DESCRIPTORS: | |
870 return result.message_types_by_name[desc_proto.name] | |
871 | |
872 full_message_name = [desc_proto.name] | 698 full_message_name = [desc_proto.name] |
873 if package: full_message_name.insert(0, package) | 699 if package: full_message_name.insert(0, package) |
874 | |
875 # Create Descriptors for enum types | |
876 enum_types = {} | |
877 for enum_proto in desc_proto.enum_type: | |
878 full_name = '.'.join(full_message_name + [enum_proto.name]) | |
879 enum_desc = EnumDescriptor( | |
880 enum_proto.name, full_name, None, [ | |
881 EnumValueDescriptor(enum_val.name, ii, enum_val.number) | |
882 for ii, enum_val in enumerate(enum_proto.value)]) | |
883 enum_types[full_name] = enum_desc | |
884 | |
885 # Create Descriptors for nested types | |
886 nested_types = {} | |
887 for nested_proto in desc_proto.nested_type: | |
888 full_name = '.'.join(full_message_name + [nested_proto.name]) | |
889 # Nested types are just those defined inside of the message, not all types | |
890 # used by fields in the message, so no loops are possible here. | |
891 nested_desc = MakeDescriptor(nested_proto, | |
892 package='.'.join(full_message_name), | |
893 build_file_if_cpp=False, | |
894 syntax=syntax) | |
895 nested_types[full_name] = nested_desc | |
896 | |
897 fields = [] | 700 fields = [] |
898 for field_proto in desc_proto.field: | 701 for field_proto in desc_proto.field: |
899 full_name = '.'.join(full_message_name + [field_proto.name]) | 702 full_name = '.'.join(full_message_name + [field_proto.name]) |
900 enum_desc = None | |
901 nested_desc = None | |
902 if field_proto.HasField('type_name'): | |
903 type_name = field_proto.type_name | |
904 full_type_name = '.'.join(full_message_name + | |
905 [type_name[type_name.rfind('.')+1:]]) | |
906 if full_type_name in nested_types: | |
907 nested_desc = nested_types[full_type_name] | |
908 elif full_type_name in enum_types: | |
909 enum_desc = enum_types[full_type_name] | |
910 # Else type_name references a non-local type, which isn't implemented | |
911 field = FieldDescriptor( | 703 field = FieldDescriptor( |
912 field_proto.name, full_name, field_proto.number - 1, | 704 field_proto.name, full_name, field_proto.number - 1, |
913 field_proto.number, field_proto.type, | 705 field_proto.number, field_proto.type, |
914 FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), | 706 FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), |
915 field_proto.label, None, nested_desc, enum_desc, None, False, None, | 707 field_proto.label, None, None, None, None, False, None, |
916 options=field_proto.options, has_default_value=False) | 708 has_default_value=False) |
917 fields.append(field) | 709 fields.append(field) |
918 | 710 |
919 desc_name = '.'.join(full_message_name) | 711 desc_name = '.'.join(full_message_name) |
920 return Descriptor(desc_proto.name, desc_name, None, None, fields, | 712 return Descriptor(desc_proto.name, desc_name, None, None, fields, |
921 nested_types.values(), enum_types.values(), [], | 713 [], [], []) |
922 options=desc_proto.options) | |
OLD | NEW |