defs.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  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. static const char* get_str(VALUE str) {
  35. Check_Type(str, T_STRING);
  36. return RSTRING_PTR(str);
  37. }
  38. static VALUE rb_str_maybe_null(const char* s) {
  39. if (s == NULL) {
  40. s = "";
  41. }
  42. return rb_str_new2(s);
  43. }
  44. static upb_def* check_notfrozen(const upb_def* def) {
  45. if (upb_def_isfrozen(def)) {
  46. rb_raise(rb_eRuntimeError,
  47. "Attempt to modify a frozen descriptor. Once descriptors are "
  48. "added to the descriptor pool, they may not be modified.");
  49. }
  50. return (upb_def*)def;
  51. }
  52. static upb_msgdef* check_msg_notfrozen(const upb_msgdef* def) {
  53. return upb_downcast_msgdef_mutable(check_notfrozen((const upb_def*)def));
  54. }
  55. static upb_fielddef* check_field_notfrozen(const upb_fielddef* def) {
  56. return upb_downcast_fielddef_mutable(check_notfrozen((const upb_def*)def));
  57. }
  58. static upb_oneofdef* check_oneof_notfrozen(const upb_oneofdef* def) {
  59. return (upb_oneofdef*)check_notfrozen((const upb_def*)def);
  60. }
  61. static upb_enumdef* check_enum_notfrozen(const upb_enumdef* def) {
  62. return (upb_enumdef*)check_notfrozen((const upb_def*)def);
  63. }
  64. // -----------------------------------------------------------------------------
  65. // DescriptorPool.
  66. // -----------------------------------------------------------------------------
  67. #define DEFINE_CLASS(name, string_name) \
  68. VALUE c ## name = Qnil; \
  69. const rb_data_type_t _ ## name ## _type = { \
  70. string_name, \
  71. { name ## _mark, name ## _free, NULL }, \
  72. }; \
  73. name* ruby_to_ ## name(VALUE val) { \
  74. name* ret; \
  75. TypedData_Get_Struct(val, name, &_ ## name ## _type, ret); \
  76. return ret; \
  77. } \
  78. #define DEFINE_SELF(type, var, rb_var) \
  79. type* var = ruby_to_ ## type(rb_var)
  80. // Global singleton DescriptorPool. The user is free to create others, but this
  81. // is used by generated code.
  82. VALUE generated_pool;
  83. DEFINE_CLASS(DescriptorPool, "Google::Protobuf::DescriptorPool");
  84. void DescriptorPool_mark(void* _self) {
  85. }
  86. void DescriptorPool_free(void* _self) {
  87. DescriptorPool* self = _self;
  88. upb_symtab_free(self->symtab);
  89. xfree(self);
  90. }
  91. /*
  92. * call-seq:
  93. * DescriptorPool.new => pool
  94. *
  95. * Creates a new, empty, descriptor pool.
  96. */
  97. VALUE DescriptorPool_alloc(VALUE klass) {
  98. DescriptorPool* self = ALLOC(DescriptorPool);
  99. self->symtab = upb_symtab_new();
  100. return TypedData_Wrap_Struct(klass, &_DescriptorPool_type, self);
  101. }
  102. void DescriptorPool_register(VALUE module) {
  103. VALUE klass = rb_define_class_under(
  104. module, "DescriptorPool", rb_cObject);
  105. rb_define_alloc_func(klass, DescriptorPool_alloc);
  106. rb_define_method(klass, "add", DescriptorPool_add, 1);
  107. rb_define_method(klass, "build", DescriptorPool_build, 0);
  108. rb_define_method(klass, "lookup", DescriptorPool_lookup, 1);
  109. rb_define_singleton_method(klass, "generated_pool",
  110. DescriptorPool_generated_pool, 0);
  111. rb_gc_register_address(&cDescriptorPool);
  112. cDescriptorPool = klass;
  113. rb_gc_register_address(&generated_pool);
  114. generated_pool = rb_class_new_instance(0, NULL, klass);
  115. }
  116. static void add_descriptor_to_pool(DescriptorPool* self,
  117. Descriptor* descriptor) {
  118. CHECK_UPB(
  119. upb_symtab_add(self->symtab, (upb_def**)&descriptor->msgdef, 1,
  120. NULL, &status),
  121. "Adding Descriptor to DescriptorPool failed");
  122. }
  123. static void add_enumdesc_to_pool(DescriptorPool* self,
  124. EnumDescriptor* enumdesc) {
  125. CHECK_UPB(
  126. upb_symtab_add(self->symtab, (upb_def**)&enumdesc->enumdef, 1,
  127. NULL, &status),
  128. "Adding EnumDescriptor to DescriptorPool failed");
  129. }
  130. /*
  131. * call-seq:
  132. * DescriptorPool.add(descriptor)
  133. *
  134. * Adds the given Descriptor or EnumDescriptor to this pool. All references to
  135. * other types in a Descriptor's fields must be resolvable within this pool or
  136. * an exception will be raised.
  137. */
  138. VALUE DescriptorPool_add(VALUE _self, VALUE def) {
  139. DEFINE_SELF(DescriptorPool, self, _self);
  140. VALUE def_klass = rb_obj_class(def);
  141. if (def_klass == cDescriptor) {
  142. add_descriptor_to_pool(self, ruby_to_Descriptor(def));
  143. } else if (def_klass == cEnumDescriptor) {
  144. add_enumdesc_to_pool(self, ruby_to_EnumDescriptor(def));
  145. } else {
  146. rb_raise(rb_eArgError,
  147. "Second argument must be a Descriptor or EnumDescriptor.");
  148. }
  149. return Qnil;
  150. }
  151. /*
  152. * call-seq:
  153. * DescriptorPool.build(&block)
  154. *
  155. * Invokes the block with a Builder instance as self. All message and enum types
  156. * added within the block are committed to the pool atomically, and may refer
  157. * (co)recursively to each other. The user should call Builder#add_message and
  158. * Builder#add_enum within the block as appropriate. This is the recommended,
  159. * idiomatic way to define new message and enum types.
  160. */
  161. VALUE DescriptorPool_build(VALUE _self) {
  162. VALUE ctx = rb_class_new_instance(0, NULL, cBuilder);
  163. VALUE block = rb_block_proc();
  164. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  165. rb_funcall(ctx, rb_intern("finalize_to_pool"), 1, _self);
  166. return Qnil;
  167. }
  168. /*
  169. * call-seq:
  170. * DescriptorPool.lookup(name) => descriptor
  171. *
  172. * Finds a Descriptor or EnumDescriptor by name and returns it, or nil if none
  173. * exists with the given name.
  174. */
  175. VALUE DescriptorPool_lookup(VALUE _self, VALUE name) {
  176. DEFINE_SELF(DescriptorPool, self, _self);
  177. const char* name_str = get_str(name);
  178. const upb_def* def = upb_symtab_lookup(self->symtab, name_str);
  179. if (!def) {
  180. return Qnil;
  181. }
  182. return get_def_obj(def);
  183. }
  184. /*
  185. * call-seq:
  186. * DescriptorPool.generated_pool => descriptor_pool
  187. *
  188. * Class method that returns the global DescriptorPool. This is a singleton into
  189. * which generated-code message and enum types are registered. The user may also
  190. * register types in this pool for convenience so that they do not have to hold
  191. * a reference to a private pool instance.
  192. */
  193. VALUE DescriptorPool_generated_pool(VALUE _self) {
  194. return generated_pool;
  195. }
  196. // -----------------------------------------------------------------------------
  197. // Descriptor.
  198. // -----------------------------------------------------------------------------
  199. DEFINE_CLASS(Descriptor, "Google::Protobuf::Descriptor");
  200. void Descriptor_mark(void* _self) {
  201. Descriptor* self = _self;
  202. rb_gc_mark(self->klass);
  203. }
  204. void Descriptor_free(void* _self) {
  205. Descriptor* self = _self;
  206. upb_msgdef_unref(self->msgdef, &self->msgdef);
  207. if (self->layout) {
  208. free_layout(self->layout);
  209. }
  210. if (self->fill_handlers) {
  211. upb_handlers_unref(self->fill_handlers, &self->fill_handlers);
  212. }
  213. if (self->fill_method) {
  214. upb_pbdecodermethod_unref(self->fill_method, &self->fill_method);
  215. }
  216. if (self->json_fill_method) {
  217. upb_json_parsermethod_unref(self->json_fill_method,
  218. &self->json_fill_method);
  219. }
  220. if (self->pb_serialize_handlers) {
  221. upb_handlers_unref(self->pb_serialize_handlers,
  222. &self->pb_serialize_handlers);
  223. }
  224. if (self->json_serialize_handlers) {
  225. upb_handlers_unref(self->json_serialize_handlers,
  226. &self->json_serialize_handlers);
  227. }
  228. if (self->json_serialize_handlers_preserve) {
  229. upb_handlers_unref(self->json_serialize_handlers_preserve,
  230. &self->json_serialize_handlers_preserve);
  231. }
  232. xfree(self);
  233. }
  234. /*
  235. * call-seq:
  236. * Descriptor.new => descriptor
  237. *
  238. * Creates a new, empty, message type descriptor. At a minimum, its name must be
  239. * set before it is added to a pool. It cannot be used to create messages until
  240. * it is added to a pool, after which it becomes immutable (as part of a
  241. * finalization process).
  242. */
  243. VALUE Descriptor_alloc(VALUE klass) {
  244. Descriptor* self = ALLOC(Descriptor);
  245. VALUE ret = TypedData_Wrap_Struct(klass, &_Descriptor_type, self);
  246. self->msgdef = upb_msgdef_new(&self->msgdef);
  247. self->klass = Qnil;
  248. self->layout = NULL;
  249. self->fill_handlers = NULL;
  250. self->fill_method = NULL;
  251. self->json_fill_method = NULL;
  252. self->pb_serialize_handlers = NULL;
  253. self->json_serialize_handlers = NULL;
  254. self->json_serialize_handlers_preserve = NULL;
  255. return ret;
  256. }
  257. void Descriptor_register(VALUE module) {
  258. VALUE klass = rb_define_class_under(
  259. module, "Descriptor", rb_cObject);
  260. rb_define_alloc_func(klass, Descriptor_alloc);
  261. rb_define_method(klass, "each", Descriptor_each, 0);
  262. rb_define_method(klass, "lookup", Descriptor_lookup, 1);
  263. rb_define_method(klass, "add_field", Descriptor_add_field, 1);
  264. rb_define_method(klass, "add_oneof", Descriptor_add_oneof, 1);
  265. rb_define_method(klass, "each_oneof", Descriptor_each_oneof, 0);
  266. rb_define_method(klass, "lookup_oneof", Descriptor_lookup_oneof, 1);
  267. rb_define_method(klass, "msgclass", Descriptor_msgclass, 0);
  268. rb_define_method(klass, "name", Descriptor_name, 0);
  269. rb_define_method(klass, "name=", Descriptor_name_set, 1);
  270. rb_include_module(klass, rb_mEnumerable);
  271. rb_gc_register_address(&cDescriptor);
  272. cDescriptor = klass;
  273. }
  274. /*
  275. * call-seq:
  276. * Descriptor.name => name
  277. *
  278. * Returns the name of this message type as a fully-qualfied string (e.g.,
  279. * My.Package.MessageType).
  280. */
  281. VALUE Descriptor_name(VALUE _self) {
  282. DEFINE_SELF(Descriptor, self, _self);
  283. return rb_str_maybe_null(upb_msgdef_fullname(self->msgdef));
  284. }
  285. /*
  286. * call-seq:
  287. * Descriptor.name = name
  288. *
  289. * Assigns a name to this message type. The descriptor must not have been added
  290. * to a pool yet.
  291. */
  292. VALUE Descriptor_name_set(VALUE _self, VALUE str) {
  293. DEFINE_SELF(Descriptor, self, _self);
  294. upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
  295. const char* name = get_str(str);
  296. CHECK_UPB(
  297. upb_msgdef_setfullname(mut_def, name, &status),
  298. "Error setting Descriptor name");
  299. return Qnil;
  300. }
  301. /*
  302. * call-seq:
  303. * Descriptor.each(&block)
  304. *
  305. * Iterates over fields in this message type, yielding to the block on each one.
  306. */
  307. VALUE Descriptor_each(VALUE _self) {
  308. DEFINE_SELF(Descriptor, self, _self);
  309. upb_msg_field_iter it;
  310. for (upb_msg_field_begin(&it, self->msgdef);
  311. !upb_msg_field_done(&it);
  312. upb_msg_field_next(&it)) {
  313. const upb_fielddef* field = upb_msg_iter_field(&it);
  314. VALUE obj = get_def_obj(field);
  315. rb_yield(obj);
  316. }
  317. return Qnil;
  318. }
  319. /*
  320. * call-seq:
  321. * Descriptor.lookup(name) => FieldDescriptor
  322. *
  323. * Returns the field descriptor for the field with the given name, if present,
  324. * or nil if none.
  325. */
  326. VALUE Descriptor_lookup(VALUE _self, VALUE name) {
  327. DEFINE_SELF(Descriptor, self, _self);
  328. const char* s = get_str(name);
  329. const upb_fielddef* field = upb_msgdef_ntofz(self->msgdef, s);
  330. if (field == NULL) {
  331. return Qnil;
  332. }
  333. return get_def_obj(field);
  334. }
  335. /*
  336. * call-seq:
  337. * Descriptor.add_field(field) => nil
  338. *
  339. * Adds the given FieldDescriptor to this message type. This descriptor must not
  340. * have been added to a pool yet. Raises an exception if a field with the same
  341. * name or number already exists. Sub-type references (e.g. for fields of type
  342. * message) are not resolved at this point.
  343. */
  344. VALUE Descriptor_add_field(VALUE _self, VALUE obj) {
  345. DEFINE_SELF(Descriptor, self, _self);
  346. upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
  347. FieldDescriptor* def = ruby_to_FieldDescriptor(obj);
  348. upb_fielddef* mut_field_def = check_field_notfrozen(def->fielddef);
  349. CHECK_UPB(
  350. upb_msgdef_addfield(mut_def, mut_field_def, NULL, &status),
  351. "Adding field to Descriptor failed");
  352. add_def_obj(def->fielddef, obj);
  353. return Qnil;
  354. }
  355. /*
  356. * call-seq:
  357. * Descriptor.add_oneof(oneof) => nil
  358. *
  359. * Adds the given OneofDescriptor to this message type. This descriptor must not
  360. * have been added to a pool yet. Raises an exception if a oneof with the same
  361. * name already exists, or if any of the oneof's fields' names or numbers
  362. * conflict with an existing field in this message type. All fields in the oneof
  363. * are added to the message descriptor. Sub-type references (e.g. for fields of
  364. * type message) are not resolved at this point.
  365. */
  366. VALUE Descriptor_add_oneof(VALUE _self, VALUE obj) {
  367. DEFINE_SELF(Descriptor, self, _self);
  368. upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
  369. OneofDescriptor* def = ruby_to_OneofDescriptor(obj);
  370. upb_oneofdef* mut_oneof_def = check_oneof_notfrozen(def->oneofdef);
  371. CHECK_UPB(
  372. upb_msgdef_addoneof(mut_def, mut_oneof_def, NULL, &status),
  373. "Adding oneof to Descriptor failed");
  374. add_def_obj(def->oneofdef, obj);
  375. return Qnil;
  376. }
  377. /*
  378. * call-seq:
  379. * Descriptor.each_oneof(&block) => nil
  380. *
  381. * Invokes the given block for each oneof in this message type, passing the
  382. * corresponding OneofDescriptor.
  383. */
  384. VALUE Descriptor_each_oneof(VALUE _self) {
  385. DEFINE_SELF(Descriptor, self, _self);
  386. upb_msg_oneof_iter it;
  387. for (upb_msg_oneof_begin(&it, self->msgdef);
  388. !upb_msg_oneof_done(&it);
  389. upb_msg_oneof_next(&it)) {
  390. const upb_oneofdef* oneof = upb_msg_iter_oneof(&it);
  391. VALUE obj = get_def_obj(oneof);
  392. rb_yield(obj);
  393. }
  394. return Qnil;
  395. }
  396. /*
  397. * call-seq:
  398. * Descriptor.lookup_oneof(name) => OneofDescriptor
  399. *
  400. * Returns the oneof descriptor for the oneof with the given name, if present,
  401. * or nil if none.
  402. */
  403. VALUE Descriptor_lookup_oneof(VALUE _self, VALUE name) {
  404. DEFINE_SELF(Descriptor, self, _self);
  405. const char* s = get_str(name);
  406. const upb_oneofdef* oneof = upb_msgdef_ntooz(self->msgdef, s);
  407. if (oneof == NULL) {
  408. return Qnil;
  409. }
  410. return get_def_obj(oneof);
  411. }
  412. /*
  413. * call-seq:
  414. * Descriptor.msgclass => message_klass
  415. *
  416. * Returns the Ruby class created for this message type. Valid only once the
  417. * message type has been added to a pool.
  418. */
  419. VALUE Descriptor_msgclass(VALUE _self) {
  420. DEFINE_SELF(Descriptor, self, _self);
  421. if (!upb_def_isfrozen((const upb_def*)self->msgdef)) {
  422. rb_raise(rb_eRuntimeError,
  423. "Cannot fetch message class from a Descriptor not yet in a pool.");
  424. }
  425. if (self->klass == Qnil) {
  426. self->klass = build_class_from_descriptor(self);
  427. }
  428. return self->klass;
  429. }
  430. // -----------------------------------------------------------------------------
  431. // FieldDescriptor.
  432. // -----------------------------------------------------------------------------
  433. DEFINE_CLASS(FieldDescriptor, "Google::Protobuf::FieldDescriptor");
  434. void FieldDescriptor_mark(void* _self) {
  435. }
  436. void FieldDescriptor_free(void* _self) {
  437. FieldDescriptor* self = _self;
  438. upb_fielddef_unref(self->fielddef, &self->fielddef);
  439. xfree(self);
  440. }
  441. /*
  442. * call-seq:
  443. * FieldDescriptor.new => field
  444. *
  445. * Returns a new field descriptor. Its name, type, etc. must be set before it is
  446. * added to a message type.
  447. */
  448. VALUE FieldDescriptor_alloc(VALUE klass) {
  449. FieldDescriptor* self = ALLOC(FieldDescriptor);
  450. VALUE ret = TypedData_Wrap_Struct(klass, &_FieldDescriptor_type, self);
  451. upb_fielddef* fielddef = upb_fielddef_new(&self->fielddef);
  452. upb_fielddef_setpacked(fielddef, false);
  453. self->fielddef = fielddef;
  454. return ret;
  455. }
  456. void FieldDescriptor_register(VALUE module) {
  457. VALUE klass = rb_define_class_under(
  458. module, "FieldDescriptor", rb_cObject);
  459. rb_define_alloc_func(klass, FieldDescriptor_alloc);
  460. rb_define_method(klass, "name", FieldDescriptor_name, 0);
  461. rb_define_method(klass, "name=", FieldDescriptor_name_set, 1);
  462. rb_define_method(klass, "type", FieldDescriptor_type, 0);
  463. rb_define_method(klass, "type=", FieldDescriptor_type_set, 1);
  464. rb_define_method(klass, "label", FieldDescriptor_label, 0);
  465. rb_define_method(klass, "label=", FieldDescriptor_label_set, 1);
  466. rb_define_method(klass, "number", FieldDescriptor_number, 0);
  467. rb_define_method(klass, "number=", FieldDescriptor_number_set, 1);
  468. rb_define_method(klass, "submsg_name", FieldDescriptor_submsg_name, 0);
  469. rb_define_method(klass, "submsg_name=", FieldDescriptor_submsg_name_set, 1);
  470. rb_define_method(klass, "subtype", FieldDescriptor_subtype, 0);
  471. rb_define_method(klass, "get", FieldDescriptor_get, 1);
  472. rb_define_method(klass, "set", FieldDescriptor_set, 2);
  473. rb_gc_register_address(&cFieldDescriptor);
  474. cFieldDescriptor = klass;
  475. }
  476. /*
  477. * call-seq:
  478. * FieldDescriptor.name => name
  479. *
  480. * Returns the name of this field.
  481. */
  482. VALUE FieldDescriptor_name(VALUE _self) {
  483. DEFINE_SELF(FieldDescriptor, self, _self);
  484. return rb_str_maybe_null(upb_fielddef_name(self->fielddef));
  485. }
  486. /*
  487. * call-seq:
  488. * FieldDescriptor.name = name
  489. *
  490. * Sets the name of this field. Cannot be called once the containing message
  491. * type, if any, is added to a pool.
  492. */
  493. VALUE FieldDescriptor_name_set(VALUE _self, VALUE str) {
  494. DEFINE_SELF(FieldDescriptor, self, _self);
  495. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  496. const char* name = get_str(str);
  497. CHECK_UPB(upb_fielddef_setname(mut_def, name, &status),
  498. "Error setting FieldDescriptor name");
  499. return Qnil;
  500. }
  501. upb_fieldtype_t ruby_to_fieldtype(VALUE type) {
  502. if (TYPE(type) != T_SYMBOL) {
  503. rb_raise(rb_eArgError, "Expected symbol for field type.");
  504. }
  505. #define CONVERT(upb, ruby) \
  506. if (SYM2ID(type) == rb_intern( # ruby )) { \
  507. return UPB_TYPE_ ## upb; \
  508. }
  509. CONVERT(FLOAT, float);
  510. CONVERT(DOUBLE, double);
  511. CONVERT(BOOL, bool);
  512. CONVERT(STRING, string);
  513. CONVERT(BYTES, bytes);
  514. CONVERT(MESSAGE, message);
  515. CONVERT(ENUM, enum);
  516. CONVERT(INT32, int32);
  517. CONVERT(INT64, int64);
  518. CONVERT(UINT32, uint32);
  519. CONVERT(UINT64, uint64);
  520. #undef CONVERT
  521. rb_raise(rb_eArgError, "Unknown field type.");
  522. return 0;
  523. }
  524. VALUE fieldtype_to_ruby(upb_fieldtype_t type) {
  525. switch (type) {
  526. #define CONVERT(upb, ruby) \
  527. case UPB_TYPE_ ## upb : return ID2SYM(rb_intern( # ruby ));
  528. CONVERT(FLOAT, float);
  529. CONVERT(DOUBLE, double);
  530. CONVERT(BOOL, bool);
  531. CONVERT(STRING, string);
  532. CONVERT(BYTES, bytes);
  533. CONVERT(MESSAGE, message);
  534. CONVERT(ENUM, enum);
  535. CONVERT(INT32, int32);
  536. CONVERT(INT64, int64);
  537. CONVERT(UINT32, uint32);
  538. CONVERT(UINT64, uint64);
  539. #undef CONVERT
  540. }
  541. return Qnil;
  542. }
  543. upb_descriptortype_t ruby_to_descriptortype(VALUE type) {
  544. if (TYPE(type) != T_SYMBOL) {
  545. rb_raise(rb_eArgError, "Expected symbol for field type.");
  546. }
  547. #define CONVERT(upb, ruby) \
  548. if (SYM2ID(type) == rb_intern( # ruby )) { \
  549. return UPB_DESCRIPTOR_TYPE_ ## upb; \
  550. }
  551. CONVERT(FLOAT, float);
  552. CONVERT(DOUBLE, double);
  553. CONVERT(BOOL, bool);
  554. CONVERT(STRING, string);
  555. CONVERT(BYTES, bytes);
  556. CONVERT(MESSAGE, message);
  557. CONVERT(GROUP, group);
  558. CONVERT(ENUM, enum);
  559. CONVERT(INT32, int32);
  560. CONVERT(INT64, int64);
  561. CONVERT(UINT32, uint32);
  562. CONVERT(UINT64, uint64);
  563. CONVERT(SINT32, sint32);
  564. CONVERT(SINT64, sint64);
  565. CONVERT(FIXED32, fixed32);
  566. CONVERT(FIXED64, fixed64);
  567. CONVERT(SFIXED32, sfixed32);
  568. CONVERT(SFIXED64, sfixed64);
  569. #undef CONVERT
  570. rb_raise(rb_eArgError, "Unknown field type.");
  571. return 0;
  572. }
  573. VALUE descriptortype_to_ruby(upb_descriptortype_t type) {
  574. switch (type) {
  575. #define CONVERT(upb, ruby) \
  576. case UPB_DESCRIPTOR_TYPE_ ## upb : return ID2SYM(rb_intern( # ruby ));
  577. CONVERT(FLOAT, float);
  578. CONVERT(DOUBLE, double);
  579. CONVERT(BOOL, bool);
  580. CONVERT(STRING, string);
  581. CONVERT(BYTES, bytes);
  582. CONVERT(MESSAGE, message);
  583. CONVERT(GROUP, group);
  584. CONVERT(ENUM, enum);
  585. CONVERT(INT32, int32);
  586. CONVERT(INT64, int64);
  587. CONVERT(UINT32, uint32);
  588. CONVERT(UINT64, uint64);
  589. CONVERT(SINT32, sint32);
  590. CONVERT(SINT64, sint64);
  591. CONVERT(FIXED32, fixed32);
  592. CONVERT(FIXED64, fixed64);
  593. CONVERT(SFIXED32, sfixed32);
  594. CONVERT(SFIXED64, sfixed64);
  595. #undef CONVERT
  596. }
  597. return Qnil;
  598. }
  599. /*
  600. * call-seq:
  601. * FieldDescriptor.type => type
  602. *
  603. * Returns this field's type, as a Ruby symbol, or nil if not yet set.
  604. *
  605. * Valid field types are:
  606. * :int32, :int64, :uint32, :uint64, :float, :double, :bool, :string,
  607. * :bytes, :message.
  608. */
  609. VALUE FieldDescriptor_type(VALUE _self) {
  610. DEFINE_SELF(FieldDescriptor, self, _self);
  611. if (!upb_fielddef_typeisset(self->fielddef)) {
  612. return Qnil;
  613. }
  614. return descriptortype_to_ruby(upb_fielddef_descriptortype(self->fielddef));
  615. }
  616. /*
  617. * call-seq:
  618. * FieldDescriptor.type = type
  619. *
  620. * Sets this field's type. Cannot be called if field is part of a message type
  621. * already in a pool.
  622. */
  623. VALUE FieldDescriptor_type_set(VALUE _self, VALUE type) {
  624. DEFINE_SELF(FieldDescriptor, self, _self);
  625. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  626. upb_fielddef_setdescriptortype(mut_def, ruby_to_descriptortype(type));
  627. return Qnil;
  628. }
  629. /*
  630. * call-seq:
  631. * FieldDescriptor.label => label
  632. *
  633. * Returns this field's label (i.e., plurality), as a Ruby symbol.
  634. *
  635. * Valid field labels are:
  636. * :optional, :repeated
  637. */
  638. VALUE FieldDescriptor_label(VALUE _self) {
  639. DEFINE_SELF(FieldDescriptor, self, _self);
  640. switch (upb_fielddef_label(self->fielddef)) {
  641. #define CONVERT(upb, ruby) \
  642. case UPB_LABEL_ ## upb : return ID2SYM(rb_intern( # ruby ));
  643. CONVERT(OPTIONAL, optional);
  644. CONVERT(REQUIRED, required);
  645. CONVERT(REPEATED, repeated);
  646. #undef CONVERT
  647. }
  648. return Qnil;
  649. }
  650. /*
  651. * call-seq:
  652. * FieldDescriptor.label = label
  653. *
  654. * Sets the label on this field. Cannot be called if field is part of a message
  655. * type already in a pool.
  656. */
  657. VALUE FieldDescriptor_label_set(VALUE _self, VALUE label) {
  658. DEFINE_SELF(FieldDescriptor, self, _self);
  659. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  660. upb_label_t upb_label = -1;
  661. bool converted = false;
  662. if (TYPE(label) != T_SYMBOL) {
  663. rb_raise(rb_eArgError, "Expected symbol for field label.");
  664. }
  665. #define CONVERT(upb, ruby) \
  666. if (SYM2ID(label) == rb_intern( # ruby )) { \
  667. upb_label = UPB_LABEL_ ## upb; \
  668. converted = true; \
  669. }
  670. CONVERT(OPTIONAL, optional);
  671. CONVERT(REQUIRED, required);
  672. CONVERT(REPEATED, repeated);
  673. #undef CONVERT
  674. if (!converted) {
  675. rb_raise(rb_eArgError, "Unknown field label.");
  676. }
  677. upb_fielddef_setlabel(mut_def, upb_label);
  678. return Qnil;
  679. }
  680. /*
  681. * call-seq:
  682. * FieldDescriptor.number => number
  683. *
  684. * Returns the tag number for this field.
  685. */
  686. VALUE FieldDescriptor_number(VALUE _self) {
  687. DEFINE_SELF(FieldDescriptor, self, _self);
  688. return INT2NUM(upb_fielddef_number(self->fielddef));
  689. }
  690. /*
  691. * call-seq:
  692. * FieldDescriptor.number = number
  693. *
  694. * Sets the tag number for this field. Cannot be called if field is part of a
  695. * message type already in a pool.
  696. */
  697. VALUE FieldDescriptor_number_set(VALUE _self, VALUE number) {
  698. DEFINE_SELF(FieldDescriptor, self, _self);
  699. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  700. CHECK_UPB(upb_fielddef_setnumber(mut_def, NUM2INT(number), &status),
  701. "Error setting field number");
  702. return Qnil;
  703. }
  704. /*
  705. * call-seq:
  706. * FieldDescriptor.submsg_name => submsg_name
  707. *
  708. * Returns the name of the message or enum type corresponding to this field, if
  709. * it is a message or enum field (respectively), or nil otherwise. This type
  710. * name will be resolved within the context of the pool to which the containing
  711. * message type is added.
  712. */
  713. VALUE FieldDescriptor_submsg_name(VALUE _self) {
  714. DEFINE_SELF(FieldDescriptor, self, _self);
  715. if (!upb_fielddef_hassubdef(self->fielddef)) {
  716. return Qnil;
  717. }
  718. return rb_str_maybe_null(upb_fielddef_subdefname(self->fielddef));
  719. }
  720. /*
  721. * call-seq:
  722. * FieldDescriptor.submsg_name = submsg_name
  723. *
  724. * Sets the name of the message or enum type corresponding to this field, if it
  725. * is a message or enum field (respectively). This type name will be resolved
  726. * within the context of the pool to which the containing message type is added.
  727. * Cannot be called on field that are not of message or enum type, or on fields
  728. * that are part of a message type already added to a pool.
  729. */
  730. VALUE FieldDescriptor_submsg_name_set(VALUE _self, VALUE value) {
  731. DEFINE_SELF(FieldDescriptor, self, _self);
  732. upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
  733. const char* str = get_str(value);
  734. if (!upb_fielddef_hassubdef(self->fielddef)) {
  735. rb_raise(rb_eTypeError, "FieldDescriptor does not have subdef.");
  736. }
  737. CHECK_UPB(upb_fielddef_setsubdefname(mut_def, str, &status),
  738. "Error setting submessage name");
  739. return Qnil;
  740. }
  741. /*
  742. * call-seq:
  743. * FieldDescriptor.subtype => message_or_enum_descriptor
  744. *
  745. * Returns the message or enum descriptor corresponding to this field's type if
  746. * it is a message or enum field, respectively, or nil otherwise. Cannot be
  747. * called *until* the containing message type is added to a pool (and thus
  748. * resolved).
  749. */
  750. VALUE FieldDescriptor_subtype(VALUE _self) {
  751. DEFINE_SELF(FieldDescriptor, self, _self);
  752. const upb_def* def;
  753. if (!upb_fielddef_hassubdef(self->fielddef)) {
  754. return Qnil;
  755. }
  756. def = upb_fielddef_subdef(self->fielddef);
  757. if (def == NULL) {
  758. return Qnil;
  759. }
  760. return get_def_obj(def);
  761. }
  762. /*
  763. * call-seq:
  764. * FieldDescriptor.get(message) => value
  765. *
  766. * Returns the value set for this field on the given message. Raises an
  767. * exception if message is of the wrong type.
  768. */
  769. VALUE FieldDescriptor_get(VALUE _self, VALUE msg_rb) {
  770. DEFINE_SELF(FieldDescriptor, self, _self);
  771. MessageHeader* msg;
  772. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  773. if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
  774. rb_raise(rb_eTypeError, "get method called on wrong message type");
  775. }
  776. return layout_get(msg->descriptor->layout, Message_data(msg), self->fielddef);
  777. }
  778. /*
  779. * call-seq:
  780. * FieldDescriptor.set(message, value)
  781. *
  782. * Sets the value corresponding to this field to the given value on the given
  783. * message. Raises an exception if message is of the wrong type. Performs the
  784. * ordinary type-checks for field setting.
  785. */
  786. VALUE FieldDescriptor_set(VALUE _self, VALUE msg_rb, VALUE value) {
  787. DEFINE_SELF(FieldDescriptor, self, _self);
  788. MessageHeader* msg;
  789. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  790. if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
  791. rb_raise(rb_eTypeError, "set method called on wrong message type");
  792. }
  793. layout_set(msg->descriptor->layout, Message_data(msg), self->fielddef, value);
  794. return Qnil;
  795. }
  796. // -----------------------------------------------------------------------------
  797. // OneofDescriptor.
  798. // -----------------------------------------------------------------------------
  799. DEFINE_CLASS(OneofDescriptor, "Google::Protobuf::OneofDescriptor");
  800. void OneofDescriptor_mark(void* _self) {
  801. }
  802. void OneofDescriptor_free(void* _self) {
  803. OneofDescriptor* self = _self;
  804. upb_oneofdef_unref(self->oneofdef, &self->oneofdef);
  805. xfree(self);
  806. }
  807. /*
  808. * call-seq:
  809. * OneofDescriptor.new => oneof_descriptor
  810. *
  811. * Creates a new, empty, oneof descriptor. The oneof may only be modified prior
  812. * to being added to a message descriptor which is subsequently added to a pool.
  813. */
  814. VALUE OneofDescriptor_alloc(VALUE klass) {
  815. OneofDescriptor* self = ALLOC(OneofDescriptor);
  816. VALUE ret = TypedData_Wrap_Struct(klass, &_OneofDescriptor_type, self);
  817. self->oneofdef = upb_oneofdef_new(&self->oneofdef);
  818. return ret;
  819. }
  820. void OneofDescriptor_register(VALUE module) {
  821. VALUE klass = rb_define_class_under(
  822. module, "OneofDescriptor", rb_cObject);
  823. rb_define_alloc_func(klass, OneofDescriptor_alloc);
  824. rb_define_method(klass, "name", OneofDescriptor_name, 0);
  825. rb_define_method(klass, "name=", OneofDescriptor_name_set, 1);
  826. rb_define_method(klass, "add_field", OneofDescriptor_add_field, 1);
  827. rb_define_method(klass, "each", OneofDescriptor_each, 0);
  828. rb_include_module(klass, rb_mEnumerable);
  829. rb_gc_register_address(&cOneofDescriptor);
  830. cOneofDescriptor = klass;
  831. }
  832. /*
  833. * call-seq:
  834. * OneofDescriptor.name => name
  835. *
  836. * Returns the name of this oneof.
  837. */
  838. VALUE OneofDescriptor_name(VALUE _self) {
  839. DEFINE_SELF(OneofDescriptor, self, _self);
  840. return rb_str_maybe_null(upb_oneofdef_name(self->oneofdef));
  841. }
  842. /*
  843. * call-seq:
  844. * OneofDescriptor.name = name
  845. *
  846. * Sets a new name for this oneof. The oneof must not have been added to a
  847. * message descriptor yet.
  848. */
  849. VALUE OneofDescriptor_name_set(VALUE _self, VALUE value) {
  850. DEFINE_SELF(OneofDescriptor, self, _self);
  851. upb_oneofdef* mut_def = check_oneof_notfrozen(self->oneofdef);
  852. const char* str = get_str(value);
  853. CHECK_UPB(upb_oneofdef_setname(mut_def, str, &status),
  854. "Error setting oneof name");
  855. return Qnil;
  856. }
  857. /*
  858. * call-seq:
  859. * OneofDescriptor.add_field(field) => nil
  860. *
  861. * Adds a field to this oneof. The field may have been added to this oneof in
  862. * the past, or the message to which this oneof belongs (if any), but may not
  863. * have already been added to any other oneof or message. Otherwise, an
  864. * exception is raised.
  865. *
  866. * All fields added to the oneof via this method will be automatically added to
  867. * the message to which this oneof belongs, if it belongs to one currently, or
  868. * else will be added to any message to which the oneof is later added at the
  869. * time that it is added.
  870. */
  871. VALUE OneofDescriptor_add_field(VALUE _self, VALUE obj) {
  872. DEFINE_SELF(OneofDescriptor, self, _self);
  873. upb_oneofdef* mut_def = check_oneof_notfrozen(self->oneofdef);
  874. FieldDescriptor* def = ruby_to_FieldDescriptor(obj);
  875. upb_fielddef* mut_field_def = check_field_notfrozen(def->fielddef);
  876. CHECK_UPB(
  877. upb_oneofdef_addfield(mut_def, mut_field_def, NULL, &status),
  878. "Adding field to OneofDescriptor failed");
  879. add_def_obj(def->fielddef, obj);
  880. return Qnil;
  881. }
  882. /*
  883. * call-seq:
  884. * OneofDescriptor.each(&block) => nil
  885. *
  886. * Iterates through fields in this oneof, yielding to the block on each one.
  887. */
  888. VALUE OneofDescriptor_each(VALUE _self, VALUE field) {
  889. DEFINE_SELF(OneofDescriptor, self, _self);
  890. upb_oneof_iter it;
  891. for (upb_oneof_begin(&it, self->oneofdef);
  892. !upb_oneof_done(&it);
  893. upb_oneof_next(&it)) {
  894. const upb_fielddef* f = upb_oneof_iter_field(&it);
  895. VALUE obj = get_def_obj(f);
  896. rb_yield(obj);
  897. }
  898. return Qnil;
  899. }
  900. // -----------------------------------------------------------------------------
  901. // EnumDescriptor.
  902. // -----------------------------------------------------------------------------
  903. DEFINE_CLASS(EnumDescriptor, "Google::Protobuf::EnumDescriptor");
  904. void EnumDescriptor_mark(void* _self) {
  905. EnumDescriptor* self = _self;
  906. rb_gc_mark(self->module);
  907. }
  908. void EnumDescriptor_free(void* _self) {
  909. EnumDescriptor* self = _self;
  910. upb_enumdef_unref(self->enumdef, &self->enumdef);
  911. xfree(self);
  912. }
  913. /*
  914. * call-seq:
  915. * EnumDescriptor.new => enum_descriptor
  916. *
  917. * Creates a new, empty, enum descriptor. Must be added to a pool before the
  918. * enum type can be used. The enum type may only be modified prior to adding to
  919. * a pool.
  920. */
  921. VALUE EnumDescriptor_alloc(VALUE klass) {
  922. EnumDescriptor* self = ALLOC(EnumDescriptor);
  923. VALUE ret = TypedData_Wrap_Struct(klass, &_EnumDescriptor_type, self);
  924. self->enumdef = upb_enumdef_new(&self->enumdef);
  925. self->module = Qnil;
  926. return ret;
  927. }
  928. void EnumDescriptor_register(VALUE module) {
  929. VALUE klass = rb_define_class_under(
  930. module, "EnumDescriptor", rb_cObject);
  931. rb_define_alloc_func(klass, EnumDescriptor_alloc);
  932. rb_define_method(klass, "name", EnumDescriptor_name, 0);
  933. rb_define_method(klass, "name=", EnumDescriptor_name_set, 1);
  934. rb_define_method(klass, "add_value", EnumDescriptor_add_value, 2);
  935. rb_define_method(klass, "lookup_name", EnumDescriptor_lookup_name, 1);
  936. rb_define_method(klass, "lookup_value", EnumDescriptor_lookup_value, 1);
  937. rb_define_method(klass, "each", EnumDescriptor_each, 0);
  938. rb_define_method(klass, "enummodule", EnumDescriptor_enummodule, 0);
  939. rb_include_module(klass, rb_mEnumerable);
  940. rb_gc_register_address(&cEnumDescriptor);
  941. cEnumDescriptor = klass;
  942. }
  943. /*
  944. * call-seq:
  945. * EnumDescriptor.name => name
  946. *
  947. * Returns the name of this enum type.
  948. */
  949. VALUE EnumDescriptor_name(VALUE _self) {
  950. DEFINE_SELF(EnumDescriptor, self, _self);
  951. return rb_str_maybe_null(upb_enumdef_fullname(self->enumdef));
  952. }
  953. /*
  954. * call-seq:
  955. * EnumDescriptor.name = name
  956. *
  957. * Sets the name of this enum type. Cannot be called if the enum type has
  958. * already been added to a pool.
  959. */
  960. VALUE EnumDescriptor_name_set(VALUE _self, VALUE str) {
  961. DEFINE_SELF(EnumDescriptor, self, _self);
  962. upb_enumdef* mut_def = check_enum_notfrozen(self->enumdef);
  963. const char* name = get_str(str);
  964. CHECK_UPB(upb_enumdef_setfullname(mut_def, name, &status),
  965. "Error setting EnumDescriptor name");
  966. return Qnil;
  967. }
  968. /*
  969. * call-seq:
  970. * EnumDescriptor.add_value(key, value)
  971. *
  972. * Adds a new key => value mapping to this enum type. Key must be given as a
  973. * Ruby symbol. Cannot be called if the enum type has already been added to a
  974. * pool. Will raise an exception if the key or value is already in use.
  975. */
  976. VALUE EnumDescriptor_add_value(VALUE _self, VALUE name, VALUE number) {
  977. DEFINE_SELF(EnumDescriptor, self, _self);
  978. upb_enumdef* mut_def = check_enum_notfrozen(self->enumdef);
  979. const char* name_str = rb_id2name(SYM2ID(name));
  980. int32_t val = NUM2INT(number);
  981. CHECK_UPB(upb_enumdef_addval(mut_def, name_str, val, &status),
  982. "Error adding value to enum");
  983. return Qnil;
  984. }
  985. /*
  986. * call-seq:
  987. * EnumDescriptor.lookup_name(name) => value
  988. *
  989. * Returns the numeric value corresponding to the given key name (as a Ruby
  990. * symbol), or nil if none.
  991. */
  992. VALUE EnumDescriptor_lookup_name(VALUE _self, VALUE name) {
  993. DEFINE_SELF(EnumDescriptor, self, _self);
  994. const char* name_str= rb_id2name(SYM2ID(name));
  995. int32_t val = 0;
  996. if (upb_enumdef_ntoiz(self->enumdef, name_str, &val)) {
  997. return INT2NUM(val);
  998. } else {
  999. return Qnil;
  1000. }
  1001. }
  1002. /*
  1003. * call-seq:
  1004. * EnumDescriptor.lookup_value(name) => value
  1005. *
  1006. * Returns the key name (as a Ruby symbol) corresponding to the integer value,
  1007. * or nil if none.
  1008. */
  1009. VALUE EnumDescriptor_lookup_value(VALUE _self, VALUE number) {
  1010. DEFINE_SELF(EnumDescriptor, self, _self);
  1011. int32_t val = NUM2INT(number);
  1012. const char* name = upb_enumdef_iton(self->enumdef, val);
  1013. if (name != NULL) {
  1014. return ID2SYM(rb_intern(name));
  1015. } else {
  1016. return Qnil;
  1017. }
  1018. }
  1019. /*
  1020. * call-seq:
  1021. * EnumDescriptor.each(&block)
  1022. *
  1023. * Iterates over key => value mappings in this enum's definition, yielding to
  1024. * the block with (key, value) arguments for each one.
  1025. */
  1026. VALUE EnumDescriptor_each(VALUE _self) {
  1027. DEFINE_SELF(EnumDescriptor, self, _self);
  1028. upb_enum_iter it;
  1029. for (upb_enum_begin(&it, self->enumdef);
  1030. !upb_enum_done(&it);
  1031. upb_enum_next(&it)) {
  1032. VALUE key = ID2SYM(rb_intern(upb_enum_iter_name(&it)));
  1033. VALUE number = INT2NUM(upb_enum_iter_number(&it));
  1034. rb_yield_values(2, key, number);
  1035. }
  1036. return Qnil;
  1037. }
  1038. /*
  1039. * call-seq:
  1040. * EnumDescriptor.enummodule => module
  1041. *
  1042. * Returns the Ruby module corresponding to this enum type. Cannot be called
  1043. * until the enum descriptor has been added to a pool.
  1044. */
  1045. VALUE EnumDescriptor_enummodule(VALUE _self) {
  1046. DEFINE_SELF(EnumDescriptor, self, _self);
  1047. if (!upb_def_isfrozen((const upb_def*)self->enumdef)) {
  1048. rb_raise(rb_eRuntimeError,
  1049. "Cannot fetch enum module from an EnumDescriptor not yet "
  1050. "in a pool.");
  1051. }
  1052. if (self->module == Qnil) {
  1053. self->module = build_module_from_enumdesc(self);
  1054. }
  1055. return self->module;
  1056. }
  1057. // -----------------------------------------------------------------------------
  1058. // MessageBuilderContext.
  1059. // -----------------------------------------------------------------------------
  1060. DEFINE_CLASS(MessageBuilderContext,
  1061. "Google::Protobuf::Internal::MessageBuilderContext");
  1062. void MessageBuilderContext_mark(void* _self) {
  1063. MessageBuilderContext* self = _self;
  1064. rb_gc_mark(self->descriptor);
  1065. rb_gc_mark(self->builder);
  1066. }
  1067. void MessageBuilderContext_free(void* _self) {
  1068. MessageBuilderContext* self = _self;
  1069. xfree(self);
  1070. }
  1071. VALUE MessageBuilderContext_alloc(VALUE klass) {
  1072. MessageBuilderContext* self = ALLOC(MessageBuilderContext);
  1073. VALUE ret = TypedData_Wrap_Struct(
  1074. klass, &_MessageBuilderContext_type, self);
  1075. self->descriptor = Qnil;
  1076. self->builder = Qnil;
  1077. return ret;
  1078. }
  1079. void MessageBuilderContext_register(VALUE module) {
  1080. VALUE klass = rb_define_class_under(
  1081. module, "MessageBuilderContext", rb_cObject);
  1082. rb_define_alloc_func(klass, MessageBuilderContext_alloc);
  1083. rb_define_method(klass, "initialize",
  1084. MessageBuilderContext_initialize, 2);
  1085. rb_define_method(klass, "optional", MessageBuilderContext_optional, -1);
  1086. rb_define_method(klass, "required", MessageBuilderContext_required, -1);
  1087. rb_define_method(klass, "repeated", MessageBuilderContext_repeated, -1);
  1088. rb_define_method(klass, "map", MessageBuilderContext_map, -1);
  1089. rb_define_method(klass, "oneof", MessageBuilderContext_oneof, 1);
  1090. rb_gc_register_address(&cMessageBuilderContext);
  1091. cMessageBuilderContext = klass;
  1092. }
  1093. /*
  1094. * call-seq:
  1095. * MessageBuilderContext.new(desc, builder) => context
  1096. *
  1097. * Create a new message builder context around the given message descriptor and
  1098. * builder context. This class is intended to serve as a DSL context to be used
  1099. * with #instance_eval.
  1100. */
  1101. VALUE MessageBuilderContext_initialize(VALUE _self,
  1102. VALUE msgdef,
  1103. VALUE builder) {
  1104. DEFINE_SELF(MessageBuilderContext, self, _self);
  1105. self->descriptor = msgdef;
  1106. self->builder = builder;
  1107. return Qnil;
  1108. }
  1109. static VALUE msgdef_add_field(VALUE msgdef,
  1110. const char* label, VALUE name,
  1111. VALUE type, VALUE number,
  1112. VALUE type_class) {
  1113. VALUE fielddef = rb_class_new_instance(0, NULL, cFieldDescriptor);
  1114. VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
  1115. rb_funcall(fielddef, rb_intern("label="), 1, ID2SYM(rb_intern(label)));
  1116. rb_funcall(fielddef, rb_intern("name="), 1, name_str);
  1117. rb_funcall(fielddef, rb_intern("type="), 1, type);
  1118. rb_funcall(fielddef, rb_intern("number="), 1, number);
  1119. if (type_class != Qnil) {
  1120. if (TYPE(type_class) != T_STRING) {
  1121. rb_raise(rb_eArgError, "Expected string for type class");
  1122. }
  1123. // Make it an absolute type name by prepending a dot.
  1124. type_class = rb_str_append(rb_str_new2("."), type_class);
  1125. rb_funcall(fielddef, rb_intern("submsg_name="), 1, type_class);
  1126. }
  1127. rb_funcall(msgdef, rb_intern("add_field"), 1, fielddef);
  1128. return fielddef;
  1129. }
  1130. /*
  1131. * call-seq:
  1132. * MessageBuilderContext.optional(name, type, number, type_class = nil)
  1133. *
  1134. * Defines a new optional field on this message type with the given type, tag
  1135. * number, and type class (for message and enum fields). The type must be a Ruby
  1136. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1137. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1138. */
  1139. VALUE MessageBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
  1140. DEFINE_SELF(MessageBuilderContext, self, _self);
  1141. VALUE name, type, number, type_class;
  1142. if (argc < 3) {
  1143. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  1144. }
  1145. name = argv[0];
  1146. type = argv[1];
  1147. number = argv[2];
  1148. type_class = (argc > 3) ? argv[3] : Qnil;
  1149. return msgdef_add_field(self->descriptor, "optional",
  1150. name, type, number, type_class);
  1151. }
  1152. /*
  1153. * call-seq:
  1154. * MessageBuilderContext.required(name, type, number, type_class = nil)
  1155. *
  1156. * Defines a new required field on this message type with the given type, tag
  1157. * number, and type class (for message and enum fields). The type must be a Ruby
  1158. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1159. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1160. *
  1161. * Proto3 does not have required fields, but this method exists for
  1162. * completeness. Any attempt to add a message type with required fields to a
  1163. * pool will currently result in an error.
  1164. */
  1165. VALUE MessageBuilderContext_required(int argc, VALUE* argv, VALUE _self) {
  1166. DEFINE_SELF(MessageBuilderContext, self, _self);
  1167. VALUE name, type, number, type_class;
  1168. if (argc < 3) {
  1169. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  1170. }
  1171. name = argv[0];
  1172. type = argv[1];
  1173. number = argv[2];
  1174. type_class = (argc > 3) ? argv[3] : Qnil;
  1175. return msgdef_add_field(self->descriptor, "required",
  1176. name, type, number, type_class);
  1177. }
  1178. /*
  1179. * call-seq:
  1180. * MessageBuilderContext.repeated(name, type, number, type_class = nil)
  1181. *
  1182. * Defines a new repeated field on this message type with the given type, tag
  1183. * number, and type class (for message and enum fields). The type must be a Ruby
  1184. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1185. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1186. */
  1187. VALUE MessageBuilderContext_repeated(int argc, VALUE* argv, VALUE _self) {
  1188. DEFINE_SELF(MessageBuilderContext, self, _self);
  1189. VALUE name, type, number, type_class;
  1190. if (argc < 3) {
  1191. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  1192. }
  1193. name = argv[0];
  1194. type = argv[1];
  1195. number = argv[2];
  1196. type_class = (argc > 3) ? argv[3] : Qnil;
  1197. return msgdef_add_field(self->descriptor, "repeated",
  1198. name, type, number, type_class);
  1199. }
  1200. /*
  1201. * call-seq:
  1202. * MessageBuilderContext.map(name, key_type, value_type, number,
  1203. * value_type_class = nil)
  1204. *
  1205. * Defines a new map field on this message type with the given key and value
  1206. * types, tag number, and type class (for message and enum value types). The key
  1207. * type must be :int32/:uint32/:int64/:uint64, :bool, or :string. The value type
  1208. * type must be a Ruby symbol (as accepted by FieldDescriptor#type=) and the
  1209. * type_class must be a string, if present (as accepted by
  1210. * FieldDescriptor#submsg_name=).
  1211. */
  1212. VALUE MessageBuilderContext_map(int argc, VALUE* argv, VALUE _self) {
  1213. DEFINE_SELF(MessageBuilderContext, self, _self);
  1214. VALUE name, key_type, value_type, number, type_class;
  1215. VALUE mapentry_desc, mapentry_desc_name;
  1216. if (argc < 4) {
  1217. rb_raise(rb_eArgError, "Expected at least 4 arguments.");
  1218. }
  1219. name = argv[0];
  1220. key_type = argv[1];
  1221. value_type = argv[2];
  1222. number = argv[3];
  1223. type_class = (argc > 4) ? argv[4] : Qnil;
  1224. // Validate the key type. We can't accept enums, messages, or floats/doubles
  1225. // as map keys. (We exclude these explicitly, and the field-descriptor setter
  1226. // below then ensures that the type is one of the remaining valid options.)
  1227. if (SYM2ID(key_type) == rb_intern("float") ||
  1228. SYM2ID(key_type) == rb_intern("double") ||
  1229. SYM2ID(key_type) == rb_intern("enum") ||
  1230. SYM2ID(key_type) == rb_intern("message")) {
  1231. rb_raise(rb_eArgError,
  1232. "Cannot add a map field with a float, double, enum, or message "
  1233. "type.");
  1234. }
  1235. // Create a new message descriptor for the map entry message, and create a
  1236. // repeated submessage field here with that type.
  1237. mapentry_desc = rb_class_new_instance(0, NULL, cDescriptor);
  1238. mapentry_desc_name = rb_funcall(self->descriptor, rb_intern("name"), 0);
  1239. mapentry_desc_name = rb_str_cat2(mapentry_desc_name, "_MapEntry_");
  1240. mapentry_desc_name = rb_str_cat2(mapentry_desc_name,
  1241. rb_id2name(SYM2ID(name)));
  1242. Descriptor_name_set(mapentry_desc, mapentry_desc_name);
  1243. {
  1244. // The 'mapentry' attribute has no Ruby setter because we do not want the
  1245. // user attempting to DIY the setup below; we want to ensure that the fields
  1246. // are correct. So we reach into the msgdef here to set the bit manually.
  1247. Descriptor* mapentry_desc_self = ruby_to_Descriptor(mapentry_desc);
  1248. upb_msgdef_setmapentry((upb_msgdef*)mapentry_desc_self->msgdef, true);
  1249. }
  1250. {
  1251. // optional <type> key = 1;
  1252. VALUE key_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
  1253. FieldDescriptor_name_set(key_field, rb_str_new2("key"));
  1254. FieldDescriptor_label_set(key_field, ID2SYM(rb_intern("optional")));
  1255. FieldDescriptor_number_set(key_field, INT2NUM(1));
  1256. FieldDescriptor_type_set(key_field, key_type);
  1257. Descriptor_add_field(mapentry_desc, key_field);
  1258. }
  1259. {
  1260. // optional <type> value = 2;
  1261. VALUE value_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
  1262. FieldDescriptor_name_set(value_field, rb_str_new2("value"));
  1263. FieldDescriptor_label_set(value_field, ID2SYM(rb_intern("optional")));
  1264. FieldDescriptor_number_set(value_field, INT2NUM(2));
  1265. FieldDescriptor_type_set(value_field, value_type);
  1266. if (type_class != Qnil) {
  1267. VALUE submsg_name = rb_str_new2("."); // prepend '.' to make absolute.
  1268. submsg_name = rb_str_append(submsg_name, type_class);
  1269. FieldDescriptor_submsg_name_set(value_field, submsg_name);
  1270. }
  1271. Descriptor_add_field(mapentry_desc, value_field);
  1272. }
  1273. {
  1274. // Add the map-entry message type to the current builder, and use the type
  1275. // to create the map field itself.
  1276. Builder* builder_self = ruby_to_Builder(self->builder);
  1277. rb_ary_push(builder_self->pending_list, mapentry_desc);
  1278. }
  1279. {
  1280. VALUE map_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
  1281. VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
  1282. VALUE submsg_name;
  1283. FieldDescriptor_name_set(map_field, name_str);
  1284. FieldDescriptor_number_set(map_field, number);
  1285. FieldDescriptor_label_set(map_field, ID2SYM(rb_intern("repeated")));
  1286. FieldDescriptor_type_set(map_field, ID2SYM(rb_intern("message")));
  1287. submsg_name = rb_str_new2("."); // prepend '.' to make name absolute.
  1288. submsg_name = rb_str_append(submsg_name, mapentry_desc_name);
  1289. FieldDescriptor_submsg_name_set(map_field, submsg_name);
  1290. Descriptor_add_field(self->descriptor, map_field);
  1291. }
  1292. return Qnil;
  1293. }
  1294. /*
  1295. * call-seq:
  1296. * MessageBuilderContext.oneof(name, &block) => nil
  1297. *
  1298. * Creates a new OneofDescriptor with the given name, creates a
  1299. * OneofBuilderContext attached to that OneofDescriptor, evaluates the given
  1300. * block in the context of that OneofBuilderContext with #instance_eval, and
  1301. * then adds the oneof to the message.
  1302. *
  1303. * This is the recommended, idiomatic way to build oneof definitions.
  1304. */
  1305. VALUE MessageBuilderContext_oneof(VALUE _self, VALUE name) {
  1306. DEFINE_SELF(MessageBuilderContext, self, _self);
  1307. VALUE oneofdef = rb_class_new_instance(0, NULL, cOneofDescriptor);
  1308. VALUE args[2] = { oneofdef, self->builder };
  1309. VALUE ctx = rb_class_new_instance(2, args, cOneofBuilderContext);
  1310. VALUE block = rb_block_proc();
  1311. VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
  1312. rb_funcall(oneofdef, rb_intern("name="), 1, name_str);
  1313. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1314. Descriptor_add_oneof(self->descriptor, oneofdef);
  1315. return Qnil;
  1316. }
  1317. // -----------------------------------------------------------------------------
  1318. // OneofBuilderContext.
  1319. // -----------------------------------------------------------------------------
  1320. DEFINE_CLASS(OneofBuilderContext,
  1321. "Google::Protobuf::Internal::OneofBuilderContext");
  1322. void OneofBuilderContext_mark(void* _self) {
  1323. OneofBuilderContext* self = _self;
  1324. rb_gc_mark(self->descriptor);
  1325. rb_gc_mark(self->builder);
  1326. }
  1327. void OneofBuilderContext_free(void* _self) {
  1328. OneofBuilderContext* self = _self;
  1329. xfree(self);
  1330. }
  1331. VALUE OneofBuilderContext_alloc(VALUE klass) {
  1332. OneofBuilderContext* self = ALLOC(OneofBuilderContext);
  1333. VALUE ret = TypedData_Wrap_Struct(
  1334. klass, &_OneofBuilderContext_type, self);
  1335. self->descriptor = Qnil;
  1336. self->builder = Qnil;
  1337. return ret;
  1338. }
  1339. void OneofBuilderContext_register(VALUE module) {
  1340. VALUE klass = rb_define_class_under(
  1341. module, "OneofBuilderContext", rb_cObject);
  1342. rb_define_alloc_func(klass, OneofBuilderContext_alloc);
  1343. rb_define_method(klass, "initialize",
  1344. OneofBuilderContext_initialize, 2);
  1345. rb_define_method(klass, "optional", OneofBuilderContext_optional, -1);
  1346. rb_gc_register_address(&cOneofBuilderContext);
  1347. cOneofBuilderContext = klass;
  1348. }
  1349. /*
  1350. * call-seq:
  1351. * OneofBuilderContext.new(desc, builder) => context
  1352. *
  1353. * Create a new oneof builder context around the given oneof descriptor and
  1354. * builder context. This class is intended to serve as a DSL context to be used
  1355. * with #instance_eval.
  1356. */
  1357. VALUE OneofBuilderContext_initialize(VALUE _self,
  1358. VALUE oneofdef,
  1359. VALUE builder) {
  1360. DEFINE_SELF(OneofBuilderContext, self, _self);
  1361. self->descriptor = oneofdef;
  1362. self->builder = builder;
  1363. return Qnil;
  1364. }
  1365. /*
  1366. * call-seq:
  1367. * OneofBuilderContext.optional(name, type, number, type_class = nil)
  1368. *
  1369. * Defines a new optional field in this oneof with the given type, tag number,
  1370. * and type class (for message and enum fields). The type must be a Ruby symbol
  1371. * (as accepted by FieldDescriptor#type=) and the type_class must be a string,
  1372. * if present (as accepted by FieldDescriptor#submsg_name=).
  1373. */
  1374. VALUE OneofBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
  1375. DEFINE_SELF(OneofBuilderContext, self, _self);
  1376. VALUE name, type, number, type_class;
  1377. if (argc < 3) {
  1378. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  1379. }
  1380. name = argv[0];
  1381. type = argv[1];
  1382. number = argv[2];
  1383. type_class = (argc > 3) ? argv[3] : Qnil;
  1384. return msgdef_add_field(self->descriptor, "optional",
  1385. name, type, number, type_class);
  1386. }
  1387. // -----------------------------------------------------------------------------
  1388. // EnumBuilderContext.
  1389. // -----------------------------------------------------------------------------
  1390. DEFINE_CLASS(EnumBuilderContext,
  1391. "Google::Protobuf::Internal::EnumBuilderContext");
  1392. void EnumBuilderContext_mark(void* _self) {
  1393. EnumBuilderContext* self = _self;
  1394. rb_gc_mark(self->enumdesc);
  1395. }
  1396. void EnumBuilderContext_free(void* _self) {
  1397. EnumBuilderContext* self = _self;
  1398. xfree(self);
  1399. }
  1400. VALUE EnumBuilderContext_alloc(VALUE klass) {
  1401. EnumBuilderContext* self = ALLOC(EnumBuilderContext);
  1402. VALUE ret = TypedData_Wrap_Struct(
  1403. klass, &_EnumBuilderContext_type, self);
  1404. self->enumdesc = Qnil;
  1405. return ret;
  1406. }
  1407. void EnumBuilderContext_register(VALUE module) {
  1408. VALUE klass = rb_define_class_under(
  1409. module, "EnumBuilderContext", rb_cObject);
  1410. rb_define_alloc_func(klass, EnumBuilderContext_alloc);
  1411. rb_define_method(klass, "initialize",
  1412. EnumBuilderContext_initialize, 1);
  1413. rb_define_method(klass, "value", EnumBuilderContext_value, 2);
  1414. rb_gc_register_address(&cEnumBuilderContext);
  1415. cEnumBuilderContext = klass;
  1416. }
  1417. /*
  1418. * call-seq:
  1419. * EnumBuilderContext.new(enumdesc) => context
  1420. *
  1421. * Create a new builder context around the given enum descriptor. This class is
  1422. * intended to serve as a DSL context to be used with #instance_eval.
  1423. */
  1424. VALUE EnumBuilderContext_initialize(VALUE _self, VALUE enumdef) {
  1425. DEFINE_SELF(EnumBuilderContext, self, _self);
  1426. self->enumdesc = enumdef;
  1427. return Qnil;
  1428. }
  1429. static VALUE enumdef_add_value(VALUE enumdef,
  1430. VALUE name, VALUE number) {
  1431. rb_funcall(enumdef, rb_intern("add_value"), 2, name, number);
  1432. return Qnil;
  1433. }
  1434. /*
  1435. * call-seq:
  1436. * EnumBuilder.add_value(name, number)
  1437. *
  1438. * Adds the given name => number mapping to the enum type. Name must be a Ruby
  1439. * symbol.
  1440. */
  1441. VALUE EnumBuilderContext_value(VALUE _self, VALUE name, VALUE number) {
  1442. DEFINE_SELF(EnumBuilderContext, self, _self);
  1443. return enumdef_add_value(self->enumdesc, name, number);
  1444. }
  1445. // -----------------------------------------------------------------------------
  1446. // Builder.
  1447. // -----------------------------------------------------------------------------
  1448. DEFINE_CLASS(Builder, "Google::Protobuf::Internal::Builder");
  1449. void Builder_mark(void* _self) {
  1450. Builder* self = _self;
  1451. rb_gc_mark(self->pending_list);
  1452. }
  1453. void Builder_free(void* _self) {
  1454. Builder* self = _self;
  1455. xfree(self->defs);
  1456. xfree(self);
  1457. }
  1458. /*
  1459. * call-seq:
  1460. * Builder.new => builder
  1461. *
  1462. * Creates a new Builder. A Builder can accumulate a set of new message and enum
  1463. * descriptors and atomically register them into a pool in a way that allows for
  1464. * (co)recursive type references.
  1465. */
  1466. VALUE Builder_alloc(VALUE klass) {
  1467. Builder* self = ALLOC(Builder);
  1468. VALUE ret = TypedData_Wrap_Struct(
  1469. klass, &_Builder_type, self);
  1470. self->pending_list = Qnil;
  1471. self->defs = NULL;
  1472. return ret;
  1473. }
  1474. void Builder_register(VALUE module) {
  1475. VALUE klass = rb_define_class_under(module, "Builder", rb_cObject);
  1476. rb_define_alloc_func(klass, Builder_alloc);
  1477. rb_define_method(klass, "add_message", Builder_add_message, 1);
  1478. rb_define_method(klass, "add_enum", Builder_add_enum, 1);
  1479. rb_define_method(klass, "initialize", Builder_initialize, 0);
  1480. rb_define_method(klass, "finalize_to_pool", Builder_finalize_to_pool, 1);
  1481. rb_gc_register_address(&cBuilder);
  1482. cBuilder = klass;
  1483. }
  1484. /*
  1485. * call-seq:
  1486. * Builder.new(d) => builder
  1487. *
  1488. * Create a new message builder.
  1489. */
  1490. VALUE Builder_initialize(VALUE _self) {
  1491. DEFINE_SELF(Builder, self, _self);
  1492. self->pending_list = rb_ary_new();
  1493. return Qnil;
  1494. }
  1495. /*
  1496. * call-seq:
  1497. * Builder.add_message(name, &block)
  1498. *
  1499. * Creates a new, empty descriptor with the given name, and invokes the block in
  1500. * the context of a MessageBuilderContext on that descriptor. The block can then
  1501. * call, e.g., MessageBuilderContext#optional and MessageBuilderContext#repeated
  1502. * methods to define the message fields.
  1503. *
  1504. * This is the recommended, idiomatic way to build message definitions.
  1505. */
  1506. VALUE Builder_add_message(VALUE _self, VALUE name) {
  1507. DEFINE_SELF(Builder, self, _self);
  1508. VALUE msgdef = rb_class_new_instance(0, NULL, cDescriptor);
  1509. VALUE args[2] = { msgdef, _self };
  1510. VALUE ctx = rb_class_new_instance(2, args, cMessageBuilderContext);
  1511. VALUE block = rb_block_proc();
  1512. rb_funcall(msgdef, rb_intern("name="), 1, name);
  1513. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1514. rb_ary_push(self->pending_list, msgdef);
  1515. return Qnil;
  1516. }
  1517. /*
  1518. * call-seq:
  1519. * Builder.add_enum(name, &block)
  1520. *
  1521. * Creates a new, empty enum descriptor with the given name, and invokes the
  1522. * block in the context of an EnumBuilderContext on that descriptor. The block
  1523. * can then call EnumBuilderContext#add_value to define the enum values.
  1524. *
  1525. * This is the recommended, idiomatic way to build enum definitions.
  1526. */
  1527. VALUE Builder_add_enum(VALUE _self, VALUE name) {
  1528. DEFINE_SELF(Builder, self, _self);
  1529. VALUE enumdef = rb_class_new_instance(0, NULL, cEnumDescriptor);
  1530. VALUE ctx = rb_class_new_instance(1, &enumdef, cEnumBuilderContext);
  1531. VALUE block = rb_block_proc();
  1532. rb_funcall(enumdef, rb_intern("name="), 1, name);
  1533. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1534. rb_ary_push(self->pending_list, enumdef);
  1535. return Qnil;
  1536. }
  1537. static void validate_msgdef(const upb_msgdef* msgdef) {
  1538. // Verify that no required fields exist. proto3 does not support these.
  1539. upb_msg_field_iter it;
  1540. for (upb_msg_field_begin(&it, msgdef);
  1541. !upb_msg_field_done(&it);
  1542. upb_msg_field_next(&it)) {
  1543. const upb_fielddef* field = upb_msg_iter_field(&it);
  1544. if (upb_fielddef_label(field) == UPB_LABEL_REQUIRED) {
  1545. rb_raise(rb_eTypeError, "Required fields are unsupported in proto3.");
  1546. }
  1547. }
  1548. }
  1549. static void validate_enumdef(const upb_enumdef* enumdef) {
  1550. // Verify that an entry exists with integer value 0. (This is the default
  1551. // value.)
  1552. const char* lookup = upb_enumdef_iton(enumdef, 0);
  1553. if (lookup == NULL) {
  1554. rb_raise(rb_eTypeError,
  1555. "Enum definition does not contain a value for '0'.");
  1556. }
  1557. }
  1558. /*
  1559. * call-seq:
  1560. * Builder.finalize_to_pool(pool)
  1561. *
  1562. * Adds all accumulated message and enum descriptors created in this builder
  1563. * context to the given pool. The operation occurs atomically, and all
  1564. * descriptors can refer to each other (including in cycles). This is the only
  1565. * way to build (co)recursive message definitions.
  1566. *
  1567. * This method is usually called automatically by DescriptorPool#build after it
  1568. * invokes the given user block in the context of the builder. The user should
  1569. * not normally need to call this manually because a Builder is not normally
  1570. * created manually.
  1571. */
  1572. VALUE Builder_finalize_to_pool(VALUE _self, VALUE pool_rb) {
  1573. DEFINE_SELF(Builder, self, _self);
  1574. DescriptorPool* pool = ruby_to_DescriptorPool(pool_rb);
  1575. REALLOC_N(self->defs, upb_def*, RARRAY_LEN(self->pending_list));
  1576. for (int i = 0; i < RARRAY_LEN(self->pending_list); i++) {
  1577. VALUE def_rb = rb_ary_entry(self->pending_list, i);
  1578. if (CLASS_OF(def_rb) == cDescriptor) {
  1579. self->defs[i] = (upb_def*)ruby_to_Descriptor(def_rb)->msgdef;
  1580. validate_msgdef((const upb_msgdef*)self->defs[i]);
  1581. } else if (CLASS_OF(def_rb) == cEnumDescriptor) {
  1582. self->defs[i] = (upb_def*)ruby_to_EnumDescriptor(def_rb)->enumdef;
  1583. validate_enumdef((const upb_enumdef*)self->defs[i]);
  1584. }
  1585. }
  1586. CHECK_UPB(upb_symtab_add(pool->symtab, (upb_def**)self->defs,
  1587. RARRAY_LEN(self->pending_list), NULL, &status),
  1588. "Unable to add defs to DescriptorPool");
  1589. for (int i = 0; i < RARRAY_LEN(self->pending_list); i++) {
  1590. VALUE def_rb = rb_ary_entry(self->pending_list, i);
  1591. add_def_obj(self->defs[i], def_rb);
  1592. }
  1593. self->pending_list = rb_ary_new();
  1594. return Qnil;
  1595. }