matlab-prodserver-client 24.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. google/__init__.py +7 -0
  2. google/protobuf_ml/__init__.py +33 -0
  3. google/protobuf_ml/descriptor.py +1230 -0
  4. google/protobuf_ml/descriptor_database.py +177 -0
  5. google/protobuf_ml/descriptor_pb2.py +1925 -0
  6. google/protobuf_ml/descriptor_pool.py +1295 -0
  7. google/protobuf_ml/internal/__init__.py +0 -0
  8. google/protobuf_ml/internal/_parameterized.py +443 -0
  9. google/protobuf_ml/internal/api_implementation.py +168 -0
  10. google/protobuf_ml/internal/builder.py +130 -0
  11. google/protobuf_ml/internal/containers.py +708 -0
  12. google/protobuf_ml/internal/decoder.py +1068 -0
  13. google/protobuf_ml/internal/descriptor_database_test.py +127 -0
  14. google/protobuf_ml/internal/descriptor_pool_test.py +1149 -0
  15. google/protobuf_ml/internal/descriptor_test.py +1076 -0
  16. google/protobuf_ml/internal/encoder.py +829 -0
  17. google/protobuf_ml/internal/enum_type_wrapper.py +124 -0
  18. google/protobuf_ml/internal/extension_dict.py +213 -0
  19. google/protobuf_ml/internal/generator_test.py +354 -0
  20. google/protobuf_ml/internal/import_test.py +49 -0
  21. google/protobuf_ml/internal/json_format_test.py +1285 -0
  22. google/protobuf_ml/internal/keywords_test.py +103 -0
  23. google/protobuf_ml/internal/message_factory_test.py +299 -0
  24. google/protobuf_ml/internal/message_listener.py +78 -0
  25. google/protobuf_ml/internal/message_test.py +2573 -0
  26. google/protobuf_ml/internal/proto_builder_test.py +106 -0
  27. google/protobuf_ml/internal/python_message.py +1539 -0
  28. google/protobuf_ml/internal/reflection_test.py +3381 -0
  29. google/protobuf_ml/internal/service_reflection_test.py +139 -0
  30. google/protobuf_ml/internal/symbol_database_test.py +133 -0
  31. google/protobuf_ml/internal/test_util.py +878 -0
  32. google/protobuf_ml/internal/testing_refleaks.py +142 -0
  33. google/protobuf_ml/internal/text_encoding_test.py +67 -0
  34. google/protobuf_ml/internal/text_format_test.py +2447 -0
  35. google/protobuf_ml/internal/type_checkers.py +435 -0
  36. google/protobuf_ml/internal/unknown_fields_test.py +461 -0
  37. google/protobuf_ml/internal/well_known_types.py +887 -0
  38. google/protobuf_ml/internal/well_known_types_test.py +1013 -0
  39. google/protobuf_ml/internal/wire_format.py +268 -0
  40. google/protobuf_ml/internal/wire_format_test.py +252 -0
  41. google/protobuf_ml/json_format.py +912 -0
  42. google/protobuf_ml/message.py +424 -0
  43. google/protobuf_ml/message_factory.py +189 -0
  44. google/protobuf_ml/proto_builder.py +134 -0
  45. google/protobuf_ml/reflection.py +95 -0
  46. google/protobuf_ml/service.py +228 -0
  47. google/protobuf_ml/service_reflection.py +295 -0
  48. google/protobuf_ml/symbol_database.py +194 -0
  49. google/protobuf_ml/text_encoding.py +110 -0
  50. google/protobuf_ml/text_format.py +1842 -0
  51. google/protobuf_ml/unknown_fields.py +120 -0
  52. matlab/__init__.py +43 -0
  53. matlab/bin/win64/libmwfoundation_matlabdata.dll +0 -0
  54. matlab/bin/win64/libmwfoundation_matlabdata_standalone.dll +0 -0
  55. matlab/extern/bin/win64/libMatlabDataArray.dll +0 -0
  56. matlab/extern/bin/win64/matlabmultidimarrayforpython.cp310-win_amd64.pyd +0 -0
  57. matlab/extern/bin/win64/matlabmultidimarrayforpython.cp39-win_amd64.pyd +0 -0
  58. matlab/extern/bin/win64/matlabmultidimarrayforpython.pyd +0 -0
  59. matlab/production_server/__init__.py +2 -0
  60. matlab/production_server/_internal_mps/__init__.py +2 -0
  61. matlab/production_server/_internal_mps/feval_handler.py +76 -0
  62. matlab/production_server/_internal_mps/invocation_handler_utils.py +52 -0
  63. matlab/production_server/_internal_mps/matlab_array_builder.py +201 -0
  64. matlab/production_server/_internal_mps/matlab_response_builder.py +134 -0
  65. matlab/production_server/_proto_generated/MATLABArray_pb2.py +129 -0
  66. matlab/production_server/_proto_generated/MATLABError_pb2.py +27 -0
  67. matlab/production_server/_proto_generated/MATLABParams_pb2.py +26 -0
  68. matlab/production_server/_proto_generated/MATLABResult_pb2.py +27 -0
  69. matlab/production_server/_proto_generated/__init__.py +0 -0
  70. matlab/production_server/client.py +140 -0
  71. matlab/production_server/mpsexceptions.py +56 -0
  72. matlab_prodserver_client-24.2.dist-info/LICENSE.txt +27 -0
  73. matlab_prodserver_client-24.2.dist-info/METADATA +94 -0
  74. matlab_prodserver_client-24.2.dist-info/RECORD +77 -0
  75. matlab_prodserver_client-24.2.dist-info/WHEEL +5 -0
  76. matlab_prodserver_client-24.2.dist-info/top_level.txt +3 -0
  77. six.py +953 -0
