defs.c 46 KB

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