defs.c 42 KB

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