@@ -0,0 +1,1230 @@
1
+ # Protocol Buffers - Google's data interchange format
2
+ # Copyright 2008 Google Inc. All rights reserved.
3
+ # https://developers.google.com/protocol-buffers/
4
+ #
5
+ # Redistribution and use in source and binary forms, with or without
6
+ # modification, are permitted provided that the following conditions are
7
+ # met:
8
+ #
9
+ # * Redistributions of source code must retain the above copyright
10
+ # notice, this list of conditions and the following disclaimer.
11
+ # * Redistributions in binary form must reproduce the above
12
+ # copyright notice, this list of conditions and the following disclaimer
13
+ # in the documentation and/or other materials provided with the
14
+ # distribution.
15
+ # * Neither the name of Google Inc. nor the names of its
16
+ # contributors may be used to endorse or promote products derived from
17
+ # this software without specific prior written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23
+ # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
+ # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
+ # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
+ # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
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.
30
+
31
+ """Descriptors essentially contain exactly the information found in a .proto
32
+ file, in types that make this information accessible in Python.
33
+ """
34
+
35
+ __author__ = 'robinson@google.com (Will Robinson)'
36
+
37
+ # Mathworks update to fix build error : 12/3/21
38
+ import six
39
+ import threading
40
+ import warnings
41
+
42
+ from google.protobuf_ml.internal import api_implementation
43
+
44
+ _USE_C_DESCRIPTORS = False
45
+ if api_implementation.Type() != 'python':
46
+ # Used by MakeDescriptor in cpp mode
47
+ import binascii
48
+ import os
49
+ # pylint: disable=protected-access
50
+ _message = api_implementation._c_module
51
+ # TODO(jieluo): Remove this import after fix api_implementation
52
+ if _message is None:
53
+ from google.protobuf_ml.pyext import _message
54
+ _USE_C_DESCRIPTORS = True
55
+
56
+
57
+ class Error(Exception):
58
+ """Base error for this module."""
59
+
60
+
61
+ class TypeTransformationError(Error):
62
+ """Error transforming between python proto type and corresponding C++ type."""
63
+
64
+
65
+ if _USE_C_DESCRIPTORS:
66
+ # This metaclass allows to override the behavior of code like
67
+ # isinstance(my_descriptor, FieldDescriptor)
68
+ # and make it return True when the descriptor is an instance of the extension
69
+ # type written in C++.
70
+ class DescriptorMetaclass(type):
71
+ def __instancecheck__(cls, obj):
72
+ if super(DescriptorMetaclass, cls).__instancecheck__(obj):
73
+ return True
74
+ if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
75
+ return True
76
+ return False
77
+ else:
78
+ # The standard metaclass; nothing changes.
79
+ DescriptorMetaclass = type
80
+
81
+
82
+ class _Lock(object):
83
+ """Wrapper class of threading.Lock(), which is allowed by 'with'."""
84
+
85
+ def __new__(cls):
86
+ self = object.__new__(cls)
87
+ self._lock = threading.Lock() # pylint: disable=protected-access
88
+ return self
89
+
90
+ def __enter__(self):
91
+ self._lock.acquire()
92
+
93
+ def __exit__(self, exc_type, exc_value, exc_tb):
94
+ self._lock.release()
95
+
96
+
97
+ _lock = threading.Lock()
98
+
99
+
100
+ def _Deprecated(name):
101
+ if _Deprecated.count > 0:
102
+ _Deprecated.count -= 1
103
+ warnings.warn(
104
+ 'Call to deprecated create function %s(). Note: Create unlinked '
105
+ 'descriptors is going to go away. Please use get/find descriptors from '
106
+ 'generated code or query the descriptor_pool.'
107
+ % name,
108
+ category=DeprecationWarning, stacklevel=3)
109
+
110
+
111
+ # Deprecated warnings will print 100 times at most which should be enough for
112
+ # users to notice and do not cause timeout.
113
+ _Deprecated.count = 100
114
+
115
+
116
+ _internal_create_key = object()
117
+
118
+ #Mathworks update to fix build error: 12/3/21
119
+ class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
120
+
121
+ """Descriptors base class.
122
+
123
+ This class is the base of all descriptor classes. It provides common options
124
+ related functionality.
125
+
126
+ Attributes:
127
+ has_options: True if the descriptor has non-default options. Usually it
128
+ is not necessary to read this -- just call GetOptions() which will
129
+ happily return the default instance. However, it's sometimes useful
130
+ for efficiency, and also useful inside the protobuf implementation to
131
+ avoid some bootstrapping issues.
132
+ """
133
+
134
+ if _USE_C_DESCRIPTORS:
135
+ # The class, or tuple of classes, that are considered as "virtual
136
+ # subclasses" of this descriptor class.
137
+ _C_DESCRIPTOR_CLASS = ()
138
+
139
+ def __init__(self, options, serialized_options, options_class_name):
140
+ """Initialize the descriptor given its options message and the name of the
141
+ class of the options message. The name of the class is required in case
142
+ the options message is None and has to be created.
143
+ """
144
+ self._options = options
145
+ self._options_class_name = options_class_name
146
+ self._serialized_options = serialized_options
147
+
148
+ # Does this descriptor have non-default options?
149
+ self.has_options = (options is not None) or (serialized_options is not None)
150
+
151
+ def _SetOptions(self, options, options_class_name):
152
+ """Sets the descriptor's options
153
+
154
+ This function is used in generated proto2 files to update descriptor
155
+ options. It must not be used outside proto2.
156
+ """
157
+ self._options = options
158
+ self._options_class_name = options_class_name
159
+
160
+ # Does this descriptor have non-default options?
161
+ self.has_options = options is not None
162
+
163
+ def GetOptions(self):
164
+ """Retrieves descriptor options.
165
+
166
+ This method returns the options set or creates the default options for the
167
+ descriptor.
168
+ """
169
+ if self._options:
170
+ return self._options
171
+
172
+ from google.protobuf_ml import descriptor_pb2
173
+ try:
174
+ options_class = getattr(descriptor_pb2,
175
+ self._options_class_name)
176
+ except AttributeError:
177
+ raise RuntimeError('Unknown options class name %s!' %
178
+ (self._options_class_name))
179
+
180
+ with _lock:
181
+ if self._serialized_options is None:
182
+ self._options = options_class()
183
+ else:
184
+ self._options = _ParseOptions(options_class(),
185
+ self._serialized_options)
186
+
187
+ return self._options
188
+
189
+
190
+ class _NestedDescriptorBase(DescriptorBase):
191
+ """Common class for descriptors that can be nested."""
192
+
193
+ def __init__(self, options, options_class_name, name, full_name,
194
+ file, containing_type, serialized_start=None,
195
+ serialized_end=None, serialized_options=None):
196
+ """Constructor.
197
+
198
+ Args:
199
+ options: Protocol message options or None
200
+ to use default message options.
201
+ options_class_name (str): The class name of the above options.
202
+ name (str): Name of this protocol message type.
203
+ full_name (str): Fully-qualified name of this protocol message type,
204
+ which will include protocol "package" name and the name of any
205
+ enclosing types.
206
+ file (FileDescriptor): Reference to file info.
207
+ containing_type: if provided, this is a nested descriptor, with this
208
+ descriptor as parent, otherwise None.
209
+ serialized_start: The start index (inclusive) in block in the
210
+ file.serialized_pb that describes this descriptor.
211
+ serialized_end: The end index (exclusive) in block in the
212
+ file.serialized_pb that describes this descriptor.
213
+ serialized_options: Protocol message serialized options or None.
214
+ """
215
+ super(_NestedDescriptorBase, self).__init__(
216
+ options, serialized_options, options_class_name)
217
+
218
+ self.name = name
219
+ # TODO(falk): Add function to calculate full_name instead of having it in
220
+ # memory?
221
+ self.full_name = full_name
222
+ self.file = file
223
+ self.containing_type = containing_type
224
+
225
+ self._serialized_start = serialized_start
226
+ self._serialized_end = serialized_end
227
+
228
+ def CopyToProto(self, proto):
229
+ """Copies this to the matching proto in descriptor_pb2.
230
+
231
+ Args:
232
+ proto: An empty proto instance from descriptor_pb2.
233
+
234
+ Raises:
235
+ Error: If self couldn't be serialized, due to to few constructor
236
+ arguments.
237
+ """
238
+ if (self.file is not None and
239
+ self._serialized_start is not None and
240
+ self._serialized_end is not None):
241
+ proto.ParseFromString(self.file.serialized_pb[
242
+ self._serialized_start:self._serialized_end])
243
+ else:
244
+ raise Error('Descriptor does not contain serialization.')
245
+
246
+
247
+ class Descriptor(_NestedDescriptorBase):
248
+
249
+ """Descriptor for a protocol message type.
250
+
251
+ Attributes:
252
+ name (str): Name of this protocol message type.
253
+ full_name (str): Fully-qualified name of this protocol message type,
254
+ which will include protocol "package" name and the name of any
255
+ enclosing types.
256
+ containing_type (Descriptor): Reference to the descriptor of the type
257
+ containing us, or None if this is top-level.
258
+ fields (list[FieldDescriptor]): Field descriptors for all fields in
259
+ this type.
260
+ fields_by_number (dict(int, FieldDescriptor)): Same
261
+ :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed
262
+ by "number" attribute in each FieldDescriptor.
263
+ fields_by_name (dict(str, FieldDescriptor)): Same
264
+ :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by
265
+ "name" attribute in each :class:`FieldDescriptor`.
266
+ nested_types (list[Descriptor]): Descriptor references
267
+ for all protocol message types nested within this one.
268
+ nested_types_by_name (dict(str, Descriptor)): Same Descriptor
269
+ objects as in :attr:`nested_types`, but indexed by "name" attribute
270
+ in each Descriptor.
271
+ enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references
272
+ for all enums contained within this type.
273
+ enum_types_by_name (dict(str, EnumDescriptor)): Same
274
+ :class:`EnumDescriptor` objects as in :attr:`enum_types`, but
275
+ indexed by "name" attribute in each EnumDescriptor.
276
+ enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping
277
+ from enum value name to :class:`EnumValueDescriptor` for that value.
278
+ extensions (list[FieldDescriptor]): All extensions defined directly
279
+ within this message type (NOT within a nested type).
280
+ extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor
281
+ objects as :attr:`extensions`, but indexed by "name" attribute of each
282
+ FieldDescriptor.
283
+ is_extendable (bool): Does this type define any extension ranges?
284
+ oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields
285
+ in this message.
286
+ oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in
287
+ :attr:`oneofs`, but indexed by "name" attribute.
288
+ file (FileDescriptor): Reference to file descriptor.
289
+
290
+ """
291
+
292
+ if _USE_C_DESCRIPTORS:
293
+ _C_DESCRIPTOR_CLASS = _message.Descriptor
294
+
295
+ def __new__(
296
+ cls,
297
+ name=None,
298
+ full_name=None,
299
+ filename=None,
300
+ containing_type=None,
301
+ fields=None,
302
+ nested_types=None,
303
+ enum_types=None,
304
+ extensions=None,
305
+ options=None,
306
+ serialized_options=None,
307
+ is_extendable=True,
308
+ extension_ranges=None,
309
+ oneofs=None,
310
+ file=None, # pylint: disable=redefined-builtin
311
+ serialized_start=None,
312
+ serialized_end=None,
313
+ syntax=None,
314
+ create_key=None):
315
+ _message.Message._CheckCalledFromGeneratedFile()
316
+ return _message.default_pool.FindMessageTypeByName(full_name)
317
+
318
+ # NOTE(tmarek): The file argument redefining a builtin is nothing we can
319
+ # fix right now since we don't know how many clients already rely on the
320
+ # name of the argument.
321
+ def __init__(self, name, full_name, filename, containing_type, fields,
322
+ nested_types, enum_types, extensions, options=None,
323
+ serialized_options=None,
324
+ is_extendable=True, extension_ranges=None, oneofs=None,
325
+ file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
326
+ syntax=None, create_key=None):
327
+ """Arguments to __init__() are as described in the description
328
+ of Descriptor fields above.
329
+
330
+ Note that filename is an obsolete argument, that is not used anymore.
331
+ Please use file.name to access this as an attribute.
332
+ """
333
+ if create_key is not _internal_create_key:
334
+ _Deprecated('Descriptor')
335
+
336
+ super(Descriptor, self).__init__(
337
+ options, 'MessageOptions', name, full_name, file,
338
+ containing_type, serialized_start=serialized_start,
339
+ serialized_end=serialized_end, serialized_options=serialized_options)
340
+
341
+ # We have fields in addition to fields_by_name and fields_by_number,
342
+ # so that:
343
+ # 1. Clients can index fields by "order in which they're listed."
344
+ # 2. Clients can easily iterate over all fields with the terse
345
+ # syntax: for f in descriptor.fields: ...
346
+ self.fields = fields
347
+ for field in self.fields:
348
+ field.containing_type = self
349
+ self.fields_by_number = dict((f.number, f) for f in fields)
350
+ self.fields_by_name = dict((f.name, f) for f in fields)
351
+ self._fields_by_camelcase_name = None
352
+
353
+ self.nested_types = nested_types
354
+ for nested_type in nested_types:
355
+ nested_type.containing_type = self
356
+ self.nested_types_by_name = dict((t.name, t) for t in nested_types)
357
+
358
+ self.enum_types = enum_types
359
+ for enum_type in self.enum_types:
360
+ enum_type.containing_type = self
361
+ self.enum_types_by_name = dict((t.name, t) for t in enum_types)
362
+ self.enum_values_by_name = dict(
363
+ (v.name, v) for t in enum_types for v in t.values)
364
+
365
+ self.extensions = extensions
366
+ for extension in self.extensions:
367
+ extension.extension_scope = self
368
+ self.extensions_by_name = dict((f.name, f) for f in extensions)
369
+ self.is_extendable = is_extendable
370
+ self.extension_ranges = extension_ranges
371
+ self.oneofs = oneofs if oneofs is not None else []
372
+ self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
373
+ for oneof in self.oneofs:
374
+ oneof.containing_type = self
375
+ self.syntax = syntax or "proto2"
376
+
377
+ @property
378
+ def fields_by_camelcase_name(self):
379
+ """Same FieldDescriptor objects as in :attr:`fields`, but indexed by
380
+ :attr:`FieldDescriptor.camelcase_name`.
381
+ """
382
+ if self._fields_by_camelcase_name is None:
383
+ self._fields_by_camelcase_name = dict(
384
+ (f.camelcase_name, f) for f in self.fields)
385
+ return self._fields_by_camelcase_name
386
+
387
+ def EnumValueName(self, enum, value):
388
+ """Returns the string name of an enum value.
389
+
390
+ This is just a small helper method to simplify a common operation.
391
+
392
+ Args:
393
+ enum: string name of the Enum.
394
+ value: int, value of the enum.
395
+
396
+ Returns:
397
+ string name of the enum value.
398
+
399
+ Raises:
400
+ KeyError if either the Enum doesn't exist or the value is not a valid
401
+ value for the enum.
402
+ """
403
+ return self.enum_types_by_name[enum].values_by_number[value].name
404
+
405
+ def CopyToProto(self, proto):
406
+ """Copies this to a descriptor_pb2.DescriptorProto.
407
+
408
+ Args:
409
+ proto: An empty descriptor_pb2.DescriptorProto.
410
+ """
411
+ # This function is overridden to give a better doc comment.
412
+ super(Descriptor, self).CopyToProto(proto)
413
+
414
+
415
+ # TODO(robinson): We should have aggressive checking here,
416
+ # for example:
417
+ # * If you specify a repeated field, you should not be allowed
418
+ # to specify a default value.
419
+ # * [Other examples here as needed].
420
+ #
421
+ # TODO(robinson): for this and other *Descriptor classes, we
422
+ # might also want to lock things down aggressively (e.g.,
423
+ # prevent clients from setting the attributes). Having
424
+ # stronger invariants here in general will reduce the number
425
+ # of runtime checks we must do in reflection.py...
426
+ class FieldDescriptor(DescriptorBase):
427
+
428
+ """Descriptor for a single field in a .proto file.
429
+
430
+ Attributes:
431
+ name (str): Name of this field, exactly as it appears in .proto.
432
+ full_name (str): Name of this field, including containing scope. This is
433
+ particularly relevant for extensions.
434
+ index (int): Dense, 0-indexed index giving the order that this
435
+ field textually appears within its message in the .proto file.
436
+ number (int): Tag number declared for this field in the .proto file.
437
+
438
+ type (int): (One of the TYPE_* constants below) Declared type.
439
+ cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to
440
+ represent this field.
441
+
442
+ label (int): (One of the LABEL_* constants below) Tells whether this
443
+ field is optional, required, or repeated.
444
+ has_default_value (bool): True if this field has a default value defined,
445
+ otherwise false.
446
+ default_value (Varies): Default value of this field. Only
447
+ meaningful for non-repeated scalar fields. Repeated fields
448
+ should always set this to [], and non-repeated composite
449
+ fields should always set this to None.
450
+
451
+ containing_type (Descriptor): Descriptor of the protocol message
452
+ type that contains this field. Set by the Descriptor constructor
453
+ if we're passed into one.
454
+ Somewhat confusingly, for extension fields, this is the
455
+ descriptor of the EXTENDED message, not the descriptor
456
+ of the message containing this field. (See is_extension and
457
+ extension_scope below).
458
+ message_type (Descriptor): If a composite field, a descriptor
459
+ of the message type contained in this field. Otherwise, this is None.
460
+ enum_type (EnumDescriptor): If this field contains an enum, a
461
+ descriptor of that enum. Otherwise, this is None.
462
+
463
+ is_extension: True iff this describes an extension field.
464
+ extension_scope (Descriptor): Only meaningful if is_extension is True.
465
+ Gives the message that immediately contains this extension field.
466
+ Will be None iff we're a top-level (file-level) extension field.
467
+
468
+ options (descriptor_pb2.FieldOptions): Protocol message field options or
469
+ None to use default field options.
470
+
471
+ containing_oneof (OneofDescriptor): If the field is a member of a oneof
472
+ union, contains its descriptor. Otherwise, None.
473
+
474
+ file (FileDescriptor): Reference to file descriptor.
475
+ """
476
+
477
+ # Must be consistent with C++ FieldDescriptor::Type enum in
478
+ # descriptor.h.
479
+ #
480
+ # TODO(robinson): Find a way to eliminate this repetition.
481
+ TYPE_DOUBLE = 1
482
+ TYPE_FLOAT = 2
483
+ TYPE_INT64 = 3
484
+ TYPE_UINT64 = 4
485
+ TYPE_INT32 = 5
486
+ TYPE_FIXED64 = 6
487
+ TYPE_FIXED32 = 7
488
+ TYPE_BOOL = 8
489
+ TYPE_STRING = 9
490
+ TYPE_GROUP = 10
491
+ TYPE_MESSAGE = 11
492
+ TYPE_BYTES = 12
493
+ TYPE_UINT32 = 13
494
+ TYPE_ENUM = 14
495
+ TYPE_SFIXED32 = 15
496
+ TYPE_SFIXED64 = 16
497
+ TYPE_SINT32 = 17
498
+ TYPE_SINT64 = 18
499
+ MAX_TYPE = 18
500
+
501
+ # Must be consistent with C++ FieldDescriptor::CppType enum in
502
+ # descriptor.h.
503
+ #
504
+ # TODO(robinson): Find a way to eliminate this repetition.
505
+ CPPTYPE_INT32 = 1
506
+ CPPTYPE_INT64 = 2
507
+ CPPTYPE_UINT32 = 3
508
+ CPPTYPE_UINT64 = 4
509
+ CPPTYPE_DOUBLE = 5
510
+ CPPTYPE_FLOAT = 6
511
+ CPPTYPE_BOOL = 7
512
+ CPPTYPE_ENUM = 8
513
+ CPPTYPE_STRING = 9
514
+ CPPTYPE_MESSAGE = 10
515
+ MAX_CPPTYPE = 10
516
+
517
+ _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
518
+ TYPE_DOUBLE: CPPTYPE_DOUBLE,
519
+ TYPE_FLOAT: CPPTYPE_FLOAT,
520
+ TYPE_ENUM: CPPTYPE_ENUM,
521
+ TYPE_INT64: CPPTYPE_INT64,
522
+ TYPE_SINT64: CPPTYPE_INT64,
523
+ TYPE_SFIXED64: CPPTYPE_INT64,
524
+ TYPE_UINT64: CPPTYPE_UINT64,
525
+ TYPE_FIXED64: CPPTYPE_UINT64,
526
+ TYPE_INT32: CPPTYPE_INT32,
527
+ TYPE_SFIXED32: CPPTYPE_INT32,
528
+ TYPE_SINT32: CPPTYPE_INT32,
529
+ TYPE_UINT32: CPPTYPE_UINT32,
530
+ TYPE_FIXED32: CPPTYPE_UINT32,
531
+ TYPE_BYTES: CPPTYPE_STRING,
532
+ TYPE_STRING: CPPTYPE_STRING,
533
+ TYPE_BOOL: CPPTYPE_BOOL,
534
+ TYPE_MESSAGE: CPPTYPE_MESSAGE,
535
+ TYPE_GROUP: CPPTYPE_MESSAGE
536
+ }
537
+
538
+ # Must be consistent with C++ FieldDescriptor::Label enum in
539
+ # descriptor.h.
540
+ #
541
+ # TODO(robinson): Find a way to eliminate this repetition.
542
+ LABEL_OPTIONAL = 1
543
+ LABEL_REQUIRED = 2
544
+ LABEL_REPEATED = 3
545
+ MAX_LABEL = 3
546
+
547
+ # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
548
+ # and kLastReservedNumber in descriptor.h
549
+ MAX_FIELD_NUMBER = (1 << 29) - 1
550
+ FIRST_RESERVED_FIELD_NUMBER = 19000
551
+ LAST_RESERVED_FIELD_NUMBER = 19999
552
+
553
+ if _USE_C_DESCRIPTORS:
554
+ _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
555
+
556
+ def __new__(cls, name, full_name, index, number, type, cpp_type, label,
557
+ default_value, message_type, enum_type, containing_type,
558
+ is_extension, extension_scope, options=None,
559
+ serialized_options=None,
560
+ has_default_value=True, containing_oneof=None, json_name=None,
561
+ file=None, create_key=None): # pylint: disable=redefined-builtin
562
+ _message.Message._CheckCalledFromGeneratedFile()
563
+ if is_extension:
564
+ return _message.default_pool.FindExtensionByName(full_name)
565
+ else:
566
+ return _message.default_pool.FindFieldByName(full_name)
567
+
568
+ def __init__(self, name, full_name, index, number, type, cpp_type, label,
569
+ default_value, message_type, enum_type, containing_type,
570
+ is_extension, extension_scope, options=None,
571
+ serialized_options=None,
572
+ has_default_value=True, containing_oneof=None, json_name=None,
573
+ file=None, create_key=None): # pylint: disable=redefined-builtin
574
+ """The arguments are as described in the description of FieldDescriptor
575
+ attributes above.
576
+
577
+ Note that containing_type may be None, and may be set later if necessary
578
+ (to deal with circular references between message types, for example).
579
+ Likewise for extension_scope.
580
+ """
581
+ if create_key is not _internal_create_key:
582
+ _Deprecated('FieldDescriptor')
583
+
584
+ super(FieldDescriptor, self).__init__(
585
+ options, serialized_options, 'FieldOptions')
586
+ self.name = name
587
+ self.full_name = full_name
588
+ self.file = file
589
+ self._camelcase_name = None
590
+ if json_name is None:
591
+ self.json_name = _ToJsonName(name)
592
+ else:
593
+ self.json_name = json_name
594
+ self.index = index
595
+ self.number = number
596
+ self.type = type
597
+ self.cpp_type = cpp_type
598
+ self.label = label
599
+ self.has_default_value = has_default_value
600
+ self.default_value = default_value
601
+ self.containing_type = containing_type
602
+ self.message_type = message_type
603
+ self.enum_type = enum_type
604
+ self.is_extension = is_extension
605
+ self.extension_scope = extension_scope
606
+ self.containing_oneof = containing_oneof
607
+ if api_implementation.Type() == 'python':
608
+ self._cdescriptor = None
609
+ else:
610
+ if is_extension:
611
+ self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
612
+ else:
613
+ self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
614
+
615
+ @property
616
+ def camelcase_name(self):
617
+ """Camelcase name of this field.
618
+
619
+ Returns:
620
+ str: the name in CamelCase.
621
+ """
622
+ if self._camelcase_name is None:
623
+ self._camelcase_name = _ToCamelCase(self.name)
624
+ return self._camelcase_name
625
+
626
+ @property
627
+ def has_presence(self):
628
+ """Whether the field distinguishes between unpopulated and default values.
629
+
630
+ Raises:
631
+ RuntimeError: singular field that is not linked with message nor file.
632
+ """
633
+ if self.label == FieldDescriptor.LABEL_REPEATED:
634
+ return False
635
+ if (self.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE or
636
+ self.containing_oneof):
637
+ return True
638
+ if hasattr(self.file, 'syntax'):
639
+ return self.file.syntax == 'proto2'
640
+ if hasattr(self.message_type, 'syntax'):
641
+ return self.message_type.syntax == 'proto2'
642
+ raise RuntimeError(
643
+ 'has_presence is not ready to use because field %s is not'
644
+ ' linked with message type nor file' % self.full_name)
645
+
646
+ @staticmethod
647
+ def ProtoTypeToCppProtoType(proto_type):
648
+ """Converts from a Python proto type to a C++ Proto Type.
649
+
650
+ The Python ProtocolBuffer classes specify both the 'Python' datatype and the
651
+ 'C++' datatype - and they're not the same. This helper method should
652
+ translate from one to another.
653
+
654
+ Args:
655
+ proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
656
+ Returns:
657
+ int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
658
+ Raises:
659
+ TypeTransformationError: when the Python proto type isn't known.
660
+ """
661
+ try:
662
+ return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
663
+ except KeyError:
664
+ raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
665
+
666
+
667
+ class EnumDescriptor(_NestedDescriptorBase):
668
+
669
+ """Descriptor for an enum defined in a .proto file.
670
+
671
+ Attributes:
672
+ name (str): Name of the enum type.
673
+ full_name (str): Full name of the type, including package name
674
+ and any enclosing type(s).
675
+
676
+ values (list[EnumValueDescriptor]): List of the values
677
+ in this enum.
678
+ values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`,
679
+ but indexed by the "name" field of each EnumValueDescriptor.
680
+ values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`,
681
+ but indexed by the "number" field of each EnumValueDescriptor.
682
+ containing_type (Descriptor): Descriptor of the immediate containing
683
+ type of this enum, or None if this is an enum defined at the
684
+ top level in a .proto file. Set by Descriptor's constructor
685
+ if we're passed into one.
686
+ file (FileDescriptor): Reference to file descriptor.
687
+ options (descriptor_pb2.EnumOptions): Enum options message or
688
+ None to use default enum options.
689
+ """
690
+
691
+ if _USE_C_DESCRIPTORS:
692
+ _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
693
+
694
+ def __new__(cls, name, full_name, filename, values,
695
+ containing_type=None, options=None,
696
+ serialized_options=None, file=None, # pylint: disable=redefined-builtin
697
+ serialized_start=None, serialized_end=None, create_key=None):
698
+ _message.Message._CheckCalledFromGeneratedFile()
699
+ return _message.default_pool.FindEnumTypeByName(full_name)
700
+
701
+ def __init__(self, name, full_name, filename, values,
702
+ containing_type=None, options=None,
703
+ serialized_options=None, file=None, # pylint: disable=redefined-builtin
704
+ serialized_start=None, serialized_end=None, create_key=None):
705
+ """Arguments are as described in the attribute description above.
706
+
707
+ Note that filename is an obsolete argument, that is not used anymore.
708
+ Please use file.name to access this as an attribute.
709
+ """
710
+ if create_key is not _internal_create_key:
711
+ _Deprecated('EnumDescriptor')
712
+
713
+ super(EnumDescriptor, self).__init__(
714
+ options, 'EnumOptions', name, full_name, file,
715
+ containing_type, serialized_start=serialized_start,
716
+ serialized_end=serialized_end, serialized_options=serialized_options)
717
+
718
+ self.values = values
719
+ for value in self.values:
720
+ value.type = self
721
+ self.values_by_name = dict((v.name, v) for v in values)
722
+ # Values are reversed to ensure that the first alias is retained.
723
+ self.values_by_number = dict((v.number, v) for v in reversed(values))
724
+
725
+ def CopyToProto(self, proto):
726
+ """Copies this to a descriptor_pb2.EnumDescriptorProto.
727
+
728
+ Args:
729
+ proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto.
730
+ """
731
+ # This function is overridden to give a better doc comment.
732
+ super(EnumDescriptor, self).CopyToProto(proto)
733
+
734
+
735
+ class EnumValueDescriptor(DescriptorBase):
736
+
737
+ """Descriptor for a single value within an enum.
738
+
739
+ Attributes:
740
+ name (str): Name of this value.
741
+ index (int): Dense, 0-indexed index giving the order that this
742
+ value appears textually within its enum in the .proto file.
743
+ number (int): Actual number assigned to this enum value.
744
+ type (EnumDescriptor): :class:`EnumDescriptor` to which this value
745
+ belongs. Set by :class:`EnumDescriptor`'s constructor if we're
746
+ passed into one.
747
+ options (descriptor_pb2.EnumValueOptions): Enum value options message or
748
+ None to use default enum value options options.
749
+ """
750
+
751
+ if _USE_C_DESCRIPTORS:
752
+ _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
753
+
754
+ def __new__(cls, name, index, number,
755
+ type=None, # pylint: disable=redefined-builtin
756
+ options=None, serialized_options=None, create_key=None):
757
+ _message.Message._CheckCalledFromGeneratedFile()
758
+ # There is no way we can build a complete EnumValueDescriptor with the
759
+ # given parameters (the name of the Enum is not known, for example).
760
+ # Fortunately generated files just pass it to the EnumDescriptor()
761
+ # constructor, which will ignore it, so returning None is good enough.
762
+ return None
763
+
764
+ def __init__(self, name, index, number,
765
+ type=None, # pylint: disable=redefined-builtin
766
+ options=None, serialized_options=None, create_key=None):
767
+ """Arguments are as described in the attribute description above."""
768
+ if create_key is not _internal_create_key:
769
+ _Deprecated('EnumValueDescriptor')
770
+
771
+ super(EnumValueDescriptor, self).__init__(
772
+ options, serialized_options, 'EnumValueOptions')
773
+ self.name = name
774
+ self.index = index
775
+ self.number = number
776
+ self.type = type
777
+
778
+
779
+ class OneofDescriptor(DescriptorBase):
780
+ """Descriptor for a oneof field.
781
+
782
+ Attributes:
783
+ name (str): Name of the oneof field.
784
+ full_name (str): Full name of the oneof field, including package name.
785
+ index (int): 0-based index giving the order of the oneof field inside
786
+ its containing type.
787
+ containing_type (Descriptor): :class:`Descriptor` of the protocol message
788
+ type that contains this field. Set by the :class:`Descriptor` constructor
789
+ if we're passed into one.
790
+ fields (list[FieldDescriptor]): The list of field descriptors this
791
+ oneof can contain.
792
+ """
793
+
794
+ if _USE_C_DESCRIPTORS:
795
+ _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
796
+
797
+ def __new__(
798
+ cls, name, full_name, index, containing_type, fields, options=None,
799
+ serialized_options=None, create_key=None):
800
+ _message.Message._CheckCalledFromGeneratedFile()
801
+ return _message.default_pool.FindOneofByName(full_name)
802
+
803
+ def __init__(
804
+ self, name, full_name, index, containing_type, fields, options=None,
805
+ serialized_options=None, create_key=None):
806
+ """Arguments are as described in the attribute description above."""
807
+ if create_key is not _internal_create_key:
808
+ _Deprecated('OneofDescriptor')
809
+
810
+ super(OneofDescriptor, self).__init__(
811
+ options, serialized_options, 'OneofOptions')
812
+ self.name = name
813
+ self.full_name = full_name
814
+ self.index = index
815
+ self.containing_type = containing_type
816
+ self.fields = fields
817
+
818
+
819
+ class ServiceDescriptor(_NestedDescriptorBase):
820
+
821
+ """Descriptor for a service.
822
+
823
+ Attributes:
824
+ name (str): Name of the service.
825
+ full_name (str): Full name of the service, including package name.
826
+ index (int): 0-indexed index giving the order that this services
827
+ definition appears within the .proto file.
828
+ methods (list[MethodDescriptor]): List of methods provided by this
829
+ service.
830
+ methods_by_name (dict(str, MethodDescriptor)): Same
831
+ :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but
832
+ indexed by "name" attribute in each :class:`MethodDescriptor`.
833
+ options (descriptor_pb2.ServiceOptions): Service options message or
834
+ None to use default service options.
835
+ file (FileDescriptor): Reference to file info.
836
+ """
837
+
838
+ if _USE_C_DESCRIPTORS:
839
+ _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
840
+
841
+ def __new__(
842
+ cls,
843
+ name=None,
844
+ full_name=None,
845
+ index=None,
846
+ methods=None,
847
+ options=None,
848
+ serialized_options=None,
849
+ file=None, # pylint: disable=redefined-builtin
850
+ serialized_start=None,
851
+ serialized_end=None,
852
+ create_key=None):
853
+ _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
854
+ return _message.default_pool.FindServiceByName(full_name)
855
+
856
+ def __init__(self, name, full_name, index, methods, options=None,
857
+ serialized_options=None, file=None, # pylint: disable=redefined-builtin
858
+ serialized_start=None, serialized_end=None, create_key=None):
859
+ if create_key is not _internal_create_key:
860
+ _Deprecated('ServiceDescriptor')
861
+
862
+ super(ServiceDescriptor, self).__init__(
863
+ options, 'ServiceOptions', name, full_name, file,
864
+ None, serialized_start=serialized_start,
865
+ serialized_end=serialized_end, serialized_options=serialized_options)
866
+ self.index = index
867
+ self.methods = methods
868
+ self.methods_by_name = dict((m.name, m) for m in methods)
869
+ # Set the containing service for each method in this service.
870
+ for method in self.methods:
871
+ method.containing_service = self
872
+
873
+ def FindMethodByName(self, name):
874
+ """Searches for the specified method, and returns its descriptor.
875
+
876
+ Args:
877
+ name (str): Name of the method.
878
+ Returns:
879
+ MethodDescriptor or None: the descriptor for the requested method, if
880
+ found.
881
+ """
882
+ return self.methods_by_name.get(name, None)
883
+
884
+ def CopyToProto(self, proto):
885
+ """Copies this to a descriptor_pb2.ServiceDescriptorProto.
886
+
887
+ Args:
888
+ proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto.
889
+ """
890
+ # This function is overridden to give a better doc comment.
891
+ super(ServiceDescriptor, self).CopyToProto(proto)
892
+
893
+
894
+ class MethodDescriptor(DescriptorBase):
895
+
896
+ """Descriptor for a method in a service.
897
+
898
+ Attributes:
899
+ name (str): Name of the method within the service.
900
+ full_name (str): Full name of method.
901
+ index (int): 0-indexed index of the method inside the service.
902
+ containing_service (ServiceDescriptor): The service that contains this
903
+ method.
904
+ input_type (Descriptor): The descriptor of the message that this method
905
+ accepts.
906
+ output_type (Descriptor): The descriptor of the message that this method
907
+ returns.
908
+ client_streaming (bool): Whether this method uses client streaming.
909
+ server_streaming (bool): Whether this method uses server streaming.
910
+ options (descriptor_pb2.MethodOptions or None): Method options message, or
911
+ None to use default method options.
912
+ """
913
+
914
+ if _USE_C_DESCRIPTORS:
915
+ _C_DESCRIPTOR_CLASS = _message.MethodDescriptor
916
+
917
+ def __new__(cls,
918
+ name,
919
+ full_name,
920
+ index,
921
+ containing_service,
922
+ input_type,
923
+ output_type,
924
+ client_streaming=False,
925
+ server_streaming=False,
926
+ options=None,
927
+ serialized_options=None,
928
+ create_key=None):
929
+ _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
930
+ return _message.default_pool.FindMethodByName(full_name)
931
+
932
+ def __init__(self,
933
+ name,
934
+ full_name,
935
+ index,
936
+ containing_service,
937
+ input_type,
938
+ output_type,
939
+ client_streaming=False,
940
+ server_streaming=False,
941
+ options=None,
942
+ serialized_options=None,
943
+ create_key=None):
944
+ """The arguments are as described in the description of MethodDescriptor
945
+ attributes above.
946
+
947
+ Note that containing_service may be None, and may be set later if necessary.
948
+ """
949
+ if create_key is not _internal_create_key:
950
+ _Deprecated('MethodDescriptor')
951
+
952
+ super(MethodDescriptor, self).__init__(
953
+ options, serialized_options, 'MethodOptions')
954
+ self.name = name
955
+ self.full_name = full_name
956
+ self.index = index
957
+ self.containing_service = containing_service
958
+ self.input_type = input_type
959
+ self.output_type = output_type
960
+ self.client_streaming = client_streaming
961
+ self.server_streaming = server_streaming
962
+
963
+ def CopyToProto(self, proto):
964
+ """Copies this to a descriptor_pb2.MethodDescriptorProto.
965
+
966
+ Args:
967
+ proto (descriptor_pb2.MethodDescriptorProto): An empty descriptor proto.
968
+
969
+ Raises:
970
+ Error: If self couldn't be serialized, due to too few constructor
971
+ arguments.
972
+ """
973
+ if self.containing_service is not None:
974
+ from google.protobuf_ml import descriptor_pb2
975
+ service_proto = descriptor_pb2.ServiceDescriptorProto()
976
+ self.containing_service.CopyToProto(service_proto)
977
+ proto.CopyFrom(service_proto.method[self.index])
978
+ else:
979
+ raise Error('Descriptor does not contain a service.')
980
+
981
+
982
+ class FileDescriptor(DescriptorBase):
983
+ """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
984
+
985
+ Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and
986
+ :attr:`dependencies` fields are only set by the
987
+ :py:mod:`google.protobuf_ml.message_factory` module, and not by the generated
988
+ proto code.
989
+
990
+ Attributes:
991
+ name (str): Name of file, relative to root of source tree.
992
+ package (str): Name of the package
993
+ syntax (str): string indicating syntax of the file (can be "proto2" or
994
+ "proto3")
995
+ serialized_pb (bytes): Byte string of serialized
996
+ :class:`descriptor_pb2.FileDescriptorProto`.
997
+ dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor`
998
+ objects this :class:`FileDescriptor` depends on.
999
+ public_dependencies (list[FileDescriptor]): A subset of
1000
+ :attr:`dependencies`, which were declared as "public".
1001
+ message_types_by_name (dict(str, Descriptor)): Mapping from message names
1002
+ to their :class:`Descriptor`.
1003
+ enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to
1004
+ their :class:`EnumDescriptor`.
1005
+ extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension
1006
+ names declared at file scope to their :class:`FieldDescriptor`.
1007
+ services_by_name (dict(str, ServiceDescriptor)): Mapping from services'
1008
+ names to their :class:`ServiceDescriptor`.
1009
+ pool (DescriptorPool): The pool this descriptor belongs to. When not
1010
+ passed to the constructor, the global default pool is used.
1011
+ """
1012
+
1013
+ if _USE_C_DESCRIPTORS:
1014
+ _C_DESCRIPTOR_CLASS = _message.FileDescriptor
1015
+
1016
+ def __new__(cls, name, package, options=None,
1017
+ serialized_options=None, serialized_pb=None,
1018
+ dependencies=None, public_dependencies=None,
1019
+ syntax=None, pool=None, create_key=None):
1020
+ # FileDescriptor() is called from various places, not only from generated
1021
+ # files, to register dynamic proto files and messages.
1022
+ # pylint: disable=g-explicit-bool-comparison
1023
+ if serialized_pb == b'':
1024
+ # Cpp generated code must be linked in if serialized_pb is ''
1025
+ try:
1026
+ return _message.default_pool.FindFileByName(name)
1027
+ except KeyError:
1028
+ raise RuntimeError('Please link in cpp generated lib for %s' % (name))
1029
+ elif serialized_pb:
1030
+ return _message.default_pool.AddSerializedFile(serialized_pb)
1031
+ else:
1032
+ return super(FileDescriptor, cls).__new__(cls)
1033
+
1034
+ def __init__(self, name, package, options=None,
1035
+ serialized_options=None, serialized_pb=None,
1036
+ dependencies=None, public_dependencies=None,
1037
+ syntax=None, pool=None, create_key=None):
1038
+ """Constructor."""
1039
+ if create_key is not _internal_create_key:
1040
+ _Deprecated('FileDescriptor')
1041
+
1042
+ super(FileDescriptor, self).__init__(
1043
+ options, serialized_options, 'FileOptions')
1044
+
1045
+ if pool is None:
1046
+ from google.protobuf_ml import descriptor_pool
1047
+ pool = descriptor_pool.Default()
1048
+ self.pool = pool
1049
+ self.message_types_by_name = {}
1050
+ self.name = name
1051
+ self.package = package
1052
+ self.syntax = syntax or "proto2"
1053
+ self.serialized_pb = serialized_pb
1054
+
1055
+ self.enum_types_by_name = {}
1056
+ self.extensions_by_name = {}
1057
+ self.services_by_name = {}
1058
+ self.dependencies = (dependencies or [])
1059
+ self.public_dependencies = (public_dependencies or [])
1060
+
1061
+ def CopyToProto(self, proto):
1062
+ """Copies this to a descriptor_pb2.FileDescriptorProto.
1063
+
1064
+ Args:
1065
+ proto: An empty descriptor_pb2.FileDescriptorProto.
1066
+ """
1067
+ proto.ParseFromString(self.serialized_pb)
1068
+
1069
+
1070
+ def _ParseOptions(message, string):
1071
+ """Parses serialized options.
1072
+
1073
+ This helper function is used to parse serialized options in generated
1074
+ proto2 files. It must not be used outside proto2.
1075
+ """
1076
+ message.ParseFromString(string)
1077
+ return message
1078
+
1079
+
1080
+ def _ToCamelCase(name):
1081
+ """Converts name to camel-case and returns it."""
1082
+ capitalize_next = False
1083
+ result = []
1084
+
1085
+ for c in name:
1086
+ if c == '_':
1087
+ if result:
1088
+ capitalize_next = True
1089
+ elif capitalize_next:
1090
+ result.append(c.upper())
1091
+ capitalize_next = False
1092
+ else:
1093
+ result += c
1094
+
1095
+ # Lower-case the first letter.
1096
+ if result and result[0].isupper():
1097
+ result[0] = result[0].lower()
1098
+ return ''.join(result)
1099
+
1100
+
1101
+ def _OptionsOrNone(descriptor_proto):
1102
+ """Returns the value of the field `options`, or None if it is not set."""
1103
+ if descriptor_proto.HasField('options'):
1104
+ return descriptor_proto.options
1105
+ else:
1106
+ return None
1107
+
1108
+
1109
+ def _ToJsonName(name):
1110
+ """Converts name to Json name and returns it."""
1111
+ capitalize_next = False
1112
+ result = []
1113
+
1114
+ for c in name:
1115
+ if c == '_':
1116
+ capitalize_next = True
1117
+ elif capitalize_next:
1118
+ result.append(c.upper())
1119
+ capitalize_next = False
1120
+ else:
1121
+ result += c
1122
+
1123
+ return ''.join(result)
1124
+
1125
+
1126
+ def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
1127
+ syntax=None):
1128
+ """Make a protobuf Descriptor given a DescriptorProto protobuf.
1129
+
1130
+ Handles nested descriptors. Note that this is limited to the scope of defining
1131
+ a message inside of another message. Composite fields can currently only be
1132
+ resolved if the message is defined in the same scope as the field.
1133
+
1134
+ Args:
1135
+ desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
1136
+ package: Optional package name for the new message Descriptor (string).
1137
+ build_file_if_cpp: Update the C++ descriptor pool if api matches.
1138
+ Set to False on recursion, so no duplicates are created.
1139
+ syntax: The syntax/semantics that should be used. Set to "proto3" to get
1140
+ proto3 field presence semantics.
1141
+ Returns:
1142
+ A Descriptor for protobuf messages.
1143
+ """
1144
+ if api_implementation.Type() != 'python' and build_file_if_cpp:
1145
+ # The C++ implementation requires all descriptors to be backed by the same
1146
+ # definition in the C++ descriptor pool. To do this, we build a
1147
+ # FileDescriptorProto with the same definition as this descriptor and build
1148
+ # it into the pool.
1149
+ from google.protobuf_ml import descriptor_pb2
1150
+ file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
1151
+ file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
1152
+
1153
+ # Generate a random name for this proto file to prevent conflicts with any
1154
+ # imported ones. We need to specify a file name so the descriptor pool
1155
+ # accepts our FileDescriptorProto, but it is not important what that file
1156
+ # name is actually set to.
1157
+ proto_name = binascii.hexlify(os.urandom(16)).decode('ascii')
1158
+
1159
+ if package:
1160
+ file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
1161
+ proto_name + '.proto')
1162
+ file_descriptor_proto.package = package
1163
+ else:
1164
+ file_descriptor_proto.name = proto_name + '.proto'
1165
+
1166
+ _message.default_pool.Add(file_descriptor_proto)
1167
+ result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
1168
+
1169
+ if _USE_C_DESCRIPTORS:
1170
+ return result.message_types_by_name[desc_proto.name]
1171
+
1172
+ full_message_name = [desc_proto.name]
1173
+ if package: full_message_name.insert(0, package)
1174
+
1175
+ # Create Descriptors for enum types
1176
+ enum_types = {}
1177
+ for enum_proto in desc_proto.enum_type:
1178
+ full_name = '.'.join(full_message_name + [enum_proto.name])
1179
+ enum_desc = EnumDescriptor(
1180
+ enum_proto.name, full_name, None, [
1181
+ EnumValueDescriptor(enum_val.name, ii, enum_val.number,
1182
+ create_key=_internal_create_key)
1183
+ for ii, enum_val in enumerate(enum_proto.value)],
1184
+ create_key=_internal_create_key)
1185
+ enum_types[full_name] = enum_desc
1186
+
1187
+ # Create Descriptors for nested types
1188
+ nested_types = {}
1189
+ for nested_proto in desc_proto.nested_type:
1190
+ full_name = '.'.join(full_message_name + [nested_proto.name])
1191
+ # Nested types are just those defined inside of the message, not all types
1192
+ # used by fields in the message, so no loops are possible here.
1193
+ nested_desc = MakeDescriptor(nested_proto,
1194
+ package='.'.join(full_message_name),
1195
+ build_file_if_cpp=False,
1196
+ syntax=syntax)
1197
+ nested_types[full_name] = nested_desc
1198
+
1199
+ fields = []
1200
+ for field_proto in desc_proto.field:
1201
+ full_name = '.'.join(full_message_name + [field_proto.name])
1202
+ enum_desc = None
1203
+ nested_desc = None
1204
+ if field_proto.json_name:
1205
+ json_name = field_proto.json_name
1206
+ else:
1207
+ json_name = None
1208
+ if field_proto.HasField('type_name'):
1209
+ type_name = field_proto.type_name
1210
+ full_type_name = '.'.join(full_message_name +
1211
+ [type_name[type_name.rfind('.')+1:]])
1212
+ if full_type_name in nested_types:
1213
+ nested_desc = nested_types[full_type_name]
1214
+ elif full_type_name in enum_types:
1215
+ enum_desc = enum_types[full_type_name]
1216
+ # Else type_name references a non-local type, which isn't implemented
1217
+ field = FieldDescriptor(
1218
+ field_proto.name, full_name, field_proto.number - 1,
1219
+ field_proto.number, field_proto.type,
1220
+ FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
1221
+ field_proto.label, None, nested_desc, enum_desc, None, False, None,
1222
+ options=_OptionsOrNone(field_proto), has_default_value=False,
1223
+ json_name=json_name, create_key=_internal_create_key)
1224
+ fields.append(field)
1225
+
1226
+ desc_name = '.'.join(full_message_name)
1227
+ return Descriptor(desc_proto.name, desc_name, None, None, fields,
1228
+ list(nested_types.values()), list(enum_types.values()), [],
1229
+ options=_OptionsOrNone(desc_proto),
1230
+ create_key=_internal_create_key)