defs.c 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366
  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 for fields that do not have presence.
  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, "proto3_optional", MessageBuilderContext_proto3_optional, -1);
  1264. rb_define_method(klass, "required", MessageBuilderContext_required, -1);
  1265. rb_define_method(klass, "repeated", MessageBuilderContext_repeated, -1);
  1266. rb_define_method(klass, "map", MessageBuilderContext_map, -1);
  1267. rb_define_method(klass, "oneof", MessageBuilderContext_oneof, 1);
  1268. rb_gc_register_address(&cMessageBuilderContext);
  1269. cMessageBuilderContext = klass;
  1270. }
  1271. /*
  1272. * call-seq:
  1273. * MessageBuilderContext.new(file_builder, name) => context
  1274. *
  1275. * Create a new message builder context around the given message descriptor and
  1276. * builder context. This class is intended to serve as a DSL context to be used
  1277. * with #instance_eval.
  1278. */
  1279. VALUE MessageBuilderContext_initialize(VALUE _self,
  1280. VALUE _file_builder,
  1281. VALUE name) {
  1282. DEFINE_SELF(MessageBuilderContext, self, _self);
  1283. FileBuilderContext* file_builder = ruby_to_FileBuilderContext(_file_builder);
  1284. google_protobuf_FileDescriptorProto* file_proto = file_builder->file_proto;
  1285. self->file_builder = _file_builder;
  1286. self->msg_proto = google_protobuf_FileDescriptorProto_add_message_type(
  1287. file_proto, file_builder->arena);
  1288. google_protobuf_DescriptorProto_set_name(
  1289. self->msg_proto, FileBuilderContext_strdup(_file_builder, name));
  1290. return Qnil;
  1291. }
  1292. static void msgdef_add_field(VALUE msgbuilder_rb, upb_label_t label, VALUE name,
  1293. VALUE type, VALUE number, VALUE type_class,
  1294. VALUE options, int oneof_index,
  1295. bool proto3_optional) {
  1296. DEFINE_SELF(MessageBuilderContext, self, msgbuilder_rb);
  1297. FileBuilderContext* file_context =
  1298. ruby_to_FileBuilderContext(self->file_builder);
  1299. google_protobuf_FieldDescriptorProto* field_proto;
  1300. VALUE name_str;
  1301. field_proto = google_protobuf_DescriptorProto_add_field(self->msg_proto,
  1302. file_context->arena);
  1303. Check_Type(name, T_SYMBOL);
  1304. name_str = rb_id2str(SYM2ID(name));
  1305. google_protobuf_FieldDescriptorProto_set_name(
  1306. field_proto, FileBuilderContext_strdup(self->file_builder, name_str));
  1307. google_protobuf_FieldDescriptorProto_set_number(field_proto, NUM2INT(number));
  1308. google_protobuf_FieldDescriptorProto_set_label(field_proto, (int)label);
  1309. google_protobuf_FieldDescriptorProto_set_type(
  1310. field_proto, (int)ruby_to_descriptortype(type));
  1311. if (proto3_optional) {
  1312. google_protobuf_FieldDescriptorProto_set_proto3_optional(field_proto, true);
  1313. }
  1314. if (type_class != Qnil) {
  1315. Check_Type(type_class, T_STRING);
  1316. // Make it an absolute type name by prepending a dot.
  1317. type_class = rb_str_append(rb_str_new2("."), type_class);
  1318. google_protobuf_FieldDescriptorProto_set_type_name(
  1319. field_proto, FileBuilderContext_strdup(self->file_builder, type_class));
  1320. }
  1321. if (options != Qnil) {
  1322. Check_Type(options, T_HASH);
  1323. if (rb_funcall(options, rb_intern("key?"), 1,
  1324. ID2SYM(rb_intern("default"))) == Qtrue) {
  1325. VALUE default_value =
  1326. rb_hash_lookup(options, ID2SYM(rb_intern("default")));
  1327. /* Call #to_s since all defaults are strings in the descriptor. */
  1328. default_value = rb_funcall(default_value, rb_intern("to_s"), 0);
  1329. google_protobuf_FieldDescriptorProto_set_default_value(
  1330. field_proto,
  1331. FileBuilderContext_strdup(self->file_builder, default_value));
  1332. }
  1333. }
  1334. if (oneof_index >= 0) {
  1335. google_protobuf_FieldDescriptorProto_set_oneof_index(field_proto,
  1336. oneof_index);
  1337. }
  1338. }
  1339. static VALUE make_mapentry(VALUE _message_builder, VALUE types, int argc,
  1340. VALUE* argv) {
  1341. DEFINE_SELF(MessageBuilderContext, message_builder, _message_builder);
  1342. VALUE type_class = rb_ary_entry(types, 2);
  1343. FileBuilderContext* file_context =
  1344. ruby_to_FileBuilderContext(message_builder->file_builder);
  1345. google_protobuf_MessageOptions* options =
  1346. google_protobuf_DescriptorProto_mutable_options(
  1347. message_builder->msg_proto, file_context->arena);
  1348. google_protobuf_MessageOptions_set_map_entry(options, true);
  1349. // optional <type> key = 1;
  1350. rb_funcall(_message_builder, rb_intern("optional"), 3,
  1351. ID2SYM(rb_intern("key")), rb_ary_entry(types, 0), INT2NUM(1));
  1352. // optional <type> value = 2;
  1353. if (type_class == Qnil) {
  1354. rb_funcall(_message_builder, rb_intern("optional"), 3,
  1355. ID2SYM(rb_intern("value")), rb_ary_entry(types, 1), INT2NUM(2));
  1356. } else {
  1357. rb_funcall(_message_builder, rb_intern("optional"), 4,
  1358. ID2SYM(rb_intern("value")), rb_ary_entry(types, 1), INT2NUM(2),
  1359. type_class);
  1360. }
  1361. return Qnil;
  1362. }
  1363. /*
  1364. * call-seq:
  1365. * MessageBuilderContext.optional(name, type, number, type_class = nil,
  1366. * options = nil)
  1367. *
  1368. * Defines a new optional field on this message type with the given type, tag
  1369. * number, and type class (for message and enum fields). The type must be a Ruby
  1370. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1371. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1372. */
  1373. VALUE MessageBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
  1374. VALUE name, type, number;
  1375. VALUE type_class, options = Qnil;
  1376. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1377. // Allow passing (name, type, number, options) or
  1378. // (name, type, number, type_class, options)
  1379. if (argc == 4 && RB_TYPE_P(type_class, T_HASH)) {
  1380. options = type_class;
  1381. type_class = Qnil;
  1382. }
  1383. msgdef_add_field(_self, UPB_LABEL_OPTIONAL, name, type, number, type_class,
  1384. options, -1, false);
  1385. return Qnil;
  1386. }
  1387. /*
  1388. * call-seq:
  1389. * MessageBuilderContext.proto3_optional(name, type, number,
  1390. * type_class = nil, options = nil)
  1391. *
  1392. * Defines a true proto3 optional field (that tracks presence) on this message
  1393. * type with the given type, tag number, and type class (for message and enum
  1394. * fields). The type must be a Ruby symbol (as accepted by
  1395. * FieldDescriptor#type=) and the type_class must be a string, if present (as
  1396. * accepted by FieldDescriptor#submsg_name=).
  1397. */
  1398. VALUE MessageBuilderContext_proto3_optional(int argc, VALUE* argv,
  1399. VALUE _self) {
  1400. VALUE name, type, number;
  1401. VALUE type_class, options = Qnil;
  1402. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1403. // Allow passing (name, type, number, options) or
  1404. // (name, type, number, type_class, options)
  1405. if (argc == 4 && RB_TYPE_P(type_class, T_HASH)) {
  1406. options = type_class;
  1407. type_class = Qnil;
  1408. }
  1409. msgdef_add_field(_self, UPB_LABEL_OPTIONAL, name, type, number, type_class,
  1410. options, -1, true);
  1411. return Qnil;
  1412. }
  1413. /*
  1414. * call-seq:
  1415. * MessageBuilderContext.required(name, type, number, type_class = nil,
  1416. * options = nil)
  1417. *
  1418. * Defines a new required field on this message type with the given type, tag
  1419. * number, and type class (for message and enum fields). The type must be a Ruby
  1420. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1421. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1422. *
  1423. * Proto3 does not have required fields, but this method exists for
  1424. * completeness. Any attempt to add a message type with required fields to a
  1425. * pool will currently result in an error.
  1426. */
  1427. VALUE MessageBuilderContext_required(int argc, VALUE* argv, VALUE _self) {
  1428. VALUE name, type, number;
  1429. VALUE type_class, options = Qnil;
  1430. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1431. // Allow passing (name, type, number, options) or
  1432. // (name, type, number, type_class, options)
  1433. if (argc == 4 && RB_TYPE_P(type_class, T_HASH)) {
  1434. options = type_class;
  1435. type_class = Qnil;
  1436. }
  1437. msgdef_add_field(_self, UPB_LABEL_REQUIRED, name, type, number, type_class,
  1438. options, -1, false);
  1439. return Qnil;
  1440. }
  1441. /*
  1442. * call-seq:
  1443. * MessageBuilderContext.repeated(name, type, number, type_class = nil)
  1444. *
  1445. * Defines a new repeated field on this message type with the given type, tag
  1446. * number, and type class (for message and enum fields). The type must be a Ruby
  1447. * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
  1448. * string, if present (as accepted by FieldDescriptor#submsg_name=).
  1449. */
  1450. VALUE MessageBuilderContext_repeated(int argc, VALUE* argv, VALUE _self) {
  1451. VALUE name, type, number, type_class;
  1452. if (argc < 3) {
  1453. rb_raise(rb_eArgError, "Expected at least 3 arguments.");
  1454. }
  1455. name = argv[0];
  1456. type = argv[1];
  1457. number = argv[2];
  1458. type_class = (argc > 3) ? argv[3] : Qnil;
  1459. msgdef_add_field(_self, UPB_LABEL_REPEATED, name, type, number, type_class,
  1460. Qnil, -1, false);
  1461. return Qnil;
  1462. }
  1463. /*
  1464. * call-seq:
  1465. * MessageBuilderContext.map(name, key_type, value_type, number,
  1466. * value_type_class = nil)
  1467. *
  1468. * Defines a new map field on this message type with the given key and value
  1469. * types, tag number, and type class (for message and enum value types). The key
  1470. * type must be :int32/:uint32/:int64/:uint64, :bool, or :string. The value type
  1471. * type must be a Ruby symbol (as accepted by FieldDescriptor#type=) and the
  1472. * type_class must be a string, if present (as accepted by
  1473. * FieldDescriptor#submsg_name=).
  1474. */
  1475. VALUE MessageBuilderContext_map(int argc, VALUE* argv, VALUE _self) {
  1476. DEFINE_SELF(MessageBuilderContext, self, _self);
  1477. VALUE name, key_type, value_type, number, type_class;
  1478. VALUE mapentry_desc_name;
  1479. FileBuilderContext* file_builder;
  1480. upb_strview msg_name;
  1481. if (argc < 4) {
  1482. rb_raise(rb_eArgError, "Expected at least 4 arguments.");
  1483. }
  1484. name = argv[0];
  1485. key_type = argv[1];
  1486. value_type = argv[2];
  1487. number = argv[3];
  1488. type_class = (argc > 4) ? argv[4] : Qnil;
  1489. // Validate the key type. We can't accept enums, messages, or floats/doubles
  1490. // as map keys. (We exclude these explicitly, and the field-descriptor setter
  1491. // below then ensures that the type is one of the remaining valid options.)
  1492. if (SYM2ID(key_type) == rb_intern("float") ||
  1493. SYM2ID(key_type) == rb_intern("double") ||
  1494. SYM2ID(key_type) == rb_intern("enum") ||
  1495. SYM2ID(key_type) == rb_intern("message")) {
  1496. rb_raise(rb_eArgError,
  1497. "Cannot add a map field with a float, double, enum, or message "
  1498. "type.");
  1499. }
  1500. file_builder = ruby_to_FileBuilderContext(self->file_builder);
  1501. // TODO(haberman): remove this restriction, maps are supported in proto2.
  1502. if (upb_strview_eql(
  1503. google_protobuf_FileDescriptorProto_syntax(file_builder->file_proto),
  1504. upb_strview_makez("proto2"))) {
  1505. rb_raise(rb_eArgError,
  1506. "Cannot add a native map field using proto2 syntax.");
  1507. }
  1508. // Create a new message descriptor for the map entry message, and create a
  1509. // repeated submessage field here with that type.
  1510. msg_name = google_protobuf_DescriptorProto_name(self->msg_proto);
  1511. mapentry_desc_name = rb_str_new(msg_name.data, msg_name.size);
  1512. mapentry_desc_name = rb_str_cat2(mapentry_desc_name, "_MapEntry_");
  1513. mapentry_desc_name =
  1514. rb_str_cat2(mapentry_desc_name, rb_id2name(SYM2ID(name)));
  1515. {
  1516. // message <msgname>_MapEntry_ { /* ... */ }
  1517. VALUE args[1] = {mapentry_desc_name};
  1518. VALUE types = rb_ary_new3(3, key_type, value_type, type_class);
  1519. rb_block_call(self->file_builder, rb_intern("add_message"), 1, args,
  1520. make_mapentry, types);
  1521. }
  1522. // If this file is in a package, we need to qualify the map entry type.
  1523. if (google_protobuf_FileDescriptorProto_has_package(file_builder->file_proto)) {
  1524. upb_strview package_view =
  1525. google_protobuf_FileDescriptorProto_package(file_builder->file_proto);
  1526. VALUE package = rb_str_new(package_view.data, package_view.size);
  1527. package = rb_str_cat2(package, ".");
  1528. mapentry_desc_name = rb_str_concat(package, mapentry_desc_name);
  1529. }
  1530. // repeated MapEntry <name> = <number>;
  1531. rb_funcall(_self, rb_intern("repeated"), 4, name,
  1532. ID2SYM(rb_intern("message")), number, mapentry_desc_name);
  1533. return Qnil;
  1534. }
  1535. /*
  1536. * call-seq:
  1537. * MessageBuilderContext.oneof(name, &block) => nil
  1538. *
  1539. * Creates a new OneofDescriptor with the given name, creates a
  1540. * OneofBuilderContext attached to that OneofDescriptor, evaluates the given
  1541. * block in the context of that OneofBuilderContext with #instance_eval, and
  1542. * then adds the oneof to the message.
  1543. *
  1544. * This is the recommended, idiomatic way to build oneof definitions.
  1545. */
  1546. VALUE MessageBuilderContext_oneof(VALUE _self, VALUE name) {
  1547. DEFINE_SELF(MessageBuilderContext, self, _self);
  1548. size_t oneof_count;
  1549. FileBuilderContext* file_context =
  1550. ruby_to_FileBuilderContext(self->file_builder);
  1551. google_protobuf_OneofDescriptorProto* oneof_proto;
  1552. // Existing oneof_count becomes oneof_index.
  1553. google_protobuf_DescriptorProto_oneof_decl(self->msg_proto, &oneof_count);
  1554. // Create oneof_proto and set its name.
  1555. oneof_proto = google_protobuf_DescriptorProto_add_oneof_decl(
  1556. self->msg_proto, file_context->arena);
  1557. google_protobuf_OneofDescriptorProto_set_name(
  1558. oneof_proto, FileBuilderContext_strdup_sym(self->file_builder, name));
  1559. // Evaluate the block with the builder as argument.
  1560. {
  1561. VALUE args[2] = { INT2NUM(oneof_count), _self };
  1562. VALUE ctx = rb_class_new_instance(2, args, cOneofBuilderContext);
  1563. VALUE block = rb_block_proc();
  1564. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1565. }
  1566. return Qnil;
  1567. }
  1568. void MessageBuilderContext_add_synthetic_oneofs(VALUE _self) {
  1569. DEFINE_SELF(MessageBuilderContext, self, _self);
  1570. FileBuilderContext* file_context =
  1571. ruby_to_FileBuilderContext(self->file_builder);
  1572. size_t field_count, oneof_count;
  1573. google_protobuf_FieldDescriptorProto** fields =
  1574. google_protobuf_DescriptorProto_mutable_field(self->msg_proto, &field_count);
  1575. const google_protobuf_OneofDescriptorProto*const* oneofs =
  1576. google_protobuf_DescriptorProto_oneof_decl(self->msg_proto, &oneof_count);
  1577. VALUE names = rb_hash_new();
  1578. VALUE underscore = rb_str_new2("_");
  1579. size_t i;
  1580. // We have to build a set of all names, to ensure that synthetic oneofs are
  1581. // not creating conflicts.
  1582. for (i = 0; i < field_count; i++) {
  1583. upb_strview name = google_protobuf_FieldDescriptorProto_name(fields[i]);
  1584. rb_hash_aset(names, rb_str_new(name.data, name.size), Qtrue);
  1585. }
  1586. for (i = 0; i < oneof_count; i++) {
  1587. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneofs[i]);
  1588. rb_hash_aset(names, rb_str_new(name.data, name.size), Qtrue);
  1589. }
  1590. for (i = 0; i < field_count; i++) {
  1591. google_protobuf_OneofDescriptorProto* oneof_proto;
  1592. VALUE oneof_name;
  1593. upb_strview field_name;
  1594. if (!google_protobuf_FieldDescriptorProto_proto3_optional(fields[i])) {
  1595. continue;
  1596. }
  1597. // Prepend '_' until we are no longer conflicting.
  1598. field_name = google_protobuf_FieldDescriptorProto_name(fields[i]);
  1599. oneof_name = rb_str_new(field_name.data, field_name.size);
  1600. while (rb_hash_lookup(names, oneof_name) != Qnil) {
  1601. oneof_name = rb_str_plus(underscore, oneof_name);
  1602. }
  1603. rb_hash_aset(names, oneof_name, Qtrue);
  1604. google_protobuf_FieldDescriptorProto_set_oneof_index(fields[i],
  1605. oneof_count++);
  1606. oneof_proto = google_protobuf_DescriptorProto_add_oneof_decl(
  1607. self->msg_proto, file_context->arena);
  1608. google_protobuf_OneofDescriptorProto_set_name(
  1609. oneof_proto, FileBuilderContext_strdup(self->file_builder, oneof_name));
  1610. }
  1611. }
  1612. // -----------------------------------------------------------------------------
  1613. // OneofBuilderContext.
  1614. // -----------------------------------------------------------------------------
  1615. DEFINE_CLASS(OneofBuilderContext,
  1616. "Google::Protobuf::Internal::OneofBuilderContext");
  1617. void OneofBuilderContext_mark(void* _self) {
  1618. OneofBuilderContext* self = _self;
  1619. rb_gc_mark(self->message_builder);
  1620. }
  1621. void OneofBuilderContext_free(void* _self) {
  1622. xfree(_self);
  1623. }
  1624. VALUE OneofBuilderContext_alloc(VALUE klass) {
  1625. OneofBuilderContext* self = ALLOC(OneofBuilderContext);
  1626. VALUE ret = TypedData_Wrap_Struct(
  1627. klass, &_OneofBuilderContext_type, self);
  1628. self->oneof_index = 0;
  1629. self->message_builder = Qnil;
  1630. return ret;
  1631. }
  1632. void OneofBuilderContext_register(VALUE module) {
  1633. VALUE klass = rb_define_class_under(
  1634. module, "OneofBuilderContext", rb_cObject);
  1635. rb_define_alloc_func(klass, OneofBuilderContext_alloc);
  1636. rb_define_method(klass, "initialize",
  1637. OneofBuilderContext_initialize, 2);
  1638. rb_define_method(klass, "optional", OneofBuilderContext_optional, -1);
  1639. rb_gc_register_address(&cOneofBuilderContext);
  1640. cOneofBuilderContext = klass;
  1641. }
  1642. /*
  1643. * call-seq:
  1644. * OneofBuilderContext.new(oneof_index, message_builder) => context
  1645. *
  1646. * Create a new oneof builder context around the given oneof descriptor and
  1647. * builder context. This class is intended to serve as a DSL context to be used
  1648. * with #instance_eval.
  1649. */
  1650. VALUE OneofBuilderContext_initialize(VALUE _self,
  1651. VALUE oneof_index,
  1652. VALUE message_builder) {
  1653. DEFINE_SELF(OneofBuilderContext, self, _self);
  1654. self->oneof_index = NUM2INT(oneof_index);
  1655. self->message_builder = message_builder;
  1656. return Qnil;
  1657. }
  1658. /*
  1659. * call-seq:
  1660. * OneofBuilderContext.optional(name, type, number, type_class = nil,
  1661. * default_value = nil)
  1662. *
  1663. * Defines a new optional field in this oneof with the given type, tag number,
  1664. * and type class (for message and enum fields). The type must be a Ruby symbol
  1665. * (as accepted by FieldDescriptor#type=) and the type_class must be a string,
  1666. * if present (as accepted by FieldDescriptor#submsg_name=).
  1667. */
  1668. VALUE OneofBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
  1669. DEFINE_SELF(OneofBuilderContext, self, _self);
  1670. VALUE name, type, number;
  1671. VALUE type_class, options = Qnil;
  1672. rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
  1673. msgdef_add_field(self->message_builder, UPB_LABEL_OPTIONAL, name, type,
  1674. number, type_class, options, self->oneof_index, false);
  1675. return Qnil;
  1676. }
  1677. // -----------------------------------------------------------------------------
  1678. // EnumBuilderContext.
  1679. // -----------------------------------------------------------------------------
  1680. DEFINE_CLASS(EnumBuilderContext,
  1681. "Google::Protobuf::Internal::EnumBuilderContext");
  1682. void EnumBuilderContext_mark(void* _self) {
  1683. EnumBuilderContext* self = _self;
  1684. rb_gc_mark(self->file_builder);
  1685. }
  1686. void EnumBuilderContext_free(void* _self) {
  1687. xfree(_self);
  1688. }
  1689. VALUE EnumBuilderContext_alloc(VALUE klass) {
  1690. EnumBuilderContext* self = ALLOC(EnumBuilderContext);
  1691. VALUE ret = TypedData_Wrap_Struct(
  1692. klass, &_EnumBuilderContext_type, self);
  1693. self->enum_proto = NULL;
  1694. self->file_builder = Qnil;
  1695. return ret;
  1696. }
  1697. void EnumBuilderContext_register(VALUE module) {
  1698. VALUE klass = rb_define_class_under(
  1699. module, "EnumBuilderContext", rb_cObject);
  1700. rb_define_alloc_func(klass, EnumBuilderContext_alloc);
  1701. rb_define_method(klass, "initialize", EnumBuilderContext_initialize, 2);
  1702. rb_define_method(klass, "value", EnumBuilderContext_value, 2);
  1703. rb_gc_register_address(&cEnumBuilderContext);
  1704. cEnumBuilderContext = klass;
  1705. }
  1706. /*
  1707. * call-seq:
  1708. * EnumBuilderContext.new(file_builder) => context
  1709. *
  1710. * Create a new builder context around the given enum descriptor. This class is
  1711. * intended to serve as a DSL context to be used with #instance_eval.
  1712. */
  1713. VALUE EnumBuilderContext_initialize(VALUE _self, VALUE _file_builder,
  1714. VALUE name) {
  1715. DEFINE_SELF(EnumBuilderContext, self, _self);
  1716. FileBuilderContext* file_builder = ruby_to_FileBuilderContext(_file_builder);
  1717. google_protobuf_FileDescriptorProto* file_proto = file_builder->file_proto;
  1718. self->file_builder = _file_builder;
  1719. self->enum_proto = google_protobuf_FileDescriptorProto_add_enum_type(
  1720. file_proto, file_builder->arena);
  1721. google_protobuf_EnumDescriptorProto_set_name(
  1722. self->enum_proto, FileBuilderContext_strdup(_file_builder, name));
  1723. return Qnil;
  1724. }
  1725. /*
  1726. * call-seq:
  1727. * EnumBuilder.add_value(name, number)
  1728. *
  1729. * Adds the given name => number mapping to the enum type. Name must be a Ruby
  1730. * symbol.
  1731. */
  1732. VALUE EnumBuilderContext_value(VALUE _self, VALUE name, VALUE number) {
  1733. DEFINE_SELF(EnumBuilderContext, self, _self);
  1734. FileBuilderContext* file_builder =
  1735. ruby_to_FileBuilderContext(self->file_builder);
  1736. google_protobuf_EnumValueDescriptorProto* enum_value;
  1737. enum_value = google_protobuf_EnumDescriptorProto_add_value(
  1738. self->enum_proto, file_builder->arena);
  1739. google_protobuf_EnumValueDescriptorProto_set_name(
  1740. enum_value, FileBuilderContext_strdup_sym(self->file_builder, name));
  1741. google_protobuf_EnumValueDescriptorProto_set_number(enum_value,
  1742. NUM2INT(number));
  1743. return Qnil;
  1744. }
  1745. // -----------------------------------------------------------------------------
  1746. // FileBuilderContext.
  1747. // -----------------------------------------------------------------------------
  1748. DEFINE_CLASS(FileBuilderContext,
  1749. "Google::Protobuf::Internal::FileBuilderContext");
  1750. void FileBuilderContext_mark(void* _self) {
  1751. FileBuilderContext* self = _self;
  1752. rb_gc_mark(self->descriptor_pool);
  1753. }
  1754. void FileBuilderContext_free(void* _self) {
  1755. FileBuilderContext* self = _self;
  1756. upb_arena_free(self->arena);
  1757. xfree(self);
  1758. }
  1759. upb_strview FileBuilderContext_strdup2(VALUE _self, const char *str) {
  1760. DEFINE_SELF(FileBuilderContext, self, _self);
  1761. upb_strview ret;
  1762. char *data;
  1763. ret.size = strlen(str);
  1764. data = upb_malloc(upb_arena_alloc(self->arena), ret.size + 1);
  1765. ret.data = data;
  1766. memcpy(data, str, ret.size);
  1767. /* Null-terminate required by rewrite_enum_defaults() above. */
  1768. data[ret.size] = '\0';
  1769. return ret;
  1770. }
  1771. upb_strview FileBuilderContext_strdup(VALUE _self, VALUE rb_str) {
  1772. return FileBuilderContext_strdup2(_self, get_str(rb_str));
  1773. }
  1774. upb_strview FileBuilderContext_strdup_sym(VALUE _self, VALUE rb_sym) {
  1775. Check_Type(rb_sym, T_SYMBOL);
  1776. return FileBuilderContext_strdup(_self, rb_id2str(SYM2ID(rb_sym)));
  1777. }
  1778. VALUE FileBuilderContext_alloc(VALUE klass) {
  1779. FileBuilderContext* self = ALLOC(FileBuilderContext);
  1780. VALUE ret = TypedData_Wrap_Struct(klass, &_FileBuilderContext_type, self);
  1781. self->arena = upb_arena_new();
  1782. self->file_proto = google_protobuf_FileDescriptorProto_new(self->arena);
  1783. self->descriptor_pool = Qnil;
  1784. return ret;
  1785. }
  1786. void FileBuilderContext_register(VALUE module) {
  1787. VALUE klass = rb_define_class_under(module, "FileBuilderContext", rb_cObject);
  1788. rb_define_alloc_func(klass, FileBuilderContext_alloc);
  1789. rb_define_method(klass, "initialize", FileBuilderContext_initialize, 3);
  1790. rb_define_method(klass, "add_message", FileBuilderContext_add_message, 1);
  1791. rb_define_method(klass, "add_enum", FileBuilderContext_add_enum, 1);
  1792. rb_gc_register_address(&cFileBuilderContext);
  1793. cFileBuilderContext = klass;
  1794. }
  1795. /*
  1796. * call-seq:
  1797. * FileBuilderContext.new(descriptor_pool) => context
  1798. *
  1799. * Create a new file builder context for the given file descriptor and
  1800. * builder context. This class is intended to serve as a DSL context to be used
  1801. * with #instance_eval.
  1802. */
  1803. VALUE FileBuilderContext_initialize(VALUE _self, VALUE descriptor_pool,
  1804. VALUE name, VALUE options) {
  1805. DEFINE_SELF(FileBuilderContext, self, _self);
  1806. self->descriptor_pool = descriptor_pool;
  1807. google_protobuf_FileDescriptorProto_set_name(
  1808. self->file_proto, FileBuilderContext_strdup(_self, name));
  1809. // Default syntax for Ruby is proto3.
  1810. google_protobuf_FileDescriptorProto_set_syntax(
  1811. self->file_proto,
  1812. FileBuilderContext_strdup(_self, rb_str_new2("proto3")));
  1813. if (options != Qnil) {
  1814. VALUE syntax;
  1815. Check_Type(options, T_HASH);
  1816. syntax = rb_hash_lookup2(options, ID2SYM(rb_intern("syntax")), Qnil);
  1817. if (syntax != Qnil) {
  1818. VALUE syntax_str;
  1819. Check_Type(syntax, T_SYMBOL);
  1820. syntax_str = rb_id2str(SYM2ID(syntax));
  1821. google_protobuf_FileDescriptorProto_set_syntax(
  1822. self->file_proto, FileBuilderContext_strdup(_self, syntax_str));
  1823. }
  1824. }
  1825. return Qnil;
  1826. }
  1827. /*
  1828. * call-seq:
  1829. * FileBuilderContext.add_message(name, &block)
  1830. *
  1831. * Creates a new, empty descriptor with the given name, and invokes the block in
  1832. * the context of a MessageBuilderContext on that descriptor. The block can then
  1833. * call, e.g., MessageBuilderContext#optional and MessageBuilderContext#repeated
  1834. * methods to define the message fields.
  1835. *
  1836. * This is the recommended, idiomatic way to build message definitions.
  1837. */
  1838. VALUE FileBuilderContext_add_message(VALUE _self, VALUE name) {
  1839. VALUE args[2] = { _self, name };
  1840. VALUE ctx = rb_class_new_instance(2, args, cMessageBuilderContext);
  1841. VALUE block = rb_block_proc();
  1842. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1843. MessageBuilderContext_add_synthetic_oneofs(ctx);
  1844. return Qnil;
  1845. }
  1846. /*
  1847. * call-seq:
  1848. * FileBuilderContext.add_enum(name, &block)
  1849. *
  1850. * Creates a new, empty enum descriptor with the given name, and invokes the
  1851. * block in the context of an EnumBuilderContext on that descriptor. The block
  1852. * can then call EnumBuilderContext#add_value to define the enum values.
  1853. *
  1854. * This is the recommended, idiomatic way to build enum definitions.
  1855. */
  1856. VALUE FileBuilderContext_add_enum(VALUE _self, VALUE name) {
  1857. VALUE args[2] = { _self, name };
  1858. VALUE ctx = rb_class_new_instance(2, args, cEnumBuilderContext);
  1859. VALUE block = rb_block_proc();
  1860. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1861. return Qnil;
  1862. }
  1863. void FileBuilderContext_build(VALUE _self) {
  1864. DEFINE_SELF(FileBuilderContext, self, _self);
  1865. DescriptorPool* pool = ruby_to_DescriptorPool(self->descriptor_pool);
  1866. upb_status status;
  1867. rewrite_enum_defaults(pool->symtab, self->file_proto);
  1868. rewrite_names(_self, self->file_proto);
  1869. upb_status_clear(&status);
  1870. if (!upb_symtab_addfile(pool->symtab, self->file_proto, &status)) {
  1871. rb_raise(cTypeError, "Unable to add defs to DescriptorPool: %s",
  1872. upb_status_errmsg(&status));
  1873. }
  1874. }
  1875. // -----------------------------------------------------------------------------
  1876. // Builder.
  1877. // -----------------------------------------------------------------------------
  1878. DEFINE_CLASS(Builder, "Google::Protobuf::Internal::Builder");
  1879. void Builder_mark(void* _self) {
  1880. Builder* self = _self;
  1881. rb_gc_mark(self->descriptor_pool);
  1882. rb_gc_mark(self->default_file_builder);
  1883. }
  1884. void Builder_free(void* _self) {
  1885. xfree(_self);
  1886. }
  1887. VALUE Builder_alloc(VALUE klass) {
  1888. Builder* self = ALLOC(Builder);
  1889. VALUE ret = TypedData_Wrap_Struct(
  1890. klass, &_Builder_type, self);
  1891. self->descriptor_pool = Qnil;
  1892. self->default_file_builder = Qnil;
  1893. return ret;
  1894. }
  1895. void Builder_register(VALUE module) {
  1896. VALUE klass = rb_define_class_under(module, "Builder", rb_cObject);
  1897. rb_define_alloc_func(klass, Builder_alloc);
  1898. rb_define_method(klass, "initialize", Builder_initialize, 1);
  1899. rb_define_method(klass, "add_file", Builder_add_file, -1);
  1900. rb_define_method(klass, "add_message", Builder_add_message, 1);
  1901. rb_define_method(klass, "add_enum", Builder_add_enum, 1);
  1902. rb_gc_register_address(&cBuilder);
  1903. cBuilder = klass;
  1904. }
  1905. /*
  1906. * call-seq:
  1907. * Builder.new(descriptor_pool) => builder
  1908. *
  1909. * Creates a new Builder. A Builder can accumulate a set of new message and enum
  1910. * descriptors and atomically register them into a pool in a way that allows for
  1911. * (co)recursive type references.
  1912. */
  1913. VALUE Builder_initialize(VALUE _self, VALUE pool) {
  1914. DEFINE_SELF(Builder, self, _self);
  1915. self->descriptor_pool = pool;
  1916. self->default_file_builder = Qnil; // Created lazily if needed.
  1917. return Qnil;
  1918. }
  1919. /*
  1920. * call-seq:
  1921. * Builder.add_file(name, options = nil, &block)
  1922. *
  1923. * Creates a new, file descriptor with the given name and options and invokes
  1924. * the block in the context of a FileBuilderContext on that descriptor. The
  1925. * block can then call FileBuilderContext#add_message or
  1926. * FileBuilderContext#add_enum to define new messages or enums, respectively.
  1927. *
  1928. * This is the recommended, idiomatic way to build file descriptors.
  1929. */
  1930. VALUE Builder_add_file(int argc, VALUE* argv, VALUE _self) {
  1931. DEFINE_SELF(Builder, self, _self);
  1932. VALUE name, options;
  1933. VALUE ctx;
  1934. VALUE block;
  1935. rb_scan_args(argc, argv, "11", &name, &options);
  1936. {
  1937. VALUE args[3] = { self->descriptor_pool, name, options };
  1938. ctx = rb_class_new_instance(3, args, cFileBuilderContext);
  1939. }
  1940. block = rb_block_proc();
  1941. rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
  1942. FileBuilderContext_build(ctx);
  1943. return Qnil;
  1944. }
  1945. static VALUE Builder_get_default_file(VALUE _self) {
  1946. DEFINE_SELF(Builder, self, _self);
  1947. /* Lazily create only if legacy builder-level methods are called. */
  1948. if (self->default_file_builder == Qnil) {
  1949. VALUE name = rb_str_new2("ruby_default_file.proto");
  1950. VALUE args [3] = { self->descriptor_pool, name, rb_hash_new() };
  1951. self->default_file_builder =
  1952. rb_class_new_instance(3, args, cFileBuilderContext);
  1953. }
  1954. return self->default_file_builder;
  1955. }
  1956. /*
  1957. * call-seq:
  1958. * Builder.add_message(name, &block)
  1959. *
  1960. * Old and deprecated way to create a new descriptor.
  1961. * See FileBuilderContext.add_message for the recommended way.
  1962. *
  1963. * Exists for backwards compatibility to allow building descriptor pool for
  1964. * files generated by protoc which don't add messages within "add_file" block.
  1965. * Descriptors created this way get assigned to a default empty FileDescriptor.
  1966. */
  1967. VALUE Builder_add_message(VALUE _self, VALUE name) {
  1968. VALUE file_builder = Builder_get_default_file(_self);
  1969. rb_funcall_with_block(file_builder, rb_intern("add_message"), 1, &name,
  1970. rb_block_proc());
  1971. return Qnil;
  1972. }
  1973. /*
  1974. * call-seq:
  1975. * Builder.add_enum(name, &block)
  1976. *
  1977. * Old and deprecated way to create a new enum descriptor.
  1978. * See FileBuilderContext.add_enum for the recommended way.
  1979. *
  1980. * Exists for backwards compatibility to allow building descriptor pool for
  1981. * files generated by protoc which don't add enums within "add_file" block.
  1982. * Enum descriptors created this way get assigned to a default empty
  1983. * FileDescriptor.
  1984. */
  1985. VALUE Builder_add_enum(VALUE _self, VALUE name) {
  1986. VALUE file_builder = Builder_get_default_file(_self);
  1987. rb_funcall_with_block(file_builder, rb_intern("add_enum"), 1, &name,
  1988. rb_block_proc());
  1989. return Qnil;
  1990. }
  1991. /* This method is hidden from Ruby, and only called directly from
  1992. * DescriptorPool_build(). */
  1993. VALUE Builder_build(VALUE _self) {
  1994. DEFINE_SELF(Builder, self, _self);
  1995. if (self->default_file_builder != Qnil) {
  1996. FileBuilderContext_build(self->default_file_builder);
  1997. self->default_file_builder = Qnil;
  1998. }
  1999. return Qnil;
  2000. }
  2001. static VALUE get_def_obj(VALUE _descriptor_pool, const void* ptr, VALUE klass) {
  2002. DEFINE_SELF(DescriptorPool, descriptor_pool, _descriptor_pool);
  2003. VALUE key = ULL2NUM((intptr_t)ptr);
  2004. VALUE def;
  2005. def = rb_hash_aref(descriptor_pool->def_to_descriptor, key);
  2006. if (ptr == NULL) {
  2007. return Qnil;
  2008. }
  2009. if (def == Qnil) {
  2010. // Lazily create wrapper object.
  2011. VALUE args[3] = { c_only_cookie, _descriptor_pool, key };
  2012. def = rb_class_new_instance(3, args, klass);
  2013. rb_hash_aset(descriptor_pool->def_to_descriptor, key, def);
  2014. // For message defs, we now eagerly get/create descriptors for all
  2015. // submessages. We will need these anyway to parse or serialize this
  2016. // message type. But more importantly, we must do this now so that
  2017. // add_handlers_for_message() (which calls get_msgdef_obj()) does *not*
  2018. // need to create a Ruby object or insert into a Ruby Hash. We need to
  2019. // avoid triggering GC, which can switch Ruby threads and re-enter our
  2020. // C extension from a different thread. This wreaks havoc on our state
  2021. // if we were in the middle of building handlers.
  2022. if (klass == cDescriptor) {
  2023. const upb_msgdef *m = ptr;
  2024. upb_msg_field_iter it;
  2025. for (upb_msg_field_begin(&it, m);
  2026. !upb_msg_field_done(&it);
  2027. upb_msg_field_next(&it)) {
  2028. const upb_fielddef* f = upb_msg_iter_field(&it);
  2029. if (upb_fielddef_issubmsg(f)) {
  2030. get_msgdef_obj(_descriptor_pool, upb_fielddef_msgsubdef(f));
  2031. }
  2032. }
  2033. }
  2034. }
  2035. return def;
  2036. }
  2037. VALUE get_msgdef_obj(VALUE descriptor_pool, const upb_msgdef* def) {
  2038. return get_def_obj(descriptor_pool, def, cDescriptor);
  2039. }
  2040. VALUE get_enumdef_obj(VALUE descriptor_pool, const upb_enumdef* def) {
  2041. return get_def_obj(descriptor_pool, def, cEnumDescriptor);
  2042. }
  2043. VALUE get_fielddef_obj(VALUE descriptor_pool, const upb_fielddef* def) {
  2044. return get_def_obj(descriptor_pool, def, cFieldDescriptor);
  2045. }
  2046. VALUE get_filedef_obj(VALUE descriptor_pool, const upb_filedef* def) {
  2047. return get_def_obj(descriptor_pool, def, cFileDescriptor);
  2048. }
  2049. VALUE get_oneofdef_obj(VALUE descriptor_pool, const upb_oneofdef* def) {
  2050. return get_def_obj(descriptor_pool, def, cOneofDescriptor);
  2051. }