34 #include <google/protobuf/pyext/message.h>
36 #include <structmember.h>
44 #include <google/protobuf/stubs/strutil.h>
46 #ifndef PyVarObject_HEAD_INIT
47 #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
50 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
52 #include <google/protobuf/stubs/common.h>
53 #include <google/protobuf/stubs/logging.h>
54 #include <google/protobuf/io/coded_stream.h>
55 #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
56 #include <google/protobuf/descriptor.pb.h>
57 #include <google/protobuf/descriptor.h>
58 #include <google/protobuf/message.h>
59 #include <google/protobuf/text_format.h>
60 #include <google/protobuf/unknown_field_set.h>
61 #include <google/protobuf/pyext/descriptor.h>
62 #include <google/protobuf/pyext/descriptor_pool.h>
63 #include <google/protobuf/pyext/extension_dict.h>
64 #include <google/protobuf/pyext/field.h>
65 #include <google/protobuf/pyext/map_container.h>
66 #include <google/protobuf/pyext/message_factory.h>
67 #include <google/protobuf/pyext/repeated_composite_container.h>
68 #include <google/protobuf/pyext/repeated_scalar_container.h>
69 #include <google/protobuf/pyext/safe_numerics.h>
70 #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
71 #include <google/protobuf/pyext/unknown_fields.h>
72 #include <google/protobuf/util/message_differencer.h>
73 #include <google/protobuf/io/strtod.h>
74 #include <google/protobuf/stubs/map_util.h>
77 #include <google/protobuf/port_def.inc>
80 #define PyString_AsString(ob) \
81 (PyUnicode_Check(ob) ? PyUnicode_AsUTF8(ob) : PyBytes_AsString(ob))
82 #define PyString_AsStringAndSize(ob, charpp, sizep) \
83 (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
84 PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
87 : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
97 const std::vector<const FieldDescriptor*>&
fields) {
113 namespace message_meta {
121 if (
'A' <= *
i && *
i <=
'Z') *
i +=
'a' -
'A';
132 if (property == NULL) {
135 if (PyObject_SetAttrString(cls, field_descriptor->
name().c_str(),
136 property.
get()) < 0) {
155 if (PyObject_SetAttrString(
165 PyLong_FromLong(enum_value_descriptor->
number()));
166 if (value_number == NULL) {
169 if (PyObject_SetAttrString(cls, enum_value_descriptor->
name().c_str(),
170 value_number.
get()) == -1) {
184 if (extension_field == NULL) {
189 if (PyObject_SetAttrString(
190 cls,
field->name().c_str(), extension_field.
get()) == -1) {
198 static PyObject*
New(PyTypeObject*
type, PyObject*
args, PyObject* kwargs) {
199 static const char* kwlist[] = {
"name",
"bases",
"dict", 0};
200 PyObject *bases, *dict;
204 if (!PyArg_ParseTupleAndKeywords(
205 args, kwargs,
"sO!O!:type",
const_cast<char**
>(kwlist), &
name,
206 &PyTuple_Type, &bases, &PyDict_Type, &dict)) {
211 if (!(PyTuple_GET_SIZE(bases) == 0 ||
212 (PyTuple_GET_SIZE(bases) == 1 &&
214 PyErr_SetString(PyExc_TypeError,
215 "A Message class can only inherit from Message");
220 PyObject* py_descriptor = PyDict_GetItem(dict,
kDESCRIPTOR);
221 if (py_descriptor ==
nullptr) {
222 PyErr_SetString(PyExc_TypeError,
"Message class has no DESCRIPTOR");
226 PyErr_Format(PyExc_TypeError,
"Expected a message Descriptor, got %s",
227 py_descriptor->ob_type->tp_name);
232 if (message_descriptor ==
nullptr) {
238 if (PyDict_SetItemString(dict,
"__slots__", slots.
get()) < 0) {
248 "google.protobuf.internal.well_known_types"));
251 WKT_classes = PyObject_GetAttrString(well_known_types.
get(),
"WKTBASES");
255 PyObject* well_known_class = PyDict_GetItemString(
257 if (well_known_class == NULL) {
265 if (new_args == NULL) {
281 Py_INCREF(py_descriptor);
288 if (py_descriptor_pool == NULL) {
311 Py_XDECREF(
self->py_message_descriptor);
312 Py_XDECREF(
self->py_message_factory);
313 return PyType_Type.tp_dealloc(pself);
318 Py_VISIT(
self->py_message_descriptor);
319 Py_VISIT(
self->py_message_factory);
320 return PyType_Type.tp_traverse(pself,
visit,
arg);
326 return PyType_Type.tp_clear(pself);
332 if (
self->message_descriptor == NULL) {
334 PyErr_SetString(PyExc_AttributeError,
335 "Base Message class has no DESCRIPTOR");
341 std::vector<const FieldDescriptor*>
extensions;
362 if (
self->message_descriptor == NULL) {
364 PyErr_SetString(PyExc_AttributeError,
365 "Base Message class has no DESCRIPTOR");
371 std::vector<const FieldDescriptor*>
extensions;
403 Py_ssize_t attr_size;
404 static const char kSuffix[] =
"_FIELD_NUMBER";
412 self->message_descriptor->FindFieldByLowercaseName(field_name);
416 self->message_descriptor->FindExtensionByLowercaseName(field_name);
419 return PyLong_FromLong(
field->number());
422 PyErr_SetObject(PyExc_AttributeError,
name);
428 reinterpret_cast<PyObject*
>(
self),
name);
432 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
448 #ifdef PROTOBUF_PYTHON_ALLOW_OVERSIZE_PROTOS
474 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
475 "The metaclass of ProtocolMessages",
498 PyErr_Format(PyExc_TypeError,
"Class %s is not a Message", cls->tp_name);
509 return type->message_descriptor;
531 PyObject* repr = PyObject_Repr(
arg);
533 PyErr_Format(PyExc_TypeError,
534 "%.100s has type %.100s, but expected one of: %s",
543 PyObject *s = PyObject_Str(
arg);
545 PyErr_Format(PyExc_ValueError,
546 "Value out of range: %s",
552 template<
class RangeType,
class ValueType>
554 if (PROTOBUF_PREDICT_FALSE(
value == -1 && PyErr_Occurred())) {
555 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
563 if (PROTOBUF_PREDICT_FALSE(!IsValidNumericCast<RangeType>(
value))) {
576 if (PROTOBUF_PREDICT_FALSE(!PyIndex_Check(
arg))) {
586 unsigned PY_LONG_LONG ulong_result;
587 if (PyLong_Check(
arg)) {
588 ulong_result = PyLong_AsUnsignedLongLong(
arg);
592 PyObject* casted = PyNumber_Long(
arg);
593 if (PROTOBUF_PREDICT_FALSE(casted ==
nullptr)) {
597 ulong_result = PyLong_AsUnsignedLongLong(casted);
600 if (VerifyIntegerCastAndRange<T, unsigned PY_LONG_LONG>(
arg,
602 *
value =
static_cast<T>(ulong_result);
608 PY_LONG_LONG long_result;
610 if ((nb =
arg->ob_type->tp_as_number) != NULL && nb->nb_int != NULL) {
613 long_result = PyLong_AsLongLong(
arg);
617 PyObject* casted = PyNumber_Long(
arg);
618 if (PROTOBUF_PREDICT_FALSE(casted ==
nullptr)) {
622 long_result = PyLong_AsLongLong(casted);
625 if (VerifyIntegerCastAndRange<T, PY_LONG_LONG>(
arg, long_result)) {
626 *
value =
static_cast<T>(long_result);
644 if (PROTOBUF_PREDICT_FALSE(*
value == -1 && PyErr_Occurred())) {
661 long long_value = PyLong_AsLong(
arg);
662 if (long_value == -1 && PyErr_Occurred()) {
666 *
value =
static_cast<bool>(long_value);
674 if (PyBytes_Check(
obj)) {
675 PyObject*
unicode = PyUnicode_FromEncodedObject(
obj,
"utf-8", NULL);
698 if (!PyBytes_Check(
arg) && !PyUnicode_Check(
arg)) {
704 PyObject* repr = PyObject_Repr(
arg);
705 PyErr_Format(PyExc_ValueError,
706 "%s has type str, but isn't valid UTF-8 "
707 "encoding. Non-UTF-8 strings must be converted to "
708 "unicode objects before being added.",
713 }
else if (!PyBytes_Check(
arg)) {
718 PyObject* encoded_string = NULL;
720 if (PyBytes_Check(
arg)) {
722 encoded_string =
arg;
723 Py_INCREF(encoded_string);
725 encoded_string = PyUnicode_AsEncodedString(
arg,
"utf-8", NULL);
729 encoded_string =
arg;
730 Py_INCREF(encoded_string);
733 return encoded_string;
739 const Reflection* reflection,
744 if (encoded_string.get() == NULL) {
749 Py_ssize_t value_len;
750 if (PyBytes_AsStringAndSize(encoded_string.get(), &
value, &value_len) < 0) {
757 }
else if (
index < 0) {
769 return PyBytes_FromStringAndSize(
value.c_str(),
value.length());
772 PyObject*
result = PyUnicode_DecodeUTF8(
value.c_str(),
value.length(), NULL);
789 PyErr_Format(PyExc_KeyError,
"Field '%s' does not belong to message '%s'",
791 message->GetDescriptor()->full_name().c_str());
799 return reinterpret_cast<CMessageClass*
>(
Py_TYPE(
message))->py_message_factory;
805 #ifdef GOOGLE_PROTOBUF_HAS_ONEOF
808 if (!
field->containing_oneof() ||
832 if (!
self->composite_fields) {
836 for (
const auto& item : *
self->composite_fields) {
841 if (cmsg->read_only ==
false) {
845 const Reflection* reflection =
message->GetReflection();
849 Message* mutable_message = reflection->MutableMessage(
851 cmsg->message = mutable_message;
852 cmsg->read_only =
false;
867 if (
self == NULL || !
self->read_only) {
880 self->parent_field_descriptor) < 0) {
885 Message* parent_message =
self->parent->message;
886 const Reflection* reflection = parent_message->GetReflection();
887 Message* mutable_message = reflection->MutableMessage(
888 parent_message,
self->parent_field_descriptor,
890 if (mutable_message == NULL) {
893 self->message = mutable_message;
894 self->read_only =
false;
908 PyErr_SetObject(PyExc_KeyError,
extension);
918 if (PyUnicode_Check(
value)) {
921 PyErr_SetString(PyExc_TypeError,
"not an enum field");
931 if (enum_value_descriptor == NULL) {
932 PyErr_Format(PyExc_ValueError,
"unknown enum label \"%s\"", enum_label);
935 return PyLong_FromLong(enum_value_descriptor->
number());
955 if (PySlice_Check(
slice)) {
967 if (
from == -1 && PyErr_Occurred()) {
968 PyErr_SetString(PyExc_TypeError,
"list indices must be integers");
979 if (from < 0 || from >=
length) {
980 PyErr_Format(PyExc_IndexError,
"list assignment index out of range");
986 std::vector<bool> to_delete(
length,
false);
987 while (i >=
min && i <=
max) {
1005 <<
"python protobuf is expected to be allocated from heap";
1028 if (
CMessage* released =
self->MaybeReleaseSubMessage(sub_message)) {
1029 released->message = sub_message;
1041 if (
args != NULL && PyTuple_Size(
args) != 0) {
1042 PyErr_SetString(PyExc_TypeError,
"No positional arguments allowed");
1046 if (kwargs == NULL) {
1054 if (!(PyUnicode_Check(
name))) {
1055 PyErr_SetString(PyExc_ValueError,
"Field name must be a string");
1059 PyObject_GetAttr(
reinterpret_cast<PyObject*
>(
Py_TYPE(
self)),
name));
1060 if (property == NULL ||
1062 PyErr_Format(PyExc_ValueError,
"Protocol message %s has no \"%s\" field.",
1063 self->message->GetDescriptor()->name().c_str(),
1068 reinterpret_cast<PyMessageFieldProperty*
>(property.get())
1070 if (
value == Py_None) {
1077 descriptor->message_type()->FindFieldByName(
"value");
1085 while ((
next.reset(PyIter_Next(
iter.get()))) != NULL) {
1088 if (source_value.get() == NULL || dest_value.get() == NULL) {
1092 dest_value.get(),
"MergeFrom",
"O", source_value.get()));
1093 if (
ok.get() == NULL) {
1099 function_return.reset(
1100 PyObject_CallMethod(
map.get(),
"update",
"O",
value));
1101 if (function_return.get() == NULL) {
1115 PyErr_SetString(PyExc_TypeError,
"Value must be iterable");
1119 while ((
next.reset(PyIter_Next(
iter.get()))) != NULL) {
1120 PyObject* kwargs = (PyDict_Check(
next.get()) ?
next.get() : NULL);
1123 if (new_msg == NULL) {
1126 if (kwargs == NULL) {
1129 reinterpret_cast<CMessage*
>(new_msg.get()),
next.get()));
1130 if (merged.get() == NULL) {
1135 if (PyErr_Occurred()) {
1144 PyErr_SetString(PyExc_TypeError,
"Value must be iterable");
1148 while ((
next.reset(PyIter_Next(
iter.get()))) != NULL) {
1151 if (enum_value == NULL) {
1155 rs_container, enum_value.get()));
1156 if (new_msg == NULL) {
1160 if (PyErr_Occurred()) {
1178 if (PyDict_Check(
value)) {
1186 if (merged == NULL) {
1194 if (new_val == NULL) {
1197 value = new_val.get();
1211 PyType_GenericAlloc(&
type->super.ht_type, 0));
1217 self->parent = NULL;
1218 self->parent_field_descriptor = NULL;
1219 self->read_only =
false;
1221 self->composite_fields = NULL;
1222 self->child_submessages = NULL;
1224 self->unknown_field_set = NULL;
1234 if (message_descriptor ==
nullptr) {
1237 PyErr_Format(PyExc_TypeError,
1238 "CMessageClass object '%s' has no descriptor.",
1243 type->py_message_factory->message_factory->GetPrototype(
1244 message_descriptor);
1245 if (prototype ==
nullptr) {
1246 PyErr_SetString(PyExc_TypeError, message_descriptor->
full_name().c_str());
1251 if (
self ==
nullptr) {
1254 self->message = prototype->
New(
nullptr);
1255 self->parent =
nullptr;
1259 static PyObject*
New(PyTypeObject* cls, PyObject* unused_args,
1260 PyObject* unused_kwargs) {
1262 if (
type ==
nullptr) {
1278 if (
self->weakreflist) {
1279 PyObject_ClearWeakRefs(
reinterpret_cast<PyObject*
>(
self));
1284 delete self->child_submessages;
1285 delete self->composite_fields;
1286 if (
self->unknown_field_set) {
1295 }
else if (parent->
AsPyObject() == Py_None) {
1297 Py_CLEAR(
self->parent);
1300 if (
self->parent_field_descriptor->is_repeated()) {
1307 Py_CLEAR(
self->parent);
1309 Py_TYPE(
self)->tp_free(
reinterpret_cast<PyObject*
>(
self));
1317 if (!PyArg_ParseTuple(
args,
"|O", &
errors)) {
1320 if (
self->message->IsInitialized()) {
1326 if (initialization_errors == NULL) {
1330 if (extend_name == NULL) {
1336 initialization_errors.get(),
1352 PyErr_SetString(PyExc_KeyError,
1353 "Field is repeated. A singular method is required.");
1356 return message->GetReflection()->HasField(*
message, field_descriptor);
1366 if (field_descriptor != NULL) {
1367 return field_descriptor;
1371 if (oneof_desc != NULL) {
1373 return message->GetReflection()->GetOneofFieldDescriptor(*
message,
1382 PyErr_Format(PyExc_ValueError,
1383 "Protocol message %s has no singular \"%s\" field.",
1384 message_name.c_str(), field_descriptor->
name().c_str());
1389 PyErr_Format(PyExc_ValueError,
1390 "Can't test non-optional, non-submessage field \"%s.%s\" for "
1391 "presence in proto3.",
1392 message_name.c_str(), field_descriptor->
name().c_str());
1402 field_name =
const_cast<char*
>(PyUnicode_AsUTF8AndSize(
arg, &
size));
1411 if (field_descriptor == NULL) {
1413 PyErr_Format(PyExc_ValueError,
"Protocol message %s has no field %s.",
1414 message->GetDescriptor()->name().c_str(), field_name);
1425 if (
message->GetReflection()->HasField(*
message, field_descriptor)) {
1449 if (has_field < 0) {
1452 return PyBool_FromLong(has_field);
1482 CMessage*
self,
const std::vector<CMessage*>& messages_to_release,
1483 const std::vector<ContainerBase*>& containers_to_release) {
1484 if (messages_to_release.empty() && containers_to_release.empty()) {
1490 if (new_message ==
nullptr) {
1493 new_message->
message =
self->message->
New(
nullptr);
1497 std::set<const FieldDescriptor*> fields_to_swap;
1503 for (
const auto& to_release : messages_to_release) {
1504 fields_to_swap.insert(to_release->parent_field_descriptor);
1506 Py_INCREF(new_message);
1507 Py_DECREF(to_release->parent);
1508 to_release->parent = new_message;
1513 for (
const auto& to_release : containers_to_release) {
1514 fields_to_swap.insert(to_release->parent_field_descriptor);
1515 Py_INCREF(new_message);
1516 Py_DECREF(to_release->parent);
1517 to_release->parent = new_message;
1519 new_message->
composite_fields->emplace(to_release->parent_field_descriptor,
1526 std::vector<const FieldDescriptor*>(fields_to_swap.begin(),
1527 fields_to_swap.end()));
1529 self->message->GetReflection()->SwapFields(
1531 std::vector<const FieldDescriptor*>(fields_to_swap.begin(),
1532 fields_to_swap.end()));
1549 std::vector<CMessage*> messages_to_release;
1550 std::vector<ContainerBase*> containers_to_release;
1553 for (
const auto& child_item : *
self->child_submessages) {
1554 if (child_item.second->parent_field_descriptor == field_descriptor) {
1555 messages_to_release.push_back(child_item.second);
1559 if (
self->composite_fields) {
1561 self->composite_fields->find(field_descriptor);
1562 if (
it !=
self->composite_fields->end()) {
1563 containers_to_release.push_back(
it->second);
1568 containers_to_release);
1587 Py_ssize_t field_size;
1595 if (field_descriptor == NULL) {
1600 PyErr_Format(PyExc_ValueError,
1601 "Protocol message has no \"%s\" field.", field_name);
1615 std::vector<CMessage*> messages_to_release;
1616 std::vector<ContainerBase*> containers_to_release;
1617 if (
self->child_submessages) {
1618 for (
const auto& item : *
self->child_submessages) {
1619 messages_to_release.push_back(item.second);
1622 if (
self->composite_fields) {
1623 for (
const auto& item : *
self->composite_fields) {
1624 containers_to_release.push_back(item.second);
1631 if (
self->unknown_field_set) {
1634 self->unknown_field_set =
nullptr;
1636 self->message->Clear();
1643 if (
self->parent_field_descriptor != NULL) {
1644 return self->parent_field_descriptor->full_name();
1646 return self->message->GetDescriptor()->full_name();
1652 bool require_initialized) {
1654 static const char* kwlist[] = {
"deterministic", 0};
1655 PyObject* deterministic_obj = Py_None;
1656 if (!PyArg_ParseTupleAndKeywords(
1657 args, kwargs,
"|O",
const_cast<char**
>(kwlist), &deterministic_obj)) {
1663 int deterministic = PyObject_IsTrue(deterministic_obj);
1664 if (deterministic < 0) {
1668 if (require_initialized && !
self->message->IsInitialized()) {
1674 if (comma == NULL) {
1678 PyObject_CallMethod(comma.
get(),
"join",
"O",
errors.get()));
1679 if (joined == NULL) {
1691 "google.protobuf.message"));
1692 if (message_module.
get() == NULL) {
1697 PyObject_GetAttrString(message_module.
get(),
"EncodeError"));
1698 if (encode_error.
get() == NULL) {
1701 PyErr_Format(encode_error.
get(),
1702 "Message %s is missing required fields: %s",
1708 const size_t size =
self->message->ByteSizeLong();
1710 return PyBytes_FromString(
"");
1713 if (
size > INT_MAX) {
1714 PyErr_Format(PyExc_ValueError,
1715 "Message %s exceeds maximum protobuf "
1721 PyObject*
result = PyBytes_FromStringAndSize(NULL,
size);
1727 if (deterministic_obj != Py_None) {
1730 self->message->SerializeWithCachedSizes(&coded_out);
1763 PrintDouble(val, generator);
1776 if (!py_value.
get()) {
1781 if (!py_str.
get()) {
1796 PyErr_SetString(PyExc_ValueError,
"Unable to convert message to str");
1799 return PyUnicode_FromString(
output.c_str());
1805 PyErr_Format(PyExc_TypeError,
1806 "Parameter to MergeFrom() must be instance of same class: "
1807 "expected %s got %s.",
1808 self->message->GetDescriptor()->full_name().c_str(),
1815 self->message->GetDescriptor()) {
1816 PyErr_Format(PyExc_TypeError,
1817 "Parameter to MergeFrom() must be instance of same class: "
1818 "expected %s got %s.",
1819 self->message->GetDescriptor()->full_name().c_str(),
1825 self->message->MergeFrom(*other_message->
message);
1838 PyErr_Format(PyExc_TypeError,
1839 "Parameter to CopyFrom() must be instance of same class: "
1840 "expected %s got %s.",
1841 self->message->GetDescriptor()->full_name().c_str(),
1848 if (
self == other_message) {
1853 self->message->GetDescriptor()) {
1854 PyErr_Format(PyExc_TypeError,
1855 "Parameter to CopyFrom() must be instance of same class: "
1856 "expected %s got %s.",
1857 self->message->GetDescriptor()->full_name().c_str(),
1868 self->message->CopyFrom(*other_message->
message);
1876 if (!
arg || !PyBool_Check(
arg)) {
1877 PyErr_SetString(PyExc_TypeError,
1878 "Argument to SetAllowOversizeProtos must be boolean");
1891 if (PyObject_GetBuffer(
arg, &
data, PyBUF_SIMPLE) < 0) {
1905 PyBuffer_Release(&
data);
1909 ptr =
self->message->_InternalParse(
ptr, &
ctx);
1920 if (
ptr ==
nullptr ||
ctx.BytesUntilLimit(
ptr) < 0) {
1924 self->GetMessageClass()->message_descriptor->full_name().c_str());
1929 if (!
ctx.EndedAtLimit()) {
1932 PyErr_Warn(
nullptr,
"Unexpected end-group tag: Not all data was converted");
1933 return PyLong_FromLong(
data.len -
ctx.BytesUntilLimit(
ptr));
1935 return PyLong_FromLong(
data.len);
1946 return PyLong_FromLong(
self->message->ByteSizeLong());
1956 PyErr_Format(PyExc_TypeError,
"Expected a message class, got %s",
1957 cls->ob_type->tp_name);
1960 CMessageClass *message_class =
reinterpret_cast<CMessageClass*
>(cls);
1961 if (message_class == NULL) {
1966 message_class->py_message_factory->pool->pool->FindExtensionByNumber(
1968 if (existing_extension != NULL && existing_extension !=
descriptor) {
1969 PyErr_SetString(PyExc_ValueError,
"Double registration of Extensions");
1981 Py_ssize_t name_size;
1986 self->message->GetDescriptor()->FindOneofByName(
1988 if (oneof_desc == NULL) {
1989 PyErr_Format(PyExc_ValueError,
1990 "Protocol message has no oneof \"%s\" field.", name_data);
1994 self->message->GetReflection()->GetOneofFieldDescriptor(
1995 *
self->message, oneof_desc);
1996 if (field_in_oneof == NULL) {
2000 return PyUnicode_FromStringAndSize(
name.c_str(),
name.size());
2007 std::vector<const FieldDescriptor*>
fields;
2008 self->message->GetReflection()->ListFields(*
self->message, &
fields);
2012 if (all_fields == NULL) {
2019 Py_ssize_t actual_size = 0;
2020 for (
size_t i = 0;
i <
fields.size(); ++
i) {
2026 if (
fields[
i]->is_extension()) {
2029 if (extension_field == NULL) {
2053 PyTuple_SET_ITEM(t.get(), 0, extension_field.
release());
2055 PyTuple_SET_ITEM(t.get(), 1,
extension);
2060 if (field_descriptor == NULL) {
2065 if (field_value == NULL) {
2069 PyTuple_SET_ITEM(t.get(), 0, field_descriptor.
release());
2070 PyTuple_SET_ITEM(t.get(), 1, field_value);
2072 PyList_SET_ITEM(all_fields.
get(), actual_size, t.release());
2075 if (
static_cast<size_t>(actual_size) !=
fields.size() &&
2076 (PyList_SetSlice(all_fields.
get(), actual_size,
fields.size(), NULL) <
2085 self->message->DiscardUnknownFields();
2091 std::vector<std::string>
errors;
2094 PyObject* error_list = PyList_New(
errors.size());
2095 if (error_list == NULL) {
2098 for (
size_t i = 0;
i <
errors.size(); ++
i) {
2100 PyObject* error_string =
2101 PyUnicode_FromStringAndSize(
error.c_str(),
error.length());
2102 if (error_string == NULL) {
2103 Py_DECREF(error_list);
2106 PyList_SET_ITEM(error_list, i, error_string);
2113 if (opid != Py_EQ && opid != Py_NE) {
2114 Py_INCREF(Py_NotImplemented);
2115 return Py_NotImplemented;
2138 if (equals ^ (opid == Py_EQ)) {
2154 switch (field_descriptor->
cpp_type()) {
2205 PyExc_SystemError,
"Getting a value from a field of unknown type %d",
2214 const Reflection* reflection =
self->message->GetReflection();
2218 factory, field_descriptor->message_type());
2220 reinterpret_cast<PyObject*
>(message_class));
2221 if (message_class == NULL) {
2231 cmsg->parent =
self;
2232 cmsg->parent_field_descriptor = field_descriptor;
2233 if (reflection->HasField(*
self->message, field_descriptor)) {
2236 field_descriptor)) {
2237 Message* sub_message = reflection->MutableMessage(
2238 self->message, field_descriptor, factory->message_factory);
2239 cmsg->read_only =
false;
2240 cmsg->message = sub_message;
2244 cmsg->read_only =
true;
2246 const Message& sub_message = reflection->GetMessage(
2247 *
self->message, field_descriptor, factory->message_factory);
2248 cmsg->message =
const_cast<Message*
>(&sub_message);
2256 const Reflection* reflection =
message->GetReflection();
2262 switch (field_descriptor->cpp_type()) {
2265 reflection->SetInt32(
message, field_descriptor,
value);
2270 reflection->SetInt64(
message, field_descriptor,
value);
2275 reflection->SetUInt32(
message, field_descriptor,
value);
2280 reflection->SetUInt64(
message, field_descriptor,
value);
2285 reflection->SetFloat(
message, field_descriptor,
value);
2290 reflection->SetDouble(
message, field_descriptor,
value);
2300 arg,
message, field_descriptor, reflection,
false, -1)) {
2307 if (reflection->SupportsUnknownEnumValues()) {
2308 reflection->SetEnumValue(
message, field_descriptor,
value);
2313 if (enum_value != NULL) {
2314 reflection->SetEnum(
message, field_descriptor, enum_value);
2316 PyErr_Format(PyExc_ValueError,
"Unknown enum value: %d",
value);
2324 PyExc_SystemError,
"Setting value to a field of unknown type %d",
2325 field_descriptor->cpp_type());
2347 PyObject*
FromString(PyTypeObject* cls, PyObject* serialized) {
2348 PyObject* py_cmsg = PyObject_CallObject(
2349 reinterpret_cast<PyObject*
>(cls), NULL);
2350 if (py_cmsg == NULL) {
2356 if (py_length == NULL) {
2365 PyObject* clone = PyObject_CallObject(
2366 reinterpret_cast<PyObject*
>(
Py_TYPE(
self)), NULL);
2367 if (clone == NULL) {
2375 reinterpret_cast<CMessage*
>(clone),
2376 reinterpret_cast<PyObject*
>(
self))) == NULL) {
2386 PyImport_ImportModule(
"google.protobuf.text_format"));
2387 if (text_format == NULL) {
2396 text_format.get(),
method_name.get(),
self, Py_True, NULL));
2398 if (encoded == NULL) {
2401 PyObject* decoded = PyUnicode_FromEncodedObject(encoded.get(),
"utf-8", NULL);
2402 if (decoded == NULL) {
2410 PyObject* unused_arg) {
2412 PyErr_SetString(PyExc_TypeError,
2413 "Descriptors should not be created directly, "
2414 "but only retrieved from their parent.");
2425 PyErr_SetNone(PyExc_AttributeError);
2428 if (!
self->composite_fields) {
2431 if (!
self->composite_fields) {
2435 return reinterpret_cast<PyObject*
>(extension_dict);
2439 if (
self->unknown_field_set == NULL) {
2442 Py_INCREF(
self->unknown_field_set);
2444 return self->unknown_field_set;
2466 {
"__deepcopy__", (PyCFunction)
DeepCopy, METH_VARARGS,
2467 "Makes a deep copy of the class." },
2468 {
"__unicode__", (PyCFunction)
ToUnicode, METH_NOARGS,
2469 "Outputs a unicode representation of the message." },
2470 {
"ByteSize", (PyCFunction)
ByteSize, METH_NOARGS,
2471 "Returns the size of the message in bytes." },
2472 {
"Clear", (PyCFunction)
Clear, METH_NOARGS,
2473 "Clears the message." },
2475 "Clears a message field." },
2476 {
"ClearField", (PyCFunction)
ClearField, METH_O,
2477 "Clears a message field." },
2478 {
"CopyFrom", (PyCFunction)
CopyFrom, METH_O,
2479 "Copies a protocol message into the current message." },
2481 "Discards the unknown fields." },
2484 "Finds unset required fields." },
2485 {
"FromString", (PyCFunction)
FromString, METH_O | METH_CLASS,
2486 "Creates new method instance from given serialized data." },
2488 "Checks if a message field is set." },
2489 {
"HasField", (PyCFunction)
HasField, METH_O,
2490 "Checks if a message field is set." },
2491 {
"IsInitialized", (PyCFunction)
IsInitialized, METH_VARARGS,
2492 "Checks if all required fields of a protocol message are set." },
2493 {
"ListFields", (PyCFunction)
ListFields, METH_NOARGS,
2494 "Lists all set fields of a message." },
2495 {
"MergeFrom", (PyCFunction)
MergeFrom, METH_O,
2496 "Merges a protocol message into the current message." },
2498 "Merges a serialized message into the current message." },
2500 "Parses a serialized message into the current message." },
2502 "Registers an extension with the current message." },
2504 METH_VARARGS | METH_KEYWORDS,
2505 "Serializes the message to a string, even if it isn't initialized." },
2507 METH_VARARGS | METH_KEYWORDS,
2508 "Serializes the message to a string, only for initialized messages." },
2509 {
"SetInParent", (PyCFunction)
SetInParent, METH_NOARGS,
2510 "Sets the has bit of the given field in its parent message." },
2512 "Parse unknown field set"},
2513 {
"WhichOneof", (PyCFunction)
WhichOneof, METH_O,
2514 "Returns the name of the field set inside a oneof, "
2515 "or None if no field is set." },
2519 METH_NOARGS | METH_STATIC,
2520 "Raises TypeError if the caller is not in a _pb2.py file."},
2526 if (
self->composite_fields == NULL) {
2534 if (
self->child_submessages == NULL) {
2537 (*
self->child_submessages)[submessage->message] = submessage;
2541 PyObject*
GetAttr(PyObject* pself, PyObject*
name) {
2543 PyObject*
result = PyObject_GenericGetAttr(
2544 reinterpret_cast<PyObject*
>(
self),
name);
2548 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
2559 if (
self->composite_fields) {
2561 self->composite_fields->find(field_descriptor);
2562 if (
it !=
self->composite_fields->end()) {
2563 ContainerBase*
value =
it->second;
2565 return value->AsPyObject();
2569 if (
self->message->GetDescriptor() != field_descriptor->containing_type()) {
2570 PyErr_Format(PyExc_TypeError,
2571 "descriptor to field '%s' doesn't apply to '%s' object",
2572 field_descriptor->full_name().c_str(),
2577 if (!field_descriptor->is_repeated() &&
2582 ContainerBase* py_container =
nullptr;
2583 if (field_descriptor->is_map()) {
2584 const Descriptor* entry_type = field_descriptor->message_type();
2589 if (value_class == NULL) {
2597 }
else if (field_descriptor->is_repeated()) {
2601 if (message_class == NULL) {
2605 self, field_descriptor, message_class);
2610 }
else if (field_descriptor->cpp_type() ==
2614 PyErr_SetString(PyExc_SystemError,
"Should never happen");
2617 if (py_container == NULL) {
2621 Py_DECREF(py_container);
2624 return py_container->AsPyObject();
2629 if (
self->message->GetDescriptor() != field_descriptor->containing_type()) {
2630 PyErr_Format(PyExc_TypeError,
2631 "descriptor to field '%s' doesn't apply to '%s' object",
2632 field_descriptor->full_name().c_str(),
2636 PyErr_Format(PyExc_AttributeError,
2637 "Assignment not allowed to repeated "
2638 "field \"%s\" in protocol message object.",
2639 field_descriptor->name().c_str());
2642 PyErr_Format(PyExc_AttributeError,
2643 "Assignment not allowed to "
2644 "field \"%s\" in protocol message object.",
2645 field_descriptor->name().c_str());
2667 {this->parent_field_descriptor});
2672 Py_DECREF(new_parent);
2687 CMessageClass* message_class) {
2701 cmsg->message = sub_message;
2703 cmsg->parent =
this;
2704 cmsg->parent_field_descriptor = field_descriptor;
2720 Py_CLEAR(released->parent);
2721 released->parent_field_descriptor =
nullptr;
2722 released->read_only =
false;
2742 PyObject_HashNotImplemented,
2748 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
2749 | Py_TPFLAGS_HAVE_VERSION_TAG,
2750 "A ProtocolMessage",
2773 const Message* (*GetCProtoInsidePyProtoPtr)(PyObject*
msg);
2774 Message* (*MutableCProtoInsidePyProtoPtr)(PyObject*
msg);
2796 PyErr_SetString(PyExc_TypeError,
"Not a Message instance");
2805 PyErr_SetString(PyExc_TypeError,
"Not a Message instance");
2811 if ((cmsg->composite_fields && !cmsg->composite_fields->empty()) ||
2812 (cmsg->child_submessages && !cmsg->child_submessages->empty())) {
2817 PyErr_SetString(PyExc_ValueError,
2818 "Cannot reliably get a mutable pointer "
2819 "to a message with extra references");
2823 return cmsg->message;
2832 if (py_message_factory ==
nullptr) {
2835 if (
pool ==
nullptr) {
2836 PyErr_SetString(PyExc_TypeError,
2837 "Unknown descriptor pool; C++ users should call "
2838 "DescriptorPool_FromPool and keep it alive");
2841 factory =
pool->py_message_factory;
2845 PyErr_SetString(PyExc_TypeError,
"Expected a MessageFactory");
2853 PyObject* py_message_factory) {
2856 if (message_class ==
nullptr) {
2861 Py_DECREF(message_class);
2862 if (
self ==
nullptr) {
2865 return self->AsPyObject();
2869 PyObject* py_message_factory) {
2871 message->GetDescriptor(), py_message_factory);
2872 if (message_class ==
nullptr) {
2877 Py_DECREF(message_class);
2878 if (
self ==
nullptr) {
2883 self->parent =
reinterpret_cast<CMessage*
>(Py_None);
2893 PyObject *dummy_obj = PySet_New(NULL);
2895 Py_DECREF(dummy_obj);
2921 PyModule_AddObject(
m,
"MessageMeta",
2939 PyModule_AddObject(
m,
"Message",
reinterpret_cast<PyObject*
>(
CMessage_Type));
2948 m,
"RepeatedScalarContainer",
2956 m,
"RepeatedCompositeContainer",
2961 if (collections == NULL) {
2965 PyObject_GetAttrString(collections.get(),
"MutableSequence"));
2966 if (mutable_sequence == NULL) {
2970 PyObject_CallMethod(mutable_sequence.get(),
"register",
"O",
2975 PyObject_CallMethod(mutable_sequence.get(),
"register",
"O",
2985 PyModule_AddObject(
m,
"UnknownFieldSet",
2992 PyModule_AddObject(
m,
"UnknownField",
2999 PyModule_AddObject(
m,
"ScalarMapContainer",
3001 PyModule_AddObject(
m,
"MessageMapContainer",
3003 PyModule_AddObject(
m,
"MapIterator",
3009 PyModule_AddObject(
m,
"ExtensionDict",
3014 PyModule_AddObject(
m,
"ExtensionIterator",
3021 PyModule_AddObject(
m,
"default_pool",
3024 PyModule_AddObject(
m,
"DescriptorPool",
3026 PyModule_AddObject(
m,
"Descriptor",
3028 PyModule_AddObject(
m,
"FieldDescriptor",
3030 PyModule_AddObject(
m,
"EnumDescriptor",
3032 PyModule_AddObject(
m,
"EnumValueDescriptor",
3034 PyModule_AddObject(
m,
"FileDescriptor",
3036 PyModule_AddObject(
m,
"OneofDescriptor",
3038 PyModule_AddObject(
m,
"ServiceDescriptor",
3040 PyModule_AddObject(
m,
"MethodDescriptor",
3043 PyObject* enum_type_wrapper = PyImport_ImportModule(
3044 "google.protobuf.internal.enum_type_wrapper");
3045 if (enum_type_wrapper == NULL) {
3049 PyObject_GetAttrString(enum_type_wrapper,
"EnumTypeWrapper");
3050 Py_DECREF(enum_type_wrapper);
3052 PyObject* message_module = PyImport_ImportModule(
3053 "google.protobuf.message");
3054 if (message_module == NULL) {
3060 Py_DECREF(message_module);
3062 PyObject* pickle_module = PyImport_ImportModule(
"pickle");
3063 if (pickle_module == NULL) {
3067 Py_DECREF(pickle_module);