1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // Author: anuraag@google.com (Anuraag Agrawal)
32 // Author: tibell@google.com (Johan Tibell)
34 #include <google/protobuf/pyext/message.h>
38 #include <google/protobuf/stubs/shared_ptr.h>
43 #ifndef PyVarObject_HEAD_INIT
44 #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
47 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
49 #include <google/protobuf/descriptor.pb.h>
50 #include <google/protobuf/stubs/common.h>
51 #include <google/protobuf/io/coded_stream.h>
52 #include <google/protobuf/descriptor.h>
53 #include <google/protobuf/dynamic_message.h>
54 #include <google/protobuf/message.h>
55 #include <google/protobuf/text_format.h>
56 #include <google/protobuf/pyext/descriptor.h>
57 #include <google/protobuf/pyext/extension_dict.h>
58 #include <google/protobuf/pyext/repeated_composite_container.h>
59 #include <google/protobuf/pyext/repeated_scalar_container.h>
60 #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
62 #if PY_MAJOR_VERSION >= 3
63 #define PyInt_Check PyLong_Check
64 #define PyInt_AsLong PyLong_AsLong
65 #define PyInt_FromLong PyLong_FromLong
66 #define PyInt_FromSize_t PyLong_FromSize_t
67 #define PyString_Check PyUnicode_Check
68 #define PyString_FromString PyUnicode_FromString
69 #define PyString_FromStringAndSize PyUnicode_FromStringAndSize
70 #if PY_VERSION_HEX < 0x03030000
71 #error "Python 3.0 - 3.2 are not supported."
73 #define PyString_AsString(ob) \
74 (PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AS_STRING(ob))
82 // Forward declarations
84 static PyObject* GetDescriptor(CMessage* self, PyObject* name);
85 static string GetMessageName(CMessage* self);
86 int InternalReleaseFieldByDescriptor(
87 const google::protobuf::FieldDescriptor* field_descriptor,
88 PyObject* composite_field,
89 google::protobuf::Message* parent_message);
90 } // namespace cmessage
92 // ---------------------------------------------------------------------
93 // Visiting the composite children of a CMessage
96 // Returns 0 on success, -1 on failure.
97 int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
101 // Returns 0 on success, -1 on failure.
102 int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
106 // Returns 0 on success, -1 on failure.
107 int VisitCMessage(CMessage* cmessage,
108 const google::protobuf::FieldDescriptor* field_descriptor) {
113 // Apply a function to a composite field. Does nothing if child is of
114 // non-composite type.
115 template<class Visitor>
116 static int VisitCompositeField(const FieldDescriptor* descriptor,
119 if (descriptor->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED) {
120 if (descriptor->cpp_type() == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
121 RepeatedCompositeContainer* container =
122 reinterpret_cast<RepeatedCompositeContainer*>(child);
123 if (visitor.VisitRepeatedCompositeContainer(container) == -1)
126 RepeatedScalarContainer* container =
127 reinterpret_cast<RepeatedScalarContainer*>(child);
128 if (visitor.VisitRepeatedScalarContainer(container) == -1)
131 } else if (descriptor->cpp_type() ==
132 google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
133 CMessage* cmsg = reinterpret_cast<CMessage*>(child);
134 if (visitor.VisitCMessage(cmsg, descriptor) == -1)
137 // The ExtensionDict might contain non-composite fields, which we
142 // Visit each composite field and extension field of this CMessage.
143 // Returns -1 on error and 0 on success.
144 template<class Visitor>
145 int ForEachCompositeField(CMessage* self, Visitor visitor) {
150 // Visit normal fields.
151 while (PyDict_Next(self->composite_fields, &pos, &key, &field)) {
152 PyObject* cdescriptor = cmessage::GetDescriptor(self, key);
153 if (cdescriptor != NULL) {
154 const google::protobuf::FieldDescriptor* descriptor =
155 reinterpret_cast<CFieldDescriptor*>(cdescriptor)->descriptor;
156 if (VisitCompositeField(descriptor, field, visitor) == -1)
161 // Visit extension fields.
162 if (self->extensions != NULL) {
163 while (PyDict_Next(self->extensions->values, &pos, &key, &field)) {
164 CFieldDescriptor* cdescriptor =
165 extension_dict::InternalGetCDescriptorFromExtension(key);
166 if (cdescriptor == NULL)
168 if (VisitCompositeField(cdescriptor->descriptor, field, visitor) == -1)
176 // ---------------------------------------------------------------------
178 // Constants used for integer type range checking.
179 PyObject* kPythonZero;
180 PyObject* kint32min_py;
181 PyObject* kint32max_py;
182 PyObject* kuint32max_py;
183 PyObject* kint64min_py;
184 PyObject* kint64max_py;
185 PyObject* kuint64max_py;
187 PyObject* EnumTypeWrapper_class;
188 PyObject* EncodeError_class;
189 PyObject* DecodeError_class;
190 PyObject* PickleError_class;
192 // Constant PyString values used for GetAttr/GetItem.
193 static PyObject* kDESCRIPTOR;
194 static PyObject* k__descriptors;
195 static PyObject* kfull_name;
196 static PyObject* kname;
197 static PyObject* kmessage_type;
198 static PyObject* kis_extendable;
199 static PyObject* kextensions_by_name;
200 static PyObject* k_extensions_by_name;
201 static PyObject* k_extensions_by_number;
202 static PyObject* k_concrete_class;
203 static PyObject* kfields_by_name;
205 static CDescriptorPool* descriptor_pool;
208 void FormatTypeError(PyObject* arg, char* expected_types) {
209 PyObject* repr = PyObject_Repr(arg);
211 PyErr_Format(PyExc_TypeError,
212 "%.100s has type %.100s, but expected one of: %s",
213 PyString_AsString(repr),
214 Py_TYPE(arg)->tp_name,
221 bool CheckAndGetInteger(
222 PyObject* arg, T* value, PyObject* min, PyObject* max) {
223 bool is_long = PyLong_Check(arg);
224 #if PY_MAJOR_VERSION < 3
225 if (!PyInt_Check(arg) && !is_long) {
226 FormatTypeError(arg, "int, long");
229 if (PyObject_Compare(min, arg) > 0 || PyObject_Compare(max, arg) < 0) {
232 FormatTypeError(arg, "int");
235 if (PyObject_RichCompareBool(min, arg, Py_LE) != 1 ||
236 PyObject_RichCompareBool(max, arg, Py_GE) != 1) {
238 PyObject *s = PyObject_Str(arg);
240 PyErr_Format(PyExc_ValueError,
241 "Value out of range: %s",
242 PyString_AsString(s));
247 #if PY_MAJOR_VERSION < 3
249 *value = static_cast<T>(PyInt_AsLong(arg));
253 if (min == kPythonZero) {
254 *value = static_cast<T>(PyLong_AsUnsignedLongLong(arg));
256 *value = static_cast<T>(PyLong_AsLongLong(arg));
262 // These are referenced by repeated_scalar_container, and must
263 // be explicitly instantiated.
264 template bool CheckAndGetInteger<int32>(
265 PyObject*, int32*, PyObject*, PyObject*);
266 template bool CheckAndGetInteger<int64>(
267 PyObject*, int64*, PyObject*, PyObject*);
268 template bool CheckAndGetInteger<uint32>(
269 PyObject*, uint32*, PyObject*, PyObject*);
270 template bool CheckAndGetInteger<uint64>(
271 PyObject*, uint64*, PyObject*, PyObject*);
273 bool CheckAndGetDouble(PyObject* arg, double* value) {
274 if (!PyInt_Check(arg) && !PyLong_Check(arg) &&
275 !PyFloat_Check(arg)) {
276 FormatTypeError(arg, "int, long, float");
279 *value = PyFloat_AsDouble(arg);
283 bool CheckAndGetFloat(PyObject* arg, float* value) {
285 if (!CheckAndGetDouble(arg, &double_value)) {
288 *value = static_cast<float>(double_value);
292 bool CheckAndGetBool(PyObject* arg, bool* value) {
293 if (!PyInt_Check(arg) && !PyBool_Check(arg) && !PyLong_Check(arg)) {
294 FormatTypeError(arg, "int, long, bool");
297 *value = static_cast<bool>(PyInt_AsLong(arg));
301 bool CheckAndSetString(
302 PyObject* arg, google::protobuf::Message* message,
303 const google::protobuf::FieldDescriptor* descriptor,
304 const google::protobuf::Reflection* reflection,
307 GOOGLE_DCHECK(descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING ||
308 descriptor->type() == google::protobuf::FieldDescriptor::TYPE_BYTES);
309 if (descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING) {
310 if (!PyBytes_Check(arg) && !PyUnicode_Check(arg)) {
311 FormatTypeError(arg, "bytes, unicode");
315 if (PyBytes_Check(arg)) {
316 PyObject* unicode = PyUnicode_FromEncodedObject(arg, "ascii", NULL);
317 if (unicode == NULL) {
318 PyObject* repr = PyObject_Repr(arg);
319 PyErr_Format(PyExc_ValueError,
320 "%s has type str, but isn't in 7-bit ASCII "
321 "encoding. Non-ASCII strings must be converted to "
322 "unicode objects before being added.",
323 PyString_AsString(repr));
330 } else if (!PyBytes_Check(arg)) {
331 FormatTypeError(arg, "bytes");
335 PyObject* encoded_string = NULL;
336 if (descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING) {
337 if (PyBytes_Check(arg)) {
338 #if PY_MAJOR_VERSION < 3
339 encoded_string = PyString_AsEncodedObject(arg, "utf-8", NULL);
341 encoded_string = arg; // Already encoded.
342 Py_INCREF(encoded_string);
345 encoded_string = PyUnicode_AsEncodedObject(arg, "utf-8", NULL);
348 // In this case field type is "bytes".
349 encoded_string = arg;
350 Py_INCREF(encoded_string);
353 if (encoded_string == NULL) {
358 Py_ssize_t value_len;
359 if (PyBytes_AsStringAndSize(encoded_string, &value, &value_len) < 0) {
360 Py_DECREF(encoded_string);
364 string value_string(value, value_len);
366 reflection->AddString(message, descriptor, value_string);
367 } else if (index < 0) {
368 reflection->SetString(message, descriptor, value_string);
370 reflection->SetRepeatedString(message, descriptor, index, value_string);
372 Py_DECREF(encoded_string);
376 PyObject* ToStringObject(
377 const google::protobuf::FieldDescriptor* descriptor, string value) {
378 if (descriptor->type() != google::protobuf::FieldDescriptor::TYPE_STRING) {
379 return PyBytes_FromStringAndSize(value.c_str(), value.length());
382 PyObject* result = PyUnicode_DecodeUTF8(value.c_str(), value.length(), NULL);
383 // If the string can't be decoded in UTF-8, just return a string object that
384 // contains the raw bytes. This can't happen if the value was assigned using
385 // the members of the Python message object, but can happen if the values were
386 // parsed from the wire (binary).
387 if (result == NULL) {
389 result = PyBytes_FromStringAndSize(value.c_str(), value.length());
394 google::protobuf::DynamicMessageFactory* global_message_factory;
398 static int MaybeReleaseOverlappingOneofField(
400 const google::protobuf::FieldDescriptor* field) {
401 #ifdef GOOGLE_PROTOBUF_HAS_ONEOF
402 google::protobuf::Message* message = cmessage->message;
403 const google::protobuf::Reflection* reflection = message->GetReflection();
404 if (!field->containing_oneof() ||
405 !reflection->HasOneof(*message, field->containing_oneof()) ||
406 reflection->HasField(*message, field)) {
407 // No other field in this oneof, no need to release.
411 const OneofDescriptor* oneof = field->containing_oneof();
412 const FieldDescriptor* existing_field =
413 reflection->GetOneofFieldDescriptor(*message, oneof);
414 if (existing_field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
415 // Non-message fields don't need to be released.
418 const char* field_name = existing_field->name().c_str();
419 PyObject* child_message = PyDict_GetItemString(
420 cmessage->composite_fields, field_name);
421 if (child_message == NULL) {
422 // No python reference to this field so no need to release.
426 if (InternalReleaseFieldByDescriptor(
427 existing_field, child_message, message) < 0) {
430 return PyDict_DelItemString(cmessage->composite_fields, field_name);
436 // ---------------------------------------------------------------------
437 // Making a message writable
439 static google::protobuf::Message* GetMutableMessage(
441 const google::protobuf::FieldDescriptor* parent_field) {
442 google::protobuf::Message* parent_message = parent->message;
443 const google::protobuf::Reflection* reflection = parent_message->GetReflection();
444 if (MaybeReleaseOverlappingOneofField(parent, parent_field) < 0) {
447 return reflection->MutableMessage(
448 parent_message, parent_field, global_message_factory);
451 struct FixupMessageReference : public ChildVisitor {
452 // message must outlive this object.
453 explicit FixupMessageReference(google::protobuf::Message* message) :
456 int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
457 container->message = message_;
461 int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
462 container->message = message_;
467 google::protobuf::Message* message_;
470 int AssureWritable(CMessage* self) {
471 if (self == NULL || !self->read_only) {
475 if (self->parent == NULL) {
476 // If parent is NULL but we are trying to modify a read-only message, this
477 // is a reference to a constant default instance that needs to be replaced
478 // with a mutable top-level message.
479 const Message* prototype = global_message_factory->GetPrototype(
480 self->message->GetDescriptor());
481 self->message = prototype->New();
482 self->owner.reset(self->message);
484 // Otherwise, we need a mutable child message.
485 if (AssureWritable(self->parent) == -1)
488 // Make self->message writable.
489 google::protobuf::Message* parent_message = self->parent->message;
490 google::protobuf::Message* mutable_message = GetMutableMessage(
492 self->parent_field->descriptor);
493 if (mutable_message == NULL) {
496 self->message = mutable_message;
498 self->read_only = false;
500 // When a CMessage is made writable its Message pointer is updated
501 // to point to a new mutable Message. When that happens we need to
502 // update any references to the old, read-only CMessage. There are
503 // three places such references occur: RepeatedScalarContainer,
504 // RepeatedCompositeContainer, and ExtensionDict.
505 if (self->extensions != NULL)
506 self->extensions->message = self->message;
507 if (ForEachCompositeField(self, FixupMessageReference(self->message)) == -1)
515 static PyObject* GetDescriptor(CMessage* self, PyObject* name) {
516 PyObject* descriptors =
517 PyDict_GetItem(Py_TYPE(self)->tp_dict, k__descriptors);
518 if (descriptors == NULL) {
519 PyErr_SetString(PyExc_TypeError, "No __descriptors");
523 return PyDict_GetItem(descriptors, name);
526 static const google::protobuf::Message* CreateMessage(const char* message_type) {
527 string message_name(message_type);
528 const google::protobuf::Descriptor* descriptor =
529 GetDescriptorPool()->FindMessageTypeByName(message_name);
530 if (descriptor == NULL) {
531 PyErr_SetString(PyExc_TypeError, message_type);
534 return global_message_factory->GetPrototype(descriptor);
537 // If cmessage_list is not NULL, this function releases values into the
538 // container CMessages instead of just removing. Repeated composite container
539 // needs to do this to make sure CMessages stay alive if they're still
540 // referenced after deletion. Repeated scalar container doesn't need to worry.
541 int InternalDeleteRepeatedField(
542 google::protobuf::Message* message,
543 const google::protobuf::FieldDescriptor* field_descriptor,
545 PyObject* cmessage_list) {
546 Py_ssize_t length, from, to, step, slice_length;
547 const google::protobuf::Reflection* reflection = message->GetReflection();
549 length = reflection->FieldSize(*message, field_descriptor);
551 if (PyInt_Check(slice) || PyLong_Check(slice)) {
552 from = to = PyLong_AsLong(slice);
554 from = to = length + from;
560 if (from < 0 || from >= length) {
561 PyErr_Format(PyExc_IndexError, "list assignment index out of range");
564 } else if (PySlice_Check(slice)) {
565 from = to = step = slice_length = 0;
566 PySlice_GetIndicesEx(
567 #if PY_MAJOR_VERSION < 3
568 reinterpret_cast<PySliceObject*>(slice),
572 length, &from, &to, &step, &slice_length);
581 PyErr_SetString(PyExc_TypeError, "list indices must be integers");
586 std::vector<bool> to_delete(length, false);
587 while (i >= min && i <= max) {
593 for (i = 0; i < length; ++i) {
596 reflection->SwapElements(message, field_descriptor, i, to);
597 if (cmessage_list != NULL) {
598 // If a list of cmessages is passed in (i.e. from a repeated
599 // composite container), swap those as well to correspond to the
600 // swaps in the underlying message so they're in the right order
601 // when we start releasing.
602 PyObject* tmp = PyList_GET_ITEM(cmessage_list, i);
603 PyList_SET_ITEM(cmessage_list, i,
604 PyList_GET_ITEM(cmessage_list, to));
605 PyList_SET_ITEM(cmessage_list, to, tmp);
613 if (cmessage_list == NULL) {
614 reflection->RemoveLast(message, field_descriptor);
616 CMessage* last_cmessage = reinterpret_cast<CMessage*>(
617 PyList_GET_ITEM(cmessage_list, PyList_GET_SIZE(cmessage_list) - 1));
618 repeated_composite_container::ReleaseLastTo(
619 field_descriptor, message, last_cmessage);
620 if (PySequence_DelItem(cmessage_list, -1) < 0) {
630 int InitAttributes(CMessage* self, PyObject* arg, PyObject* kwargs) {
631 ScopedPyObjectPtr descriptor;
634 PyObject_GetAttr(reinterpret_cast<PyObject*>(self), kDESCRIPTOR));
635 if (descriptor == NULL) {
639 descriptor.reset(arg);
642 ScopedPyObjectPtr is_extendable(PyObject_GetAttr(descriptor, kis_extendable));
643 if (is_extendable == NULL) {
646 int retcode = PyObject_IsTrue(is_extendable);
651 PyObject* py_extension_dict = PyObject_CallObject(
652 reinterpret_cast<PyObject*>(&ExtensionDict_Type), NULL);
653 if (py_extension_dict == NULL) {
656 ExtensionDict* extension_dict = reinterpret_cast<ExtensionDict*>(
658 extension_dict->parent = self;
659 extension_dict->message = self->message;
660 self->extensions = extension_dict;
663 if (kwargs == NULL) {
670 while (PyDict_Next(kwargs, &pos, &name, &value)) {
671 if (!PyString_Check(name)) {
672 PyErr_SetString(PyExc_ValueError, "Field name must be a string");
675 PyObject* py_cdescriptor = GetDescriptor(self, name);
676 if (py_cdescriptor == NULL) {
677 PyErr_Format(PyExc_ValueError, "Protocol message has no \"%s\" field.",
678 PyString_AsString(name));
681 const google::protobuf::FieldDescriptor* descriptor =
682 reinterpret_cast<CFieldDescriptor*>(py_cdescriptor)->descriptor;
683 if (descriptor->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED) {
684 ScopedPyObjectPtr container(GetAttr(self, name));
685 if (container == NULL) {
688 if (descriptor->cpp_type() == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
689 if (repeated_composite_container::Extend(
690 reinterpret_cast<RepeatedCompositeContainer*>(container.get()),
696 if (repeated_scalar_container::Extend(
697 reinterpret_cast<RepeatedScalarContainer*>(container.get()),
703 } else if (descriptor->cpp_type() ==
704 google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
705 ScopedPyObjectPtr message(GetAttr(self, name));
706 if (message == NULL) {
709 if (MergeFrom(reinterpret_cast<CMessage*>(message.get()),
714 if (SetAttr(self, name, value) < 0) {
722 static PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
723 CMessage* self = reinterpret_cast<CMessage*>(type->tp_alloc(type, 0));
728 self->message = NULL;
730 self->parent_field = NULL;
731 self->read_only = false;
732 self->extensions = NULL;
734 self->composite_fields = PyDict_New();
735 if (self->composite_fields == NULL) {
738 return reinterpret_cast<PyObject*>(self);
741 PyObject* NewEmpty(PyObject* type) {
742 return New(reinterpret_cast<PyTypeObject*>(type), NULL, NULL);
745 static int Init(CMessage* self, PyObject* args, PyObject* kwargs) {
746 if (kwargs == NULL) {
747 // TODO(anuraag): Set error
751 PyObject* descriptor = PyTuple_GetItem(args, 0);
752 if (descriptor == NULL || PyTuple_Size(args) != 1) {
753 PyErr_SetString(PyExc_ValueError, "args must contain one arg: descriptor");
757 ScopedPyObjectPtr py_message_type(PyObject_GetAttr(descriptor, kfull_name));
758 if (py_message_type == NULL) {
762 const char* message_type = PyString_AsString(py_message_type.get());
763 const google::protobuf::Message* message = CreateMessage(message_type);
764 if (message == NULL) {
768 self->message = message->New();
769 self->owner.reset(self->message);
771 if (InitAttributes(self, descriptor, kwargs) < 0) {
777 // ---------------------------------------------------------------------
778 // Deallocating a CMessage
780 // Deallocating a CMessage requires that we clear any weak references
781 // from children to the message being deallocated.
783 // Clear the weak reference from the child to the parent.
784 struct ClearWeakReferences : public ChildVisitor {
785 int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
786 container->parent = NULL;
787 // The elements in the container have the same parent as the
788 // container itself, so NULL out that pointer as well.
789 const Py_ssize_t n = PyList_GET_SIZE(container->child_messages);
790 for (Py_ssize_t i = 0; i < n; ++i) {
791 CMessage* child_cmessage = reinterpret_cast<CMessage*>(
792 PyList_GET_ITEM(container->child_messages, i));
793 child_cmessage->parent = NULL;
798 int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
799 container->parent = NULL;
803 int VisitCMessage(CMessage* cmessage,
804 const google::protobuf::FieldDescriptor* field_descriptor) {
805 cmessage->parent = NULL;
810 static void Dealloc(CMessage* self) {
811 // Null out all weak references from children to this message.
812 GOOGLE_CHECK_EQ(0, ForEachCompositeField(self, ClearWeakReferences()));
814 Py_CLEAR(self->extensions);
815 Py_CLEAR(self->composite_fields);
817 Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
820 // ---------------------------------------------------------------------
823 PyObject* IsInitialized(CMessage* self, PyObject* args) {
824 PyObject* errors = NULL;
825 if (PyArg_ParseTuple(args, "|O", &errors) < 0) {
828 if (self->message->IsInitialized()) {
831 if (errors != NULL) {
832 ScopedPyObjectPtr initialization_errors(
833 FindInitializationErrors(self));
834 if (initialization_errors == NULL) {
837 ScopedPyObjectPtr extend_name(PyString_FromString("extend"));
838 if (extend_name == NULL) {
841 ScopedPyObjectPtr result(PyObject_CallMethodObjArgs(
844 initialization_errors.get(),
846 if (result == NULL) {
853 PyObject* HasFieldByDescriptor(
854 CMessage* self, const google::protobuf::FieldDescriptor* field_descriptor) {
855 google::protobuf::Message* message = self->message;
856 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
857 PyErr_SetString(PyExc_KeyError,
858 "Field does not belong to message!");
861 if (field_descriptor->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED) {
862 PyErr_SetString(PyExc_KeyError,
863 "Field is repeated. A singular method is required.");
867 message->GetReflection()->HasField(*message, field_descriptor);
868 return PyBool_FromLong(has_field ? 1 : 0);
871 const google::protobuf::FieldDescriptor* FindFieldWithOneofs(
872 const google::protobuf::Message* message, const char* field_name, bool* in_oneof) {
873 const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
874 const google::protobuf::FieldDescriptor* field_descriptor =
875 descriptor->FindFieldByName(field_name);
876 if (field_descriptor == NULL) {
877 const google::protobuf::OneofDescriptor* oneof_desc =
878 message->GetDescriptor()->FindOneofByName(field_name);
879 if (oneof_desc == NULL) {
884 return message->GetReflection()->GetOneofFieldDescriptor(
885 *message, oneof_desc);
888 return field_descriptor;
891 PyObject* HasField(CMessage* self, PyObject* arg) {
892 #if PY_MAJOR_VERSION < 3
894 if (PyString_AsStringAndSize(arg, &field_name, NULL) < 0) {
896 char* field_name = PyUnicode_AsUTF8(arg);
902 google::protobuf::Message* message = self->message;
903 const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
905 const google::protobuf::FieldDescriptor* field_descriptor =
906 FindFieldWithOneofs(message, field_name, &is_in_oneof);
907 if (field_descriptor == NULL) {
909 PyErr_Format(PyExc_ValueError, "Unknown field %s.", field_name);
916 if (field_descriptor->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED) {
917 PyErr_Format(PyExc_ValueError,
918 "Protocol message has no singular \"%s\" field.", field_name);
923 message->GetReflection()->HasField(*message, field_descriptor);
924 if (!has_field && field_descriptor->cpp_type() ==
925 google::protobuf::FieldDescriptor::CPPTYPE_ENUM) {
926 // We may have an invalid enum value stored in the UnknownFieldSet and need
927 // to check presence in there as well.
928 const google::protobuf::UnknownFieldSet& unknown_field_set =
929 message->GetReflection()->GetUnknownFields(*message);
930 for (int i = 0; i < unknown_field_set.field_count(); ++i) {
931 if (unknown_field_set.field(i).number() == field_descriptor->number()) {
937 return PyBool_FromLong(has_field ? 1 : 0);
940 PyObject* ClearExtension(CMessage* self, PyObject* arg) {
941 if (self->extensions != NULL) {
942 return extension_dict::ClearExtension(self->extensions, arg);
944 PyErr_SetString(PyExc_TypeError, "Message is not extendable");
948 PyObject* HasExtension(CMessage* self, PyObject* arg) {
949 if (self->extensions != NULL) {
950 return extension_dict::HasExtension(self->extensions, arg);
952 PyErr_SetString(PyExc_TypeError, "Message is not extendable");
956 // ---------------------------------------------------------------------
957 // Releasing messages
959 // The Python API's ClearField() and Clear() methods behave
960 // differently than their C++ counterparts. While the C++ versions
961 // clears the children the Python versions detaches the children,
962 // without touching their content. This impedance mismatch causes
963 // some complexity in the implementation, which is captured in this
966 // When a CMessage field is cleared we need to:
968 // * Release the Message used as the backing store for the CMessage
971 // * Change the owner field of the released CMessage and all of its
972 // children to point to the newly released Message.
974 // * Clear the weak references from the released CMessage to the
977 // When a RepeatedCompositeContainer field is cleared we need to:
979 // * Release all the Message used as the backing store for the
980 // CMessages stored in the container.
982 // * Change the owner field of all the released CMessage and all of
983 // their children to point to the newly released Messages.
985 // * Clear the weak references from the released container to the
988 struct SetOwnerVisitor : public ChildVisitor {
989 // new_owner must outlive this object.
990 explicit SetOwnerVisitor(const shared_ptr<Message>& new_owner)
991 : new_owner_(new_owner) {}
993 int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
994 repeated_composite_container::SetOwner(container, new_owner_);
998 int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
999 repeated_scalar_container::SetOwner(container, new_owner_);
1003 int VisitCMessage(CMessage* cmessage,
1004 const google::protobuf::FieldDescriptor* field_descriptor) {
1005 return SetOwner(cmessage, new_owner_);
1009 const shared_ptr<Message>& new_owner_;
1012 // Change the owner of this CMessage and all its children, recursively.
1013 int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner) {
1014 self->owner = new_owner;
1015 if (ForEachCompositeField(self, SetOwnerVisitor(new_owner)) == -1)
1020 // Releases the message specified by 'field' and returns the
1021 // pointer. If the field does not exist a new message is created using
1022 // 'descriptor'. The caller takes ownership of the returned pointer.
1023 Message* ReleaseMessage(google::protobuf::Message* message,
1024 const google::protobuf::Descriptor* descriptor,
1025 const google::protobuf::FieldDescriptor* field_descriptor) {
1026 Message* released_message = message->GetReflection()->ReleaseMessage(
1027 message, field_descriptor, global_message_factory);
1028 // ReleaseMessage will return NULL which differs from
1029 // child_cmessage->message, if the field does not exist. In this case,
1030 // the latter points to the default instance via a const_cast<>, so we
1031 // have to reset it to a new mutable object since we are taking ownership.
1032 if (released_message == NULL) {
1033 const Message* prototype = global_message_factory->GetPrototype(
1035 GOOGLE_DCHECK(prototype != NULL);
1036 released_message = prototype->New();
1039 return released_message;
1042 int ReleaseSubMessage(google::protobuf::Message* message,
1043 const google::protobuf::FieldDescriptor* field_descriptor,
1044 CMessage* child_cmessage) {
1045 // Release the Message
1046 shared_ptr<Message> released_message(ReleaseMessage(
1047 message, child_cmessage->message->GetDescriptor(), field_descriptor));
1048 child_cmessage->message = released_message.get();
1049 child_cmessage->owner.swap(released_message);
1050 child_cmessage->parent = NULL;
1051 child_cmessage->parent_field = NULL;
1052 child_cmessage->read_only = false;
1053 return ForEachCompositeField(child_cmessage,
1054 SetOwnerVisitor(child_cmessage->owner));
1057 struct ReleaseChild : public ChildVisitor {
1058 // message must outlive this object.
1059 explicit ReleaseChild(google::protobuf::Message* parent_message) :
1060 parent_message_(parent_message) {}
1062 int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
1063 return repeated_composite_container::Release(
1064 reinterpret_cast<RepeatedCompositeContainer*>(container));
1067 int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
1068 return repeated_scalar_container::Release(
1069 reinterpret_cast<RepeatedScalarContainer*>(container));
1072 int VisitCMessage(CMessage* cmessage,
1073 const google::protobuf::FieldDescriptor* field_descriptor) {
1074 return ReleaseSubMessage(parent_message_, field_descriptor,
1075 reinterpret_cast<CMessage*>(cmessage));
1078 google::protobuf::Message* parent_message_;
1081 int InternalReleaseFieldByDescriptor(
1082 const google::protobuf::FieldDescriptor* field_descriptor,
1083 PyObject* composite_field,
1084 google::protobuf::Message* parent_message) {
1085 return VisitCompositeField(
1088 ReleaseChild(parent_message));
1091 int InternalReleaseField(CMessage* self, PyObject* composite_field,
1093 PyObject* cdescriptor = GetDescriptor(self, name);
1094 if (cdescriptor != NULL) {
1095 const google::protobuf::FieldDescriptor* descriptor =
1096 reinterpret_cast<CFieldDescriptor*>(cdescriptor)->descriptor;
1097 return InternalReleaseFieldByDescriptor(
1098 descriptor, composite_field, self->message);
1104 PyObject* ClearFieldByDescriptor(
1106 const google::protobuf::FieldDescriptor* descriptor) {
1107 if (!FIELD_BELONGS_TO_MESSAGE(descriptor, self->message)) {
1108 PyErr_SetString(PyExc_KeyError,
1109 "Field does not belong to message!");
1112 AssureWritable(self);
1113 self->message->GetReflection()->ClearField(self->message, descriptor);
1117 PyObject* ClearField(CMessage* self, PyObject* arg) {
1119 if (!PyString_Check(arg)) {
1120 PyErr_SetString(PyExc_TypeError, "field name must be a string");
1123 #if PY_MAJOR_VERSION < 3
1124 if (PyString_AsStringAndSize(arg, &field_name, NULL) < 0) {
1128 field_name = PyUnicode_AsUTF8(arg);
1130 AssureWritable(self);
1131 google::protobuf::Message* message = self->message;
1132 const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
1133 ScopedPyObjectPtr arg_in_oneof;
1135 const google::protobuf::FieldDescriptor* field_descriptor =
1136 FindFieldWithOneofs(message, field_name, &is_in_oneof);
1137 if (field_descriptor == NULL) {
1139 PyErr_Format(PyExc_ValueError,
1140 "Protocol message has no \"%s\" field.", field_name);
1145 } else if (is_in_oneof) {
1146 arg_in_oneof.reset(PyString_FromString(field_descriptor->name().c_str()));
1147 arg = arg_in_oneof.get();
1150 PyObject* composite_field = PyDict_GetItem(self->composite_fields,
1153 // Only release the field if there's a possibility that there are
1154 // references to it.
1155 if (composite_field != NULL) {
1156 if (InternalReleaseField(self, composite_field, arg) < 0) {
1159 PyDict_DelItem(self->composite_fields, arg);
1161 message->GetReflection()->ClearField(message, field_descriptor);
1162 if (field_descriptor->cpp_type() == google::protobuf::FieldDescriptor::CPPTYPE_ENUM) {
1163 google::protobuf::UnknownFieldSet* unknown_field_set =
1164 message->GetReflection()->MutableUnknownFields(message);
1165 unknown_field_set->DeleteByNumber(field_descriptor->number());
1171 PyObject* Clear(CMessage* self) {
1172 AssureWritable(self);
1173 if (ForEachCompositeField(self, ReleaseChild(self->message)) == -1)
1176 // The old ExtensionDict still aliases this CMessage, but all its
1177 // fields have been released.
1178 if (self->extensions != NULL) {
1179 Py_CLEAR(self->extensions);
1180 PyObject* py_extension_dict = PyObject_CallObject(
1181 reinterpret_cast<PyObject*>(&ExtensionDict_Type), NULL);
1182 if (py_extension_dict == NULL) {
1185 ExtensionDict* extension_dict = reinterpret_cast<ExtensionDict*>(
1187 extension_dict->parent = self;
1188 extension_dict->message = self->message;
1189 self->extensions = extension_dict;
1191 PyDict_Clear(self->composite_fields);
1192 self->message->Clear();
1196 // ---------------------------------------------------------------------
1198 static string GetMessageName(CMessage* self) {
1199 if (self->parent_field != NULL) {
1200 return self->parent_field->descriptor->full_name();
1202 return self->message->GetDescriptor()->full_name();
1206 static PyObject* SerializeToString(CMessage* self, PyObject* args) {
1207 if (!self->message->IsInitialized()) {
1208 ScopedPyObjectPtr errors(FindInitializationErrors(self));
1209 if (errors == NULL) {
1212 ScopedPyObjectPtr comma(PyString_FromString(","));
1213 if (comma == NULL) {
1216 ScopedPyObjectPtr joined(
1217 PyObject_CallMethod(comma.get(), "join", "O", errors.get()));
1218 if (joined == NULL) {
1221 PyErr_Format(EncodeError_class, "Message %s is missing required fields: %s",
1222 GetMessageName(self).c_str(), PyString_AsString(joined.get()));
1225 int size = self->message->ByteSize();
1227 return PyBytes_FromString("");
1229 PyObject* result = PyBytes_FromStringAndSize(NULL, size);
1230 if (result == NULL) {
1233 char* buffer = PyBytes_AS_STRING(result);
1234 self->message->SerializeWithCachedSizesToArray(
1235 reinterpret_cast<uint8*>(buffer));
1239 static PyObject* SerializePartialToString(CMessage* self) {
1241 self->message->SerializePartialToString(&contents);
1242 return PyBytes_FromStringAndSize(contents.c_str(), contents.size());
1245 // Formats proto fields for ascii dumps using python formatting functions where
1247 class PythonFieldValuePrinter : public google::protobuf::TextFormat::FieldValuePrinter {
1249 PythonFieldValuePrinter() : float_holder_(PyFloat_FromDouble(0)) {}
1251 // Python has some differences from C++ when printing floating point numbers.
1253 // 1) Trailing .0 is always printed.
1254 // 2) Outputted is rounded to 12 digits.
1256 // We override floating point printing with the C-API function for printing
1257 // Python floats to ensure consistency.
1258 string PrintFloat(float value) const { return PrintDouble(value); }
1259 string PrintDouble(double value) const {
1260 reinterpret_cast<PyFloatObject*>(float_holder_.get())->ob_fval = value;
1261 ScopedPyObjectPtr s(PyObject_Str(float_holder_.get()));
1262 if (s == NULL) return string();
1263 #if PY_MAJOR_VERSION < 3
1264 char *cstr = PyBytes_AS_STRING(static_cast<PyObject*>(s));
1266 char *cstr = PyUnicode_AsUTF8(s);
1268 return string(cstr);
1272 // Holder for a python float object which we use to allow us to use
1273 // the Python API for printing doubles. We initialize once and then
1274 // directly modify it for every float printed to save on allocations
1276 ScopedPyObjectPtr float_holder_;
1279 static PyObject* ToStr(CMessage* self) {
1280 google::protobuf::TextFormat::Printer printer;
1282 printer.SetDefaultFieldValuePrinter(new PythonFieldValuePrinter());
1283 printer.SetHideUnknownFields(true);
1285 if (!printer.PrintToString(*self->message, &output)) {
1286 PyErr_SetString(PyExc_ValueError, "Unable to convert message to str");
1289 return PyString_FromString(output.c_str());
1292 PyObject* MergeFrom(CMessage* self, PyObject* arg) {
1293 CMessage* other_message;
1294 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg), &CMessage_Type)) {
1295 PyErr_SetString(PyExc_TypeError, "Must be a message");
1299 other_message = reinterpret_cast<CMessage*>(arg);
1300 if (other_message->message->GetDescriptor() !=
1301 self->message->GetDescriptor()) {
1302 PyErr_Format(PyExc_TypeError,
1303 "Tried to merge from a message with a different type. "
1305 self->message->GetDescriptor()->full_name().c_str(),
1306 other_message->message->GetDescriptor()->full_name().c_str());
1309 AssureWritable(self);
1311 // TODO(tibell): Message::MergeFrom might turn some child Messages
1312 // into mutable messages, invalidating the message field in the
1313 // corresponding CMessages. We should run a FixupMessageReferences
1316 self->message->MergeFrom(*other_message->message);
1320 static PyObject* CopyFrom(CMessage* self, PyObject* arg) {
1321 CMessage* other_message;
1322 if (!PyObject_TypeCheck(reinterpret_cast<PyObject *>(arg), &CMessage_Type)) {
1323 PyErr_SetString(PyExc_TypeError, "Must be a message");
1327 other_message = reinterpret_cast<CMessage*>(arg);
1329 if (self == other_message) {
1333 if (other_message->message->GetDescriptor() !=
1334 self->message->GetDescriptor()) {
1335 PyErr_Format(PyExc_TypeError,
1336 "Tried to copy from a message with a different type. "
1338 self->message->GetDescriptor()->full_name().c_str(),
1339 other_message->message->GetDescriptor()->full_name().c_str());
1343 AssureWritable(self);
1345 // CopyFrom on the message will not clean up self->composite_fields,
1346 // which can leave us in an inconsistent state, so clear it out here.
1349 self->message->CopyFrom(*other_message->message);
1354 static PyObject* MergeFromString(CMessage* self, PyObject* arg) {
1356 Py_ssize_t data_length;
1357 if (PyObject_AsReadBuffer(arg, &data, &data_length) < 0) {
1361 AssureWritable(self);
1362 google::protobuf::io::CodedInputStream input(
1363 reinterpret_cast<const uint8*>(data), data_length);
1364 input.SetExtensionRegistry(GetDescriptorPool(), global_message_factory);
1365 bool success = self->message->MergePartialFromCodedStream(&input);
1367 return PyInt_FromLong(input.CurrentPosition());
1369 PyErr_Format(DecodeError_class, "Error parsing message");
1374 static PyObject* ParseFromString(CMessage* self, PyObject* arg) {
1375 if (Clear(self) == NULL) {
1378 return MergeFromString(self, arg);
1381 static PyObject* ByteSize(CMessage* self, PyObject* args) {
1382 return PyLong_FromLong(self->message->ByteSize());
1385 static PyObject* RegisterExtension(PyObject* cls,
1386 PyObject* extension_handle) {
1387 ScopedPyObjectPtr message_descriptor(PyObject_GetAttr(cls, kDESCRIPTOR));
1388 if (message_descriptor == NULL) {
1391 if (PyObject_SetAttrString(extension_handle, "containing_type",
1392 message_descriptor) < 0) {
1395 ScopedPyObjectPtr extensions_by_name(
1396 PyObject_GetAttr(cls, k_extensions_by_name));
1397 if (extensions_by_name == NULL) {
1398 PyErr_SetString(PyExc_TypeError, "no extensions_by_name on class");
1401 ScopedPyObjectPtr full_name(PyObject_GetAttr(extension_handle, kfull_name));
1402 if (full_name == NULL) {
1405 if (PyDict_SetItem(extensions_by_name, full_name, extension_handle) < 0) {
1409 // Also store a mapping from extension number to implementing class.
1410 ScopedPyObjectPtr extensions_by_number(
1411 PyObject_GetAttr(cls, k_extensions_by_number));
1412 if (extensions_by_number == NULL) {
1413 PyErr_SetString(PyExc_TypeError, "no extensions_by_number on class");
1416 ScopedPyObjectPtr number(PyObject_GetAttrString(extension_handle, "number"));
1417 if (number == NULL) {
1420 if (PyDict_SetItem(extensions_by_number, number, extension_handle) < 0) {
1424 CFieldDescriptor* cdescriptor =
1425 extension_dict::InternalGetCDescriptorFromExtension(extension_handle);
1426 ScopedPyObjectPtr py_cdescriptor(reinterpret_cast<PyObject*>(cdescriptor));
1427 if (cdescriptor == NULL) {
1430 Py_INCREF(extension_handle);
1431 cdescriptor->descriptor_field = extension_handle;
1432 const google::protobuf::FieldDescriptor* descriptor = cdescriptor->descriptor;
1433 // Check if it's a message set
1434 if (descriptor->is_extension() &&
1435 descriptor->containing_type()->options().message_set_wire_format() &&
1436 descriptor->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE &&
1437 descriptor->message_type() == descriptor->extension_scope() &&
1438 descriptor->label() == google::protobuf::FieldDescriptor::LABEL_OPTIONAL) {
1439 ScopedPyObjectPtr message_name(PyString_FromStringAndSize(
1440 descriptor->message_type()->full_name().c_str(),
1441 descriptor->message_type()->full_name().size()));
1442 if (message_name == NULL) {
1445 PyDict_SetItem(extensions_by_name, message_name, extension_handle);
1451 static PyObject* SetInParent(CMessage* self, PyObject* args) {
1452 AssureWritable(self);
1456 static PyObject* WhichOneof(CMessage* self, PyObject* arg) {
1458 if (!PyString_Check(arg)) {
1459 PyErr_SetString(PyExc_TypeError, "field name must be a string");
1462 oneof_name = PyString_AsString(arg);
1463 if (oneof_name == NULL) {
1466 const google::protobuf::OneofDescriptor* oneof_desc =
1467 self->message->GetDescriptor()->FindOneofByName(oneof_name);
1468 if (oneof_desc == NULL) {
1469 PyErr_Format(PyExc_ValueError,
1470 "Protocol message has no oneof \"%s\" field.", oneof_name);
1473 const google::protobuf::FieldDescriptor* field_in_oneof =
1474 self->message->GetReflection()->GetOneofFieldDescriptor(
1475 *self->message, oneof_desc);
1476 if (field_in_oneof == NULL) {
1479 return PyString_FromString(field_in_oneof->name().c_str());
1483 static PyObject* ListFields(CMessage* self) {
1484 vector<const google::protobuf::FieldDescriptor*> fields;
1485 self->message->GetReflection()->ListFields(*self->message, &fields);
1487 PyObject* descriptor = PyDict_GetItem(Py_TYPE(self)->tp_dict, kDESCRIPTOR);
1488 if (descriptor == NULL) {
1491 ScopedPyObjectPtr fields_by_name(
1492 PyObject_GetAttr(descriptor, kfields_by_name));
1493 if (fields_by_name == NULL) {
1496 ScopedPyObjectPtr extensions_by_name(PyObject_GetAttr(
1497 reinterpret_cast<PyObject*>(Py_TYPE(self)), k_extensions_by_name));
1498 if (extensions_by_name == NULL) {
1499 PyErr_SetString(PyExc_ValueError, "no extensionsbyname");
1502 // Normally, the list will be exactly the size of the fields.
1503 PyObject* all_fields = PyList_New(fields.size());
1504 if (all_fields == NULL) {
1508 // When there are unknown extensions, the py list will *not* contain
1509 // the field information. Thus the actual size of the py list will be
1510 // smaller than the size of fields. Set the actual size at the end.
1511 Py_ssize_t actual_size = 0;
1512 for (Py_ssize_t i = 0; i < fields.size(); ++i) {
1513 ScopedPyObjectPtr t(PyTuple_New(2));
1515 Py_DECREF(all_fields);
1519 if (fields[i]->is_extension()) {
1520 const string& field_name = fields[i]->full_name();
1521 PyObject* extension_field = PyDict_GetItemString(extensions_by_name,
1522 field_name.c_str());
1523 if (extension_field == NULL) {
1524 // If we couldn't fetch extension_field, it means the module that
1525 // defines this extension has not been explicitly imported in Python
1526 // code, and the extension hasn't been registered. There's nothing much
1527 // we can do about this, so just skip it in the output to match the
1528 // behavior of the python implementation.
1531 PyObject* extensions = reinterpret_cast<PyObject*>(self->extensions);
1532 if (extensions == NULL) {
1533 Py_DECREF(all_fields);
1536 // 'extension' reference later stolen by PyTuple_SET_ITEM.
1537 PyObject* extension = PyObject_GetItem(extensions, extension_field);
1538 if (extension == NULL) {
1539 Py_DECREF(all_fields);
1542 Py_INCREF(extension_field);
1543 PyTuple_SET_ITEM(t.get(), 0, extension_field);
1544 // Steals reference to 'extension'
1545 PyTuple_SET_ITEM(t.get(), 1, extension);
1547 const string& field_name = fields[i]->name();
1548 ScopedPyObjectPtr py_field_name(PyString_FromStringAndSize(
1549 field_name.c_str(), field_name.length()));
1550 if (py_field_name == NULL) {
1551 PyErr_SetString(PyExc_ValueError, "bad string");
1552 Py_DECREF(all_fields);
1555 PyObject* field_descriptor =
1556 PyDict_GetItem(fields_by_name, py_field_name);
1557 if (field_descriptor == NULL) {
1558 Py_DECREF(all_fields);
1562 PyObject* field_value = GetAttr(self, py_field_name);
1563 if (field_value == NULL) {
1564 PyErr_SetObject(PyExc_ValueError, py_field_name);
1565 Py_DECREF(all_fields);
1568 Py_INCREF(field_descriptor);
1569 PyTuple_SET_ITEM(t.get(), 0, field_descriptor);
1570 PyTuple_SET_ITEM(t.get(), 1, field_value);
1572 PyList_SET_ITEM(all_fields, actual_size, t.release());
1575 Py_SIZE(all_fields) = actual_size;
1579 PyObject* FindInitializationErrors(CMessage* self) {
1580 google::protobuf::Message* message = self->message;
1581 vector<string> errors;
1582 message->FindInitializationErrors(&errors);
1584 PyObject* error_list = PyList_New(errors.size());
1585 if (error_list == NULL) {
1588 for (Py_ssize_t i = 0; i < errors.size(); ++i) {
1589 const string& error = errors[i];
1590 PyObject* error_string = PyString_FromStringAndSize(
1591 error.c_str(), error.length());
1592 if (error_string == NULL) {
1593 Py_DECREF(error_list);
1596 PyList_SET_ITEM(error_list, i, error_string);
1601 static PyObject* RichCompare(CMessage* self, PyObject* other, int opid) {
1602 if (!PyObject_TypeCheck(other, &CMessage_Type)) {
1603 if (opid == Py_EQ) {
1605 } else if (opid == Py_NE) {
1609 if (opid == Py_EQ || opid == Py_NE) {
1610 ScopedPyObjectPtr self_fields(ListFields(self));
1611 ScopedPyObjectPtr other_fields(ListFields(
1612 reinterpret_cast<CMessage*>(other)));
1613 return PyObject_RichCompare(self_fields, other_fields, opid);
1615 Py_INCREF(Py_NotImplemented);
1616 return Py_NotImplemented;
1620 PyObject* InternalGetScalar(
1622 const google::protobuf::FieldDescriptor* field_descriptor) {
1623 google::protobuf::Message* message = self->message;
1624 const google::protobuf::Reflection* reflection = message->GetReflection();
1626 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
1628 PyExc_KeyError, "Field does not belong to message!");
1632 PyObject* result = NULL;
1633 switch (field_descriptor->cpp_type()) {
1634 case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
1635 int32 value = reflection->GetInt32(*message, field_descriptor);
1636 result = PyInt_FromLong(value);
1639 case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
1640 int64 value = reflection->GetInt64(*message, field_descriptor);
1641 result = PyLong_FromLongLong(value);
1644 case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
1645 uint32 value = reflection->GetUInt32(*message, field_descriptor);
1646 result = PyInt_FromSize_t(value);
1649 case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
1650 uint64 value = reflection->GetUInt64(*message, field_descriptor);
1651 result = PyLong_FromUnsignedLongLong(value);
1654 case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
1655 float value = reflection->GetFloat(*message, field_descriptor);
1656 result = PyFloat_FromDouble(value);
1659 case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
1660 double value = reflection->GetDouble(*message, field_descriptor);
1661 result = PyFloat_FromDouble(value);
1664 case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
1665 bool value = reflection->GetBool(*message, field_descriptor);
1666 result = PyBool_FromLong(value);
1669 case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
1670 string value = reflection->GetString(*message, field_descriptor);
1671 result = ToStringObject(field_descriptor, value);
1674 case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
1675 if (!message->GetReflection()->HasField(*message, field_descriptor)) {
1676 // Look for the value in the unknown fields.
1677 google::protobuf::UnknownFieldSet* unknown_field_set =
1678 message->GetReflection()->MutableUnknownFields(message);
1679 for (int i = 0; i < unknown_field_set->field_count(); ++i) {
1680 if (unknown_field_set->field(i).number() ==
1681 field_descriptor->number()) {
1682 result = PyInt_FromLong(unknown_field_set->field(i).varint());
1688 if (result == NULL) {
1689 const google::protobuf::EnumValueDescriptor* enum_value =
1690 message->GetReflection()->GetEnum(*message, field_descriptor);
1691 result = PyInt_FromLong(enum_value->number());
1697 PyExc_SystemError, "Getting a value from a field of unknown type %d",
1698 field_descriptor->cpp_type());
1704 PyObject* InternalGetSubMessage(CMessage* self,
1705 CFieldDescriptor* cfield_descriptor) {
1706 PyObject* field = cfield_descriptor->descriptor_field;
1707 ScopedPyObjectPtr message_type(PyObject_GetAttr(field, kmessage_type));
1708 if (message_type == NULL) {
1711 ScopedPyObjectPtr concrete_class(
1712 PyObject_GetAttr(message_type, k_concrete_class));
1713 if (concrete_class == NULL) {
1716 PyObject* py_cmsg = cmessage::NewEmpty(concrete_class);
1717 if (py_cmsg == NULL) {
1720 if (!PyObject_TypeCheck(py_cmsg, &CMessage_Type)) {
1721 PyErr_SetString(PyExc_TypeError, "Not a CMessage!");
1723 CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
1725 const google::protobuf::FieldDescriptor* field_descriptor =
1726 cfield_descriptor->descriptor;
1727 const google::protobuf::Reflection* reflection = self->message->GetReflection();
1728 const google::protobuf::Message& sub_message = reflection->GetMessage(
1729 *self->message, field_descriptor, global_message_factory);
1730 cmsg->owner = self->owner;
1731 cmsg->parent = self;
1732 cmsg->parent_field = cfield_descriptor;
1733 cmsg->read_only = !reflection->HasField(*self->message, field_descriptor);
1734 cmsg->message = const_cast<google::protobuf::Message*>(&sub_message);
1736 if (InitAttributes(cmsg, NULL, NULL) < 0) {
1743 int InternalSetScalar(
1745 const google::protobuf::FieldDescriptor* field_descriptor,
1747 google::protobuf::Message* message = self->message;
1748 const google::protobuf::Reflection* reflection = message->GetReflection();
1750 if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) {
1752 PyExc_KeyError, "Field does not belong to message!");
1756 if (MaybeReleaseOverlappingOneofField(self, field_descriptor) < 0) {
1760 switch (field_descriptor->cpp_type()) {
1761 case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
1762 GOOGLE_CHECK_GET_INT32(arg, value, -1);
1763 reflection->SetInt32(message, field_descriptor, value);
1766 case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
1767 GOOGLE_CHECK_GET_INT64(arg, value, -1);
1768 reflection->SetInt64(message, field_descriptor, value);
1771 case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
1772 GOOGLE_CHECK_GET_UINT32(arg, value, -1);
1773 reflection->SetUInt32(message, field_descriptor, value);
1776 case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
1777 GOOGLE_CHECK_GET_UINT64(arg, value, -1);
1778 reflection->SetUInt64(message, field_descriptor, value);
1781 case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
1782 GOOGLE_CHECK_GET_FLOAT(arg, value, -1);
1783 reflection->SetFloat(message, field_descriptor, value);
1786 case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
1787 GOOGLE_CHECK_GET_DOUBLE(arg, value, -1);
1788 reflection->SetDouble(message, field_descriptor, value);
1791 case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
1792 GOOGLE_CHECK_GET_BOOL(arg, value, -1);
1793 reflection->SetBool(message, field_descriptor, value);
1796 case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
1797 if (!CheckAndSetString(
1798 arg, message, field_descriptor, reflection, false, -1)) {
1803 case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
1804 GOOGLE_CHECK_GET_INT32(arg, value, -1);
1805 const google::protobuf::EnumDescriptor* enum_descriptor =
1806 field_descriptor->enum_type();
1807 const google::protobuf::EnumValueDescriptor* enum_value =
1808 enum_descriptor->FindValueByNumber(value);
1809 if (enum_value != NULL) {
1810 reflection->SetEnum(message, field_descriptor, enum_value);
1812 PyErr_Format(PyExc_ValueError, "Unknown enum value: %d", value);
1819 PyExc_SystemError, "Setting value to a field of unknown type %d",
1820 field_descriptor->cpp_type());
1827 PyObject* FromString(PyTypeObject* cls, PyObject* serialized) {
1828 PyObject* py_cmsg = PyObject_CallObject(
1829 reinterpret_cast<PyObject*>(cls), NULL);
1830 if (py_cmsg == NULL) {
1833 CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
1835 ScopedPyObjectPtr py_length(MergeFromString(cmsg, serialized));
1836 if (py_length == NULL) {
1841 if (InitAttributes(cmsg, NULL, NULL) < 0) {
1848 static PyObject* AddDescriptors(PyTypeObject* cls,
1849 PyObject* descriptor) {
1850 if (PyObject_SetAttr(reinterpret_cast<PyObject*>(cls),
1851 k_extensions_by_name, PyDict_New()) < 0) {
1854 if (PyObject_SetAttr(reinterpret_cast<PyObject*>(cls),
1855 k_extensions_by_number, PyDict_New()) < 0) {
1859 ScopedPyObjectPtr field_descriptors(PyDict_New());
1861 ScopedPyObjectPtr fields(PyObject_GetAttrString(descriptor, "fields"));
1862 if (fields == NULL) {
1866 ScopedPyObjectPtr _NUMBER_string(PyString_FromString("_FIELD_NUMBER"));
1867 if (_NUMBER_string == NULL) {
1871 const Py_ssize_t fields_size = PyList_GET_SIZE(fields.get());
1872 for (int i = 0; i < fields_size; ++i) {
1873 PyObject* field = PyList_GET_ITEM(fields.get(), i);
1874 ScopedPyObjectPtr field_name(PyObject_GetAttr(field, kname));
1875 ScopedPyObjectPtr full_field_name(PyObject_GetAttr(field, kfull_name));
1876 if (field_name == NULL || full_field_name == NULL) {
1877 PyErr_SetString(PyExc_TypeError, "Name is null");
1881 PyObject* field_descriptor =
1882 cdescriptor_pool::FindFieldByName(descriptor_pool, full_field_name);
1883 if (field_descriptor == NULL) {
1884 PyErr_SetString(PyExc_TypeError, "Couldn't find field");
1888 CFieldDescriptor* cfield_descriptor = reinterpret_cast<CFieldDescriptor*>(
1890 cfield_descriptor->descriptor_field = field;
1891 if (PyDict_SetItem(field_descriptors, field_name, field_descriptor) < 0) {
1895 // The FieldDescriptor's name field might either be of type bytes or
1896 // of type unicode, depending on whether the FieldDescriptor was
1897 // parsed from a serialized message or read from the
1898 // <message>_pb2.py module.
1899 ScopedPyObjectPtr field_name_upcased(
1900 PyObject_CallMethod(field_name, "upper", NULL));
1901 if (field_name_upcased == NULL) {
1905 ScopedPyObjectPtr field_number_name(PyObject_CallMethod(
1906 field_name_upcased, "__add__", "(O)", _NUMBER_string.get()));
1907 if (field_number_name == NULL) {
1911 ScopedPyObjectPtr number(PyInt_FromLong(
1912 cfield_descriptor->descriptor->number()));
1913 if (number == NULL) {
1916 if (PyObject_SetAttr(reinterpret_cast<PyObject*>(cls),
1917 field_number_name, number) == -1) {
1922 PyDict_SetItem(cls->tp_dict, k__descriptors, field_descriptors);
1925 ScopedPyObjectPtr enum_types(PyObject_GetAttrString(descriptor,
1927 if (enum_types == NULL) {
1930 ScopedPyObjectPtr type_iter(PyObject_GetIter(enum_types));
1931 if (type_iter == NULL) {
1934 ScopedPyObjectPtr enum_type;
1935 while ((enum_type.reset(PyIter_Next(type_iter))) != NULL) {
1936 ScopedPyObjectPtr wrapped(PyObject_CallFunctionObjArgs(
1937 EnumTypeWrapper_class, enum_type.get(), NULL));
1938 if (wrapped == NULL) {
1941 ScopedPyObjectPtr enum_name(PyObject_GetAttr(enum_type, kname));
1942 if (enum_name == NULL) {
1945 if (PyObject_SetAttr(reinterpret_cast<PyObject*>(cls),
1946 enum_name, wrapped) == -1) {
1950 ScopedPyObjectPtr enum_values(PyObject_GetAttrString(enum_type, "values"));
1951 if (enum_values == NULL) {
1954 ScopedPyObjectPtr values_iter(PyObject_GetIter(enum_values));
1955 if (values_iter == NULL) {
1958 ScopedPyObjectPtr enum_value;
1959 while ((enum_value.reset(PyIter_Next(values_iter))) != NULL) {
1960 ScopedPyObjectPtr value_name(PyObject_GetAttr(enum_value, kname));
1961 if (value_name == NULL) {
1964 ScopedPyObjectPtr value_number(PyObject_GetAttrString(enum_value,
1966 if (value_number == NULL) {
1969 if (PyObject_SetAttr(reinterpret_cast<PyObject*>(cls),
1970 value_name, value_number) == -1) {
1974 if (PyErr_Occurred()) { // If PyIter_Next failed
1978 if (PyErr_Occurred()) { // If PyIter_Next failed
1982 ScopedPyObjectPtr extension_dict(
1983 PyObject_GetAttr(descriptor, kextensions_by_name));
1984 if (extension_dict == NULL || !PyDict_Check(extension_dict)) {
1985 PyErr_SetString(PyExc_TypeError, "extensions_by_name not a dict");
1989 PyObject* extension_name;
1990 PyObject* extension_field;
1992 while (PyDict_Next(extension_dict, &pos, &extension_name, &extension_field)) {
1993 if (PyObject_SetAttr(reinterpret_cast<PyObject*>(cls),
1994 extension_name, extension_field) == -1) {
1997 ScopedPyObjectPtr py_cfield_descriptor(
1998 PyObject_GetAttrString(extension_field, "_cdescriptor"));
1999 if (py_cfield_descriptor == NULL) {
2002 CFieldDescriptor* cfield_descriptor =
2003 reinterpret_cast<CFieldDescriptor*>(py_cfield_descriptor.get());
2004 Py_INCREF(extension_field);
2005 cfield_descriptor->descriptor_field = extension_field;
2007 ScopedPyObjectPtr field_name_upcased(
2008 PyObject_CallMethod(extension_name, "upper", NULL));
2009 if (field_name_upcased == NULL) {
2012 ScopedPyObjectPtr field_number_name(PyObject_CallMethod(
2013 field_name_upcased, "__add__", "(O)", _NUMBER_string.get()));
2014 if (field_number_name == NULL) {
2017 ScopedPyObjectPtr number(PyInt_FromLong(
2018 cfield_descriptor->descriptor->number()));
2019 if (number == NULL) {
2022 if (PyObject_SetAttr(reinterpret_cast<PyObject*>(cls),
2023 field_number_name, PyInt_FromLong(
2024 cfield_descriptor->descriptor->number())) == -1) {
2032 PyObject* DeepCopy(CMessage* self, PyObject* arg) {
2033 PyObject* clone = PyObject_CallObject(
2034 reinterpret_cast<PyObject*>(Py_TYPE(self)), NULL);
2035 if (clone == NULL) {
2038 if (!PyObject_TypeCheck(clone, &CMessage_Type)) {
2042 if (InitAttributes(reinterpret_cast<CMessage*>(clone), NULL, NULL) < 0) {
2046 if (MergeFrom(reinterpret_cast<CMessage*>(clone),
2047 reinterpret_cast<PyObject*>(self)) == NULL) {
2054 PyObject* ToUnicode(CMessage* self) {
2055 // Lazy import to prevent circular dependencies
2056 ScopedPyObjectPtr text_format(
2057 PyImport_ImportModule("google.protobuf.text_format"));
2058 if (text_format == NULL) {
2061 ScopedPyObjectPtr method_name(PyString_FromString("MessageToString"));
2062 if (method_name == NULL) {
2066 ScopedPyObjectPtr encoded(PyObject_CallMethodObjArgs(text_format, method_name,
2067 self, Py_True, NULL));
2069 if (encoded == NULL) {
2072 #if PY_MAJOR_VERSION < 3
2073 PyObject* decoded = PyString_AsDecodedObject(encoded, "utf-8", NULL);
2075 PyObject* decoded = PyUnicode_FromEncodedObject(encoded, "utf-8", NULL);
2077 if (decoded == NULL) {
2083 PyObject* Reduce(CMessage* self) {
2084 ScopedPyObjectPtr constructor(reinterpret_cast<PyObject*>(Py_TYPE(self)));
2086 ScopedPyObjectPtr args(PyTuple_New(0));
2090 ScopedPyObjectPtr state(PyDict_New());
2091 if (state == NULL) {
2094 ScopedPyObjectPtr serialized(SerializePartialToString(self));
2095 if (serialized == NULL) {
2098 if (PyDict_SetItemString(state, "serialized", serialized) < 0) {
2101 return Py_BuildValue("OOO", constructor.get(), args.get(), state.get());
2104 PyObject* SetState(CMessage* self, PyObject* state) {
2105 if (!PyDict_Check(state)) {
2106 PyErr_SetString(PyExc_TypeError, "state not a dict");
2109 PyObject* serialized = PyDict_GetItemString(state, "serialized");
2110 if (serialized == NULL) {
2113 if (ParseFromString(self, serialized) == NULL) {
2119 // CMessage static methods:
2120 PyObject* _GetFieldDescriptor(PyObject* unused, PyObject* arg) {
2121 return cdescriptor_pool::FindFieldByName(descriptor_pool, arg);
2124 PyObject* _GetExtensionDescriptor(PyObject* unused, PyObject* arg) {
2125 return cdescriptor_pool::FindExtensionByName(descriptor_pool, arg);
2128 static PyMemberDef Members[] = {
2129 {"Extensions", T_OBJECT_EX, offsetof(CMessage, extensions), 0,
2134 static PyMethodDef Methods[] = {
2135 { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
2136 "Makes a deep copy of the class." },
2137 { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
2138 "Outputs picklable representation of the message." },
2139 { "__setstate__", (PyCFunction)SetState, METH_O,
2140 "Inputs picklable representation of the message." },
2141 { "__unicode__", (PyCFunction)ToUnicode, METH_NOARGS,
2142 "Outputs a unicode representation of the message." },
2143 { "AddDescriptors", (PyCFunction)AddDescriptors, METH_O | METH_CLASS,
2144 "Adds field descriptors to the class" },
2145 { "ByteSize", (PyCFunction)ByteSize, METH_NOARGS,
2146 "Returns the size of the message in bytes." },
2147 { "Clear", (PyCFunction)Clear, METH_NOARGS,
2148 "Clears the message." },
2149 { "ClearExtension", (PyCFunction)ClearExtension, METH_O,
2150 "Clears a message field." },
2151 { "ClearField", (PyCFunction)ClearField, METH_O,
2152 "Clears a message field." },
2153 { "CopyFrom", (PyCFunction)CopyFrom, METH_O,
2154 "Copies a protocol message into the current message." },
2155 { "FindInitializationErrors", (PyCFunction)FindInitializationErrors,
2157 "Finds unset required fields." },
2158 { "FromString", (PyCFunction)FromString, METH_O | METH_CLASS,
2159 "Creates new method instance from given serialized data." },
2160 { "HasExtension", (PyCFunction)HasExtension, METH_O,
2161 "Checks if a message field is set." },
2162 { "HasField", (PyCFunction)HasField, METH_O,
2163 "Checks if a message field is set." },
2164 { "IsInitialized", (PyCFunction)IsInitialized, METH_VARARGS,
2165 "Checks if all required fields of a protocol message are set." },
2166 { "ListFields", (PyCFunction)ListFields, METH_NOARGS,
2167 "Lists all set fields of a message." },
2168 { "MergeFrom", (PyCFunction)MergeFrom, METH_O,
2169 "Merges a protocol message into the current message." },
2170 { "MergeFromString", (PyCFunction)MergeFromString, METH_O,
2171 "Merges a serialized message into the current message." },
2172 { "ParseFromString", (PyCFunction)ParseFromString, METH_O,
2173 "Parses a serialized message into the current message." },
2174 { "RegisterExtension", (PyCFunction)RegisterExtension, METH_O | METH_CLASS,
2175 "Registers an extension with the current message." },
2176 { "SerializePartialToString", (PyCFunction)SerializePartialToString,
2178 "Serializes the message to a string, even if it isn't initialized." },
2179 { "SerializeToString", (PyCFunction)SerializeToString, METH_NOARGS,
2180 "Serializes the message to a string, only for initialized messages." },
2181 { "SetInParent", (PyCFunction)SetInParent, METH_NOARGS,
2182 "Sets the has bit of the given field in its parent message." },
2183 { "WhichOneof", (PyCFunction)WhichOneof, METH_O,
2184 "Returns the name of the field set inside a oneof, "
2185 "or None if no field is set." },
2188 { "_BuildFile", (PyCFunction)Python_BuildFile, METH_O | METH_STATIC,
2189 "Registers a new protocol buffer file in the global C++ descriptor pool." },
2190 { "_GetFieldDescriptor", (PyCFunction)_GetFieldDescriptor,
2191 METH_O | METH_STATIC, "Finds a field descriptor in the message pool." },
2192 { "_GetExtensionDescriptor", (PyCFunction)_GetExtensionDescriptor,
2193 METH_O | METH_STATIC,
2194 "Finds a extension descriptor in the message pool." },
2198 PyObject* GetAttr(CMessage* self, PyObject* name) {
2199 PyObject* value = PyDict_GetItem(self->composite_fields, name);
2200 if (value != NULL) {
2205 PyObject* descriptor = GetDescriptor(self, name);
2206 if (descriptor != NULL) {
2207 CFieldDescriptor* cdescriptor =
2208 reinterpret_cast<CFieldDescriptor*>(descriptor);
2209 const google::protobuf::FieldDescriptor* field_descriptor = cdescriptor->descriptor;
2210 if (field_descriptor->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED) {
2211 if (field_descriptor->cpp_type() ==
2212 google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
2213 PyObject* py_container = PyObject_CallObject(
2214 reinterpret_cast<PyObject*>(&RepeatedCompositeContainer_Type),
2216 if (py_container == NULL) {
2219 RepeatedCompositeContainer* container =
2220 reinterpret_cast<RepeatedCompositeContainer*>(py_container);
2221 PyObject* field = cdescriptor->descriptor_field;
2222 PyObject* message_type = PyObject_GetAttr(field, kmessage_type);
2223 if (message_type == NULL) {
2226 PyObject* concrete_class =
2227 PyObject_GetAttr(message_type, k_concrete_class);
2228 if (concrete_class == NULL) {
2231 container->parent = self;
2232 container->parent_field = cdescriptor;
2233 container->message = self->message;
2234 container->owner = self->owner;
2235 container->subclass_init = concrete_class;
2236 Py_DECREF(message_type);
2237 if (PyDict_SetItem(self->composite_fields, name, py_container) < 0) {
2238 Py_DECREF(py_container);
2241 return py_container;
2243 ScopedPyObjectPtr init_args(PyTuple_Pack(2, self, cdescriptor));
2244 PyObject* py_container = PyObject_CallObject(
2245 reinterpret_cast<PyObject*>(&RepeatedScalarContainer_Type),
2247 if (py_container == NULL) {
2250 if (PyDict_SetItem(self->composite_fields, name, py_container) < 0) {
2251 Py_DECREF(py_container);
2254 return py_container;
2257 if (field_descriptor->cpp_type() ==
2258 google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
2259 PyObject* sub_message = InternalGetSubMessage(self, cdescriptor);
2260 if (PyDict_SetItem(self->composite_fields, name, sub_message) < 0) {
2261 Py_DECREF(sub_message);
2266 return InternalGetScalar(self, field_descriptor);
2271 return CMessage_Type.tp_base->tp_getattro(reinterpret_cast<PyObject*>(self),
2275 int SetAttr(CMessage* self, PyObject* name, PyObject* value) {
2276 if (PyDict_Contains(self->composite_fields, name)) {
2277 PyErr_SetString(PyExc_TypeError, "Can't set composite field");
2281 PyObject* descriptor = GetDescriptor(self, name);
2282 if (descriptor != NULL) {
2283 AssureWritable(self);
2284 CFieldDescriptor* cdescriptor =
2285 reinterpret_cast<CFieldDescriptor*>(descriptor);
2286 const google::protobuf::FieldDescriptor* field_descriptor = cdescriptor->descriptor;
2287 if (field_descriptor->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED) {
2288 PyErr_Format(PyExc_AttributeError, "Assignment not allowed to repeated "
2289 "field \"%s\" in protocol message object.",
2290 field_descriptor->name().c_str());
2293 if (field_descriptor->cpp_type() ==
2294 google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
2295 PyErr_Format(PyExc_AttributeError, "Assignment not allowed to "
2296 "field \"%s\" in protocol message object.",
2297 field_descriptor->name().c_str());
2300 return InternalSetScalar(self, field_descriptor, value);
2305 PyErr_Format(PyExc_AttributeError, "Assignment not allowed");
2309 } // namespace cmessage
2311 PyTypeObject CMessage_Type = {
2312 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2313 "google.protobuf.internal."
2314 "cpp._message.CMessage", // tp_name
2315 sizeof(CMessage), // tp_basicsize
2317 (destructor)cmessage::Dealloc, // tp_dealloc
2324 0, // tp_as_sequence
2328 (reprfunc)cmessage::ToStr, // tp_str
2329 (getattrofunc)cmessage::GetAttr, // tp_getattro
2330 (setattrofunc)cmessage::SetAttr, // tp_setattro
2332 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
2333 "A ProtocolMessage", // tp_doc
2336 (richcmpfunc)cmessage::RichCompare, // tp_richcompare
2337 0, // tp_weaklistoffset
2340 cmessage::Methods, // tp_methods
2341 cmessage::Members, // tp_members
2348 (initproc)cmessage::Init, // tp_init
2350 cmessage::New, // tp_new
2353 // --- Exposing the C proto living inside Python proto to C code:
2355 const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg);
2356 Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg);
2358 static const google::protobuf::Message* GetCProtoInsidePyProtoImpl(PyObject* msg) {
2359 if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
2362 CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
2363 return cmsg->message;
2366 static google::protobuf::Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
2367 if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
2370 CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
2371 if (PyDict_Size(cmsg->composite_fields) != 0 ||
2372 (cmsg->extensions != NULL &&
2373 PyDict_Size(cmsg->extensions->values) != 0)) {
2374 // There is currently no way of accurately syncing arbitrary changes to
2375 // the underlying C++ message back to the CMessage (e.g. removed repeated
2376 // composite containers). We only allow direct mutation of the underlying
2377 // C++ message if there is no child data in the CMessage.
2380 cmessage::AssureWritable(cmsg);
2381 return cmsg->message;
2384 static const char module_docstring[] =
2385 "python-proto2 is a module that can be used to enhance proto2 Python API\n"
2388 "It provides access to the protocol buffers C++ reflection API that\n"
2389 "implements the basic protocol buffer functions.";
2391 void InitGlobals() {
2392 // TODO(gps): Check all return values in this function for NULL and propagate
2393 // the error (MemoryError) on up to result in an import failure. These should
2394 // also be freed and reset to NULL during finalization.
2395 kPythonZero = PyInt_FromLong(0);
2396 kint32min_py = PyInt_FromLong(kint32min);
2397 kint32max_py = PyInt_FromLong(kint32max);
2398 kuint32max_py = PyLong_FromLongLong(kuint32max);
2399 kint64min_py = PyLong_FromLongLong(kint64min);
2400 kint64max_py = PyLong_FromLongLong(kint64max);
2401 kuint64max_py = PyLong_FromUnsignedLongLong(kuint64max);
2403 kDESCRIPTOR = PyString_FromString("DESCRIPTOR");
2404 k__descriptors = PyString_FromString("__descriptors");
2405 kfull_name = PyString_FromString("full_name");
2406 kis_extendable = PyString_FromString("is_extendable");
2407 kextensions_by_name = PyString_FromString("extensions_by_name");
2408 k_extensions_by_name = PyString_FromString("_extensions_by_name");
2409 k_extensions_by_number = PyString_FromString("_extensions_by_number");
2410 k_concrete_class = PyString_FromString("_concrete_class");
2411 kmessage_type = PyString_FromString("message_type");
2412 kname = PyString_FromString("name");
2413 kfields_by_name = PyString_FromString("fields_by_name");
2415 global_message_factory = new DynamicMessageFactory(GetDescriptorPool());
2416 global_message_factory->SetDelegateToGeneratedFactory(true);
2418 descriptor_pool = reinterpret_cast<google::protobuf::python::CDescriptorPool*>(
2419 Python_NewCDescriptorPool(NULL, NULL));
2422 bool InitProto2MessageModule(PyObject *m) {
2425 google::protobuf::python::CMessage_Type.tp_hash = PyObject_HashNotImplemented;
2426 if (PyType_Ready(&google::protobuf::python::CMessage_Type) < 0) {
2430 // All three of these are actually set elsewhere, directly onto the child
2431 // protocol buffer message class, but set them here as well to document that
2432 // subclasses need to set these.
2433 PyDict_SetItem(google::protobuf::python::CMessage_Type.tp_dict, kDESCRIPTOR, Py_None);
2434 PyDict_SetItem(google::protobuf::python::CMessage_Type.tp_dict,
2435 k_extensions_by_name, Py_None);
2436 PyDict_SetItem(google::protobuf::python::CMessage_Type.tp_dict,
2437 k_extensions_by_number, Py_None);
2439 PyModule_AddObject(m, "Message", reinterpret_cast<PyObject*>(
2440 &google::protobuf::python::CMessage_Type));
2442 google::protobuf::python::RepeatedScalarContainer_Type.tp_new = PyType_GenericNew;
2443 google::protobuf::python::RepeatedScalarContainer_Type.tp_hash =
2444 PyObject_HashNotImplemented;
2445 if (PyType_Ready(&google::protobuf::python::RepeatedScalarContainer_Type) < 0) {
2449 PyModule_AddObject(m, "RepeatedScalarContainer",
2450 reinterpret_cast<PyObject*>(
2451 &google::protobuf::python::RepeatedScalarContainer_Type));
2453 google::protobuf::python::RepeatedCompositeContainer_Type.tp_new = PyType_GenericNew;
2454 google::protobuf::python::RepeatedCompositeContainer_Type.tp_hash =
2455 PyObject_HashNotImplemented;
2456 if (PyType_Ready(&google::protobuf::python::RepeatedCompositeContainer_Type) < 0) {
2461 m, "RepeatedCompositeContainer",
2462 reinterpret_cast<PyObject*>(
2463 &google::protobuf::python::RepeatedCompositeContainer_Type));
2465 google::protobuf::python::ExtensionDict_Type.tp_new = PyType_GenericNew;
2466 google::protobuf::python::ExtensionDict_Type.tp_hash = PyObject_HashNotImplemented;
2467 if (PyType_Ready(&google::protobuf::python::ExtensionDict_Type) < 0) {
2473 reinterpret_cast<PyObject*>(&google::protobuf::python::ExtensionDict_Type));
2475 if (!google::protobuf::python::InitDescriptor()) {
2479 PyObject* enum_type_wrapper = PyImport_ImportModule(
2480 "google.protobuf.internal.enum_type_wrapper");
2481 if (enum_type_wrapper == NULL) {
2484 google::protobuf::python::EnumTypeWrapper_class =
2485 PyObject_GetAttrString(enum_type_wrapper, "EnumTypeWrapper");
2486 Py_DECREF(enum_type_wrapper);
2488 PyObject* message_module = PyImport_ImportModule(
2489 "google.protobuf.message");
2490 if (message_module == NULL) {
2493 google::protobuf::python::EncodeError_class = PyObject_GetAttrString(message_module,
2495 google::protobuf::python::DecodeError_class = PyObject_GetAttrString(message_module,
2497 Py_DECREF(message_module);
2499 PyObject* pickle_module = PyImport_ImportModule("pickle");
2500 if (pickle_module == NULL) {
2503 google::protobuf::python::PickleError_class = PyObject_GetAttrString(pickle_module,
2505 Py_DECREF(pickle_module);
2507 // Override {Get,Mutable}CProtoInsidePyProto.
2508 google::protobuf::python::GetCProtoInsidePyProtoPtr =
2509 google::protobuf::python::GetCProtoInsidePyProtoImpl;
2510 google::protobuf::python::MutableCProtoInsidePyProtoPtr =
2511 google::protobuf::python::MutableCProtoInsidePyProtoImpl;
2516 } // namespace python
2517 } // namespace protobuf
2520 #if PY_MAJOR_VERSION >= 3
2521 static struct PyModuleDef _module = {
2522 PyModuleDef_HEAD_INIT,
2524 google::protobuf::python::module_docstring,
2532 #define INITFUNC PyInit__message
2533 #define INITFUNC_ERRORVAL NULL
2535 #define INITFUNC init_message
2536 #define INITFUNC_ERRORVAL
2540 PyMODINIT_FUNC INITFUNC(void) {
2542 #if PY_MAJOR_VERSION >= 3
2543 m = PyModule_Create(&_module);
2545 m = Py_InitModule3("_message", NULL, google::protobuf::python::module_docstring);
2548 return INITFUNC_ERRORVAL;
2551 if (!google::protobuf::python::InitProto2MessageModule(m)) {
2553 return INITFUNC_ERRORVAL;
2556 #if PY_MAJOR_VERSION >= 3
2561 } // namespace google