40 #include <structmember.h>
42 #ifndef PyVarObject_HEAD_INIT
43 #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
46 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
73 #include <google/protobuf/port_def.inc>
75 #if PY_MAJOR_VERSION >= 3
76 #define PyInt_AsLong PyLong_AsLong
77 #define PyInt_FromLong PyLong_FromLong
78 #define PyInt_FromSize_t PyLong_FromSize_t
79 #define PyString_Check PyUnicode_Check
80 #define PyString_FromString PyUnicode_FromString
81 #define PyString_FromStringAndSize PyUnicode_FromStringAndSize
82 #define PyString_FromFormat PyUnicode_FromFormat
83 #if PY_VERSION_HEX < 0x03030000
84 #error "Python 3.0 - 3.2 are not supported."
86 #define PyString_AsString(ob) \
87 (PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AsString(ob))
88 #define PyString_AsStringAndSize(ob, charpp, sizep) \
89 (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
90 PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
93 : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
107 namespace message_meta {
114 string::iterator
end =
s->end();
115 for (string::iterator
i =
s->begin();
i !=
end; ++
i) {
117 if (
'A' <= *
i && *
i <=
'Z') *
i +=
'a' -
'A';
128 if (property ==
NULL) {
131 if (PyObject_SetAttrString(cls, field_descriptor->
name().c_str(),
132 property.
get()) < 0) {
148 if (wrapped ==
NULL) {
151 if (PyObject_SetAttrString(
161 enum_value_descriptor->
number()));
162 if (value_number ==
NULL) {
165 if (PyObject_SetAttrString(cls, enum_value_descriptor->
name().c_str(),
166 value_number.
get()) == -1) {
180 if (extension_field ==
NULL) {
185 if (PyObject_SetAttrString(
186 cls,
field->name().c_str(), extension_field.
get()) == -1) {
195 PyObject*
args, PyObject* kwargs) {
196 static char *kwlist[] = {
"name",
"bases",
"dict", 0};
197 PyObject *bases, *dict;
201 if (!PyArg_ParseTupleAndKeywords(
args, kwargs,
"sO!O!:type", kwlist,
203 &PyTuple_Type, &bases,
204 &PyDict_Type, &dict)) {
209 if (!(PyTuple_GET_SIZE(bases) == 0 ||
210 (PyTuple_GET_SIZE(bases) == 1 &&
212 PyErr_SetString(PyExc_TypeError,
213 "A Message class can only inherit from Message");
218 PyObject* py_descriptor = PyDict_GetItem(dict,
kDESCRIPTOR);
219 if (py_descriptor ==
NULL) {
220 PyErr_SetString(PyExc_TypeError,
"Message class has no DESCRIPTOR");
224 PyErr_Format(PyExc_TypeError,
"Expected a message Descriptor, got %s",
225 py_descriptor->ob_type->tp_name);
231 if (PyDict_SetItemString(dict,
"__slots__", slots.
get()) < 0) {
240 if (message_descriptor ==
NULL) {
246 "google.protobuf.internal.well_known_types"));
249 WKT_classes = PyObject_GetAttrString(well_known_types.
get(),
"WKTBASES");
253 PyObject* well_known_class = PyDict_GetItemString(
255 if (well_known_class ==
NULL) {
263 if (new_args ==
NULL) {
268 if (result ==
NULL) {
286 Py_INCREF(py_descriptor);
293 if (py_descriptor_pool ==
NULL) {
316 Py_XDECREF(
self->py_message_descriptor);
317 Py_XDECREF(
self->py_message_factory);
318 return PyType_Type.tp_dealloc(pself);
323 Py_VISIT(
self->py_message_descriptor);
324 Py_VISIT(
self->py_message_factory);
325 return PyType_Type.tp_traverse(pself,
visit, arg);
331 return PyType_Type.tp_clear(pself);
340 #if PY_MAJOR_VERSION >= 3
351 PyObject *subclasses = base_type->tp_subclasses;
352 if (subclasses && PyList_CheckExact(subclasses)) {
357 #endif // PY_MAJOR_VERSION >= 3
363 if (
self->message_descriptor ==
NULL) {
365 PyErr_SetString(PyExc_AttributeError,
366 "Base Message class has no DESCRIPTOR");
372 std::vector<const FieldDescriptor*> extensions;
373 pool->pool->FindAllExtensions(
self->message_descriptor, &extensions);
376 for (
int i = 0;
i < extensions.size();
i++) {
382 if (PyDict_SetItemString(result.
get(), extensions[
i]->full_name().c_str(),
393 if (
self->message_descriptor ==
NULL) {
395 PyErr_SetString(PyExc_AttributeError,
396 "Base Message class has no DESCRIPTOR");
402 std::vector<const FieldDescriptor*> extensions;
403 pool->pool->FindAllExtensions(
self->message_descriptor, &extensions);
406 for (
int i = 0;
i < extensions.size();
i++) {
434 Py_ssize_t attr_size;
435 static const char kSuffix[] =
"_FIELD_NUMBER";
436 if (PyString_AsStringAndSize(
name, &attr, &attr_size) >= 0 &&
438 string field_name(attr, attr_size -
sizeof(kSuffix) + 1);
443 self->message_descriptor->FindFieldByLowercaseName(field_name);
447 self->message_descriptor->FindExtensionByLowercaseName(field_name);
450 return PyInt_FromLong(
field->number());
453 PyErr_SetObject(PyExc_AttributeError,
name);
459 reinterpret_cast<PyObject*
>(
self),
name);
460 if (result !=
NULL) {
463 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
493 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
494 "The metaclass of ProtocolMessages",
517 PyErr_Format(PyExc_TypeError,
"Class %s is not a Message", cls->tp_name);
528 return type->message_descriptor;
550 PyObject* repr = PyObject_Repr(arg);
552 PyErr_Format(PyExc_TypeError,
553 "%.100s has type %.100s, but expected one of: %s",
554 PyString_AsString(repr),
562 PyObject *
s = PyObject_Str(arg);
564 PyErr_Format(PyExc_ValueError,
565 "Value out of range: %s",
566 PyString_AsString(
s));
571 template<
class RangeType,
class ValueType>
573 if (PROTOBUF_PREDICT_FALSE(
value == -1 && PyErr_Occurred())) {
574 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
582 if (PROTOBUF_PREDICT_FALSE(!IsValidNumericCast<RangeType>(
value))) {
592 #if PY_MAJOR_VERSION < 3
594 if (PROTOBUF_PREDICT_TRUE(PyInt_Check(arg))) {
595 long int_result = PyInt_AsLong(arg);
596 if (PROTOBUF_PREDICT_TRUE(IsValidNumericCast<T>(int_result))) {
597 *
value =
static_cast<T>(int_result);
609 if (PROTOBUF_PREDICT_FALSE(!PyIndex_Check(arg))) {
617 if (std::numeric_limits<T>::min() == 0) {
619 unsigned PY_LONG_LONG ulong_result;
620 if (PyLong_Check(arg)) {
621 ulong_result = PyLong_AsUnsignedLongLong(arg);
625 PyObject* casted = PyNumber_Long(arg);
626 if (PROTOBUF_PREDICT_FALSE(casted ==
nullptr)) {
630 ulong_result = PyLong_AsUnsignedLongLong(casted);
633 if (VerifyIntegerCastAndRange<T, unsigned PY_LONG_LONG>(arg,
635 *
value =
static_cast<T>(ulong_result);
641 PY_LONG_LONG long_result;
643 if ((nb = arg->ob_type->tp_as_number) !=
NULL && nb->nb_int !=
NULL) {
646 long_result = PyLong_AsLongLong(arg);
650 PyObject* casted = PyNumber_Long(arg);
651 if (PROTOBUF_PREDICT_FALSE(casted ==
nullptr)) {
655 long_result = PyLong_AsLongLong(casted);
658 if (VerifyIntegerCastAndRange<T, PY_LONG_LONG>(arg, long_result)) {
659 *
value =
static_cast<T>(long_result);
676 *
value = PyFloat_AsDouble(arg);
677 if (PROTOBUF_PREDICT_FALSE(*
value == -1 && PyErr_Occurred())) {
694 long long_value = PyInt_AsLong(arg);
695 if (long_value == -1 && PyErr_Occurred()) {
699 *
value =
static_cast<bool>(long_value);
707 if (PyBytes_Check(
obj)) {
708 PyObject* unicode = PyUnicode_FromEncodedObject(
obj,
"utf-8",
NULL);
731 if (!PyBytes_Check(arg) && !PyUnicode_Check(arg)) {
737 PyObject* repr = PyObject_Repr(arg);
738 PyErr_Format(PyExc_ValueError,
739 "%s has type str, but isn't valid UTF-8 "
740 "encoding. Non-UTF-8 strings must be converted to "
741 "unicode objects before being added.",
742 PyString_AsString(repr));
746 }
else if (!PyBytes_Check(arg)) {
751 PyObject* encoded_string =
NULL;
753 if (PyBytes_Check(arg)) {
755 encoded_string = arg;
756 Py_INCREF(encoded_string);
758 encoded_string = PyUnicode_AsEncodedString(arg,
"utf-8",
NULL);
762 encoded_string = arg;
763 Py_INCREF(encoded_string);
766 return encoded_string;
777 if (encoded_string.
get() ==
NULL) {
782 Py_ssize_t value_len;
783 if (PyBytes_AsStringAndSize(encoded_string.
get(), &
value, &value_len) < 0) {
787 string value_string(
value, value_len);
790 }
else if (
index < 0) {
799 const string&
value) {
801 return PyBytes_FromStringAndSize(
value.c_str(),
value.length());
804 PyObject* result = PyUnicode_DecodeUTF8(
value.c_str(),
value.length(),
NULL);
809 if (result ==
NULL) {
811 result = PyBytes_FromStringAndSize(
value.c_str(),
value.length());
821 PyErr_Format(PyExc_KeyError,
"Field '%s' does not belong to message '%s'",
823 message->GetDescriptor()->full_name().c_str());
837 #ifdef GOOGLE_PROTOBUF_HAS_ONEOF
840 if (!
field->containing_oneof() ||
864 if (!
self->composite_fields) {
867 for (
const auto&
item : *
self->composite_fields) {
882 cmsg->
message = mutable_message;
898 if (
self ==
NULL || !
self->read_only) {
911 self->parent_field_descriptor) < 0) {
916 Message* parent_message =
self->parent->message;
919 parent_message,
self->parent_field_descriptor,
921 if (mutable_message ==
NULL) {
924 self->message = mutable_message;
925 self->read_only =
false;
939 PyErr_SetObject(PyExc_KeyError,
extension);
949 if (PyString_Check(
value) || PyUnicode_Check(
value)) {
952 PyErr_SetString(PyExc_TypeError,
"not an enum field");
957 if (PyString_AsStringAndSize(
value, &enum_label, &
size) < 0) {
962 if (enum_value_descriptor ==
NULL) {
963 PyErr_Format(PyExc_ValueError,
"unknown enum label \"%s\"", enum_label);
966 return PyInt_FromLong(enum_value_descriptor->
number());
980 Py_ssize_t
length, from, to, step, slice_length;
986 if (PySlice_Check(slice)) {
987 from = to = step = slice_length = 0;
988 #if PY_MAJOR_VERSION < 3
989 PySlice_GetIndicesEx(
990 reinterpret_cast<PySliceObject*
>(slice),
991 length, &from, &to, &step, &slice_length);
993 PySlice_GetIndicesEx(
995 length, &from, &to, &step, &slice_length);
1005 from = to = PyLong_AsLong(slice);
1006 if (from == -1 && PyErr_Occurred()) {
1007 PyErr_SetString(PyExc_TypeError,
"list indices must be integers");
1012 from = to =
length + from;
1018 if (from < 0 || from >=
length) {
1019 PyErr_Format(PyExc_IndexError,
"list assignment index out of range");
1024 Py_ssize_t
i = from;
1025 std::vector<bool> to_delete(
length,
false);
1026 while (
i >= min &&
i <= max) {
1027 to_delete[
i] =
true;
1034 if (!to_delete[
i]) {
1053 if (
CMessage* released =
self->MaybeReleaseSubMessage(sub_message)) {
1054 released->message = sub_message;
1067 PyErr_SetString(PyExc_TypeError,
"No positional arguments allowed");
1071 if (kwargs ==
NULL) {
1078 while (PyDict_Next(kwargs, &pos, &
name, &
value)) {
1079 if (!(PyString_Check(
name) || PyUnicode_Check(
name))) {
1080 PyErr_SetString(PyExc_ValueError,
"Field name must be a string");
1084 PyObject_GetAttr(
reinterpret_cast<PyObject*
>(
Py_TYPE(
self)),
name));
1085 if (property ==
NULL ||
1087 PyErr_Format(PyExc_ValueError,
"Protocol message %s has no \"%s\" field.",
1088 self->message->GetDescriptor()->name().c_str(),
1089 PyString_AsString(
name));
1095 if (
value == Py_None) {
1102 descriptor->message_type()->FindFieldByName(
"value");
1106 PyErr_Format(PyExc_TypeError,
"Argument %s is not iterable", PyString_AsString(
name));
1110 while ((
next.reset(PyIter_Next(iter.
get()))) !=
NULL) {
1117 dest_value.
get(),
"MergeFrom",
"O", source_value.
get()));
1124 function_return.
reset(
1125 PyObject_CallMethod(
map.get(),
"update",
"O",
value));
1126 if (function_return.
get() ==
NULL) {
1132 if (container ==
NULL) {
1140 PyErr_SetString(PyExc_TypeError,
"Value must be iterable");
1144 while ((
next.reset(PyIter_Next(iter.
get()))) !=
NULL) {
1145 PyObject* kwargs = (PyDict_Check(
next.get()) ?
next.get() :
NULL);
1148 if (new_msg ==
NULL) {
1151 if (kwargs ==
NULL) {
1160 if (PyErr_Occurred()) {
1169 PyErr_SetString(PyExc_TypeError,
"Value must be iterable");
1173 while ((
next.reset(PyIter_Next(iter.
get()))) !=
NULL) {
1176 if (enum_value ==
NULL) {
1180 rs_container, enum_value.
get()));
1181 if (new_msg ==
NULL) {
1185 if (PyErr_Occurred()) {
1203 if (PyDict_Check(
value)) {
1219 if (new_val ==
NULL) {
1236 PyType_GenericAlloc(&
type->super.ht_type, 0));
1241 self->message =
NULL;
1242 self->parent =
NULL;
1243 self->parent_field_descriptor =
NULL;
1244 self->read_only =
false;
1246 self->composite_fields =
NULL;
1247 self->child_submessages =
NULL;
1249 self->unknown_field_set =
NULL;
1256 static PyObject*
New(PyTypeObject* cls,
1257 PyObject* unused_args, PyObject* unused_kwargs) {
1264 if (message_descriptor ==
NULL) {
1268 type->py_message_factory->message_factory->GetPrototype(
1269 message_descriptor);
1270 if (prototype ==
NULL) {
1271 PyErr_SetString(PyExc_TypeError, message_descriptor->
full_name().c_str());
1279 self->message = prototype->
New();
1280 self->parent =
nullptr;
1281 return reinterpret_cast<PyObject*
>(
self);
1294 if (
self->weakreflist) {
1295 PyObject_ClearWeakRefs(
reinterpret_cast<PyObject*
>(
self));
1300 delete self->child_submessages;
1301 delete self->composite_fields;
1302 if (
self->unknown_field_set) {
1311 }
else if (parent->
AsPyObject() == Py_None) {
1313 Py_CLEAR(
self->parent);
1316 if (
self->parent_field_descriptor->is_repeated()) {
1323 Py_CLEAR(
self->parent);
1325 Py_TYPE(
self)->tp_free(
reinterpret_cast<PyObject*
>(
self));
1333 if (PyArg_ParseTuple(
args,
"|O", &
errors) < 0) {
1336 if (
self->message->IsInitialized()) {
1342 if (initialization_errors ==
NULL) {
1346 if (extend_name ==
NULL) {
1352 initialization_errors.
get(),
1354 if (result ==
NULL) {
1368 PyErr_SetString(PyExc_KeyError,
1369 "Field is repeated. A singular method is required.");
1374 return PyBool_FromLong(has_field ? 1 : 0);
1378 const Message*
message,
const string& field_name,
bool* in_oneof) {
1383 if (field_descriptor !=
NULL) {
1384 return field_descriptor;
1388 if (oneof_desc !=
NULL) {
1390 return message->GetReflection()->GetOneofFieldDescriptor(*
message,
1399 PyErr_Format(PyExc_ValueError,
1400 "Protocol message %s has no singular \"%s\" field.",
1401 message_name.c_str(), field_descriptor->
name().c_str());
1408 PyErr_Format(PyExc_ValueError,
1409 "Can't test oneof field \"%s.%s\" for presence in proto3, "
1410 "use WhichOneof instead.", message_name.c_str(),
1423 "Can't test non-submessage field \"%s.%s\" for presence in proto3.",
1424 message_name.c_str(), field_descriptor->
name().c_str());
1435 #if PY_MAJOR_VERSION < 3
1436 if (PyString_AsStringAndSize(arg, &field_name, &
size) < 0) {
1440 field_name =
const_cast<char*
>(PyUnicode_AsUTF8AndSize(arg, &
size));
1450 if (field_descriptor ==
NULL) {
1452 PyErr_Format(PyExc_ValueError,
"Protocol message %s has no field %s.",
1453 message->GetDescriptor()->name().c_str(), field_name);
1464 if (
message->GetReflection()->HasField(*
message, field_descriptor)) {
1516 CMessage*
self,
const std::vector<CMessage*>& messages_to_release,
1517 const std::vector<ContainerBase*>& containers_to_release) {
1518 if (messages_to_release.empty() && containers_to_release.empty()) {
1524 if (new_message ==
nullptr) {
1531 std::set<const FieldDescriptor*> fields_to_swap;
1537 for (
const auto& to_release : messages_to_release) {
1538 fields_to_swap.insert(to_release->parent_field_descriptor);
1540 Py_INCREF(new_message);
1541 Py_DECREF(to_release->parent);
1542 to_release->parent = new_message;
1547 for (
const auto& to_release : containers_to_release) {
1548 fields_to_swap.insert(to_release->parent_field_descriptor);
1549 Py_INCREF(new_message);
1550 Py_DECREF(to_release->parent);
1551 to_release->parent = new_message;
1553 new_message->
composite_fields->emplace(to_release->parent_field_descriptor,
1557 self->message->GetReflection()->SwapFields(
1559 std::vector<const FieldDescriptor*>(fields_to_swap.begin(),
1560 fields_to_swap.end()));
1576 std::vector<CMessage*> messages_to_release;
1577 std::vector<ContainerBase*> containers_to_release;
1580 for (
const auto& child_item : *
self->child_submessages) {
1581 if (child_item.second->parent_field_descriptor == field_descriptor) {
1582 messages_to_release.push_back(child_item.second);
1586 if (
self->composite_fields) {
1587 CMessage::CompositeFieldsMap::iterator
it =
1588 self->composite_fields->find(field_descriptor);
1589 if (
it !=
self->composite_fields->end()) {
1590 containers_to_release.push_back(
it->second);
1595 containers_to_release);
1611 if (!(PyString_Check(arg) || PyUnicode_Check(arg))) {
1612 PyErr_SetString(PyExc_TypeError,
"field name must be a string");
1615 #if PY_MAJOR_VERSION < 3
1618 if (PyString_AsStringAndSize(arg, &field_name, &
size) < 0) {
1623 const char* field_name = PyUnicode_AsUTF8AndSize(arg, &
size);
1631 if (field_descriptor ==
NULL) {
1633 PyErr_Format(PyExc_ValueError,
1634 "Protocol message has no \"%s\" field.", field_name);
1639 }
else if (is_in_oneof) {
1640 const string&
name = field_descriptor->
name();
1641 arg_in_oneof.
reset(PyString_FromStringAndSize(
name.c_str(),
name.size()));
1642 arg = arg_in_oneof.
get();
1654 std::vector<CMessage*> messages_to_release;
1655 std::vector<ContainerBase*> containers_to_release;
1656 if (
self->child_submessages) {
1657 for (
const auto&
item : *
self->child_submessages) {
1658 messages_to_release.push_back(
item.second);
1661 if (
self->composite_fields) {
1662 for (
const auto&
item : *
self->composite_fields) {
1663 containers_to_release.push_back(
item.second);
1670 if (
self->unknown_field_set) {
1673 self->unknown_field_set =
nullptr;
1675 self->message->Clear();
1682 if (
self->parent_field_descriptor !=
NULL) {
1683 return self->parent_field_descriptor->full_name();
1685 return self->message->GetDescriptor()->full_name();
1691 bool require_initialized) {
1693 static char* kwlist[] = {
"deterministic", 0 };
1694 PyObject* deterministic_obj = Py_None;
1695 if (!PyArg_ParseTupleAndKeywords(
args, kwargs,
"|O", kwlist,
1696 &deterministic_obj)) {
1702 int deterministic = PyObject_IsTrue(deterministic_obj);
1703 if (deterministic < 0) {
1707 if (require_initialized && !
self->message->IsInitialized()) {
1713 if (comma ==
NULL) {
1717 PyObject_CallMethod(comma.
get(),
"join",
"O",
errors.get()));
1718 if (joined ==
NULL) {
1730 "google.protobuf.message"));
1731 if (message_module.
get() ==
NULL) {
1736 PyObject_GetAttrString(message_module.
get(),
"EncodeError"));
1737 if (encode_error.
get() ==
NULL) {
1740 PyErr_Format(encode_error.
get(),
1741 "Message %s is missing required fields: %s",
1747 const size_t size =
self->message->ByteSizeLong();
1749 return PyBytes_FromString(
"");
1751 PyObject* result = PyBytes_FromStringAndSize(
NULL,
size);
1752 if (result ==
NULL) {
1757 if (deterministic_obj != Py_None) {
1760 self->message->SerializeWithCachedSizes(&coded_out);
1802 if (!py_value.
get()) {
1807 if (!py_str.
get()) {
1811 return string(PyString_AsString(py_str.
get()));
1822 PyErr_SetString(PyExc_ValueError,
"Unable to convert message to str");
1825 return PyString_FromString(
output.c_str());
1831 PyErr_Format(PyExc_TypeError,
1832 "Parameter to MergeFrom() must be instance of same class: "
1833 "expected %s got %s.",
1834 self->message->GetDescriptor()->full_name().c_str(),
1839 other_message =
reinterpret_cast<CMessage*
>(arg);
1841 self->message->GetDescriptor()) {
1842 PyErr_Format(PyExc_TypeError,
1843 "Parameter to MergeFrom() must be instance of same class: "
1844 "expected %s got %s.",
1845 self->message->GetDescriptor()->full_name().c_str(),
1851 self->message->MergeFrom(*other_message->
message);
1864 PyErr_Format(PyExc_TypeError,
1865 "Parameter to CopyFrom() must be instance of same class: "
1866 "expected %s got %s.",
1867 self->message->GetDescriptor()->full_name().c_str(),
1872 other_message =
reinterpret_cast<CMessage*
>(arg);
1874 if (
self == other_message) {
1879 self->message->GetDescriptor()) {
1880 PyErr_Format(PyExc_TypeError,
1881 "Parameter to CopyFrom() must be instance of same class: "
1882 "expected %s got %s.",
1883 self->message->GetDescriptor()->full_name().c_str(),
1894 self->message->CopyFrom(*other_message->
message);
1905 #ifdef PROTOBUF_PYTHON_ALLOW_OVERSIZE_PROTOS
1914 if (!arg || !PyBool_Check(arg)) {
1915 PyErr_SetString(PyExc_TypeError,
1916 "Argument to SetAllowOversizeProtos must be boolean");
1929 Py_ssize_t data_length;
1930 if (PyObject_AsReadBuffer(arg, &
data, &data_length) < 0) {
1937 reinterpret_cast<const uint8*
>(
data), data_length);
1939 input.SetTotalBytesLimit(INT_MAX, INT_MAX);
1940 input.SetRecursionLimit(INT_MAX);
1944 bool success =
self->message->MergePartialFromCodedStream(&
input);
1952 if (!
input.ConsumedEntireMessage()) {
1955 PyErr_Warn(
NULL,
"Unexpected end-group tag: Not all data was converted");
1957 return PyInt_FromLong(
input.CurrentPosition());
1972 return PyLong_FromLong(
self->message->ByteSize());
1982 PyErr_Format(PyExc_TypeError,
"Expected a message class, got %s",
1983 cls->ob_type->tp_name);
1992 message_class->py_message_factory->pool->pool->FindExtensionByNumber(
1994 if (existing_extension !=
NULL && existing_extension !=
descriptor) {
1995 PyErr_SetString(PyExc_ValueError,
"Double registration of Extensions");
2007 Py_ssize_t name_size;
2009 if (PyString_AsStringAndSize(arg, &name_data, &name_size) < 0)
2013 self->message->GetDescriptor()->FindOneofByName(
oneof_name);
2014 if (oneof_desc ==
NULL) {
2015 PyErr_Format(PyExc_ValueError,
2016 "Protocol message has no oneof \"%s\" field.",
2021 self->message->GetReflection()->GetOneofFieldDescriptor(
2022 *
self->message, oneof_desc);
2023 if (field_in_oneof ==
NULL) {
2026 const string&
name = field_in_oneof->
name();
2027 return PyString_FromStringAndSize(
name.c_str(),
name.size());
2034 std::vector<const FieldDescriptor*>
fields;
2035 self->message->GetReflection()->ListFields(*
self->message, &
fields);
2039 if (all_fields ==
NULL) {
2046 Py_ssize_t actual_size = 0;
2047 for (
size_t i = 0;
i <
fields.size(); ++
i) {
2053 if (
fields[
i]->is_extension()) {
2056 if (extension_field ==
NULL) {
2071 if (extensions ==
NULL) {
2076 extensions.
get(), extension_field.
get());
2080 PyTuple_SET_ITEM(t.
get(), 0, extension_field.
release());
2087 if (field_descriptor ==
NULL) {
2092 if (field_value ==
NULL) {
2093 PyErr_SetString(PyExc_ValueError,
fields[
i]->
name().c_str());
2096 PyTuple_SET_ITEM(t.
get(), 0, field_descriptor.
release());
2097 PyTuple_SET_ITEM(t.
get(), 1, field_value);
2099 PyList_SET_ITEM(all_fields.
get(), actual_size, t.
release());
2102 if (
static_cast<size_t>(actual_size) !=
fields.size() &&
2103 (PyList_SetSlice(all_fields.
get(), actual_size,
fields.size(),
NULL) <
2112 self->message->DiscardUnknownFields();
2118 std::vector<string>
errors;
2121 PyObject* error_list = PyList_New(
errors.size());
2122 if (error_list ==
NULL) {
2125 for (
size_t i = 0;
i <
errors.size(); ++
i) {
2127 PyObject* error_string = PyString_FromStringAndSize(
2129 if (error_string ==
NULL) {
2130 Py_DECREF(error_list);
2133 PyList_SET_ITEM(error_list,
i, error_string);
2140 if (opid != Py_EQ && opid != Py_NE) {
2141 Py_INCREF(Py_NotImplemented);
2142 return Py_NotImplemented;
2163 if (equals ^ (opid == Py_EQ)) {
2178 PyObject* result =
NULL;
2179 switch (field_descriptor->
cpp_type()) {
2182 result = PyInt_FromLong(
value);
2187 result = PyLong_FromLongLong(
value);
2192 result = PyInt_FromSize_t(
value);
2197 result = PyLong_FromUnsignedLongLong(
value);
2202 result = PyFloat_FromDouble(
value);
2207 result = PyFloat_FromDouble(
value);
2212 result = PyBool_FromLong(
value);
2217 const string&
value =
2225 result = PyInt_FromLong(enum_value->
number());
2230 PyExc_SystemError,
"Getting a value from a field of unknown type %d",
2239 const Reflection* reflection =
self->message->GetReflection();
2275 switch (field_descriptor->
cpp_type()) {
2313 arg,
message, field_descriptor, reflection,
false, -1)) {
2326 if (enum_value !=
NULL) {
2329 PyErr_Format(PyExc_ValueError,
"Unknown enum value: %d",
value);
2337 PyExc_SystemError,
"Setting value to a field of unknown type %d",
2361 PyObject* py_cmsg = PyObject_CallObject(
2362 reinterpret_cast<PyObject*
>(cls),
NULL);
2363 if (py_cmsg ==
NULL) {
2369 if (py_length ==
NULL) {
2378 PyObject* clone = PyObject_CallObject(
2379 reinterpret_cast<PyObject*
>(
Py_TYPE(
self)),
NULL);
2380 if (clone ==
NULL) {
2388 reinterpret_cast<CMessage*
>(clone),
2389 reinterpret_cast<PyObject*
>(
self))) ==
NULL) {
2399 PyImport_ImportModule(
"google.protobuf.text_format"));
2400 if (text_format ==
NULL) {
2404 if (method_name ==
NULL) {
2409 text_format.
get(), method_name.
get(),
self, Py_True,
NULL));
2411 if (encoded ==
NULL) {
2414 #if PY_MAJOR_VERSION < 3
2415 PyObject* decoded = PyString_AsDecodedObject(encoded.
get(),
"utf-8",
NULL);
2417 PyObject* decoded = PyUnicode_FromEncodedObject(encoded.
get(),
"utf-8",
NULL);
2419 if (decoded ==
NULL) {
2433 if (state ==
NULL) {
2437 self->message->SerializePartialToString(&contents);
2439 PyBytes_FromStringAndSize(contents.c_str(), contents.size()));
2440 if (serialized ==
NULL) {
2443 if (PyDict_SetItemString(state.
get(),
"serialized", serialized.
get()) < 0) {
2446 return Py_BuildValue(
"OOO", constructor.
get(),
args.get(), state.
get());
2450 if (!PyDict_Check(state)) {
2451 PyErr_SetString(PyExc_TypeError,
"state not a dict");
2454 PyObject* serialized = PyDict_GetItemString(state,
"serialized");
2455 if (serialized ==
NULL) {
2458 #if PY_MAJOR_VERSION >= 3
2461 if (!PyBytes_Check(serialized)) {
2462 serialized = PyUnicode_AsEncodedString(serialized,
"latin1",
NULL);
2473 PyObject* unused_arg) {
2475 PyErr_SetString(PyExc_TypeError,
2476 "Descriptors should not be created directly, "
2477 "but only retrieved from their parent.");
2488 PyErr_SetNone(PyExc_AttributeError);
2491 if (!
self->composite_fields) {
2494 if (!
self->composite_fields) {
2498 return reinterpret_cast<PyObject*
>(extension_dict);
2502 if (
self->unknown_field_set ==
NULL) {
2505 Py_INCREF(
self->unknown_field_set);
2507 return self->unknown_field_set;
2529 {
"__deepcopy__", (PyCFunction)
DeepCopy, METH_VARARGS,
2530 "Makes a deep copy of the class." },
2531 {
"__reduce__", (PyCFunction)
Reduce, METH_NOARGS,
2532 "Outputs picklable representation of the message." },
2533 {
"__setstate__", (PyCFunction)
SetState, METH_O,
2534 "Inputs picklable representation of the message." },
2535 {
"__unicode__", (PyCFunction)
ToUnicode, METH_NOARGS,
2536 "Outputs a unicode representation of the message." },
2537 {
"ByteSize", (PyCFunction)
ByteSize, METH_NOARGS,
2538 "Returns the size of the message in bytes." },
2539 {
"Clear", (PyCFunction)
Clear, METH_NOARGS,
2540 "Clears the message." },
2542 "Clears a message field." },
2543 {
"ClearField", (PyCFunction)
ClearField, METH_O,
2544 "Clears a message field." },
2545 {
"CopyFrom", (PyCFunction)
CopyFrom, METH_O,
2546 "Copies a protocol message into the current message." },
2548 "Discards the unknown fields." },
2551 "Finds unset required fields." },
2552 {
"FromString", (PyCFunction)
FromString, METH_O | METH_CLASS,
2553 "Creates new method instance from given serialized data." },
2555 "Checks if a message field is set." },
2556 {
"HasField", (PyCFunction)
HasField, METH_O,
2557 "Checks if a message field is set." },
2558 {
"IsInitialized", (PyCFunction)
IsInitialized, METH_VARARGS,
2559 "Checks if all required fields of a protocol message are set." },
2560 {
"ListFields", (PyCFunction)
ListFields, METH_NOARGS,
2561 "Lists all set fields of a message." },
2562 {
"MergeFrom", (PyCFunction)
MergeFrom, METH_O,
2563 "Merges a protocol message into the current message." },
2565 "Merges a serialized message into the current message." },
2567 "Parses a serialized message into the current message." },
2569 "Registers an extension with the current message." },
2571 METH_VARARGS | METH_KEYWORDS,
2572 "Serializes the message to a string, even if it isn't initialized." },
2574 METH_VARARGS | METH_KEYWORDS,
2575 "Serializes the message to a string, only for initialized messages." },
2576 {
"SetInParent", (PyCFunction)
SetInParent, METH_NOARGS,
2577 "Sets the has bit of the given field in its parent message." },
2579 "Parse unknown field set"},
2580 {
"WhichOneof", (PyCFunction)
WhichOneof, METH_O,
2581 "Returns the name of the field set inside a oneof, "
2582 "or None if no field is set." },
2586 METH_NOARGS | METH_STATIC,
2587 "Raises TypeError if the caller is not in a _pb2.py file."},
2593 if (
self->composite_fields ==
NULL) {
2601 if (
self->child_submessages ==
NULL) {
2604 (*
self->child_submessages)[submessage->
message] = submessage;
2610 PyObject* result = PyObject_GenericGetAttr(
2611 reinterpret_cast<PyObject*
>(
self),
name);
2612 if (result !=
NULL) {
2615 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
2626 if (
self->composite_fields) {
2627 CMessage::CompositeFieldsMap::iterator
it =
2628 self->composite_fields->find(field_descriptor);
2629 if (
it !=
self->composite_fields->end()) {
2632 return value->AsPyObject();
2637 PyErr_Format(PyExc_TypeError,
2638 "descriptor to field '%s' doesn't apply to '%s' object",
2650 if (field_descriptor->
is_map()) {
2656 if (value_class ==
NULL) {
2677 }
else if (field_descriptor->
cpp_type() ==
2681 PyErr_SetString(PyExc_SystemError,
"Should never happen");
2684 if (py_container ==
NULL) {
2688 Py_DECREF(py_container);
2697 PyErr_Format(PyExc_TypeError,
2698 "descriptor to field '%s' doesn't apply to '%s' object",
2703 PyErr_Format(PyExc_AttributeError,
2704 "Assignment not allowed to repeated "
2705 "field \"%s\" in protocol message object.",
2706 field_descriptor->
name().c_str());
2709 PyErr_Format(PyExc_AttributeError,
2710 "Assignment not allowed to "
2711 "field \"%s\" in protocol message object.",
2712 field_descriptor->
name().c_str());
2734 {this->parent_field_descriptor});
2739 Py_DECREF(new_parent);
2787 Py_CLEAR(released->
parent);
2809 PyObject_HashNotImplemented,
2815 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
2816 | Py_TPFLAGS_HAVE_VERSION_TAG,
2817 "A ProtocolMessage",
2840 const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg);
2841 Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg);
2863 PyErr_SetString(PyExc_TypeError,
"Not a Message instance");
2872 PyErr_SetString(PyExc_TypeError,
"Not a Message instance");
2884 PyErr_SetString(PyExc_ValueError,
2885 "Cannot reliably get a mutable pointer "
2886 "to a message with extra references");
2894 PyObject* message_factory) {
2895 if (message_factory) {
2896 PyErr_SetString(PyExc_NotImplementedError,
2897 "Default message_factory=NULL is the only supported value");
2900 if (
message->GetReflection()->GetMessageFactory() !=
2902 PyErr_SetString(PyExc_TypeError,
2903 "Message pointer was not created from the default factory");
2917 self->parent =
reinterpret_cast<CMessage*
>(Py_None);
2927 PyObject *dummy_obj = PySet_New(
NULL);
2929 Py_DECREF(dummy_obj);
2955 PyModule_AddObject(
m,
"MessageMeta",
2973 PyModule_AddObject(
m,
"Message",
reinterpret_cast<PyObject*
>(
CMessage_Type));
2981 PyModule_AddObject(
m,
"RepeatedScalarContainer",
2982 reinterpret_cast<PyObject*
>(
2990 m,
"RepeatedCompositeContainer",
2991 reinterpret_cast<PyObject*
>(
2996 if (collections ==
NULL) {
3000 PyObject_GetAttrString(collections.
get(),
"MutableSequence"));
3001 if (mutable_sequence ==
NULL) {
3005 PyObject_CallMethod(mutable_sequence.
get(),
"register",
"O",
3010 PyObject_CallMethod(mutable_sequence.
get(),
"register",
"O",
3020 PyModule_AddObject(
m,
"UnknownFieldSet",
3021 reinterpret_cast<PyObject*
>(
3028 PyModule_AddObject(
m,
"UnknownField",
3029 reinterpret_cast<PyObject*
>(
3036 PyModule_AddObject(
m,
"ScalarMapContainer",
3038 PyModule_AddObject(
m,
"MessageMapContainer",
3040 PyModule_AddObject(
m,
"MapIterator",
3052 PyModule_AddObject(
m,
"ExtensionIterator",
3059 PyModule_AddObject(
m,
"default_pool",
3062 PyModule_AddObject(
m,
"DescriptorPool",
reinterpret_cast<PyObject*
>(
3067 PyModule_AddIntConstant(
m,
"_USE_C_DESCRIPTORS", 1);
3069 PyModule_AddObject(
m,
"Descriptor",
reinterpret_cast<PyObject*
>(
3071 PyModule_AddObject(
m,
"FieldDescriptor",
reinterpret_cast<PyObject*
>(
3073 PyModule_AddObject(
m,
"EnumDescriptor",
reinterpret_cast<PyObject*
>(
3075 PyModule_AddObject(
m,
"EnumValueDescriptor",
reinterpret_cast<PyObject*
>(
3077 PyModule_AddObject(
m,
"FileDescriptor",
reinterpret_cast<PyObject*
>(
3079 PyModule_AddObject(
m,
"OneofDescriptor",
reinterpret_cast<PyObject*
>(
3081 PyModule_AddObject(
m,
"ServiceDescriptor",
reinterpret_cast<PyObject*
>(
3083 PyModule_AddObject(
m,
"MethodDescriptor",
reinterpret_cast<PyObject*
>(
3086 PyObject* enum_type_wrapper = PyImport_ImportModule(
3087 "google.protobuf.internal.enum_type_wrapper");
3088 if (enum_type_wrapper ==
NULL) {
3092 PyObject_GetAttrString(enum_type_wrapper,
"EnumTypeWrapper");
3093 Py_DECREF(enum_type_wrapper);
3095 PyObject* message_module = PyImport_ImportModule(
3096 "google.protobuf.message");
3097 if (message_module ==
NULL) {
3103 Py_DECREF(message_module);
3105 PyObject* pickle_module = PyImport_ImportModule(
"pickle");
3106 if (pickle_module ==
NULL) {
3110 Py_DECREF(pickle_module);