defs.c 83 KB

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