defs.c 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557
  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 <ctype.h>
  31. #include <errno.h>
  32. #include <ruby/version.h>
  33. #include "convert.h"
  34. #include "message.h"
  35. #include "protobuf.h"
  36. static VALUE Builder_build(VALUE _self);
  37. static VALUE cMessageBuilderContext;
  38. static VALUE cOneofBuilderContext;
  39. static VALUE cEnumBuilderContext;
  40. static VALUE cBuilder;
  41. // -----------------------------------------------------------------------------
  42. // Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
  43. // instances.
  44. // -----------------------------------------------------------------------------
  45. static VALUE get_msgdef_obj(VALUE descriptor_pool, const upb_msgdef* def);
  46. static VALUE get_enumdef_obj(VALUE descriptor_pool, const upb_enumdef* def);
  47. static VALUE get_fielddef_obj(VALUE descriptor_pool, const upb_fielddef* def);
  48. static VALUE get_filedef_obj(VALUE descriptor_pool, const upb_filedef* def);
  49. static VALUE get_oneofdef_obj(VALUE descriptor_pool, const upb_oneofdef* def);
  50. // A distinct object that is not accessible from Ruby. We use this as a
  51. // constructor argument to enforce that certain objects cannot be created from
  52. // Ruby.
  53. VALUE c_only_cookie = Qnil;
  54. // -----------------------------------------------------------------------------
  55. // Common utilities.
  56. // -----------------------------------------------------------------------------
  57. static const char* get_str(VALUE str) {
  58. Check_Type(str, T_STRING);
  59. return RSTRING_PTR(str);
  60. }
  61. static VALUE rb_str_maybe_null(const char* s) {
  62. if (s == NULL) {
  63. s = "";
  64. }
  65. return rb_str_new2(s);
  66. }
  67. // -----------------------------------------------------------------------------
  68. // Backward compatibility code.
  69. // -----------------------------------------------------------------------------
  70. static void rewrite_enum_default(const upb_symtab* symtab,
  71. google_protobuf_FileDescriptorProto* file,
  72. google_protobuf_FieldDescriptorProto* field) {
  73. upb_strview defaultval;
  74. const char *type_name_str;
  75. char *end;
  76. long val;
  77. const upb_enumdef *e;
  78. upb_strview type_name;
  79. /* Look for TYPE_ENUM fields that have a default. */
  80. if (google_protobuf_FieldDescriptorProto_type(field) !=
  81. google_protobuf_FieldDescriptorProto_TYPE_ENUM ||
  82. !google_protobuf_FieldDescriptorProto_has_default_value(field) ||
  83. !google_protobuf_FieldDescriptorProto_has_type_name(field)) {
  84. return;
  85. }
  86. defaultval = google_protobuf_FieldDescriptorProto_default_value(field);
  87. type_name = google_protobuf_FieldDescriptorProto_type_name(field);
  88. if (defaultval.size == 0 || !isdigit(defaultval.data[0])) {
  89. return;
  90. }
  91. if (type_name.size == 0 || type_name.data[0] != '.') {
  92. return;
  93. }
  94. type_name_str = type_name.data + 1;
  95. errno = 0;
  96. val = strtol(defaultval.data, &end, 10);
  97. if (errno != 0 || *end != 0 || val < INT32_MIN || val > INT32_MAX) {
  98. return;
  99. }
  100. /* Now find the corresponding enum definition. */
  101. e = upb_symtab_lookupenum(symtab, type_name_str);
  102. if (e) {
  103. /* Look in previously loaded files. */
  104. const char *label = upb_enumdef_iton(e, val);
  105. if (!label) {
  106. return;
  107. }
  108. google_protobuf_FieldDescriptorProto_set_default_value(
  109. field, upb_strview_makez(label));
  110. } else {
  111. /* Look in enums defined in this file. */
  112. const google_protobuf_EnumDescriptorProto* matching_enum = NULL;
  113. size_t i, n;
  114. const google_protobuf_EnumDescriptorProto* const* enums =
  115. google_protobuf_FileDescriptorProto_enum_type(file, &n);
  116. const google_protobuf_EnumValueDescriptorProto* const* values;
  117. for (i = 0; i < n; i++) {
  118. if (upb_strview_eql(google_protobuf_EnumDescriptorProto_name(enums[i]),
  119. upb_strview_makez(type_name_str))) {
  120. matching_enum = enums[i];
  121. break;
  122. }
  123. }
  124. if (!matching_enum) {
  125. return;
  126. }
  127. values = google_protobuf_EnumDescriptorProto_value(matching_enum, &n);
  128. for (i = 0; i < n; i++) {
  129. if (google_protobuf_EnumValueDescriptorProto_number(values[i]) == val) {
  130. google_protobuf_FieldDescriptorProto_set_default_value(
  131. field, google_protobuf_EnumValueDescriptorProto_name(values[i]));
  132. return;
  133. }
  134. }
  135. /* We failed to find an enum default. But we'll just leave the enum
  136. * untouched and let the normal def-building code catch it. */
  137. }
  138. }
  139. /* Historically we allowed enum defaults to be specified as a number. In
  140. * retrospect this was a mistake as descriptors require defaults to be
  141. * specified as a label. This can make a difference if multiple labels have the
  142. * same number.
  143. *
  144. * Here we do a pass over all enum defaults and rewrite numeric defaults by
  145. * looking up their labels. This is complicated by the fact that the enum
  146. * definition can live in either the symtab or the file_proto.
  147. * */
  148. static void rewrite_enum_defaults(
  149. const upb_symtab* symtab, google_protobuf_FileDescriptorProto* file_proto) {
  150. size_t i, n;
  151. google_protobuf_DescriptorProto** msgs =
  152. google_protobuf_FileDescriptorProto_mutable_message_type(file_proto, &n);
  153. for (i = 0; i < n; i++) {
  154. size_t j, m;
  155. google_protobuf_FieldDescriptorProto** fields =
  156. google_protobuf_DescriptorProto_mutable_field(msgs[i], &m);
  157. for (j = 0; j < m; j++) {
  158. rewrite_enum_default(symtab, file_proto, fields[j]);
  159. }
  160. }
  161. }
  162. static void remove_path(upb_strview *name) {
  163. const char* last = strrchr(name->data, '.');
  164. if (last) {
  165. size_t remove = last - name->data + 1;
  166. name->data += remove;
  167. name->size -= remove;
  168. }
  169. }
  170. static void rewrite_nesting(VALUE msg_ent, google_protobuf_DescriptorProto* msg,
  171. google_protobuf_DescriptorProto* const* msgs,
  172. google_protobuf_EnumDescriptorProto* const* enums,
  173. upb_arena *arena) {
  174. VALUE submsgs = rb_hash_aref(msg_ent, ID2SYM(rb_intern("msgs")));
  175. VALUE enum_pos = rb_hash_aref(msg_ent, ID2SYM(rb_intern("enums")));
  176. int submsg_count;
  177. int enum_count;
  178. int i;
  179. google_protobuf_DescriptorProto** msg_msgs;
  180. google_protobuf_EnumDescriptorProto** msg_enums;
  181. Check_Type(submsgs, T_ARRAY);
  182. Check_Type(enum_pos, T_ARRAY);
  183. submsg_count = RARRAY_LEN(submsgs);
  184. enum_count = RARRAY_LEN(enum_pos);
  185. msg_msgs = google_protobuf_DescriptorProto_resize_nested_type(
  186. msg, submsg_count, arena);
  187. msg_enums =
  188. google_protobuf_DescriptorProto_resize_enum_type(msg, enum_count, arena);
  189. for (i = 0; i < submsg_count; i++) {
  190. VALUE submsg_ent = RARRAY_PTR(submsgs)[i];
  191. VALUE pos = rb_hash_aref(submsg_ent, ID2SYM(rb_intern("pos")));
  192. upb_strview name;
  193. msg_msgs[i] = msgs[NUM2INT(pos)];
  194. name = google_protobuf_DescriptorProto_name(msg_msgs[i]);
  195. remove_path(&name);
  196. google_protobuf_DescriptorProto_set_name(msg_msgs[i], name);
  197. rewrite_nesting(submsg_ent, msg_msgs[i], msgs, enums, arena);
  198. }
  199. for (i = 0; i < enum_count; i++) {
  200. VALUE pos = RARRAY_PTR(enum_pos)[i];
  201. msg_enums[i] = enums[NUM2INT(pos)];
  202. }
  203. }
  204. // -----------------------------------------------------------------------------
  205. // DescriptorPool.
  206. // -----------------------------------------------------------------------------
  207. typedef struct {
  208. VALUE def_to_descriptor; // Hash table of def* -> Ruby descriptor.
  209. upb_symtab* symtab;
  210. } DescriptorPool;
  211. VALUE cDescriptorPool = Qnil;
  212. // Global singleton DescriptorPool. The user is free to create others, but this
  213. // is used by generated code.
  214. VALUE generated_pool = Qnil;
  215. static void DescriptorPool_mark(void* _self) {
  216. DescriptorPool* self = _self;
  217. rb_gc_mark(self->def_to_descriptor);
  218. }
  219. static void DescriptorPool_free(void* _self) {
  220. DescriptorPool* self = _self;
  221. upb_symtab_free(self->symtab);
  222. xfree(self);
  223. }
  224. static const rb_data_type_t DescriptorPool_type = {
  225. "Google::Protobuf::DescriptorPool",
  226. {DescriptorPool_mark, DescriptorPool_free, NULL},
  227. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  228. };
  229. static DescriptorPool* ruby_to_DescriptorPool(VALUE val) {
  230. DescriptorPool* ret;
  231. TypedData_Get_Struct(val, DescriptorPool, &DescriptorPool_type, ret);
  232. return ret;
  233. }
  234. // Exposed to other modules in defs.h.
  235. const upb_symtab *DescriptorPool_GetSymtab(VALUE desc_pool_rb) {
  236. DescriptorPool *pool = ruby_to_DescriptorPool(desc_pool_rb);
  237. return pool->symtab;
  238. }
  239. /*
  240. * call-seq:
  241. * DescriptorPool.new => pool
  242. *
  243. * Creates a new, empty, descriptor pool.
  244. */
  245. static VALUE DescriptorPool_alloc(VALUE klass) {
  246. DescriptorPool* self = ALLOC(DescriptorPool);
  247. VALUE ret;
  248. self->def_to_descriptor = Qnil;
  249. ret = TypedData_Wrap_Struct(klass, &DescriptorPool_type, self);
  250. self->def_to_descriptor = rb_hash_new();
  251. self->symtab = upb_symtab_new();
  252. ObjectCache_Add(self->symtab, ret);
  253. return ret;
  254. }
  255. /*
  256. * call-seq:
  257. * DescriptorPool.build(&block)
  258. *
  259. * Invokes the block with a Builder instance as self. All message and enum types
  260. * added within the block are committed to the pool atomically, and may refer
  261. * (co)recursively to each other. The user should call Builder#add_message and
  262. * Builder#add_enum within the block as appropriate. This is the recommended,
  263. * idiomatic way to define new message and enum types.
  264. */
  265. static VALUE DescriptorPool_build(int argc, VALUE* argv, VALUE _self) {
  266. VALUE ctx = rb_class_new_instance(1, &_self, cBuilder);
  267. VALUE block = rb_block_proc();
  268. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  269. Builder_build(ctx);
  270. return Qnil;
  271. }
  272. /*
  273. * call-seq:
  274. * DescriptorPool.lookup(name) => descriptor
  275. *
  276. * Finds a Descriptor or EnumDescriptor by name and returns it, or nil if none
  277. * exists with the given name.
  278. */
  279. static VALUE DescriptorPool_lookup(VALUE _self, VALUE name) {
  280. DescriptorPool* self = ruby_to_DescriptorPool(_self);
  281. const char* name_str = get_str(name);
  282. const upb_msgdef* msgdef;
  283. const upb_enumdef* enumdef;
  284. msgdef = upb_symtab_lookupmsg(self->symtab, name_str);
  285. if (msgdef) {
  286. return get_msgdef_obj(_self, msgdef);
  287. }
  288. enumdef = upb_symtab_lookupenum(self->symtab, name_str);
  289. if (enumdef) {
  290. return get_enumdef_obj(_self, enumdef);
  291. }
  292. return Qnil;
  293. }
  294. /*
  295. * call-seq:
  296. * DescriptorPool.generated_pool => descriptor_pool
  297. *
  298. * Class method that returns the global DescriptorPool. This is a singleton into
  299. * which generated-code message and enum types are registered. The user may also
  300. * register types in this pool for convenience so that they do not have to hold
  301. * a reference to a private pool instance.
  302. */
  303. static VALUE DescriptorPool_generated_pool(VALUE _self) {
  304. return generated_pool;
  305. }
  306. static void DescriptorPool_register(VALUE module) {
  307. VALUE klass = rb_define_class_under(
  308. module, "DescriptorPool", rb_cObject);
  309. rb_define_alloc_func(klass, DescriptorPool_alloc);
  310. rb_define_method(klass, "build", DescriptorPool_build, -1);
  311. rb_define_method(klass, "lookup", DescriptorPool_lookup, 1);
  312. rb_define_singleton_method(klass, "generated_pool",
  313. DescriptorPool_generated_pool, 0);
  314. rb_gc_register_address(&cDescriptorPool);
  315. cDescriptorPool = klass;
  316. rb_gc_register_address(&generated_pool);
  317. generated_pool = rb_class_new_instance(0, NULL, klass);
  318. }
  319. // -----------------------------------------------------------------------------
  320. // Descriptor.
  321. // -----------------------------------------------------------------------------
  322. typedef struct {
  323. const upb_msgdef* msgdef;
  324. VALUE klass;
  325. VALUE descriptor_pool;
  326. } Descriptor;
  327. VALUE cDescriptor = Qnil;
  328. static void Descriptor_mark(void* _self) {
  329. Descriptor* self = _self;
  330. rb_gc_mark(self->klass);
  331. rb_gc_mark(self->descriptor_pool);
  332. }
  333. static const rb_data_type_t Descriptor_type = {
  334. "Google::Protobuf::Descriptor",
  335. {Descriptor_mark, RUBY_DEFAULT_FREE, NULL},
  336. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  337. };
  338. static Descriptor* ruby_to_Descriptor(VALUE val) {
  339. Descriptor* ret;
  340. TypedData_Get_Struct(val, Descriptor, &Descriptor_type, ret);
  341. return ret;
  342. }
  343. /*
  344. * call-seq:
  345. * Descriptor.new => descriptor
  346. *
  347. * Creates a new, empty, message type descriptor. At a minimum, its name must be
  348. * set before it is added to a pool. It cannot be used to create messages until
  349. * it is added to a pool, after which it becomes immutable (as part of a
  350. * finalization process).
  351. */
  352. static VALUE Descriptor_alloc(VALUE klass) {
  353. Descriptor* self = ALLOC(Descriptor);
  354. VALUE ret = TypedData_Wrap_Struct(klass, &Descriptor_type, self);
  355. self->msgdef = NULL;
  356. self->klass = Qnil;
  357. self->descriptor_pool = Qnil;
  358. return ret;
  359. }
  360. /*
  361. * call-seq:
  362. * Descriptor.new(c_only_cookie, ptr) => Descriptor
  363. *
  364. * Creates a descriptor wrapper object. May only be called from C.
  365. */
  366. static VALUE Descriptor_initialize(VALUE _self, VALUE cookie,
  367. VALUE descriptor_pool, VALUE ptr) {
  368. Descriptor* self = ruby_to_Descriptor(_self);
  369. if (cookie != c_only_cookie) {
  370. rb_raise(rb_eRuntimeError,
  371. "Descriptor objects may not be created from Ruby.");
  372. }
  373. self->descriptor_pool = descriptor_pool;
  374. self->msgdef = (const upb_msgdef*)NUM2ULL(ptr);
  375. return Qnil;
  376. }
  377. /*
  378. * call-seq:
  379. * Descriptor.file_descriptor
  380. *
  381. * Returns the FileDescriptor object this message belongs to.
  382. */
  383. static VALUE Descriptor_file_descriptor(VALUE _self) {
  384. Descriptor* self = ruby_to_Descriptor(_self);
  385. return get_filedef_obj(self->descriptor_pool, upb_msgdef_file(self->msgdef));
  386. }
  387. /*
  388. * call-seq:
  389. * Descriptor.name => name
  390. *
  391. * Returns the name of this message type as a fully-qualified string (e.g.,
  392. * My.Package.MessageType).
  393. */
  394. static VALUE Descriptor_name(VALUE _self) {
  395. Descriptor* self = ruby_to_Descriptor(_self);
  396. return rb_str_maybe_null(upb_msgdef_fullname(self->msgdef));
  397. }
  398. /*
  399. * call-seq:
  400. * Descriptor.each(&block)
  401. *
  402. * Iterates over fields in this message type, yielding to the block on each one.
  403. */
  404. static VALUE Descriptor_each(VALUE _self) {
  405. Descriptor* self = ruby_to_Descriptor(_self);
  406. upb_msg_field_iter it;
  407. for (upb_msg_field_begin(&it, self->msgdef);
  408. !upb_msg_field_done(&it);
  409. upb_msg_field_next(&it)) {
  410. const upb_fielddef* field = upb_msg_iter_field(&it);
  411. VALUE obj = get_fielddef_obj(self->descriptor_pool, field);
  412. rb_yield(obj);
  413. }
  414. return Qnil;
  415. }
  416. /*
  417. * call-seq:
  418. * Descriptor.lookup(name) => FieldDescriptor
  419. *
  420. * Returns the field descriptor for the field with the given name, if present,
  421. * or nil if none.
  422. */
  423. static VALUE Descriptor_lookup(VALUE _self, VALUE name) {
  424. Descriptor* self = ruby_to_Descriptor(_self);
  425. const char* s = get_str(name);
  426. const upb_fielddef* field = upb_msgdef_ntofz(self->msgdef, s);
  427. if (field == NULL) {
  428. return Qnil;
  429. }
  430. return get_fielddef_obj(self->descriptor_pool, field);
  431. }
  432. /*
  433. * call-seq:
  434. * Descriptor.each_oneof(&block) => nil
  435. *
  436. * Invokes the given block for each oneof in this message type, passing the
  437. * corresponding OneofDescriptor.
  438. */
  439. static VALUE Descriptor_each_oneof(VALUE _self) {
  440. Descriptor* self = ruby_to_Descriptor(_self);
  441. upb_msg_oneof_iter it;
  442. for (upb_msg_oneof_begin(&it, self->msgdef);
  443. !upb_msg_oneof_done(&it);
  444. upb_msg_oneof_next(&it)) {
  445. const upb_oneofdef* oneof = upb_msg_iter_oneof(&it);
  446. VALUE obj = get_oneofdef_obj(self->descriptor_pool, oneof);
  447. rb_yield(obj);
  448. }
  449. return Qnil;
  450. }
  451. /*
  452. * call-seq:
  453. * Descriptor.lookup_oneof(name) => OneofDescriptor
  454. *
  455. * Returns the oneof descriptor for the oneof with the given name, if present,
  456. * or nil if none.
  457. */
  458. static VALUE Descriptor_lookup_oneof(VALUE _self, VALUE name) {
  459. Descriptor* self = ruby_to_Descriptor(_self);
  460. const char* s = get_str(name);
  461. const upb_oneofdef* oneof = upb_msgdef_ntooz(self->msgdef, s);
  462. if (oneof == NULL) {
  463. return Qnil;
  464. }
  465. return get_oneofdef_obj(self->descriptor_pool, oneof);
  466. }
  467. /*
  468. * call-seq:
  469. * Descriptor.msgclass => message_klass
  470. *
  471. * Returns the Ruby class created for this message type.
  472. */
  473. static VALUE Descriptor_msgclass(VALUE _self) {
  474. Descriptor* self = ruby_to_Descriptor(_self);
  475. if (self->klass == Qnil) {
  476. self->klass = build_class_from_descriptor(_self);
  477. }
  478. return self->klass;
  479. }
  480. static void Descriptor_register(VALUE module) {
  481. VALUE klass = rb_define_class_under(
  482. module, "Descriptor", rb_cObject);
  483. rb_define_alloc_func(klass, Descriptor_alloc);
  484. rb_define_method(klass, "initialize", Descriptor_initialize, 3);
  485. rb_define_method(klass, "each", Descriptor_each, 0);
  486. rb_define_method(klass, "lookup", Descriptor_lookup, 1);
  487. rb_define_method(klass, "each_oneof", Descriptor_each_oneof, 0);
  488. rb_define_method(klass, "lookup_oneof", Descriptor_lookup_oneof, 1);
  489. rb_define_method(klass, "msgclass", Descriptor_msgclass, 0);
  490. rb_define_method(klass, "name", Descriptor_name, 0);
  491. rb_define_method(klass, "file_descriptor", Descriptor_file_descriptor, 0);
  492. rb_include_module(klass, rb_mEnumerable);
  493. rb_gc_register_address(&cDescriptor);
  494. cDescriptor = klass;
  495. }
  496. // -----------------------------------------------------------------------------
  497. // FileDescriptor.
  498. // -----------------------------------------------------------------------------
  499. typedef struct {
  500. const upb_filedef* filedef;
  501. VALUE descriptor_pool; // Owns the upb_filedef.
  502. } FileDescriptor;
  503. static VALUE cFileDescriptor = Qnil;
  504. static void FileDescriptor_mark(void* _self) {
  505. FileDescriptor* self = _self;
  506. rb_gc_mark(self->descriptor_pool);
  507. }
  508. static const rb_data_type_t FileDescriptor_type = {
  509. "Google::Protobuf::FileDescriptor",
  510. {FileDescriptor_mark, RUBY_DEFAULT_FREE, NULL},
  511. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  512. };
  513. static FileDescriptor* ruby_to_FileDescriptor(VALUE val) {
  514. FileDescriptor* ret;
  515. TypedData_Get_Struct(val, FileDescriptor, &FileDescriptor_type, ret);
  516. return ret;
  517. }
  518. static VALUE FileDescriptor_alloc(VALUE klass) {
  519. FileDescriptor* self = ALLOC(FileDescriptor);
  520. VALUE ret = TypedData_Wrap_Struct(klass, &FileDescriptor_type, self);
  521. self->descriptor_pool = Qnil;
  522. self->filedef = NULL;
  523. return ret;
  524. }
  525. /*
  526. * call-seq:
  527. * FileDescriptor.new => file
  528. *
  529. * Returns a new file descriptor. The syntax must be set before it's passed
  530. * to a builder.
  531. */
  532. static VALUE FileDescriptor_initialize(VALUE _self, VALUE cookie,
  533. VALUE descriptor_pool, VALUE ptr) {
  534. FileDescriptor* self = ruby_to_FileDescriptor(_self);
  535. if (cookie != c_only_cookie) {
  536. rb_raise(rb_eRuntimeError,
  537. "Descriptor objects may not be created from Ruby.");
  538. }
  539. self->descriptor_pool = descriptor_pool;
  540. self->filedef = (const upb_filedef*)NUM2ULL(ptr);
  541. return Qnil;
  542. }
  543. /*
  544. * call-seq:
  545. * FileDescriptor.name => name
  546. *
  547. * Returns the name of the file.
  548. */
  549. static VALUE FileDescriptor_name(VALUE _self) {
  550. FileDescriptor* self = ruby_to_FileDescriptor(_self);
  551. const char* name = upb_filedef_name(self->filedef);
  552. return name == NULL ? Qnil : rb_str_new2(name);
  553. }
  554. /*
  555. * call-seq:
  556. * FileDescriptor.syntax => syntax
  557. *
  558. * Returns this file descriptors syntax.
  559. *
  560. * Valid syntax versions are:
  561. * :proto2 or :proto3.
  562. */
  563. static VALUE FileDescriptor_syntax(VALUE _self) {
  564. FileDescriptor* self = ruby_to_FileDescriptor(_self);
  565. switch (upb_filedef_syntax(self->filedef)) {
  566. case UPB_SYNTAX_PROTO3: return ID2SYM(rb_intern("proto3"));
  567. case UPB_SYNTAX_PROTO2: return ID2SYM(rb_intern("proto2"));
  568. default: return Qnil;
  569. }
  570. }
  571. static void FileDescriptor_register(VALUE module) {
  572. VALUE klass = rb_define_class_under(
  573. module, "FileDescriptor", rb_cObject);
  574. rb_define_alloc_func(klass, FileDescriptor_alloc);
  575. rb_define_method(klass, "initialize", FileDescriptor_initialize, 3);
  576. rb_define_method(klass, "name", FileDescriptor_name, 0);
  577. rb_define_method(klass, "syntax", FileDescriptor_syntax, 0);
  578. rb_gc_register_address(&cFileDescriptor);
  579. cFileDescriptor = klass;
  580. }
  581. // -----------------------------------------------------------------------------
  582. // FieldDescriptor.
  583. // -----------------------------------------------------------------------------
  584. typedef struct {
  585. const upb_fielddef* fielddef;
  586. VALUE descriptor_pool; // Owns the upb_fielddef.
  587. } FieldDescriptor;
  588. static VALUE cFieldDescriptor = Qnil;
  589. static void FieldDescriptor_mark(void* _self) {
  590. FieldDescriptor* self = _self;
  591. rb_gc_mark(self->descriptor_pool);
  592. }
  593. static const rb_data_type_t FieldDescriptor_type = {
  594. "Google::Protobuf::FieldDescriptor",
  595. {FieldDescriptor_mark, RUBY_DEFAULT_FREE, NULL},
  596. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  597. };
  598. static FieldDescriptor* ruby_to_FieldDescriptor(VALUE val) {
  599. FieldDescriptor* ret;
  600. TypedData_Get_Struct(val, FieldDescriptor, &FieldDescriptor_type, ret);
  601. return ret;
  602. }
  603. /*
  604. * call-seq:
  605. * FieldDescriptor.new => field
  606. *
  607. * Returns a new field descriptor. Its name, type, etc. must be set before it is
  608. * added to a message type.
  609. */
  610. static VALUE FieldDescriptor_alloc(VALUE klass) {
  611. FieldDescriptor* self = ALLOC(FieldDescriptor);
  612. VALUE ret = TypedData_Wrap_Struct(klass, &FieldDescriptor_type, self);
  613. self->fielddef = NULL;
  614. return ret;
  615. }
  616. /*
  617. * call-seq:
  618. * EnumDescriptor.new(c_only_cookie, pool, ptr) => EnumDescriptor
  619. *
  620. * Creates a descriptor wrapper object. May only be called from C.
  621. */
  622. static VALUE FieldDescriptor_initialize(VALUE _self, VALUE cookie,
  623. VALUE descriptor_pool, VALUE ptr) {
  624. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  625. if (cookie != c_only_cookie) {
  626. rb_raise(rb_eRuntimeError,
  627. "Descriptor objects may not be created from Ruby.");
  628. }
  629. self->descriptor_pool = descriptor_pool;
  630. self->fielddef = (const upb_fielddef*)NUM2ULL(ptr);
  631. return Qnil;
  632. }
  633. /*
  634. * call-seq:
  635. * FieldDescriptor.name => name
  636. *
  637. * Returns the name of this field.
  638. */
  639. static VALUE FieldDescriptor_name(VALUE _self) {
  640. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  641. return rb_str_maybe_null(upb_fielddef_name(self->fielddef));
  642. }
  643. // Non-static, exposed to other .c files.
  644. upb_fieldtype_t ruby_to_fieldtype(VALUE type) {
  645. if (TYPE(type) != T_SYMBOL) {
  646. rb_raise(rb_eArgError, "Expected symbol for field type.");
  647. }
  648. #define CONVERT(upb, ruby) \
  649. if (SYM2ID(type) == rb_intern( # ruby )) { \
  650. return UPB_TYPE_ ## upb; \
  651. }
  652. CONVERT(FLOAT, float);
  653. CONVERT(DOUBLE, double);
  654. CONVERT(BOOL, bool);
  655. CONVERT(STRING, string);
  656. CONVERT(BYTES, bytes);
  657. CONVERT(MESSAGE, message);
  658. CONVERT(ENUM, enum);
  659. CONVERT(INT32, int32);
  660. CONVERT(INT64, int64);
  661. CONVERT(UINT32, uint32);
  662. CONVERT(UINT64, uint64);
  663. #undef CONVERT
  664. rb_raise(rb_eArgError, "Unknown field type.");
  665. return 0;
  666. }
  667. static upb_descriptortype_t ruby_to_descriptortype(VALUE type) {
  668. if (TYPE(type) != T_SYMBOL) {
  669. rb_raise(rb_eArgError, "Expected symbol for field type.");
  670. }
  671. #define CONVERT(upb, ruby) \
  672. if (SYM2ID(type) == rb_intern( # ruby )) { \
  673. return UPB_DESCRIPTOR_TYPE_ ## upb; \
  674. }
  675. CONVERT(FLOAT, float);
  676. CONVERT(DOUBLE, double);
  677. CONVERT(BOOL, bool);
  678. CONVERT(STRING, string);
  679. CONVERT(BYTES, bytes);
  680. CONVERT(MESSAGE, message);
  681. CONVERT(GROUP, group);
  682. CONVERT(ENUM, enum);
  683. CONVERT(INT32, int32);
  684. CONVERT(INT64, int64);
  685. CONVERT(UINT32, uint32);
  686. CONVERT(UINT64, uint64);
  687. CONVERT(SINT32, sint32);
  688. CONVERT(SINT64, sint64);
  689. CONVERT(FIXED32, fixed32);
  690. CONVERT(FIXED64, fixed64);
  691. CONVERT(SFIXED32, sfixed32);
  692. CONVERT(SFIXED64, sfixed64);
  693. #undef CONVERT
  694. rb_raise(rb_eArgError, "Unknown field type.");
  695. return 0;
  696. }
  697. static VALUE descriptortype_to_ruby(upb_descriptortype_t type) {
  698. switch (type) {
  699. #define CONVERT(upb, ruby) \
  700. case UPB_DESCRIPTOR_TYPE_ ## upb : return ID2SYM(rb_intern( # ruby ));
  701. CONVERT(FLOAT, float);
  702. CONVERT(DOUBLE, double);
  703. CONVERT(BOOL, bool);
  704. CONVERT(STRING, string);
  705. CONVERT(BYTES, bytes);
  706. CONVERT(MESSAGE, message);
  707. CONVERT(GROUP, group);
  708. CONVERT(ENUM, enum);
  709. CONVERT(INT32, int32);
  710. CONVERT(INT64, int64);
  711. CONVERT(UINT32, uint32);
  712. CONVERT(UINT64, uint64);
  713. CONVERT(SINT32, sint32);
  714. CONVERT(SINT64, sint64);
  715. CONVERT(FIXED32, fixed32);
  716. CONVERT(FIXED64, fixed64);
  717. CONVERT(SFIXED32, sfixed32);
  718. CONVERT(SFIXED64, sfixed64);
  719. #undef CONVERT
  720. }
  721. return Qnil;
  722. }
  723. /*
  724. * call-seq:
  725. * FieldDescriptor.type => type
  726. *
  727. * Returns this field's type, as a Ruby symbol, or nil if not yet set.
  728. *
  729. * Valid field types are:
  730. * :int32, :int64, :uint32, :uint64, :float, :double, :bool, :string,
  731. * :bytes, :message.
  732. */
  733. static VALUE FieldDescriptor__type(VALUE _self) {
  734. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  735. return descriptortype_to_ruby(upb_fielddef_descriptortype(self->fielddef));
  736. }
  737. /*
  738. * call-seq:
  739. * FieldDescriptor.default => default
  740. *
  741. * Returns this field's default, as a Ruby object, or nil if not yet set.
  742. */
  743. static VALUE FieldDescriptor_default(VALUE _self) {
  744. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  745. const upb_fielddef *f = self->fielddef;
  746. upb_msgval default_val = {0};
  747. if (upb_fielddef_issubmsg(f)) {
  748. return Qnil;
  749. } else if (!upb_fielddef_isseq(f)) {
  750. default_val = upb_fielddef_default(f);
  751. }
  752. return Convert_UpbToRuby(default_val, TypeInfo_get(self->fielddef), Qnil);
  753. }
  754. /*
  755. * call-seq:
  756. * FieldDescriptor.label => label
  757. *
  758. * Returns this field's label (i.e., plurality), as a Ruby symbol.
  759. *
  760. * Valid field labels are:
  761. * :optional, :repeated
  762. */
  763. static VALUE FieldDescriptor_label(VALUE _self) {
  764. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  765. switch (upb_fielddef_label(self->fielddef)) {
  766. #define CONVERT(upb, ruby) \
  767. case UPB_LABEL_ ## upb : return ID2SYM(rb_intern( # ruby ));
  768. CONVERT(OPTIONAL, optional);
  769. CONVERT(REQUIRED, required);
  770. CONVERT(REPEATED, repeated);
  771. #undef CONVERT
  772. }
  773. return Qnil;
  774. }
  775. /*
  776. * call-seq:
  777. * FieldDescriptor.number => number
  778. *
  779. * Returns the tag number for this field.
  780. */
  781. static VALUE FieldDescriptor_number(VALUE _self) {
  782. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  783. return INT2NUM(upb_fielddef_number(self->fielddef));
  784. }
  785. /*
  786. * call-seq:
  787. * FieldDescriptor.submsg_name => submsg_name
  788. *
  789. * Returns the name of the message or enum type corresponding to this field, if
  790. * it is a message or enum field (respectively), or nil otherwise. This type
  791. * name will be resolved within the context of the pool to which the containing
  792. * message type is added.
  793. */
  794. static VALUE FieldDescriptor_submsg_name(VALUE _self) {
  795. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  796. switch (upb_fielddef_type(self->fielddef)) {
  797. case UPB_TYPE_ENUM:
  798. return rb_str_new2(
  799. upb_enumdef_fullname(upb_fielddef_enumsubdef(self->fielddef)));
  800. case UPB_TYPE_MESSAGE:
  801. return rb_str_new2(
  802. upb_msgdef_fullname(upb_fielddef_msgsubdef(self->fielddef)));
  803. default:
  804. return Qnil;
  805. }
  806. }
  807. /*
  808. * call-seq:
  809. * FieldDescriptor.subtype => message_or_enum_descriptor
  810. *
  811. * Returns the message or enum descriptor corresponding to this field's type if
  812. * it is a message or enum field, respectively, or nil otherwise. Cannot be
  813. * called *until* the containing message type is added to a pool (and thus
  814. * resolved).
  815. */
  816. static VALUE FieldDescriptor_subtype(VALUE _self) {
  817. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  818. switch (upb_fielddef_type(self->fielddef)) {
  819. case UPB_TYPE_ENUM:
  820. return get_enumdef_obj(self->descriptor_pool,
  821. upb_fielddef_enumsubdef(self->fielddef));
  822. case UPB_TYPE_MESSAGE:
  823. return get_msgdef_obj(self->descriptor_pool,
  824. upb_fielddef_msgsubdef(self->fielddef));
  825. default:
  826. return Qnil;
  827. }
  828. }
  829. /*
  830. * call-seq:
  831. * FieldDescriptor.get(message) => value
  832. *
  833. * Returns the value set for this field on the given message. Raises an
  834. * exception if message is of the wrong type.
  835. */
  836. static VALUE FieldDescriptor_get(VALUE _self, VALUE msg_rb) {
  837. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  838. const upb_msgdef *m;
  839. Message_Get(msg_rb, &m);
  840. if (m != upb_fielddef_containingtype(self->fielddef)) {
  841. rb_raise(cTypeError, "get method called on wrong message type");
  842. }
  843. return Message_getfield(msg_rb, self->fielddef);
  844. }
  845. /*
  846. * call-seq:
  847. * FieldDescriptor.has?(message) => boolean
  848. *
  849. * Returns whether the value is set on the given message. Raises an
  850. * exception when calling for fields that do not have presence.
  851. */
  852. static VALUE FieldDescriptor_has(VALUE _self, VALUE msg_rb) {
  853. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  854. const upb_msgdef *m;
  855. const upb_msgdef *msg = Message_Get(msg_rb, &m);
  856. if (m != upb_fielddef_containingtype(self->fielddef)) {
  857. rb_raise(cTypeError, "has method called on wrong message type");
  858. } else if (!upb_fielddef_haspresence(self->fielddef)) {
  859. rb_raise(rb_eArgError, "does not track presence");
  860. }
  861. return upb_msg_has(msg, self->fielddef) ? Qtrue : Qfalse;
  862. }
  863. /*
  864. * call-seq:
  865. * FieldDescriptor.clear(message)
  866. *
  867. * Clears the field from the message if it's set.
  868. */
  869. static VALUE FieldDescriptor_clear(VALUE _self, VALUE msg_rb) {
  870. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  871. const upb_msgdef *m;
  872. upb_msgdef *msg = Message_GetMutable(msg_rb, &m);
  873. if (m != upb_fielddef_containingtype(self->fielddef)) {
  874. rb_raise(cTypeError, "has method called on wrong message type");
  875. }
  876. upb_msg_clearfield(msg, self->fielddef);
  877. return Qnil;
  878. }
  879. /*
  880. * call-seq:
  881. * FieldDescriptor.set(message, value)
  882. *
  883. * Sets the value corresponding to this field to the given value on the given
  884. * message. Raises an exception if message is of the wrong type. Performs the
  885. * ordinary type-checks for field setting.
  886. */
  887. static VALUE FieldDescriptor_set(VALUE _self, VALUE msg_rb, VALUE value) {
  888. FieldDescriptor* self = ruby_to_FieldDescriptor(_self);
  889. const upb_msgdef *m;
  890. upb_msgdef *msg = Message_GetMutable(msg_rb, &m);
  891. upb_arena *arena = Arena_get(Message_GetArena(msg_rb));
  892. upb_msgval msgval;
  893. if (m != upb_fielddef_containingtype(self->fielddef)) {
  894. rb_raise(cTypeError, "set method called on wrong message type");
  895. }
  896. msgval = Convert_RubyToUpb(value, upb_fielddef_name(self->fielddef),
  897. TypeInfo_get(self->fielddef), arena);
  898. upb_msg_set(msg, self->fielddef, msgval, arena);
  899. return Qnil;
  900. }
  901. static void FieldDescriptor_register(VALUE module) {
  902. VALUE klass = rb_define_class_under(
  903. module, "FieldDescriptor", rb_cObject);
  904. rb_define_alloc_func(klass, FieldDescriptor_alloc);
  905. rb_define_method(klass, "initialize", FieldDescriptor_initialize, 3);
  906. rb_define_method(klass, "name", FieldDescriptor_name, 0);
  907. rb_define_method(klass, "type", FieldDescriptor__type, 0);
  908. rb_define_method(klass, "default", FieldDescriptor_default, 0);
  909. rb_define_method(klass, "label", FieldDescriptor_label, 0);
  910. rb_define_method(klass, "number", FieldDescriptor_number, 0);
  911. rb_define_method(klass, "submsg_name", FieldDescriptor_submsg_name, 0);
  912. rb_define_method(klass, "subtype", FieldDescriptor_subtype, 0);
  913. rb_define_method(klass, "has?", FieldDescriptor_has, 1);
  914. rb_define_method(klass, "clear", FieldDescriptor_clear, 1);
  915. rb_define_method(klass, "get", FieldDescriptor_get, 1);
  916. rb_define_method(klass, "set", FieldDescriptor_set, 2);
  917. rb_gc_register_address(&cFieldDescriptor);
  918. cFieldDescriptor = klass;
  919. }
  920. // -----------------------------------------------------------------------------
  921. // OneofDescriptor.
  922. // -----------------------------------------------------------------------------
  923. typedef struct {
  924. const upb_oneofdef* oneofdef;
  925. VALUE descriptor_pool; // Owns the upb_oneofdef.
  926. } OneofDescriptor;
  927. static VALUE cOneofDescriptor = Qnil;
  928. static void OneofDescriptor_mark(void* _self) {
  929. OneofDescriptor* self = _self;
  930. rb_gc_mark(self->descriptor_pool);
  931. }
  932. static const rb_data_type_t OneofDescriptor_type = {
  933. "Google::Protobuf::OneofDescriptor",
  934. {OneofDescriptor_mark, RUBY_DEFAULT_FREE, NULL},
  935. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  936. };
  937. static OneofDescriptor* ruby_to_OneofDescriptor(VALUE val) {
  938. OneofDescriptor* ret;
  939. TypedData_Get_Struct(val, OneofDescriptor, &OneofDescriptor_type, ret);
  940. return ret;
  941. }
  942. /*
  943. * call-seq:
  944. * OneofDescriptor.new => oneof_descriptor
  945. *
  946. * Creates a new, empty, oneof descriptor. The oneof may only be modified prior
  947. * to being added to a message descriptor which is subsequently added to a pool.
  948. */
  949. static VALUE OneofDescriptor_alloc(VALUE klass) {
  950. OneofDescriptor* self = ALLOC(OneofDescriptor);
  951. VALUE ret = TypedData_Wrap_Struct(klass, &OneofDescriptor_type, self);
  952. self->oneofdef = NULL;
  953. self->descriptor_pool = Qnil;
  954. return ret;
  955. }
  956. /*
  957. * call-seq:
  958. * OneofDescriptor.new(c_only_cookie, pool, ptr) => OneofDescriptor
  959. *
  960. * Creates a descriptor wrapper object. May only be called from C.
  961. */
  962. static VALUE OneofDescriptor_initialize(VALUE _self, VALUE cookie,
  963. VALUE descriptor_pool, VALUE ptr) {
  964. OneofDescriptor* self = ruby_to_OneofDescriptor(_self);
  965. if (cookie != c_only_cookie) {
  966. rb_raise(rb_eRuntimeError,
  967. "Descriptor objects may not be created from Ruby.");
  968. }
  969. self->descriptor_pool = descriptor_pool;
  970. self->oneofdef = (const upb_oneofdef*)NUM2ULL(ptr);
  971. return Qnil;
  972. }
  973. /*
  974. * call-seq:
  975. * OneofDescriptor.name => name
  976. *
  977. * Returns the name of this oneof.
  978. */
  979. static VALUE OneofDescriptor_name(VALUE _self) {
  980. OneofDescriptor* self = ruby_to_OneofDescriptor(_self);
  981. return rb_str_maybe_null(upb_oneofdef_name(self->oneofdef));
  982. }
  983. /*
  984. * call-seq:
  985. * OneofDescriptor.each(&block) => nil
  986. *
  987. * Iterates through fields in this oneof, yielding to the block on each one.
  988. */
  989. static VALUE OneofDescriptor_each(VALUE _self) {
  990. OneofDescriptor* self = ruby_to_OneofDescriptor(_self);
  991. upb_oneof_iter it;
  992. for (upb_oneof_begin(&it, self->oneofdef);
  993. !upb_oneof_done(&it);
  994. upb_oneof_next(&it)) {
  995. const upb_fielddef* f = upb_oneof_iter_field(&it);
  996. VALUE obj = get_fielddef_obj(self->descriptor_pool, f);
  997. rb_yield(obj);
  998. }
  999. return Qnil;
  1000. }
  1001. static void OneofDescriptor_register(VALUE module) {
  1002. VALUE klass = rb_define_class_under(
  1003. module, "OneofDescriptor", rb_cObject);
  1004. rb_define_alloc_func(klass, OneofDescriptor_alloc);
  1005. rb_define_method(klass, "initialize", OneofDescriptor_initialize, 3);
  1006. rb_define_method(klass, "name", OneofDescriptor_name, 0);
  1007. rb_define_method(klass, "each", OneofDescriptor_each, 0);
  1008. rb_include_module(klass, rb_mEnumerable);
  1009. rb_gc_register_address(&cOneofDescriptor);
  1010. cOneofDescriptor = klass;
  1011. }
  1012. // -----------------------------------------------------------------------------
  1013. // EnumDescriptor.
  1014. // -----------------------------------------------------------------------------
  1015. typedef struct {
  1016. const upb_enumdef* enumdef;
  1017. VALUE module; // begins as nil
  1018. VALUE descriptor_pool; // Owns the upb_enumdef.
  1019. } EnumDescriptor;
  1020. static VALUE cEnumDescriptor = Qnil;
  1021. static void EnumDescriptor_mark(void* _self) {
  1022. EnumDescriptor* self = _self;
  1023. rb_gc_mark(self->module);
  1024. rb_gc_mark(self->descriptor_pool);
  1025. }
  1026. static const rb_data_type_t EnumDescriptor_type = {
  1027. "Google::Protobuf::EnumDescriptor",
  1028. {EnumDescriptor_mark, RUBY_DEFAULT_FREE, NULL},
  1029. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  1030. };
  1031. static EnumDescriptor* ruby_to_EnumDescriptor(VALUE val) {
  1032. EnumDescriptor* ret;
  1033. TypedData_Get_Struct(val, EnumDescriptor, &EnumDescriptor_type, ret);
  1034. return ret;
  1035. }
  1036. static VALUE EnumDescriptor_alloc(VALUE klass) {
  1037. EnumDescriptor* self = ALLOC(EnumDescriptor);
  1038. VALUE ret = TypedData_Wrap_Struct(klass, &EnumDescriptor_type, self);
  1039. self->enumdef = NULL;
  1040. self->module = Qnil;
  1041. self->descriptor_pool = Qnil;
  1042. return ret;
  1043. }
  1044. // Exposed to other modules in defs.h.
  1045. const upb_enumdef *EnumDescriptor_GetEnumDef(VALUE enum_desc_rb) {
  1046. EnumDescriptor *desc = ruby_to_EnumDescriptor(enum_desc_rb);
  1047. return desc->enumdef;
  1048. }
  1049. /*
  1050. * call-seq:
  1051. * EnumDescriptor.new(c_only_cookie, ptr) => EnumDescriptor
  1052. *
  1053. * Creates a descriptor wrapper object. May only be called from C.
  1054. */
  1055. static VALUE EnumDescriptor_initialize(VALUE _self, VALUE cookie,
  1056. VALUE descriptor_pool, VALUE ptr) {
  1057. EnumDescriptor* self = ruby_to_EnumDescriptor(_self);
  1058. if (cookie != c_only_cookie) {
  1059. rb_raise(rb_eRuntimeError,
  1060. "Descriptor objects may not be created from Ruby.");
  1061. }
  1062. self->descriptor_pool = descriptor_pool;
  1063. self->enumdef = (const upb_enumdef*)NUM2ULL(ptr);
  1064. return Qnil;
  1065. }
  1066. /*
  1067. * call-seq:
  1068. * EnumDescriptor.file_descriptor
  1069. *
  1070. * Returns the FileDescriptor object this enum belongs to.
  1071. */
  1072. static VALUE EnumDescriptor_file_descriptor(VALUE _self) {
  1073. EnumDescriptor* self = ruby_to_EnumDescriptor(_self);
  1074. return get_filedef_obj(self->descriptor_pool,
  1075. upb_enumdef_file(self->enumdef));
  1076. }
  1077. /*
  1078. * call-seq:
  1079. * EnumDescriptor.name => name
  1080. *
  1081. * Returns the name of this enum type.
  1082. */
  1083. static VALUE EnumDescriptor_name(VALUE _self) {
  1084. EnumDescriptor* self = ruby_to_EnumDescriptor(_self);
  1085. return rb_str_maybe_null(upb_enumdef_fullname(self->enumdef));
  1086. }
  1087. /*
  1088. * call-seq:
  1089. * EnumDescriptor.lookup_name(name) => value
  1090. *
  1091. * Returns the numeric value corresponding to the given key name (as a Ruby
  1092. * symbol), or nil if none.
  1093. */
  1094. static VALUE EnumDescriptor_lookup_name(VALUE _self, VALUE name) {
  1095. EnumDescriptor* self = ruby_to_EnumDescriptor(_self);
  1096. const char* name_str= rb_id2name(SYM2ID(name));
  1097. int32_t val = 0;
  1098. if (upb_enumdef_ntoiz(self->enumdef, name_str, &val)) {
  1099. return INT2NUM(val);
  1100. } else {
  1101. return Qnil;
  1102. }
  1103. }
  1104. /*
  1105. * call-seq:
  1106. * EnumDescriptor.lookup_value(name) => value
  1107. *
  1108. * Returns the key name (as a Ruby symbol) corresponding to the integer value,
  1109. * or nil if none.
  1110. */
  1111. static VALUE EnumDescriptor_lookup_value(VALUE _self, VALUE number) {
  1112. EnumDescriptor* self = ruby_to_EnumDescriptor(_self);
  1113. int32_t val = NUM2INT(number);
  1114. const char* name = upb_enumdef_iton(self->enumdef, val);
  1115. if (name != NULL) {
  1116. return ID2SYM(rb_intern(name));
  1117. } else {
  1118. return Qnil;
  1119. }
  1120. }
  1121. /*
  1122. * call-seq:
  1123. * EnumDescriptor.each(&block)
  1124. *
  1125. * Iterates over key => value mappings in this enum's definition, yielding to
  1126. * the block with (key, value) arguments for each one.
  1127. */
  1128. static VALUE EnumDescriptor_each(VALUE _self) {
  1129. EnumDescriptor* self = ruby_to_EnumDescriptor(_self);
  1130. upb_enum_iter it;
  1131. for (upb_enum_begin(&it, self->enumdef);
  1132. !upb_enum_done(&it);
  1133. upb_enum_next(&it)) {
  1134. VALUE key = ID2SYM(rb_intern(upb_enum_iter_name(&it)));
  1135. VALUE number = INT2NUM(upb_enum_iter_number(&it));
  1136. rb_yield_values(2, key, number);
  1137. }
  1138. return Qnil;
  1139. }
  1140. /*
  1141. * call-seq:
  1142. * EnumDescriptor.enummodule => module
  1143. *
  1144. * Returns the Ruby module corresponding to this enum type.
  1145. */
  1146. static VALUE EnumDescriptor_enummodule(VALUE _self) {
  1147. EnumDescriptor* self = ruby_to_EnumDescriptor(_self);
  1148. if (self->module == Qnil) {
  1149. self->module = build_module_from_enumdesc(_self);
  1150. }
  1151. return self->module;
  1152. }
  1153. static void EnumDescriptor_register(VALUE module) {
  1154. VALUE klass = rb_define_class_under(
  1155. module, "EnumDescriptor", rb_cObject);
  1156. rb_define_alloc_func(klass, EnumDescriptor_alloc);
  1157. rb_define_method(klass, "initialize", EnumDescriptor_initialize, 3);
  1158. rb_define_method(klass, "name", EnumDescriptor_name, 0);
  1159. rb_define_method(klass, "lookup_name", EnumDescriptor_lookup_name, 1);
  1160. rb_define_method(klass, "lookup_value", EnumDescriptor_lookup_value, 1);
  1161. rb_define_method(klass, "each", EnumDescriptor_each, 0);
  1162. rb_define_method(klass, "enummodule", EnumDescriptor_enummodule, 0);
  1163. rb_define_method(klass, "file_descriptor", EnumDescriptor_file_descriptor, 0);
  1164. rb_include_module(klass, rb_mEnumerable);
  1165. rb_gc_register_address(&cEnumDescriptor);
  1166. cEnumDescriptor = klass;
  1167. }
  1168. // -----------------------------------------------------------------------------
  1169. // FileBuilderContext.
  1170. // -----------------------------------------------------------------------------
  1171. typedef struct {
  1172. upb_arena *arena;
  1173. google_protobuf_FileDescriptorProto* file_proto;
  1174. VALUE descriptor_pool;
  1175. } FileBuilderContext;
  1176. static VALUE cFileBuilderContext = Qnil;
  1177. static void FileBuilderContext_mark(void* _self) {
  1178. FileBuilderContext* self = _self;
  1179. rb_gc_mark(self->descriptor_pool);
  1180. }
  1181. static void FileBuilderContext_free(void* _self) {
  1182. FileBuilderContext* self = _self;
  1183. upb_arena_free(self->arena);
  1184. xfree(self);
  1185. }
  1186. static const rb_data_type_t FileBuilderContext_type = {
  1187. "Google::Protobuf::Internal::FileBuilderContext",
  1188. {FileBuilderContext_mark, FileBuilderContext_free, NULL},
  1189. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  1190. };
  1191. static FileBuilderContext* ruby_to_FileBuilderContext(VALUE val) {
  1192. FileBuilderContext* ret;
  1193. TypedData_Get_Struct(val, FileBuilderContext, &FileBuilderContext_type, ret);
  1194. return ret;
  1195. }
  1196. static upb_strview FileBuilderContext_strdup2(VALUE _self, const char *str) {
  1197. FileBuilderContext* self = ruby_to_FileBuilderContext(_self);
  1198. upb_strview ret;
  1199. char *data;
  1200. ret.size = strlen(str);
  1201. data = upb_malloc(upb_arena_alloc(self->arena), ret.size + 1);
  1202. ret.data = data;
  1203. memcpy(data, str, ret.size);
  1204. /* Null-terminate required by rewrite_enum_defaults() above. */
  1205. data[ret.size] = '\0';
  1206. return ret;
  1207. }
  1208. static upb_strview FileBuilderContext_strdup(VALUE _self, VALUE rb_str) {
  1209. return FileBuilderContext_strdup2(_self, get_str(rb_str));
  1210. }
  1211. static upb_strview FileBuilderContext_strdup_sym(VALUE _self, VALUE rb_sym) {
  1212. Check_Type(rb_sym, T_SYMBOL);
  1213. return FileBuilderContext_strdup(_self, rb_id2str(SYM2ID(rb_sym)));
  1214. }
  1215. static VALUE FileBuilderContext_alloc(VALUE klass) {
  1216. FileBuilderContext* self = ALLOC(FileBuilderContext);
  1217. VALUE ret = TypedData_Wrap_Struct(klass, &FileBuilderContext_type, self);
  1218. self->arena = upb_arena_new();
  1219. self->file_proto = google_protobuf_FileDescriptorProto_new(self->arena);
  1220. self->descriptor_pool = Qnil;
  1221. return ret;
  1222. }
  1223. /*
  1224. * call-seq:
  1225. * FileBuilderContext.new(descriptor_pool) => context
  1226. *
  1227. * Create a new file builder context for the given file descriptor and
  1228. * builder context. This class is intended to serve as a DSL context to be used
  1229. * with #instance_eval.
  1230. */
  1231. static VALUE FileBuilderContext_initialize(VALUE _self, VALUE descriptor_pool,
  1232. VALUE name, VALUE options) {
  1233. FileBuilderContext* self = ruby_to_FileBuilderContext(_self);
  1234. self->descriptor_pool = descriptor_pool;
  1235. google_protobuf_FileDescriptorProto_set_name(
  1236. self->file_proto, FileBuilderContext_strdup(_self, name));
  1237. // Default syntax for Ruby is proto3.
  1238. google_protobuf_FileDescriptorProto_set_syntax(
  1239. self->file_proto,
  1240. FileBuilderContext_strdup(_self, rb_str_new2("proto3")));
  1241. if (options != Qnil) {
  1242. VALUE syntax;
  1243. Check_Type(options, T_HASH);
  1244. syntax = rb_hash_lookup2(options, ID2SYM(rb_intern("syntax")), Qnil);
  1245. if (syntax != Qnil) {
  1246. VALUE syntax_str;
  1247. Check_Type(syntax, T_SYMBOL);
  1248. syntax_str = rb_id2str(SYM2ID(syntax));
  1249. google_protobuf_FileDescriptorProto_set_syntax(
  1250. self->file_proto, FileBuilderContext_strdup(_self, syntax_str));
  1251. }
  1252. }
  1253. return Qnil;
  1254. }
  1255. static void MessageBuilderContext_add_synthetic_oneofs(VALUE _self);
  1256. /*
  1257. * call-seq:
  1258. * FileBuilderContext.add_message(name, &block)
  1259. *
  1260. * Creates a new, empty descriptor with the given name, and invokes the block in
  1261. * the context of a MessageBuilderContext on that descriptor. The block can then
  1262. * call, e.g., MessageBuilderContext#optional and MessageBuilderContext#repeated
  1263. * methods to define the message fields.
  1264. *
  1265. * This is the recommended, idiomatic way to build message definitions.
  1266. */
  1267. static VALUE FileBuilderContext_add_message(VALUE _self, VALUE name) {
  1268. VALUE args[2] = { _self, name };
  1269. VALUE ctx = rb_class_new_instance(2, args, cMessageBuilderContext);
  1270. VALUE block = rb_block_proc();
  1271. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1272. MessageBuilderContext_add_synthetic_oneofs(ctx);
  1273. return Qnil;
  1274. }
  1275. /* We have to do some relatively complicated logic here for backward
  1276. * compatibility.
  1277. *
  1278. * In descriptor.proto, messages are nested inside other messages if that is
  1279. * what the original .proto file looks like. For example, suppose we have this
  1280. * foo.proto:
  1281. *
  1282. * package foo;
  1283. * message Bar {
  1284. * message Baz {}
  1285. * }
  1286. *
  1287. * The descriptor for this must look like this:
  1288. *
  1289. * file {
  1290. * name: "test.proto"
  1291. * package: "foo"
  1292. * message_type {
  1293. * name: "Bar"
  1294. * nested_type {
  1295. * name: "Baz"
  1296. * }
  1297. * }
  1298. * }
  1299. *
  1300. * However, the Ruby generated code has always generated messages in a flat,
  1301. * non-nested way:
  1302. *
  1303. * Google::Protobuf::DescriptorPool.generated_pool.build do
  1304. * add_message "foo.Bar" do
  1305. * end
  1306. * add_message "foo.Bar.Baz" do
  1307. * end
  1308. * end
  1309. *
  1310. * Here we need to do a translation where we turn this generated code into the
  1311. * above descriptor. We need to infer that "foo" is the package name, and not
  1312. * a message itself.
  1313. *
  1314. * We delegate to Ruby to compute the transformation, for more concice and
  1315. * readable code than we can do in C */
  1316. static void rewrite_names(VALUE _file_builder,
  1317. google_protobuf_FileDescriptorProto* file_proto) {
  1318. FileBuilderContext* file_builder = ruby_to_FileBuilderContext(_file_builder);
  1319. upb_arena *arena = file_builder->arena;
  1320. // Build params (package, msg_names, enum_names).
  1321. VALUE package = Qnil;
  1322. VALUE msg_names = rb_ary_new();
  1323. VALUE enum_names = rb_ary_new();
  1324. size_t msg_count, enum_count, i;
  1325. VALUE new_package, nesting, msg_ents, enum_ents;
  1326. google_protobuf_DescriptorProto** msgs;
  1327. google_protobuf_EnumDescriptorProto** enums;
  1328. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  1329. upb_strview package_str =
  1330. google_protobuf_FileDescriptorProto_package(file_proto);
  1331. package = rb_str_new(package_str.data, package_str.size);
  1332. }
  1333. msgs = google_protobuf_FileDescriptorProto_mutable_message_type(file_proto,
  1334. &msg_count);
  1335. for (i = 0; i < msg_count; i++) {
  1336. upb_strview name = google_protobuf_DescriptorProto_name(msgs[i]);
  1337. rb_ary_push(msg_names, rb_str_new(name.data, name.size));
  1338. }
  1339. enums = google_protobuf_FileDescriptorProto_mutable_enum_type(file_proto,
  1340. &enum_count);
  1341. for (i = 0; i < enum_count; i++) {
  1342. upb_strview name = google_protobuf_EnumDescriptorProto_name(enums[i]);
  1343. rb_ary_push(enum_names, rb_str_new(name.data, name.size));
  1344. }
  1345. {
  1346. // Call Ruby code to calculate package name and nesting.
  1347. VALUE args[3] = { package, msg_names, enum_names };
  1348. VALUE internal = rb_eval_string("Google::Protobuf::Internal");
  1349. VALUE ret = rb_funcallv(internal, rb_intern("fixup_descriptor"), 3, args);
  1350. new_package = rb_ary_entry(ret, 0);
  1351. nesting = rb_ary_entry(ret, 1);
  1352. }
  1353. // Rewrite package and names.
  1354. if (new_package != Qnil) {
  1355. upb_strview new_package_str =
  1356. FileBuilderContext_strdup(_file_builder, new_package);
  1357. google_protobuf_FileDescriptorProto_set_package(file_proto,
  1358. new_package_str);
  1359. }
  1360. for (i = 0; i < msg_count; i++) {
  1361. upb_strview name = google_protobuf_DescriptorProto_name(msgs[i]);
  1362. remove_path(&name);
  1363. google_protobuf_DescriptorProto_set_name(msgs[i], name);
  1364. }
  1365. for (i = 0; i < enum_count; i++) {
  1366. upb_strview name = google_protobuf_EnumDescriptorProto_name(enums[i]);
  1367. remove_path(&name);
  1368. google_protobuf_EnumDescriptorProto_set_name(enums[i], name);
  1369. }
  1370. // Rewrite nesting.
  1371. msg_ents = rb_hash_aref(nesting, ID2SYM(rb_intern("msgs")));
  1372. enum_ents = rb_hash_aref(nesting, ID2SYM(rb_intern("enums")));
  1373. Check_Type(msg_ents, T_ARRAY);
  1374. Check_Type(enum_ents, T_ARRAY);
  1375. for (i = 0; i < (size_t)RARRAY_LEN(msg_ents); i++) {
  1376. VALUE msg_ent = rb_ary_entry(msg_ents, i);
  1377. VALUE pos = rb_hash_aref(msg_ent, ID2SYM(rb_intern("pos")));
  1378. msgs[i] = msgs[NUM2INT(pos)];
  1379. rewrite_nesting(msg_ent, msgs[i], msgs, enums, arena);
  1380. }
  1381. for (i = 0; i < (size_t)RARRAY_LEN(enum_ents); i++) {
  1382. VALUE enum_pos = rb_ary_entry(enum_ents, i);
  1383. enums[i] = enums[NUM2INT(enum_pos)];
  1384. }
  1385. google_protobuf_FileDescriptorProto_resize_message_type(
  1386. file_proto, RARRAY_LEN(msg_ents), arena);
  1387. google_protobuf_FileDescriptorProto_resize_enum_type(
  1388. file_proto, RARRAY_LEN(enum_ents), arena);
  1389. }
  1390. /*
  1391. * call-seq:
  1392. * FileBuilderContext.add_enum(name, &block)
  1393. *
  1394. * Creates a new, empty enum descriptor with the given name, and invokes the
  1395. * block in the context of an EnumBuilderContext on that descriptor. The block
  1396. * can then call EnumBuilderContext#add_value to define the enum values.
  1397. *
  1398. * This is the recommended, idiomatic way to build enum definitions.
  1399. */
  1400. static VALUE FileBuilderContext_add_enum(VALUE _self, VALUE name) {
  1401. VALUE args[2] = { _self, name };
  1402. VALUE ctx = rb_class_new_instance(2, args, cEnumBuilderContext);
  1403. VALUE block = rb_block_proc();
  1404. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1405. return Qnil;
  1406. }
  1407. static void FileBuilderContext_build(VALUE _self) {
  1408. FileBuilderContext* self = ruby_to_FileBuilderContext(_self);
  1409. DescriptorPool* pool = ruby_to_DescriptorPool(self->descriptor_pool);
  1410. upb_status status;
  1411. rewrite_enum_defaults(pool->symtab, self->file_proto);
  1412. rewrite_names(_self, self->file_proto);
  1413. upb_status_clear(&status);
  1414. if (!upb_symtab_addfile(pool->symtab, self->file_proto, &status)) {
  1415. rb_raise(cTypeError, "Unable to add defs to DescriptorPool: %s",
  1416. upb_status_errmsg(&status));
  1417. }
  1418. }
  1419. static void FileBuilderContext_register(VALUE module) {
  1420. VALUE klass = rb_define_class_under(module, "FileBuilderContext", rb_cObject);
  1421. rb_define_alloc_func(klass, FileBuilderContext_alloc);
  1422. rb_define_method(klass, "initialize", FileBuilderContext_initialize, 3);
  1423. rb_define_method(klass, "add_message", FileBuilderContext_add_message, 1);
  1424. rb_define_method(klass, "add_enum", FileBuilderContext_add_enum, 1);
  1425. rb_gc_register_address(&cFileBuilderContext);
  1426. cFileBuilderContext = klass;
  1427. }
  1428. // -----------------------------------------------------------------------------
  1429. // MessageBuilderContext.
  1430. // -----------------------------------------------------------------------------
  1431. typedef struct {
  1432. google_protobuf_DescriptorProto* msg_proto;
  1433. VALUE file_builder;
  1434. } MessageBuilderContext;
  1435. static VALUE cMessageBuilderContext = Qnil;
  1436. static void MessageBuilderContext_mark(void* _self) {
  1437. MessageBuilderContext* self = _self;
  1438. rb_gc_mark(self->file_builder);
  1439. }
  1440. static const rb_data_type_t MessageBuilderContext_type = {
  1441. "Google::Protobuf::Internal::MessageBuilderContext",
  1442. {MessageBuilderContext_mark, RUBY_DEFAULT_FREE, NULL},
  1443. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  1444. };
  1445. static MessageBuilderContext* ruby_to_MessageBuilderContext(VALUE val) {
  1446. MessageBuilderContext* ret;
  1447. TypedData_Get_Struct(val, MessageBuilderContext, &MessageBuilderContext_type,
  1448. ret);
  1449. return ret;
  1450. }
  1451. static VALUE MessageBuilderContext_alloc(VALUE klass) {
  1452. MessageBuilderContext* self = ALLOC(MessageBuilderContext);
  1453. VALUE ret = TypedData_Wrap_Struct(klass, &MessageBuilderContext_type, self);
  1454. self->file_builder = Qnil;
  1455. return ret;
  1456. }
  1457. /*
  1458. * call-seq:
  1459. * MessageBuilderContext.new(file_builder, name) => context
  1460. *
  1461. * Create a new message builder context around the given message descriptor and
  1462. * builder context. This class is intended to serve as a DSL context to be used
  1463. * with #instance_eval.
  1464. */
  1465. static VALUE MessageBuilderContext_initialize(VALUE _self, VALUE _file_builder,
  1466. VALUE name) {
  1467. MessageBuilderContext* self = ruby_to_MessageBuilderContext(_self);
  1468. FileBuilderContext* file_builder = ruby_to_FileBuilderContext(_file_builder);
  1469. google_protobuf_FileDescriptorProto* file_proto = file_builder->file_proto;
  1470. self->file_builder = _file_builder;
  1471. self->msg_proto = google_protobuf_FileDescriptorProto_add_message_type(
  1472. file_proto, file_builder->arena);
  1473. google_protobuf_DescriptorProto_set_name(
  1474. self->msg_proto, FileBuilderContext_strdup(_file_builder, name));
  1475. return Qnil;
  1476. }
  1477. static void msgdef_add_field(VALUE msgbuilder_rb, upb_label_t label, VALUE name,
  1478. VALUE type, VALUE number, VALUE type_class,
  1479. VALUE options, int oneof_index,
  1480. bool proto3_optional) {
  1481. MessageBuilderContext* self = ruby_to_MessageBuilderContext(msgbuilder_rb);
  1482. FileBuilderContext* file_context =
  1483. ruby_to_FileBuilderContext(self->file_builder);
  1484. google_protobuf_FieldDescriptorProto* field_proto;
  1485. VALUE name_str;
  1486. field_proto = google_protobuf_DescriptorProto_add_field(self->msg_proto,
  1487. file_context->arena);
  1488. Check_Type(name, T_SYMBOL);
  1489. name_str = rb_id2str(SYM2ID(name));
  1490. google_protobuf_FieldDescriptorProto_set_name(
  1491. field_proto, FileBuilderContext_strdup(self->file_builder, name_str));
  1492. google_protobuf_FieldDescriptorProto_set_number(field_proto, NUM2INT(number));
  1493. google_protobuf_FieldDescriptorProto_set_label(field_proto, (int)label);
  1494. google_protobuf_FieldDescriptorProto_set_type(
  1495. field_proto, (int)ruby_to_descriptortype(type));
  1496. if (proto3_optional) {
  1497. google_protobuf_FieldDescriptorProto_set_proto3_optional(field_proto, true);
  1498. }
  1499. if (type_class != Qnil) {
  1500. Check_Type(type_class, T_STRING);
  1501. // Make it an absolute type name by prepending a dot.
  1502. type_class = rb_str_append(rb_str_new2("."), type_class);
  1503. google_protobuf_FieldDescriptorProto_set_type_name(
  1504. field_proto, FileBuilderContext_strdup(self->file_builder, type_class));
  1505. }
  1506. if (options != Qnil) {
  1507. Check_Type(options, T_HASH);
  1508. if (rb_funcall(options, rb_intern("key?"), 1,
  1509. ID2SYM(rb_intern("default"))) == Qtrue) {
  1510. VALUE default_value =
  1511. rb_hash_lookup(options, ID2SYM(rb_intern("default")));
  1512. /* Call #to_s since all defaults are strings in the descriptor. */
  1513. default_value = rb_funcall(default_value, rb_intern("to_s"), 0);
  1514. google_protobuf_FieldDescriptorProto_set_default_value(
  1515. field_proto,
  1516. FileBuilderContext_strdup(self->file_builder, default_value));
  1517. }
  1518. }
  1519. if (oneof_index >= 0) {
  1520. google_protobuf_FieldDescriptorProto_set_oneof_index(field_proto,
  1521. oneof_index);
  1522. }
  1523. }
  1524. #if RUBY_API_VERSION_CODE >= 20700
  1525. static VALUE make_mapentry(VALUE _message_builder, VALUE types, int argc,
  1526. const VALUE* argv, VALUE blockarg) {
  1527. (void)blockarg;
  1528. #else
  1529. static VALUE make_mapentry(VALUE _message_builder, VALUE types, int argc,
  1530. VALUE* argv) {
  1531. #endif
  1532. MessageBuilderContext* message_builder =
  1533. ruby_to_MessageBuilderContext(_message_builder);
  1534. VALUE type_class = rb_ary_entry(types, 2);
  1535. FileBuilderContext* file_context =
  1536. ruby_to_FileBuilderContext(message_builder->file_builder);
  1537. google_protobuf_MessageOptions* options =
  1538. google_protobuf_DescriptorProto_mutable_options(
  1539. message_builder->msg_proto, file_context->arena);
  1540. google_protobuf_MessageOptions_set_map_entry(options, true);
  1541. // optional <type> key = 1;
  1542. rb_funcall(_message_builder, rb_intern("optional"), 3,
  1543. ID2SYM(rb_intern("key")), rb_ary_entry(types, 0), INT2NUM(1));
  1544. // optional <type> value = 2;
  1545. if (type_class == Qnil) {
  1546. rb_funcall(_message_builder, rb_intern("optional"), 3,
  1547. ID2SYM(rb_intern("value")), rb_ary_entry(types, 1), INT2NUM(2));
  1548. } else {
  1549. rb_funcall(_message_builder, rb_intern("optional"), 4,
  1550. ID2SYM(rb_intern("value")), rb_ary_entry(types, 1), INT2NUM(2),
  1551. type_class);
  1552. }
  1553. return Qnil;
  1554. }
  1555. /*
  1556. * call-seq:
  1557. * MessageBuilderContext.optional(name, type, number, type_class = nil,
  1558. * options = nil)
  1559. *
  1560. * Defines a new optional field on this message type with the given type, tag
  1561. * number, and type class (for message and enum fields). The type must be a Ruby
  1562. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1563. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1564. */
  1565. VALUE MessageBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
  1566. VALUE name, type, number;
  1567. VALUE type_class, options = Qnil;
  1568. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1569. // Allow passing (name, type, number, options) or
  1570. // (name, type, number, type_class, options)
  1571. if (argc == 4 && RB_TYPE_P(type_class, T_HASH)) {
  1572. options = type_class;
  1573. type_class = Qnil;
  1574. }
  1575. msgdef_add_field(_self, UPB_LABEL_OPTIONAL, name, type, number, type_class,
  1576. options, -1, false);
  1577. return Qnil;
  1578. }
  1579. /*
  1580. * call-seq:
  1581. * MessageBuilderContext.proto3_optional(name, type, number,
  1582. * type_class = nil, options = nil)
  1583. *
  1584. * Defines a true proto3 optional field (that tracks presence) on this message
  1585. * type with the given type, tag number, and type class (for message and enum
  1586. * fields). The type must be a Ruby symbol (as accepted by
  1587. * FieldDescriptor#type=) and the type_class must be a string, if present (as
  1588. * accepted by FieldDescriptor#submsg_name=).
  1589. */
  1590. static VALUE MessageBuilderContext_proto3_optional(int argc, VALUE* argv,
  1591. VALUE _self) {
  1592. VALUE name, type, number;
  1593. VALUE type_class, options = Qnil;
  1594. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1595. // Allow passing (name, type, number, options) or
  1596. // (name, type, number, type_class, options)
  1597. if (argc == 4 && RB_TYPE_P(type_class, T_HASH)) {
  1598. options = type_class;
  1599. type_class = Qnil;
  1600. }
  1601. msgdef_add_field(_self, UPB_LABEL_OPTIONAL, name, type, number, type_class,
  1602. options, -1, true);
  1603. return Qnil;
  1604. }
  1605. /*
  1606. * call-seq:
  1607. * MessageBuilderContext.required(name, type, number, type_class = nil,
  1608. * options = nil)
  1609. *
  1610. * Defines a new required field on this message type with the given type, tag
  1611. * number, and type class (for message and enum fields). The type must be a Ruby
  1612. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1613. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1614. *
  1615. * Proto3 does not have required fields, but this method exists for
  1616. * completeness. Any attempt to add a message type with required fields to a
  1617. * pool will currently result in an error.
  1618. */
  1619. static VALUE MessageBuilderContext_required(int argc, VALUE* argv,
  1620. VALUE _self) {
  1621. VALUE name, type, number;
  1622. VALUE type_class, options = Qnil;
  1623. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1624. // Allow passing (name, type, number, options) or
  1625. // (name, type, number, type_class, options)
  1626. if (argc == 4 && RB_TYPE_P(type_class, T_HASH)) {
  1627. options = type_class;
  1628. type_class = Qnil;
  1629. }
  1630. msgdef_add_field(_self, UPB_LABEL_REQUIRED, name, type, number, type_class,
  1631. options, -1, false);
  1632. return Qnil;
  1633. }
  1634. /*
  1635. * call-seq:
  1636. * MessageBuilderContext.repeated(name, type, number, type_class = nil)
  1637. *
  1638. * Defines a new repeated field on this message type with the given type, tag
  1639. * number, and type class (for message and enum fields). The type must be a Ruby
  1640. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1641. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1642. */
  1643. static VALUE MessageBuilderContext_repeated(int argc, VALUE* argv,
  1644. VALUE _self) {
  1645. VALUE name, type, number, type_class;
  1646. if (argc < 3) {
  1647. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  1648. }
  1649. name = argv[0];
  1650. type = argv[1];
  1651. number = argv[2];
  1652. type_class = (argc > 3) ? argv[3] : Qnil;
  1653. msgdef_add_field(_self, UPB_LABEL_REPEATED, name, type, number, type_class,
  1654. Qnil, -1, false);
  1655. return Qnil;
  1656. }
  1657. /*
  1658. * call-seq:
  1659. * MessageBuilderContext.map(name, key_type, value_type, number,
  1660. * value_type_class = nil)
  1661. *
  1662. * Defines a new map field on this message type with the given key and value
  1663. * types, tag number, and type class (for message and enum value types). The key
  1664. * type must be :int32/:uint32/:int64/:uint64, :bool, or :string. The value type
  1665. * type must be a Ruby symbol (as accepted by FieldDescriptor#type=) and the
  1666. * type_class must be a string, if present (as accepted by
  1667. * FieldDescriptor#submsg_name=).
  1668. */
  1669. static VALUE MessageBuilderContext_map(int argc, VALUE* argv, VALUE _self) {
  1670. MessageBuilderContext* self = ruby_to_MessageBuilderContext(_self);
  1671. VALUE name, key_type, value_type, number, type_class;
  1672. VALUE mapentry_desc_name;
  1673. FileBuilderContext* file_builder;
  1674. upb_strview msg_name;
  1675. if (argc < 4) {
  1676. rb_raise(rb_eArgError, "Expected at least 4 arguments.");
  1677. }
  1678. name = argv[0];
  1679. key_type = argv[1];
  1680. value_type = argv[2];
  1681. number = argv[3];
  1682. type_class = (argc > 4) ? argv[4] : Qnil;
  1683. // Validate the key type. We can't accept enums, messages, or floats/doubles
  1684. // as map keys. (We exclude these explicitly, and the field-descriptor setter
  1685. // below then ensures that the type is one of the remaining valid options.)
  1686. if (SYM2ID(key_type) == rb_intern("float") ||
  1687. SYM2ID(key_type) == rb_intern("double") ||
  1688. SYM2ID(key_type) == rb_intern("enum") ||
  1689. SYM2ID(key_type) == rb_intern("message")) {
  1690. rb_raise(rb_eArgError,
  1691. "Cannot add a map field with a float, double, enum, or message "
  1692. "type.");
  1693. }
  1694. file_builder = ruby_to_FileBuilderContext(self->file_builder);
  1695. // Create a new message descriptor for the map entry message, and create a
  1696. // repeated submessage field here with that type.
  1697. msg_name = google_protobuf_DescriptorProto_name(self->msg_proto);
  1698. mapentry_desc_name = rb_str_new(msg_name.data, msg_name.size);
  1699. mapentry_desc_name = rb_str_cat2(mapentry_desc_name, "_MapEntry_");
  1700. mapentry_desc_name =
  1701. rb_str_cat2(mapentry_desc_name, rb_id2name(SYM2ID(name)));
  1702. {
  1703. // message <msgname>_MapEntry_ { /* ... */ }
  1704. VALUE args[1] = {mapentry_desc_name};
  1705. VALUE types = rb_ary_new3(3, key_type, value_type, type_class);
  1706. rb_block_call(self->file_builder, rb_intern("add_message"), 1, args,
  1707. make_mapentry, types);
  1708. }
  1709. // If this file is in a package, we need to qualify the map entry type.
  1710. if (google_protobuf_FileDescriptorProto_has_package(file_builder->file_proto)) {
  1711. upb_strview package_view =
  1712. google_protobuf_FileDescriptorProto_package(file_builder->file_proto);
  1713. VALUE package = rb_str_new(package_view.data, package_view.size);
  1714. package = rb_str_cat2(package, ".");
  1715. mapentry_desc_name = rb_str_concat(package, mapentry_desc_name);
  1716. }
  1717. // repeated MapEntry <name> = <number>;
  1718. rb_funcall(_self, rb_intern("repeated"), 4, name,
  1719. ID2SYM(rb_intern("message")), number, mapentry_desc_name);
  1720. return Qnil;
  1721. }
  1722. /*
  1723. * call-seq:
  1724. * MessageBuilderContext.oneof(name, &block) => nil
  1725. *
  1726. * Creates a new OneofDescriptor with the given name, creates a
  1727. * OneofBuilderContext attached to that OneofDescriptor, evaluates the given
  1728. * block in the context of that OneofBuilderContext with #instance_eval, and
  1729. * then adds the oneof to the message.
  1730. *
  1731. * This is the recommended, idiomatic way to build oneof definitions.
  1732. */
  1733. static VALUE MessageBuilderContext_oneof(VALUE _self, VALUE name) {
  1734. MessageBuilderContext* self = ruby_to_MessageBuilderContext(_self);
  1735. size_t oneof_count;
  1736. FileBuilderContext* file_context =
  1737. ruby_to_FileBuilderContext(self->file_builder);
  1738. google_protobuf_OneofDescriptorProto* oneof_proto;
  1739. // Existing oneof_count becomes oneof_index.
  1740. google_protobuf_DescriptorProto_oneof_decl(self->msg_proto, &oneof_count);
  1741. // Create oneof_proto and set its name.
  1742. oneof_proto = google_protobuf_DescriptorProto_add_oneof_decl(
  1743. self->msg_proto, file_context->arena);
  1744. google_protobuf_OneofDescriptorProto_set_name(
  1745. oneof_proto, FileBuilderContext_strdup_sym(self->file_builder, name));
  1746. // Evaluate the block with the builder as argument.
  1747. {
  1748. VALUE args[2] = { INT2NUM(oneof_count), _self };
  1749. VALUE ctx = rb_class_new_instance(2, args, cOneofBuilderContext);
  1750. VALUE block = rb_block_proc();
  1751. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1752. }
  1753. return Qnil;
  1754. }
  1755. static void MessageBuilderContext_add_synthetic_oneofs(VALUE _self) {
  1756. MessageBuilderContext* self = ruby_to_MessageBuilderContext(_self);
  1757. FileBuilderContext* file_context =
  1758. ruby_to_FileBuilderContext(self->file_builder);
  1759. size_t field_count, oneof_count;
  1760. google_protobuf_FieldDescriptorProto** fields =
  1761. google_protobuf_DescriptorProto_mutable_field(self->msg_proto, &field_count);
  1762. const google_protobuf_OneofDescriptorProto*const* oneofs =
  1763. google_protobuf_DescriptorProto_oneof_decl(self->msg_proto, &oneof_count);
  1764. VALUE names = rb_hash_new();
  1765. VALUE underscore = rb_str_new2("_");
  1766. size_t i;
  1767. // We have to build a set of all names, to ensure that synthetic oneofs are
  1768. // not creating conflicts.
  1769. for (i = 0; i < field_count; i++) {
  1770. upb_strview name = google_protobuf_FieldDescriptorProto_name(fields[i]);
  1771. rb_hash_aset(names, rb_str_new(name.data, name.size), Qtrue);
  1772. }
  1773. for (i = 0; i < oneof_count; i++) {
  1774. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneofs[i]);
  1775. rb_hash_aset(names, rb_str_new(name.data, name.size), Qtrue);
  1776. }
  1777. for (i = 0; i < field_count; i++) {
  1778. google_protobuf_OneofDescriptorProto* oneof_proto;
  1779. VALUE oneof_name;
  1780. upb_strview field_name;
  1781. if (!google_protobuf_FieldDescriptorProto_proto3_optional(fields[i])) {
  1782. continue;
  1783. }
  1784. // Prepend '_' until we are no longer conflicting.
  1785. field_name = google_protobuf_FieldDescriptorProto_name(fields[i]);
  1786. oneof_name = rb_str_new(field_name.data, field_name.size);
  1787. while (rb_hash_lookup(names, oneof_name) != Qnil) {
  1788. oneof_name = rb_str_plus(underscore, oneof_name);
  1789. }
  1790. rb_hash_aset(names, oneof_name, Qtrue);
  1791. google_protobuf_FieldDescriptorProto_set_oneof_index(fields[i],
  1792. oneof_count++);
  1793. oneof_proto = google_protobuf_DescriptorProto_add_oneof_decl(
  1794. self->msg_proto, file_context->arena);
  1795. google_protobuf_OneofDescriptorProto_set_name(
  1796. oneof_proto, FileBuilderContext_strdup(self->file_builder, oneof_name));
  1797. }
  1798. }
  1799. static void MessageBuilderContext_register(VALUE module) {
  1800. VALUE klass = rb_define_class_under(
  1801. module, "MessageBuilderContext", rb_cObject);
  1802. rb_define_alloc_func(klass, MessageBuilderContext_alloc);
  1803. rb_define_method(klass, "initialize",
  1804. MessageBuilderContext_initialize, 2);
  1805. rb_define_method(klass, "optional", MessageBuilderContext_optional, -1);
  1806. rb_define_method(klass, "proto3_optional", MessageBuilderContext_proto3_optional, -1);
  1807. rb_define_method(klass, "required", MessageBuilderContext_required, -1);
  1808. rb_define_method(klass, "repeated", MessageBuilderContext_repeated, -1);
  1809. rb_define_method(klass, "map", MessageBuilderContext_map, -1);
  1810. rb_define_method(klass, "oneof", MessageBuilderContext_oneof, 1);
  1811. rb_gc_register_address(&cMessageBuilderContext);
  1812. cMessageBuilderContext = klass;
  1813. }
  1814. // -----------------------------------------------------------------------------
  1815. // OneofBuilderContext.
  1816. // -----------------------------------------------------------------------------
  1817. typedef struct {
  1818. int oneof_index;
  1819. VALUE message_builder;
  1820. } OneofBuilderContext;
  1821. static VALUE cOneofBuilderContext = Qnil;
  1822. void OneofBuilderContext_mark(void* _self) {
  1823. OneofBuilderContext* self = _self;
  1824. rb_gc_mark(self->message_builder);
  1825. }
  1826. static const rb_data_type_t OneofBuilderContext_type = {
  1827. "Google::Protobuf::Internal::OneofBuilderContext",
  1828. {OneofBuilderContext_mark, RUBY_DEFAULT_FREE, NULL},
  1829. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  1830. };
  1831. static OneofBuilderContext* ruby_to_OneofBuilderContext(VALUE val) {
  1832. OneofBuilderContext* ret;
  1833. TypedData_Get_Struct(val, OneofBuilderContext, &OneofBuilderContext_type,
  1834. ret);
  1835. return ret;
  1836. }
  1837. static VALUE OneofBuilderContext_alloc(VALUE klass) {
  1838. OneofBuilderContext* self = ALLOC(OneofBuilderContext);
  1839. VALUE ret = TypedData_Wrap_Struct(klass, &OneofBuilderContext_type, self);
  1840. self->oneof_index = 0;
  1841. self->message_builder = Qnil;
  1842. return ret;
  1843. }
  1844. /*
  1845. * call-seq:
  1846. * OneofBuilderContext.new(oneof_index, message_builder) => context
  1847. *
  1848. * Create a new oneof builder context around the given oneof descriptor and
  1849. * builder context. This class is intended to serve as a DSL context to be used
  1850. * with #instance_eval.
  1851. */
  1852. static VALUE OneofBuilderContext_initialize(VALUE _self, VALUE oneof_index,
  1853. VALUE message_builder) {
  1854. OneofBuilderContext* self = ruby_to_OneofBuilderContext(_self);
  1855. self->oneof_index = NUM2INT(oneof_index);
  1856. self->message_builder = message_builder;
  1857. return Qnil;
  1858. }
  1859. /*
  1860. * call-seq:
  1861. * OneofBuilderContext.optional(name, type, number, type_class = nil,
  1862. * default_value = nil)
  1863. *
  1864. * Defines a new optional field in this oneof with the given type, tag number,
  1865. * and type class (for message and enum fields). The type must be a Ruby symbol
  1866. * (as accepted by FieldDescriptor#type=) and the type_class must be a string,
  1867. * if present (as accepted by FieldDescriptor#submsg_name=).
  1868. */
  1869. static VALUE OneofBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
  1870. OneofBuilderContext* self = ruby_to_OneofBuilderContext(_self);
  1871. VALUE name, type, number;
  1872. VALUE type_class, options = Qnil;
  1873. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1874. msgdef_add_field(self->message_builder, UPB_LABEL_OPTIONAL, name, type,
  1875. number, type_class, options, self->oneof_index, false);
  1876. return Qnil;
  1877. }
  1878. static void OneofBuilderContext_register(VALUE module) {
  1879. VALUE klass = rb_define_class_under(
  1880. module, "OneofBuilderContext", rb_cObject);
  1881. rb_define_alloc_func(klass, OneofBuilderContext_alloc);
  1882. rb_define_method(klass, "initialize",
  1883. OneofBuilderContext_initialize, 2);
  1884. rb_define_method(klass, "optional", OneofBuilderContext_optional, -1);
  1885. rb_gc_register_address(&cOneofBuilderContext);
  1886. cOneofBuilderContext = klass;
  1887. }
  1888. // -----------------------------------------------------------------------------
  1889. // EnumBuilderContext.
  1890. // -----------------------------------------------------------------------------
  1891. typedef struct {
  1892. google_protobuf_EnumDescriptorProto* enum_proto;
  1893. VALUE file_builder;
  1894. } EnumBuilderContext;
  1895. static VALUE cEnumBuilderContext = Qnil;
  1896. void EnumBuilderContext_mark(void* _self) {
  1897. EnumBuilderContext* self = _self;
  1898. rb_gc_mark(self->file_builder);
  1899. }
  1900. static const rb_data_type_t EnumBuilderContext_type = {
  1901. "Google::Protobuf::Internal::EnumBuilderContext",
  1902. {EnumBuilderContext_mark, RUBY_DEFAULT_FREE, NULL},
  1903. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  1904. };
  1905. static EnumBuilderContext* ruby_to_EnumBuilderContext(VALUE val) {
  1906. EnumBuilderContext* ret;
  1907. TypedData_Get_Struct(val, EnumBuilderContext, &EnumBuilderContext_type, ret);
  1908. return ret;
  1909. }
  1910. static VALUE EnumBuilderContext_alloc(VALUE klass) {
  1911. EnumBuilderContext* self = ALLOC(EnumBuilderContext);
  1912. VALUE ret = TypedData_Wrap_Struct(klass, &EnumBuilderContext_type, self);
  1913. self->enum_proto = NULL;
  1914. self->file_builder = Qnil;
  1915. return ret;
  1916. }
  1917. /*
  1918. * call-seq:
  1919. * EnumBuilderContext.new(file_builder) => context
  1920. *
  1921. * Create a new builder context around the given enum descriptor. This class is
  1922. * intended to serve as a DSL context to be used with #instance_eval.
  1923. */
  1924. static VALUE EnumBuilderContext_initialize(VALUE _self, VALUE _file_builder,
  1925. VALUE name) {
  1926. EnumBuilderContext* self = ruby_to_EnumBuilderContext(_self);
  1927. FileBuilderContext* file_builder = ruby_to_FileBuilderContext(_file_builder);
  1928. google_protobuf_FileDescriptorProto* file_proto = file_builder->file_proto;
  1929. self->file_builder = _file_builder;
  1930. self->enum_proto = google_protobuf_FileDescriptorProto_add_enum_type(
  1931. file_proto, file_builder->arena);
  1932. google_protobuf_EnumDescriptorProto_set_name(
  1933. self->enum_proto, FileBuilderContext_strdup(_file_builder, name));
  1934. return Qnil;
  1935. }
  1936. /*
  1937. * call-seq:
  1938. * EnumBuilder.add_value(name, number)
  1939. *
  1940. * Adds the given name => number mapping to the enum type. Name must be a Ruby
  1941. * symbol.
  1942. */
  1943. static VALUE EnumBuilderContext_value(VALUE _self, VALUE name, VALUE number) {
  1944. EnumBuilderContext* self = ruby_to_EnumBuilderContext(_self);
  1945. FileBuilderContext* file_builder =
  1946. ruby_to_FileBuilderContext(self->file_builder);
  1947. google_protobuf_EnumValueDescriptorProto* enum_value;
  1948. enum_value = google_protobuf_EnumDescriptorProto_add_value(
  1949. self->enum_proto, file_builder->arena);
  1950. google_protobuf_EnumValueDescriptorProto_set_name(
  1951. enum_value, FileBuilderContext_strdup_sym(self->file_builder, name));
  1952. google_protobuf_EnumValueDescriptorProto_set_number(enum_value,
  1953. NUM2INT(number));
  1954. return Qnil;
  1955. }
  1956. static void EnumBuilderContext_register(VALUE module) {
  1957. VALUE klass = rb_define_class_under(
  1958. module, "EnumBuilderContext", rb_cObject);
  1959. rb_define_alloc_func(klass, EnumBuilderContext_alloc);
  1960. rb_define_method(klass, "initialize", EnumBuilderContext_initialize, 2);
  1961. rb_define_method(klass, "value", EnumBuilderContext_value, 2);
  1962. rb_gc_register_address(&cEnumBuilderContext);
  1963. cEnumBuilderContext = klass;
  1964. }
  1965. // -----------------------------------------------------------------------------
  1966. // Builder.
  1967. // -----------------------------------------------------------------------------
  1968. typedef struct {
  1969. VALUE descriptor_pool;
  1970. VALUE default_file_builder;
  1971. } Builder;
  1972. static VALUE cBuilder = Qnil;
  1973. static void Builder_mark(void* _self) {
  1974. Builder* self = _self;
  1975. rb_gc_mark(self->descriptor_pool);
  1976. rb_gc_mark(self->default_file_builder);
  1977. }
  1978. static const rb_data_type_t Builder_type = {
  1979. "Google::Protobuf::Internal::Builder",
  1980. {Builder_mark, RUBY_DEFAULT_FREE, NULL},
  1981. .flags = RUBY_TYPED_FREE_IMMEDIATELY,
  1982. };
  1983. static Builder* ruby_to_Builder(VALUE val) {
  1984. Builder* ret;
  1985. TypedData_Get_Struct(val, Builder, &Builder_type, ret);
  1986. return ret;
  1987. }
  1988. static VALUE Builder_alloc(VALUE klass) {
  1989. Builder* self = ALLOC(Builder);
  1990. VALUE ret = TypedData_Wrap_Struct(klass, &Builder_type, self);
  1991. self->descriptor_pool = Qnil;
  1992. self->default_file_builder = Qnil;
  1993. return ret;
  1994. }
  1995. /*
  1996. * call-seq:
  1997. * Builder.new(descriptor_pool) => builder
  1998. *
  1999. * Creates a new Builder. A Builder can accumulate a set of new message and enum
  2000. * descriptors and atomically register them into a pool in a way that allows for
  2001. * (co)recursive type references.
  2002. */
  2003. static VALUE Builder_initialize(VALUE _self, VALUE pool) {
  2004. Builder* self = ruby_to_Builder(_self);
  2005. self->descriptor_pool = pool;
  2006. self->default_file_builder = Qnil; // Created lazily if needed.
  2007. return Qnil;
  2008. }
  2009. /*
  2010. * call-seq:
  2011. * Builder.add_file(name, options = nil, &block)
  2012. *
  2013. * Creates a new, file descriptor with the given name and options and invokes
  2014. * the block in the context of a FileBuilderContext on that descriptor. The
  2015. * block can then call FileBuilderContext#add_message or
  2016. * FileBuilderContext#add_enum to define new messages or enums, respectively.
  2017. *
  2018. * This is the recommended, idiomatic way to build file descriptors.
  2019. */
  2020. static VALUE Builder_add_file(int argc, VALUE* argv, VALUE _self) {
  2021. Builder* self = ruby_to_Builder(_self);
  2022. VALUE name, options;
  2023. VALUE ctx;
  2024. VALUE block;
  2025. rb_scan_args(argc, argv, "11", &name, &options);
  2026. {
  2027. VALUE args[3] = { self->descriptor_pool, name, options };
  2028. ctx = rb_class_new_instance(3, args, cFileBuilderContext);
  2029. }
  2030. block = rb_block_proc();
  2031. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  2032. FileBuilderContext_build(ctx);
  2033. return Qnil;
  2034. }
  2035. static VALUE Builder_get_default_file(VALUE _self) {
  2036. Builder* self = ruby_to_Builder(_self);
  2037. /* Lazily create only if legacy builder-level methods are called. */
  2038. if (self->default_file_builder == Qnil) {
  2039. VALUE name = rb_str_new2("ruby_default_file.proto");
  2040. VALUE args [3] = { self->descriptor_pool, name, rb_hash_new() };
  2041. self->default_file_builder =
  2042. rb_class_new_instance(3, args, cFileBuilderContext);
  2043. }
  2044. return self->default_file_builder;
  2045. }
  2046. /*
  2047. * call-seq:
  2048. * Builder.add_message(name, &block)
  2049. *
  2050. * Old and deprecated way to create a new descriptor.
  2051. * See FileBuilderContext.add_message for the recommended way.
  2052. *
  2053. * Exists for backwards compatibility to allow building descriptor pool for
  2054. * files generated by protoc which don't add messages within "add_file" block.
  2055. * Descriptors created this way get assigned to a default empty FileDescriptor.
  2056. */
  2057. static VALUE Builder_add_message(VALUE _self, VALUE name) {
  2058. VALUE file_builder = Builder_get_default_file(_self);
  2059. rb_funcall_with_block(file_builder, rb_intern("add_message"), 1, &name,
  2060. rb_block_proc());
  2061. return Qnil;
  2062. }
  2063. /*
  2064. * call-seq:
  2065. * Builder.add_enum(name, &block)
  2066. *
  2067. * Old and deprecated way to create a new enum descriptor.
  2068. * See FileBuilderContext.add_enum for the recommended way.
  2069. *
  2070. * Exists for backwards compatibility to allow building descriptor pool for
  2071. * files generated by protoc which don't add enums within "add_file" block.
  2072. * Enum descriptors created this way get assigned to a default empty
  2073. * FileDescriptor.
  2074. */
  2075. static VALUE Builder_add_enum(VALUE _self, VALUE name) {
  2076. VALUE file_builder = Builder_get_default_file(_self);
  2077. rb_funcall_with_block(file_builder, rb_intern("add_enum"), 1, &name,
  2078. rb_block_proc());
  2079. return Qnil;
  2080. }
  2081. /* This method is hidden from Ruby, and only called directly from
  2082. * DescriptorPool_build(). */
  2083. static VALUE Builder_build(VALUE _self) {
  2084. Builder* self = ruby_to_Builder(_self);
  2085. if (self->default_file_builder != Qnil) {
  2086. FileBuilderContext_build(self->default_file_builder);
  2087. self->default_file_builder = Qnil;
  2088. }
  2089. return Qnil;
  2090. }
  2091. static void Builder_register(VALUE module) {
  2092. VALUE klass = rb_define_class_under(module, "Builder", rb_cObject);
  2093. rb_define_alloc_func(klass, Builder_alloc);
  2094. rb_define_method(klass, "initialize", Builder_initialize, 1);
  2095. rb_define_method(klass, "add_file", Builder_add_file, -1);
  2096. rb_define_method(klass, "add_message", Builder_add_message, 1);
  2097. rb_define_method(klass, "add_enum", Builder_add_enum, 1);
  2098. rb_gc_register_address(&cBuilder);
  2099. cBuilder = klass;
  2100. }
  2101. static VALUE get_def_obj(VALUE _descriptor_pool, const void* ptr, VALUE klass) {
  2102. DescriptorPool* descriptor_pool = ruby_to_DescriptorPool(_descriptor_pool);
  2103. VALUE key = ULL2NUM((intptr_t)ptr);
  2104. VALUE def;
  2105. def = rb_hash_aref(descriptor_pool->def_to_descriptor, key);
  2106. if (ptr == NULL) {
  2107. return Qnil;
  2108. }
  2109. if (def == Qnil) {
  2110. // Lazily create wrapper object.
  2111. VALUE args[3] = { c_only_cookie, _descriptor_pool, key };
  2112. def = rb_class_new_instance(3, args, klass);
  2113. rb_hash_aset(descriptor_pool->def_to_descriptor, key, def);
  2114. }
  2115. return def;
  2116. }
  2117. static VALUE get_msgdef_obj(VALUE descriptor_pool, const upb_msgdef* def) {
  2118. return get_def_obj(descriptor_pool, def, cDescriptor);
  2119. }
  2120. static VALUE get_enumdef_obj(VALUE descriptor_pool, const upb_enumdef* def) {
  2121. return get_def_obj(descriptor_pool, def, cEnumDescriptor);
  2122. }
  2123. static VALUE get_fielddef_obj(VALUE descriptor_pool, const upb_fielddef* def) {
  2124. return get_def_obj(descriptor_pool, def, cFieldDescriptor);
  2125. }
  2126. static VALUE get_filedef_obj(VALUE descriptor_pool, const upb_filedef* def) {
  2127. return get_def_obj(descriptor_pool, def, cFileDescriptor);
  2128. }
  2129. static VALUE get_oneofdef_obj(VALUE descriptor_pool, const upb_oneofdef* def) {
  2130. return get_def_obj(descriptor_pool, def, cOneofDescriptor);
  2131. }
  2132. // -----------------------------------------------------------------------------
  2133. // Shared functions
  2134. // -----------------------------------------------------------------------------
  2135. // Functions exposed to other modules in defs.h.
  2136. VALUE Descriptor_DefToClass(const upb_msgdef *m) {
  2137. const upb_symtab *symtab = upb_filedef_symtab(upb_msgdef_file(m));
  2138. VALUE pool = ObjectCache_Get(symtab);
  2139. PBRUBY_ASSERT(pool != Qnil);
  2140. VALUE desc_rb = get_msgdef_obj(pool, m);
  2141. const Descriptor* desc = ruby_to_Descriptor(desc_rb);
  2142. return desc->klass;
  2143. }
  2144. const upb_msgdef *Descriptor_GetMsgDef(VALUE desc_rb) {
  2145. const Descriptor* desc = ruby_to_Descriptor(desc_rb);
  2146. return desc->msgdef;
  2147. }
  2148. VALUE TypeInfo_InitArg(int argc, VALUE *argv, int skip_arg) {
  2149. if (argc > skip_arg) {
  2150. if (argc > 1 + skip_arg) {
  2151. rb_raise(rb_eArgError, "Expected a maximum of %d arguments.", skip_arg + 1);
  2152. }
  2153. return argv[skip_arg];
  2154. } else {
  2155. return Qnil;
  2156. }
  2157. }
  2158. TypeInfo TypeInfo_FromClass(int argc, VALUE* argv, int skip_arg,
  2159. VALUE* type_class, VALUE* init_arg) {
  2160. TypeInfo ret = {ruby_to_fieldtype(argv[skip_arg])};
  2161. if (ret.type == UPB_TYPE_MESSAGE || ret.type == UPB_TYPE_ENUM) {
  2162. *init_arg = TypeInfo_InitArg(argc, argv, skip_arg + 2);
  2163. if (argc < 2 + skip_arg) {
  2164. rb_raise(rb_eArgError, "Expected at least %d arguments for message/enum.",
  2165. 2 + skip_arg);
  2166. }
  2167. VALUE klass = argv[1 + skip_arg];
  2168. VALUE desc = MessageOrEnum_GetDescriptor(klass);
  2169. *type_class = klass;
  2170. if (desc == Qnil) {
  2171. rb_raise(rb_eArgError,
  2172. "Type class has no descriptor. Please pass a "
  2173. "class or enum as returned by the DescriptorPool.");
  2174. }
  2175. if (ret.type == UPB_TYPE_MESSAGE) {
  2176. ret.def.msgdef = ruby_to_Descriptor(desc)->msgdef;
  2177. Message_CheckClass(klass);
  2178. } else {
  2179. PBRUBY_ASSERT(ret.type == UPB_TYPE_ENUM);
  2180. ret.def.enumdef = ruby_to_EnumDescriptor(desc)->enumdef;
  2181. }
  2182. } else {
  2183. *init_arg = TypeInfo_InitArg(argc, argv, skip_arg + 1);
  2184. }
  2185. return ret;
  2186. }
  2187. void Defs_register(VALUE module) {
  2188. DescriptorPool_register(module);
  2189. Descriptor_register(module);
  2190. FileDescriptor_register(module);
  2191. FieldDescriptor_register(module);
  2192. OneofDescriptor_register(module);
  2193. EnumDescriptor_register(module);
  2194. FileBuilderContext_register(module);
  2195. MessageBuilderContext_register(module);
  2196. OneofBuilderContext_register(module);
  2197. EnumBuilderContext_register(module);
  2198. Builder_register(module);
  2199. rb_gc_register_address(&c_only_cookie);
  2200. c_only_cookie = rb_class_new_instance(0, NULL, rb_cObject);
  2201. }