defs.c 73 KB

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