defs.c 46 KB

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