message.cc 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: anuraag@google.com (Anuraag Agrawal)
  31. // Author: tibell@google.com (Johan Tibell)
  32. #include <google/protobuf/pyext/message.h>
  33. #include <map>
  34. #include <memory>
  35. #ifndef _SHARED_PTR_H
  36. #include <google/protobuf/stubs/shared_ptr.h>
  37. #endif
  38. #include <string>
  39. #include <vector>
  40. #include <structmember.h> // A Python header file.
  41. #ifndef PyVarObject_HEAD_INIT
  42. #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
  43. #endif
  44. #ifndef Py_TYPE
  45. #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
  46. #endif
  47. #include <google/protobuf/descriptor.pb.h>
  48. #include <google/protobuf/stubs/common.h>
  49. #include <google/protobuf/stubs/logging.h>
  50. #include <google/protobuf/io/coded_stream.h>
  51. #include <google/protobuf/util/message_differencer.h>
  52. #include <google/protobuf/descriptor.h>
  53. #include <google/protobuf/message.h>
  54. #include <google/protobuf/text_format.h>
  55. #include <google/protobuf/unknown_field_set.h>
  56. #include <google/protobuf/pyext/descriptor.h>
  57. #include <google/protobuf/pyext/descriptor_pool.h>
  58. #include <google/protobuf/pyext/extension_dict.h>
  59. #include <google/protobuf/pyext/repeated_composite_container.h>
  60. #include <google/protobuf/pyext/repeated_scalar_container.h>
  61. #include <google/protobuf/pyext/map_container.h>
  62. #include <google/protobuf/pyext/message_factory.h>
  63. #include <google/protobuf/pyext/safe_numerics.h>
  64. #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
  65. #include <google/protobuf/stubs/strutil.h>
  66. #if PY_MAJOR_VERSION >= 3
  67. #define PyInt_AsLong PyLong_AsLong
  68. #define PyInt_FromLong PyLong_FromLong
  69. #define PyInt_FromSize_t PyLong_FromSize_t
  70. #define PyString_Check PyUnicode_Check
  71. #define PyString_FromString PyUnicode_FromString
  72. #define PyString_FromStringAndSize PyUnicode_FromStringAndSize
  73. #if PY_VERSION_HEX < 0x03030000
  74. #error "Python 3.0 - 3.2 are not supported."
  75. #else
  76. #define PyString_AsString(ob) \
  77. (PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AsString(ob))
  78. #define PyString_AsStringAndSize(ob, charpp, sizep) \
  79. (PyUnicode_Check(ob)? \
  80. ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
  81. PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
  82. #endif
  83. #endif
  84. namespace google {
  85. namespace protobuf {
  86. namespace python {
  87. static PyObject* kDESCRIPTOR;
  88. PyObject* EnumTypeWrapper_class;
  89. static PyObject* PythonMessage_class;
  90. static PyObject* kEmptyWeakref;
  91. static PyObject* WKT_classes = NULL;
  92. namespace message_meta {
  93. static int InsertEmptyWeakref(PyTypeObject* base);
  94. // Add the number of a field descriptor to the containing message class.
  95. // Equivalent to:
  96. // _cls.<field>_FIELD_NUMBER = <number>
  97. static bool AddFieldNumberToClass(
  98. PyObject* cls, const FieldDescriptor* field_descriptor) {
  99. string constant_name = field_descriptor->name() + "_FIELD_NUMBER";
  100. UpperString(&constant_name);
  101. ScopedPyObjectPtr attr_name(PyString_FromStringAndSize(
  102. constant_name.c_str(), constant_name.size()));
  103. if (attr_name == NULL) {
  104. return false;
  105. }
  106. ScopedPyObjectPtr number(PyInt_FromLong(field_descriptor->number()));
  107. if (number == NULL) {
  108. return false;
  109. }
  110. if (PyObject_SetAttr(cls, attr_name.get(), number.get()) == -1) {
  111. return false;
  112. }
  113. return true;
  114. }
  115. // Finalize the creation of the Message class.
  116. static int AddDescriptors(PyObject* cls, const Descriptor* descriptor) {
  117. // For each field set: cls.<field>_FIELD_NUMBER = <number>
  118. for (int i = 0; i < descriptor->field_count(); ++i) {
  119. if (!AddFieldNumberToClass(cls, descriptor->field(i))) {
  120. return -1;
  121. }
  122. }
  123. // For each enum set cls.<enum name> = EnumTypeWrapper(<enum descriptor>).
  124. for (int i = 0; i < descriptor->enum_type_count(); ++i) {
  125. const EnumDescriptor* enum_descriptor = descriptor->enum_type(i);
  126. ScopedPyObjectPtr enum_type(
  127. PyEnumDescriptor_FromDescriptor(enum_descriptor));
  128. if (enum_type == NULL) {
  129. return -1;
  130. }
  131. // Add wrapped enum type to message class.
  132. ScopedPyObjectPtr wrapped(PyObject_CallFunctionObjArgs(
  133. EnumTypeWrapper_class, enum_type.get(), NULL));
  134. if (wrapped == NULL) {
  135. return -1;
  136. }
  137. if (PyObject_SetAttrString(
  138. cls, enum_descriptor->name().c_str(), wrapped.get()) == -1) {
  139. return -1;
  140. }
  141. // For each enum value add cls.<name> = <number>
  142. for (int j = 0; j < enum_descriptor->value_count(); ++j) {
  143. const EnumValueDescriptor* enum_value_descriptor =
  144. enum_descriptor->value(j);
  145. ScopedPyObjectPtr value_number(PyInt_FromLong(
  146. enum_value_descriptor->number()));
  147. if (value_number == NULL) {
  148. return -1;
  149. }
  150. if (PyObject_SetAttrString(cls, enum_value_descriptor->name().c_str(),
  151. value_number.get()) == -1) {
  152. return -1;
  153. }
  154. }
  155. }
  156. // For each extension set cls.<extension name> = <extension descriptor>.
  157. //
  158. // Extension descriptors come from
  159. // <message descriptor>.extensions_by_name[name]
  160. // which was defined previously.
  161. for (int i = 0; i < descriptor->extension_count(); ++i) {
  162. const google::protobuf::FieldDescriptor* field = descriptor->extension(i);
  163. ScopedPyObjectPtr extension_field(PyFieldDescriptor_FromDescriptor(field));
  164. if (extension_field == NULL) {
  165. return -1;
  166. }
  167. // Add the extension field to the message class.
  168. if (PyObject_SetAttrString(
  169. cls, field->name().c_str(), extension_field.get()) == -1) {
  170. return -1;
  171. }
  172. // For each extension set cls.<extension name>_FIELD_NUMBER = <number>.
  173. if (!AddFieldNumberToClass(cls, field)) {
  174. return -1;
  175. }
  176. }
  177. return 0;
  178. }
  179. static PyObject* New(PyTypeObject* type,
  180. PyObject* args, PyObject* kwargs) {
  181. static char *kwlist[] = {"name", "bases", "dict", 0};
  182. PyObject *bases, *dict;
  183. const char* name;
  184. // Check arguments: (name, bases, dict)
  185. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO!O!:type", kwlist,
  186. &name,
  187. &PyTuple_Type, &bases,
  188. &PyDict_Type, &dict)) {
  189. return NULL;
  190. }
  191. // Check bases: only (), or (message.Message,) are allowed
  192. if (!(PyTuple_GET_SIZE(bases) == 0 ||
  193. (PyTuple_GET_SIZE(bases) == 1 &&
  194. PyTuple_GET_ITEM(bases, 0) == PythonMessage_class))) {
  195. PyErr_SetString(PyExc_TypeError,
  196. "A Message class can only inherit from Message");
  197. return NULL;
  198. }
  199. // Check dict['DESCRIPTOR']
  200. PyObject* py_descriptor = PyDict_GetItem(dict, kDESCRIPTOR);
  201. if (py_descriptor == NULL) {
  202. PyErr_SetString(PyExc_TypeError, "Message class has no DESCRIPTOR");
  203. return NULL;
  204. }
  205. if (!PyObject_TypeCheck(py_descriptor, &PyMessageDescriptor_Type)) {
  206. PyErr_Format(PyExc_TypeError, "Expected a message Descriptor, got %s",
  207. py_descriptor->ob_type->tp_name);
  208. return NULL;
  209. }
  210. // Messages have no __dict__
  211. ScopedPyObjectPtr slots(PyTuple_New(0));
  212. if (PyDict_SetItemString(dict, "__slots__", slots.get()) < 0) {
  213. return NULL;
  214. }
  215. // Build the arguments to the base metaclass.
  216. // We change the __bases__ classes.
  217. ScopedPyObjectPtr new_args;
  218. const Descriptor* message_descriptor =
  219. PyMessageDescriptor_AsDescriptor(py_descriptor);
  220. if (message_descriptor == NULL) {
  221. return NULL;
  222. }
  223. if (WKT_classes == NULL) {
  224. ScopedPyObjectPtr well_known_types(PyImport_ImportModule(
  225. "google.protobuf.internal.well_known_types"));
  226. GOOGLE_DCHECK(well_known_types != NULL);
  227. WKT_classes = PyObject_GetAttrString(well_known_types.get(), "WKTBASES");
  228. GOOGLE_DCHECK(WKT_classes != NULL);
  229. }
  230. PyObject* well_known_class = PyDict_GetItemString(
  231. WKT_classes, message_descriptor->full_name().c_str());
  232. if (well_known_class == NULL) {
  233. new_args.reset(Py_BuildValue("s(OO)O", name, &CMessage_Type,
  234. PythonMessage_class, dict));
  235. } else {
  236. new_args.reset(Py_BuildValue("s(OOO)O", name, &CMessage_Type,
  237. PythonMessage_class, well_known_class, dict));
  238. }
  239. if (new_args == NULL) {
  240. return NULL;
  241. }
  242. // Call the base metaclass.
  243. ScopedPyObjectPtr result(PyType_Type.tp_new(type, new_args.get(), NULL));
  244. if (result == NULL) {
  245. return NULL;
  246. }
  247. CMessageClass* newtype = reinterpret_cast<CMessageClass*>(result.get());
  248. // Insert the empty weakref into the base classes.
  249. if (InsertEmptyWeakref(
  250. reinterpret_cast<PyTypeObject*>(PythonMessage_class)) < 0 ||
  251. InsertEmptyWeakref(&CMessage_Type) < 0) {
  252. return NULL;
  253. }
  254. // Cache the descriptor, both as Python object and as C++ pointer.
  255. const Descriptor* descriptor =
  256. PyMessageDescriptor_AsDescriptor(py_descriptor);
  257. if (descriptor == NULL) {
  258. return NULL;
  259. }
  260. Py_INCREF(py_descriptor);
  261. newtype->py_message_descriptor = py_descriptor;
  262. newtype->message_descriptor = descriptor;
  263. // TODO(amauryfa): Don't always use the canonical pool of the descriptor,
  264. // use the MessageFactory optionally passed in the class dict.
  265. PyDescriptorPool* py_descriptor_pool =
  266. GetDescriptorPool_FromPool(descriptor->file()->pool());
  267. if (py_descriptor_pool == NULL) {
  268. return NULL;
  269. }
  270. newtype->py_message_factory = py_descriptor_pool->py_message_factory;
  271. Py_INCREF(newtype->py_message_factory);
  272. // Register the message in the MessageFactory.
  273. // TODO(amauryfa): Move this call to MessageFactory.GetPrototype() when the
  274. // MessageFactory is fully implemented in C++.
  275. if (message_factory::RegisterMessageClass(newtype->py_message_factory,
  276. descriptor, newtype) < 0) {
  277. return NULL;
  278. }
  279. // Continue with type initialization: add other descriptors, enum values...
  280. if (AddDescriptors(result.get(), descriptor) < 0) {
  281. return NULL;
  282. }
  283. return result.release();
  284. }
  285. static void Dealloc(CMessageClass *self) {
  286. Py_XDECREF(self->py_message_descriptor);
  287. Py_XDECREF(self->py_message_factory);
  288. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  289. }
  290. // This function inserts and empty weakref at the end of the list of
  291. // subclasses for the main protocol buffer Message class.
  292. //
  293. // This eliminates a O(n^2) behaviour in the internal add_subclass
  294. // routine.
  295. static int InsertEmptyWeakref(PyTypeObject *base_type) {
  296. #if PY_MAJOR_VERSION >= 3
  297. // Python 3.4 has already included the fix for the issue that this
  298. // hack addresses. For further background and the fix please see
  299. // https://bugs.python.org/issue17936.
  300. return 0;
  301. #else
  302. PyObject *subclasses = base_type->tp_subclasses;
  303. if (subclasses && PyList_CheckExact(subclasses)) {
  304. return PyList_Append(subclasses, kEmptyWeakref);
  305. }
  306. return 0;
  307. #endif // PY_MAJOR_VERSION >= 3
  308. }
  309. // The _extensions_by_name dictionary is built on every access.
  310. // TODO(amauryfa): Migrate all users to pool.FindAllExtensions()
  311. static PyObject* GetExtensionsByName(CMessageClass *self, void *closure) {
  312. const PyDescriptorPool* pool = self->py_message_factory->pool;
  313. std::vector<const FieldDescriptor*> extensions;
  314. pool->pool->FindAllExtensions(self->message_descriptor, &extensions);
  315. ScopedPyObjectPtr result(PyDict_New());
  316. for (int i = 0; i < extensions.size(); i++) {
  317. ScopedPyObjectPtr extension(
  318. PyFieldDescriptor_FromDescriptor(extensions[i]));
  319. if (extension == NULL) {
  320. return NULL;
  321. }
  322. if (PyDict_SetItemString(result.get(), extensions[i]->full_name().c_str(),
  323. extension.get()) < 0) {
  324. return NULL;
  325. }
  326. }
  327. return result.release();
  328. }
  329. // The _extensions_by_number dictionary is built on every access.
  330. // TODO(amauryfa): Migrate all users to pool.FindExtensionByNumber()
  331. static PyObject* GetExtensionsByNumber(CMessageClass *self, void *closure) {
  332. const PyDescriptorPool* pool = self->py_message_factory->pool;
  333. std::vector<const FieldDescriptor*> extensions;
  334. pool->pool->FindAllExtensions(self->message_descriptor, &extensions);
  335. ScopedPyObjectPtr result(PyDict_New());
  336. for (int i = 0; i < extensions.size(); i++) {
  337. ScopedPyObjectPtr extension(
  338. PyFieldDescriptor_FromDescriptor(extensions[i]));
  339. if (extension == NULL) {
  340. return NULL;
  341. }
  342. ScopedPyObjectPtr number(PyInt_FromLong(extensions[i]->number()));
  343. if (number == NULL) {
  344. return NULL;
  345. }
  346. if (PyDict_SetItem(result.get(), number.get(), extension.get()) < 0) {
  347. return NULL;
  348. }
  349. }
  350. return result.release();
  351. }
  352. static PyGetSetDef Getters[] = {
  353. {"_extensions_by_name", (getter)GetExtensionsByName, NULL},
  354. {"_extensions_by_number", (getter)GetExtensionsByNumber, NULL},
  355. {NULL}
  356. };
  357. } // namespace message_meta
  358. PyTypeObject CMessageClass_Type = {
  359. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  360. FULL_MODULE_NAME ".MessageMeta", // tp_name
  361. sizeof(CMessageClass), // tp_basicsize
  362. 0, // tp_itemsize
  363. (destructor)message_meta::Dealloc, // tp_dealloc
  364. 0, // tp_print
  365. 0, // tp_getattr
  366. 0, // tp_setattr
  367. 0, // tp_compare
  368. 0, // tp_repr
  369. 0, // tp_as_number
  370. 0, // tp_as_sequence
  371. 0, // tp_as_mapping
  372. 0, // tp_hash
  373. 0, // tp_call
  374. 0, // tp_str
  375. 0, // tp_getattro
  376. 0, // tp_setattro
  377. 0, // tp_as_buffer
  378. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
  379. "The metaclass of ProtocolMessages", // tp_doc
  380. 0, // tp_traverse
  381. 0, // tp_clear
  382. 0, // tp_richcompare
  383. 0, // tp_weaklistoffset
  384. 0, // tp_iter
  385. 0, // tp_iternext
  386. 0, // tp_methods
  387. 0, // tp_members
  388. message_meta::Getters, // tp_getset
  389. 0, // tp_base
  390. 0, // tp_dict
  391. 0, // tp_descr_get
  392. 0, // tp_descr_set
  393. 0, // tp_dictoffset
  394. 0, // tp_init
  395. 0, // tp_alloc
  396. message_meta::New, // tp_new
  397. };
  398. static CMessageClass* CheckMessageClass(PyTypeObject* cls) {
  399. if (!PyObject_TypeCheck(cls, &CMessageClass_Type)) {
  400. PyErr_Format(PyExc_TypeError, "Class %s is not a Message", cls->tp_name);
  401. return NULL;
  402. }
  403. return reinterpret_cast<CMessageClass*>(cls);
  404. }
  405. static const Descriptor* GetMessageDescriptor(PyTypeObject* cls) {
  406. CMessageClass* type = CheckMessageClass(cls);
  407. if (type == NULL) {
  408. return NULL;
  409. }
  410. return type->message_descriptor;
  411. }
  412. // Forward declarations
  413. namespace cmessage {
  414. int InternalReleaseFieldByDescriptor(
  415. CMessage* self,
  416. const FieldDescriptor* field_descriptor,
  417. PyObject* composite_field);
  418. } // namespace cmessage
  419. // ---------------------------------------------------------------------
  420. // Visiting the composite children of a CMessage
  421. struct ChildVisitor {
  422. // Returns 0 on success, -1 on failure.
  423. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  424. return 0;
  425. }
  426. // Returns 0 on success, -1 on failure.
  427. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  428. return 0;
  429. }
  430. // Returns 0 on success, -1 on failure.
  431. int VisitCMessage(CMessage* cmessage,
  432. const FieldDescriptor* field_descriptor) {
  433. return 0;
  434. }
  435. };
  436. // Apply a function to a composite field. Does nothing if child is of
  437. // non-composite type.
  438. template<class Visitor>
  439. static int VisitCompositeField(const FieldDescriptor* descriptor,
  440. PyObject* child,
  441. Visitor visitor) {
  442. if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  443. if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  444. if (descriptor->is_map()) {
  445. MapContainer* container = reinterpret_cast<MapContainer*>(child);
  446. if (visitor.VisitMapContainer(container) == -1) {
  447. return -1;
  448. }
  449. } else {
  450. RepeatedCompositeContainer* container =
  451. reinterpret_cast<RepeatedCompositeContainer*>(child);
  452. if (visitor.VisitRepeatedCompositeContainer(container) == -1)
  453. return -1;
  454. }
  455. } else {
  456. RepeatedScalarContainer* container =
  457. reinterpret_cast<RepeatedScalarContainer*>(child);
  458. if (visitor.VisitRepeatedScalarContainer(container) == -1)
  459. return -1;
  460. }
  461. } else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  462. CMessage* cmsg = reinterpret_cast<CMessage*>(child);
  463. if (visitor.VisitCMessage(cmsg, descriptor) == -1)
  464. return -1;
  465. }
  466. // The ExtensionDict might contain non-composite fields, which we
  467. // skip here.
  468. return 0;
  469. }
  470. // Visit each composite field and extension field of this CMessage.
  471. // Returns -1 on error and 0 on success.
  472. template<class Visitor>
  473. int ForEachCompositeField(CMessage* self, Visitor visitor) {
  474. Py_ssize_t pos = 0;
  475. PyObject* key;
  476. PyObject* field;
  477. // Visit normal fields.
  478. if (self->composite_fields) {
  479. // Never use self->message in this function, it may be already freed.
  480. const Descriptor* message_descriptor =
  481. GetMessageDescriptor(Py_TYPE(self));
  482. while (PyDict_Next(self->composite_fields, &pos, &key, &field)) {
  483. Py_ssize_t key_str_size;
  484. char *key_str_data;
  485. if (PyString_AsStringAndSize(key, &key_str_data, &key_str_size) != 0)
  486. return -1;
  487. const string key_str(key_str_data, key_str_size);
  488. const FieldDescriptor* descriptor =
  489. message_descriptor->FindFieldByName(key_str);
  490. if (descriptor != NULL) {
  491. if (VisitCompositeField(descriptor, field, visitor) == -1)
  492. return -1;
  493. }
  494. }
  495. }
  496. // Visit extension fields.
  497. if (self->extensions != NULL) {
  498. pos = 0;
  499. while (PyDict_Next(self->extensions->values, &pos, &key, &field)) {
  500. const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key);
  501. if (descriptor == NULL)
  502. return -1;
  503. if (VisitCompositeField(descriptor, field, visitor) == -1)
  504. return -1;
  505. }
  506. }
  507. return 0;
  508. }
  509. // ---------------------------------------------------------------------
  510. PyObject* EncodeError_class;
  511. PyObject* DecodeError_class;
  512. PyObject* PickleError_class;
  513. /* Is 64bit */
  514. void FormatTypeError(PyObject* arg, char* expected_types) {
  515. PyObject* repr = PyObject_Repr(arg);
  516. if (repr) {
  517. PyErr_Format(PyExc_TypeError,
  518. "%.100s has type %.100s, but expected one of: %s",
  519. PyString_AsString(repr),
  520. Py_TYPE(arg)->tp_name,
  521. expected_types);
  522. Py_DECREF(repr);
  523. }
  524. }
  525. void OutOfRangeError(PyObject* arg) {
  526. PyObject *s = PyObject_Str(arg);
  527. if (s) {
  528. PyErr_Format(PyExc_ValueError,
  529. "Value out of range: %s",
  530. PyString_AsString(s));
  531. Py_DECREF(s);
  532. }
  533. }
  534. template<class RangeType, class ValueType>
  535. bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) {
  536. if GOOGLE_PREDICT_FALSE(value == -1 && PyErr_Occurred()) {
  537. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  538. // Replace it with the same ValueError as pure python protos instead of
  539. // the default one.
  540. PyErr_Clear();
  541. OutOfRangeError(arg);
  542. } // Otherwise propagate existing error.
  543. return false;
  544. }
  545. if GOOGLE_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value)) {
  546. OutOfRangeError(arg);
  547. return false;
  548. }
  549. return true;
  550. }
  551. template<class T>
  552. bool CheckAndGetInteger(PyObject* arg, T* value) {
  553. // The fast path.
  554. #if PY_MAJOR_VERSION < 3
  555. // For the typical case, offer a fast path.
  556. if GOOGLE_PREDICT_TRUE(PyInt_Check(arg)) {
  557. long int_result = PyInt_AsLong(arg);
  558. if GOOGLE_PREDICT_TRUE(IsValidNumericCast<T>(int_result)) {
  559. *value = static_cast<T>(int_result);
  560. return true;
  561. } else {
  562. OutOfRangeError(arg);
  563. return false;
  564. }
  565. }
  566. #endif
  567. // This effectively defines an integer as "an object that can be cast as
  568. // an integer and can be used as an ordinal number".
  569. // This definition includes everything that implements numbers.Integral
  570. // and shouldn't cast the net too wide.
  571. if GOOGLE_PREDICT_FALSE(!PyIndex_Check(arg)) {
  572. FormatTypeError(arg, "int, long");
  573. return false;
  574. }
  575. // Now we have an integral number so we can safely use PyLong_ functions.
  576. // We need to treat the signed and unsigned cases differently in case arg is
  577. // holding a value above the maximum for signed longs.
  578. if (std::numeric_limits<T>::min() == 0) {
  579. // Unsigned case.
  580. unsigned PY_LONG_LONG ulong_result;
  581. if (PyLong_Check(arg)) {
  582. ulong_result = PyLong_AsUnsignedLongLong(arg);
  583. } else {
  584. // Unlike PyLong_AsLongLong, PyLong_AsUnsignedLongLong is very
  585. // picky about the exact type.
  586. PyObject* casted = PyNumber_Long(arg);
  587. if GOOGLE_PREDICT_FALSE(casted == NULL) {
  588. // Propagate existing error.
  589. return false;
  590. }
  591. ulong_result = PyLong_AsUnsignedLongLong(casted);
  592. Py_DECREF(casted);
  593. }
  594. if (VerifyIntegerCastAndRange<T, unsigned PY_LONG_LONG>(arg,
  595. ulong_result)) {
  596. *value = static_cast<T>(ulong_result);
  597. } else {
  598. return false;
  599. }
  600. } else {
  601. // Signed case.
  602. PY_LONG_LONG long_result;
  603. PyNumberMethods *nb;
  604. if ((nb = arg->ob_type->tp_as_number) != NULL && nb->nb_int != NULL) {
  605. // PyLong_AsLongLong requires it to be a long or to have an __int__()
  606. // method.
  607. long_result = PyLong_AsLongLong(arg);
  608. } else {
  609. // Valid subclasses of numbers.Integral should have a __long__() method
  610. // so fall back to that.
  611. PyObject* casted = PyNumber_Long(arg);
  612. if GOOGLE_PREDICT_FALSE(casted == NULL) {
  613. // Propagate existing error.
  614. return false;
  615. }
  616. long_result = PyLong_AsLongLong(casted);
  617. Py_DECREF(casted);
  618. }
  619. if (VerifyIntegerCastAndRange<T, PY_LONG_LONG>(arg, long_result)) {
  620. *value = static_cast<T>(long_result);
  621. } else {
  622. return false;
  623. }
  624. }
  625. return true;
  626. }
  627. // These are referenced by repeated_scalar_container, and must
  628. // be explicitly instantiated.
  629. template bool CheckAndGetInteger<int32>(PyObject*, int32*);
  630. template bool CheckAndGetInteger<int64>(PyObject*, int64*);
  631. template bool CheckAndGetInteger<uint32>(PyObject*, uint32*);
  632. template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
  633. bool CheckAndGetDouble(PyObject* arg, double* value) {
  634. *value = PyFloat_AsDouble(arg);
  635. if GOOGLE_PREDICT_FALSE(*value == -1 && PyErr_Occurred()) {
  636. FormatTypeError(arg, "int, long, float");
  637. return false;
  638. }
  639. return true;
  640. }
  641. bool CheckAndGetFloat(PyObject* arg, float* value) {
  642. double double_value;
  643. if (!CheckAndGetDouble(arg, &double_value)) {
  644. return false;
  645. }
  646. *value = static_cast<float>(double_value);
  647. return true;
  648. }
  649. bool CheckAndGetBool(PyObject* arg, bool* value) {
  650. long long_value = PyInt_AsLong(arg);
  651. if (long_value == -1 && PyErr_Occurred()) {
  652. FormatTypeError(arg, "int, long, bool");
  653. return false;
  654. }
  655. *value = static_cast<bool>(long_value);
  656. return true;
  657. }
  658. // Checks whether the given object (which must be "bytes" or "unicode") contains
  659. // valid UTF-8.
  660. bool IsValidUTF8(PyObject* obj) {
  661. if (PyBytes_Check(obj)) {
  662. PyObject* unicode = PyUnicode_FromEncodedObject(obj, "utf-8", NULL);
  663. // Clear the error indicator; we report our own error when desired.
  664. PyErr_Clear();
  665. if (unicode) {
  666. Py_DECREF(unicode);
  667. return true;
  668. } else {
  669. return false;
  670. }
  671. } else {
  672. // Unicode object, known to be valid UTF-8.
  673. return true;
  674. }
  675. }
  676. bool AllowInvalidUTF8(const FieldDescriptor* field) { return false; }
  677. PyObject* CheckString(PyObject* arg, const FieldDescriptor* descriptor) {
  678. GOOGLE_DCHECK(descriptor->type() == FieldDescriptor::TYPE_STRING ||
  679. descriptor->type() == FieldDescriptor::TYPE_BYTES);
  680. if (descriptor->type() == FieldDescriptor::TYPE_STRING) {
  681. if (!PyBytes_Check(arg) && !PyUnicode_Check(arg)) {
  682. FormatTypeError(arg, "bytes, unicode");
  683. return NULL;
  684. }
  685. if (!IsValidUTF8(arg) && !AllowInvalidUTF8(descriptor)) {
  686. PyObject* repr = PyObject_Repr(arg);
  687. PyErr_Format(PyExc_ValueError,
  688. "%s has type str, but isn't valid UTF-8 "
  689. "encoding. Non-UTF-8 strings must be converted to "
  690. "unicode objects before being added.",
  691. PyString_AsString(repr));
  692. Py_DECREF(repr);
  693. return NULL;
  694. }
  695. } else if (!PyBytes_Check(arg)) {
  696. FormatTypeError(arg, "bytes");
  697. return NULL;
  698. }
  699. PyObject* encoded_string = NULL;
  700. if (descriptor->type() == FieldDescriptor::TYPE_STRING) {
  701. if (PyBytes_Check(arg)) {
  702. // The bytes were already validated as correctly encoded UTF-8 above.
  703. encoded_string = arg; // Already encoded.
  704. Py_INCREF(encoded_string);
  705. } else {
  706. encoded_string = PyUnicode_AsEncodedObject(arg, "utf-8", NULL);
  707. }
  708. } else {
  709. // In this case field type is "bytes".
  710. encoded_string = arg;
  711. Py_INCREF(encoded_string);
  712. }
  713. return encoded_string;
  714. }
  715. bool CheckAndSetString(
  716. PyObject* arg, Message* message,
  717. const FieldDescriptor* descriptor,
  718. const Reflection* reflection,
  719. bool append,
  720. int index) {
  721. ScopedPyObjectPtr encoded_string(CheckString(arg, descriptor));
  722. if (encoded_string.get() == NULL) {
  723. return false;
  724. }
  725. char* value;
  726. Py_ssize_t value_len;
  727. if (PyBytes_AsStringAndSize(encoded_string.get(), &value, &value_len) < 0) {
  728. return false;
  729. }
  730. string value_string(value, value_len);
  731. if (append) {
  732. reflection->AddString(message, descriptor, value_string);
  733. } else if (index < 0) {
  734. reflection->SetString(message, descriptor, value_string);
  735. } else {
  736. reflection->SetRepeatedString(message, descriptor, index, value_string);
  737. }
  738. return true;
  739. }
  740. PyObject* ToStringObject(const FieldDescriptor* descriptor, string value) {
  741. if (descriptor->type() != FieldDescriptor::TYPE_STRING) {
  742. return PyBytes_FromStringAndSize(value.c_str(), value.length());
  743. }
  744. PyObject* result = PyUnicode_DecodeUTF8(value.c_str(), value.length(), NULL);
  745. // If the string can't be decoded in UTF-8, just return a string object that
  746. // contains the raw bytes. This can't happen if the value was assigned using
  747. // the members of the Python message object, but can happen if the values were
  748. // parsed from the wire (binary).
  749. if (result == NULL) {
  750. PyErr_Clear();
  751. result = PyBytes_FromStringAndSize(value.c_str(), value.length());
  752. }
  753. return result;
  754. }
  755. bool CheckFieldBelongsToMessage(const FieldDescriptor* field_descriptor,
  756. const Message* message) {
  757. if (message->GetDescriptor() == field_descriptor->containing_type()) {
  758. return true;
  759. }
  760. PyErr_Format(PyExc_KeyError, "Field '%s' does not belong to message '%s'",
  761. field_descriptor->full_name().c_str(),
  762. message->GetDescriptor()->full_name().c_str());
  763. return false;
  764. }
  765. namespace cmessage {
  766. PyMessageFactory* GetFactoryForMessage(CMessage* message) {
  767. GOOGLE_DCHECK(PyObject_TypeCheck(message, &CMessage_Type));
  768. return reinterpret_cast<CMessageClass*>(Py_TYPE(message))->py_message_factory;
  769. }
  770. static int MaybeReleaseOverlappingOneofField(
  771. CMessage* cmessage,
  772. const FieldDescriptor* field) {
  773. #ifdef GOOGLE_PROTOBUF_HAS_ONEOF
  774. Message* message = cmessage->message;
  775. const Reflection* reflection = message->GetReflection();
  776. if (!field->containing_oneof() ||
  777. !reflection->HasOneof(*message, field->containing_oneof()) ||
  778. reflection->HasField(*message, field)) {
  779. // No other field in this oneof, no need to release.
  780. return 0;
  781. }
  782. const OneofDescriptor* oneof = field->containing_oneof();
  783. const FieldDescriptor* existing_field =
  784. reflection->GetOneofFieldDescriptor(*message, oneof);
  785. if (existing_field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
  786. // Non-message fields don't need to be released.
  787. return 0;
  788. }
  789. const char* field_name = existing_field->name().c_str();
  790. PyObject* child_message = cmessage->composite_fields ?
  791. PyDict_GetItemString(cmessage->composite_fields, field_name) : NULL;
  792. if (child_message == NULL) {
  793. // No python reference to this field so no need to release.
  794. return 0;
  795. }
  796. if (InternalReleaseFieldByDescriptor(
  797. cmessage, existing_field, child_message) < 0) {
  798. return -1;
  799. }
  800. return PyDict_DelItemString(cmessage->composite_fields, field_name);
  801. #else
  802. return 0;
  803. #endif
  804. }
  805. // ---------------------------------------------------------------------
  806. // Making a message writable
  807. static Message* GetMutableMessage(
  808. CMessage* parent,
  809. const FieldDescriptor* parent_field) {
  810. Message* parent_message = parent->message;
  811. const Reflection* reflection = parent_message->GetReflection();
  812. if (MaybeReleaseOverlappingOneofField(parent, parent_field) < 0) {
  813. return NULL;
  814. }
  815. return reflection->MutableMessage(
  816. parent_message, parent_field,
  817. GetFactoryForMessage(parent)->message_factory);
  818. }
  819. struct FixupMessageReference : public ChildVisitor {
  820. // message must outlive this object.
  821. explicit FixupMessageReference(Message* message) :
  822. message_(message) {}
  823. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  824. container->message = message_;
  825. return 0;
  826. }
  827. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  828. container->message = message_;
  829. return 0;
  830. }
  831. int VisitMapContainer(MapContainer* container) {
  832. container->message = message_;
  833. return 0;
  834. }
  835. private:
  836. Message* message_;
  837. };
  838. int AssureWritable(CMessage* self) {
  839. if (self == NULL || !self->read_only) {
  840. return 0;
  841. }
  842. if (self->parent == NULL) {
  843. // If parent is NULL but we are trying to modify a read-only message, this
  844. // is a reference to a constant default instance that needs to be replaced
  845. // with a mutable top-level message.
  846. self->message = self->message->New();
  847. self->owner.reset(self->message);
  848. // Cascade the new owner to eventual children: even if this message is
  849. // empty, some submessages or repeated containers might exist already.
  850. SetOwner(self, self->owner);
  851. } else {
  852. // Otherwise, we need a mutable child message.
  853. if (AssureWritable(self->parent) == -1)
  854. return -1;
  855. // Make self->message writable.
  856. Message* mutable_message = GetMutableMessage(
  857. self->parent,
  858. self->parent_field_descriptor);
  859. if (mutable_message == NULL) {
  860. return -1;
  861. }
  862. self->message = mutable_message;
  863. }
  864. self->read_only = false;
  865. // When a CMessage is made writable its Message pointer is updated
  866. // to point to a new mutable Message. When that happens we need to
  867. // update any references to the old, read-only CMessage. There are
  868. // four places such references occur: RepeatedScalarContainer,
  869. // RepeatedCompositeContainer, MapContainer, and ExtensionDict.
  870. if (self->extensions != NULL)
  871. self->extensions->message = self->message;
  872. if (ForEachCompositeField(self, FixupMessageReference(self->message)) == -1)
  873. return -1;
  874. return 0;
  875. }
  876. // --- Globals:
  877. // Retrieve a C++ FieldDescriptor for a message attribute.
  878. // The C++ message must be valid.
  879. // TODO(amauryfa): This function should stay internal, because exception
  880. // handling is not consistent.
  881. static const FieldDescriptor* GetFieldDescriptor(
  882. CMessage* self, PyObject* name) {
  883. const Descriptor *message_descriptor = self->message->GetDescriptor();
  884. char* field_name;
  885. Py_ssize_t size;
  886. if (PyString_AsStringAndSize(name, &field_name, &size) < 0) {
  887. return NULL;
  888. }
  889. const FieldDescriptor *field_descriptor =
  890. message_descriptor->FindFieldByName(string(field_name, size));
  891. if (field_descriptor == NULL) {
  892. // Note: No exception is set!
  893. return NULL;
  894. }
  895. return field_descriptor;
  896. }
  897. // Retrieve a C++ FieldDescriptor for an extension handle.
  898. const FieldDescriptor* GetExtensionDescriptor(PyObject* extension) {
  899. ScopedPyObjectPtr cdescriptor;
  900. if (!PyObject_TypeCheck(extension, &PyFieldDescriptor_Type)) {
  901. // Most callers consider extensions as a plain dictionary. We should
  902. // allow input which is not a field descriptor, and simply pretend it does
  903. // not exist.
  904. PyErr_SetObject(PyExc_KeyError, extension);
  905. return NULL;
  906. }
  907. return PyFieldDescriptor_AsDescriptor(extension);
  908. }
  909. // If value is a string, convert it into an enum value based on the labels in
  910. // descriptor, otherwise simply return value. Always returns a new reference.
  911. static PyObject* GetIntegerEnumValue(const FieldDescriptor& descriptor,
  912. PyObject* value) {
  913. if (PyString_Check(value) || PyUnicode_Check(value)) {
  914. const EnumDescriptor* enum_descriptor = descriptor.enum_type();
  915. if (enum_descriptor == NULL) {
  916. PyErr_SetString(PyExc_TypeError, "not an enum field");
  917. return NULL;
  918. }
  919. char* enum_label;
  920. Py_ssize_t size;
  921. if (PyString_AsStringAndSize(value, &enum_label, &size) < 0) {
  922. return NULL;
  923. }
  924. const EnumValueDescriptor* enum_value_descriptor =
  925. enum_descriptor->FindValueByName(string(enum_label, size));
  926. if (enum_value_descriptor == NULL) {
  927. PyErr_SetString(PyExc_ValueError, "unknown enum label");
  928. return NULL;
  929. }
  930. return PyInt_FromLong(enum_value_descriptor->number());
  931. }
  932. Py_INCREF(value);
  933. return value;
  934. }
  935. // If cmessage_list is not NULL, this function releases values into the
  936. // container CMessages instead of just removing. Repeated composite container
  937. // needs to do this to make sure CMessages stay alive if they're still
  938. // referenced after deletion. Repeated scalar container doesn't need to worry.
  939. int InternalDeleteRepeatedField(
  940. CMessage* self,
  941. const FieldDescriptor* field_descriptor,
  942. PyObject* slice,
  943. PyObject* cmessage_list) {
  944. Message* message = self->message;
  945. Py_ssize_t length, from, to, step, slice_length;
  946. const Reflection* reflection = message->GetReflection();
  947. int min, max;
  948. length = reflection->FieldSize(*message, field_descriptor);
  949. if (PySlice_Check(slice)) {
  950. from = to = step = slice_length = 0;
  951. PySlice_GetIndicesEx(
  952. #if PY_MAJOR_VERSION < 3
  953. reinterpret_cast<PySliceObject*>(slice),
  954. #else
  955. slice,
  956. #endif
  957. length, &from, &to, &step, &slice_length);
  958. if (from < to) {
  959. min = from;
  960. max = to - 1;
  961. } else {
  962. min = to + 1;
  963. max = from;
  964. }
  965. } else {
  966. from = to = PyLong_AsLong(slice);
  967. if (from == -1 && PyErr_Occurred()) {
  968. PyErr_SetString(PyExc_TypeError, "list indices must be integers");
  969. return -1;
  970. }
  971. if (from < 0) {
  972. from = to = length + from;
  973. }
  974. step = 1;
  975. min = max = from;
  976. // Range check.
  977. if (from < 0 || from >= length) {
  978. PyErr_Format(PyExc_IndexError, "list assignment index out of range");
  979. return -1;
  980. }
  981. }
  982. Py_ssize_t i = from;
  983. std::vector<bool> to_delete(length, false);
  984. while (i >= min && i <= max) {
  985. to_delete[i] = true;
  986. i += step;
  987. }
  988. to = 0;
  989. for (i = 0; i < length; ++i) {
  990. if (!to_delete[i]) {
  991. if (i != to) {
  992. reflection->SwapElements(message, field_descriptor, i, to);
  993. if (cmessage_list != NULL) {
  994. // If a list of cmessages is passed in (i.e. from a repeated
  995. // composite container), swap those as well to correspond to the
  996. // swaps in the underlying message so they're in the right order
  997. // when we start releasing.
  998. PyObject* tmp = PyList_GET_ITEM(cmessage_list, i);
  999. PyList_SET_ITEM(cmessage_list, i,
  1000. PyList_GET_ITEM(cmessage_list, to));
  1001. PyList_SET_ITEM(cmessage_list, to, tmp);
  1002. }
  1003. }
  1004. ++to;
  1005. }
  1006. }
  1007. while (i > to) {
  1008. if (cmessage_list == NULL) {
  1009. reflection->RemoveLast(message, field_descriptor);
  1010. } else {
  1011. CMessage* last_cmessage = reinterpret_cast<CMessage*>(
  1012. PyList_GET_ITEM(cmessage_list, PyList_GET_SIZE(cmessage_list) - 1));
  1013. repeated_composite_container::ReleaseLastTo(
  1014. self, field_descriptor, last_cmessage);
  1015. if (PySequence_DelItem(cmessage_list, -1) < 0) {
  1016. return -1;
  1017. }
  1018. }
  1019. --i;
  1020. }
  1021. return 0;
  1022. }
  1023. // Initializes fields of a message. Used in constructors.
  1024. int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
  1025. if (args != NULL && PyTuple_Size(args) != 0) {
  1026. PyErr_SetString(PyExc_TypeError, "No positional arguments allowed");
  1027. return -1;
  1028. }
  1029. if (kwargs == NULL) {
  1030. return 0;
  1031. }
  1032. Py_ssize_t pos = 0;
  1033. PyObject* name;
  1034. PyObject* value;
  1035. while (PyDict_Next(kwargs, &pos, &name, &value)) {
  1036. if (!PyString_Check(name)) {
  1037. PyErr_SetString(PyExc_ValueError, "Field name must be a string");
  1038. return -1;
  1039. }
  1040. const FieldDescriptor* descriptor = GetFieldDescriptor(self, name);
  1041. if (descriptor == NULL) {
  1042. PyErr_Format(PyExc_ValueError, "Protocol message %s has no \"%s\" field.",
  1043. self->message->GetDescriptor()->name().c_str(),
  1044. PyString_AsString(name));
  1045. return -1;
  1046. }
  1047. if (value == Py_None) {
  1048. // field=None is the same as no field at all.
  1049. continue;
  1050. }
  1051. if (descriptor->is_map()) {
  1052. ScopedPyObjectPtr map(GetAttr(self, name));
  1053. const FieldDescriptor* value_descriptor =
  1054. descriptor->message_type()->FindFieldByName("value");
  1055. if (value_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1056. Py_ssize_t map_pos = 0;
  1057. PyObject* map_key;
  1058. PyObject* map_value;
  1059. while (PyDict_Next(value, &map_pos, &map_key, &map_value)) {
  1060. ScopedPyObjectPtr function_return;
  1061. function_return.reset(PyObject_GetItem(map.get(), map_key));
  1062. if (function_return.get() == NULL) {
  1063. return -1;
  1064. }
  1065. ScopedPyObjectPtr ok(PyObject_CallMethod(
  1066. function_return.get(), "MergeFrom", "O", map_value));
  1067. if (ok.get() == NULL) {
  1068. return -1;
  1069. }
  1070. }
  1071. } else {
  1072. ScopedPyObjectPtr function_return;
  1073. function_return.reset(
  1074. PyObject_CallMethod(map.get(), "update", "O", value));
  1075. if (function_return.get() == NULL) {
  1076. return -1;
  1077. }
  1078. }
  1079. } else if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  1080. ScopedPyObjectPtr container(GetAttr(self, name));
  1081. if (container == NULL) {
  1082. return -1;
  1083. }
  1084. if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1085. RepeatedCompositeContainer* rc_container =
  1086. reinterpret_cast<RepeatedCompositeContainer*>(container.get());
  1087. ScopedPyObjectPtr iter(PyObject_GetIter(value));
  1088. if (iter == NULL) {
  1089. PyErr_SetString(PyExc_TypeError, "Value must be iterable");
  1090. return -1;
  1091. }
  1092. ScopedPyObjectPtr next;
  1093. while ((next.reset(PyIter_Next(iter.get()))) != NULL) {
  1094. PyObject* kwargs = (PyDict_Check(next.get()) ? next.get() : NULL);
  1095. ScopedPyObjectPtr new_msg(
  1096. repeated_composite_container::Add(rc_container, NULL, kwargs));
  1097. if (new_msg == NULL) {
  1098. return -1;
  1099. }
  1100. if (kwargs == NULL) {
  1101. // next was not a dict, it's a message we need to merge
  1102. ScopedPyObjectPtr merged(MergeFrom(
  1103. reinterpret_cast<CMessage*>(new_msg.get()), next.get()));
  1104. if (merged.get() == NULL) {
  1105. return -1;
  1106. }
  1107. }
  1108. }
  1109. if (PyErr_Occurred()) {
  1110. // Check to see how PyIter_Next() exited.
  1111. return -1;
  1112. }
  1113. } else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  1114. RepeatedScalarContainer* rs_container =
  1115. reinterpret_cast<RepeatedScalarContainer*>(container.get());
  1116. ScopedPyObjectPtr iter(PyObject_GetIter(value));
  1117. if (iter == NULL) {
  1118. PyErr_SetString(PyExc_TypeError, "Value must be iterable");
  1119. return -1;
  1120. }
  1121. ScopedPyObjectPtr next;
  1122. while ((next.reset(PyIter_Next(iter.get()))) != NULL) {
  1123. ScopedPyObjectPtr enum_value(
  1124. GetIntegerEnumValue(*descriptor, next.get()));
  1125. if (enum_value == NULL) {
  1126. return -1;
  1127. }
  1128. ScopedPyObjectPtr new_msg(repeated_scalar_container::Append(
  1129. rs_container, enum_value.get()));
  1130. if (new_msg == NULL) {
  1131. return -1;
  1132. }
  1133. }
  1134. if (PyErr_Occurred()) {
  1135. // Check to see how PyIter_Next() exited.
  1136. return -1;
  1137. }
  1138. } else {
  1139. if (ScopedPyObjectPtr(repeated_scalar_container::Extend(
  1140. reinterpret_cast<RepeatedScalarContainer*>(container.get()),
  1141. value)) ==
  1142. NULL) {
  1143. return -1;
  1144. }
  1145. }
  1146. } else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1147. ScopedPyObjectPtr message(GetAttr(self, name));
  1148. if (message == NULL) {
  1149. return -1;
  1150. }
  1151. CMessage* cmessage = reinterpret_cast<CMessage*>(message.get());
  1152. if (PyDict_Check(value)) {
  1153. // Make the message exist even if the dict is empty.
  1154. AssureWritable(cmessage);
  1155. if (InitAttributes(cmessage, NULL, value) < 0) {
  1156. return -1;
  1157. }
  1158. } else {
  1159. ScopedPyObjectPtr merged(MergeFrom(cmessage, value));
  1160. if (merged == NULL) {
  1161. return -1;
  1162. }
  1163. }
  1164. } else {
  1165. ScopedPyObjectPtr new_val;
  1166. if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  1167. new_val.reset(GetIntegerEnumValue(*descriptor, value));
  1168. if (new_val == NULL) {
  1169. return -1;
  1170. }
  1171. }
  1172. if (SetAttr(self, name, (new_val.get() == NULL) ? value : new_val.get()) <
  1173. 0) {
  1174. return -1;
  1175. }
  1176. }
  1177. }
  1178. return 0;
  1179. }
  1180. // Allocates an incomplete Python Message: the caller must fill self->message,
  1181. // self->owner and eventually self->parent.
  1182. CMessage* NewEmptyMessage(CMessageClass* type) {
  1183. CMessage* self = reinterpret_cast<CMessage*>(
  1184. PyType_GenericAlloc(&type->super.ht_type, 0));
  1185. if (self == NULL) {
  1186. return NULL;
  1187. }
  1188. self->message = NULL;
  1189. self->parent = NULL;
  1190. self->parent_field_descriptor = NULL;
  1191. self->read_only = false;
  1192. self->extensions = NULL;
  1193. self->composite_fields = NULL;
  1194. return self;
  1195. }
  1196. // The __new__ method of Message classes.
  1197. // Creates a new C++ message and takes ownership.
  1198. static PyObject* New(PyTypeObject* cls,
  1199. PyObject* unused_args, PyObject* unused_kwargs) {
  1200. CMessageClass* type = CheckMessageClass(cls);
  1201. if (type == NULL) {
  1202. return NULL;
  1203. }
  1204. // Retrieve the message descriptor and the default instance (=prototype).
  1205. const Descriptor* message_descriptor = type->message_descriptor;
  1206. if (message_descriptor == NULL) {
  1207. return NULL;
  1208. }
  1209. const Message* default_message = type->py_message_factory->message_factory
  1210. ->GetPrototype(message_descriptor);
  1211. if (default_message == NULL) {
  1212. PyErr_SetString(PyExc_TypeError, message_descriptor->full_name().c_str());
  1213. return NULL;
  1214. }
  1215. CMessage* self = NewEmptyMessage(type);
  1216. if (self == NULL) {
  1217. return NULL;
  1218. }
  1219. self->message = default_message->New();
  1220. self->owner.reset(self->message);
  1221. return reinterpret_cast<PyObject*>(self);
  1222. }
  1223. // The __init__ method of Message classes.
  1224. // It initializes fields from keywords passed to the constructor.
  1225. static int Init(CMessage* self, PyObject* args, PyObject* kwargs) {
  1226. return InitAttributes(self, args, kwargs);
  1227. }
  1228. // ---------------------------------------------------------------------
  1229. // Deallocating a CMessage
  1230. //
  1231. // Deallocating a CMessage requires that we clear any weak references
  1232. // from children to the message being deallocated.
  1233. // Clear the weak reference from the child to the parent.
  1234. struct ClearWeakReferences : public ChildVisitor {
  1235. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  1236. container->parent = NULL;
  1237. // The elements in the container have the same parent as the
  1238. // container itself, so NULL out that pointer as well.
  1239. const Py_ssize_t n = PyList_GET_SIZE(container->child_messages);
  1240. for (Py_ssize_t i = 0; i < n; ++i) {
  1241. CMessage* child_cmessage = reinterpret_cast<CMessage*>(
  1242. PyList_GET_ITEM(container->child_messages, i));
  1243. child_cmessage->parent = NULL;
  1244. }
  1245. return 0;
  1246. }
  1247. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  1248. container->parent = NULL;
  1249. return 0;
  1250. }
  1251. int VisitMapContainer(MapContainer* container) {
  1252. container->parent = NULL;
  1253. return 0;
  1254. }
  1255. int VisitCMessage(CMessage* cmessage,
  1256. const FieldDescriptor* field_descriptor) {
  1257. cmessage->parent = NULL;
  1258. return 0;
  1259. }
  1260. };
  1261. static void Dealloc(CMessage* self) {
  1262. if (self->weakreflist) {
  1263. PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
  1264. }
  1265. // Null out all weak references from children to this message.
  1266. GOOGLE_CHECK_EQ(0, ForEachCompositeField(self, ClearWeakReferences()));
  1267. if (self->extensions) {
  1268. self->extensions->parent = NULL;
  1269. }
  1270. Py_CLEAR(self->extensions);
  1271. Py_CLEAR(self->composite_fields);
  1272. self->owner.reset();
  1273. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  1274. }
  1275. // ---------------------------------------------------------------------
  1276. PyObject* IsInitialized(CMessage* self, PyObject* args) {
  1277. PyObject* errors = NULL;
  1278. if (PyArg_ParseTuple(args, "|O", &errors) < 0) {
  1279. return NULL;
  1280. }
  1281. if (self->message->IsInitialized()) {
  1282. Py_RETURN_TRUE;
  1283. }
  1284. if (errors != NULL) {
  1285. ScopedPyObjectPtr initialization_errors(
  1286. FindInitializationErrors(self));
  1287. if (initialization_errors == NULL) {
  1288. return NULL;
  1289. }
  1290. ScopedPyObjectPtr extend_name(PyString_FromString("extend"));
  1291. if (extend_name == NULL) {
  1292. return NULL;
  1293. }
  1294. ScopedPyObjectPtr result(PyObject_CallMethodObjArgs(
  1295. errors,
  1296. extend_name.get(),
  1297. initialization_errors.get(),
  1298. NULL));
  1299. if (result == NULL) {
  1300. return NULL;
  1301. }
  1302. }
  1303. Py_RETURN_FALSE;
  1304. }
  1305. PyObject* HasFieldByDescriptor(
  1306. CMessage* self, const FieldDescriptor* field_descriptor) {
  1307. Message* message = self->message;
  1308. if (!CheckFieldBelongsToMessage(field_descriptor, message)) {
  1309. return NULL;
  1310. }
  1311. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  1312. PyErr_SetString(PyExc_KeyError,
  1313. "Field is repeated. A singular method is required.");
  1314. return NULL;
  1315. }
  1316. bool has_field =
  1317. message->GetReflection()->HasField(*message, field_descriptor);
  1318. return PyBool_FromLong(has_field ? 1 : 0);
  1319. }
  1320. const FieldDescriptor* FindFieldWithOneofs(
  1321. const Message* message, const string& field_name, bool* in_oneof) {
  1322. *in_oneof = false;
  1323. const Descriptor* descriptor = message->GetDescriptor();
  1324. const FieldDescriptor* field_descriptor =
  1325. descriptor->FindFieldByName(field_name);
  1326. if (field_descriptor != NULL) {
  1327. return field_descriptor;
  1328. }
  1329. const OneofDescriptor* oneof_desc =
  1330. descriptor->FindOneofByName(field_name);
  1331. if (oneof_desc != NULL) {
  1332. *in_oneof = true;
  1333. return message->GetReflection()->GetOneofFieldDescriptor(*message,
  1334. oneof_desc);
  1335. }
  1336. return NULL;
  1337. }
  1338. bool CheckHasPresence(const FieldDescriptor* field_descriptor, bool in_oneof) {
  1339. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  1340. PyErr_Format(PyExc_ValueError,
  1341. "Protocol message has no singular \"%s\" field.",
  1342. field_descriptor->name().c_str());
  1343. return false;
  1344. }
  1345. if (field_descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
  1346. // HasField() for a oneof *itself* isn't supported.
  1347. if (in_oneof) {
  1348. PyErr_Format(PyExc_ValueError,
  1349. "Can't test oneof field \"%s\" for presence in proto3, use "
  1350. "WhichOneof instead.",
  1351. field_descriptor->containing_oneof()->name().c_str());
  1352. return false;
  1353. }
  1354. // ...but HasField() for fields *in* a oneof is supported.
  1355. if (field_descriptor->containing_oneof() != NULL) {
  1356. return true;
  1357. }
  1358. if (field_descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
  1359. PyErr_Format(
  1360. PyExc_ValueError,
  1361. "Can't test non-submessage field \"%s\" for presence in proto3.",
  1362. field_descriptor->name().c_str());
  1363. return false;
  1364. }
  1365. }
  1366. return true;
  1367. }
  1368. PyObject* HasField(CMessage* self, PyObject* arg) {
  1369. char* field_name;
  1370. Py_ssize_t size;
  1371. #if PY_MAJOR_VERSION < 3
  1372. if (PyString_AsStringAndSize(arg, &field_name, &size) < 0) {
  1373. return NULL;
  1374. }
  1375. #else
  1376. field_name = PyUnicode_AsUTF8AndSize(arg, &size);
  1377. if (!field_name) {
  1378. return NULL;
  1379. }
  1380. #endif
  1381. Message* message = self->message;
  1382. bool is_in_oneof;
  1383. const FieldDescriptor* field_descriptor =
  1384. FindFieldWithOneofs(message, string(field_name, size), &is_in_oneof);
  1385. if (field_descriptor == NULL) {
  1386. if (!is_in_oneof) {
  1387. PyErr_Format(PyExc_ValueError, "Unknown field %s.", field_name);
  1388. return NULL;
  1389. } else {
  1390. Py_RETURN_FALSE;
  1391. }
  1392. }
  1393. if (!CheckHasPresence(field_descriptor, is_in_oneof)) {
  1394. return NULL;
  1395. }
  1396. if (message->GetReflection()->HasField(*message, field_descriptor)) {
  1397. Py_RETURN_TRUE;
  1398. }
  1399. if (!message->GetReflection()->SupportsUnknownEnumValues() &&
  1400. field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  1401. // Special case: Python HasField() differs in semantics from C++
  1402. // slightly: we return HasField('enum_field') == true if there is
  1403. // an unknown enum value present. To implement this we have to
  1404. // look in the UnknownFieldSet.
  1405. const UnknownFieldSet& unknown_field_set =
  1406. message->GetReflection()->GetUnknownFields(*message);
  1407. for (int i = 0; i < unknown_field_set.field_count(); ++i) {
  1408. if (unknown_field_set.field(i).number() == field_descriptor->number()) {
  1409. Py_RETURN_TRUE;
  1410. }
  1411. }
  1412. }
  1413. Py_RETURN_FALSE;
  1414. }
  1415. PyObject* ClearExtension(CMessage* self, PyObject* extension) {
  1416. const FieldDescriptor* descriptor = GetExtensionDescriptor(extension);
  1417. if (descriptor == NULL) {
  1418. return NULL;
  1419. }
  1420. if (self->extensions != NULL) {
  1421. PyObject* value = PyDict_GetItem(self->extensions->values, extension);
  1422. if (value != NULL) {
  1423. if (InternalReleaseFieldByDescriptor(self, descriptor, value) < 0) {
  1424. return NULL;
  1425. }
  1426. PyDict_DelItem(self->extensions->values, extension);
  1427. }
  1428. }
  1429. return ClearFieldByDescriptor(self, descriptor);
  1430. }
  1431. PyObject* HasExtension(CMessage* self, PyObject* extension) {
  1432. const FieldDescriptor* descriptor = GetExtensionDescriptor(extension);
  1433. if (descriptor == NULL) {
  1434. return NULL;
  1435. }
  1436. return HasFieldByDescriptor(self, descriptor);
  1437. }
  1438. // ---------------------------------------------------------------------
  1439. // Releasing messages
  1440. //
  1441. // The Python API's ClearField() and Clear() methods behave
  1442. // differently than their C++ counterparts. While the C++ versions
  1443. // clears the children the Python versions detaches the children,
  1444. // without touching their content. This impedance mismatch causes
  1445. // some complexity in the implementation, which is captured in this
  1446. // section.
  1447. //
  1448. // When a CMessage field is cleared we need to:
  1449. //
  1450. // * Release the Message used as the backing store for the CMessage
  1451. // from its parent.
  1452. //
  1453. // * Change the owner field of the released CMessage and all of its
  1454. // children to point to the newly released Message.
  1455. //
  1456. // * Clear the weak references from the released CMessage to the
  1457. // parent.
  1458. //
  1459. // When a RepeatedCompositeContainer field is cleared we need to:
  1460. //
  1461. // * Release all the Message used as the backing store for the
  1462. // CMessages stored in the container.
  1463. //
  1464. // * Change the owner field of all the released CMessage and all of
  1465. // their children to point to the newly released Messages.
  1466. //
  1467. // * Clear the weak references from the released container to the
  1468. // parent.
  1469. struct SetOwnerVisitor : public ChildVisitor {
  1470. // new_owner must outlive this object.
  1471. explicit SetOwnerVisitor(const shared_ptr<Message>& new_owner)
  1472. : new_owner_(new_owner) {}
  1473. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  1474. repeated_composite_container::SetOwner(container, new_owner_);
  1475. return 0;
  1476. }
  1477. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  1478. repeated_scalar_container::SetOwner(container, new_owner_);
  1479. return 0;
  1480. }
  1481. int VisitMapContainer(MapContainer* container) {
  1482. container->SetOwner(new_owner_);
  1483. return 0;
  1484. }
  1485. int VisitCMessage(CMessage* cmessage,
  1486. const FieldDescriptor* field_descriptor) {
  1487. return SetOwner(cmessage, new_owner_);
  1488. }
  1489. private:
  1490. const shared_ptr<Message>& new_owner_;
  1491. };
  1492. // Change the owner of this CMessage and all its children, recursively.
  1493. int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner) {
  1494. self->owner = new_owner;
  1495. if (ForEachCompositeField(self, SetOwnerVisitor(new_owner)) == -1)
  1496. return -1;
  1497. return 0;
  1498. }
  1499. // Releases the message specified by 'field' and returns the
  1500. // pointer. If the field does not exist a new message is created using
  1501. // 'descriptor'. The caller takes ownership of the returned pointer.
  1502. Message* ReleaseMessage(CMessage* self,
  1503. const Descriptor* descriptor,
  1504. const FieldDescriptor* field_descriptor) {
  1505. MessageFactory* message_factory = GetFactoryForMessage(self)->message_factory;
  1506. Message* released_message = self->message->GetReflection()->ReleaseMessage(
  1507. self->message, field_descriptor, message_factory);
  1508. // ReleaseMessage will return NULL which differs from
  1509. // child_cmessage->message, if the field does not exist. In this case,
  1510. // the latter points to the default instance via a const_cast<>, so we
  1511. // have to reset it to a new mutable object since we are taking ownership.
  1512. if (released_message == NULL) {
  1513. const Message* prototype = message_factory->GetPrototype(descriptor);
  1514. GOOGLE_DCHECK(prototype != NULL);
  1515. released_message = prototype->New();
  1516. }
  1517. return released_message;
  1518. }
  1519. int ReleaseSubMessage(CMessage* self,
  1520. const FieldDescriptor* field_descriptor,
  1521. CMessage* child_cmessage) {
  1522. // Release the Message
  1523. shared_ptr<Message> released_message(ReleaseMessage(
  1524. self, child_cmessage->message->GetDescriptor(), field_descriptor));
  1525. child_cmessage->message = released_message.get();
  1526. child_cmessage->owner.swap(released_message);
  1527. child_cmessage->parent = NULL;
  1528. child_cmessage->parent_field_descriptor = NULL;
  1529. child_cmessage->read_only = false;
  1530. return ForEachCompositeField(child_cmessage,
  1531. SetOwnerVisitor(child_cmessage->owner));
  1532. }
  1533. struct ReleaseChild : public ChildVisitor {
  1534. // message must outlive this object.
  1535. explicit ReleaseChild(CMessage* parent) :
  1536. parent_(parent) {}
  1537. int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) {
  1538. return repeated_composite_container::Release(container);
  1539. }
  1540. int VisitRepeatedScalarContainer(RepeatedScalarContainer* container) {
  1541. return repeated_scalar_container::Release(container);
  1542. }
  1543. int VisitMapContainer(MapContainer* container) {
  1544. return container->Release();
  1545. }
  1546. int VisitCMessage(CMessage* cmessage,
  1547. const FieldDescriptor* field_descriptor) {
  1548. return ReleaseSubMessage(parent_, field_descriptor, cmessage);
  1549. }
  1550. CMessage* parent_;
  1551. };
  1552. int InternalReleaseFieldByDescriptor(
  1553. CMessage* self,
  1554. const FieldDescriptor* field_descriptor,
  1555. PyObject* composite_field) {
  1556. return VisitCompositeField(
  1557. field_descriptor,
  1558. composite_field,
  1559. ReleaseChild(self));
  1560. }
  1561. PyObject* ClearFieldByDescriptor(
  1562. CMessage* self,
  1563. const FieldDescriptor* field_descriptor) {
  1564. if (!CheckFieldBelongsToMessage(field_descriptor, self->message)) {
  1565. return NULL;
  1566. }
  1567. AssureWritable(self);
  1568. Message* message = self->message;
  1569. message->GetReflection()->ClearField(message, field_descriptor);
  1570. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
  1571. !message->GetReflection()->SupportsUnknownEnumValues()) {
  1572. UnknownFieldSet* unknown_field_set =
  1573. message->GetReflection()->MutableUnknownFields(message);
  1574. unknown_field_set->DeleteByNumber(field_descriptor->number());
  1575. }
  1576. Py_RETURN_NONE;
  1577. }
  1578. PyObject* ClearField(CMessage* self, PyObject* arg) {
  1579. if (!PyString_Check(arg)) {
  1580. PyErr_SetString(PyExc_TypeError, "field name must be a string");
  1581. return NULL;
  1582. }
  1583. #if PY_MAJOR_VERSION < 3
  1584. const char* field_name = PyString_AS_STRING(arg);
  1585. Py_ssize_t size = PyString_GET_SIZE(arg);
  1586. #else
  1587. Py_ssize_t size;
  1588. const char* field_name = PyUnicode_AsUTF8AndSize(arg, &size);
  1589. #endif
  1590. AssureWritable(self);
  1591. Message* message = self->message;
  1592. ScopedPyObjectPtr arg_in_oneof;
  1593. bool is_in_oneof;
  1594. const FieldDescriptor* field_descriptor =
  1595. FindFieldWithOneofs(message, string(field_name, size), &is_in_oneof);
  1596. if (field_descriptor == NULL) {
  1597. if (!is_in_oneof) {
  1598. PyErr_Format(PyExc_ValueError,
  1599. "Protocol message has no \"%s\" field.", field_name);
  1600. return NULL;
  1601. } else {
  1602. Py_RETURN_NONE;
  1603. }
  1604. } else if (is_in_oneof) {
  1605. const string& name = field_descriptor->name();
  1606. arg_in_oneof.reset(PyString_FromStringAndSize(name.c_str(), name.size()));
  1607. arg = arg_in_oneof.get();
  1608. }
  1609. // Release the field if it exists in the dict of composite fields.
  1610. if (self->composite_fields) {
  1611. PyObject* value = PyDict_GetItem(self->composite_fields, arg);
  1612. if (value != NULL) {
  1613. if (InternalReleaseFieldByDescriptor(self, field_descriptor, value) < 0) {
  1614. return NULL;
  1615. }
  1616. PyDict_DelItem(self->composite_fields, arg);
  1617. }
  1618. }
  1619. return ClearFieldByDescriptor(self, field_descriptor);
  1620. }
  1621. PyObject* Clear(CMessage* self) {
  1622. AssureWritable(self);
  1623. if (ForEachCompositeField(self, ReleaseChild(self)) == -1)
  1624. return NULL;
  1625. Py_CLEAR(self->extensions);
  1626. if (self->composite_fields) {
  1627. PyDict_Clear(self->composite_fields);
  1628. }
  1629. self->message->Clear();
  1630. Py_RETURN_NONE;
  1631. }
  1632. // ---------------------------------------------------------------------
  1633. static string GetMessageName(CMessage* self) {
  1634. if (self->parent_field_descriptor != NULL) {
  1635. return self->parent_field_descriptor->full_name();
  1636. } else {
  1637. return self->message->GetDescriptor()->full_name();
  1638. }
  1639. }
  1640. static PyObject* SerializeToString(CMessage* self, PyObject* args) {
  1641. if (!self->message->IsInitialized()) {
  1642. ScopedPyObjectPtr errors(FindInitializationErrors(self));
  1643. if (errors == NULL) {
  1644. return NULL;
  1645. }
  1646. ScopedPyObjectPtr comma(PyString_FromString(","));
  1647. if (comma == NULL) {
  1648. return NULL;
  1649. }
  1650. ScopedPyObjectPtr joined(
  1651. PyObject_CallMethod(comma.get(), "join", "O", errors.get()));
  1652. if (joined == NULL) {
  1653. return NULL;
  1654. }
  1655. // TODO(haberman): this is a (hopefully temporary) hack. The unit testing
  1656. // infrastructure reloads all pure-Python modules for every test, but not
  1657. // C++ modules (because that's generally impossible:
  1658. // http://bugs.python.org/issue1144263). But if we cache EncodeError, we'll
  1659. // return the EncodeError from a previous load of the module, which won't
  1660. // match a user's attempt to catch EncodeError. So we have to look it up
  1661. // again every time.
  1662. ScopedPyObjectPtr message_module(PyImport_ImportModule(
  1663. "google.protobuf.message"));
  1664. if (message_module.get() == NULL) {
  1665. return NULL;
  1666. }
  1667. ScopedPyObjectPtr encode_error(
  1668. PyObject_GetAttrString(message_module.get(), "EncodeError"));
  1669. if (encode_error.get() == NULL) {
  1670. return NULL;
  1671. }
  1672. PyErr_Format(encode_error.get(),
  1673. "Message %s is missing required fields: %s",
  1674. GetMessageName(self).c_str(), PyString_AsString(joined.get()));
  1675. return NULL;
  1676. }
  1677. int size = self->message->ByteSize();
  1678. if (size <= 0) {
  1679. return PyBytes_FromString("");
  1680. }
  1681. PyObject* result = PyBytes_FromStringAndSize(NULL, size);
  1682. if (result == NULL) {
  1683. return NULL;
  1684. }
  1685. char* buffer = PyBytes_AS_STRING(result);
  1686. self->message->SerializeWithCachedSizesToArray(
  1687. reinterpret_cast<uint8*>(buffer));
  1688. return result;
  1689. }
  1690. static PyObject* SerializePartialToString(CMessage* self) {
  1691. string contents;
  1692. self->message->SerializePartialToString(&contents);
  1693. return PyBytes_FromStringAndSize(contents.c_str(), contents.size());
  1694. }
  1695. // Formats proto fields for ascii dumps using python formatting functions where
  1696. // appropriate.
  1697. class PythonFieldValuePrinter : public TextFormat::FieldValuePrinter {
  1698. public:
  1699. // Python has some differences from C++ when printing floating point numbers.
  1700. //
  1701. // 1) Trailing .0 is always printed.
  1702. // 2) (Python2) Output is rounded to 12 digits.
  1703. // 3) (Python3) The full precision of the double is preserved (and Python uses
  1704. // David M. Gay's dtoa(), when the C++ code uses SimpleDtoa. There are some
  1705. // differences, but they rarely happen)
  1706. //
  1707. // We override floating point printing with the C-API function for printing
  1708. // Python floats to ensure consistency.
  1709. string PrintFloat(float value) const { return PrintDouble(value); }
  1710. string PrintDouble(double value) const {
  1711. // This implementation is not highly optimized (it allocates two temporary
  1712. // Python objects) but it is simple and portable. If this is shown to be a
  1713. // performance bottleneck, we can optimize it, but the results will likely
  1714. // be more complicated to accommodate the differing behavior of double
  1715. // formatting between Python 2 and Python 3.
  1716. //
  1717. // (Though a valid question is: do we really want to make out output
  1718. // dependent on the Python version?)
  1719. ScopedPyObjectPtr py_value(PyFloat_FromDouble(value));
  1720. if (!py_value.get()) {
  1721. return string();
  1722. }
  1723. ScopedPyObjectPtr py_str(PyObject_Str(py_value.get()));
  1724. if (!py_str.get()) {
  1725. return string();
  1726. }
  1727. return string(PyString_AsString(py_str.get()));
  1728. }
  1729. };
  1730. static PyObject* ToStr(CMessage* self) {
  1731. TextFormat::Printer printer;
  1732. // Passes ownership
  1733. printer.SetDefaultFieldValuePrinter(new PythonFieldValuePrinter());
  1734. printer.SetHideUnknownFields(true);
  1735. string output;
  1736. if (!printer.PrintToString(*self->message, &output)) {
  1737. PyErr_SetString(PyExc_ValueError, "Unable to convert message to str");
  1738. return NULL;
  1739. }
  1740. return PyString_FromString(output.c_str());
  1741. }
  1742. PyObject* MergeFrom(CMessage* self, PyObject* arg) {
  1743. CMessage* other_message;
  1744. if (!PyObject_TypeCheck(arg, &CMessage_Type)) {
  1745. PyErr_Format(PyExc_TypeError,
  1746. "Parameter to MergeFrom() must be instance of same class: "
  1747. "expected %s got %s.",
  1748. self->message->GetDescriptor()->full_name().c_str(),
  1749. Py_TYPE(arg)->tp_name);
  1750. return NULL;
  1751. }
  1752. other_message = reinterpret_cast<CMessage*>(arg);
  1753. if (other_message->message->GetDescriptor() !=
  1754. self->message->GetDescriptor()) {
  1755. PyErr_Format(PyExc_TypeError,
  1756. "Parameter to MergeFrom() must be instance of same class: "
  1757. "expected %s got %s.",
  1758. self->message->GetDescriptor()->full_name().c_str(),
  1759. other_message->message->GetDescriptor()->full_name().c_str());
  1760. return NULL;
  1761. }
  1762. AssureWritable(self);
  1763. // TODO(tibell): Message::MergeFrom might turn some child Messages
  1764. // into mutable messages, invalidating the message field in the
  1765. // corresponding CMessages. We should run a FixupMessageReferences
  1766. // pass here.
  1767. self->message->MergeFrom(*other_message->message);
  1768. Py_RETURN_NONE;
  1769. }
  1770. static PyObject* CopyFrom(CMessage* self, PyObject* arg) {
  1771. CMessage* other_message;
  1772. if (!PyObject_TypeCheck(arg, &CMessage_Type)) {
  1773. PyErr_Format(PyExc_TypeError,
  1774. "Parameter to CopyFrom() must be instance of same class: "
  1775. "expected %s got %s.",
  1776. self->message->GetDescriptor()->full_name().c_str(),
  1777. Py_TYPE(arg)->tp_name);
  1778. return NULL;
  1779. }
  1780. other_message = reinterpret_cast<CMessage*>(arg);
  1781. if (self == other_message) {
  1782. Py_RETURN_NONE;
  1783. }
  1784. if (other_message->message->GetDescriptor() !=
  1785. self->message->GetDescriptor()) {
  1786. PyErr_Format(PyExc_TypeError,
  1787. "Parameter to CopyFrom() must be instance of same class: "
  1788. "expected %s got %s.",
  1789. self->message->GetDescriptor()->full_name().c_str(),
  1790. other_message->message->GetDescriptor()->full_name().c_str());
  1791. return NULL;
  1792. }
  1793. AssureWritable(self);
  1794. // CopyFrom on the message will not clean up self->composite_fields,
  1795. // which can leave us in an inconsistent state, so clear it out here.
  1796. (void)ScopedPyObjectPtr(Clear(self));
  1797. self->message->CopyFrom(*other_message->message);
  1798. Py_RETURN_NONE;
  1799. }
  1800. // Protobuf has a 64MB limit built in, this variable will override this. Please
  1801. // do not enable this unless you fully understand the implications: protobufs
  1802. // must all be kept in memory at the same time, so if they grow too big you may
  1803. // get OOM errors. The protobuf APIs do not provide any tools for processing
  1804. // protobufs in chunks. If you have protos this big you should break them up if
  1805. // it is at all convenient to do so.
  1806. #ifdef PROTOBUF_PYTHON_ALLOW_OVERSIZE_PROTOS
  1807. static bool allow_oversize_protos = true;
  1808. #else
  1809. static bool allow_oversize_protos = false;
  1810. #endif
  1811. // Provide a method in the module to set allow_oversize_protos to a boolean
  1812. // value. This method returns the newly value of allow_oversize_protos.
  1813. PyObject* SetAllowOversizeProtos(PyObject* m, PyObject* arg) {
  1814. if (!arg || !PyBool_Check(arg)) {
  1815. PyErr_SetString(PyExc_TypeError,
  1816. "Argument to SetAllowOversizeProtos must be boolean");
  1817. return NULL;
  1818. }
  1819. allow_oversize_protos = PyObject_IsTrue(arg);
  1820. if (allow_oversize_protos) {
  1821. Py_RETURN_TRUE;
  1822. } else {
  1823. Py_RETURN_FALSE;
  1824. }
  1825. }
  1826. static PyObject* MergeFromString(CMessage* self, PyObject* arg) {
  1827. const void* data;
  1828. Py_ssize_t data_length;
  1829. if (PyObject_AsReadBuffer(arg, &data, &data_length) < 0) {
  1830. return NULL;
  1831. }
  1832. AssureWritable(self);
  1833. io::CodedInputStream input(
  1834. reinterpret_cast<const uint8*>(data), data_length);
  1835. if (allow_oversize_protos) {
  1836. input.SetTotalBytesLimit(INT_MAX, INT_MAX);
  1837. }
  1838. PyMessageFactory* factory = GetFactoryForMessage(self);
  1839. input.SetExtensionRegistry(factory->pool->pool, factory->message_factory);
  1840. bool success = self->message->MergePartialFromCodedStream(&input);
  1841. if (success) {
  1842. return PyInt_FromLong(input.CurrentPosition());
  1843. } else {
  1844. PyErr_Format(DecodeError_class, "Error parsing message");
  1845. return NULL;
  1846. }
  1847. }
  1848. static PyObject* ParseFromString(CMessage* self, PyObject* arg) {
  1849. if (ScopedPyObjectPtr(Clear(self)) == NULL) {
  1850. return NULL;
  1851. }
  1852. return MergeFromString(self, arg);
  1853. }
  1854. static PyObject* ByteSize(CMessage* self, PyObject* args) {
  1855. return PyLong_FromLong(self->message->ByteSize());
  1856. }
  1857. PyObject* RegisterExtension(PyObject* cls, PyObject* extension_handle) {
  1858. const FieldDescriptor* descriptor =
  1859. GetExtensionDescriptor(extension_handle);
  1860. if (descriptor == NULL) {
  1861. return NULL;
  1862. }
  1863. if (!PyObject_TypeCheck(cls, &CMessageClass_Type)) {
  1864. PyErr_Format(PyExc_TypeError, "Expected a message class, got %s",
  1865. cls->ob_type->tp_name);
  1866. return NULL;
  1867. }
  1868. CMessageClass *message_class = reinterpret_cast<CMessageClass*>(cls);
  1869. if (message_class == NULL) {
  1870. return NULL;
  1871. }
  1872. // If the extension was already registered, check that it is the same.
  1873. const FieldDescriptor* existing_extension =
  1874. message_class->py_message_factory->pool->pool->FindExtensionByNumber(
  1875. descriptor->containing_type(), descriptor->number());
  1876. if (existing_extension != NULL && existing_extension != descriptor) {
  1877. PyErr_SetString(PyExc_ValueError, "Double registration of Extensions");
  1878. return NULL;
  1879. }
  1880. Py_RETURN_NONE;
  1881. }
  1882. static PyObject* SetInParent(CMessage* self, PyObject* args) {
  1883. AssureWritable(self);
  1884. Py_RETURN_NONE;
  1885. }
  1886. static PyObject* WhichOneof(CMessage* self, PyObject* arg) {
  1887. Py_ssize_t name_size;
  1888. char *name_data;
  1889. if (PyString_AsStringAndSize(arg, &name_data, &name_size) < 0)
  1890. return NULL;
  1891. string oneof_name = string(name_data, name_size);
  1892. const OneofDescriptor* oneof_desc =
  1893. self->message->GetDescriptor()->FindOneofByName(oneof_name);
  1894. if (oneof_desc == NULL) {
  1895. PyErr_Format(PyExc_ValueError,
  1896. "Protocol message has no oneof \"%s\" field.",
  1897. oneof_name.c_str());
  1898. return NULL;
  1899. }
  1900. const FieldDescriptor* field_in_oneof =
  1901. self->message->GetReflection()->GetOneofFieldDescriptor(
  1902. *self->message, oneof_desc);
  1903. if (field_in_oneof == NULL) {
  1904. Py_RETURN_NONE;
  1905. } else {
  1906. const string& name = field_in_oneof->name();
  1907. return PyString_FromStringAndSize(name.c_str(), name.size());
  1908. }
  1909. }
  1910. static PyObject* GetExtensionDict(CMessage* self, void *closure);
  1911. static PyObject* ListFields(CMessage* self) {
  1912. std::vector<const FieldDescriptor*> fields;
  1913. self->message->GetReflection()->ListFields(*self->message, &fields);
  1914. // Normally, the list will be exactly the size of the fields.
  1915. ScopedPyObjectPtr all_fields(PyList_New(fields.size()));
  1916. if (all_fields == NULL) {
  1917. return NULL;
  1918. }
  1919. // When there are unknown extensions, the py list will *not* contain
  1920. // the field information. Thus the actual size of the py list will be
  1921. // smaller than the size of fields. Set the actual size at the end.
  1922. Py_ssize_t actual_size = 0;
  1923. for (size_t i = 0; i < fields.size(); ++i) {
  1924. ScopedPyObjectPtr t(PyTuple_New(2));
  1925. if (t == NULL) {
  1926. return NULL;
  1927. }
  1928. if (fields[i]->is_extension()) {
  1929. ScopedPyObjectPtr extension_field(
  1930. PyFieldDescriptor_FromDescriptor(fields[i]));
  1931. if (extension_field == NULL) {
  1932. return NULL;
  1933. }
  1934. // With C++ descriptors, the field can always be retrieved, but for
  1935. // unknown extensions which have not been imported in Python code, there
  1936. // is no message class and we cannot retrieve the value.
  1937. // TODO(amauryfa): consider building the class on the fly!
  1938. if (fields[i]->message_type() != NULL &&
  1939. message_factory::GetMessageClass(
  1940. GetFactoryForMessage(self),
  1941. fields[i]->message_type()) == NULL) {
  1942. PyErr_Clear();
  1943. continue;
  1944. }
  1945. ScopedPyObjectPtr extensions(GetExtensionDict(self, NULL));
  1946. if (extensions == NULL) {
  1947. return NULL;
  1948. }
  1949. // 'extension' reference later stolen by PyTuple_SET_ITEM.
  1950. PyObject* extension = PyObject_GetItem(
  1951. extensions.get(), extension_field.get());
  1952. if (extension == NULL) {
  1953. return NULL;
  1954. }
  1955. PyTuple_SET_ITEM(t.get(), 0, extension_field.release());
  1956. // Steals reference to 'extension'
  1957. PyTuple_SET_ITEM(t.get(), 1, extension);
  1958. } else {
  1959. // Normal field
  1960. const string& field_name = fields[i]->name();
  1961. ScopedPyObjectPtr py_field_name(PyString_FromStringAndSize(
  1962. field_name.c_str(), field_name.length()));
  1963. if (py_field_name == NULL) {
  1964. PyErr_SetString(PyExc_ValueError, "bad string");
  1965. return NULL;
  1966. }
  1967. ScopedPyObjectPtr field_descriptor(
  1968. PyFieldDescriptor_FromDescriptor(fields[i]));
  1969. if (field_descriptor == NULL) {
  1970. return NULL;
  1971. }
  1972. PyObject* field_value = GetAttr(self, py_field_name.get());
  1973. if (field_value == NULL) {
  1974. PyErr_SetObject(PyExc_ValueError, py_field_name.get());
  1975. return NULL;
  1976. }
  1977. PyTuple_SET_ITEM(t.get(), 0, field_descriptor.release());
  1978. PyTuple_SET_ITEM(t.get(), 1, field_value);
  1979. }
  1980. PyList_SET_ITEM(all_fields.get(), actual_size, t.release());
  1981. ++actual_size;
  1982. }
  1983. if (static_cast<size_t>(actual_size) != fields.size() &&
  1984. (PyList_SetSlice(all_fields.get(), actual_size, fields.size(), NULL) <
  1985. 0)) {
  1986. return NULL;
  1987. }
  1988. return all_fields.release();
  1989. }
  1990. static PyObject* DiscardUnknownFields(CMessage* self) {
  1991. AssureWritable(self);
  1992. self->message->DiscardUnknownFields();
  1993. Py_RETURN_NONE;
  1994. }
  1995. PyObject* FindInitializationErrors(CMessage* self) {
  1996. Message* message = self->message;
  1997. std::vector<string> errors;
  1998. message->FindInitializationErrors(&errors);
  1999. PyObject* error_list = PyList_New(errors.size());
  2000. if (error_list == NULL) {
  2001. return NULL;
  2002. }
  2003. for (size_t i = 0; i < errors.size(); ++i) {
  2004. const string& error = errors[i];
  2005. PyObject* error_string = PyString_FromStringAndSize(
  2006. error.c_str(), error.length());
  2007. if (error_string == NULL) {
  2008. Py_DECREF(error_list);
  2009. return NULL;
  2010. }
  2011. PyList_SET_ITEM(error_list, i, error_string);
  2012. }
  2013. return error_list;
  2014. }
  2015. static PyObject* RichCompare(CMessage* self, PyObject* other, int opid) {
  2016. // Only equality comparisons are implemented.
  2017. if (opid != Py_EQ && opid != Py_NE) {
  2018. Py_INCREF(Py_NotImplemented);
  2019. return Py_NotImplemented;
  2020. }
  2021. bool equals = true;
  2022. // If other is not a message, it cannot be equal.
  2023. if (!PyObject_TypeCheck(other, &CMessage_Type)) {
  2024. equals = false;
  2025. }
  2026. const google::protobuf::Message* other_message =
  2027. reinterpret_cast<CMessage*>(other)->message;
  2028. // If messages don't have the same descriptors, they are not equal.
  2029. if (equals &&
  2030. self->message->GetDescriptor() != other_message->GetDescriptor()) {
  2031. equals = false;
  2032. }
  2033. // Check the message contents.
  2034. if (equals && !google::protobuf::util::MessageDifferencer::Equals(
  2035. *self->message,
  2036. *reinterpret_cast<CMessage*>(other)->message)) {
  2037. equals = false;
  2038. }
  2039. if (equals ^ (opid == Py_EQ)) {
  2040. Py_RETURN_FALSE;
  2041. } else {
  2042. Py_RETURN_TRUE;
  2043. }
  2044. }
  2045. PyObject* InternalGetScalar(const Message* message,
  2046. const FieldDescriptor* field_descriptor) {
  2047. const Reflection* reflection = message->GetReflection();
  2048. if (!CheckFieldBelongsToMessage(field_descriptor, message)) {
  2049. return NULL;
  2050. }
  2051. PyObject* result = NULL;
  2052. switch (field_descriptor->cpp_type()) {
  2053. case FieldDescriptor::CPPTYPE_INT32: {
  2054. int32 value = reflection->GetInt32(*message, field_descriptor);
  2055. result = PyInt_FromLong(value);
  2056. break;
  2057. }
  2058. case FieldDescriptor::CPPTYPE_INT64: {
  2059. int64 value = reflection->GetInt64(*message, field_descriptor);
  2060. result = PyLong_FromLongLong(value);
  2061. break;
  2062. }
  2063. case FieldDescriptor::CPPTYPE_UINT32: {
  2064. uint32 value = reflection->GetUInt32(*message, field_descriptor);
  2065. result = PyInt_FromSize_t(value);
  2066. break;
  2067. }
  2068. case FieldDescriptor::CPPTYPE_UINT64: {
  2069. uint64 value = reflection->GetUInt64(*message, field_descriptor);
  2070. result = PyLong_FromUnsignedLongLong(value);
  2071. break;
  2072. }
  2073. case FieldDescriptor::CPPTYPE_FLOAT: {
  2074. float value = reflection->GetFloat(*message, field_descriptor);
  2075. result = PyFloat_FromDouble(value);
  2076. break;
  2077. }
  2078. case FieldDescriptor::CPPTYPE_DOUBLE: {
  2079. double value = reflection->GetDouble(*message, field_descriptor);
  2080. result = PyFloat_FromDouble(value);
  2081. break;
  2082. }
  2083. case FieldDescriptor::CPPTYPE_BOOL: {
  2084. bool value = reflection->GetBool(*message, field_descriptor);
  2085. result = PyBool_FromLong(value);
  2086. break;
  2087. }
  2088. case FieldDescriptor::CPPTYPE_STRING: {
  2089. string value = reflection->GetString(*message, field_descriptor);
  2090. result = ToStringObject(field_descriptor, value);
  2091. break;
  2092. }
  2093. case FieldDescriptor::CPPTYPE_ENUM: {
  2094. if (!message->GetReflection()->SupportsUnknownEnumValues() &&
  2095. !message->GetReflection()->HasField(*message, field_descriptor)) {
  2096. // Look for the value in the unknown fields.
  2097. const UnknownFieldSet& unknown_field_set =
  2098. message->GetReflection()->GetUnknownFields(*message);
  2099. for (int i = 0; i < unknown_field_set.field_count(); ++i) {
  2100. if (unknown_field_set.field(i).number() ==
  2101. field_descriptor->number() &&
  2102. unknown_field_set.field(i).type() ==
  2103. google::protobuf::UnknownField::TYPE_VARINT) {
  2104. result = PyInt_FromLong(unknown_field_set.field(i).varint());
  2105. break;
  2106. }
  2107. }
  2108. }
  2109. if (result == NULL) {
  2110. const EnumValueDescriptor* enum_value =
  2111. message->GetReflection()->GetEnum(*message, field_descriptor);
  2112. result = PyInt_FromLong(enum_value->number());
  2113. }
  2114. break;
  2115. }
  2116. default:
  2117. PyErr_Format(
  2118. PyExc_SystemError, "Getting a value from a field of unknown type %d",
  2119. field_descriptor->cpp_type());
  2120. }
  2121. return result;
  2122. }
  2123. PyObject* InternalGetSubMessage(
  2124. CMessage* self, const FieldDescriptor* field_descriptor) {
  2125. const Reflection* reflection = self->message->GetReflection();
  2126. PyMessageFactory* factory = GetFactoryForMessage(self);
  2127. const Message& sub_message = reflection->GetMessage(
  2128. *self->message, field_descriptor, factory->message_factory);
  2129. CMessageClass* message_class = message_factory::GetMessageClass(
  2130. factory, field_descriptor->message_type());
  2131. if (message_class == NULL) {
  2132. return NULL;
  2133. }
  2134. CMessage* cmsg = cmessage::NewEmptyMessage(message_class);
  2135. if (cmsg == NULL) {
  2136. return NULL;
  2137. }
  2138. cmsg->owner = self->owner;
  2139. cmsg->parent = self;
  2140. cmsg->parent_field_descriptor = field_descriptor;
  2141. cmsg->read_only = !reflection->HasField(*self->message, field_descriptor);
  2142. cmsg->message = const_cast<Message*>(&sub_message);
  2143. return reinterpret_cast<PyObject*>(cmsg);
  2144. }
  2145. int InternalSetNonOneofScalar(
  2146. Message* message,
  2147. const FieldDescriptor* field_descriptor,
  2148. PyObject* arg) {
  2149. const Reflection* reflection = message->GetReflection();
  2150. if (!CheckFieldBelongsToMessage(field_descriptor, message)) {
  2151. return -1;
  2152. }
  2153. switch (field_descriptor->cpp_type()) {
  2154. case FieldDescriptor::CPPTYPE_INT32: {
  2155. GOOGLE_CHECK_GET_INT32(arg, value, -1);
  2156. reflection->SetInt32(message, field_descriptor, value);
  2157. break;
  2158. }
  2159. case FieldDescriptor::CPPTYPE_INT64: {
  2160. GOOGLE_CHECK_GET_INT64(arg, value, -1);
  2161. reflection->SetInt64(message, field_descriptor, value);
  2162. break;
  2163. }
  2164. case FieldDescriptor::CPPTYPE_UINT32: {
  2165. GOOGLE_CHECK_GET_UINT32(arg, value, -1);
  2166. reflection->SetUInt32(message, field_descriptor, value);
  2167. break;
  2168. }
  2169. case FieldDescriptor::CPPTYPE_UINT64: {
  2170. GOOGLE_CHECK_GET_UINT64(arg, value, -1);
  2171. reflection->SetUInt64(message, field_descriptor, value);
  2172. break;
  2173. }
  2174. case FieldDescriptor::CPPTYPE_FLOAT: {
  2175. GOOGLE_CHECK_GET_FLOAT(arg, value, -1);
  2176. reflection->SetFloat(message, field_descriptor, value);
  2177. break;
  2178. }
  2179. case FieldDescriptor::CPPTYPE_DOUBLE: {
  2180. GOOGLE_CHECK_GET_DOUBLE(arg, value, -1);
  2181. reflection->SetDouble(message, field_descriptor, value);
  2182. break;
  2183. }
  2184. case FieldDescriptor::CPPTYPE_BOOL: {
  2185. GOOGLE_CHECK_GET_BOOL(arg, value, -1);
  2186. reflection->SetBool(message, field_descriptor, value);
  2187. break;
  2188. }
  2189. case FieldDescriptor::CPPTYPE_STRING: {
  2190. if (!CheckAndSetString(
  2191. arg, message, field_descriptor, reflection, false, -1)) {
  2192. return -1;
  2193. }
  2194. break;
  2195. }
  2196. case FieldDescriptor::CPPTYPE_ENUM: {
  2197. GOOGLE_CHECK_GET_INT32(arg, value, -1);
  2198. if (reflection->SupportsUnknownEnumValues()) {
  2199. reflection->SetEnumValue(message, field_descriptor, value);
  2200. } else {
  2201. const EnumDescriptor* enum_descriptor = field_descriptor->enum_type();
  2202. const EnumValueDescriptor* enum_value =
  2203. enum_descriptor->FindValueByNumber(value);
  2204. if (enum_value != NULL) {
  2205. reflection->SetEnum(message, field_descriptor, enum_value);
  2206. } else {
  2207. PyErr_Format(PyExc_ValueError, "Unknown enum value: %d", value);
  2208. return -1;
  2209. }
  2210. }
  2211. break;
  2212. }
  2213. default:
  2214. PyErr_Format(
  2215. PyExc_SystemError, "Setting value to a field of unknown type %d",
  2216. field_descriptor->cpp_type());
  2217. return -1;
  2218. }
  2219. return 0;
  2220. }
  2221. int InternalSetScalar(
  2222. CMessage* self,
  2223. const FieldDescriptor* field_descriptor,
  2224. PyObject* arg) {
  2225. if (!CheckFieldBelongsToMessage(field_descriptor, self->message)) {
  2226. return -1;
  2227. }
  2228. if (MaybeReleaseOverlappingOneofField(self, field_descriptor) < 0) {
  2229. return -1;
  2230. }
  2231. return InternalSetNonOneofScalar(self->message, field_descriptor, arg);
  2232. }
  2233. PyObject* FromString(PyTypeObject* cls, PyObject* serialized) {
  2234. PyObject* py_cmsg = PyObject_CallObject(
  2235. reinterpret_cast<PyObject*>(cls), NULL);
  2236. if (py_cmsg == NULL) {
  2237. return NULL;
  2238. }
  2239. CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
  2240. ScopedPyObjectPtr py_length(MergeFromString(cmsg, serialized));
  2241. if (py_length == NULL) {
  2242. Py_DECREF(py_cmsg);
  2243. return NULL;
  2244. }
  2245. return py_cmsg;
  2246. }
  2247. PyObject* DeepCopy(CMessage* self, PyObject* arg) {
  2248. PyObject* clone = PyObject_CallObject(
  2249. reinterpret_cast<PyObject*>(Py_TYPE(self)), NULL);
  2250. if (clone == NULL) {
  2251. return NULL;
  2252. }
  2253. if (!PyObject_TypeCheck(clone, &CMessage_Type)) {
  2254. Py_DECREF(clone);
  2255. return NULL;
  2256. }
  2257. if (ScopedPyObjectPtr(MergeFrom(
  2258. reinterpret_cast<CMessage*>(clone),
  2259. reinterpret_cast<PyObject*>(self))) == NULL) {
  2260. Py_DECREF(clone);
  2261. return NULL;
  2262. }
  2263. return clone;
  2264. }
  2265. PyObject* ToUnicode(CMessage* self) {
  2266. // Lazy import to prevent circular dependencies
  2267. ScopedPyObjectPtr text_format(
  2268. PyImport_ImportModule("google.protobuf.text_format"));
  2269. if (text_format == NULL) {
  2270. return NULL;
  2271. }
  2272. ScopedPyObjectPtr method_name(PyString_FromString("MessageToString"));
  2273. if (method_name == NULL) {
  2274. return NULL;
  2275. }
  2276. Py_INCREF(Py_True);
  2277. ScopedPyObjectPtr encoded(PyObject_CallMethodObjArgs(
  2278. text_format.get(), method_name.get(), self, Py_True, NULL));
  2279. Py_DECREF(Py_True);
  2280. if (encoded == NULL) {
  2281. return NULL;
  2282. }
  2283. #if PY_MAJOR_VERSION < 3
  2284. PyObject* decoded = PyString_AsDecodedObject(encoded.get(), "utf-8", NULL);
  2285. #else
  2286. PyObject* decoded = PyUnicode_FromEncodedObject(encoded.get(), "utf-8", NULL);
  2287. #endif
  2288. if (decoded == NULL) {
  2289. return NULL;
  2290. }
  2291. return decoded;
  2292. }
  2293. PyObject* Reduce(CMessage* self) {
  2294. ScopedPyObjectPtr constructor(reinterpret_cast<PyObject*>(Py_TYPE(self)));
  2295. constructor.inc();
  2296. ScopedPyObjectPtr args(PyTuple_New(0));
  2297. if (args == NULL) {
  2298. return NULL;
  2299. }
  2300. ScopedPyObjectPtr state(PyDict_New());
  2301. if (state == NULL) {
  2302. return NULL;
  2303. }
  2304. ScopedPyObjectPtr serialized(SerializePartialToString(self));
  2305. if (serialized == NULL) {
  2306. return NULL;
  2307. }
  2308. if (PyDict_SetItemString(state.get(), "serialized", serialized.get()) < 0) {
  2309. return NULL;
  2310. }
  2311. return Py_BuildValue("OOO", constructor.get(), args.get(), state.get());
  2312. }
  2313. PyObject* SetState(CMessage* self, PyObject* state) {
  2314. if (!PyDict_Check(state)) {
  2315. PyErr_SetString(PyExc_TypeError, "state not a dict");
  2316. return NULL;
  2317. }
  2318. PyObject* serialized = PyDict_GetItemString(state, "serialized");
  2319. if (serialized == NULL) {
  2320. return NULL;
  2321. }
  2322. if (ScopedPyObjectPtr(ParseFromString(self, serialized)) == NULL) {
  2323. return NULL;
  2324. }
  2325. Py_RETURN_NONE;
  2326. }
  2327. // CMessage static methods:
  2328. PyObject* _CheckCalledFromGeneratedFile(PyObject* unused,
  2329. PyObject* unused_arg) {
  2330. if (!_CalledFromGeneratedFile(1)) {
  2331. PyErr_SetString(PyExc_TypeError,
  2332. "Descriptors should not be created directly, "
  2333. "but only retrieved from their parent.");
  2334. return NULL;
  2335. }
  2336. Py_RETURN_NONE;
  2337. }
  2338. static PyObject* GetExtensionDict(CMessage* self, void *closure) {
  2339. if (self->extensions) {
  2340. Py_INCREF(self->extensions);
  2341. return reinterpret_cast<PyObject*>(self->extensions);
  2342. }
  2343. // If there are extension_ranges, the message is "extendable". Allocate a
  2344. // dictionary to store the extension fields.
  2345. const Descriptor* descriptor = GetMessageDescriptor(Py_TYPE(self));
  2346. if (descriptor->extension_range_count() > 0) {
  2347. ExtensionDict* extension_dict = extension_dict::NewExtensionDict(self);
  2348. if (extension_dict == NULL) {
  2349. return NULL;
  2350. }
  2351. self->extensions = extension_dict;
  2352. Py_INCREF(self->extensions);
  2353. return reinterpret_cast<PyObject*>(self->extensions);
  2354. }
  2355. PyErr_SetNone(PyExc_AttributeError);
  2356. return NULL;
  2357. }
  2358. static PyObject* GetExtensionsByName(CMessage *self, void *closure) {
  2359. return message_meta::GetExtensionsByName(
  2360. reinterpret_cast<CMessageClass*>(Py_TYPE(self)), closure);
  2361. }
  2362. static PyObject* GetExtensionsByNumber(CMessage *self, void *closure) {
  2363. return message_meta::GetExtensionsByNumber(
  2364. reinterpret_cast<CMessageClass*>(Py_TYPE(self)), closure);
  2365. }
  2366. static PyGetSetDef Getters[] = {
  2367. {"Extensions", (getter)GetExtensionDict, NULL, "Extension dict"},
  2368. {"_extensions_by_name", (getter)GetExtensionsByName, NULL},
  2369. {"_extensions_by_number", (getter)GetExtensionsByNumber, NULL},
  2370. {NULL}
  2371. };
  2372. static PyMethodDef Methods[] = {
  2373. { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
  2374. "Makes a deep copy of the class." },
  2375. { "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
  2376. "Outputs picklable representation of the message." },
  2377. { "__setstate__", (PyCFunction)SetState, METH_O,
  2378. "Inputs picklable representation of the message." },
  2379. { "__unicode__", (PyCFunction)ToUnicode, METH_NOARGS,
  2380. "Outputs a unicode representation of the message." },
  2381. { "ByteSize", (PyCFunction)ByteSize, METH_NOARGS,
  2382. "Returns the size of the message in bytes." },
  2383. { "Clear", (PyCFunction)Clear, METH_NOARGS,
  2384. "Clears the message." },
  2385. { "ClearExtension", (PyCFunction)ClearExtension, METH_O,
  2386. "Clears a message field." },
  2387. { "ClearField", (PyCFunction)ClearField, METH_O,
  2388. "Clears a message field." },
  2389. { "CopyFrom", (PyCFunction)CopyFrom, METH_O,
  2390. "Copies a protocol message into the current message." },
  2391. { "DiscardUnknownFields", (PyCFunction)DiscardUnknownFields, METH_NOARGS,
  2392. "Discards the unknown fields." },
  2393. { "FindInitializationErrors", (PyCFunction)FindInitializationErrors,
  2394. METH_NOARGS,
  2395. "Finds unset required fields." },
  2396. { "FromString", (PyCFunction)FromString, METH_O | METH_CLASS,
  2397. "Creates new method instance from given serialized data." },
  2398. { "HasExtension", (PyCFunction)HasExtension, METH_O,
  2399. "Checks if a message field is set." },
  2400. { "HasField", (PyCFunction)HasField, METH_O,
  2401. "Checks if a message field is set." },
  2402. { "IsInitialized", (PyCFunction)IsInitialized, METH_VARARGS,
  2403. "Checks if all required fields of a protocol message are set." },
  2404. { "ListFields", (PyCFunction)ListFields, METH_NOARGS,
  2405. "Lists all set fields of a message." },
  2406. { "MergeFrom", (PyCFunction)MergeFrom, METH_O,
  2407. "Merges a protocol message into the current message." },
  2408. { "MergeFromString", (PyCFunction)MergeFromString, METH_O,
  2409. "Merges a serialized message into the current message." },
  2410. { "ParseFromString", (PyCFunction)ParseFromString, METH_O,
  2411. "Parses a serialized message into the current message." },
  2412. { "RegisterExtension", (PyCFunction)RegisterExtension, METH_O | METH_CLASS,
  2413. "Registers an extension with the current message." },
  2414. { "SerializePartialToString", (PyCFunction)SerializePartialToString,
  2415. METH_NOARGS,
  2416. "Serializes the message to a string, even if it isn't initialized." },
  2417. { "SerializeToString", (PyCFunction)SerializeToString, METH_NOARGS,
  2418. "Serializes the message to a string, only for initialized messages." },
  2419. { "SetInParent", (PyCFunction)SetInParent, METH_NOARGS,
  2420. "Sets the has bit of the given field in its parent message." },
  2421. { "WhichOneof", (PyCFunction)WhichOneof, METH_O,
  2422. "Returns the name of the field set inside a oneof, "
  2423. "or None if no field is set." },
  2424. // Static Methods.
  2425. { "_CheckCalledFromGeneratedFile", (PyCFunction)_CheckCalledFromGeneratedFile,
  2426. METH_NOARGS | METH_STATIC,
  2427. "Raises TypeError if the caller is not in a _pb2.py file."},
  2428. { NULL, NULL}
  2429. };
  2430. static bool SetCompositeField(
  2431. CMessage* self, PyObject* name, PyObject* value) {
  2432. if (self->composite_fields == NULL) {
  2433. self->composite_fields = PyDict_New();
  2434. if (self->composite_fields == NULL) {
  2435. return false;
  2436. }
  2437. }
  2438. return PyDict_SetItem(self->composite_fields, name, value) == 0;
  2439. }
  2440. PyObject* GetAttr(CMessage* self, PyObject* name) {
  2441. PyObject* value = self->composite_fields ?
  2442. PyDict_GetItem(self->composite_fields, name) : NULL;
  2443. if (value != NULL) {
  2444. Py_INCREF(value);
  2445. return value;
  2446. }
  2447. const FieldDescriptor* field_descriptor = GetFieldDescriptor(self, name);
  2448. if (field_descriptor == NULL) {
  2449. return CMessage_Type.tp_base->tp_getattro(
  2450. reinterpret_cast<PyObject*>(self), name);
  2451. }
  2452. if (field_descriptor->is_map()) {
  2453. PyObject* py_container = NULL;
  2454. const Descriptor* entry_type = field_descriptor->message_type();
  2455. const FieldDescriptor* value_type = entry_type->FindFieldByName("value");
  2456. if (value_type->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2457. CMessageClass* value_class = message_factory::GetMessageClass(
  2458. GetFactoryForMessage(self), value_type->message_type());
  2459. if (value_class == NULL) {
  2460. return NULL;
  2461. }
  2462. py_container =
  2463. NewMessageMapContainer(self, field_descriptor, value_class);
  2464. } else {
  2465. py_container = NewScalarMapContainer(self, field_descriptor);
  2466. }
  2467. if (py_container == NULL) {
  2468. return NULL;
  2469. }
  2470. if (!SetCompositeField(self, name, py_container)) {
  2471. Py_DECREF(py_container);
  2472. return NULL;
  2473. }
  2474. return py_container;
  2475. }
  2476. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  2477. PyObject* py_container = NULL;
  2478. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2479. CMessageClass* message_class = message_factory::GetMessageClass(
  2480. GetFactoryForMessage(self), field_descriptor->message_type());
  2481. if (message_class == NULL) {
  2482. return NULL;
  2483. }
  2484. py_container = repeated_composite_container::NewContainer(
  2485. self, field_descriptor, message_class);
  2486. } else {
  2487. py_container = repeated_scalar_container::NewContainer(
  2488. self, field_descriptor);
  2489. }
  2490. if (py_container == NULL) {
  2491. return NULL;
  2492. }
  2493. if (!SetCompositeField(self, name, py_container)) {
  2494. Py_DECREF(py_container);
  2495. return NULL;
  2496. }
  2497. return py_container;
  2498. }
  2499. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2500. PyObject* sub_message = InternalGetSubMessage(self, field_descriptor);
  2501. if (sub_message == NULL) {
  2502. return NULL;
  2503. }
  2504. if (!SetCompositeField(self, name, sub_message)) {
  2505. Py_DECREF(sub_message);
  2506. return NULL;
  2507. }
  2508. return sub_message;
  2509. }
  2510. return InternalGetScalar(self->message, field_descriptor);
  2511. }
  2512. int SetAttr(CMessage* self, PyObject* name, PyObject* value) {
  2513. if (self->composite_fields && PyDict_Contains(self->composite_fields, name)) {
  2514. PyErr_SetString(PyExc_TypeError, "Can't set composite field");
  2515. return -1;
  2516. }
  2517. const FieldDescriptor* field_descriptor = GetFieldDescriptor(self, name);
  2518. if (field_descriptor != NULL) {
  2519. AssureWritable(self);
  2520. if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
  2521. PyErr_Format(PyExc_AttributeError, "Assignment not allowed to repeated "
  2522. "field \"%s\" in protocol message object.",
  2523. field_descriptor->name().c_str());
  2524. return -1;
  2525. } else {
  2526. if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  2527. PyErr_Format(PyExc_AttributeError, "Assignment not allowed to "
  2528. "field \"%s\" in protocol message object.",
  2529. field_descriptor->name().c_str());
  2530. return -1;
  2531. } else {
  2532. return InternalSetScalar(self, field_descriptor, value);
  2533. }
  2534. }
  2535. }
  2536. PyErr_Format(PyExc_AttributeError,
  2537. "Assignment not allowed "
  2538. "(no field \"%s\" in protocol message object).",
  2539. PyString_AsString(name));
  2540. return -1;
  2541. }
  2542. } // namespace cmessage
  2543. PyTypeObject CMessage_Type = {
  2544. PyVarObject_HEAD_INIT(&CMessageClass_Type, 0)
  2545. FULL_MODULE_NAME ".CMessage", // tp_name
  2546. sizeof(CMessage), // tp_basicsize
  2547. 0, // tp_itemsize
  2548. (destructor)cmessage::Dealloc, // tp_dealloc
  2549. 0, // tp_print
  2550. 0, // tp_getattr
  2551. 0, // tp_setattr
  2552. 0, // tp_compare
  2553. (reprfunc)cmessage::ToStr, // tp_repr
  2554. 0, // tp_as_number
  2555. 0, // tp_as_sequence
  2556. 0, // tp_as_mapping
  2557. PyObject_HashNotImplemented, // tp_hash
  2558. 0, // tp_call
  2559. (reprfunc)cmessage::ToStr, // tp_str
  2560. (getattrofunc)cmessage::GetAttr, // tp_getattro
  2561. (setattrofunc)cmessage::SetAttr, // tp_setattro
  2562. 0, // tp_as_buffer
  2563. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
  2564. "A ProtocolMessage", // tp_doc
  2565. 0, // tp_traverse
  2566. 0, // tp_clear
  2567. (richcmpfunc)cmessage::RichCompare, // tp_richcompare
  2568. offsetof(CMessage, weakreflist), // tp_weaklistoffset
  2569. 0, // tp_iter
  2570. 0, // tp_iternext
  2571. cmessage::Methods, // tp_methods
  2572. 0, // tp_members
  2573. cmessage::Getters, // tp_getset
  2574. 0, // tp_base
  2575. 0, // tp_dict
  2576. 0, // tp_descr_get
  2577. 0, // tp_descr_set
  2578. 0, // tp_dictoffset
  2579. (initproc)cmessage::Init, // tp_init
  2580. 0, // tp_alloc
  2581. cmessage::New, // tp_new
  2582. };
  2583. // --- Exposing the C proto living inside Python proto to C code:
  2584. const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg);
  2585. Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg);
  2586. static const Message* GetCProtoInsidePyProtoImpl(PyObject* msg) {
  2587. if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
  2588. return NULL;
  2589. }
  2590. CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
  2591. return cmsg->message;
  2592. }
  2593. static Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
  2594. if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
  2595. return NULL;
  2596. }
  2597. CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
  2598. if ((cmsg->composite_fields && PyDict_Size(cmsg->composite_fields) != 0) ||
  2599. (cmsg->extensions != NULL &&
  2600. PyDict_Size(cmsg->extensions->values) != 0)) {
  2601. // There is currently no way of accurately syncing arbitrary changes to
  2602. // the underlying C++ message back to the CMessage (e.g. removed repeated
  2603. // composite containers). We only allow direct mutation of the underlying
  2604. // C++ message if there is no child data in the CMessage.
  2605. return NULL;
  2606. }
  2607. cmessage::AssureWritable(cmsg);
  2608. return cmsg->message;
  2609. }
  2610. void InitGlobals() {
  2611. // TODO(gps): Check all return values in this function for NULL and propagate
  2612. // the error (MemoryError) on up to result in an import failure. These should
  2613. // also be freed and reset to NULL during finalization.
  2614. kDESCRIPTOR = PyString_FromString("DESCRIPTOR");
  2615. PyObject *dummy_obj = PySet_New(NULL);
  2616. kEmptyWeakref = PyWeakref_NewRef(dummy_obj, NULL);
  2617. Py_DECREF(dummy_obj);
  2618. }
  2619. bool InitProto2MessageModule(PyObject *m) {
  2620. // Initialize types and globals in descriptor.cc
  2621. if (!InitDescriptor()) {
  2622. return false;
  2623. }
  2624. // Initialize types and globals in descriptor_pool.cc
  2625. if (!InitDescriptorPool()) {
  2626. return false;
  2627. }
  2628. // Initialize types and globals in message_factory.cc
  2629. if (!InitMessageFactory()) {
  2630. return false;
  2631. }
  2632. // Initialize constants defined in this file.
  2633. InitGlobals();
  2634. CMessageClass_Type.tp_base = &PyType_Type;
  2635. if (PyType_Ready(&CMessageClass_Type) < 0) {
  2636. return false;
  2637. }
  2638. PyModule_AddObject(m, "MessageMeta",
  2639. reinterpret_cast<PyObject*>(&CMessageClass_Type));
  2640. if (PyType_Ready(&CMessage_Type) < 0) {
  2641. return false;
  2642. }
  2643. // DESCRIPTOR is set on each protocol buffer message class elsewhere, but set
  2644. // it here as well to document that subclasses need to set it.
  2645. PyDict_SetItem(CMessage_Type.tp_dict, kDESCRIPTOR, Py_None);
  2646. PyModule_AddObject(m, "Message", reinterpret_cast<PyObject*>(&CMessage_Type));
  2647. // Initialize Repeated container types.
  2648. {
  2649. if (PyType_Ready(&RepeatedScalarContainer_Type) < 0) {
  2650. return false;
  2651. }
  2652. PyModule_AddObject(m, "RepeatedScalarContainer",
  2653. reinterpret_cast<PyObject*>(
  2654. &RepeatedScalarContainer_Type));
  2655. if (PyType_Ready(&RepeatedCompositeContainer_Type) < 0) {
  2656. return false;
  2657. }
  2658. PyModule_AddObject(
  2659. m, "RepeatedCompositeContainer",
  2660. reinterpret_cast<PyObject*>(
  2661. &RepeatedCompositeContainer_Type));
  2662. // Register them as collections.Sequence
  2663. ScopedPyObjectPtr collections(PyImport_ImportModule("collections"));
  2664. if (collections == NULL) {
  2665. return false;
  2666. }
  2667. ScopedPyObjectPtr mutable_sequence(
  2668. PyObject_GetAttrString(collections.get(), "MutableSequence"));
  2669. if (mutable_sequence == NULL) {
  2670. return false;
  2671. }
  2672. if (ScopedPyObjectPtr(
  2673. PyObject_CallMethod(mutable_sequence.get(), "register", "O",
  2674. &RepeatedScalarContainer_Type)) == NULL) {
  2675. return false;
  2676. }
  2677. if (ScopedPyObjectPtr(
  2678. PyObject_CallMethod(mutable_sequence.get(), "register", "O",
  2679. &RepeatedCompositeContainer_Type)) == NULL) {
  2680. return false;
  2681. }
  2682. }
  2683. // Initialize Map container types.
  2684. if (!InitMapContainers()) {
  2685. return false;
  2686. }
  2687. PyModule_AddObject(m, "ScalarMapContainer",
  2688. reinterpret_cast<PyObject*>(ScalarMapContainer_Type));
  2689. PyModule_AddObject(m, "MessageMapContainer",
  2690. reinterpret_cast<PyObject*>(MessageMapContainer_Type));
  2691. PyModule_AddObject(m, "MapIterator",
  2692. reinterpret_cast<PyObject*>(&MapIterator_Type));
  2693. if (PyType_Ready(&ExtensionDict_Type) < 0) {
  2694. return false;
  2695. }
  2696. PyModule_AddObject(
  2697. m, "ExtensionDict",
  2698. reinterpret_cast<PyObject*>(&ExtensionDict_Type));
  2699. // Expose the DescriptorPool used to hold all descriptors added from generated
  2700. // pb2.py files.
  2701. // PyModule_AddObject steals a reference.
  2702. Py_INCREF(GetDefaultDescriptorPool());
  2703. PyModule_AddObject(m, "default_pool",
  2704. reinterpret_cast<PyObject*>(GetDefaultDescriptorPool()));
  2705. PyModule_AddObject(m, "DescriptorPool", reinterpret_cast<PyObject*>(
  2706. &PyDescriptorPool_Type));
  2707. // This implementation provides full Descriptor types, we advertise it so that
  2708. // descriptor.py can use them in replacement of the Python classes.
  2709. PyModule_AddIntConstant(m, "_USE_C_DESCRIPTORS", 1);
  2710. PyModule_AddObject(m, "Descriptor", reinterpret_cast<PyObject*>(
  2711. &PyMessageDescriptor_Type));
  2712. PyModule_AddObject(m, "FieldDescriptor", reinterpret_cast<PyObject*>(
  2713. &PyFieldDescriptor_Type));
  2714. PyModule_AddObject(m, "EnumDescriptor", reinterpret_cast<PyObject*>(
  2715. &PyEnumDescriptor_Type));
  2716. PyModule_AddObject(m, "EnumValueDescriptor", reinterpret_cast<PyObject*>(
  2717. &PyEnumValueDescriptor_Type));
  2718. PyModule_AddObject(m, "FileDescriptor", reinterpret_cast<PyObject*>(
  2719. &PyFileDescriptor_Type));
  2720. PyModule_AddObject(m, "OneofDescriptor", reinterpret_cast<PyObject*>(
  2721. &PyOneofDescriptor_Type));
  2722. PyModule_AddObject(m, "ServiceDescriptor", reinterpret_cast<PyObject*>(
  2723. &PyServiceDescriptor_Type));
  2724. PyModule_AddObject(m, "MethodDescriptor", reinterpret_cast<PyObject*>(
  2725. &PyMethodDescriptor_Type));
  2726. PyObject* enum_type_wrapper = PyImport_ImportModule(
  2727. "google.protobuf.internal.enum_type_wrapper");
  2728. if (enum_type_wrapper == NULL) {
  2729. return false;
  2730. }
  2731. EnumTypeWrapper_class =
  2732. PyObject_GetAttrString(enum_type_wrapper, "EnumTypeWrapper");
  2733. Py_DECREF(enum_type_wrapper);
  2734. PyObject* message_module = PyImport_ImportModule(
  2735. "google.protobuf.message");
  2736. if (message_module == NULL) {
  2737. return false;
  2738. }
  2739. EncodeError_class = PyObject_GetAttrString(message_module, "EncodeError");
  2740. DecodeError_class = PyObject_GetAttrString(message_module, "DecodeError");
  2741. PythonMessage_class = PyObject_GetAttrString(message_module, "Message");
  2742. Py_DECREF(message_module);
  2743. PyObject* pickle_module = PyImport_ImportModule("pickle");
  2744. if (pickle_module == NULL) {
  2745. return false;
  2746. }
  2747. PickleError_class = PyObject_GetAttrString(pickle_module, "PickleError");
  2748. Py_DECREF(pickle_module);
  2749. // Override {Get,Mutable}CProtoInsidePyProto.
  2750. GetCProtoInsidePyProtoPtr = GetCProtoInsidePyProtoImpl;
  2751. MutableCProtoInsidePyProtoPtr = MutableCProtoInsidePyProtoImpl;
  2752. return true;
  2753. }
  2754. } // namespace python
  2755. } // namespace protobuf
  2756. } // namespace google