descriptor_pool.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. // Implements the DescriptorPool, which collects all descriptors.
  31. #include <Python.h>
  32. #include <google/protobuf/descriptor.pb.h>
  33. #include <google/protobuf/dynamic_message.h>
  34. #include <google/protobuf/pyext/descriptor.h>
  35. #include <google/protobuf/pyext/descriptor_database.h>
  36. #include <google/protobuf/pyext/descriptor_pool.h>
  37. #include <google/protobuf/pyext/message.h>
  38. #include <google/protobuf/pyext/scoped_pyobject_ptr.h>
  39. #if PY_MAJOR_VERSION >= 3
  40. #define PyString_FromStringAndSize PyUnicode_FromStringAndSize
  41. #if PY_VERSION_HEX < 0x03030000
  42. #error "Python 3.0 - 3.2 are not supported."
  43. #endif
  44. #define PyString_AsStringAndSize(ob, charpp, sizep) \
  45. (PyUnicode_Check(ob)? \
  46. ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
  47. PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
  48. #endif
  49. namespace google {
  50. namespace protobuf {
  51. namespace python {
  52. // A map to cache Python Pools per C++ pointer.
  53. // Pointers are not owned here, and belong to the PyDescriptorPool.
  54. static hash_map<const DescriptorPool*, PyDescriptorPool*> descriptor_pool_map;
  55. namespace cdescriptor_pool {
  56. // Create a Python DescriptorPool object, but does not fill the "pool"
  57. // attribute.
  58. static PyDescriptorPool* _CreateDescriptorPool() {
  59. PyDescriptorPool* cpool = PyObject_New(
  60. PyDescriptorPool, &PyDescriptorPool_Type);
  61. if (cpool == NULL) {
  62. return NULL;
  63. }
  64. cpool->underlay = NULL;
  65. cpool->database = NULL;
  66. DynamicMessageFactory* message_factory = new DynamicMessageFactory();
  67. // This option might be the default some day.
  68. message_factory->SetDelegateToGeneratedFactory(true);
  69. cpool->message_factory = message_factory;
  70. // TODO(amauryfa): Rewrite the SymbolDatabase in C so that it uses the same
  71. // storage.
  72. cpool->classes_by_descriptor =
  73. new PyDescriptorPool::ClassesByMessageMap();
  74. cpool->descriptor_options =
  75. new hash_map<const void*, PyObject *>();
  76. return cpool;
  77. }
  78. // Create a Python DescriptorPool, using the given pool as an underlay:
  79. // new messages will be added to a custom pool, not to the underlay.
  80. //
  81. // Ownership of the underlay is not transferred, its pointer should
  82. // stay alive.
  83. static PyDescriptorPool* PyDescriptorPool_NewWithUnderlay(
  84. const DescriptorPool* underlay) {
  85. PyDescriptorPool* cpool = _CreateDescriptorPool();
  86. if (cpool == NULL) {
  87. return NULL;
  88. }
  89. cpool->pool = new DescriptorPool(underlay);
  90. cpool->underlay = underlay;
  91. if (!descriptor_pool_map.insert(
  92. std::make_pair(cpool->pool, cpool)).second) {
  93. // Should never happen -- would indicate an internal error / bug.
  94. PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
  95. return NULL;
  96. }
  97. return cpool;
  98. }
  99. static PyDescriptorPool* PyDescriptorPool_NewWithDatabase(
  100. DescriptorDatabase* database) {
  101. PyDescriptorPool* cpool = _CreateDescriptorPool();
  102. if (cpool == NULL) {
  103. return NULL;
  104. }
  105. if (database != NULL) {
  106. cpool->pool = new DescriptorPool(database);
  107. cpool->database = database;
  108. } else {
  109. cpool->pool = new DescriptorPool();
  110. }
  111. if (!descriptor_pool_map.insert(std::make_pair(cpool->pool, cpool)).second) {
  112. // Should never happen -- would indicate an internal error / bug.
  113. PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
  114. return NULL;
  115. }
  116. return cpool;
  117. }
  118. // The public DescriptorPool constructor.
  119. static PyObject* New(PyTypeObject* type,
  120. PyObject* args, PyObject* kwargs) {
  121. static char* kwlist[] = {"descriptor_db", 0};
  122. PyObject* py_database = NULL;
  123. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &py_database)) {
  124. return NULL;
  125. }
  126. DescriptorDatabase* database = NULL;
  127. if (py_database && py_database != Py_None) {
  128. database = new PyDescriptorDatabase(py_database);
  129. }
  130. return reinterpret_cast<PyObject*>(
  131. PyDescriptorPool_NewWithDatabase(database));
  132. }
  133. static void Dealloc(PyDescriptorPool* self) {
  134. typedef PyDescriptorPool::ClassesByMessageMap::iterator iterator;
  135. descriptor_pool_map.erase(self->pool);
  136. for (iterator it = self->classes_by_descriptor->begin();
  137. it != self->classes_by_descriptor->end(); ++it) {
  138. Py_DECREF(it->second);
  139. }
  140. delete self->classes_by_descriptor;
  141. for (hash_map<const void*, PyObject*>::iterator it =
  142. self->descriptor_options->begin();
  143. it != self->descriptor_options->end(); ++it) {
  144. Py_DECREF(it->second);
  145. }
  146. delete self->descriptor_options;
  147. delete self->message_factory;
  148. delete self->database;
  149. delete self->pool;
  150. Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
  151. }
  152. PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) {
  153. Py_ssize_t name_size;
  154. char* name;
  155. if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
  156. return NULL;
  157. }
  158. const Descriptor* message_descriptor =
  159. self->pool->FindMessageTypeByName(string(name, name_size));
  160. if (message_descriptor == NULL) {
  161. PyErr_Format(PyExc_KeyError, "Couldn't find message %.200s", name);
  162. return NULL;
  163. }
  164. return PyMessageDescriptor_FromDescriptor(message_descriptor);
  165. }
  166. // Add a message class to our database.
  167. int RegisterMessageClass(PyDescriptorPool* self,
  168. const Descriptor *message_descriptor,
  169. PyObject *message_class) {
  170. Py_INCREF(message_class);
  171. typedef PyDescriptorPool::ClassesByMessageMap::iterator iterator;
  172. std::pair<iterator, bool> ret = self->classes_by_descriptor->insert(
  173. std::make_pair(message_descriptor, message_class));
  174. if (!ret.second) {
  175. // Update case: DECREF the previous value.
  176. Py_DECREF(ret.first->second);
  177. ret.first->second = message_class;
  178. }
  179. return 0;
  180. }
  181. // Retrieve the message class added to our database.
  182. PyObject *GetMessageClass(PyDescriptorPool* self,
  183. const Descriptor *message_descriptor) {
  184. typedef PyDescriptorPool::ClassesByMessageMap::iterator iterator;
  185. iterator ret = self->classes_by_descriptor->find(message_descriptor);
  186. if (ret == self->classes_by_descriptor->end()) {
  187. PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
  188. message_descriptor->full_name().c_str());
  189. return NULL;
  190. } else {
  191. return ret->second;
  192. }
  193. }
  194. PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) {
  195. Py_ssize_t name_size;
  196. char* name;
  197. if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
  198. return NULL;
  199. }
  200. const FileDescriptor* file_descriptor =
  201. self->pool->FindFileByName(string(name, name_size));
  202. if (file_descriptor == NULL) {
  203. PyErr_Format(PyExc_KeyError, "Couldn't find file %.200s",
  204. name);
  205. return NULL;
  206. }
  207. return PyFileDescriptor_FromDescriptor(file_descriptor);
  208. }
  209. PyObject* FindFieldByName(PyDescriptorPool* self, PyObject* arg) {
  210. Py_ssize_t name_size;
  211. char* name;
  212. if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
  213. return NULL;
  214. }
  215. const FieldDescriptor* field_descriptor =
  216. self->pool->FindFieldByName(string(name, name_size));
  217. if (field_descriptor == NULL) {
  218. PyErr_Format(PyExc_KeyError, "Couldn't find field %.200s",
  219. name);
  220. return NULL;
  221. }
  222. return PyFieldDescriptor_FromDescriptor(field_descriptor);
  223. }
  224. PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) {
  225. Py_ssize_t name_size;
  226. char* name;
  227. if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
  228. return NULL;
  229. }
  230. const FieldDescriptor* field_descriptor =
  231. self->pool->FindExtensionByName(string(name, name_size));
  232. if (field_descriptor == NULL) {
  233. PyErr_Format(PyExc_KeyError, "Couldn't find extension field %.200s", name);
  234. return NULL;
  235. }
  236. return PyFieldDescriptor_FromDescriptor(field_descriptor);
  237. }
  238. PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) {
  239. Py_ssize_t name_size;
  240. char* name;
  241. if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
  242. return NULL;
  243. }
  244. const EnumDescriptor* enum_descriptor =
  245. self->pool->FindEnumTypeByName(string(name, name_size));
  246. if (enum_descriptor == NULL) {
  247. PyErr_Format(PyExc_KeyError, "Couldn't find enum %.200s", name);
  248. return NULL;
  249. }
  250. return PyEnumDescriptor_FromDescriptor(enum_descriptor);
  251. }
  252. PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) {
  253. Py_ssize_t name_size;
  254. char* name;
  255. if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
  256. return NULL;
  257. }
  258. const OneofDescriptor* oneof_descriptor =
  259. self->pool->FindOneofByName(string(name, name_size));
  260. if (oneof_descriptor == NULL) {
  261. PyErr_Format(PyExc_KeyError, "Couldn't find oneof %.200s", name);
  262. return NULL;
  263. }
  264. return PyOneofDescriptor_FromDescriptor(oneof_descriptor);
  265. }
  266. PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) {
  267. Py_ssize_t name_size;
  268. char* name;
  269. if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
  270. return NULL;
  271. }
  272. const FileDescriptor* file_descriptor =
  273. self->pool->FindFileContainingSymbol(string(name, name_size));
  274. if (file_descriptor == NULL) {
  275. PyErr_Format(PyExc_KeyError, "Couldn't find symbol %.200s", name);
  276. return NULL;
  277. }
  278. return PyFileDescriptor_FromDescriptor(file_descriptor);
  279. }
  280. // These functions should not exist -- the only valid way to create
  281. // descriptors is to call Add() or AddSerializedFile().
  282. // But these AddDescriptor() functions were created in Python and some people
  283. // call them, so we support them for now for compatibility.
  284. // However we do check that the existing descriptor already exists in the pool,
  285. // which appears to always be true for existing calls -- but then why do people
  286. // call a function that will just be a no-op?
  287. // TODO(amauryfa): Need to investigate further.
  288. PyObject* AddFileDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
  289. const FileDescriptor* file_descriptor =
  290. PyFileDescriptor_AsDescriptor(descriptor);
  291. if (!file_descriptor) {
  292. return NULL;
  293. }
  294. if (file_descriptor !=
  295. self->pool->FindFileByName(file_descriptor->name())) {
  296. PyErr_Format(PyExc_ValueError,
  297. "The file descriptor %s does not belong to this pool",
  298. file_descriptor->name().c_str());
  299. return NULL;
  300. }
  301. Py_RETURN_NONE;
  302. }
  303. PyObject* AddDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
  304. const Descriptor* message_descriptor =
  305. PyMessageDescriptor_AsDescriptor(descriptor);
  306. if (!message_descriptor) {
  307. return NULL;
  308. }
  309. if (message_descriptor !=
  310. self->pool->FindMessageTypeByName(message_descriptor->full_name())) {
  311. PyErr_Format(PyExc_ValueError,
  312. "The message descriptor %s does not belong to this pool",
  313. message_descriptor->full_name().c_str());
  314. return NULL;
  315. }
  316. Py_RETURN_NONE;
  317. }
  318. PyObject* AddEnumDescriptor(PyDescriptorPool* self, PyObject* descriptor) {
  319. const EnumDescriptor* enum_descriptor =
  320. PyEnumDescriptor_AsDescriptor(descriptor);
  321. if (!enum_descriptor) {
  322. return NULL;
  323. }
  324. if (enum_descriptor !=
  325. self->pool->FindEnumTypeByName(enum_descriptor->full_name())) {
  326. PyErr_Format(PyExc_ValueError,
  327. "The enum descriptor %s does not belong to this pool",
  328. enum_descriptor->full_name().c_str());
  329. return NULL;
  330. }
  331. Py_RETURN_NONE;
  332. }
  333. // The code below loads new Descriptors from a serialized FileDescriptorProto.
  334. // Collects errors that occur during proto file building to allow them to be
  335. // propagated in the python exception instead of only living in ERROR logs.
  336. class BuildFileErrorCollector : public DescriptorPool::ErrorCollector {
  337. public:
  338. BuildFileErrorCollector() : error_message(""), had_errors(false) {}
  339. void AddError(const string& filename, const string& element_name,
  340. const Message* descriptor, ErrorLocation location,
  341. const string& message) {
  342. // Replicates the logging behavior that happens in the C++ implementation
  343. // when an error collector is not passed in.
  344. if (!had_errors) {
  345. error_message +=
  346. ("Invalid proto descriptor for file \"" + filename + "\":\n");
  347. had_errors = true;
  348. }
  349. // As this only happens on failure and will result in the program not
  350. // running at all, no effort is made to optimize this string manipulation.
  351. error_message += (" " + element_name + ": " + message + "\n");
  352. }
  353. string error_message;
  354. bool had_errors;
  355. };
  356. PyObject* AddSerializedFile(PyDescriptorPool* self, PyObject* serialized_pb) {
  357. char* message_type;
  358. Py_ssize_t message_len;
  359. if (self->database != NULL) {
  360. PyErr_SetString(
  361. PyExc_ValueError,
  362. "Cannot call Add on a DescriptorPool that uses a DescriptorDatabase. "
  363. "Add your file to the underlying database.");
  364. return NULL;
  365. }
  366. if (PyBytes_AsStringAndSize(serialized_pb, &message_type, &message_len) < 0) {
  367. return NULL;
  368. }
  369. FileDescriptorProto file_proto;
  370. if (!file_proto.ParseFromArray(message_type, message_len)) {
  371. PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!");
  372. return NULL;
  373. }
  374. // If the file was already part of a C++ library, all its descriptors are in
  375. // the underlying pool. No need to do anything else.
  376. const FileDescriptor* generated_file = NULL;
  377. if (self->underlay) {
  378. generated_file = self->underlay->FindFileByName(file_proto.name());
  379. }
  380. if (generated_file != NULL) {
  381. return PyFileDescriptor_FromDescriptorWithSerializedPb(
  382. generated_file, serialized_pb);
  383. }
  384. BuildFileErrorCollector error_collector;
  385. const FileDescriptor* descriptor =
  386. self->pool->BuildFileCollectingErrors(file_proto,
  387. &error_collector);
  388. if (descriptor == NULL) {
  389. PyErr_Format(PyExc_TypeError,
  390. "Couldn't build proto file into descriptor pool!\n%s",
  391. error_collector.error_message.c_str());
  392. return NULL;
  393. }
  394. return PyFileDescriptor_FromDescriptorWithSerializedPb(
  395. descriptor, serialized_pb);
  396. }
  397. PyObject* Add(PyDescriptorPool* self, PyObject* file_descriptor_proto) {
  398. ScopedPyObjectPtr serialized_pb(
  399. PyObject_CallMethod(file_descriptor_proto, "SerializeToString", NULL));
  400. if (serialized_pb == NULL) {
  401. return NULL;
  402. }
  403. return AddSerializedFile(self, serialized_pb.get());
  404. }
  405. static PyMethodDef Methods[] = {
  406. { "Add", (PyCFunction)Add, METH_O,
  407. "Adds the FileDescriptorProto and its types to this pool." },
  408. { "AddSerializedFile", (PyCFunction)AddSerializedFile, METH_O,
  409. "Adds a serialized FileDescriptorProto to this pool." },
  410. // TODO(amauryfa): Understand why the Python implementation differs from
  411. // this one, ask users to use another API and deprecate these functions.
  412. { "AddFileDescriptor", (PyCFunction)AddFileDescriptor, METH_O,
  413. "No-op. Add() must have been called before." },
  414. { "AddDescriptor", (PyCFunction)AddDescriptor, METH_O,
  415. "No-op. Add() must have been called before." },
  416. { "AddEnumDescriptor", (PyCFunction)AddEnumDescriptor, METH_O,
  417. "No-op. Add() must have been called before." },
  418. { "FindFileByName", (PyCFunction)FindFileByName, METH_O,
  419. "Searches for a file descriptor by its .proto name." },
  420. { "FindMessageTypeByName", (PyCFunction)FindMessageByName, METH_O,
  421. "Searches for a message descriptor by full name." },
  422. { "FindFieldByName", (PyCFunction)FindFieldByName, METH_O,
  423. "Searches for a field descriptor by full name." },
  424. { "FindExtensionByName", (PyCFunction)FindExtensionByName, METH_O,
  425. "Searches for extension descriptor by full name." },
  426. { "FindEnumTypeByName", (PyCFunction)FindEnumTypeByName, METH_O,
  427. "Searches for enum type descriptor by full name." },
  428. { "FindOneofByName", (PyCFunction)FindOneofByName, METH_O,
  429. "Searches for oneof descriptor by full name." },
  430. { "FindFileContainingSymbol", (PyCFunction)FindFileContainingSymbol, METH_O,
  431. "Gets the FileDescriptor containing the specified symbol." },
  432. {NULL}
  433. };
  434. } // namespace cdescriptor_pool
  435. PyTypeObject PyDescriptorPool_Type = {
  436. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  437. FULL_MODULE_NAME ".DescriptorPool", // tp_name
  438. sizeof(PyDescriptorPool), // tp_basicsize
  439. 0, // tp_itemsize
  440. (destructor)cdescriptor_pool::Dealloc, // tp_dealloc
  441. 0, // tp_print
  442. 0, // tp_getattr
  443. 0, // tp_setattr
  444. 0, // tp_compare
  445. 0, // tp_repr
  446. 0, // tp_as_number
  447. 0, // tp_as_sequence
  448. 0, // tp_as_mapping
  449. 0, // tp_hash
  450. 0, // tp_call
  451. 0, // tp_str
  452. 0, // tp_getattro
  453. 0, // tp_setattro
  454. 0, // tp_as_buffer
  455. Py_TPFLAGS_DEFAULT, // tp_flags
  456. "A Descriptor Pool", // tp_doc
  457. 0, // tp_traverse
  458. 0, // tp_clear
  459. 0, // tp_richcompare
  460. 0, // tp_weaklistoffset
  461. 0, // tp_iter
  462. 0, // tp_iternext
  463. cdescriptor_pool::Methods, // tp_methods
  464. 0, // tp_members
  465. 0, // tp_getset
  466. 0, // tp_base
  467. 0, // tp_dict
  468. 0, // tp_descr_get
  469. 0, // tp_descr_set
  470. 0, // tp_dictoffset
  471. 0, // tp_init
  472. 0, // tp_alloc
  473. cdescriptor_pool::New, // tp_new
  474. PyObject_Del, // tp_free
  475. };
  476. // This is the DescriptorPool which contains all the definitions from the
  477. // generated _pb2.py modules.
  478. static PyDescriptorPool* python_generated_pool = NULL;
  479. bool InitDescriptorPool() {
  480. if (PyType_Ready(&PyDescriptorPool_Type) < 0)
  481. return false;
  482. // The Pool of messages declared in Python libraries.
  483. // generated_pool() contains all messages already linked in C++ libraries, and
  484. // is used as underlay.
  485. python_generated_pool = cdescriptor_pool::PyDescriptorPool_NewWithUnderlay(
  486. DescriptorPool::generated_pool());
  487. if (python_generated_pool == NULL) {
  488. return false;
  489. }
  490. // Register this pool to be found for C++-generated descriptors.
  491. descriptor_pool_map.insert(
  492. std::make_pair(DescriptorPool::generated_pool(),
  493. python_generated_pool));
  494. return true;
  495. }
  496. // The default DescriptorPool used everywhere in this module.
  497. // Today it's the python_generated_pool.
  498. // TODO(amauryfa): Remove all usages of this function: the pool should be
  499. // derived from the context.
  500. PyDescriptorPool* GetDefaultDescriptorPool() {
  501. return python_generated_pool;
  502. }
  503. PyDescriptorPool* GetDescriptorPool_FromPool(const DescriptorPool* pool) {
  504. // Fast path for standard descriptors.
  505. if (pool == python_generated_pool->pool ||
  506. pool == DescriptorPool::generated_pool()) {
  507. return python_generated_pool;
  508. }
  509. hash_map<const DescriptorPool*, PyDescriptorPool*>::iterator it =
  510. descriptor_pool_map.find(pool);
  511. if (it == descriptor_pool_map.end()) {
  512. PyErr_SetString(PyExc_KeyError, "Unknown descriptor pool");
  513. return NULL;
  514. }
  515. return it->second;
  516. }
  517. } // namespace python
  518. } // namespace protobuf
  519. } // namespace google