defs.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2014 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. #include "protobuf.h"
  31. // -----------------------------------------------------------------------------
  32. // Common utilities.
  33. // -----------------------------------------------------------------------------
  34. const char* kDescriptorInstanceVar = "descriptor";
  35. static const char* get_str(VALUE str) {
  36. Check_Type(str, T_STRING);
  37. return RSTRING_PTR(str);
  38. }
  39. static VALUE rb_str_maybe_null(const char* s) {
  40. if (s == NULL) {
  41. s = "";
  42. }
  43. return rb_str_new2(s);
  44. }
  45. static upb_def* check_notfrozen(const upb_def* def) {
  46. if (upb_def_isfrozen(def)) {
  47. rb_raise(rb_eRuntimeError,
  48. "Attempt to modify a frozen descriptor. Once descriptors are "
  49. "added to the descriptor pool, they may not be modified.");
  50. }
  51. return (upb_def*)def;
  52. }
  53. static upb_msgdef* check_msg_notfrozen(const upb_msgdef* def) {
  54. return (upb_msgdef*)check_notfrozen((const upb_def*)def);
  55. }
  56. static upb_fielddef* check_field_notfrozen(const upb_fielddef* def) {
  57. return (upb_fielddef*)check_notfrozen((const upb_def*)def);
  58. }
  59. static upb_enumdef* check_enum_notfrozen(const upb_enumdef* def) {
  60. return (upb_enumdef*)check_notfrozen((const upb_def*)def);
  61. }
  62. // -----------------------------------------------------------------------------
  63. // DescriptorPool.
  64. // -----------------------------------------------------------------------------
  65. #define DEFINE_CLASS(name, string_name) \
  66. VALUE c ## name; \
  67. const rb_data_type_t _ ## name ## _type = { \
  68. string_name, \
  69. { name ## _mark, name ## _free, NULL }, \
  70. }; \
  71. name* ruby_to_ ## name(VALUE val) { \
  72. name* ret; \
  73. TypedData_Get_Struct(val, name, &_ ## name ## _type, ret); \
  74. return ret; \
  75. } \
  76. #define DEFINE_SELF(type, var, rb_var) \
  77. type* var = ruby_to_ ## type(rb_var);
  78. // Global singleton DescriptorPool. The user is free to create others, but this
  79. // is used by generated code.
  80. VALUE generated_pool;
  81. DEFINE_CLASS(DescriptorPool, "Google::Protobuf::DescriptorPool");
  82. void DescriptorPool_mark(void* _self) {
  83. }
  84. void DescriptorPool_free(void* _self) {
  85. DescriptorPool* self = _self;
  86. upb_symtab_unref(self->symtab, &self->symtab);
  87. xfree(self);
  88. }
  89. /*
  90. * call-seq:
  91. * DescriptorPool.new => pool
  92. *
  93. * Creates a new, empty, descriptor pool.
  94. */
  95. VALUE DescriptorPool_alloc(VALUE klass) {
  96. DescriptorPool* self = ALLOC(DescriptorPool);
  97. self->symtab = upb_symtab_new(&self->symtab);
  98. return TypedData_Wrap_Struct(klass, &_DescriptorPool_type, self);
  99. }
  100. void DescriptorPool_register(VALUE module) {
  101. VALUE klass = rb_define_class_under(
  102. module, "DescriptorPool", rb_cObject);
  103. rb_define_alloc_func(klass, DescriptorPool_alloc);
  104. rb_define_method(klass, "add", DescriptorPool_add, 1);
  105. rb_define_method(klass, "build", DescriptorPool_build, 0);
  106. rb_define_method(klass, "lookup", DescriptorPool_lookup, 1);
  107. rb_define_singleton_method(klass, "generated_pool",
  108. DescriptorPool_generated_pool, 0);
  109. cDescriptorPool = klass;
  110. rb_gc_register_address(&cDescriptorPool);
  111. generated_pool = rb_class_new_instance(0, NULL, klass);
  112. rb_gc_register_address(&generated_pool);
  113. }
  114. static void add_descriptor_to_pool(DescriptorPool* self,
  115. Descriptor* descriptor) {
  116. CHECK_UPB(
  117. upb_symtab_add(self->symtab, (upb_def**)&descriptor->msgdef, 1,
  118. NULL, &status),
  119. "Adding Descriptor to DescriptorPool failed");
  120. }
  121. static void add_enumdesc_to_pool(DescriptorPool* self,
  122. EnumDescriptor* enumdesc) {
  123. CHECK_UPB(
  124. upb_symtab_add(self->symtab, (upb_def**)&enumdesc->enumdef, 1,
  125. NULL, &status),
  126. "Adding EnumDescriptor to DescriptorPool failed");
  127. }
  128. /*
  129. * call-seq:
  130. * DescriptorPool.add(descriptor)
  131. *
  132. * Adds the given Descriptor or EnumDescriptor to this pool. All references to
  133. * other types in a Descriptor's fields must be resolvable within this pool or
  134. * an exception will be raised.
  135. */
  136. VALUE DescriptorPool_add(VALUE _self, VALUE def) {
  137. DEFINE_SELF(DescriptorPool, self, _self);
  138. VALUE def_klass = rb_obj_class(def);
  139. if (def_klass == cDescriptor) {
  140. add_descriptor_to_pool(self, ruby_to_Descriptor(def));
  141. } else if (def_klass == cEnumDescriptor) {
  142. add_enumdesc_to_pool(self, ruby_to_EnumDescriptor(def));
  143. } else {
  144. rb_raise(rb_eArgError,
  145. "Second argument must be a Descriptor or EnumDescriptor.");
  146. }
  147. return Qnil;
  148. }
  149. /*
  150. * call-seq:
  151. * DescriptorPool.build(&block)
  152. *
  153. * Invokes the block with a Builder instance as self. All message and enum types
  154. * added within the block are committed to the pool atomically, and may refer
  155. * (co)recursively to each other. The user should call Builder#add_message and
  156. * Builder#add_enum within the block as appropriate. This is the recommended,
  157. * idiomatic way to define new message and enum types.
  158. */
  159. VALUE DescriptorPool_build(VALUE _self) {
  160. VALUE ctx = rb_class_new_instance(0, NULL, cBuilder);
  161. VALUE block = rb_block_proc();
  162. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  163. rb_funcall(ctx, rb_intern("finalize_to_pool"), 1, _self);
  164. return Qnil;
  165. }
  166. /*
  167. * call-seq:
  168. * DescriptorPool.lookup(name) => descriptor
  169. *
  170. * Finds a Descriptor or EnumDescriptor by name and returns it, or nil if none
  171. * exists with the given name.
  172. */
  173. VALUE DescriptorPool_lookup(VALUE _self, VALUE name) {
  174. DEFINE_SELF(DescriptorPool, self, _self);
  175. const char* name_str = get_str(name);
  176. const upb_def* def = upb_symtab_lookup(self->symtab, name_str);
  177. if (!def) {
  178. return Qnil;
  179. }
  180. return get_def_obj(def);
  181. }
  182. /*
  183. * call-seq:
  184. * DescriptorPool.generated_pool => descriptor_pool
  185. *
  186. * Class method that returns the global DescriptorPool. This is a singleton into
  187. * which generated-code message and enum types are registered. The user may also
  188. * register types in this pool for convenience so that they do not have to hold
  189. * a reference to a private pool instance.
  190. */
  191. VALUE DescriptorPool_generated_pool(VALUE _self) {
  192. return generated_pool;
  193. }
  194. // -----------------------------------------------------------------------------
  195. // Descriptor.
  196. // -----------------------------------------------------------------------------
  197. DEFINE_CLASS(Descriptor, "Google::Protobuf::Descriptor");
  198. void Descriptor_mark(void* _self) {
  199. Descriptor* self = _self;
  200. rb_gc_mark(self->klass);
  201. }
  202. void Descriptor_free(void* _self) {
  203. Descriptor* self = _self;
  204. upb_msgdef_unref(self->msgdef, &self->msgdef);
  205. if (self->layout) {
  206. free_layout(self->layout);
  207. }
  208. if (self->fill_handlers) {
  209. upb_handlers_unref(self->fill_handlers, &self->fill_handlers);
  210. }
  211. if (self->fill_method) {
  212. upb_pbdecodermethod_unref(self->fill_method, &self->fill_method);
  213. }
  214. if (self->pb_serialize_handlers) {
  215. upb_handlers_unref(self->pb_serialize_handlers,
  216. &self->pb_serialize_handlers);
  217. }
  218. if (self->json_serialize_handlers) {
  219. upb_handlers_unref(self->pb_serialize_handlers,
  220. &self->json_serialize_handlers);
  221. }
  222. xfree(self);
  223. }
  224. /*
  225. * call-seq:
  226. * Descriptor.new => descriptor
  227. *
  228. * Creates a new, empty, message type descriptor. At a minimum, its name must be
  229. * set before it is added to a pool. It cannot be used to create messages until
  230. * it is added to a pool, after which it becomes immutable (as part of a
  231. * finalization process).
  232. */
  233. VALUE Descriptor_alloc(VALUE klass) {
  234. Descriptor* self = ALLOC(Descriptor);
  235. VALUE ret = TypedData_Wrap_Struct(klass, &_Descriptor_type, self);
  236. self->msgdef = upb_msgdef_new(&self->msgdef);
  237. self->klass = Qnil;
  238. self->layout = NULL;
  239. self->fill_handlers = NULL;
  240. self->fill_method = NULL;
  241. self->pb_serialize_handlers = NULL;
  242. self->json_serialize_handlers = NULL;
  243. return ret;
  244. }
  245. void Descriptor_register(VALUE module) {
  246. VALUE klass = rb_define_class_under(
  247. module, "Descriptor", rb_cObject);
  248. rb_define_alloc_func(klass, Descriptor_alloc);
  249. rb_define_method(klass, "each", Descriptor_each, 0);
  250. rb_define_method(klass, "lookup", Descriptor_lookup, 1);
  251. rb_define_method(klass, "add_field", Descriptor_add_field, 1);
  252. rb_define_method(klass, "msgclass", Descriptor_msgclass, 0);
  253. rb_define_method(klass, "name", Descriptor_name, 0);
  254. rb_define_method(klass, "name=", Descriptor_name_set, 1);
  255. rb_include_module(klass, rb_mEnumerable);
  256. cDescriptor = klass;
  257. rb_gc_register_address(&cDescriptor);
  258. }
  259. /*
  260. * call-seq:
  261. * Descriptor.name => name
  262. *
  263. * Returns the name of this message type as a fully-qualfied string (e.g.,
  264. * My.Package.MessageType).
  265. */
  266. VALUE Descriptor_name(VALUE _self) {
  267. DEFINE_SELF(Descriptor, self, _self);
  268. return rb_str_maybe_null(upb_msgdef_fullname(self->msgdef));
  269. }
  270. /*
  271. * call-seq:
  272. * Descriptor.name = name
  273. *
  274. * Assigns a name to this message type. The descriptor must not have been added
  275. * to a pool yet.
  276. */
  277. VALUE Descriptor_name_set(VALUE _self, VALUE str) {
  278. DEFINE_SELF(Descriptor, self, _self);
  279. upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
  280. const char* name = get_str(str);
  281. CHECK_UPB(
  282. upb_msgdef_setfullname(mut_def, name, &status),
  283. "Error setting Descriptor name");
  284. return Qnil;
  285. }
  286. /*
  287. * call-seq:
  288. * Descriptor.each(&block)
  289. *
  290. * Iterates over fields in this message type, yielding to the block on each one.
  291. */
  292. VALUE Descriptor_each(VALUE _self) {
  293. DEFINE_SELF(Descriptor, self, _self);
  294. upb_msg_iter it;
  295. for (upb_msg_begin(&it, self->msgdef);
  296. !upb_msg_done(&it);
  297. upb_msg_next(&it)) {
  298. const upb_fielddef* field = upb_msg_iter_field(&it);
  299. VALUE obj = get_def_obj(field);
  300. rb_yield(obj);
  301. }
  302. return Qnil;
  303. }
  304. /*
  305. * call-seq:
  306. * Descriptor.lookup(name) => FieldDescriptor
  307. *
  308. * Returns the field descriptor for the field with the given name, if present,
  309. * or nil if none.
  310. */
  311. VALUE Descriptor_lookup(VALUE _self, VALUE name) {
  312. DEFINE_SELF(Descriptor, self, _self);
  313. const char* s = get_str(name);
  314. const upb_fielddef* field = upb_msgdef_ntofz(self->msgdef, s);
  315. if (field == NULL) {
  316. return Qnil;
  317. }
  318. return get_def_obj(field);
  319. }
  320. /*
  321. * call-seq:
  322. * Descriptor.add_field(field) => nil
  323. *
  324. * Adds the given FieldDescriptor to this message type. The descriptor must not
  325. * have been added to a pool yet. Raises an exception if a field with the same
  326. * name or number already exists. Sub-type references (e.g. for fields of type
  327. * message) are not resolved at this point.
  328. */
  329. VALUE Descriptor_add_field(VALUE _self, VALUE obj) {
  330. DEFINE_SELF(Descriptor, self, _self);
  331. upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
  332. FieldDescriptor* def = ruby_to_FieldDescriptor(obj);
  333. upb_fielddef* mut_field_def = check_field_notfrozen(def->fielddef);
  334. CHECK_UPB(
  335. upb_msgdef_addfield(mut_def, mut_field_def, NULL, &status),
  336. "Adding field to Descriptor failed");
  337. add_def_obj(def->fielddef, obj);
  338. return Qnil;
  339. }
  340. /*
  341. * call-seq:
  342. * Descriptor.msgclass => message_klass
  343. *
  344. * Returns the Ruby class created for this message type. Valid only once the
  345. * message type has been added to a pool.
  346. */
  347. VALUE Descriptor_msgclass(VALUE _self) {
  348. DEFINE_SELF(Descriptor, self, _self);
  349. if (!upb_def_isfrozen((const upb_def*)self->msgdef)) {
  350. rb_raise(rb_eRuntimeError,
  351. "Cannot fetch message class from a Descriptor not yet in a pool.");
  352. }
  353. if (self->klass == Qnil) {
  354. self->klass = build_class_from_descriptor(self);
  355. }
  356. return self->klass;
  357. }
  358. // -----------------------------------------------------------------------------
  359. // FieldDescriptor.
  360. // -----------------------------------------------------------------------------
  361. DEFINE_CLASS(FieldDescriptor, "Google::Protobuf::FieldDescriptor");
  362. void FieldDescriptor_mark(void* _self) {
  363. }
  364. void FieldDescriptor_free(void* _self) {
  365. FieldDescriptor* self = _self;
  366. upb_fielddef_unref(self->fielddef, &self->fielddef);
  367. xfree(self);
  368. }
  369. /*
  370. * call-seq:
  371. * FieldDescriptor.new => field
  372. *
  373. * Returns a new field descriptor. Its name, type, etc. must be set before it is
  374. * added to a message type.
  375. */
  376. VALUE FieldDescriptor_alloc(VALUE klass) {
  377. FieldDescriptor* self = ALLOC(FieldDescriptor);
  378. VALUE ret = TypedData_Wrap_Struct(klass, &_FieldDescriptor_type, self);
  379. upb_fielddef* fielddef = upb_fielddef_new(&self->fielddef);
  380. upb_fielddef_setpacked(fielddef, false);
  381. self->fielddef = fielddef;
  382. return ret;
  383. }
  384. void FieldDescriptor_register(VALUE module) {
  385. VALUE klass = rb_define_class_under(
  386. module, "FieldDescriptor", rb_cObject);
  387. rb_define_alloc_func(klass, FieldDescriptor_alloc);
  388. rb_define_method(klass, "name", FieldDescriptor_name, 0);
  389. rb_define_method(klass, "name=", FieldDescriptor_name_set, 1);
  390. rb_define_method(klass, "type", FieldDescriptor_type, 0);
  391. rb_define_method(klass, "type=", FieldDescriptor_type_set, 1);
  392. rb_define_method(klass, "label", FieldDescriptor_label, 0);
  393. rb_define_method(klass, "label=", FieldDescriptor_label_set, 1);
  394. rb_define_method(klass, "number", FieldDescriptor_number, 0);
  395. rb_define_method(klass, "number=", FieldDescriptor_number_set, 1);
  396. rb_define_method(klass, "submsg_name", FieldDescriptor_submsg_name, 0);
  397. rb_define_method(klass, "submsg_name=", FieldDescriptor_submsg_name_set, 1);
  398. rb_define_method(klass, "subtype", FieldDescriptor_subtype, 0);
  399. rb_define_method(klass, "get", FieldDescriptor_get, 1);
  400. rb_define_method(klass, "set", FieldDescriptor_set, 2);
  401. cFieldDescriptor = klass;
  402. rb_gc_register_address(&cFieldDescriptor);
  403. }
  404. /*
  405. * call-seq:
  406. * FieldDescriptor.name => name
  407. *
  408. * Returns the name of this field.
  409. */
  410. VALUE FieldDescriptor_name(VALUE _self) {
  411. DEFINE_SELF(FieldDescriptor, self, _self);
  412. return rb_str_maybe_null(upb_fielddef_name(self->fielddef));
  413. }
  414. /*
  415. * call-seq:
  416. * FieldDescriptor.name = name
  417. *
  418. * Sets the name of this field. Cannot be called once the containing message
  419. * type, if any, is added to a pool.
  420. */
  421. VALUE FieldDescriptor_name_set(VALUE _self, VALUE str) {
  422. DEFINE_SELF(FieldDescriptor, self, _self);
  423. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  424. const char* name = get_str(str);
  425. CHECK_UPB(upb_fielddef_setname(mut_def, name, &status),
  426. "Error setting FieldDescriptor name");
  427. return Qnil;
  428. }
  429. upb_fieldtype_t ruby_to_fieldtype(VALUE type) {
  430. if (TYPE(type) != T_SYMBOL) {
  431. rb_raise(rb_eArgError, "Expected symbol for field type.");
  432. }
  433. upb_fieldtype_t upb_type = -1;
  434. #define CONVERT(upb, ruby) \
  435. if (SYM2ID(type) == rb_intern( # ruby )) { \
  436. upb_type = UPB_TYPE_ ## upb; \
  437. }
  438. CONVERT(FLOAT, float);
  439. CONVERT(DOUBLE, double);
  440. CONVERT(BOOL, bool);
  441. CONVERT(STRING, string);
  442. CONVERT(BYTES, bytes);
  443. CONVERT(MESSAGE, message);
  444. CONVERT(ENUM, enum);
  445. CONVERT(INT32, int32);
  446. CONVERT(INT64, int64);
  447. CONVERT(UINT32, uint32);
  448. CONVERT(UINT64, uint64);
  449. #undef CONVERT
  450. if (upb_type == -1) {
  451. rb_raise(rb_eArgError, "Unknown field type.");
  452. }
  453. return upb_type;
  454. }
  455. VALUE fieldtype_to_ruby(upb_fieldtype_t type) {
  456. switch (type) {
  457. #define CONVERT(upb, ruby) \
  458. case UPB_TYPE_ ## upb : return ID2SYM(rb_intern( # ruby ));
  459. CONVERT(FLOAT, float);
  460. CONVERT(DOUBLE, double);
  461. CONVERT(BOOL, bool);
  462. CONVERT(STRING, string);
  463. CONVERT(BYTES, bytes);
  464. CONVERT(MESSAGE, message);
  465. CONVERT(ENUM, enum);
  466. CONVERT(INT32, int32);
  467. CONVERT(INT64, int64);
  468. CONVERT(UINT32, uint32);
  469. CONVERT(UINT64, uint64);
  470. #undef CONVERT
  471. }
  472. return Qnil;
  473. }
  474. /*
  475. * call-seq:
  476. * FieldDescriptor.type => type
  477. *
  478. * Returns this field's type, as a Ruby symbol, or nil if not yet set.
  479. *
  480. * Valid field types are:
  481. * :int32, :int64, :uint32, :uint64, :float, :double, :bool, :string,
  482. * :bytes, :message.
  483. */
  484. VALUE FieldDescriptor_type(VALUE _self) {
  485. DEFINE_SELF(FieldDescriptor, self, _self);
  486. if (!upb_fielddef_typeisset(self->fielddef)) {
  487. return Qnil;
  488. }
  489. return fieldtype_to_ruby(upb_fielddef_type(self->fielddef));
  490. }
  491. /*
  492. * call-seq:
  493. * FieldDescriptor.type = type
  494. *
  495. * Sets this field's type. Cannot be called if field is part of a message type
  496. * already in a pool.
  497. */
  498. VALUE FieldDescriptor_type_set(VALUE _self, VALUE type) {
  499. DEFINE_SELF(FieldDescriptor, self, _self);
  500. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  501. upb_fielddef_settype(mut_def, ruby_to_fieldtype(type));
  502. return Qnil;
  503. }
  504. /*
  505. * call-seq:
  506. * FieldDescriptor.label => label
  507. *
  508. * Returns this field's label (i.e., plurality), as a Ruby symbol.
  509. *
  510. * Valid field labels are:
  511. * :optional, :repeated
  512. */
  513. VALUE FieldDescriptor_label(VALUE _self) {
  514. DEFINE_SELF(FieldDescriptor, self, _self);
  515. switch (upb_fielddef_label(self->fielddef)) {
  516. #define CONVERT(upb, ruby) \
  517. case UPB_LABEL_ ## upb : return ID2SYM(rb_intern( # ruby ));
  518. CONVERT(OPTIONAL, optional);
  519. CONVERT(REQUIRED, required);
  520. CONVERT(REPEATED, repeated);
  521. #undef CONVERT
  522. }
  523. return Qnil;
  524. }
  525. /*
  526. * call-seq:
  527. * FieldDescriptor.label = label
  528. *
  529. * Sets the label on this field. Cannot be called if field is part of a message
  530. * type already in a pool.
  531. */
  532. VALUE FieldDescriptor_label_set(VALUE _self, VALUE label) {
  533. DEFINE_SELF(FieldDescriptor, self, _self);
  534. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  535. if (TYPE(label) != T_SYMBOL) {
  536. rb_raise(rb_eArgError, "Expected symbol for field label.");
  537. }
  538. upb_label_t upb_label = -1;
  539. #define CONVERT(upb, ruby) \
  540. if (SYM2ID(label) == rb_intern( # ruby )) { \
  541. upb_label = UPB_LABEL_ ## upb; \
  542. }
  543. CONVERT(OPTIONAL, optional);
  544. CONVERT(REQUIRED, required);
  545. CONVERT(REPEATED, repeated);
  546. #undef CONVERT
  547. if (upb_label == -1) {
  548. rb_raise(rb_eArgError, "Unknown field label.");
  549. }
  550. upb_fielddef_setlabel(mut_def, upb_label);
  551. return Qnil;
  552. }
  553. /*
  554. * call-seq:
  555. * FieldDescriptor.number => number
  556. *
  557. * Returns the tag number for this field.
  558. */
  559. VALUE FieldDescriptor_number(VALUE _self) {
  560. DEFINE_SELF(FieldDescriptor, self, _self);
  561. return INT2NUM(upb_fielddef_number(self->fielddef));
  562. }
  563. /*
  564. * call-seq:
  565. * FieldDescriptor.number = number
  566. *
  567. * Sets the tag number for this field. Cannot be called if field is part of a
  568. * message type already in a pool.
  569. */
  570. VALUE FieldDescriptor_number_set(VALUE _self, VALUE number) {
  571. DEFINE_SELF(FieldDescriptor, self, _self);
  572. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  573. CHECK_UPB(upb_fielddef_setnumber(mut_def, NUM2INT(number), &status),
  574. "Error setting field number");
  575. return Qnil;
  576. }
  577. /*
  578. * call-seq:
  579. * FieldDescriptor.submsg_name => submsg_name
  580. *
  581. * Returns the name of the message or enum type corresponding to this field, if
  582. * it is a message or enum field (respectively), or nil otherwise. This type
  583. * name will be resolved within the context of the pool to which the containing
  584. * message type is added.
  585. */
  586. VALUE FieldDescriptor_submsg_name(VALUE _self) {
  587. DEFINE_SELF(FieldDescriptor, self, _self);
  588. if (!upb_fielddef_hassubdef(self->fielddef)) {
  589. return Qnil;
  590. }
  591. return rb_str_maybe_null(upb_fielddef_subdefname(self->fielddef));
  592. }
  593. /*
  594. * call-seq:
  595. * FieldDescriptor.submsg_name = submsg_name
  596. *
  597. * Sets the name of the message or enum type corresponding to this field, if it
  598. * is a message or enum field (respectively). This type name will be resolved
  599. * within the context of the pool to which the containing message type is added.
  600. * Cannot be called on field that are not of message or enum type, or on fields
  601. * that are part of a message type already added to a pool.
  602. */
  603. VALUE FieldDescriptor_submsg_name_set(VALUE _self, VALUE value) {
  604. DEFINE_SELF(FieldDescriptor, self, _self);
  605. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  606. if (!upb_fielddef_hassubdef(self->fielddef)) {
  607. rb_raise(rb_eTypeError, "FieldDescriptor does not have subdef.");
  608. }
  609. const char* str = get_str(value);
  610. CHECK_UPB(upb_fielddef_setsubdefname(mut_def, str, &status),
  611. "Error setting submessage name");
  612. return Qnil;
  613. }
  614. /*
  615. * call-seq:
  616. * FieldDescriptor.subtype => message_or_enum_descriptor
  617. *
  618. * Returns the message or enum descriptor corresponding to this field's type if
  619. * it is a message or enum field, respectively, or nil otherwise. Cannot be
  620. * called *until* the containing message type is added to a pool (and thus
  621. * resolved).
  622. */
  623. VALUE FieldDescriptor_subtype(VALUE _self) {
  624. DEFINE_SELF(FieldDescriptor, self, _self);
  625. if (!upb_fielddef_hassubdef(self->fielddef)) {
  626. return Qnil;
  627. }
  628. const upb_def* def = upb_fielddef_subdef(self->fielddef);
  629. if (def == NULL) {
  630. return Qnil;
  631. }
  632. return get_def_obj(def);
  633. }
  634. /*
  635. * call-seq:
  636. * FieldDescriptor.get(message) => value
  637. *
  638. * Returns the value set for this field on the given message. Raises an
  639. * exception if message is of the wrong type.
  640. */
  641. VALUE FieldDescriptor_get(VALUE _self, VALUE msg_rb) {
  642. DEFINE_SELF(FieldDescriptor, self, _self);
  643. MessageHeader* msg;
  644. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  645. if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
  646. rb_raise(rb_eTypeError, "get method called on wrong message type");
  647. }
  648. return layout_get(msg->descriptor->layout, Message_data(msg), self->fielddef);
  649. }
  650. /*
  651. * call-seq:
  652. * FieldDescriptor.set(message, value)
  653. *
  654. * Sets the value corresponding to this field to the given value on the given
  655. * message. Raises an exception if message is of the wrong type. Performs the
  656. * ordinary type-checks for field setting.
  657. */
  658. VALUE FieldDescriptor_set(VALUE _self, VALUE msg_rb, VALUE value) {
  659. DEFINE_SELF(FieldDescriptor, self, _self);
  660. MessageHeader* msg;
  661. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  662. if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
  663. rb_raise(rb_eTypeError, "set method called on wrong message type");
  664. }
  665. layout_set(msg->descriptor->layout, Message_data(msg), self->fielddef, value);
  666. return Qnil;
  667. }
  668. // -----------------------------------------------------------------------------
  669. // EnumDescriptor.
  670. // -----------------------------------------------------------------------------
  671. DEFINE_CLASS(EnumDescriptor, "Google::Protobuf::EnumDescriptor");
  672. void EnumDescriptor_mark(void* _self) {
  673. EnumDescriptor* self = _self;
  674. rb_gc_mark(self->module);
  675. }
  676. void EnumDescriptor_free(void* _self) {
  677. EnumDescriptor* self = _self;
  678. upb_enumdef_unref(self->enumdef, &self->enumdef);
  679. xfree(self);
  680. }
  681. /*
  682. * call-seq:
  683. * EnumDescriptor.new => enum_descriptor
  684. *
  685. * Creates a new, empty, enum descriptor. Must be added to a pool before the
  686. * enum type can be used. The enum type may only be modified prior to adding to
  687. * a pool.
  688. */
  689. VALUE EnumDescriptor_alloc(VALUE klass) {
  690. EnumDescriptor* self = ALLOC(EnumDescriptor);
  691. VALUE ret = TypedData_Wrap_Struct(klass, &_EnumDescriptor_type, self);
  692. self->enumdef = upb_enumdef_new(&self->enumdef);
  693. self->module = Qnil;
  694. return ret;
  695. }
  696. void EnumDescriptor_register(VALUE module) {
  697. VALUE klass = rb_define_class_under(
  698. module, "EnumDescriptor", rb_cObject);
  699. rb_define_alloc_func(klass, EnumDescriptor_alloc);
  700. rb_define_method(klass, "name", EnumDescriptor_name, 0);
  701. rb_define_method(klass, "name=", EnumDescriptor_name_set, 1);
  702. rb_define_method(klass, "add_value", EnumDescriptor_add_value, 2);
  703. rb_define_method(klass, "lookup_name", EnumDescriptor_lookup_name, 1);
  704. rb_define_method(klass, "lookup_value", EnumDescriptor_lookup_value, 1);
  705. rb_define_method(klass, "each", EnumDescriptor_each, 0);
  706. rb_define_method(klass, "enummodule", EnumDescriptor_enummodule, 0);
  707. rb_include_module(klass, rb_mEnumerable);
  708. cEnumDescriptor = klass;
  709. rb_gc_register_address(&cEnumDescriptor);
  710. }
  711. /*
  712. * call-seq:
  713. * EnumDescriptor.name => name
  714. *
  715. * Returns the name of this enum type.
  716. */
  717. VALUE EnumDescriptor_name(VALUE _self) {
  718. DEFINE_SELF(EnumDescriptor, self, _self);
  719. return rb_str_maybe_null(upb_enumdef_fullname(self->enumdef));
  720. }
  721. /*
  722. * call-seq:
  723. * EnumDescriptor.name = name
  724. *
  725. * Sets the name of this enum type. Cannot be called if the enum type has
  726. * already been added to a pool.
  727. */
  728. VALUE EnumDescriptor_name_set(VALUE _self, VALUE str) {
  729. DEFINE_SELF(EnumDescriptor, self, _self);
  730. upb_enumdef* mut_def = check_enum_notfrozen(self->enumdef);
  731. const char* name = get_str(str);
  732. CHECK_UPB(upb_enumdef_setfullname(mut_def, name, &status),
  733. "Error setting EnumDescriptor name");
  734. return Qnil;
  735. }
  736. /*
  737. * call-seq:
  738. * EnumDescriptor.add_value(key, value)
  739. *
  740. * Adds a new key => value mapping to this enum type. Key must be given as a
  741. * Ruby symbol. Cannot be called if the enum type has already been added to a
  742. * pool. Will raise an exception if the key or value is already in use.
  743. */
  744. VALUE EnumDescriptor_add_value(VALUE _self, VALUE name, VALUE number) {
  745. DEFINE_SELF(EnumDescriptor, self, _self);
  746. upb_enumdef* mut_def = check_enum_notfrozen(self->enumdef);
  747. const char* name_str = rb_id2name(SYM2ID(name));
  748. int32_t val = NUM2INT(number);
  749. CHECK_UPB(upb_enumdef_addval(mut_def, name_str, val, &status),
  750. "Error adding value to enum");
  751. return Qnil;
  752. }
  753. /*
  754. * call-seq:
  755. * EnumDescriptor.lookup_name(name) => value
  756. *
  757. * Returns the numeric value corresponding to the given key name (as a Ruby
  758. * symbol), or nil if none.
  759. */
  760. VALUE EnumDescriptor_lookup_name(VALUE _self, VALUE name) {
  761. DEFINE_SELF(EnumDescriptor, self, _self);
  762. const char* name_str= rb_id2name(SYM2ID(name));
  763. int32_t val = 0;
  764. if (upb_enumdef_ntoiz(self->enumdef, name_str, &val)) {
  765. return INT2NUM(val);
  766. } else {
  767. return Qnil;
  768. }
  769. }
  770. /*
  771. * call-seq:
  772. * EnumDescriptor.lookup_value(name) => value
  773. *
  774. * Returns the key name (as a Ruby symbol) corresponding to the integer value,
  775. * or nil if none.
  776. */
  777. VALUE EnumDescriptor_lookup_value(VALUE _self, VALUE number) {
  778. DEFINE_SELF(EnumDescriptor, self, _self);
  779. int32_t val = NUM2INT(number);
  780. const char* name = upb_enumdef_iton(self->enumdef, val);
  781. if (name != NULL) {
  782. return ID2SYM(rb_intern(name));
  783. } else {
  784. return Qnil;
  785. }
  786. }
  787. /*
  788. * call-seq:
  789. * EnumDescriptor.each(&block)
  790. *
  791. * Iterates over key => value mappings in this enum's definition, yielding to
  792. * the block with (key, value) arguments for each one.
  793. */
  794. VALUE EnumDescriptor_each(VALUE _self) {
  795. DEFINE_SELF(EnumDescriptor, self, _self);
  796. upb_enum_iter it;
  797. for (upb_enum_begin(&it, self->enumdef);
  798. !upb_enum_done(&it);
  799. upb_enum_next(&it)) {
  800. VALUE key = ID2SYM(rb_intern(upb_enum_iter_name(&it)));
  801. VALUE number = INT2NUM(upb_enum_iter_number(&it));
  802. rb_yield_values(2, key, number);
  803. }
  804. return Qnil;
  805. }
  806. /*
  807. * call-seq:
  808. * EnumDescriptor.enummodule => module
  809. *
  810. * Returns the Ruby module corresponding to this enum type. Cannot be called
  811. * until the enum descriptor has been added to a pool.
  812. */
  813. VALUE EnumDescriptor_enummodule(VALUE _self) {
  814. DEFINE_SELF(EnumDescriptor, self, _self);
  815. if (!upb_def_isfrozen((const upb_def*)self->enumdef)) {
  816. rb_raise(rb_eRuntimeError,
  817. "Cannot fetch enum module from an EnumDescriptor not yet "
  818. "in a pool.");
  819. }
  820. if (self->module == Qnil) {
  821. self->module = build_module_from_enumdesc(self);
  822. }
  823. return self->module;
  824. }
  825. // -----------------------------------------------------------------------------
  826. // MessageBuilderContext.
  827. // -----------------------------------------------------------------------------
  828. DEFINE_CLASS(MessageBuilderContext,
  829. "Google::Protobuf::Internal::MessageBuilderContext");
  830. void MessageBuilderContext_mark(void* _self) {
  831. MessageBuilderContext* self = _self;
  832. rb_gc_mark(self->descriptor);
  833. rb_gc_mark(self->builder);
  834. }
  835. void MessageBuilderContext_free(void* _self) {
  836. MessageBuilderContext* self = _self;
  837. xfree(self);
  838. }
  839. VALUE MessageBuilderContext_alloc(VALUE klass) {
  840. MessageBuilderContext* self = ALLOC(MessageBuilderContext);
  841. VALUE ret = TypedData_Wrap_Struct(
  842. klass, &_MessageBuilderContext_type, self);
  843. self->descriptor = Qnil;
  844. self->builder = Qnil;
  845. return ret;
  846. }
  847. void MessageBuilderContext_register(VALUE module) {
  848. VALUE klass = rb_define_class_under(
  849. module, "MessageBuilderContext", rb_cObject);
  850. rb_define_alloc_func(klass, MessageBuilderContext_alloc);
  851. rb_define_method(klass, "initialize",
  852. MessageBuilderContext_initialize, 2);
  853. rb_define_method(klass, "optional", MessageBuilderContext_optional, -1);
  854. rb_define_method(klass, "required", MessageBuilderContext_required, -1);
  855. rb_define_method(klass, "repeated", MessageBuilderContext_repeated, -1);
  856. rb_define_method(klass, "map", MessageBuilderContext_map, -1);
  857. cMessageBuilderContext = klass;
  858. rb_gc_register_address(&cMessageBuilderContext);
  859. }
  860. /*
  861. * call-seq:
  862. * MessageBuilderContext.new(desc, builder) => context
  863. *
  864. * Create a new message builder context around the given message descriptor and
  865. * builder context. This class is intended to serve as a DSL context to be used
  866. * with #instance_eval.
  867. */
  868. VALUE MessageBuilderContext_initialize(VALUE _self,
  869. VALUE msgdef,
  870. VALUE builder) {
  871. DEFINE_SELF(MessageBuilderContext, self, _self);
  872. self->descriptor = msgdef;
  873. self->builder = builder;
  874. return Qnil;
  875. }
  876. static VALUE msgdef_add_field(VALUE msgdef,
  877. const char* label, VALUE name,
  878. VALUE type, VALUE number,
  879. VALUE type_class) {
  880. VALUE fielddef = rb_class_new_instance(0, NULL, cFieldDescriptor);
  881. VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
  882. rb_funcall(fielddef, rb_intern("label="), 1, ID2SYM(rb_intern(label)));
  883. rb_funcall(fielddef, rb_intern("name="), 1, name_str);
  884. rb_funcall(fielddef, rb_intern("type="), 1, type);
  885. rb_funcall(fielddef, rb_intern("number="), 1, number);
  886. if (type_class != Qnil) {
  887. if (TYPE(type_class) != T_STRING) {
  888. rb_raise(rb_eArgError, "Expected string for type class");
  889. }
  890. // Make it an absolute type name by prepending a dot.
  891. type_class = rb_str_append(rb_str_new2("."), type_class);
  892. rb_funcall(fielddef, rb_intern("submsg_name="), 1, type_class);
  893. }
  894. rb_funcall(msgdef, rb_intern("add_field"), 1, fielddef);
  895. return fielddef;
  896. }
  897. /*
  898. * call-seq:
  899. * MessageBuilderContext.optional(name, type, number, type_class = nil)
  900. *
  901. * Defines a new optional field on this message type with the given type, tag
  902. * number, and type class (for message and enum fields). The type must be a Ruby
  903. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  904. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  905. */
  906. VALUE MessageBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
  907. DEFINE_SELF(MessageBuilderContext, self, _self);
  908. if (argc < 3) {
  909. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  910. }
  911. VALUE name = argv[0];
  912. VALUE type = argv[1];
  913. VALUE number = argv[2];
  914. VALUE type_class = (argc > 3) ? argv[3] : Qnil;
  915. return msgdef_add_field(self->descriptor, "optional",
  916. name, type, number, type_class);
  917. }
  918. /*
  919. * call-seq:
  920. * MessageBuilderContext.required(name, type, number, type_class = nil)
  921. *
  922. * Defines a new required field on this message type with the given type, tag
  923. * number, and type class (for message and enum fields). The type must be a Ruby
  924. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  925. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  926. *
  927. * Proto3 does not have required fields, but this method exists for
  928. * completeness. Any attempt to add a message type with required fields to a
  929. * pool will currently result in an error.
  930. */
  931. VALUE MessageBuilderContext_required(int argc, VALUE* argv, VALUE _self) {
  932. DEFINE_SELF(MessageBuilderContext, self, _self);
  933. if (argc < 3) {
  934. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  935. }
  936. VALUE name = argv[0];
  937. VALUE type = argv[1];
  938. VALUE number = argv[2];
  939. VALUE type_class = (argc > 3) ? argv[3] : Qnil;
  940. return msgdef_add_field(self->descriptor, "required",
  941. name, type, number, type_class);
  942. }
  943. /*
  944. * call-seq:
  945. * MessageBuilderContext.repeated(name, type, number, type_class = nil)
  946. *
  947. * Defines a new repeated field on this message type with the given type, tag
  948. * number, and type class (for message and enum fields). The type must be a Ruby
  949. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  950. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  951. */
  952. VALUE MessageBuilderContext_repeated(int argc, VALUE* argv, VALUE _self) {
  953. DEFINE_SELF(MessageBuilderContext, self, _self);
  954. if (argc < 3) {
  955. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  956. }
  957. VALUE name = argv[0];
  958. VALUE type = argv[1];
  959. VALUE number = argv[2];
  960. VALUE type_class = (argc > 3) ? argv[3] : Qnil;
  961. return msgdef_add_field(self->descriptor, "repeated",
  962. name, type, number, type_class);
  963. }
  964. /*
  965. * call-seq:
  966. * MessageBuilderContext.map(name, key_type, value_type, number,
  967. * value_type_class = nil)
  968. *
  969. * Defines a new map field on this message type with the given key and value types, tag
  970. * number, and type class (for message and enum value types). The key type must
  971. * be :int32/:uint32/:int64/:uint64, :bool, or :string. The value type type must
  972. * be a Ruby symbol (as accepted by FieldDescriptor#type=) and the type_class
  973. * must be a string, if present (as accepted by FieldDescriptor#submsg_name=).
  974. */
  975. VALUE MessageBuilderContext_map(int argc, VALUE* argv, VALUE _self) {
  976. DEFINE_SELF(MessageBuilderContext, self, _self);
  977. if (argc < 4) {
  978. rb_raise(rb_eArgError, "Expected at least 4 arguments.");
  979. }
  980. VALUE name = argv[0];
  981. VALUE key_type = argv[1];
  982. VALUE value_type = argv[2];
  983. VALUE number = argv[3];
  984. VALUE type_class = (argc > 4) ? argv[4] : Qnil;
  985. // Validate the key type. We can't accept enums, messages, or floats/doubles
  986. // as map keys. (We exclude these explicitly, and the field-descriptor setter
  987. // below then ensures that the type is one of the remaining valid options.)
  988. if (SYM2ID(key_type) == rb_intern("float") ||
  989. SYM2ID(key_type) == rb_intern("double") ||
  990. SYM2ID(key_type) == rb_intern("enum") ||
  991. SYM2ID(key_type) == rb_intern("message")) {
  992. rb_raise(rb_eArgError,
  993. "Cannot add a map field with a float, double, enum, or message "
  994. "type.");
  995. }
  996. // Create a new message descriptor for the map entry message, and create a
  997. // repeated submessage field here with that type.
  998. VALUE mapentry_desc = rb_class_new_instance(0, NULL, cDescriptor);
  999. VALUE mapentry_desc_name = rb_funcall(self->descriptor, rb_intern("name"), 0);
  1000. mapentry_desc_name = rb_str_cat2(mapentry_desc_name, "_MapEntry_");
  1001. mapentry_desc_name = rb_str_cat2(mapentry_desc_name,
  1002. rb_id2name(SYM2ID(name)));
  1003. Descriptor_name_set(mapentry_desc, mapentry_desc_name);
  1004. // The 'mapentry' attribute has no Ruby setter because we do not want the user
  1005. // attempting to DIY the setup below; we want to ensure that the fields are
  1006. // correct. So we reach into the msgdef here to set the bit manually.
  1007. Descriptor* mapentry_desc_self = ruby_to_Descriptor(mapentry_desc);
  1008. upb_msgdef_setmapentry((upb_msgdef*)mapentry_desc_self->msgdef, true);
  1009. // optional <type> key = 1;
  1010. VALUE key_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
  1011. FieldDescriptor_name_set(key_field, rb_str_new2("key"));
  1012. FieldDescriptor_label_set(key_field, ID2SYM(rb_intern("optional")));
  1013. FieldDescriptor_number_set(key_field, INT2NUM(1));
  1014. FieldDescriptor_type_set(key_field, key_type);
  1015. Descriptor_add_field(mapentry_desc, key_field);
  1016. // optional <type> value = 2;
  1017. VALUE value_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
  1018. FieldDescriptor_name_set(value_field, rb_str_new2("value"));
  1019. FieldDescriptor_label_set(value_field, ID2SYM(rb_intern("optional")));
  1020. FieldDescriptor_number_set(value_field, INT2NUM(2));
  1021. FieldDescriptor_type_set(value_field, value_type);
  1022. if (type_class != Qnil) {
  1023. VALUE submsg_name = rb_str_new2("."); // prepend '.' to make name absolute.
  1024. submsg_name = rb_str_append(submsg_name, type_class);
  1025. FieldDescriptor_submsg_name_set(value_field, submsg_name);
  1026. }
  1027. Descriptor_add_field(mapentry_desc, value_field);
  1028. // Add the map-entry message type to the current builder, and use the type to
  1029. // create the map field itself.
  1030. Builder* builder_self = ruby_to_Builder(self->builder);
  1031. rb_ary_push(builder_self->pending_list, mapentry_desc);
  1032. VALUE map_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
  1033. VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
  1034. FieldDescriptor_name_set(map_field, name_str);
  1035. FieldDescriptor_number_set(map_field, number);
  1036. FieldDescriptor_label_set(map_field, ID2SYM(rb_intern("repeated")));
  1037. FieldDescriptor_type_set(map_field, ID2SYM(rb_intern("message")));
  1038. VALUE submsg_name = rb_str_new2("."); // prepend '.' to make name absolute.
  1039. submsg_name = rb_str_append(submsg_name, mapentry_desc_name);
  1040. FieldDescriptor_submsg_name_set(map_field, submsg_name);
  1041. Descriptor_add_field(self->descriptor, map_field);
  1042. return Qnil;
  1043. }
  1044. // -----------------------------------------------------------------------------
  1045. // EnumBuilderContext.
  1046. // -----------------------------------------------------------------------------
  1047. DEFINE_CLASS(EnumBuilderContext,
  1048. "Google::Protobuf::Internal::EnumBuilderContext");
  1049. void EnumBuilderContext_mark(void* _self) {
  1050. EnumBuilderContext* self = _self;
  1051. rb_gc_mark(self->enumdesc);
  1052. }
  1053. void EnumBuilderContext_free(void* _self) {
  1054. EnumBuilderContext* self = _self;
  1055. xfree(self);
  1056. }
  1057. VALUE EnumBuilderContext_alloc(VALUE klass) {
  1058. EnumBuilderContext* self = ALLOC(EnumBuilderContext);
  1059. VALUE ret = TypedData_Wrap_Struct(
  1060. klass, &_EnumBuilderContext_type, self);
  1061. self->enumdesc = Qnil;
  1062. return ret;
  1063. }
  1064. void EnumBuilderContext_register(VALUE module) {
  1065. VALUE klass = rb_define_class_under(
  1066. module, "EnumBuilderContext", rb_cObject);
  1067. rb_define_alloc_func(klass, EnumBuilderContext_alloc);
  1068. rb_define_method(klass, "initialize",
  1069. EnumBuilderContext_initialize, 1);
  1070. rb_define_method(klass, "value", EnumBuilderContext_value, 2);
  1071. cEnumBuilderContext = klass;
  1072. rb_gc_register_address(&cEnumBuilderContext);
  1073. }
  1074. /*
  1075. * call-seq:
  1076. * EnumBuilderContext.new(enumdesc) => context
  1077. *
  1078. * Create a new builder context around the given enum descriptor. This class is
  1079. * intended to serve as a DSL context to be used with #instance_eval.
  1080. */
  1081. VALUE EnumBuilderContext_initialize(VALUE _self, VALUE enumdef) {
  1082. DEFINE_SELF(EnumBuilderContext, self, _self);
  1083. self->enumdesc = enumdef;
  1084. return Qnil;
  1085. }
  1086. static VALUE enumdef_add_value(VALUE enumdef,
  1087. VALUE name, VALUE number) {
  1088. rb_funcall(enumdef, rb_intern("add_value"), 2, name, number);
  1089. return Qnil;
  1090. }
  1091. /*
  1092. * call-seq:
  1093. * EnumBuilder.add_value(name, number)
  1094. *
  1095. * Adds the given name => number mapping to the enum type. Name must be a Ruby
  1096. * symbol.
  1097. */
  1098. VALUE EnumBuilderContext_value(VALUE _self, VALUE name, VALUE number) {
  1099. DEFINE_SELF(EnumBuilderContext, self, _self);
  1100. return enumdef_add_value(self->enumdesc, name, number);
  1101. }
  1102. // -----------------------------------------------------------------------------
  1103. // Builder.
  1104. // -----------------------------------------------------------------------------
  1105. DEFINE_CLASS(Builder, "Google::Protobuf::Internal::Builder");
  1106. void Builder_mark(void* _self) {
  1107. Builder* self = _self;
  1108. rb_gc_mark(self->pending_list);
  1109. }
  1110. void Builder_free(void* _self) {
  1111. Builder* self = _self;
  1112. xfree(self->defs);
  1113. xfree(self);
  1114. }
  1115. /*
  1116. * call-seq:
  1117. * Builder.new => builder
  1118. *
  1119. * Creates a new Builder. A Builder can accumulate a set of new message and enum
  1120. * descriptors and atomically register them into a pool in a way that allows for
  1121. * (co)recursive type references.
  1122. */
  1123. VALUE Builder_alloc(VALUE klass) {
  1124. Builder* self = ALLOC(Builder);
  1125. VALUE ret = TypedData_Wrap_Struct(
  1126. klass, &_Builder_type, self);
  1127. self->pending_list = rb_ary_new();
  1128. self->defs = NULL;
  1129. return ret;
  1130. }
  1131. void Builder_register(VALUE module) {
  1132. VALUE klass = rb_define_class_under(module, "Builder", rb_cObject);
  1133. rb_define_alloc_func(klass, Builder_alloc);
  1134. rb_define_method(klass, "add_message", Builder_add_message, 1);
  1135. rb_define_method(klass, "add_enum", Builder_add_enum, 1);
  1136. rb_define_method(klass, "finalize_to_pool", Builder_finalize_to_pool, 1);
  1137. cBuilder = klass;
  1138. rb_gc_register_address(&cBuilder);
  1139. }
  1140. /*
  1141. * call-seq:
  1142. * Builder.add_message(name, &block)
  1143. *
  1144. * Creates a new, empty descriptor with the given name, and invokes the block in
  1145. * the context of a MessageBuilderContext on that descriptor. The block can then
  1146. * call, e.g., MessageBuilderContext#optional and MessageBuilderContext#repeated
  1147. * methods to define the message fields.
  1148. *
  1149. * This is the recommended, idiomatic way to build message definitions.
  1150. */
  1151. VALUE Builder_add_message(VALUE _self, VALUE name) {
  1152. DEFINE_SELF(Builder, self, _self);
  1153. VALUE msgdef = rb_class_new_instance(0, NULL, cDescriptor);
  1154. VALUE args[2] = { msgdef, _self };
  1155. VALUE ctx = rb_class_new_instance(2, args, cMessageBuilderContext);
  1156. VALUE block = rb_block_proc();
  1157. rb_funcall(msgdef, rb_intern("name="), 1, name);
  1158. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1159. rb_ary_push(self->pending_list, msgdef);
  1160. return Qnil;
  1161. }
  1162. /*
  1163. * call-seq:
  1164. * Builder.add_enum(name, &block)
  1165. *
  1166. * Creates a new, empty enum descriptor with the given name, and invokes the block in
  1167. * the context of an EnumBuilderContext on that descriptor. The block can then
  1168. * call EnumBuilderContext#add_value to define the enum values.
  1169. *
  1170. * This is the recommended, idiomatic way to build enum definitions.
  1171. */
  1172. VALUE Builder_add_enum(VALUE _self, VALUE name) {
  1173. DEFINE_SELF(Builder, self, _self);
  1174. VALUE enumdef = rb_class_new_instance(0, NULL, cEnumDescriptor);
  1175. VALUE ctx = rb_class_new_instance(1, &enumdef, cEnumBuilderContext);
  1176. VALUE block = rb_block_proc();
  1177. rb_funcall(enumdef, rb_intern("name="), 1, name);
  1178. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1179. rb_ary_push(self->pending_list, enumdef);
  1180. return Qnil;
  1181. }
  1182. static void validate_msgdef(const upb_msgdef* msgdef) {
  1183. // Verify that no required fields exist. proto3 does not support these.
  1184. upb_msg_iter it;
  1185. for (upb_msg_begin(&it, msgdef); !upb_msg_done(&it); upb_msg_next(&it)) {
  1186. const upb_fielddef* field = upb_msg_iter_field(&it);
  1187. if (upb_fielddef_label(field) == UPB_LABEL_REQUIRED) {
  1188. rb_raise(rb_eTypeError, "Required fields are unsupported in proto3.");
  1189. }
  1190. }
  1191. }
  1192. static void validate_enumdef(const upb_enumdef* enumdef) {
  1193. // Verify that an entry exists with integer value 0. (This is the default
  1194. // value.)
  1195. const char* lookup = upb_enumdef_iton(enumdef, 0);
  1196. if (lookup == NULL) {
  1197. rb_raise(rb_eTypeError,
  1198. "Enum definition does not contain a value for '0'.");
  1199. }
  1200. }
  1201. /*
  1202. * call-seq:
  1203. * Builder.finalize_to_pool(pool)
  1204. *
  1205. * Adds all accumulated message and enum descriptors created in this builder
  1206. * context to the given pool. The operation occurs atomically, and all
  1207. * descriptors can refer to each other (including in cycles). This is the only
  1208. * way to build (co)recursive message definitions.
  1209. *
  1210. * This method is usually called automatically by DescriptorPool#build after it
  1211. * invokes the given user block in the context of the builder. The user should
  1212. * not normally need to call this manually because a Builder is not normally
  1213. * created manually.
  1214. */
  1215. VALUE Builder_finalize_to_pool(VALUE _self, VALUE pool_rb) {
  1216. DEFINE_SELF(Builder, self, _self);
  1217. DescriptorPool* pool = ruby_to_DescriptorPool(pool_rb);
  1218. REALLOC_N(self->defs, upb_def*, RARRAY_LEN(self->pending_list));
  1219. for (int i = 0; i < RARRAY_LEN(self->pending_list); i++) {
  1220. VALUE def_rb = rb_ary_entry(self->pending_list, i);
  1221. if (CLASS_OF(def_rb) == cDescriptor) {
  1222. self->defs[i] = (upb_def*)ruby_to_Descriptor(def_rb)->msgdef;
  1223. validate_msgdef((const upb_msgdef*)self->defs[i]);
  1224. } else if (CLASS_OF(def_rb) == cEnumDescriptor) {
  1225. self->defs[i] = (upb_def*)ruby_to_EnumDescriptor(def_rb)->enumdef;
  1226. validate_enumdef((const upb_enumdef*)self->defs[i]);
  1227. }
  1228. }
  1229. CHECK_UPB(upb_symtab_add(pool->symtab, (upb_def**)self->defs,
  1230. RARRAY_LEN(self->pending_list), NULL, &status),
  1231. "Unable to add defs to DescriptorPool");
  1232. for (int i = 0; i < RARRAY_LEN(self->pending_list); i++) {
  1233. VALUE def_rb = rb_ary_entry(self->pending_list, i);
  1234. add_def_obj(self->defs[i], def_rb);
  1235. }
  1236. self->pending_list = rb_ary_new();
  1237. return Qnil;
  1238. }