blob: 96ef4953b95205ad4de6b8bed0c0322d5a410c29 [file] [log] [blame]
Chris Fallin973f4252014-11-18 14:19:58 -08001// 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
31#include "protobuf.h"
32
33// -----------------------------------------------------------------------------
34// Common utilities.
35// -----------------------------------------------------------------------------
36
Chris Fallin973f4252014-11-18 14:19:58 -080037static const char* get_str(VALUE str) {
38 Check_Type(str, T_STRING);
39 return RSTRING_PTR(str);
40}
41
42static VALUE rb_str_maybe_null(const char* s) {
43 if (s == NULL) {
44 s = "";
45 }
46 return rb_str_new2(s);
47}
48
49static upb_def* check_notfrozen(const upb_def* def) {
50 if (upb_def_isfrozen(def)) {
51 rb_raise(rb_eRuntimeError,
52 "Attempt to modify a frozen descriptor. Once descriptors are "
53 "added to the descriptor pool, they may not be modified.");
54 }
55 return (upb_def*)def;
56}
57
58static upb_msgdef* check_msg_notfrozen(const upb_msgdef* def) {
Chris Fallin9de35e72015-01-26 11:23:19 -080059 return upb_downcast_msgdef_mutable(check_notfrozen((const upb_def*)def));
Chris Fallin973f4252014-11-18 14:19:58 -080060}
61
62static upb_fielddef* check_field_notfrozen(const upb_fielddef* def) {
Chris Fallin9de35e72015-01-26 11:23:19 -080063 return upb_downcast_fielddef_mutable(check_notfrozen((const upb_def*)def));
Chris Fallin973f4252014-11-18 14:19:58 -080064}
65
Chris Fallinfcd88892015-01-13 18:14:39 -080066static upb_oneofdef* check_oneof_notfrozen(const upb_oneofdef* def) {
67 return (upb_oneofdef*)check_notfrozen((const upb_def*)def);
68}
69
Chris Fallin973f4252014-11-18 14:19:58 -080070static upb_enumdef* check_enum_notfrozen(const upb_enumdef* def) {
71 return (upb_enumdef*)check_notfrozen((const upb_def*)def);
72}
73
74// -----------------------------------------------------------------------------
75// DescriptorPool.
76// -----------------------------------------------------------------------------
77
78#define DEFINE_CLASS(name, string_name) \
79 VALUE c ## name; \
80 const rb_data_type_t _ ## name ## _type = { \
81 string_name, \
82 { name ## _mark, name ## _free, NULL }, \
83 }; \
84 name* ruby_to_ ## name(VALUE val) { \
85 name* ret; \
86 TypedData_Get_Struct(val, name, &_ ## name ## _type, ret); \
87 return ret; \
88 } \
89
90#define DEFINE_SELF(type, var, rb_var) \
Josh Habermana1daeab2015-07-10 11:56:06 -070091 type* var = ruby_to_ ## type(rb_var)
Chris Fallin973f4252014-11-18 14:19:58 -080092
93// Global singleton DescriptorPool. The user is free to create others, but this
94// is used by generated code.
95VALUE generated_pool;
96
97DEFINE_CLASS(DescriptorPool, "Google::Protobuf::DescriptorPool");
98
99void DescriptorPool_mark(void* _self) {
100}
101
102void DescriptorPool_free(void* _self) {
103 DescriptorPool* self = _self;
104 upb_symtab_unref(self->symtab, &self->symtab);
105 xfree(self);
106}
107
108/*
109 * call-seq:
110 * DescriptorPool.new => pool
111 *
112 * Creates a new, empty, descriptor pool.
113 */
114VALUE DescriptorPool_alloc(VALUE klass) {
115 DescriptorPool* self = ALLOC(DescriptorPool);
116 self->symtab = upb_symtab_new(&self->symtab);
117 return TypedData_Wrap_Struct(klass, &_DescriptorPool_type, self);
118}
119
120void DescriptorPool_register(VALUE module) {
121 VALUE klass = rb_define_class_under(
122 module, "DescriptorPool", rb_cObject);
123 rb_define_alloc_func(klass, DescriptorPool_alloc);
124 rb_define_method(klass, "add", DescriptorPool_add, 1);
125 rb_define_method(klass, "build", DescriptorPool_build, 0);
126 rb_define_method(klass, "lookup", DescriptorPool_lookup, 1);
127 rb_define_singleton_method(klass, "generated_pool",
128 DescriptorPool_generated_pool, 0);
129 cDescriptorPool = klass;
130 rb_gc_register_address(&cDescriptorPool);
131
132 generated_pool = rb_class_new_instance(0, NULL, klass);
133 rb_gc_register_address(&generated_pool);
134}
135
136static void add_descriptor_to_pool(DescriptorPool* self,
137 Descriptor* descriptor) {
138 CHECK_UPB(
139 upb_symtab_add(self->symtab, (upb_def**)&descriptor->msgdef, 1,
140 NULL, &status),
141 "Adding Descriptor to DescriptorPool failed");
142}
143
144static void add_enumdesc_to_pool(DescriptorPool* self,
145 EnumDescriptor* enumdesc) {
146 CHECK_UPB(
147 upb_symtab_add(self->symtab, (upb_def**)&enumdesc->enumdef, 1,
148 NULL, &status),
149 "Adding EnumDescriptor to DescriptorPool failed");
150}
151
152/*
153 * call-seq:
154 * DescriptorPool.add(descriptor)
155 *
156 * Adds the given Descriptor or EnumDescriptor to this pool. All references to
157 * other types in a Descriptor's fields must be resolvable within this pool or
158 * an exception will be raised.
159 */
160VALUE DescriptorPool_add(VALUE _self, VALUE def) {
161 DEFINE_SELF(DescriptorPool, self, _self);
162 VALUE def_klass = rb_obj_class(def);
163 if (def_klass == cDescriptor) {
164 add_descriptor_to_pool(self, ruby_to_Descriptor(def));
165 } else if (def_klass == cEnumDescriptor) {
166 add_enumdesc_to_pool(self, ruby_to_EnumDescriptor(def));
167 } else {
168 rb_raise(rb_eArgError,
169 "Second argument must be a Descriptor or EnumDescriptor.");
170 }
171 return Qnil;
172}
173
174/*
175 * call-seq:
176 * DescriptorPool.build(&block)
177 *
178 * Invokes the block with a Builder instance as self. All message and enum types
179 * added within the block are committed to the pool atomically, and may refer
180 * (co)recursively to each other. The user should call Builder#add_message and
181 * Builder#add_enum within the block as appropriate. This is the recommended,
182 * idiomatic way to define new message and enum types.
183 */
184VALUE DescriptorPool_build(VALUE _self) {
185 VALUE ctx = rb_class_new_instance(0, NULL, cBuilder);
186 VALUE block = rb_block_proc();
187 rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
188 rb_funcall(ctx, rb_intern("finalize_to_pool"), 1, _self);
189 return Qnil;
190}
191
192/*
193 * call-seq:
194 * DescriptorPool.lookup(name) => descriptor
195 *
196 * Finds a Descriptor or EnumDescriptor by name and returns it, or nil if none
197 * exists with the given name.
198 */
199VALUE DescriptorPool_lookup(VALUE _self, VALUE name) {
200 DEFINE_SELF(DescriptorPool, self, _self);
201 const char* name_str = get_str(name);
202 const upb_def* def = upb_symtab_lookup(self->symtab, name_str);
203 if (!def) {
204 return Qnil;
205 }
206 return get_def_obj(def);
207}
208
209/*
210 * call-seq:
211 * DescriptorPool.generated_pool => descriptor_pool
212 *
213 * Class method that returns the global DescriptorPool. This is a singleton into
214 * which generated-code message and enum types are registered. The user may also
215 * register types in this pool for convenience so that they do not have to hold
216 * a reference to a private pool instance.
217 */
218VALUE DescriptorPool_generated_pool(VALUE _self) {
219 return generated_pool;
220}
221
222// -----------------------------------------------------------------------------
223// Descriptor.
224// -----------------------------------------------------------------------------
225
226DEFINE_CLASS(Descriptor, "Google::Protobuf::Descriptor");
227
228void Descriptor_mark(void* _self) {
229 Descriptor* self = _self;
230 rb_gc_mark(self->klass);
Chris Fallin4c922892015-01-09 15:29:45 -0800231 rb_gc_mark(self->typeclass_references);
Chris Fallin973f4252014-11-18 14:19:58 -0800232}
233
234void Descriptor_free(void* _self) {
235 Descriptor* self = _self;
236 upb_msgdef_unref(self->msgdef, &self->msgdef);
237 if (self->layout) {
238 free_layout(self->layout);
239 }
240 if (self->fill_handlers) {
241 upb_handlers_unref(self->fill_handlers, &self->fill_handlers);
242 }
243 if (self->fill_method) {
244 upb_pbdecodermethod_unref(self->fill_method, &self->fill_method);
245 }
Josh Haberman78da6662016-01-13 19:05:43 -0800246 if (self->json_fill_method) {
247 upb_json_parsermethod_unref(self->json_fill_method,
248 &self->json_fill_method);
249 }
Chris Fallin973f4252014-11-18 14:19:58 -0800250 if (self->pb_serialize_handlers) {
251 upb_handlers_unref(self->pb_serialize_handlers,
252 &self->pb_serialize_handlers);
253 }
254 if (self->json_serialize_handlers) {
Chris Falline9abbd22015-04-13 14:01:54 -0700255 upb_handlers_unref(self->json_serialize_handlers,
Chris Fallin973f4252014-11-18 14:19:58 -0800256 &self->json_serialize_handlers);
257 }
258 xfree(self);
259}
260
261/*
262 * call-seq:
263 * Descriptor.new => descriptor
264 *
265 * Creates a new, empty, message type descriptor. At a minimum, its name must be
266 * set before it is added to a pool. It cannot be used to create messages until
267 * it is added to a pool, after which it becomes immutable (as part of a
268 * finalization process).
269 */
270VALUE Descriptor_alloc(VALUE klass) {
271 Descriptor* self = ALLOC(Descriptor);
272 VALUE ret = TypedData_Wrap_Struct(klass, &_Descriptor_type, self);
273 self->msgdef = upb_msgdef_new(&self->msgdef);
274 self->klass = Qnil;
275 self->layout = NULL;
276 self->fill_handlers = NULL;
277 self->fill_method = NULL;
Josh Haberman78da6662016-01-13 19:05:43 -0800278 self->json_fill_method = NULL;
Chris Fallin973f4252014-11-18 14:19:58 -0800279 self->pb_serialize_handlers = NULL;
280 self->json_serialize_handlers = NULL;
Chris Fallin4c922892015-01-09 15:29:45 -0800281 self->typeclass_references = rb_ary_new();
Chris Fallin973f4252014-11-18 14:19:58 -0800282 return ret;
283}
284
285void Descriptor_register(VALUE module) {
286 VALUE klass = rb_define_class_under(
287 module, "Descriptor", rb_cObject);
288 rb_define_alloc_func(klass, Descriptor_alloc);
289 rb_define_method(klass, "each", Descriptor_each, 0);
290 rb_define_method(klass, "lookup", Descriptor_lookup, 1);
291 rb_define_method(klass, "add_field", Descriptor_add_field, 1);
Chris Fallinfcd88892015-01-13 18:14:39 -0800292 rb_define_method(klass, "add_oneof", Descriptor_add_oneof, 1);
Chris Falline1b7d382015-01-14 17:14:05 -0800293 rb_define_method(klass, "each_oneof", Descriptor_each_oneof, 0);
Chris Fallinfcd88892015-01-13 18:14:39 -0800294 rb_define_method(klass, "lookup_oneof", Descriptor_lookup_oneof, 1);
Chris Fallin973f4252014-11-18 14:19:58 -0800295 rb_define_method(klass, "msgclass", Descriptor_msgclass, 0);
296 rb_define_method(klass, "name", Descriptor_name, 0);
297 rb_define_method(klass, "name=", Descriptor_name_set, 1);
298 rb_include_module(klass, rb_mEnumerable);
299 cDescriptor = klass;
300 rb_gc_register_address(&cDescriptor);
301}
302
303/*
304 * call-seq:
305 * Descriptor.name => name
306 *
307 * Returns the name of this message type as a fully-qualfied string (e.g.,
308 * My.Package.MessageType).
309 */
310VALUE Descriptor_name(VALUE _self) {
311 DEFINE_SELF(Descriptor, self, _self);
312 return rb_str_maybe_null(upb_msgdef_fullname(self->msgdef));
313}
314
315/*
316 * call-seq:
317 * Descriptor.name = name
318 *
319 * Assigns a name to this message type. The descriptor must not have been added
320 * to a pool yet.
321 */
322VALUE Descriptor_name_set(VALUE _self, VALUE str) {
323 DEFINE_SELF(Descriptor, self, _self);
324 upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
325 const char* name = get_str(str);
326 CHECK_UPB(
327 upb_msgdef_setfullname(mut_def, name, &status),
328 "Error setting Descriptor name");
329 return Qnil;
330}
331
332/*
333 * call-seq:
334 * Descriptor.each(&block)
335 *
336 * Iterates over fields in this message type, yielding to the block on each one.
337 */
338VALUE Descriptor_each(VALUE _self) {
339 DEFINE_SELF(Descriptor, self, _self);
340
Chris Fallinfcd88892015-01-13 18:14:39 -0800341 upb_msg_field_iter it;
342 for (upb_msg_field_begin(&it, self->msgdef);
343 !upb_msg_field_done(&it);
344 upb_msg_field_next(&it)) {
Chris Fallin973f4252014-11-18 14:19:58 -0800345 const upb_fielddef* field = upb_msg_iter_field(&it);
346 VALUE obj = get_def_obj(field);
347 rb_yield(obj);
348 }
349 return Qnil;
350}
351
352/*
353 * call-seq:
354 * Descriptor.lookup(name) => FieldDescriptor
355 *
356 * Returns the field descriptor for the field with the given name, if present,
357 * or nil if none.
358 */
359VALUE Descriptor_lookup(VALUE _self, VALUE name) {
360 DEFINE_SELF(Descriptor, self, _self);
361 const char* s = get_str(name);
362 const upb_fielddef* field = upb_msgdef_ntofz(self->msgdef, s);
363 if (field == NULL) {
364 return Qnil;
365 }
366 return get_def_obj(field);
367}
368
369/*
370 * call-seq:
371 * Descriptor.add_field(field) => nil
372 *
Chris Fallinfcd88892015-01-13 18:14:39 -0800373 * Adds the given FieldDescriptor to this message type. This descriptor must not
Chris Fallin973f4252014-11-18 14:19:58 -0800374 * have been added to a pool yet. Raises an exception if a field with the same
375 * name or number already exists. Sub-type references (e.g. for fields of type
376 * message) are not resolved at this point.
377 */
378VALUE Descriptor_add_field(VALUE _self, VALUE obj) {
379 DEFINE_SELF(Descriptor, self, _self);
380 upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
381 FieldDescriptor* def = ruby_to_FieldDescriptor(obj);
382 upb_fielddef* mut_field_def = check_field_notfrozen(def->fielddef);
383 CHECK_UPB(
384 upb_msgdef_addfield(mut_def, mut_field_def, NULL, &status),
385 "Adding field to Descriptor failed");
386 add_def_obj(def->fielddef, obj);
387 return Qnil;
388}
389
390/*
391 * call-seq:
Chris Fallinfcd88892015-01-13 18:14:39 -0800392 * Descriptor.add_oneof(oneof) => nil
393 *
394 * Adds the given OneofDescriptor to this message type. This descriptor must not
395 * have been added to a pool yet. Raises an exception if a oneof with the same
396 * name already exists, or if any of the oneof's fields' names or numbers
397 * conflict with an existing field in this message type. All fields in the oneof
398 * are added to the message descriptor. Sub-type references (e.g. for fields of
399 * type message) are not resolved at this point.
400 */
401VALUE Descriptor_add_oneof(VALUE _self, VALUE obj) {
402 DEFINE_SELF(Descriptor, self, _self);
403 upb_msgdef* mut_def = check_msg_notfrozen(self->msgdef);
404 OneofDescriptor* def = ruby_to_OneofDescriptor(obj);
405 upb_oneofdef* mut_oneof_def = check_oneof_notfrozen(def->oneofdef);
406 CHECK_UPB(
407 upb_msgdef_addoneof(mut_def, mut_oneof_def, NULL, &status),
408 "Adding oneof to Descriptor failed");
409 add_def_obj(def->oneofdef, obj);
410 return Qnil;
411}
412
413/*
414 * call-seq:
Chris Falline1b7d382015-01-14 17:14:05 -0800415 * Descriptor.each_oneof(&block) => nil
Chris Fallinfcd88892015-01-13 18:14:39 -0800416 *
Chris Falline1b7d382015-01-14 17:14:05 -0800417 * Invokes the given block for each oneof in this message type, passing the
418 * corresponding OneofDescriptor.
Chris Fallinfcd88892015-01-13 18:14:39 -0800419 */
Chris Falline1b7d382015-01-14 17:14:05 -0800420VALUE Descriptor_each_oneof(VALUE _self) {
Chris Fallinfcd88892015-01-13 18:14:39 -0800421 DEFINE_SELF(Descriptor, self, _self);
422
Chris Fallinfcd88892015-01-13 18:14:39 -0800423 upb_msg_oneof_iter it;
424 for (upb_msg_oneof_begin(&it, self->msgdef);
425 !upb_msg_oneof_done(&it);
426 upb_msg_oneof_next(&it)) {
427 const upb_oneofdef* oneof = upb_msg_iter_oneof(&it);
428 VALUE obj = get_def_obj(oneof);
Chris Falline1b7d382015-01-14 17:14:05 -0800429 rb_yield(obj);
Chris Fallinfcd88892015-01-13 18:14:39 -0800430 }
Chris Falline1b7d382015-01-14 17:14:05 -0800431 return Qnil;
Chris Fallinfcd88892015-01-13 18:14:39 -0800432}
433
434/*
435 * call-seq:
436 * Descriptor.lookup_oneof(name) => OneofDescriptor
437 *
438 * Returns the oneof descriptor for the oneof with the given name, if present,
439 * or nil if none.
440 */
441VALUE Descriptor_lookup_oneof(VALUE _self, VALUE name) {
442 DEFINE_SELF(Descriptor, self, _self);
443 const char* s = get_str(name);
444 const upb_oneofdef* oneof = upb_msgdef_ntooz(self->msgdef, s);
445 if (oneof == NULL) {
446 return Qnil;
447 }
448 return get_def_obj(oneof);
449}
450
451/*
452 * call-seq:
Chris Fallin973f4252014-11-18 14:19:58 -0800453 * Descriptor.msgclass => message_klass
454 *
455 * Returns the Ruby class created for this message type. Valid only once the
456 * message type has been added to a pool.
457 */
458VALUE Descriptor_msgclass(VALUE _self) {
459 DEFINE_SELF(Descriptor, self, _self);
460 if (!upb_def_isfrozen((const upb_def*)self->msgdef)) {
461 rb_raise(rb_eRuntimeError,
462 "Cannot fetch message class from a Descriptor not yet in a pool.");
463 }
464 if (self->klass == Qnil) {
465 self->klass = build_class_from_descriptor(self);
466 }
467 return self->klass;
468}
469
470// -----------------------------------------------------------------------------
471// FieldDescriptor.
472// -----------------------------------------------------------------------------
473
474DEFINE_CLASS(FieldDescriptor, "Google::Protobuf::FieldDescriptor");
475
476void FieldDescriptor_mark(void* _self) {
477}
478
479void FieldDescriptor_free(void* _self) {
480 FieldDescriptor* self = _self;
481 upb_fielddef_unref(self->fielddef, &self->fielddef);
482 xfree(self);
483}
484
485/*
486 * call-seq:
487 * FieldDescriptor.new => field
488 *
489 * Returns a new field descriptor. Its name, type, etc. must be set before it is
490 * added to a message type.
491 */
492VALUE FieldDescriptor_alloc(VALUE klass) {
493 FieldDescriptor* self = ALLOC(FieldDescriptor);
494 VALUE ret = TypedData_Wrap_Struct(klass, &_FieldDescriptor_type, self);
495 upb_fielddef* fielddef = upb_fielddef_new(&self->fielddef);
496 upb_fielddef_setpacked(fielddef, false);
497 self->fielddef = fielddef;
498 return ret;
499}
500
501void FieldDescriptor_register(VALUE module) {
502 VALUE klass = rb_define_class_under(
503 module, "FieldDescriptor", rb_cObject);
504 rb_define_alloc_func(klass, FieldDescriptor_alloc);
505 rb_define_method(klass, "name", FieldDescriptor_name, 0);
506 rb_define_method(klass, "name=", FieldDescriptor_name_set, 1);
507 rb_define_method(klass, "type", FieldDescriptor_type, 0);
508 rb_define_method(klass, "type=", FieldDescriptor_type_set, 1);
509 rb_define_method(klass, "label", FieldDescriptor_label, 0);
510 rb_define_method(klass, "label=", FieldDescriptor_label_set, 1);
511 rb_define_method(klass, "number", FieldDescriptor_number, 0);
512 rb_define_method(klass, "number=", FieldDescriptor_number_set, 1);
513 rb_define_method(klass, "submsg_name", FieldDescriptor_submsg_name, 0);
514 rb_define_method(klass, "submsg_name=", FieldDescriptor_submsg_name_set, 1);
515 rb_define_method(klass, "subtype", FieldDescriptor_subtype, 0);
516 rb_define_method(klass, "get", FieldDescriptor_get, 1);
517 rb_define_method(klass, "set", FieldDescriptor_set, 2);
518 cFieldDescriptor = klass;
519 rb_gc_register_address(&cFieldDescriptor);
520}
521
522/*
523 * call-seq:
524 * FieldDescriptor.name => name
525 *
526 * Returns the name of this field.
527 */
528VALUE FieldDescriptor_name(VALUE _self) {
529 DEFINE_SELF(FieldDescriptor, self, _self);
530 return rb_str_maybe_null(upb_fielddef_name(self->fielddef));
531}
532
533/*
534 * call-seq:
535 * FieldDescriptor.name = name
536 *
537 * Sets the name of this field. Cannot be called once the containing message
538 * type, if any, is added to a pool.
539 */
540VALUE FieldDescriptor_name_set(VALUE _self, VALUE str) {
541 DEFINE_SELF(FieldDescriptor, self, _self);
542 upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
543 const char* name = get_str(str);
544 CHECK_UPB(upb_fielddef_setname(mut_def, name, &status),
545 "Error setting FieldDescriptor name");
546 return Qnil;
547}
548
549upb_fieldtype_t ruby_to_fieldtype(VALUE type) {
550 if (TYPE(type) != T_SYMBOL) {
551 rb_raise(rb_eArgError, "Expected symbol for field type.");
552 }
553
Chris Fallin973f4252014-11-18 14:19:58 -0800554#define CONVERT(upb, ruby) \
555 if (SYM2ID(type) == rb_intern( # ruby )) { \
Josh Haberman181c7f22015-07-15 11:05:10 -0700556 return UPB_TYPE_ ## upb; \
Chris Fallin973f4252014-11-18 14:19:58 -0800557 }
558
559 CONVERT(FLOAT, float);
560 CONVERT(DOUBLE, double);
561 CONVERT(BOOL, bool);
562 CONVERT(STRING, string);
563 CONVERT(BYTES, bytes);
564 CONVERT(MESSAGE, message);
565 CONVERT(ENUM, enum);
566 CONVERT(INT32, int32);
567 CONVERT(INT64, int64);
568 CONVERT(UINT32, uint32);
569 CONVERT(UINT64, uint64);
570
571#undef CONVERT
572
Josh Habermane3ce4512015-06-09 11:08:25 -0700573 rb_raise(rb_eArgError, "Unknown field type.");
574 return 0;
Chris Fallin973f4252014-11-18 14:19:58 -0800575}
576
577VALUE fieldtype_to_ruby(upb_fieldtype_t type) {
578 switch (type) {
579#define CONVERT(upb, ruby) \
580 case UPB_TYPE_ ## upb : return ID2SYM(rb_intern( # ruby ));
581 CONVERT(FLOAT, float);
582 CONVERT(DOUBLE, double);
583 CONVERT(BOOL, bool);
584 CONVERT(STRING, string);
585 CONVERT(BYTES, bytes);
586 CONVERT(MESSAGE, message);
587 CONVERT(ENUM, enum);
588 CONVERT(INT32, int32);
589 CONVERT(INT64, int64);
590 CONVERT(UINT32, uint32);
591 CONVERT(UINT64, uint64);
592#undef CONVERT
593 }
594 return Qnil;
595}
596
Josh Haberman181c7f22015-07-15 11:05:10 -0700597upb_descriptortype_t ruby_to_descriptortype(VALUE type) {
598 if (TYPE(type) != T_SYMBOL) {
599 rb_raise(rb_eArgError, "Expected symbol for field type.");
600 }
601
602#define CONVERT(upb, ruby) \
603 if (SYM2ID(type) == rb_intern( # ruby )) { \
604 return UPB_DESCRIPTOR_TYPE_ ## upb; \
605 }
606
607 CONVERT(FLOAT, float);
608 CONVERT(DOUBLE, double);
609 CONVERT(BOOL, bool);
610 CONVERT(STRING, string);
611 CONVERT(BYTES, bytes);
612 CONVERT(MESSAGE, message);
613 CONVERT(GROUP, group);
614 CONVERT(ENUM, enum);
615 CONVERT(INT32, int32);
616 CONVERT(INT64, int64);
617 CONVERT(UINT32, uint32);
618 CONVERT(UINT64, uint64);
619 CONVERT(SINT32, sint32);
620 CONVERT(SINT64, sint64);
621 CONVERT(FIXED32, fixed32);
622 CONVERT(FIXED64, fixed64);
623 CONVERT(SFIXED32, sfixed32);
624 CONVERT(SFIXED64, sfixed64);
625
626#undef CONVERT
627
628 rb_raise(rb_eArgError, "Unknown field type.");
629 return 0;
630}
631
632VALUE descriptortype_to_ruby(upb_descriptortype_t type) {
633 switch (type) {
634#define CONVERT(upb, ruby) \
635 case UPB_DESCRIPTOR_TYPE_ ## upb : return ID2SYM(rb_intern( # ruby ));
636 CONVERT(FLOAT, float);
637 CONVERT(DOUBLE, double);
638 CONVERT(BOOL, bool);
639 CONVERT(STRING, string);
640 CONVERT(BYTES, bytes);
641 CONVERT(MESSAGE, message);
642 CONVERT(GROUP, group);
643 CONVERT(ENUM, enum);
644 CONVERT(INT32, int32);
645 CONVERT(INT64, int64);
646 CONVERT(UINT32, uint32);
647 CONVERT(UINT64, uint64);
648 CONVERT(SINT32, sint32);
649 CONVERT(SINT64, sint64);
650 CONVERT(FIXED32, fixed32);
651 CONVERT(FIXED64, fixed64);
652 CONVERT(SFIXED32, sfixed32);
653 CONVERT(SFIXED64, sfixed64);
654#undef CONVERT
655 }
656 return Qnil;
657}
658
Chris Fallin973f4252014-11-18 14:19:58 -0800659/*
660 * call-seq:
661 * FieldDescriptor.type => type
662 *
663 * Returns this field's type, as a Ruby symbol, or nil if not yet set.
664 *
665 * Valid field types are:
666 * :int32, :int64, :uint32, :uint64, :float, :double, :bool, :string,
667 * :bytes, :message.
668 */
669VALUE FieldDescriptor_type(VALUE _self) {
670 DEFINE_SELF(FieldDescriptor, self, _self);
671 if (!upb_fielddef_typeisset(self->fielddef)) {
672 return Qnil;
673 }
Josh Haberman181c7f22015-07-15 11:05:10 -0700674 return descriptortype_to_ruby(upb_fielddef_descriptortype(self->fielddef));
Chris Fallin973f4252014-11-18 14:19:58 -0800675}
676
677/*
678 * call-seq:
679 * FieldDescriptor.type = type
680 *
681 * Sets this field's type. Cannot be called if field is part of a message type
682 * already in a pool.
683 */
684VALUE FieldDescriptor_type_set(VALUE _self, VALUE type) {
685 DEFINE_SELF(FieldDescriptor, self, _self);
686 upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
Josh Haberman181c7f22015-07-15 11:05:10 -0700687 upb_fielddef_setdescriptortype(mut_def, ruby_to_descriptortype(type));
Chris Fallin973f4252014-11-18 14:19:58 -0800688 return Qnil;
689}
690
691/*
692 * call-seq:
693 * FieldDescriptor.label => label
694 *
695 * Returns this field's label (i.e., plurality), as a Ruby symbol.
696 *
697 * Valid field labels are:
698 * :optional, :repeated
699 */
700VALUE FieldDescriptor_label(VALUE _self) {
701 DEFINE_SELF(FieldDescriptor, self, _self);
702 switch (upb_fielddef_label(self->fielddef)) {
703#define CONVERT(upb, ruby) \
704 case UPB_LABEL_ ## upb : return ID2SYM(rb_intern( # ruby ));
705
706 CONVERT(OPTIONAL, optional);
707 CONVERT(REQUIRED, required);
708 CONVERT(REPEATED, repeated);
709
710#undef CONVERT
711 }
712
713 return Qnil;
714}
715
716/*
717 * call-seq:
718 * FieldDescriptor.label = label
719 *
720 * Sets the label on this field. Cannot be called if field is part of a message
721 * type already in a pool.
722 */
723VALUE FieldDescriptor_label_set(VALUE _self, VALUE label) {
724 DEFINE_SELF(FieldDescriptor, self, _self);
725 upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
Josh Habermana1daeab2015-07-10 11:56:06 -0700726 upb_label_t upb_label = -1;
727 bool converted = false;
728
Chris Fallin973f4252014-11-18 14:19:58 -0800729 if (TYPE(label) != T_SYMBOL) {
730 rb_raise(rb_eArgError, "Expected symbol for field label.");
731 }
732
Chris Fallin973f4252014-11-18 14:19:58 -0800733#define CONVERT(upb, ruby) \
734 if (SYM2ID(label) == rb_intern( # ruby )) { \
735 upb_label = UPB_LABEL_ ## upb; \
Josh Habermane3ce4512015-06-09 11:08:25 -0700736 converted = true; \
Chris Fallin973f4252014-11-18 14:19:58 -0800737 }
738
739 CONVERT(OPTIONAL, optional);
740 CONVERT(REQUIRED, required);
741 CONVERT(REPEATED, repeated);
742
743#undef CONVERT
744
Josh Habermane3ce4512015-06-09 11:08:25 -0700745 if (!converted) {
Chris Fallin973f4252014-11-18 14:19:58 -0800746 rb_raise(rb_eArgError, "Unknown field label.");
747 }
748
749 upb_fielddef_setlabel(mut_def, upb_label);
750
751 return Qnil;
752}
753
754/*
755 * call-seq:
756 * FieldDescriptor.number => number
757 *
758 * Returns the tag number for this field.
759 */
760VALUE FieldDescriptor_number(VALUE _self) {
761 DEFINE_SELF(FieldDescriptor, self, _self);
762 return INT2NUM(upb_fielddef_number(self->fielddef));
763}
764
765/*
766 * call-seq:
767 * FieldDescriptor.number = number
768 *
769 * Sets the tag number for this field. Cannot be called if field is part of a
770 * message type already in a pool.
771 */
772VALUE FieldDescriptor_number_set(VALUE _self, VALUE number) {
773 DEFINE_SELF(FieldDescriptor, self, _self);
774 upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
775 CHECK_UPB(upb_fielddef_setnumber(mut_def, NUM2INT(number), &status),
776 "Error setting field number");
777 return Qnil;
778}
779
780/*
781 * call-seq:
782 * FieldDescriptor.submsg_name => submsg_name
783 *
784 * Returns the name of the message or enum type corresponding to this field, if
785 * it is a message or enum field (respectively), or nil otherwise. This type
786 * name will be resolved within the context of the pool to which the containing
787 * message type is added.
788 */
789VALUE FieldDescriptor_submsg_name(VALUE _self) {
790 DEFINE_SELF(FieldDescriptor, self, _self);
791 if (!upb_fielddef_hassubdef(self->fielddef)) {
792 return Qnil;
793 }
794 return rb_str_maybe_null(upb_fielddef_subdefname(self->fielddef));
795}
796
797/*
798 * call-seq:
799 * FieldDescriptor.submsg_name = submsg_name
800 *
801 * Sets the name of the message or enum type corresponding to this field, if it
802 * is a message or enum field (respectively). This type name will be resolved
803 * within the context of the pool to which the containing message type is added.
804 * Cannot be called on field that are not of message or enum type, or on fields
805 * that are part of a message type already added to a pool.
806 */
807VALUE FieldDescriptor_submsg_name_set(VALUE _self, VALUE value) {
808 DEFINE_SELF(FieldDescriptor, self, _self);
809 upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
Josh Habermana1daeab2015-07-10 11:56:06 -0700810 const char* str = get_str(value);
Chris Fallin973f4252014-11-18 14:19:58 -0800811 if (!upb_fielddef_hassubdef(self->fielddef)) {
812 rb_raise(rb_eTypeError, "FieldDescriptor does not have subdef.");
813 }
Chris Fallin973f4252014-11-18 14:19:58 -0800814 CHECK_UPB(upb_fielddef_setsubdefname(mut_def, str, &status),
815 "Error setting submessage name");
816 return Qnil;
817}
818
819/*
820 * call-seq:
821 * FieldDescriptor.subtype => message_or_enum_descriptor
822 *
823 * Returns the message or enum descriptor corresponding to this field's type if
824 * it is a message or enum field, respectively, or nil otherwise. Cannot be
825 * called *until* the containing message type is added to a pool (and thus
826 * resolved).
827 */
828VALUE FieldDescriptor_subtype(VALUE _self) {
829 DEFINE_SELF(FieldDescriptor, self, _self);
Josh Habermana1daeab2015-07-10 11:56:06 -0700830 const upb_def* def;
831
Chris Fallin973f4252014-11-18 14:19:58 -0800832 if (!upb_fielddef_hassubdef(self->fielddef)) {
833 return Qnil;
834 }
Josh Habermana1daeab2015-07-10 11:56:06 -0700835 def = upb_fielddef_subdef(self->fielddef);
Chris Fallin973f4252014-11-18 14:19:58 -0800836 if (def == NULL) {
837 return Qnil;
838 }
839 return get_def_obj(def);
840}
841
842/*
843 * call-seq:
844 * FieldDescriptor.get(message) => value
845 *
846 * Returns the value set for this field on the given message. Raises an
847 * exception if message is of the wrong type.
848 */
849VALUE FieldDescriptor_get(VALUE _self, VALUE msg_rb) {
850 DEFINE_SELF(FieldDescriptor, self, _self);
851 MessageHeader* msg;
852 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
853 if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
854 rb_raise(rb_eTypeError, "get method called on wrong message type");
855 }
856 return layout_get(msg->descriptor->layout, Message_data(msg), self->fielddef);
857}
858
859/*
860 * call-seq:
861 * FieldDescriptor.set(message, value)
862 *
863 * Sets the value corresponding to this field to the given value on the given
864 * message. Raises an exception if message is of the wrong type. Performs the
865 * ordinary type-checks for field setting.
866 */
867VALUE FieldDescriptor_set(VALUE _self, VALUE msg_rb, VALUE value) {
868 DEFINE_SELF(FieldDescriptor, self, _self);
869 MessageHeader* msg;
870 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
871 if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
872 rb_raise(rb_eTypeError, "set method called on wrong message type");
873 }
874 layout_set(msg->descriptor->layout, Message_data(msg), self->fielddef, value);
875 return Qnil;
876}
877
878// -----------------------------------------------------------------------------
Chris Fallinfcd88892015-01-13 18:14:39 -0800879// OneofDescriptor.
880// -----------------------------------------------------------------------------
881
882DEFINE_CLASS(OneofDescriptor, "Google::Protobuf::OneofDescriptor");
883
884void OneofDescriptor_mark(void* _self) {
885}
886
887void OneofDescriptor_free(void* _self) {
888 OneofDescriptor* self = _self;
889 upb_oneofdef_unref(self->oneofdef, &self->oneofdef);
890 xfree(self);
891}
892
893/*
894 * call-seq:
895 * OneofDescriptor.new => oneof_descriptor
896 *
897 * Creates a new, empty, oneof descriptor. The oneof may only be modified prior
898 * to being added to a message descriptor which is subsequently added to a pool.
899 */
900VALUE OneofDescriptor_alloc(VALUE klass) {
901 OneofDescriptor* self = ALLOC(OneofDescriptor);
902 VALUE ret = TypedData_Wrap_Struct(klass, &_OneofDescriptor_type, self);
903 self->oneofdef = upb_oneofdef_new(&self->oneofdef);
904 return ret;
905}
906
907void OneofDescriptor_register(VALUE module) {
908 VALUE klass = rb_define_class_under(
909 module, "OneofDescriptor", rb_cObject);
910 rb_define_alloc_func(klass, OneofDescriptor_alloc);
911 rb_define_method(klass, "name", OneofDescriptor_name, 0);
912 rb_define_method(klass, "name=", OneofDescriptor_name_set, 1);
913 rb_define_method(klass, "add_field", OneofDescriptor_add_field, 1);
914 rb_define_method(klass, "each", OneofDescriptor_each, 0);
915 rb_include_module(klass, rb_mEnumerable);
916 cOneofDescriptor = klass;
917 rb_gc_register_address(&cOneofDescriptor);
918}
919
920/*
921 * call-seq:
922 * OneofDescriptor.name => name
923 *
924 * Returns the name of this oneof.
925 */
926VALUE OneofDescriptor_name(VALUE _self) {
927 DEFINE_SELF(OneofDescriptor, self, _self);
928 return rb_str_maybe_null(upb_oneofdef_name(self->oneofdef));
929}
930
931/*
932 * call-seq:
933 * OneofDescriptor.name = name
934 *
935 * Sets a new name for this oneof. The oneof must not have been added to a
936 * message descriptor yet.
937 */
938VALUE OneofDescriptor_name_set(VALUE _self, VALUE value) {
939 DEFINE_SELF(OneofDescriptor, self, _self);
940 upb_oneofdef* mut_def = check_oneof_notfrozen(self->oneofdef);
941 const char* str = get_str(value);
942 CHECK_UPB(upb_oneofdef_setname(mut_def, str, &status),
943 "Error setting oneof name");
944 return Qnil;
945}
946
947/*
948 * call-seq:
949 * OneofDescriptor.add_field(field) => nil
950 *
951 * Adds a field to this oneof. The field may have been added to this oneof in
952 * the past, or the message to which this oneof belongs (if any), but may not
953 * have already been added to any other oneof or message. Otherwise, an
954 * exception is raised.
955 *
956 * All fields added to the oneof via this method will be automatically added to
957 * the message to which this oneof belongs, if it belongs to one currently, or
958 * else will be added to any message to which the oneof is later added at the
959 * time that it is added.
960 */
961VALUE OneofDescriptor_add_field(VALUE _self, VALUE obj) {
962 DEFINE_SELF(OneofDescriptor, self, _self);
963 upb_oneofdef* mut_def = check_oneof_notfrozen(self->oneofdef);
964 FieldDescriptor* def = ruby_to_FieldDescriptor(obj);
965 upb_fielddef* mut_field_def = check_field_notfrozen(def->fielddef);
966 CHECK_UPB(
967 upb_oneofdef_addfield(mut_def, mut_field_def, NULL, &status),
968 "Adding field to OneofDescriptor failed");
969 add_def_obj(def->fielddef, obj);
970 return Qnil;
971}
972
973/*
974 * call-seq:
975 * OneofDescriptor.each(&block) => nil
976 *
977 * Iterates through fields in this oneof, yielding to the block on each one.
978 */
979VALUE OneofDescriptor_each(VALUE _self, VALUE field) {
980 DEFINE_SELF(OneofDescriptor, self, _self);
981 upb_oneof_iter it;
982 for (upb_oneof_begin(&it, self->oneofdef);
983 !upb_oneof_done(&it);
984 upb_oneof_next(&it)) {
985 const upb_fielddef* f = upb_oneof_iter_field(&it);
986 VALUE obj = get_def_obj(f);
987 rb_yield(obj);
988 }
989 return Qnil;
990}
991
992// -----------------------------------------------------------------------------
Chris Fallin973f4252014-11-18 14:19:58 -0800993// EnumDescriptor.
994// -----------------------------------------------------------------------------
995
996DEFINE_CLASS(EnumDescriptor, "Google::Protobuf::EnumDescriptor");
997
998void EnumDescriptor_mark(void* _self) {
999 EnumDescriptor* self = _self;
1000 rb_gc_mark(self->module);
1001}
1002
1003void EnumDescriptor_free(void* _self) {
1004 EnumDescriptor* self = _self;
1005 upb_enumdef_unref(self->enumdef, &self->enumdef);
1006 xfree(self);
1007}
1008
1009/*
1010 * call-seq:
1011 * EnumDescriptor.new => enum_descriptor
1012 *
1013 * Creates a new, empty, enum descriptor. Must be added to a pool before the
1014 * enum type can be used. The enum type may only be modified prior to adding to
1015 * a pool.
1016 */
1017VALUE EnumDescriptor_alloc(VALUE klass) {
1018 EnumDescriptor* self = ALLOC(EnumDescriptor);
1019 VALUE ret = TypedData_Wrap_Struct(klass, &_EnumDescriptor_type, self);
1020 self->enumdef = upb_enumdef_new(&self->enumdef);
1021 self->module = Qnil;
1022 return ret;
1023}
1024
1025void EnumDescriptor_register(VALUE module) {
1026 VALUE klass = rb_define_class_under(
1027 module, "EnumDescriptor", rb_cObject);
1028 rb_define_alloc_func(klass, EnumDescriptor_alloc);
1029 rb_define_method(klass, "name", EnumDescriptor_name, 0);
1030 rb_define_method(klass, "name=", EnumDescriptor_name_set, 1);
1031 rb_define_method(klass, "add_value", EnumDescriptor_add_value, 2);
1032 rb_define_method(klass, "lookup_name", EnumDescriptor_lookup_name, 1);
1033 rb_define_method(klass, "lookup_value", EnumDescriptor_lookup_value, 1);
1034 rb_define_method(klass, "each", EnumDescriptor_each, 0);
1035 rb_define_method(klass, "enummodule", EnumDescriptor_enummodule, 0);
1036 rb_include_module(klass, rb_mEnumerable);
1037 cEnumDescriptor = klass;
1038 rb_gc_register_address(&cEnumDescriptor);
1039}
1040
1041/*
1042 * call-seq:
1043 * EnumDescriptor.name => name
1044 *
1045 * Returns the name of this enum type.
1046 */
1047VALUE EnumDescriptor_name(VALUE _self) {
1048 DEFINE_SELF(EnumDescriptor, self, _self);
1049 return rb_str_maybe_null(upb_enumdef_fullname(self->enumdef));
1050}
1051
1052/*
1053 * call-seq:
1054 * EnumDescriptor.name = name
1055 *
1056 * Sets the name of this enum type. Cannot be called if the enum type has
1057 * already been added to a pool.
1058 */
1059VALUE EnumDescriptor_name_set(VALUE _self, VALUE str) {
1060 DEFINE_SELF(EnumDescriptor, self, _self);
1061 upb_enumdef* mut_def = check_enum_notfrozen(self->enumdef);
1062 const char* name = get_str(str);
1063 CHECK_UPB(upb_enumdef_setfullname(mut_def, name, &status),
1064 "Error setting EnumDescriptor name");
1065 return Qnil;
1066}
1067
1068/*
1069 * call-seq:
1070 * EnumDescriptor.add_value(key, value)
1071 *
1072 * Adds a new key => value mapping to this enum type. Key must be given as a
1073 * Ruby symbol. Cannot be called if the enum type has already been added to a
1074 * pool. Will raise an exception if the key or value is already in use.
1075 */
1076VALUE EnumDescriptor_add_value(VALUE _self, VALUE name, VALUE number) {
1077 DEFINE_SELF(EnumDescriptor, self, _self);
1078 upb_enumdef* mut_def = check_enum_notfrozen(self->enumdef);
1079 const char* name_str = rb_id2name(SYM2ID(name));
1080 int32_t val = NUM2INT(number);
1081 CHECK_UPB(upb_enumdef_addval(mut_def, name_str, val, &status),
1082 "Error adding value to enum");
1083 return Qnil;
1084}
1085
1086/*
1087 * call-seq:
1088 * EnumDescriptor.lookup_name(name) => value
1089 *
1090 * Returns the numeric value corresponding to the given key name (as a Ruby
1091 * symbol), or nil if none.
1092 */
1093VALUE EnumDescriptor_lookup_name(VALUE _self, VALUE name) {
1094 DEFINE_SELF(EnumDescriptor, self, _self);
1095 const char* name_str= rb_id2name(SYM2ID(name));
1096 int32_t val = 0;
1097 if (upb_enumdef_ntoiz(self->enumdef, name_str, &val)) {
1098 return INT2NUM(val);
1099 } else {
1100 return Qnil;
1101 }
1102}
1103
1104/*
1105 * call-seq:
1106 * EnumDescriptor.lookup_value(name) => value
1107 *
1108 * Returns the key name (as a Ruby symbol) corresponding to the integer value,
1109 * or nil if none.
1110 */
1111VALUE EnumDescriptor_lookup_value(VALUE _self, VALUE number) {
1112 DEFINE_SELF(EnumDescriptor, self, _self);
1113 int32_t val = NUM2INT(number);
1114 const char* name = upb_enumdef_iton(self->enumdef, val);
1115 if (name != NULL) {
1116 return ID2SYM(rb_intern(name));
1117 } else {
1118 return Qnil;
1119 }
1120}
1121
1122/*
1123 * call-seq:
1124 * EnumDescriptor.each(&block)
1125 *
1126 * Iterates over key => value mappings in this enum's definition, yielding to
1127 * the block with (key, value) arguments for each one.
1128 */
1129VALUE EnumDescriptor_each(VALUE _self) {
1130 DEFINE_SELF(EnumDescriptor, self, _self);
1131
1132 upb_enum_iter it;
1133 for (upb_enum_begin(&it, self->enumdef);
1134 !upb_enum_done(&it);
1135 upb_enum_next(&it)) {
1136 VALUE key = ID2SYM(rb_intern(upb_enum_iter_name(&it)));
1137 VALUE number = INT2NUM(upb_enum_iter_number(&it));
1138 rb_yield_values(2, key, number);
1139 }
1140
1141 return Qnil;
1142}
1143
1144/*
1145 * call-seq:
1146 * EnumDescriptor.enummodule => module
1147 *
1148 * Returns the Ruby module corresponding to this enum type. Cannot be called
1149 * until the enum descriptor has been added to a pool.
1150 */
1151VALUE EnumDescriptor_enummodule(VALUE _self) {
1152 DEFINE_SELF(EnumDescriptor, self, _self);
1153 if (!upb_def_isfrozen((const upb_def*)self->enumdef)) {
1154 rb_raise(rb_eRuntimeError,
1155 "Cannot fetch enum module from an EnumDescriptor not yet "
1156 "in a pool.");
1157 }
1158 if (self->module == Qnil) {
1159 self->module = build_module_from_enumdesc(self);
1160 }
1161 return self->module;
1162}
1163
1164// -----------------------------------------------------------------------------
1165// MessageBuilderContext.
1166// -----------------------------------------------------------------------------
1167
1168DEFINE_CLASS(MessageBuilderContext,
1169 "Google::Protobuf::Internal::MessageBuilderContext");
1170
1171void MessageBuilderContext_mark(void* _self) {
1172 MessageBuilderContext* self = _self;
1173 rb_gc_mark(self->descriptor);
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001174 rb_gc_mark(self->builder);
Chris Fallin973f4252014-11-18 14:19:58 -08001175}
1176
1177void MessageBuilderContext_free(void* _self) {
1178 MessageBuilderContext* self = _self;
1179 xfree(self);
1180}
1181
1182VALUE MessageBuilderContext_alloc(VALUE klass) {
1183 MessageBuilderContext* self = ALLOC(MessageBuilderContext);
1184 VALUE ret = TypedData_Wrap_Struct(
1185 klass, &_MessageBuilderContext_type, self);
1186 self->descriptor = Qnil;
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001187 self->builder = Qnil;
Chris Fallin973f4252014-11-18 14:19:58 -08001188 return ret;
1189}
1190
1191void MessageBuilderContext_register(VALUE module) {
1192 VALUE klass = rb_define_class_under(
1193 module, "MessageBuilderContext", rb_cObject);
1194 rb_define_alloc_func(klass, MessageBuilderContext_alloc);
1195 rb_define_method(klass, "initialize",
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001196 MessageBuilderContext_initialize, 2);
Chris Fallin973f4252014-11-18 14:19:58 -08001197 rb_define_method(klass, "optional", MessageBuilderContext_optional, -1);
1198 rb_define_method(klass, "required", MessageBuilderContext_required, -1);
1199 rb_define_method(klass, "repeated", MessageBuilderContext_repeated, -1);
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001200 rb_define_method(klass, "map", MessageBuilderContext_map, -1);
Chris Fallinfcd88892015-01-13 18:14:39 -08001201 rb_define_method(klass, "oneof", MessageBuilderContext_oneof, 1);
Chris Fallin973f4252014-11-18 14:19:58 -08001202 cMessageBuilderContext = klass;
1203 rb_gc_register_address(&cMessageBuilderContext);
1204}
1205
1206/*
1207 * call-seq:
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001208 * MessageBuilderContext.new(desc, builder) => context
Chris Fallin973f4252014-11-18 14:19:58 -08001209 *
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001210 * Create a new message builder context around the given message descriptor and
1211 * builder context. This class is intended to serve as a DSL context to be used
1212 * with #instance_eval.
Chris Fallin973f4252014-11-18 14:19:58 -08001213 */
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001214VALUE MessageBuilderContext_initialize(VALUE _self,
1215 VALUE msgdef,
1216 VALUE builder) {
Chris Fallin973f4252014-11-18 14:19:58 -08001217 DEFINE_SELF(MessageBuilderContext, self, _self);
1218 self->descriptor = msgdef;
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001219 self->builder = builder;
Chris Fallin973f4252014-11-18 14:19:58 -08001220 return Qnil;
1221}
1222
1223static VALUE msgdef_add_field(VALUE msgdef,
1224 const char* label, VALUE name,
1225 VALUE type, VALUE number,
1226 VALUE type_class) {
1227 VALUE fielddef = rb_class_new_instance(0, NULL, cFieldDescriptor);
1228 VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
1229
1230 rb_funcall(fielddef, rb_intern("label="), 1, ID2SYM(rb_intern(label)));
1231 rb_funcall(fielddef, rb_intern("name="), 1, name_str);
1232 rb_funcall(fielddef, rb_intern("type="), 1, type);
1233 rb_funcall(fielddef, rb_intern("number="), 1, number);
1234
1235 if (type_class != Qnil) {
1236 if (TYPE(type_class) != T_STRING) {
1237 rb_raise(rb_eArgError, "Expected string for type class");
1238 }
1239 // Make it an absolute type name by prepending a dot.
1240 type_class = rb_str_append(rb_str_new2("."), type_class);
1241 rb_funcall(fielddef, rb_intern("submsg_name="), 1, type_class);
1242 }
1243
1244 rb_funcall(msgdef, rb_intern("add_field"), 1, fielddef);
1245 return fielddef;
1246}
1247
1248/*
1249 * call-seq:
1250 * MessageBuilderContext.optional(name, type, number, type_class = nil)
1251 *
1252 * Defines a new optional field on this message type with the given type, tag
1253 * number, and type class (for message and enum fields). The type must be a Ruby
1254 * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
1255 * string, if present (as accepted by FieldDescriptor#submsg_name=).
1256 */
1257VALUE MessageBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
1258 DEFINE_SELF(MessageBuilderContext, self, _self);
Josh Habermana1daeab2015-07-10 11:56:06 -07001259 VALUE name, type, number, type_class;
Chris Fallin973f4252014-11-18 14:19:58 -08001260
1261 if (argc < 3) {
1262 rb_raise(rb_eArgError, "Expected at least 3 arguments.");
1263 }
Josh Habermana1daeab2015-07-10 11:56:06 -07001264 name = argv[0];
1265 type = argv[1];
1266 number = argv[2];
1267 type_class = (argc > 3) ? argv[3] : Qnil;
Chris Fallin973f4252014-11-18 14:19:58 -08001268
1269 return msgdef_add_field(self->descriptor, "optional",
1270 name, type, number, type_class);
1271}
1272
1273/*
1274 * call-seq:
1275 * MessageBuilderContext.required(name, type, number, type_class = nil)
1276 *
1277 * Defines a new required field on this message type with the given type, tag
1278 * number, and type class (for message and enum fields). The type must be a Ruby
1279 * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
1280 * string, if present (as accepted by FieldDescriptor#submsg_name=).
1281 *
1282 * Proto3 does not have required fields, but this method exists for
1283 * completeness. Any attempt to add a message type with required fields to a
1284 * pool will currently result in an error.
1285 */
1286VALUE MessageBuilderContext_required(int argc, VALUE* argv, VALUE _self) {
1287 DEFINE_SELF(MessageBuilderContext, self, _self);
Josh Habermana1daeab2015-07-10 11:56:06 -07001288 VALUE name, type, number, type_class;
Chris Fallin973f4252014-11-18 14:19:58 -08001289
1290 if (argc < 3) {
1291 rb_raise(rb_eArgError, "Expected at least 3 arguments.");
1292 }
Josh Habermana1daeab2015-07-10 11:56:06 -07001293 name = argv[0];
1294 type = argv[1];
1295 number = argv[2];
1296 type_class = (argc > 3) ? argv[3] : Qnil;
Chris Fallin973f4252014-11-18 14:19:58 -08001297
1298 return msgdef_add_field(self->descriptor, "required",
1299 name, type, number, type_class);
1300}
1301
1302/*
1303 * call-seq:
1304 * MessageBuilderContext.repeated(name, type, number, type_class = nil)
1305 *
1306 * Defines a new repeated field on this message type with the given type, tag
1307 * number, and type class (for message and enum fields). The type must be a Ruby
1308 * symbol (as accepted by FieldDescriptor#type=) and the type_class must be a
1309 * string, if present (as accepted by FieldDescriptor#submsg_name=).
1310 */
1311VALUE MessageBuilderContext_repeated(int argc, VALUE* argv, VALUE _self) {
1312 DEFINE_SELF(MessageBuilderContext, self, _self);
Josh Habermana1daeab2015-07-10 11:56:06 -07001313 VALUE name, type, number, type_class;
Chris Fallin973f4252014-11-18 14:19:58 -08001314
1315 if (argc < 3) {
1316 rb_raise(rb_eArgError, "Expected at least 3 arguments.");
1317 }
Josh Habermana1daeab2015-07-10 11:56:06 -07001318 name = argv[0];
1319 type = argv[1];
1320 number = argv[2];
1321 type_class = (argc > 3) ? argv[3] : Qnil;
Chris Fallin973f4252014-11-18 14:19:58 -08001322
1323 return msgdef_add_field(self->descriptor, "repeated",
1324 name, type, number, type_class);
1325}
1326
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001327/*
1328 * call-seq:
1329 * MessageBuilderContext.map(name, key_type, value_type, number,
1330 * value_type_class = nil)
1331 *
Chris Fallin80276ac2015-01-06 18:01:32 -08001332 * Defines a new map field on this message type with the given key and value
1333 * types, tag number, and type class (for message and enum value types). The key
1334 * type must be :int32/:uint32/:int64/:uint64, :bool, or :string. The value type
1335 * type must be a Ruby symbol (as accepted by FieldDescriptor#type=) and the
1336 * type_class must be a string, if present (as accepted by
1337 * FieldDescriptor#submsg_name=).
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001338 */
1339VALUE MessageBuilderContext_map(int argc, VALUE* argv, VALUE _self) {
1340 DEFINE_SELF(MessageBuilderContext, self, _self);
Josh Habermana1daeab2015-07-10 11:56:06 -07001341 VALUE name, key_type, value_type, number, type_class;
1342 VALUE mapentry_desc, mapentry_desc_name;
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001343
1344 if (argc < 4) {
1345 rb_raise(rb_eArgError, "Expected at least 4 arguments.");
1346 }
Josh Habermana1daeab2015-07-10 11:56:06 -07001347 name = argv[0];
1348 key_type = argv[1];
1349 value_type = argv[2];
1350 number = argv[3];
1351 type_class = (argc > 4) ? argv[4] : Qnil;
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001352
1353 // Validate the key type. We can't accept enums, messages, or floats/doubles
1354 // as map keys. (We exclude these explicitly, and the field-descriptor setter
1355 // below then ensures that the type is one of the remaining valid options.)
1356 if (SYM2ID(key_type) == rb_intern("float") ||
1357 SYM2ID(key_type) == rb_intern("double") ||
1358 SYM2ID(key_type) == rb_intern("enum") ||
1359 SYM2ID(key_type) == rb_intern("message")) {
1360 rb_raise(rb_eArgError,
1361 "Cannot add a map field with a float, double, enum, or message "
1362 "type.");
1363 }
1364
1365 // Create a new message descriptor for the map entry message, and create a
1366 // repeated submessage field here with that type.
Josh Habermana1daeab2015-07-10 11:56:06 -07001367 mapentry_desc = rb_class_new_instance(0, NULL, cDescriptor);
1368 mapentry_desc_name = rb_funcall(self->descriptor, rb_intern("name"), 0);
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001369 mapentry_desc_name = rb_str_cat2(mapentry_desc_name, "_MapEntry_");
1370 mapentry_desc_name = rb_str_cat2(mapentry_desc_name,
1371 rb_id2name(SYM2ID(name)));
1372 Descriptor_name_set(mapentry_desc, mapentry_desc_name);
1373
Josh Habermana1daeab2015-07-10 11:56:06 -07001374 {
1375 // The 'mapentry' attribute has no Ruby setter because we do not want the
1376 // user attempting to DIY the setup below; we want to ensure that the fields
1377 // are correct. So we reach into the msgdef here to set the bit manually.
1378 Descriptor* mapentry_desc_self = ruby_to_Descriptor(mapentry_desc);
1379 upb_msgdef_setmapentry((upb_msgdef*)mapentry_desc_self->msgdef, true);
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001380 }
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001381
Josh Habermana1daeab2015-07-10 11:56:06 -07001382 {
1383 // optional <type> key = 1;
1384 VALUE key_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
1385 FieldDescriptor_name_set(key_field, rb_str_new2("key"));
1386 FieldDescriptor_label_set(key_field, ID2SYM(rb_intern("optional")));
1387 FieldDescriptor_number_set(key_field, INT2NUM(1));
1388 FieldDescriptor_type_set(key_field, key_type);
1389 Descriptor_add_field(mapentry_desc, key_field);
1390 }
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001391
Josh Habermana1daeab2015-07-10 11:56:06 -07001392 {
1393 // optional <type> value = 2;
1394 VALUE value_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
1395 FieldDescriptor_name_set(value_field, rb_str_new2("value"));
1396 FieldDescriptor_label_set(value_field, ID2SYM(rb_intern("optional")));
1397 FieldDescriptor_number_set(value_field, INT2NUM(2));
1398 FieldDescriptor_type_set(value_field, value_type);
1399 if (type_class != Qnil) {
1400 VALUE submsg_name = rb_str_new2("."); // prepend '.' to make absolute.
1401 submsg_name = rb_str_append(submsg_name, type_class);
1402 FieldDescriptor_submsg_name_set(value_field, submsg_name);
1403 }
1404 Descriptor_add_field(mapentry_desc, value_field);
1405 }
1406
1407 {
1408 // Add the map-entry message type to the current builder, and use the type
1409 // to create the map field itself.
1410 Builder* builder_self = ruby_to_Builder(self->builder);
1411 rb_ary_push(builder_self->pending_list, mapentry_desc);
1412 }
1413
1414 {
1415 VALUE map_field = rb_class_new_instance(0, NULL, cFieldDescriptor);
1416 VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
1417 VALUE submsg_name;
1418
1419 FieldDescriptor_name_set(map_field, name_str);
1420 FieldDescriptor_number_set(map_field, number);
1421 FieldDescriptor_label_set(map_field, ID2SYM(rb_intern("repeated")));
1422 FieldDescriptor_type_set(map_field, ID2SYM(rb_intern("message")));
1423 submsg_name = rb_str_new2("."); // prepend '.' to make name absolute.
1424 submsg_name = rb_str_append(submsg_name, mapentry_desc_name);
1425 FieldDescriptor_submsg_name_set(map_field, submsg_name);
1426 Descriptor_add_field(self->descriptor, map_field);
1427 }
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001428
1429 return Qnil;
1430}
1431
Chris Fallinfcd88892015-01-13 18:14:39 -08001432/*
1433 * call-seq:
1434 * MessageBuilderContext.oneof(name, &block) => nil
1435 *
1436 * Creates a new OneofDescriptor with the given name, creates a
1437 * OneofBuilderContext attached to that OneofDescriptor, evaluates the given
1438 * block in the context of that OneofBuilderContext with #instance_eval, and
1439 * then adds the oneof to the message.
1440 *
1441 * This is the recommended, idiomatic way to build oneof definitions.
1442 */
1443VALUE MessageBuilderContext_oneof(VALUE _self, VALUE name) {
1444 DEFINE_SELF(MessageBuilderContext, self, _self);
1445 VALUE oneofdef = rb_class_new_instance(0, NULL, cOneofDescriptor);
1446 VALUE args[2] = { oneofdef, self->builder };
1447 VALUE ctx = rb_class_new_instance(2, args, cOneofBuilderContext);
1448 VALUE block = rb_block_proc();
1449 VALUE name_str = rb_str_new2(rb_id2name(SYM2ID(name)));
1450 rb_funcall(oneofdef, rb_intern("name="), 1, name_str);
1451 rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
1452 Descriptor_add_oneof(self->descriptor, oneofdef);
1453
1454 return Qnil;
1455}
1456
1457// -----------------------------------------------------------------------------
1458// OneofBuilderContext.
1459// -----------------------------------------------------------------------------
1460
1461DEFINE_CLASS(OneofBuilderContext,
1462 "Google::Protobuf::Internal::OneofBuilderContext");
1463
1464void OneofBuilderContext_mark(void* _self) {
1465 OneofBuilderContext* self = _self;
1466 rb_gc_mark(self->descriptor);
1467 rb_gc_mark(self->builder);
1468}
1469
1470void OneofBuilderContext_free(void* _self) {
1471 OneofBuilderContext* self = _self;
1472 xfree(self);
1473}
1474
1475VALUE OneofBuilderContext_alloc(VALUE klass) {
1476 OneofBuilderContext* self = ALLOC(OneofBuilderContext);
1477 VALUE ret = TypedData_Wrap_Struct(
1478 klass, &_OneofBuilderContext_type, self);
1479 self->descriptor = Qnil;
1480 self->builder = Qnil;
1481 return ret;
1482}
1483
1484void OneofBuilderContext_register(VALUE module) {
1485 VALUE klass = rb_define_class_under(
1486 module, "OneofBuilderContext", rb_cObject);
1487 rb_define_alloc_func(klass, OneofBuilderContext_alloc);
1488 rb_define_method(klass, "initialize",
1489 OneofBuilderContext_initialize, 2);
1490 rb_define_method(klass, "optional", OneofBuilderContext_optional, -1);
1491 cOneofBuilderContext = klass;
1492 rb_gc_register_address(&cOneofBuilderContext);
1493}
1494
1495/*
1496 * call-seq:
1497 * OneofBuilderContext.new(desc, builder) => context
1498 *
1499 * Create a new oneof builder context around the given oneof descriptor and
1500 * builder context. This class is intended to serve as a DSL context to be used
1501 * with #instance_eval.
1502 */
1503VALUE OneofBuilderContext_initialize(VALUE _self,
1504 VALUE oneofdef,
1505 VALUE builder) {
1506 DEFINE_SELF(OneofBuilderContext, self, _self);
1507 self->descriptor = oneofdef;
1508 self->builder = builder;
1509 return Qnil;
1510}
1511
1512/*
1513 * call-seq:
1514 * OneofBuilderContext.optional(name, type, number, type_class = nil)
1515 *
1516 * Defines a new optional field in this oneof with the given type, tag number,
1517 * and type class (for message and enum fields). The type must be a Ruby symbol
1518 * (as accepted by FieldDescriptor#type=) and the type_class must be a string,
1519 * if present (as accepted by FieldDescriptor#submsg_name=).
1520 */
1521VALUE OneofBuilderContext_optional(int argc, VALUE* argv, VALUE _self) {
1522 DEFINE_SELF(OneofBuilderContext, self, _self);
Josh Habermana1daeab2015-07-10 11:56:06 -07001523 VALUE name, type, number, type_class;
Chris Fallinfcd88892015-01-13 18:14:39 -08001524
1525 if (argc < 3) {
1526 rb_raise(rb_eArgError, "Expected at least 3 arguments.");
1527 }
Josh Habermana1daeab2015-07-10 11:56:06 -07001528 name = argv[0];
1529 type = argv[1];
1530 number = argv[2];
1531 type_class = (argc > 3) ? argv[3] : Qnil;
Chris Fallinfcd88892015-01-13 18:14:39 -08001532
1533 return msgdef_add_field(self->descriptor, "optional",
1534 name, type, number, type_class);
1535}
1536
Chris Fallin973f4252014-11-18 14:19:58 -08001537// -----------------------------------------------------------------------------
1538// EnumBuilderContext.
1539// -----------------------------------------------------------------------------
1540
1541DEFINE_CLASS(EnumBuilderContext,
1542 "Google::Protobuf::Internal::EnumBuilderContext");
1543
1544void EnumBuilderContext_mark(void* _self) {
1545 EnumBuilderContext* self = _self;
1546 rb_gc_mark(self->enumdesc);
1547}
1548
1549void EnumBuilderContext_free(void* _self) {
1550 EnumBuilderContext* self = _self;
1551 xfree(self);
1552}
1553
1554VALUE EnumBuilderContext_alloc(VALUE klass) {
1555 EnumBuilderContext* self = ALLOC(EnumBuilderContext);
1556 VALUE ret = TypedData_Wrap_Struct(
1557 klass, &_EnumBuilderContext_type, self);
1558 self->enumdesc = Qnil;
1559 return ret;
1560}
1561
1562void EnumBuilderContext_register(VALUE module) {
1563 VALUE klass = rb_define_class_under(
1564 module, "EnumBuilderContext", rb_cObject);
1565 rb_define_alloc_func(klass, EnumBuilderContext_alloc);
1566 rb_define_method(klass, "initialize",
1567 EnumBuilderContext_initialize, 1);
1568 rb_define_method(klass, "value", EnumBuilderContext_value, 2);
1569 cEnumBuilderContext = klass;
1570 rb_gc_register_address(&cEnumBuilderContext);
1571}
1572
1573/*
1574 * call-seq:
1575 * EnumBuilderContext.new(enumdesc) => context
1576 *
1577 * Create a new builder context around the given enum descriptor. This class is
1578 * intended to serve as a DSL context to be used with #instance_eval.
1579 */
1580VALUE EnumBuilderContext_initialize(VALUE _self, VALUE enumdef) {
1581 DEFINE_SELF(EnumBuilderContext, self, _self);
1582 self->enumdesc = enumdef;
1583 return Qnil;
1584}
1585
1586static VALUE enumdef_add_value(VALUE enumdef,
1587 VALUE name, VALUE number) {
1588 rb_funcall(enumdef, rb_intern("add_value"), 2, name, number);
1589 return Qnil;
1590}
1591
1592/*
1593 * call-seq:
1594 * EnumBuilder.add_value(name, number)
1595 *
1596 * Adds the given name => number mapping to the enum type. Name must be a Ruby
1597 * symbol.
1598 */
1599VALUE EnumBuilderContext_value(VALUE _self, VALUE name, VALUE number) {
1600 DEFINE_SELF(EnumBuilderContext, self, _self);
1601 return enumdef_add_value(self->enumdesc, name, number);
1602}
1603
1604// -----------------------------------------------------------------------------
1605// Builder.
1606// -----------------------------------------------------------------------------
1607
1608DEFINE_CLASS(Builder, "Google::Protobuf::Internal::Builder");
1609
1610void Builder_mark(void* _self) {
1611 Builder* self = _self;
1612 rb_gc_mark(self->pending_list);
1613}
1614
1615void Builder_free(void* _self) {
1616 Builder* self = _self;
1617 xfree(self->defs);
1618 xfree(self);
1619}
1620
1621/*
1622 * call-seq:
1623 * Builder.new => builder
1624 *
1625 * Creates a new Builder. A Builder can accumulate a set of new message and enum
1626 * descriptors and atomically register them into a pool in a way that allows for
1627 * (co)recursive type references.
1628 */
1629VALUE Builder_alloc(VALUE klass) {
1630 Builder* self = ALLOC(Builder);
1631 VALUE ret = TypedData_Wrap_Struct(
1632 klass, &_Builder_type, self);
1633 self->pending_list = rb_ary_new();
1634 self->defs = NULL;
1635 return ret;
1636}
1637
1638void Builder_register(VALUE module) {
1639 VALUE klass = rb_define_class_under(module, "Builder", rb_cObject);
1640 rb_define_alloc_func(klass, Builder_alloc);
1641 rb_define_method(klass, "add_message", Builder_add_message, 1);
1642 rb_define_method(klass, "add_enum", Builder_add_enum, 1);
1643 rb_define_method(klass, "finalize_to_pool", Builder_finalize_to_pool, 1);
1644 cBuilder = klass;
1645 rb_gc_register_address(&cBuilder);
1646}
1647
1648/*
1649 * call-seq:
1650 * Builder.add_message(name, &block)
1651 *
1652 * Creates a new, empty descriptor with the given name, and invokes the block in
1653 * the context of a MessageBuilderContext on that descriptor. The block can then
1654 * call, e.g., MessageBuilderContext#optional and MessageBuilderContext#repeated
1655 * methods to define the message fields.
1656 *
1657 * This is the recommended, idiomatic way to build message definitions.
1658 */
1659VALUE Builder_add_message(VALUE _self, VALUE name) {
1660 DEFINE_SELF(Builder, self, _self);
1661 VALUE msgdef = rb_class_new_instance(0, NULL, cDescriptor);
Chris Fallinfd1a3ff2015-01-06 15:44:09 -08001662 VALUE args[2] = { msgdef, _self };
1663 VALUE ctx = rb_class_new_instance(2, args, cMessageBuilderContext);
Chris Fallin973f4252014-11-18 14:19:58 -08001664 VALUE block = rb_block_proc();
1665 rb_funcall(msgdef, rb_intern("name="), 1, name);
1666 rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
1667 rb_ary_push(self->pending_list, msgdef);
1668 return Qnil;
1669}
1670
1671/*
1672 * call-seq:
1673 * Builder.add_enum(name, &block)
1674 *
Chris Fallin231886f2015-05-19 15:33:48 -07001675 * Creates a new, empty enum descriptor with the given name, and invokes the
1676 * block in the context of an EnumBuilderContext on that descriptor. The block
1677 * can then call EnumBuilderContext#add_value to define the enum values.
Chris Fallin973f4252014-11-18 14:19:58 -08001678 *
1679 * This is the recommended, idiomatic way to build enum definitions.
1680 */
1681VALUE Builder_add_enum(VALUE _self, VALUE name) {
1682 DEFINE_SELF(Builder, self, _self);
1683 VALUE enumdef = rb_class_new_instance(0, NULL, cEnumDescriptor);
1684 VALUE ctx = rb_class_new_instance(1, &enumdef, cEnumBuilderContext);
1685 VALUE block = rb_block_proc();
1686 rb_funcall(enumdef, rb_intern("name="), 1, name);
1687 rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
1688 rb_ary_push(self->pending_list, enumdef);
1689 return Qnil;
1690}
1691
1692static void validate_msgdef(const upb_msgdef* msgdef) {
1693 // Verify that no required fields exist. proto3 does not support these.
Chris Fallinfcd88892015-01-13 18:14:39 -08001694 upb_msg_field_iter it;
1695 for (upb_msg_field_begin(&it, msgdef);
1696 !upb_msg_field_done(&it);
1697 upb_msg_field_next(&it)) {
Chris Fallin973f4252014-11-18 14:19:58 -08001698 const upb_fielddef* field = upb_msg_iter_field(&it);
1699 if (upb_fielddef_label(field) == UPB_LABEL_REQUIRED) {
1700 rb_raise(rb_eTypeError, "Required fields are unsupported in proto3.");
1701 }
1702 }
1703}
1704
1705static void validate_enumdef(const upb_enumdef* enumdef) {
1706 // Verify that an entry exists with integer value 0. (This is the default
1707 // value.)
1708 const char* lookup = upb_enumdef_iton(enumdef, 0);
1709 if (lookup == NULL) {
1710 rb_raise(rb_eTypeError,
1711 "Enum definition does not contain a value for '0'.");
1712 }
1713}
1714
1715/*
1716 * call-seq:
1717 * Builder.finalize_to_pool(pool)
1718 *
1719 * Adds all accumulated message and enum descriptors created in this builder
1720 * context to the given pool. The operation occurs atomically, and all
1721 * descriptors can refer to each other (including in cycles). This is the only
1722 * way to build (co)recursive message definitions.
1723 *
1724 * This method is usually called automatically by DescriptorPool#build after it
1725 * invokes the given user block in the context of the builder. The user should
1726 * not normally need to call this manually because a Builder is not normally
1727 * created manually.
1728 */
1729VALUE Builder_finalize_to_pool(VALUE _self, VALUE pool_rb) {
1730 DEFINE_SELF(Builder, self, _self);
1731
1732 DescriptorPool* pool = ruby_to_DescriptorPool(pool_rb);
1733
1734 REALLOC_N(self->defs, upb_def*, RARRAY_LEN(self->pending_list));
1735
1736 for (int i = 0; i < RARRAY_LEN(self->pending_list); i++) {
1737 VALUE def_rb = rb_ary_entry(self->pending_list, i);
1738 if (CLASS_OF(def_rb) == cDescriptor) {
1739 self->defs[i] = (upb_def*)ruby_to_Descriptor(def_rb)->msgdef;
1740 validate_msgdef((const upb_msgdef*)self->defs[i]);
1741 } else if (CLASS_OF(def_rb) == cEnumDescriptor) {
1742 self->defs[i] = (upb_def*)ruby_to_EnumDescriptor(def_rb)->enumdef;
1743 validate_enumdef((const upb_enumdef*)self->defs[i]);
1744 }
1745 }
1746
1747 CHECK_UPB(upb_symtab_add(pool->symtab, (upb_def**)self->defs,
1748 RARRAY_LEN(self->pending_list), NULL, &status),
1749 "Unable to add defs to DescriptorPool");
1750
1751 for (int i = 0; i < RARRAY_LEN(self->pending_list); i++) {
1752 VALUE def_rb = rb_ary_entry(self->pending_list, i);
1753 add_def_obj(self->defs[i], def_rb);
1754 }
1755
1756 self->pending_list = rb_ary_new();
1757 return Qnil;
1758}