defs.c 58 KB

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