Debian Codegraph @

third_party/upb/python/message.c

raw
1 /*
2 * Copyright (c) 2009-2021, Google LLC
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of Google LLC nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL Google LLC BE LIABLE FOR ANY DIRECT,
20 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include "python/message.h"
29
30 #include "python/convert.h"
31 #include "python/descriptor.h"
32 #include "python/extension_dict.h"
33 #include "python/map.h"
34 #include "python/repeated.h"
35 #include "upb/def.h"
36 #include "upb/reflection.h"
37 #include "upb/text_encode.h"
38 #include "upb/util/required_fields.h"
39
40 static const upb_MessageDef* PyUpb_MessageMeta_GetMsgdef(PyObject* cls);
41 static PyObject* PyUpb_MessageMeta_GetAttr(PyObject* self, PyObject* name);
42
43 // -----------------------------------------------------------------------------
44 // CPythonBits
45 // -----------------------------------------------------------------------------
46
47 // This struct contains a few things that are not exposed directly through the
48 // limited API, but that we can get at in somewhat more roundabout ways. The
49 // roundabout ways are slower, so we cache the values here.
50 //
51 // These values are valid to cache in a global, even across sub-interpreters,
52 // because they are not pointers to interpreter state. They are process
53 // globals that will be the same for any interpreter in this process.
54 typedef struct {
55 // For each member, we note the equivalent expression that we could use in the
56 // full (non-limited) API.
57 newfunc type_new; // PyTypeObject.tp_new
58 destructor type_dealloc; // PyTypeObject.tp_dealloc
59 getattrofunc type_getattro; // PyTypeObject.tp_getattro
60 setattrofunc type_setattro; // PyTypeObject.tp_setattro
61 size_t type_basicsize; // sizeof(PyHeapTypeObject)
62
63 // While we can refer to PY_VERSION_HEX in the limited API, this will give us
64 // the version of Python we were compiled against, which may be different
65 // than the version we are dynamically linked against. Here we want the
66 // version that is actually running in this process.
67 long python_version_hex; // PY_VERSION_HEX
68 } PyUpb_CPythonBits;
69
70 // A global containing the values for this process.
71 PyUpb_CPythonBits cpython_bits;
72
73 destructor upb_Pre310_PyType_GetDeallocSlot(PyTypeObject* type_subclass) {
74 // This is a bit desperate. We need type_dealloc(), but PyType_GetSlot(type,
75 // Py_tp_dealloc) will return subtype_dealloc(). There appears to be no way
76 // whatsoever to fetch type_dealloc() through the limited API until Python
77 // 3.10.
78 //
79 // To work around this so we attempt to find it by looking for the offset of
80 // tp_dealloc in PyTypeObject, then memcpy() it directly. This should always
81 // work in practice.
82 //
83 // Starting with Python 3.10 on you can call PyType_GetSlot() on non-heap
84 // types. We will be able to replace all this hack with just:
85 //
86 // PyType_GetSlot(&PyType_Type, Py_tp_dealloc)
87 //
88 destructor subtype_dealloc = PyType_GetSlot(type_subclass, Py_tp_dealloc);
89 for (size_t i = 0; i < 2000; i += sizeof(uintptr_t)) {
90 destructor maybe_subtype_dealloc;
91 memcpy(&maybe_subtype_dealloc, (char*)type_subclass + i,
92 sizeof(destructor));
93 if (maybe_subtype_dealloc == subtype_dealloc) {
94 destructor type_dealloc;
95 memcpy(&type_dealloc, (char*)&PyType_Type + i, sizeof(destructor));
96 return type_dealloc;
97 }
98 }
99 assert(false);
100 return NULL;
101 }
102
103 static bool PyUpb_CPythonBits_Init(PyUpb_CPythonBits* bits) {
104 PyObject* bases = NULL;
105 PyTypeObject* type = NULL;
106 PyObject* size = NULL;
107 PyObject* sys = NULL;
108 PyObject* hex_version = NULL;
109 bool ret = false;
110
111 // PyType_GetSlot() only works on heap types, so we cannot use it on
112 // &PyType_Type directly. Instead we create our own (temporary) type derived
113 // from PyType_Type: this will inherit all of the slots from PyType_Type, but
114 // as a heap type it can be queried with PyType_GetSlot().
115 static PyType_Slot dummy_slots[] = {{0, NULL}};
116
117 static PyType_Spec dummy_spec = {
118 "module.DummyClass", // tp_name
119 0, // To be filled in by size of base // tp_basicsize
120 0, // tp_itemsize
121 Py_TPFLAGS_DEFAULT, // tp_flags
122 dummy_slots,
123 };
124
125 bases = Py_BuildValue("(O)", &PyType_Type);
126 if (!bases) goto err;
127 type = (PyTypeObject*)PyType_FromSpecWithBases(&dummy_spec, bases);
128 if (!type) goto err;
129
130 bits->type_new = PyType_GetSlot(type, Py_tp_new);
131 bits->type_dealloc = upb_Pre310_PyType_GetDeallocSlot(type);
132 bits->type_getattro = PyType_GetSlot(type, Py_tp_getattro);
133 bits->type_setattro = PyType_GetSlot(type, Py_tp_setattro);
134
135 size = PyObject_GetAttrString((PyObject*)&PyType_Type, "__basicsize__");
136 if (!size) goto err;
137 bits->type_basicsize = PyLong_AsLong(size);
138 if (bits->type_basicsize == -1) goto err;
139
140 assert(bits->type_new);
141 assert(bits->type_dealloc);
142 assert(bits->type_getattro);
143 assert(bits->type_setattro);
144
145 #ifndef Py_LIMITED_API
146 assert(bits->type_new == PyType_Type.tp_new);
147 assert(bits->type_dealloc == PyType_Type.tp_dealloc);
148 assert(bits->type_getattro == PyType_Type.tp_getattro);
149 assert(bits->type_setattro == PyType_Type.tp_setattro);
150 assert(bits->type_basicsize == sizeof(PyHeapTypeObject));
151 #endif
152
153 sys = PyImport_ImportModule("sys");
154 hex_version = PyObject_GetAttrString(sys, "hexversion");
155 bits->python_version_hex = PyLong_AsLong(hex_version);
156 ret = true;
157
158 err:
159 Py_XDECREF(bases);
160 Py_XDECREF(type);
161 Py_XDECREF(size);
162 Py_XDECREF(sys);
163 Py_XDECREF(hex_version);
164 return ret;
165 }
166
167 // -----------------------------------------------------------------------------
168 // Message
169 // -----------------------------------------------------------------------------
170
171 // The main message object. The type of the object (PyUpb_Message.ob_type)
172 // will be an instance of the PyUpb_MessageMeta type (defined below). So the
173 // chain is:
174 // FooMessage = MessageMeta(...)
175 // foo = FooMessage()
176 //
177 // Which becomes:
178 // Object C Struct Type Python type (ob_type)
179 // ----------------- ----------------- ---------------------
180 // foo PyUpb_Message FooMessage
181 // FooMessage PyUpb_MessageMeta message_meta_type
182 // message_meta_type PyTypeObject 'type' in Python
183 //
184 // A message object can be in one of two states: present or non-present. When
185 // a message is non-present, it stores a reference to its parent, and a write
186 // to any attribute will trigger the message to become present in its parent.
187 // The parent may also be non-present, in which case a mutation will trigger a
188 // chain reaction.
189 typedef struct PyUpb_Message {
190 PyObject_HEAD;
191 PyObject* arena;
192 uintptr_t def; // Tagged, low bit 1 == upb_FieldDef*, else upb_MessageDef*
193 union {
194 // when def is msgdef, the data for this msg.
195 upb_Message* msg;
196 // when def is fielddef, owning pointer to parent
197 struct PyUpb_Message* parent;
198 } ptr;
199 PyObject* ext_dict; // Weak pointer to extension dict, if any.
200 // name->obj dict for non-present msg/map/repeated, NULL if none.
201 PyUpb_WeakMap* unset_subobj_map;
202 int version;
203 } PyUpb_Message;
204
205 static PyObject* PyUpb_Message_GetAttr(PyObject* _self, PyObject* attr);
206
207 bool PyUpb_Message_IsStub(PyUpb_Message* msg) { return msg->def & 1; }
208
209 const upb_FieldDef* PyUpb_Message_GetFieldDef(PyUpb_Message* msg) {
210 assert(PyUpb_Message_IsStub(msg));
211 return (void*)(msg->def & ~(uintptr_t)1);
212 }
213
214 static const upb_MessageDef* _PyUpb_Message_GetMsgdef(PyUpb_Message* msg) {
215 return PyUpb_Message_IsStub(msg)
216 ? upb_FieldDef_MessageSubDef(PyUpb_Message_GetFieldDef(msg))
217 : (void*)msg->def;
218 }
219
220 const upb_MessageDef* PyUpb_Message_GetMsgdef(PyObject* self) {
221 return _PyUpb_Message_GetMsgdef((PyUpb_Message*)self);
222 }
223
224 static upb_Message* PyUpb_Message_GetMsg(PyUpb_Message* self) {
225 assert(!PyUpb_Message_IsStub(self));
226 return self->ptr.msg;
227 }
228
229 bool PyUpb_Message_TryCheck(PyObject* self) {
230 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
231 PyObject* type = (PyObject*)Py_TYPE(self);
232 return Py_TYPE(type) == state->message_meta_type;
233 }
234
235 bool PyUpb_Message_Verify(PyObject* self) {
236 if (!PyUpb_Message_TryCheck(self)) {
237 PyErr_Format(PyExc_TypeError, "Expected a message object, but got %R.",
238 self);
239 return false;
240 }
241 return true;
242 }
243
244 // If the message is reified, returns it. Otherwise, returns NULL.
245 // If NULL is returned, the object is empty and has no underlying data.
246 upb_Message* PyUpb_Message_GetIfReified(PyObject* _self) {
247 PyUpb_Message* self = (void*)_self;
248 return PyUpb_Message_IsStub(self) ? NULL : self->ptr.msg;
249 }
250
251 static PyObject* PyUpb_Message_New(PyObject* cls, PyObject* unused_args,
252 PyObject* unused_kwargs) {
253 const upb_MessageDef* msgdef = PyUpb_MessageMeta_GetMsgdef(cls);
254 PyUpb_Message* msg = (void*)PyType_GenericAlloc((PyTypeObject*)cls, 0);
255 msg->def = (uintptr_t)msgdef;
256 msg->arena = PyUpb_Arena_New();
257 msg->ptr.msg = upb_Message_New(msgdef, PyUpb_Arena_Get(msg->arena));
258 msg->unset_subobj_map = NULL;
259 msg->ext_dict = NULL;
260 msg->version = 0;
261
262 PyObject* ret = &msg->ob_base;
263 PyUpb_ObjCache_Add(msg->ptr.msg, ret);
264 return ret;
265 }
266
267 /*
268 * PyUpb_Message_LookupName()
269 *
270 * Tries to find a field or oneof named `py_name` in the message object `self`.
271 * The user must pass `f` and/or `o` to indicate whether a field or a oneof name
272 * is expected. If the name is found and it has an expected type, the function
273 * sets `*f` or `*o` respectively and returns true. Otherwise returns false
274 * and sets an exception of type `exc_type` if provided.
275 */
276 static bool PyUpb_Message_LookupName(PyUpb_Message* self, PyObject* py_name,
277 const upb_FieldDef** f,
278 const upb_OneofDef** o,
279 PyObject* exc_type) {
280 assert(f || o);
281 Py_ssize_t size;
282 const char* name = NULL;
283 if (PyUnicode_Check(py_name)) {
284 name = PyUnicode_AsUTF8AndSize(py_name, &size);
285 } else if (PyBytes_Check(py_name)) {
286 PyBytes_AsStringAndSize(py_name, (char**)&name, &size);
287 }
288 if (!name) {
289 PyErr_Format(exc_type,
290 "Expected a field name, but got non-string argument %S.",
291 py_name);
292 return false;
293 }
294 const upb_MessageDef* msgdef = _PyUpb_Message_GetMsgdef(self);
295
296 if (!upb_MessageDef_FindByNameWithSize(msgdef, name, size, f, o)) {
297 if (exc_type) {
298 PyErr_Format(exc_type, "Protocol message %s has no \"%s\" field.",
299 upb_MessageDef_Name(msgdef), name);
300 }
301 return false;
302 }
303
304 if (!o && !*f) {
305 if (exc_type) {
306 PyErr_Format(exc_type, "Expected a field name, but got oneof name %s.",
307 name);
308 }
309 return false;
310 }
311
312 if (!f && !*o) {
313 if (exc_type) {
314 PyErr_Format(exc_type, "Expected a oneof name, but got field name %s.",
315 name);
316 }
317 return false;
318 }
319
320 return true;
321 }
322
323 static bool PyUpb_Message_InitMessageMapEntry(PyObject* dst, PyObject* src) {
324 if (!src || !dst) return false;
325
326 // TODO(haberman): Currently we are doing Clear()+MergeFrom(). Replace with
327 // CopyFrom() once that is implemented.
328 PyObject* ok = PyObject_CallMethod(dst, "Clear", NULL);
329 if (!ok) return false;
330 Py_DECREF(ok);
331 ok = PyObject_CallMethod(dst, "MergeFrom", "O", src);
332 if (!ok) return false;
333 Py_DECREF(ok);
334
335 return true;
336 }
337
338 int PyUpb_Message_InitMapAttributes(PyObject* map, PyObject* value,
339 const upb_FieldDef* f) {
340 const upb_MessageDef* entry_m = upb_FieldDef_MessageSubDef(f);
341 const upb_FieldDef* val_f = upb_MessageDef_Field(entry_m, 1);
342 PyObject* it = NULL;
343 PyObject* tmp = NULL;
344 int ret = -1;
345 if (upb_FieldDef_IsSubMessage(val_f)) {
346 it = PyObject_GetIter(value);
347 if (it == NULL) {
348 PyErr_Format(PyExc_TypeError, "Argument for field %s is not iterable",
349 upb_FieldDef_FullName(f));
350 goto err;
351 }
352 PyObject* e;
353 while ((e = PyIter_Next(it)) != NULL) {
354 PyObject* src = PyObject_GetItem(value, e);
355 PyObject* dst = PyObject_GetItem(map, e);
356 Py_DECREF(e);
357 bool ok = PyUpb_Message_InitMessageMapEntry(dst, src);
358 Py_XDECREF(src);
359 Py_XDECREF(dst);
360 if (!ok) goto err;
361 }
362 } else {
363 tmp = PyObject_CallMethod(map, "update", "O", value);
364 if (!tmp) goto err;
365 }
366 ret = 0;
367
368 err:
369 Py_XDECREF(it);
370 Py_XDECREF(tmp);
371 return ret;
372 }
373
374 void PyUpb_Message_EnsureReified(PyUpb_Message* self);
375
376 static bool PyUpb_Message_InitMapAttribute(PyObject* _self, PyObject* name,
377 const upb_FieldDef* f,
378 PyObject* value) {
379 PyObject* map = PyUpb_Message_GetAttr(_self, name);
380 int ok = PyUpb_Message_InitMapAttributes(map, value, f);
381 Py_DECREF(map);
382 return ok >= 0;
383 }
384
385 static bool PyUpb_Message_InitRepeatedMessageAttribute(PyObject* _self,
386 PyObject* repeated,
387 PyObject* value,
388 const upb_FieldDef* f) {
389 PyObject* it = PyObject_GetIter(value);
390 if (!it) {
391 PyErr_Format(PyExc_TypeError, "Argument for field %s is not iterable",
392 upb_FieldDef_FullName(f));
393 return false;
394 }
395 PyObject* e = NULL;
396 PyObject* m = NULL;
397 while ((e = PyIter_Next(it)) != NULL) {
398 if (PyDict_Check(e)) {
399 m = PyUpb_RepeatedCompositeContainer_Add(repeated, NULL, e);
400 if (!m) goto err;
401 } else {
402 m = PyUpb_RepeatedCompositeContainer_Add(repeated, NULL, NULL);
403 if (!m) goto err;
404 PyObject* merged = PyUpb_Message_MergeFrom(m, e);
405 if (!merged) goto err;
406 Py_DECREF(merged);
407 }
408 Py_DECREF(e);
409 Py_DECREF(m);
410 m = NULL;
411 }
412
413 err:
414 Py_XDECREF(it);
415 Py_XDECREF(e);
416 Py_XDECREF(m);
417 return !PyErr_Occurred(); // Check PyIter_Next() exit.
418 }
419
420 static bool PyUpb_Message_InitRepeatedAttribute(PyObject* _self, PyObject* name,
421 PyObject* value) {
422 PyUpb_Message* self = (void*)_self;
423 const upb_FieldDef* field;
424 if (!PyUpb_Message_LookupName(self, name, &field, NULL,
425 PyExc_AttributeError)) {
426 return false;
427 }
428 bool ok = false;
429 PyObject* repeated = PyUpb_Message_GetFieldValue(_self, field);
430 PyObject* tmp = NULL;
431 if (!repeated) goto err;
432 if (upb_FieldDef_IsSubMessage(field)) {
433 if (!PyUpb_Message_InitRepeatedMessageAttribute(_self, repeated, value,
434 field)) {
435 goto err;
436 }
437 } else {
438 tmp = PyUpb_RepeatedContainer_Extend(repeated, value);
439 if (!tmp) goto err;
440 }
441 ok = true;
442
443 err:
444 Py_XDECREF(repeated);
445 Py_XDECREF(tmp);
446 return ok;
447 }
448
449 static bool PyUpb_Message_InitMessageAttribute(PyObject* _self, PyObject* name,
450 PyObject* value) {
451 PyObject* submsg = PyUpb_Message_GetAttr(_self, name);
452 if (!submsg) return -1;
453 assert(!PyErr_Occurred());
454 bool ok;
455 if (PyUpb_Message_TryCheck(value)) {
456 PyObject* tmp = PyUpb_Message_MergeFrom(submsg, value);
457 ok = tmp != NULL;
458 Py_DECREF(tmp);
459 } else if (PyDict_Check(value)) {
460 assert(!PyErr_Occurred());
461 ok = PyUpb_Message_InitAttributes(submsg, NULL, value) >= 0;
462 } else {
463 const upb_MessageDef* m = PyUpb_Message_GetMsgdef(_self);
464 PyErr_Format(PyExc_TypeError, "Message must be initialized with a dict: %s",
465 upb_MessageDef_FullName(m));
466 ok = false;
467 }
468 Py_DECREF(submsg);
469 return ok;
470 }
471
472 static bool PyUpb_Message_InitScalarAttribute(upb_Message* msg,
473 const upb_FieldDef* f,
474 PyObject* value,
475 upb_Arena* arena) {
476 upb_MessageValue msgval;
477 assert(!PyErr_Occurred());
478 if (!PyUpb_PyToUpb(value, f, &msgval, arena)) return false;
479 upb_Message_Set(msg, f, msgval, arena);
480 return true;
481 }
482
483 int PyUpb_Message_InitAttributes(PyObject* _self, PyObject* args,
484 PyObject* kwargs) {
485 assert(!PyErr_Occurred());
486
487 if (args != NULL && PyTuple_Size(args) != 0) {
488 PyErr_SetString(PyExc_TypeError, "No positional arguments allowed");
489 return -1;
490 }
491
492 if (kwargs == NULL) return 0;
493
494 PyUpb_Message* self = (void*)_self;
495 Py_ssize_t pos = 0;
496 PyObject* name;
497 PyObject* value;
498 PyUpb_Message_EnsureReified(self);
499 upb_Message* msg = PyUpb_Message_GetMsg(self);
500 upb_Arena* arena = PyUpb_Arena_Get(self->arena);
501
502 while (PyDict_Next(kwargs, &pos, &name, &value)) {
503 assert(!PyErr_Occurred());
504 const upb_FieldDef* f;
505 assert(!PyErr_Occurred());
506 if (!PyUpb_Message_LookupName(self, name, &f, NULL, PyExc_ValueError)) {
507 return -1;
508 }
509
510 if (value == Py_None) continue; // Ignored.
511
512 assert(!PyErr_Occurred());
513
514 if (upb_FieldDef_IsMap(f)) {
515 if (!PyUpb_Message_InitMapAttribute(_self, name, f, value)) return -1;
516 } else if (upb_FieldDef_IsRepeated(f)) {
517 if (!PyUpb_Message_InitRepeatedAttribute(_self, name, value)) return -1;
518 } else if (upb_FieldDef_IsSubMessage(f)) {
519 if (!PyUpb_Message_InitMessageAttribute(_self, name, value)) return -1;
520 } else {
521 if (!PyUpb_Message_InitScalarAttribute(msg, f, value, arena)) return -1;
522 }
523 if (PyErr_Occurred()) return -1;
524 }
525
526 if (PyErr_Occurred()) return -1;
527 return 0;
528 }
529
530 static int PyUpb_Message_Init(PyObject* _self, PyObject* args,
531 PyObject* kwargs) {
532 if (args != NULL && PyTuple_Size(args) != 0) {
533 PyErr_SetString(PyExc_TypeError, "No positional arguments allowed");
534 return -1;
535 }
536
537 return PyUpb_Message_InitAttributes(_self, args, kwargs);
538 }
539
540 static PyObject* PyUpb_Message_NewStub(PyObject* parent, const upb_FieldDef* f,
541 PyObject* arena) {
542 const upb_MessageDef* sub_m = upb_FieldDef_MessageSubDef(f);
543 PyObject* cls = PyUpb_Descriptor_GetClass(sub_m);
544
545 PyUpb_Message* msg = (void*)PyType_GenericAlloc((PyTypeObject*)cls, 0);
546 msg->def = (uintptr_t)f | 1;
547 msg->arena = arena;
548 msg->ptr.parent = (PyUpb_Message*)parent;
549 msg->unset_subobj_map = NULL;
550 msg->ext_dict = NULL;
551 msg->version = 0;
552
553 Py_DECREF(cls);
554 Py_INCREF(parent);
555 Py_INCREF(arena);
556 return &msg->ob_base;
557 }
558
559 static bool PyUpb_Message_IsEqual(PyUpb_Message* m1, PyObject* _m2) {
560 PyUpb_Message* m2 = (void*)_m2;
561 if (m1 == m2) return true;
562 if (!PyObject_TypeCheck(_m2, m1->ob_base.ob_type)) {
563 return false;
564 }
565 const upb_MessageDef* m1_msgdef = _PyUpb_Message_GetMsgdef(m1);
566 #ifndef NDEBUG
567 const upb_MessageDef* m2_msgdef = _PyUpb_Message_GetMsgdef(m2);
568 assert(m1_msgdef == m2_msgdef);
569 #endif
570 const upb_Message* m1_msg = PyUpb_Message_GetIfReified((PyObject*)m1);
571 const upb_Message* m2_msg = PyUpb_Message_GetIfReified(_m2);
572 return upb_Message_IsEqual(m1_msg, m2_msg, m1_msgdef);
573 }
574
575 static const upb_FieldDef* PyUpb_Message_InitAsMsg(PyUpb_Message* m,
576 upb_Arena* arena) {
577 const upb_FieldDef* f = PyUpb_Message_GetFieldDef(m);
578 m->ptr.msg = upb_Message_New(upb_FieldDef_MessageSubDef(f), arena);
579 m->def = (uintptr_t)upb_FieldDef_MessageSubDef(f);
580 PyUpb_ObjCache_Add(m->ptr.msg, &m->ob_base);
581 return f;
582 }
583
584 static void PyUpb_Message_SetField(PyUpb_Message* parent, const upb_FieldDef* f,
585 PyUpb_Message* child, upb_Arena* arena) {
586 upb_MessageValue msgval = {.msg_val = PyUpb_Message_GetMsg(child)};
587 upb_Message_Set(PyUpb_Message_GetMsg(parent), f, msgval, arena);
588 PyUpb_WeakMap_Delete(parent->unset_subobj_map, f);
589 // Releases a ref previously owned by child->ptr.parent of our child.
590 Py_DECREF(child);
591 }
592
593 /*
594 * PyUpb_Message_EnsureReified()
595 *
596 * This implements the "expando" behavior of Python protos:
597 * foo = FooProto()
598 *
599 * # The intermediate messages don't really exist, and won't be serialized.
600 * x = foo.bar.bar.bar.bar.bar.baz
601 *
602 * # Now all the intermediate objects are created.
603 * foo.bar.bar.bar.bar.bar.baz = 5
604 *
605 * This function should be called before performing any mutation of a protobuf
606 * object.
607 *
608 * Post-condition:
609 * PyUpb_Message_IsStub(self) is false
610 */
611 void PyUpb_Message_EnsureReified(PyUpb_Message* self) {
612 if (!PyUpb_Message_IsStub(self)) return;
613 upb_Arena* arena = PyUpb_Arena_Get(self->arena);
614
615 // This is a non-present message. We need to create a real upb_Message for
616 // this object and every parent until we reach a present message.
617 PyUpb_Message* child = self;
618 PyUpb_Message* parent = self->ptr.parent;
619 const upb_FieldDef* child_f = PyUpb_Message_InitAsMsg(child, arena);
620 Py_INCREF(child); // To avoid a special-case in PyUpb_Message_SetField().
621
622 do {
623 PyUpb_Message* next_parent = parent->ptr.parent;
624 const upb_FieldDef* parent_f = NULL;
625 if (PyUpb_Message_IsStub(parent)) {
626 parent_f = PyUpb_Message_InitAsMsg(parent, arena);
627 }
628 PyUpb_Message_SetField(parent, child_f, child, arena);
629 child = parent;
630 child_f = parent_f;
631 parent = next_parent;
632 } while (child_f);
633
634 // Releases ref previously owned by child->ptr.parent of our child.
635 Py_DECREF(child);
636 self->version++;
637 }
638
639 static void PyUpb_Message_SyncSubobjs(PyUpb_Message* self);
640
641 /*
642 * PyUpb_Message_Reify()
643 *
644 * The message equivalent of PyUpb_*Container_Reify(), this transitions
645 * the wrapper from the unset state (owning a reference on self->ptr.parent) to
646 * the set state (having a non-owning pointer to self->ptr.msg).
647 */
648 static void PyUpb_Message_Reify(PyUpb_Message* self, const upb_FieldDef* f,
649 upb_Message* msg) {
650 assert(f == PyUpb_Message_GetFieldDef(self));
651 if (!msg) {
652 const upb_MessageDef* msgdef = PyUpb_Message_GetMsgdef((PyObject*)self);
653 msg = upb_Message_New(msgdef, PyUpb_Arena_Get(self->arena));
654 }
655 PyUpb_ObjCache_Add(msg, &self->ob_base);
656 Py_DECREF(&self->ptr.parent->ob_base);
657 self->ptr.msg = msg; // Overwrites self->ptr.parent
658 self->def = (uintptr_t)upb_FieldDef_MessageSubDef(f);
659 PyUpb_Message_SyncSubobjs(self);
660 }
661
662 /*
663 * PyUpb_Message_SyncSubobjs()
664 *
665 * This operation must be invoked whenever the underlying upb_Message has been
666 * mutated directly in C. This will attach any newly-present field data
667 * to previously returned stub wrapper objects.
668 *
669 * For example:
670 * foo = FooMessage()
671 * sub = foo.submsg # Empty, unset sub-message
672 *
673 * # SyncSubobjs() is required to connect our existing 'sub' wrapper to the
674 * # newly created foo.submsg data in C.
675 * foo.MergeFrom(FooMessage(submsg={}))
676 *
677 * This requires that all of the new sub-objects that have appeared are owned
678 * by `self`'s arena.
679 */
680 static void PyUpb_Message_SyncSubobjs(PyUpb_Message* self) {
681 PyUpb_WeakMap* subobj_map = self->unset_subobj_map;
682 if (!subobj_map) return;
683
684 upb_Message* msg = PyUpb_Message_GetMsg(self);
685 intptr_t iter = PYUPB_WEAKMAP_BEGIN;
686 const void* key;
687 PyObject* obj;
688
689 // The last ref to this message could disappear during iteration.
690 // When we call PyUpb_*Container_Reify() below, the container will drop
691 // its ref on `self`. If that was the last ref on self, the object will be
692 // deleted, and `subobj_map` along with it. We need it to live until we are
693 // done iterating.
694 Py_INCREF(&self->ob_base);
695
696 while (PyUpb_WeakMap_Next(subobj_map, &key, &obj, &iter)) {
697 const upb_FieldDef* f = key;
698 if (upb_FieldDef_HasPresence(f) && !upb_Message_Has(msg, f)) continue;
699 upb_MessageValue msgval = upb_Message_Get(msg, f);
700 PyUpb_WeakMap_DeleteIter(subobj_map, &iter);
701 if (upb_FieldDef_IsMap(f)) {
702 if (!msgval.map_val) continue;
703 PyUpb_MapContainer_Reify(obj, (upb_Map*)msgval.map_val);
704 } else if (upb_FieldDef_IsRepeated(f)) {
705 if (!msgval.array_val) continue;
706 PyUpb_RepeatedContainer_Reify(obj, (upb_Array*)msgval.array_val);
707 } else {
708 PyUpb_Message* sub = (void*)obj;
709 assert(self == sub->ptr.parent);
710 PyUpb_Message_Reify(sub, f, (upb_Message*)msgval.msg_val);
711 }
712 }
713
714 Py_DECREF(&self->ob_base);
715
716 // TODO(haberman): present fields need to be iterated too if they can reach
717 // a WeakMap.
718 }
719
720 static PyObject* PyUpb_Message_ToString(PyUpb_Message* self) {
721 if (PyUpb_Message_IsStub(self)) {
722 return PyUnicode_FromStringAndSize(NULL, 0);
723 }
724 upb_Message* msg = PyUpb_Message_GetMsg(self);
725 const upb_MessageDef* msgdef = _PyUpb_Message_GetMsgdef(self);
726 const upb_DefPool* symtab = upb_FileDef_Pool(upb_MessageDef_File(msgdef));
727 char buf[1024];
728 int options = UPB_TXTENC_SKIPUNKNOWN;
729 size_t size = upb_TextEncode(msg, msgdef, symtab, options, buf, sizeof(buf));
730 if (size < sizeof(buf)) {
731 return PyUnicode_FromStringAndSize(buf, size);
732 } else {
733 char* buf2 = malloc(size + 1);
734 size_t size2 = upb_TextEncode(msg, msgdef, symtab, options, buf2, size + 1);
735 assert(size == size2);
736 PyObject* ret = PyUnicode_FromStringAndSize(buf2, size2);
737 free(buf2);
738 return ret;
739 }
740 }
741
742 static PyObject* PyUpb_Message_RichCompare(PyObject* _self, PyObject* other,
743 int opid) {
744 PyUpb_Message* self = (void*)_self;
745 if (opid != Py_EQ && opid != Py_NE) {
746 Py_INCREF(Py_NotImplemented);
747 return Py_NotImplemented;
748 }
749 bool ret = PyUpb_Message_IsEqual(self, other);
750 if (opid == Py_NE) ret = !ret;
751 return PyBool_FromLong(ret);
752 }
753
754 void PyUpb_Message_CacheDelete(PyObject* _self, const upb_FieldDef* f) {
755 PyUpb_Message* self = (void*)_self;
756 PyUpb_WeakMap_Delete(self->unset_subobj_map, f);
757 }
758
759 void PyUpb_Message_SetConcreteSubobj(PyObject* _self, const upb_FieldDef* f,
760 upb_MessageValue subobj) {
761 PyUpb_Message* self = (void*)_self;
762 PyUpb_Message_EnsureReified(self);
763 PyUpb_Message_CacheDelete(_self, f);
764 upb_Message_Set(self->ptr.msg, f, subobj, PyUpb_Arena_Get(self->arena));
765 }
766
767 static void PyUpb_Message_Dealloc(PyObject* _self) {
768 PyUpb_Message* self = (void*)_self;
769
770 if (PyUpb_Message_IsStub(self)) {
771 PyUpb_Message_CacheDelete((PyObject*)self->ptr.parent,
772 PyUpb_Message_GetFieldDef(self));
773 Py_DECREF(self->ptr.parent);
774 } else {
775 PyUpb_ObjCache_Delete(self->ptr.msg);
776 }
777
778 if (self->unset_subobj_map) {
779 PyUpb_WeakMap_Free(self->unset_subobj_map);
780 }
781
782 Py_DECREF(self->arena);
783
784 // We do not use PyUpb_Dealloc() here because Message is a base type and for
785 // base types there is a bug we have to work around in this case (see below).
786 PyTypeObject* tp = Py_TYPE(self);
787 freefunc tp_free = PyType_GetSlot(tp, Py_tp_free);
788 tp_free(self);
789
790 if (cpython_bits.python_version_hex >= 0x03080000) {
791 // Prior to Python 3.8 there is a bug where deallocating the type here would
792 // lead to a double-decref: https://bugs.python.org/issue37879
793 Py_DECREF(tp);
794 }
795 }
796
797 PyObject* PyUpb_Message_Get(upb_Message* u_msg, const upb_MessageDef* m,
798 PyObject* arena) {
799 PyObject* ret = PyUpb_ObjCache_Get(u_msg);
800 if (ret) return ret;
801
802 PyObject* cls = PyUpb_Descriptor_GetClass(m);
803 // It is not safe to use PyObject_{,GC}_New() due to:
804 // https://bugs.python.org/issue35810
805 PyUpb_Message* py_msg = (void*)PyType_GenericAlloc((PyTypeObject*)cls, 0);
806 py_msg->arena = arena;
807 py_msg->def = (uintptr_t)m;
808 py_msg->ptr.msg = u_msg;
809 py_msg->unset_subobj_map = NULL;
810 py_msg->ext_dict = NULL;
811 py_msg->version = 0;
812 ret = &py_msg->ob_base;
813 Py_DECREF(cls);
814 Py_INCREF(arena);
815 PyUpb_ObjCache_Add(u_msg, ret);
816 return ret;
817 }
818
819 /* PyUpb_Message_GetStub()
820 *
821 * Non-present messages return "stub" objects that point to their parent, but
822 * will materialize into real upb objects if they are mutated.
823 *
824 * Note: we do *not* create stubs for repeated/map fields unless the parent
825 * is a stub:
826 *
827 * msg = TestMessage()
828 * msg.submessage # (A) Creates a stub
829 * msg.repeated_foo # (B) Does *not* create a stub
830 * msg.submessage.repeated_bar # (C) Creates a stub
831 *
832 * In case (B) we have some freedom: we could either create a stub, or create
833 * a reified object with underlying data. It appears that either could work
834 * equally well, with no observable change to users. There isn't a clear
835 * advantage to either choice. We choose to follow the behavior of the
836 * pre-existing C++ behavior for consistency, but if it becomes apparent that
837 * there would be some benefit to reversing this decision, it should be totally
838 * within the realm of possibility.
839 */
840 PyObject* PyUpb_Message_GetStub(PyUpb_Message* self,
841 const upb_FieldDef* field) {
842 PyObject* _self = (void*)self;
843 if (!self->unset_subobj_map) {
844 self->unset_subobj_map = PyUpb_WeakMap_New();
845 }
846 PyObject* subobj = PyUpb_WeakMap_Get(self->unset_subobj_map, field);
847
848 if (subobj) return subobj;
849
850 if (upb_FieldDef_IsMap(field)) {
851 subobj = PyUpb_MapContainer_NewStub(_self, field, self->arena);
852 } else if (upb_FieldDef_IsRepeated(field)) {
853 subobj = PyUpb_RepeatedContainer_NewStub(_self, field, self->arena);
854 } else {
855 subobj = PyUpb_Message_NewStub(&self->ob_base, field, self->arena);
856 }
857 PyUpb_WeakMap_Add(self->unset_subobj_map, field, subobj);
858
859 assert(!PyErr_Occurred());
860 return subobj;
861 }
862
863 PyObject* PyUpb_Message_GetPresentWrapper(PyUpb_Message* self,
864 const upb_FieldDef* field) {
865 assert(!PyUpb_Message_IsStub(self));
866 upb_MutableMessageValue mutval =
867 upb_Message_Mutable(self->ptr.msg, field, PyUpb_Arena_Get(self->arena));
868 if (upb_FieldDef_IsMap(field)) {
869 return PyUpb_MapContainer_GetOrCreateWrapper(mutval.map, field,
870 self->arena);
871 } else {
872 return PyUpb_RepeatedContainer_GetOrCreateWrapper(mutval.array, field,
873 self->arena);
874 }
875 }
876
877 PyObject* PyUpb_Message_GetScalarValue(PyUpb_Message* self,
878 const upb_FieldDef* field) {
879 upb_MessageValue val;
880 if (PyUpb_Message_IsStub(self)) {
881 // Unset message always returns default values.
882 val = upb_FieldDef_Default(field);
883 } else {
884 val = upb_Message_Get(self->ptr.msg, field);
885 }
886 return PyUpb_UpbToPy(val, field, self->arena);
887 }
888
889 /*
890 * PyUpb_Message_GetFieldValue()
891 *
892 * Implements the equivalent of getattr(msg, field), once `field` has
893 * already been resolved to a `upb_FieldDef*`.
894 *
895 * This may involve constructing a wrapper object for the given field, or
896 * returning one that was previously constructed. If the field is not actually
897 * set, the wrapper object will be an "unset" object that is not actually
898 * connected to any C data.
899 */
900 PyObject* PyUpb_Message_GetFieldValue(PyObject* _self,
901 const upb_FieldDef* field) {
902 PyUpb_Message* self = (void*)_self;
903 assert(upb_FieldDef_ContainingType(field) == PyUpb_Message_GetMsgdef(_self));
904 bool submsg = upb_FieldDef_IsSubMessage(field);
905 bool seq = upb_FieldDef_IsRepeated(field);
906
907 if ((PyUpb_Message_IsStub(self) && (submsg || seq)) ||
908 (submsg && !seq && !upb_Message_Has(self->ptr.msg, field))) {
909 return PyUpb_Message_GetStub(self, field);
910 } else if (seq) {
911 return PyUpb_Message_GetPresentWrapper(self, field);
912 } else {
913 return PyUpb_Message_GetScalarValue(self, field);
914 }
915 }
916
917 int PyUpb_Message_SetFieldValue(PyObject* _self, const upb_FieldDef* field,
918 PyObject* value, PyObject* exc) {
919 PyUpb_Message* self = (void*)_self;
920 assert(value);
921
922 if (upb_FieldDef_IsSubMessage(field) || upb_FieldDef_IsRepeated(field)) {
923 PyErr_Format(exc,
924 "Assignment not allowed to message, map, or repeated "
925 "field \"%s\" in protocol message object.",
926 upb_FieldDef_Name(field));
927 return -1;
928 }
929
930 PyUpb_Message_EnsureReified(self);
931
932 upb_MessageValue val;
933 upb_Arena* arena = PyUpb_Arena_Get(self->arena);
934 if (!PyUpb_PyToUpb(value, field, &val, arena)) {
935 return -1;
936 }
937
938 upb_Message_Set(self->ptr.msg, field, val, arena);
939 return 0;
940 }
941
942 int PyUpb_Message_GetVersion(PyObject* _self) {
943 PyUpb_Message* self = (void*)_self;
944 return self->version;
945 }
946
947 /*
948 * PyUpb_Message_GetAttr()
949 *
950 * Implements:
951 * foo = msg.foo
952 *
953 * Attribute lookup must find both message fields and base class methods like
954 * msg.SerializeToString().
955 */
956 __attribute__((flatten)) static PyObject* PyUpb_Message_GetAttr(
957 PyObject* _self, PyObject* attr) {
958 PyUpb_Message* self = (void*)_self;
959
960 // Lookup field by name.
961 const upb_FieldDef* field;
962 if (PyUpb_Message_LookupName(self, attr, &field, NULL, NULL)) {
963 return PyUpb_Message_GetFieldValue(_self, field);
964 }
965
966 // Check base class attributes.
967 assert(!PyErr_Occurred());
968 PyObject* ret = PyObject_GenericGetAttr(_self, attr);
969 if (ret) return ret;
970
971 // Swallow AttributeError if it occurred and try again on the metaclass
972 // to pick up class attributes. But we have to special-case "Extensions"
973 // which affirmatively returns AttributeError when a message is not
974 // extendable.
975 const char* name;
976 if (PyErr_ExceptionMatches(PyExc_AttributeError) &&
977 (name = PyUpb_GetStrData(attr)) && strcmp(name, "Extensions") != 0) {
978 PyErr_Clear();
979 return PyUpb_MessageMeta_GetAttr((PyObject*)Py_TYPE(_self), attr);
980 }
981
982 return NULL;
983 }
984
985 /*
986 * PyUpb_Message_SetAttr()
987 *
988 * Implements:
989 * msg.foo = foo
990 */
991 static int PyUpb_Message_SetAttr(PyObject* _self, PyObject* attr,
992 PyObject* value) {
993 PyUpb_Message* self = (void*)_self;
994 const upb_FieldDef* field;
995 if (!PyUpb_Message_LookupName(self, attr, &field, NULL,
996 PyExc_AttributeError)) {
997 return -1;
998 }
999
1000 return PyUpb_Message_SetFieldValue(_self, field, value, PyExc_AttributeError);
1001 }
1002
1003 static PyObject* PyUpb_Message_HasField(PyObject* _self, PyObject* arg) {
1004 PyUpb_Message* self = (void*)_self;
1005 const upb_FieldDef* field;
1006 const upb_OneofDef* oneof;
1007
1008 if (!PyUpb_Message_LookupName(self, arg, &field, &oneof, PyExc_ValueError)) {
1009 return NULL;
1010 }
1011
1012 if (field && !upb_FieldDef_HasPresence(field)) {
1013 PyErr_Format(PyExc_ValueError, "Field %s does not have presence.",
1014 upb_FieldDef_FullName(field));
1015 return NULL;
1016 }
1017
1018 if (PyUpb_Message_IsStub(self)) Py_RETURN_FALSE;
1019
1020 return PyBool_FromLong(field ? upb_Message_Has(self->ptr.msg, field)
1021 : upb_Message_WhichOneof(self->ptr.msg, oneof) !=
1022 NULL);
1023 }
1024
1025 static PyObject* PyUpb_Message_FindInitializationErrors(PyObject* _self,
1026 PyObject* arg);
1027
1028 static PyObject* PyUpb_Message_IsInitializedAppendErrors(PyObject* _self,
1029 PyObject* errors) {
1030 PyObject* list = PyUpb_Message_FindInitializationErrors(_self, NULL);
1031 if (!list) return NULL;
1032 bool ok = PyList_Size(list) == 0;
1033 PyObject* ret = NULL;
1034 PyObject* extend_result = NULL;
1035 if (!ok) {
1036 extend_result = PyObject_CallMethod(errors, "extend", "O", list);
1037 if (!extend_result) goto done;
1038 }
1039 ret = PyBool_FromLong(ok);
1040
1041 done:
1042 Py_XDECREF(list);
1043 Py_XDECREF(extend_result);
1044 return ret;
1045 }
1046
1047 static PyObject* PyUpb_Message_IsInitialized(PyObject* _self, PyObject* args) {
1048 PyObject* errors = NULL;
1049 if (!PyArg_ParseTuple(args, "|O", &errors)) {
1050 return NULL;
1051 }
1052 if (errors) {
1053 // We need to collect a list of unset required fields and append it to
1054 // `errors`.
1055 return PyUpb_Message_IsInitializedAppendErrors(_self, errors);
1056 } else {
1057 // We just need to return a boolean "true" or "false" for whether all
1058 // required fields are set.
1059 upb_Message* msg = PyUpb_Message_GetIfReified(_self);
1060 const upb_MessageDef* m = PyUpb_Message_GetMsgdef(_self);
1061 const upb_DefPool* symtab = upb_FileDef_Pool(upb_MessageDef_File(m));
1062 bool initialized = !upb_util_HasUnsetRequired(msg, m, symtab, NULL);
1063 return PyBool_FromLong(initialized);
1064 }
1065 }
1066
1067 static PyObject* PyUpb_Message_ListFieldsItemKey(PyObject* self,
1068 PyObject* val) {
1069 assert(PyTuple_Check(val));
1070 PyObject* field = PyTuple_GetItem(val, 0);
1071 const upb_FieldDef* f = PyUpb_FieldDescriptor_GetDef(field);
1072 return PyLong_FromLong(upb_FieldDef_Number(f));
1073 }
1074
1075 static PyObject* PyUpb_Message_CheckCalledFromGeneratedFile(
1076 PyObject* unused, PyObject* unused_arg) {
1077 PyErr_SetString(
1078 PyExc_TypeError,
1079 "Descriptors cannot not be created directly.\n"
1080 "If this call came from a _pb2.py file, your generated code is out of "
1081 "date and must be regenerated with protoc >= 3.19.0.\n"
1082 "If you cannot immediately regenerate your protos, some other possible "
1083 "workarounds are:\n"
1084 " 1. Downgrade the protobuf package to 3.20.x or lower.\n"
1085 " 2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will "
1086 "use pure-Python parsing and will be much slower).\n"
1087 "\n"
1088 "More information: "
1089 "https://developers.google.com/protocol-buffers/docs/news/"
1090 "2022-05-06#python-updates");
1091 return NULL;
1092 }
1093
1094 static bool PyUpb_Message_SortFieldList(PyObject* list) {
1095 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
1096 bool ok = false;
1097 PyObject* args = PyTuple_New(0);
1098 PyObject* kwargs = PyDict_New();
1099 PyObject* method = PyObject_GetAttrString(list, "sort");
1100 PyObject* call_result = NULL;
1101 if (!args || !kwargs || !method) goto err;
1102 if (PyDict_SetItemString(kwargs, "key", state->listfields_item_key) < 0) {
1103 goto err;
1104 }
1105 call_result = PyObject_Call(method, args, kwargs);
1106 if (!call_result) goto err;
1107 ok = true;
1108
1109 err:
1110 Py_XDECREF(method);
1111 Py_XDECREF(args);
1112 Py_XDECREF(kwargs);
1113 Py_XDECREF(call_result);
1114 return ok;
1115 }
1116
1117 static PyObject* PyUpb_Message_ListFields(PyObject* _self, PyObject* arg) {
1118 PyObject* list = PyList_New(0);
1119 upb_Message* msg = PyUpb_Message_GetIfReified(_self);
1120 if (!msg) return list;
1121
1122 size_t iter1 = kUpb_Message_Begin;
1123 const upb_MessageDef* m = PyUpb_Message_GetMsgdef(_self);
1124 const upb_DefPool* symtab = upb_FileDef_Pool(upb_MessageDef_File(m));
1125 const upb_FieldDef* f;
1126 PyObject* field_desc = NULL;
1127 PyObject* py_val = NULL;
1128 PyObject* tuple = NULL;
1129 upb_MessageValue val;
1130 uint32_t last_field = 0;
1131 bool in_order = true;
1132 while (upb_Message_Next(msg, m, symtab, &f, &val, &iter1)) {
1133 const uint32_t field_number = upb_FieldDef_Number(f);
1134 if (field_number < last_field) in_order = false;
1135 last_field = field_number;
1136 PyObject* field_desc = PyUpb_FieldDescriptor_Get(f);
1137 PyObject* py_val = PyUpb_Message_GetFieldValue(_self, f);
1138 if (!field_desc || !py_val) goto err;
1139 PyObject* tuple = Py_BuildValue("(NN)", field_desc, py_val);
1140 field_desc = NULL;
1141 py_val = NULL;
1142 if (!tuple) goto err;
1143 if (PyList_Append(list, tuple)) goto err;
1144 Py_DECREF(tuple);
1145 tuple = NULL;
1146 }
1147
1148 // Users rely on fields being returned in field number order.
1149 if (!in_order && !PyUpb_Message_SortFieldList(list)) goto err;
1150
1151 return list;
1152
1153 err:
1154 Py_XDECREF(field_desc);
1155 Py_XDECREF(py_val);
1156 Py_XDECREF(tuple);
1157 Py_DECREF(list);
1158 return NULL;
1159 }
1160
1161 PyObject* PyUpb_Message_MergeFrom(PyObject* self, PyObject* arg) {
1162 if (self->ob_type != arg->ob_type) {
1163 PyErr_Format(PyExc_TypeError,
1164 "Parameter to MergeFrom() must be instance of same class: "
1165 "expected %S got %S.",
1166 Py_TYPE(self), Py_TYPE(arg));
1167 return NULL;
1168 }
1169 // OPT: exit if src is empty.
1170 PyObject* subargs = PyTuple_New(0);
1171 PyObject* serialized = PyUpb_Message_SerializeToString(arg, subargs, NULL);
1172 Py_DECREF(subargs);
1173 if (!serialized) return NULL;
1174 PyObject* ret = PyUpb_Message_MergeFromString(self, serialized);
1175 Py_DECREF(serialized);
1176 Py_DECREF(ret);
1177 Py_RETURN_NONE;
1178 }
1179
1180 static PyObject* PyUpb_Message_SetInParent(PyObject* _self, PyObject* arg) {
1181 PyUpb_Message* self = (void*)_self;
1182 PyUpb_Message_EnsureReified(self);
1183 Py_RETURN_NONE;
1184 }
1185
1186 static PyObject* PyUpb_Message_UnknownFields(PyObject* _self, PyObject* arg) {
1187 // TODO(haberman): re-enable when unknown fields are added.
1188 // return PyUpb_UnknownFields_New(_self);
1189 PyErr_SetString(PyExc_NotImplementedError, "unknown field accessor");
1190 return NULL;
1191 }
1192
1193 PyObject* PyUpb_Message_MergeFromString(PyObject* _self, PyObject* arg) {
1194 PyUpb_Message* self = (void*)_self;
1195 char* buf;
1196 Py_ssize_t size;
1197 PyObject* bytes = NULL;
1198
1199 if (PyMemoryView_Check(arg)) {
1200 bytes = PyBytes_FromObject(arg);
1201 // Cannot fail when passed something of the correct type.
1202 int err = PyBytes_AsStringAndSize(bytes, &buf, &size);
1203 (void)err;
1204 assert(err >= 0);
1205 } else if (PyBytes_AsStringAndSize(arg, &buf, &size) < 0) {
1206 return NULL;
1207 }
1208
1209 PyUpb_Message_EnsureReified(self);
1210 const upb_MessageDef* msgdef = _PyUpb_Message_GetMsgdef(self);
1211 const upb_FileDef* file = upb_MessageDef_File(msgdef);
1212 const upb_ExtensionRegistry* extreg =
1213 upb_DefPool_ExtensionRegistry(upb_FileDef_Pool(file));
1214 const upb_MiniTable* layout = upb_MessageDef_MiniTable(msgdef);
1215 upb_Arena* arena = PyUpb_Arena_Get(self->arena);
1216 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
1217 int options =
1218 UPB_DECODE_MAXDEPTH(state->allow_oversize_protos ? UINT32_MAX : 100);
1219 upb_DecodeStatus status =
1220 upb_Decode(buf, size, self->ptr.msg, layout, extreg, options, arena);
1221 Py_XDECREF(bytes);
1222 if (status != kUpb_DecodeStatus_Ok) {
1223 PyErr_Format(state->decode_error_class, "Error parsing message");
1224 return NULL;
1225 }
1226 PyUpb_Message_SyncSubobjs(self);
1227 return PyLong_FromSsize_t(size);
1228 }
1229
1230 static PyObject* PyUpb_Message_Clear(PyUpb_Message* self, PyObject* args);
1231
1232 static PyObject* PyUpb_Message_ParseFromString(PyObject* self, PyObject* arg) {
1233 PyObject* tmp = PyUpb_Message_Clear((PyUpb_Message*)self, NULL);
1234 Py_DECREF(tmp);
1235 return PyUpb_Message_MergeFromString(self, arg);
1236 }
1237
1238 static PyObject* PyUpb_Message_ByteSize(PyObject* self, PyObject* args) {
1239 // TODO(https://github.com/protocolbuffers/upb/issues/462): At the moment upb
1240 // does not have a "byte size" function, so we just serialize to string and
1241 // get the size of the string.
1242 PyObject* subargs = PyTuple_New(0);
1243 PyObject* serialized = PyUpb_Message_SerializeToString(self, subargs, NULL);
1244 Py_DECREF(subargs);
1245 if (!serialized) return NULL;
1246 size_t size = PyBytes_Size(serialized);
1247 Py_DECREF(serialized);
1248 return PyLong_FromSize_t(size);
1249 }
1250
1251 static PyObject* PyUpb_Message_Clear(PyUpb_Message* self, PyObject* args) {
1252 PyUpb_Message_EnsureReified(self);
1253 const upb_MessageDef* msgdef = _PyUpb_Message_GetMsgdef(self);
1254 PyUpb_WeakMap* subobj_map = self->unset_subobj_map;
1255
1256 if (subobj_map) {
1257 upb_Message* msg = PyUpb_Message_GetMsg(self);
1258 (void)msg; // Suppress unused warning when asserts are disabled.
1259 intptr_t iter = PYUPB_WEAKMAP_BEGIN;
1260 const void* key;
1261 PyObject* obj;
1262
1263 while (PyUpb_WeakMap_Next(subobj_map, &key, &obj, &iter)) {
1264 const upb_FieldDef* f = key;
1265 PyUpb_WeakMap_DeleteIter(subobj_map, &iter);
1266 if (upb_FieldDef_IsMap(f)) {
1267 assert(upb_Message_Get(msg, f).map_val == NULL);
1268 PyUpb_MapContainer_Reify(obj, NULL);
1269 } else if (upb_FieldDef_IsRepeated(f)) {
1270 assert(upb_Message_Get(msg, f).array_val == NULL);
1271 PyUpb_RepeatedContainer_Reify(obj, NULL);
1272 } else {
1273 assert(!upb_Message_Has(msg, f));
1274 PyUpb_Message* sub = (void*)obj;
1275 assert(self == sub->ptr.parent);
1276 PyUpb_Message_Reify(sub, f, NULL);
1277 }
1278 }
1279 }
1280
1281 upb_Message_Clear(self->ptr.msg, msgdef);
1282 Py_RETURN_NONE;
1283 }
1284
1285 void PyUpb_Message_DoClearField(PyObject* _self, const upb_FieldDef* f) {
1286 PyUpb_Message* self = (void*)_self;
1287 PyUpb_Message_EnsureReified((PyUpb_Message*)self);
1288
1289 // We must ensure that any stub object is reified so its parent no longer
1290 // points to us.
1291 PyObject* sub = self->unset_subobj_map
1292 ? PyUpb_WeakMap_Get(self->unset_subobj_map, f)
1293 : NULL;
1294
1295 if (upb_FieldDef_IsMap(f)) {
1296 // For maps we additionally have to invalidate any iterators. So we need
1297 // to get an object even if it's reified.
1298 if (!sub) {
1299 sub = PyUpb_Message_GetFieldValue(_self, f);
1300 }
1301 PyUpb_MapContainer_EnsureReified(sub);
1302 PyUpb_MapContainer_Invalidate(sub);
1303 } else if (upb_FieldDef_IsRepeated(f)) {
1304 if (sub) {
1305 PyUpb_RepeatedContainer_EnsureReified(sub);
1306 }
1307 } else if (upb_FieldDef_IsSubMessage(f)) {
1308 if (sub) {
1309 PyUpb_Message_EnsureReified((PyUpb_Message*)sub);
1310 }
1311 }
1312
1313 Py_XDECREF(sub);
1314 upb_Message_ClearField(self->ptr.msg, f);
1315 }
1316
1317 static PyObject* PyUpb_Message_ClearExtension(PyObject* _self, PyObject* arg) {
1318 PyUpb_Message* self = (void*)_self;
1319 PyUpb_Message_EnsureReified(self);
1320 const upb_FieldDef* f = PyUpb_Message_GetExtensionDef(_self, arg);
1321 if (!f) return NULL;
1322 PyUpb_Message_DoClearField(_self, f);
1323 Py_RETURN_NONE;
1324 }
1325
1326 static PyObject* PyUpb_Message_ClearField(PyObject* _self, PyObject* arg) {
1327 PyUpb_Message* self = (void*)_self;
1328
1329 // We always need EnsureReified() here (even for an unset message) to
1330 // preserve behavior like:
1331 // msg = FooMessage()
1332 // msg.foo.Clear()
1333 // assert msg.HasField("foo")
1334 PyUpb_Message_EnsureReified(self);
1335
1336 const upb_FieldDef* f;
1337 const upb_OneofDef* o;
1338 if (!PyUpb_Message_LookupName(self, arg, &f, &o, PyExc_ValueError)) {
1339 return NULL;
1340 }
1341
1342 if (o) f = upb_Message_WhichOneof(self->ptr.msg, o);
1343 PyUpb_Message_DoClearField(_self, f);
1344 Py_RETURN_NONE;
1345 }
1346
1347 static PyObject* PyUpb_Message_DiscardUnknownFields(PyUpb_Message* self,
1348 PyObject* arg) {
1349 PyUpb_Message_EnsureReified(self);
1350 const upb_MessageDef* msgdef = _PyUpb_Message_GetMsgdef(self);
1351 upb_Message_DiscardUnknown(self->ptr.msg, msgdef, 64);
1352 Py_RETURN_NONE;
1353 }
1354
1355 static PyObject* PyUpb_Message_FindInitializationErrors(PyObject* _self,
1356 PyObject* arg) {
1357 PyUpb_Message* self = (void*)_self;
1358 upb_Message* msg = PyUpb_Message_GetIfReified(_self);
1359 const upb_MessageDef* msgdef = _PyUpb_Message_GetMsgdef(self);
1360 const upb_DefPool* ext_pool = upb_FileDef_Pool(upb_MessageDef_File(msgdef));
1361 upb_FieldPathEntry* fields;
1362 PyObject* ret = PyList_New(0);
1363 if (upb_util_HasUnsetRequired(msg, msgdef, ext_pool, &fields)) {
1364 char* buf = NULL;
1365 size_t size = 0;
1366 assert(fields->field);
1367 while (fields->field) {
1368 upb_FieldPathEntry* field = fields;
1369 size_t need = upb_FieldPath_ToText(&fields, buf, size);
1370 if (need >= size) {
1371 fields = field;
1372 size = size ? size * 2 : 16;
1373 while (size <= need) size *= 2;
1374 buf = realloc(buf, size);
1375 need = upb_FieldPath_ToText(&fields, buf, size);
1376 assert(size > need);
1377 }
1378 PyObject* str = PyUnicode_FromString(buf);
1379 PyList_Append(ret, str);
1380 Py_DECREF(str);
1381 }
1382 free(buf);
1383 }
1384 return ret;
1385 }
1386
1387 static PyObject* PyUpb_Message_FromString(PyObject* cls, PyObject* serialized) {
1388 PyObject* ret = NULL;
1389 PyObject* length = NULL;
1390
1391 ret = PyObject_CallObject(cls, NULL);
1392 if (ret == NULL) goto err;
1393 length = PyUpb_Message_MergeFromString(ret, serialized);
1394 if (length == NULL) goto err;
1395
1396 done:
1397 Py_XDECREF(length);
1398 return ret;
1399
1400 err:
1401 Py_XDECREF(ret);
1402 ret = NULL;
1403 goto done;
1404 }
1405
1406 const upb_FieldDef* PyUpb_Message_GetExtensionDef(PyObject* _self,
1407 PyObject* key) {
1408 const upb_FieldDef* f = PyUpb_FieldDescriptor_GetDef(key);
1409 if (!f) {
1410 PyErr_Clear();
1411 PyErr_Format(PyExc_KeyError, "Object %R is not a field descriptor\n", key);
1412 return NULL;
1413 }
1414 if (!upb_FieldDef_IsExtension(f)) {
1415 PyErr_Format(PyExc_KeyError, "Field %s is not an extension\n",
1416 upb_FieldDef_FullName(f));
1417 return NULL;
1418 }
1419 const upb_MessageDef* msgdef = PyUpb_Message_GetMsgdef(_self);
1420 if (upb_FieldDef_ContainingType(f) != msgdef) {
1421 PyErr_Format(PyExc_KeyError, "Extension doesn't match (%s vs %s)",
1422 upb_MessageDef_FullName(msgdef), upb_FieldDef_FullName(f));
1423 return NULL;
1424 }
1425 return f;
1426 }
1427
1428 static PyObject* PyUpb_Message_HasExtension(PyObject* _self,
1429 PyObject* ext_desc) {
1430 upb_Message* msg = PyUpb_Message_GetIfReified(_self);
1431 const upb_FieldDef* f = PyUpb_Message_GetExtensionDef(_self, ext_desc);
1432 if (!f) return NULL;
1433 if (upb_FieldDef_IsRepeated(f)) {
1434 PyErr_SetString(PyExc_KeyError,
1435 "Field is repeated. A singular method is required.");
1436 return NULL;
1437 }
1438 if (!msg) Py_RETURN_FALSE;
1439 return PyBool_FromLong(upb_Message_Has(msg, f));
1440 }
1441
1442 void PyUpb_Message_ReportInitializationErrors(const upb_MessageDef* msgdef,
1443 PyObject* errors, PyObject* exc) {
1444 PyObject* comma = PyUnicode_FromString(",");
1445 PyObject* missing_fields = NULL;
1446 if (!comma) goto done;
1447 missing_fields = PyUnicode_Join(comma, errors);
1448 if (!missing_fields) goto done;
1449 PyErr_Format(exc, "Message %s is missing required fields: %U",
1450 upb_MessageDef_FullName(msgdef), missing_fields);
1451 done:
1452 Py_XDECREF(comma);
1453 Py_XDECREF(missing_fields);
1454 Py_DECREF(errors);
1455 }
1456
1457 PyObject* PyUpb_Message_SerializeInternal(PyObject* _self, PyObject* args,
1458 PyObject* kwargs,
1459 bool check_required) {
1460 PyUpb_Message* self = (void*)_self;
1461 if (!PyUpb_Message_Verify((PyObject*)self)) return NULL;
1462 static const char* kwlist[] = {"deterministic", NULL};
1463 int deterministic = 0;
1464 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|p", (char**)(kwlist),
1465 &deterministic)) {
1466 return NULL;
1467 }
1468
1469 const upb_MessageDef* msgdef = _PyUpb_Message_GetMsgdef(self);
1470 if (PyUpb_Message_IsStub(self)) {
1471 // Nothing to serialize, but we do have to check whether the message is
1472 // initialized.
1473 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
1474 PyObject* errors = PyUpb_Message_FindInitializationErrors(_self, NULL);
1475 if (!errors) return NULL;
1476 if (PyList_Size(errors) == 0) {
1477 Py_DECREF(errors);
1478 return PyBytes_FromStringAndSize(NULL, 0);
1479 }
1480 PyUpb_Message_ReportInitializationErrors(msgdef, errors,
1481 state->encode_error_class);
1482 return NULL;
1483 }
1484
1485 upb_Arena* arena = upb_Arena_New();
1486 const upb_MiniTable* layout = upb_MessageDef_MiniTable(msgdef);
1487 size_t size = 0;
1488 // Python does not currently have any effective limit on serialization depth.
1489 int options = UPB_ENCODE_MAXDEPTH(UINT32_MAX);
1490 if (check_required) options |= kUpb_EncodeOption_CheckRequired;
1491 if (deterministic) options |= kUpb_EncodeOption_Deterministic;
1492 char* pb;
1493 upb_EncodeStatus status =
1494 upb_Encode(self->ptr.msg, layout, options, arena, &pb, &size);
1495 PyObject* ret = NULL;
1496
1497 if (status != kUpb_EncodeStatus_Ok) {
1498 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
1499 PyObject* errors = PyUpb_Message_FindInitializationErrors(_self, NULL);
1500 if (PyList_Size(errors) != 0) {
1501 PyUpb_Message_ReportInitializationErrors(msgdef, errors,
1502 state->encode_error_class);
1503 } else {
1504 PyErr_Format(state->encode_error_class, "Failed to serialize proto");
1505 }
1506 goto done;
1507 }
1508
1509 ret = PyBytes_FromStringAndSize(pb, size);
1510
1511 done:
1512 upb_Arena_Free(arena);
1513 return ret;
1514 }
1515
1516 PyObject* PyUpb_Message_SerializeToString(PyObject* _self, PyObject* args,
1517 PyObject* kwargs) {
1518 return PyUpb_Message_SerializeInternal(_self, args, kwargs, true);
1519 }
1520
1521 PyObject* PyUpb_Message_SerializePartialToString(PyObject* _self,
1522 PyObject* args,
1523 PyObject* kwargs) {
1524 return PyUpb_Message_SerializeInternal(_self, args, kwargs, false);
1525 }
1526
1527 static PyObject* PyUpb_Message_WhichOneof(PyObject* _self, PyObject* name) {
1528 PyUpb_Message* self = (void*)_self;
1529 const upb_OneofDef* o;
1530 if (!PyUpb_Message_LookupName(self, name, NULL, &o, PyExc_ValueError)) {
1531 return NULL;
1532 }
1533 upb_Message* msg = PyUpb_Message_GetIfReified(_self);
1534 if (!msg) Py_RETURN_NONE;
1535 const upb_FieldDef* f = upb_Message_WhichOneof(msg, o);
1536 if (!f) Py_RETURN_NONE;
1537 return PyUnicode_FromString(upb_FieldDef_Name(f));
1538 }
1539
1540 void PyUpb_Message_ClearExtensionDict(PyObject* _self) {
1541 PyUpb_Message* self = (void*)_self;
1542 assert(self->ext_dict);
1543 self->ext_dict = NULL;
1544 }
1545
1546 static PyObject* PyUpb_Message_GetExtensionDict(PyObject* _self,
1547 void* closure) {
1548 PyUpb_Message* self = (void*)_self;
1549 if (self->ext_dict) {
1550 Py_INCREF(self->ext_dict);
1551 return self->ext_dict;
1552 }
1553
1554 const upb_MessageDef* m = _PyUpb_Message_GetMsgdef(self);
1555 if (upb_MessageDef_ExtensionRangeCount(m) == 0) {
1556 PyErr_SetNone(PyExc_AttributeError);
1557 return NULL;
1558 }
1559
1560 self->ext_dict = PyUpb_ExtensionDict_New(_self);
1561 return self->ext_dict;
1562 }
1563
1564 static PyGetSetDef PyUpb_Message_Getters[] = {
1565 {"Extensions", PyUpb_Message_GetExtensionDict, NULL, "Extension dict"},
1566 {NULL}};
1567
1568 static PyMethodDef PyUpb_Message_Methods[] = {
1569 // TODO(https://github.com/protocolbuffers/upb/issues/459)
1570 //{ "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
1571 // "Makes a deep copy of the class." },
1572 //{ "__unicode__", (PyCFunction)ToUnicode, METH_NOARGS,
1573 // "Outputs a unicode representation of the message." },
1574 {"ByteSize", (PyCFunction)PyUpb_Message_ByteSize, METH_NOARGS,
1575 "Returns the size of the message in bytes."},
1576 {"Clear", (PyCFunction)PyUpb_Message_Clear, METH_NOARGS,
1577 "Clears the message."},
1578 {"ClearExtension", PyUpb_Message_ClearExtension, METH_O,
1579 "Clears a message field."},
1580 {"ClearField", PyUpb_Message_ClearField, METH_O, "Clears a message field."},
1581 // TODO(https://github.com/protocolbuffers/upb/issues/459)
1582 //{ "CopyFrom", (PyCFunction)CopyFrom, METH_O,
1583 // "Copies a protocol message into the current message." },
1584 {"DiscardUnknownFields", (PyCFunction)PyUpb_Message_DiscardUnknownFields,
1585 METH_NOARGS, "Discards the unknown fields."},
1586 {"FindInitializationErrors", PyUpb_Message_FindInitializationErrors,
1587 METH_NOARGS, "Finds unset required fields."},
1588 {"FromString", PyUpb_Message_FromString, METH_O | METH_CLASS,
1589 "Creates new method instance from given serialized data."},
1590 {"HasExtension", PyUpb_Message_HasExtension, METH_O,
1591 "Checks if a message field is set."},
1592 {"HasField", PyUpb_Message_HasField, METH_O,
1593 "Checks if a message field is set."},
1594 {"IsInitialized", PyUpb_Message_IsInitialized, METH_VARARGS,
1595 "Checks if all required fields of a protocol message are set."},
1596 {"ListFields", PyUpb_Message_ListFields, METH_NOARGS,
1597 "Lists all set fields of a message."},
1598 {"MergeFrom", PyUpb_Message_MergeFrom, METH_O,
1599 "Merges a protocol message into the current message."},
1600 {"MergeFromString", PyUpb_Message_MergeFromString, METH_O,
1601 "Merges a serialized message into the current message."},
1602 {"ParseFromString", PyUpb_Message_ParseFromString, METH_O,
1603 "Parses a serialized message into the current message."},
1604 // TODO(https://github.com/protocolbuffers/upb/issues/459)
1605 //{ "RegisterExtension", (PyCFunction)RegisterExtension, METH_O |
1606 // METH_CLASS,
1607 // "Registers an extension with the current message." },
1608 {"SerializePartialToString",
1609 (PyCFunction)PyUpb_Message_SerializePartialToString,
1610 METH_VARARGS | METH_KEYWORDS,
1611 "Serializes the message to a string, even if it isn't initialized."},
1612 {"SerializeToString", (PyCFunction)PyUpb_Message_SerializeToString,
1613 METH_VARARGS | METH_KEYWORDS,
1614 "Serializes the message to a string, only for initialized messages."},
1615 {"SetInParent", (PyCFunction)PyUpb_Message_SetInParent, METH_NOARGS,
1616 "Sets the has bit of the given field in its parent message."},
1617 {"UnknownFields", (PyCFunction)PyUpb_Message_UnknownFields, METH_NOARGS,
1618 "Parse unknown field set"},
1619 {"WhichOneof", PyUpb_Message_WhichOneof, METH_O,
1620 "Returns the name of the field set inside a oneof, "
1621 "or None if no field is set."},
1622 {"_ListFieldsItemKey", PyUpb_Message_ListFieldsItemKey,
1623 METH_O | METH_STATIC,
1624 "Compares ListFields() list entries by field number"},
1625 {"_CheckCalledFromGeneratedFile",
1626 PyUpb_Message_CheckCalledFromGeneratedFile, METH_NOARGS | METH_STATIC,
1627 "Raises TypeError if the caller is not in a _pb2.py file."},
1628 {NULL, NULL}};
1629
1630 static PyType_Slot PyUpb_Message_Slots[] = {
1631 {Py_tp_dealloc, PyUpb_Message_Dealloc},
1632 {Py_tp_doc, "A ProtocolMessage"},
1633 {Py_tp_getattro, PyUpb_Message_GetAttr},
1634 {Py_tp_getset, PyUpb_Message_Getters},
1635 {Py_tp_hash, PyObject_HashNotImplemented},
1636 {Py_tp_methods, PyUpb_Message_Methods},
1637 {Py_tp_new, PyUpb_Message_New},
1638 {Py_tp_str, PyUpb_Message_ToString},
1639 {Py_tp_repr, PyUpb_Message_ToString},
1640 {Py_tp_richcompare, PyUpb_Message_RichCompare},
1641 {Py_tp_setattro, PyUpb_Message_SetAttr},
1642 {Py_tp_init, PyUpb_Message_Init},
1643 {0, NULL}};
1644
1645 PyType_Spec PyUpb_Message_Spec = {
1646 PYUPB_MODULE_NAME ".Message", // tp_name
1647 sizeof(PyUpb_Message), // tp_basicsize
1648 0, // tp_itemsize
1649 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
1650 PyUpb_Message_Slots,
1651 };
1652
1653 // -----------------------------------------------------------------------------
1654 // MessageMeta
1655 // -----------------------------------------------------------------------------
1656
1657 // MessageMeta is the metaclass for message objects. The generated code uses it
1658 // to construct message classes, ie.
1659 //
1660 // FooMessage = _message.MessageMeta('FooMessage', (_message.Message), {...})
1661 //
1662 // (This is not quite true: at the moment the Python library subclasses
1663 // MessageMeta, and uses that subclass as the metaclass. There is a TODO below
1664 // to simplify this, so that the illustration above is indeed accurate).
1665
1666 typedef struct {
1667 const upb_MiniTable* layout;
1668 PyObject* py_message_descriptor;
1669 } PyUpb_MessageMeta;
1670
1671 // The PyUpb_MessageMeta struct is trailing data tacked onto the end of
1672 // MessageMeta instances. This means that we get our instances of this struct
1673 // by adding the appropriate number of bytes.
1674 static PyUpb_MessageMeta* PyUpb_GetMessageMeta(PyObject* cls) {
1675 #ifndef NDEBUG
1676 PyUpb_ModuleState* state = PyUpb_ModuleState_MaybeGet();
1677 assert(!state || cls->ob_type == state->message_meta_type);
1678 #endif
1679 return (PyUpb_MessageMeta*)((char*)cls + cpython_bits.type_basicsize);
1680 }
1681
1682 static const upb_MessageDef* PyUpb_MessageMeta_GetMsgdef(PyObject* cls) {
1683 PyUpb_MessageMeta* self = PyUpb_GetMessageMeta(cls);
1684 return PyUpb_Descriptor_GetDef(self->py_message_descriptor);
1685 }
1686
1687 PyObject* PyUpb_MessageMeta_DoCreateClass(PyObject* py_descriptor,
1688 const char* name, PyObject* dict) {
1689 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
1690 PyTypeObject* descriptor_type = state->descriptor_types[kPyUpb_Descriptor];
1691 if (!PyObject_TypeCheck(py_descriptor, descriptor_type)) {
1692 return PyErr_Format(PyExc_TypeError, "Expected a message Descriptor");
1693 }
1694
1695 const upb_MessageDef* msgdef = PyUpb_Descriptor_GetDef(py_descriptor);
1696 assert(msgdef);
1697 assert(!PyUpb_ObjCache_Get(upb_MessageDef_MiniTable(msgdef)));
1698
1699 PyObject* slots = PyTuple_New(0);
1700 if (!slots) return NULL;
1701 int status = PyDict_SetItemString(dict, "__slots__", slots);
1702 Py_DECREF(slots);
1703 if (status < 0) return NULL;
1704
1705 // Bases are either:
1706 // (Message, Message) # for regular messages
1707 // (Message, Message, WktBase) # For well-known types
1708 PyObject* wkt_bases = PyUpb_GetWktBases(state);
1709 PyObject* wkt_base =
1710 PyDict_GetItemString(wkt_bases, upb_MessageDef_FullName(msgdef));
1711 PyObject* args;
1712 if (wkt_base == NULL) {
1713 args = Py_BuildValue("s(OO)O", name, state->cmessage_type,
1714 state->message_class, dict);
1715 } else {
1716 args = Py_BuildValue("s(OOO)O", name, state->cmessage_type,
1717 state->message_class, wkt_base, dict);
1718 }
1719
1720 PyObject* ret = cpython_bits.type_new(state->message_meta_type, args, NULL);
1721 Py_DECREF(args);
1722 if (!ret) return NULL;
1723
1724 PyUpb_MessageMeta* meta = PyUpb_GetMessageMeta(ret);
1725 meta->py_message_descriptor = py_descriptor;
1726 meta->layout = upb_MessageDef_MiniTable(msgdef);
1727 Py_INCREF(meta->py_message_descriptor);
1728
1729 PyUpb_ObjCache_Add(meta->layout, ret);
1730
1731 return ret;
1732 }
1733
1734 static PyObject* PyUpb_MessageMeta_New(PyTypeObject* type, PyObject* args,
1735 PyObject* kwargs) {
1736 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
1737 static const char* kwlist[] = {"name", "bases", "dict", 0};
1738 PyObject *bases, *dict;
1739 const char* name;
1740
1741 // Check arguments: (name, bases, dict)
1742 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO!O!:type", (char**)kwlist,
1743 &name, &PyTuple_Type, &bases, &PyDict_Type,
1744 &dict)) {
1745 return NULL;
1746 }
1747
1748 // Check bases: only (), or (message.Message,) are allowed
1749 Py_ssize_t size = PyTuple_Size(bases);
1750 if (!(size == 0 ||
1751 (size == 1 && PyTuple_GetItem(bases, 0) == state->message_class))) {
1752 PyErr_Format(PyExc_TypeError,
1753 "A Message class can only inherit from Message, not %S",
1754 bases);
1755 return NULL;
1756 }
1757
1758 // Check dict['DESCRIPTOR']
1759 PyObject* py_descriptor = PyDict_GetItemString(dict, "DESCRIPTOR");
1760 if (py_descriptor == NULL) {
1761 PyErr_SetString(PyExc_TypeError, "Message class has no DESCRIPTOR");
1762 return NULL;
1763 }
1764
1765 const upb_MessageDef* m = PyUpb_Descriptor_GetDef(py_descriptor);
1766 PyObject* ret = PyUpb_ObjCache_Get(upb_MessageDef_MiniTable(m));
1767 if (ret) return ret;
1768 return PyUpb_MessageMeta_DoCreateClass(py_descriptor, name, dict);
1769 }
1770
1771 static void PyUpb_MessageMeta_Dealloc(PyObject* self) {
1772 PyUpb_MessageMeta* meta = PyUpb_GetMessageMeta(self);
1773 PyUpb_ObjCache_Delete(meta->layout);
1774 Py_DECREF(meta->py_message_descriptor);
1775 PyTypeObject* tp = Py_TYPE(self);
1776 cpython_bits.type_dealloc(self);
1777 Py_DECREF(tp);
1778 }
1779
1780 void PyUpb_MessageMeta_AddFieldNumber(PyObject* self, const upb_FieldDef* f) {
1781 PyObject* name =
1782 PyUnicode_FromFormat("%s_FIELD_NUMBER", upb_FieldDef_Name(f));
1783 PyObject* upper = PyObject_CallMethod(name, "upper", "");
1784 PyObject_SetAttr(self, upper, PyLong_FromLong(upb_FieldDef_Number(f)));
1785 Py_DECREF(name);
1786 Py_DECREF(upper);
1787 }
1788
1789 static PyObject* PyUpb_MessageMeta_GetDynamicAttr(PyObject* self,
1790 PyObject* name) {
1791 const char* name_buf = PyUpb_GetStrData(name);
1792 if (!name_buf) return NULL;
1793 const upb_MessageDef* msgdef = PyUpb_MessageMeta_GetMsgdef(self);
1794 const upb_FileDef* filedef = upb_MessageDef_File(msgdef);
1795 const upb_DefPool* symtab = upb_FileDef_Pool(filedef);
1796
1797 PyObject* py_key =
1798 PyBytes_FromFormat("%s.%s", upb_MessageDef_FullName(msgdef), name_buf);
1799 const char* key = PyUpb_GetStrData(py_key);
1800 PyObject* ret = NULL;
1801 const upb_MessageDef* nested = upb_DefPool_FindMessageByName(symtab, key);
1802 const upb_EnumDef* enumdef;
1803 const upb_EnumValueDef* enumval;
1804 const upb_FieldDef* ext;
1805
1806 if (nested) {
1807 ret = PyUpb_Descriptor_GetClass(nested);
1808 } else if ((enumdef = upb_DefPool_FindEnumByName(symtab, key))) {
1809 PyUpb_ModuleState* state = PyUpb_ModuleState_Get();
1810 PyObject* klass = state->enum_type_wrapper_class;
1811 ret = PyUpb_EnumDescriptor_Get(enumdef);
1812 ret = PyObject_CallFunctionObjArgs(klass, ret, NULL);
1813 } else if ((enumval = upb_DefPool_FindEnumByNameval(symtab, key))) {
1814 ret = PyLong_FromLong(upb_EnumValueDef_Number(enumval));
1815 } else if ((ext = upb_DefPool_FindExtensionByName(symtab, key))) {
1816 ret = PyUpb_FieldDescriptor_Get(ext);
1817 }
1818
1819 Py_DECREF(py_key);
1820
1821 const char* suffix = "_FIELD_NUMBER";
1822 size_t n = strlen(name_buf);
1823 size_t suffix_n = strlen(suffix);
1824 if (n > suffix_n && memcmp(suffix, name_buf + n - suffix_n, suffix_n) == 0) {
1825 // We can't look up field names dynamically, because the <NAME>_FIELD_NUMBER
1826 // naming scheme upper-cases the field name and is therefore non-reversible.
1827 // So we just add all field numbers.
1828 int n = upb_MessageDef_FieldCount(msgdef);
1829 for (int i = 0; i < n; i++) {
1830 PyUpb_MessageMeta_AddFieldNumber(self, upb_MessageDef_Field(msgdef, i));
1831 }
1832 n = upb_MessageDef_NestedExtensionCount(msgdef);
1833 for (int i = 0; i < n; i++) {
1834 PyUpb_MessageMeta_AddFieldNumber(
1835 self, upb_MessageDef_NestedExtension(msgdef, i));
1836 }
1837 ret = PyObject_GenericGetAttr(self, name);
1838 }
1839
1840 return ret;
1841 }
1842
1843 static PyObject* PyUpb_MessageMeta_GetAttr(PyObject* self, PyObject* name) {
1844 // We want to first delegate to the type's tp_dict to retrieve any attributes
1845 // that were previously calculated and cached in the type's dict.
1846 PyObject* ret = cpython_bits.type_getattro(self, name);
1847 if (ret) return ret;
1848
1849 // We did not find a cached attribute. Try to calculate the attribute
1850 // dynamically, using the descriptor as an argument.
1851 PyErr_Clear();
1852 ret = PyUpb_MessageMeta_GetDynamicAttr(self, name);
1853
1854 if (ret) {
1855 PyObject_SetAttr(self, name, ret);
1856 PyErr_Clear();
1857 return ret;
1858 }
1859
1860 PyErr_SetObject(PyExc_AttributeError, name);
1861 return NULL;
1862 }
1863
1864 static PyType_Slot PyUpb_MessageMeta_Slots[] = {
1865 {Py_tp_new, PyUpb_MessageMeta_New},
1866 {Py_tp_dealloc, PyUpb_MessageMeta_Dealloc},
1867 {Py_tp_getattro, PyUpb_MessageMeta_GetAttr},
1868 {0, NULL}};
1869
1870 static PyType_Spec PyUpb_MessageMeta_Spec = {
1871 PYUPB_MODULE_NAME ".MessageMeta", // tp_name
1872 0, // To be filled in by size of base // tp_basicsize
1873 0, // tp_itemsize
1874 // TODO(haberman): remove BASETYPE, Python should just use MessageMeta
1875 // directly instead of subclassing it.
1876 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
1877 PyUpb_MessageMeta_Slots,
1878 };
1879
1880 static PyObject* PyUpb_MessageMeta_CreateType(void) {
1881 PyObject* bases = Py_BuildValue("(O)", &PyType_Type);
1882 if (!bases) return NULL;
1883 PyUpb_MessageMeta_Spec.basicsize =
1884 cpython_bits.type_basicsize + sizeof(PyUpb_MessageMeta);
1885 PyObject* type = PyType_FromSpecWithBases(&PyUpb_MessageMeta_Spec, bases);
1886 Py_DECREF(bases);
1887 return type;
1888 }
1889
1890 bool PyUpb_InitMessage(PyObject* m) {
1891 if (!PyUpb_CPythonBits_Init(&cpython_bits)) return false;
1892 PyObject* message_meta_type = PyUpb_MessageMeta_CreateType();
1893
1894 PyUpb_ModuleState* state = PyUpb_ModuleState_GetFromModule(m);
1895 state->cmessage_type = PyUpb_AddClass(m, &PyUpb_Message_Spec);
1896 state->message_meta_type = (PyTypeObject*)message_meta_type;
1897
1898 if (!state->cmessage_type || !state->message_meta_type) return false;
1899 if (PyModule_AddObject(m, "MessageMeta", message_meta_type)) return false;
1900 state->listfields_item_key = PyObject_GetAttrString(
1901 (PyObject*)state->cmessage_type, "_ListFieldsItemKey");
1902
1903 PyObject* mod =
1904 PyImport_ImportModule(PYUPB_PROTOBUF_PUBLIC_PACKAGE ".message");
1905 if (mod == NULL) return false;
1906
1907 state->encode_error_class = PyObject_GetAttrString(mod, "EncodeError");
1908 state->decode_error_class = PyObject_GetAttrString(mod, "DecodeError");
1909 state->message_class = PyObject_GetAttrString(mod, "Message");
1910 Py_DECREF(mod);
1911
1912 PyObject* enum_type_wrapper = PyImport_ImportModule(
1913 PYUPB_PROTOBUF_INTERNAL_PACKAGE ".enum_type_wrapper");
1914 if (enum_type_wrapper == NULL) return false;
1915
1916 state->enum_type_wrapper_class =
1917 PyObject_GetAttrString(enum_type_wrapper, "EnumTypeWrapper");
1918 Py_DECREF(enum_type_wrapper);
1919
1920 if (!state->encode_error_class || !state->decode_error_class ||
1921 !state->message_class || !state->listfields_item_key ||
1922 !state->enum_type_wrapper_class) {
1923 return false;
1924 }
1925
1926 return true;
1927 }