1 // Amalgamated source file
2 /*
3 ** Defs are upb's internal representation of the constructs that can appear
4 ** in a .proto file:
5 **
6 ** - upb::MessageDef (upb_msgdef): describes a "message" construct.
7 ** - upb::FieldDef (upb_fielddef): describes a message field.
8 ** - upb::EnumDef (upb_enumdef): describes an enum.
9 ** - upb::OneofDef (upb_oneofdef): describes a oneof.
10 ** - upb::Def (upb_def): base class of all the others.
11 **
12 ** TODO: definitions of services.
13 **
14 ** Like upb_refcounted objects, defs are mutable only until frozen, and are
15 ** only thread-safe once frozen.
16 **
17 ** This is a mixed C/C++ interface that offers a full API to both languages.
18 ** See the top-level README for more information.
19 */
20 
21 #ifndef UPB_DEF_H_
22 #define UPB_DEF_H_
23 
24 /*
25 ** upb::RefCounted (upb_refcounted)
26 **
27 ** A refcounting scheme that supports circular refs.  It accomplishes this by
28 ** partitioning the set of objects into groups such that no cycle spans groups;
29 ** we can then reference-count the group as a whole and ignore refs within the
30 ** group.  When objects are mutable, these groups are computed very
31 ** conservatively; we group any objects that have ever had a link between them.
32 ** When objects are frozen, we compute strongly-connected components which
33 ** allows us to be precise and only group objects that are actually cyclic.
34 **
35 ** This is a mixed C/C++ interface that offers a full API to both languages.
36 ** See the top-level README for more information.
37 */
38 
39 #ifndef UPB_REFCOUNTED_H_
40 #define UPB_REFCOUNTED_H_
41 
42 /*
43 ** upb_table
44 **
45 ** This header is INTERNAL-ONLY!  Its interfaces are not public or stable!
46 ** This file defines very fast int->upb_value (inttable) and string->upb_value
47 ** (strtable) hash tables.
48 **
49 ** The table uses chained scatter with Brent's variation (inspired by the Lua
50 ** implementation of hash tables).  The hash function for strings is Austin
51 ** Appleby's "MurmurHash."
52 **
53 ** The inttable uses uintptr_t as its key, which guarantees it can be used to
54 ** store pointers or integers of at least 32 bits (upb isn't really useful on
55 ** systems where sizeof(void*) < 4).
56 **
57 ** The table must be homogenous (all values of the same type).  In debug
58 ** mode, we check this on insert and lookup.
59 */
60 
61 #ifndef UPB_TABLE_H_
62 #define UPB_TABLE_H_
63 
64 #include <assert.h>
65 #include <stdint.h>
66 #include <string.h>
67 /*
68 ** This file contains shared definitions that are widely used across upb.
69 **
70 ** This is a mixed C/C++ interface that offers a full API to both languages.
71 ** See the top-level README for more information.
72 */
73 
74 #ifndef UPB_H_
75 #define UPB_H_
76 
77 #include <assert.h>
78 #include <stdarg.h>
79 #include <stdbool.h>
80 #include <stddef.h>
81 
82 /* UPB_INLINE: inline if possible, emit standalone code if required. */
83 #ifdef __cplusplus
84 #define UPB_INLINE inline
85 #elif defined (__GNUC__)
86 #define UPB_INLINE static __inline__
87 #else
88 #define UPB_INLINE static
89 #endif
90 
91 /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
92  * doesn't provide these preprocessor symbols. */
93 #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
94 #define UPB_BIG_ENDIAN
95 #endif
96 
97 /* Macros for function attributes on compilers that support them. */
98 #ifdef __GNUC__
99 #define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
100 #define UPB_NOINLINE __attribute__((noinline))
101 #define UPB_NORETURN __attribute__((__noreturn__))
102 #else  /* !defined(__GNUC__) */
103 #define UPB_FORCEINLINE
104 #define UPB_NOINLINE
105 #define UPB_NORETURN
106 #endif
107 
108 /* A few hacky workarounds for functions not in C89.
109  * For internal use only!
110  * TODO(haberman): fix these by including our own implementations, or finding
111  * another workaround.
112  */
113 #ifdef __GNUC__
114 #define _upb_snprintf __builtin_snprintf
115 #define _upb_vsnprintf __builtin_vsnprintf
116 #define _upb_va_copy(a, b) __va_copy(a, b)
117 #elif __STDC_VERSION__ >= 199901L
118 /* C99 versions. */
119 #define _upb_snprintf snprintf
120 #define _upb_vsnprintf vsnprintf
121 #define _upb_va_copy(a, b) va_copy(a, b)
122 #else
123 #error Need implementations of [v]snprintf and va_copy
124 #endif
125 
126 
127 #if ((defined(__cplusplus) && __cplusplus >= 201103L) || \
128       defined(__GXX_EXPERIMENTAL_CXX0X__)) && !defined(UPB_NO_CXX11)
129 #define UPB_CXX11
130 #endif
131 
132 /* UPB_DISALLOW_COPY_AND_ASSIGN()
133  * UPB_DISALLOW_POD_OPS()
134  *
135  * Declare these in the "private" section of a C++ class to forbid copy/assign
136  * or all POD ops (construct, destruct, copy, assign) on that class. */
137 #ifdef UPB_CXX11
138 #include <type_traits>
139 #define UPB_DISALLOW_COPY_AND_ASSIGN(class_name) \
140   class_name(const class_name&) = delete; \
141   void operator=(const class_name&) = delete;
142 #define UPB_DISALLOW_POD_OPS(class_name, full_class_name) \
143   class_name() = delete; \
144   ~class_name() = delete; \
145   UPB_DISALLOW_COPY_AND_ASSIGN(class_name)
146 #define UPB_ASSERT_STDLAYOUT(type) \
147   static_assert(std::is_standard_layout<type>::value, \
148                 #type " must be standard layout");
149 #else  /* !defined(UPB_CXX11) */
150 #define UPB_DISALLOW_COPY_AND_ASSIGN(class_name) \
151   class_name(const class_name&); \
152   void operator=(const class_name&);
153 #define UPB_DISALLOW_POD_OPS(class_name, full_class_name) \
154   class_name(); \
155   ~class_name(); \
156   UPB_DISALLOW_COPY_AND_ASSIGN(class_name)
157 #define UPB_ASSERT_STDLAYOUT(type)
158 #endif
159 
160 /* UPB_DECLARE_TYPE()
161  * UPB_DECLARE_DERIVED_TYPE()
162  * UPB_DECLARE_DERIVED_TYPE2()
163  *
164  * Macros for declaring C and C++ types both, including inheritance.
165  * The inheritance doesn't use real C++ inheritance, to stay compatible with C.
166  *
167  * These macros also provide upcasts:
168  *  - in C: types-specific functions (ie. upb_foo_upcast(foo))
169  *  - in C++: upb::upcast(foo) along with implicit conversions
170  *
171  * Downcasts are not provided, but upb/def.h defines downcasts for upb::Def. */
172 
173 #define UPB_C_UPCASTS(ty, base)                                      \
174   UPB_INLINE base *ty ## _upcast_mutable(ty *p) { return (base*)p; } \
175   UPB_INLINE const base *ty ## _upcast(const ty *p) { return (const base*)p; }
176 
177 #define UPB_C_UPCASTS2(ty, base, base2)                                 \
178   UPB_C_UPCASTS(ty, base)                                               \
179   UPB_INLINE base2 *ty ## _upcast2_mutable(ty *p) { return (base2*)p; } \
180   UPB_INLINE const base2 *ty ## _upcast2(const ty *p) { return (const base2*)p; }
181 
182 #ifdef __cplusplus
183 
184 #define UPB_BEGIN_EXTERN_C extern "C" {
185 #define UPB_END_EXTERN_C }
186 #define UPB_PRIVATE_FOR_CPP private:
187 #define UPB_DECLARE_TYPE(cppname, cname) typedef cppname cname;
188 
189 #define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase)  \
190   UPB_DECLARE_TYPE(cppname, cname)                                \
191   UPB_C_UPCASTS(cname, cbase)                                     \
192   namespace upb {                                                 \
193   template <>                                                     \
194   class Pointer<cppname> : public PointerBase<cppname, cppbase> { \
195    public:                                                        \
196     explicit Pointer(cppname* ptr) : PointerBase(ptr) {}          \
197   };                                                              \
198   template <>                                                     \
199   class Pointer<const cppname>                                    \
200       : public PointerBase<const cppname, const cppbase> {        \
201    public:                                                        \
202     explicit Pointer(const cppname* ptr) : PointerBase(ptr) {}    \
203   };                                                              \
204   }
205 
206 #define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2, cname, cbase,  \
207                                   cbase2)                                    \
208   UPB_DECLARE_TYPE(cppname, cname)                                           \
209   UPB_C_UPCASTS2(cname, cbase, cbase2)                                       \
210   namespace upb {                                                            \
211   template <>                                                                \
212   class Pointer<cppname> : public PointerBase2<cppname, cppbase, cppbase2> { \
213    public:                                                                   \
214     explicit Pointer(cppname* ptr) : PointerBase2(ptr) {}                    \
215   };                                                                         \
216   template <>                                                                \
217   class Pointer<const cppname>                                               \
218       : public PointerBase2<const cppname, const cppbase, const cppbase2> {  \
219    public:                                                                   \
220     explicit Pointer(const cppname* ptr) : PointerBase2(ptr) {}              \
221   };                                                                         \
222   }
223 
224 #else  /* !defined(__cplusplus) */
225 
226 #define UPB_BEGIN_EXTERN_C
227 #define UPB_END_EXTERN_C
228 #define UPB_PRIVATE_FOR_CPP
229 #define UPB_DECLARE_TYPE(cppname, cname) \
230   struct cname;                          \
231   typedef struct cname cname;
232 #define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase) \
233   UPB_DECLARE_TYPE(cppname, cname)                               \
234   UPB_C_UPCASTS(cname, cbase)
235 #define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2,    \
236                                   cname, cbase, cbase2)          \
237   UPB_DECLARE_TYPE(cppname, cname)                               \
238   UPB_C_UPCASTS2(cname, cbase, cbase2)
239 
240 #endif  /* defined(__cplusplus) */
241 
242 #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
243 #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
244 
245 #define UPB_UNUSED(var) (void)var
246 
247 /* For asserting something about a variable when the variable is not used for
248  * anything else.  This prevents "unused variable" warnings when compiling in
249  * debug mode. */
250 #define UPB_ASSERT_VAR(var, predicate) UPB_UNUSED(var); assert(predicate)
251 
252 /* Generic function type. */
253 typedef void upb_func();
254 
255 /* C++ Casts ******************************************************************/
256 
257 #ifdef __cplusplus
258 
259 namespace upb {
260 
261 template <class T> class Pointer;
262 
263 /* Casts to a subclass.  The caller must know that cast is correct; an
264  * incorrect cast will throw an assertion failure in debug mode.
265  *
266  * Example:
267  *   upb::Def* def = GetDef();
268  *   // Assert-fails if this was not actually a MessageDef.
269  *   upb::MessgeDef* md = upb::down_cast<upb::MessageDef>(def);
270  *
271  * Note that downcasts are only defined for some types (at the moment you can
272  * only downcast from a upb::Def to a specific Def type). */
273 template<class To, class From> To down_cast(From* f);
274 
275 /* Casts to a subclass.  If the class does not actually match the given To type,
276  * returns NULL.
277  *
278  * Example:
279  *   upb::Def* def = GetDef();
280  *   // md will be NULL if this was not actually a MessageDef.
281  *   upb::MessgeDef* md = upb::down_cast<upb::MessageDef>(def);
282  *
283  * Note that dynamic casts are only defined for some types (at the moment you
284  * can only downcast from a upb::Def to a specific Def type).. */
285 template<class To, class From> To dyn_cast(From* f);
286 
287 /* Casts to any base class, or the type itself (ie. can be a no-op).
288  *
289  * Example:
290  *   upb::MessageDef* md = GetDef();
291  *   // This will fail to compile if this wasn't actually a base class.
292  *   upb::Def* def = upb::upcast(md);
293  */
upcast(T * f)294 template <class T> inline Pointer<T> upcast(T *f) { return Pointer<T>(f); }
295 
296 /* Attempt upcast to specific base class.
297  *
298  * Example:
299  *   upb::MessageDef* md = GetDef();
300  *   upb::upcast_to<upb::Def>(md)->MethodOnDef();
301  */
upcast_to(F * f)302 template <class T, class F> inline T* upcast_to(F *f) {
303   return static_cast<T*>(upcast(f));
304 }
305 
306 /* PointerBase<T>: implementation detail of upb::upcast().
307  * It is implicitly convertable to pointers to the Base class(es).
308  */
309 template <class T, class Base>
310 class PointerBase {
311  public:
PointerBase(T * ptr)312   explicit PointerBase(T* ptr) : ptr_(ptr) {}
313   operator T*() { return ptr_; }
314   operator Base*() { return (Base*)ptr_; }
315 
316  private:
317   T* ptr_;
318 };
319 
320 template <class T, class Base, class Base2>
321 class PointerBase2 : public PointerBase<T, Base> {
322  public:
PointerBase2(T * ptr)323   explicit PointerBase2(T* ptr) : PointerBase<T, Base>(ptr) {}
324   operator Base2*() { return Pointer<Base>(*this); }
325 };
326 
327 }
328 
329 #endif
330 
331 
332 /* upb::reffed_ptr ************************************************************/
333 
334 #ifdef __cplusplus
335 
336 #include <algorithm>  /* For std::swap(). */
337 
338 namespace upb {
339 
340 /* Provides RAII semantics for upb refcounted objects.  Each reffed_ptr owns a
341  * ref on whatever object it points to (if any). */
342 template <class T> class reffed_ptr {
343  public:
reffed_ptr()344   reffed_ptr() : ptr_(NULL) {}
345 
346   /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */
347   template <class U>
348   reffed_ptr(U* val, const void* ref_donor = NULL)
ptr_(upb::upcast (val))349       : ptr_(upb::upcast(val)) {
350     if (ref_donor) {
351       assert(ptr_);
352       ptr_->DonateRef(ref_donor, this);
353     } else if (ptr_) {
354       ptr_->Ref(this);
355     }
356   }
357 
358   template <class U>
reffed_ptr(const reffed_ptr<U> & other)359   reffed_ptr(const reffed_ptr<U>& other)
360       : ptr_(upb::upcast(other.get())) {
361     if (ptr_) ptr_->Ref(this);
362   }
363 
~reffed_ptr()364   ~reffed_ptr() { if (ptr_) ptr_->Unref(this); }
365 
366   template <class U>
367   reffed_ptr& operator=(const reffed_ptr<U>& other) {
368     reset(other.get());
369     return *this;
370   }
371 
372   reffed_ptr& operator=(const reffed_ptr& other) {
373     reset(other.get());
374     return *this;
375   }
376 
377   /* TODO(haberman): add C++11 move construction/assignment for greater
378    * efficiency. */
379 
swap(reffed_ptr & other)380   void swap(reffed_ptr& other) {
381     if (ptr_ == other.ptr_) {
382       return;
383     }
384 
385     if (ptr_) ptr_->DonateRef(this, &other);
386     if (other.ptr_) other.ptr_->DonateRef(&other, this);
387     std::swap(ptr_, other.ptr_);
388   }
389 
390   T& operator*() const {
391     assert(ptr_);
392     return *ptr_;
393   }
394 
395   T* operator->() const {
396     assert(ptr_);
397     return ptr_;
398   }
399 
get()400   T* get() const { return ptr_; }
401 
402   /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */
403   template <class U>
404   void reset(U* ptr = NULL, const void* ref_donor = NULL) {
405     reffed_ptr(ptr, ref_donor).swap(*this);
406   }
407 
408   template <class U>
down_cast()409   reffed_ptr<U> down_cast() {
410     return reffed_ptr<U>(upb::down_cast<U*>(get()));
411   }
412 
413   template <class U>
dyn_cast()414   reffed_ptr<U> dyn_cast() {
415     return reffed_ptr<U>(upb::dyn_cast<U*>(get()));
416   }
417 
418   /* Plain release() is unsafe; if we were the only owner, it would leak the
419    * object.  Instead we provide this: */
ReleaseTo(const void * new_owner)420   T* ReleaseTo(const void* new_owner) {
421     T* ret = NULL;
422     ptr_->DonateRef(this, new_owner);
423     std::swap(ret, ptr_);
424     return ret;
425   }
426 
427  private:
428   T* ptr_;
429 };
430 
431 }  /* namespace upb */
432 
433 #endif  /* __cplusplus */
434 
435 
436 /* upb::Status ****************************************************************/
437 
438 #ifdef __cplusplus
439 namespace upb {
440 class ErrorSpace;
441 class Status;
442 }
443 #endif
444 
445 UPB_DECLARE_TYPE(upb::ErrorSpace, upb_errorspace)
446 UPB_DECLARE_TYPE(upb::Status, upb_status)
447 
448 /* The maximum length of an error message before it will get truncated. */
449 #define UPB_STATUS_MAX_MESSAGE 128
450 
451 /* An error callback function is used to report errors from some component.
452  * The function can return "true" to indicate that the component should try
453  * to recover and proceed, but this is not always possible. */
454 typedef bool upb_errcb_t(void *closure, const upb_status* status);
455 
456 #ifdef __cplusplus
457 class upb::ErrorSpace {
458 #else
459 struct upb_errorspace {
460 #endif
461   const char *name;
462   /* Should the error message in the status object according to this code. */
463   void (*set_message)(upb_status* status, int code);
464 };
465 
466 #ifdef __cplusplus
467 
468 /* Object representing a success or failure status.
469  * It owns no resources and allocates no memory, so it should work
470  * even in OOM situations. */
471 
472 class upb::Status {
473  public:
474   Status();
475 
476   /* Returns true if there is no error. */
477   bool ok() const;
478 
479   /* Optional error space and code, useful if the caller wants to
480    * programmatically check the specific kind of error. */
481   ErrorSpace* error_space();
482   int code() const;
483 
484   const char *error_message() const;
485 
486   /* The error message will be truncated if it is longer than
487    * UPB_STATUS_MAX_MESSAGE-4. */
488   void SetErrorMessage(const char* msg);
489   void SetFormattedErrorMessage(const char* fmt, ...);
490 
491   /* If there is no error message already, this will use the ErrorSpace to
492    * populate the error message for this code.  The caller can still call
493    * SetErrorMessage() to give a more specific message. */
494   void SetErrorCode(ErrorSpace* space, int code);
495 
496   /* Resets the status to a successful state with no message. */
497   void Clear();
498 
499   void CopyFrom(const Status& other);
500 
501  private:
502   UPB_DISALLOW_COPY_AND_ASSIGN(Status)
503 #else
504 struct upb_status {
505 #endif
506   bool ok_;
507 
508   /* Specific status code defined by some error space (optional). */
509   int code_;
510   upb_errorspace *error_space_;
511 
512   /* Error message; NULL-terminated. */
513   char msg[UPB_STATUS_MAX_MESSAGE];
514 };
515 
516 #define UPB_STATUS_INIT {true, 0, NULL, {0}}
517 
518 #ifdef __cplusplus
519 extern "C" {
520 #endif
521 
522 /* The returned string is invalidated by any other call into the status. */
523 const char *upb_status_errmsg(const upb_status *status);
524 bool upb_ok(const upb_status *status);
525 upb_errorspace *upb_status_errspace(const upb_status *status);
526 int upb_status_errcode(const upb_status *status);
527 
528 /* Any of the functions that write to a status object allow status to be NULL,
529  * to support use cases where the function's caller does not care about the
530  * status message. */
531 void upb_status_clear(upb_status *status);
532 void upb_status_seterrmsg(upb_status *status, const char *msg);
533 void upb_status_seterrf(upb_status *status, const char *fmt, ...);
534 void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args);
535 void upb_status_seterrcode(upb_status *status, upb_errorspace *space, int code);
536 void upb_status_copy(upb_status *to, const upb_status *from);
537 
538 #ifdef __cplusplus
539 }  /* extern "C" */
540 
541 namespace upb {
542 
543 /* C++ Wrappers */
Status()544 inline Status::Status() { Clear(); }
ok()545 inline bool Status::ok() const { return upb_ok(this); }
error_message()546 inline const char* Status::error_message() const {
547   return upb_status_errmsg(this);
548 }
SetErrorMessage(const char * msg)549 inline void Status::SetErrorMessage(const char* msg) {
550   upb_status_seterrmsg(this, msg);
551 }
SetFormattedErrorMessage(const char * fmt,...)552 inline void Status::SetFormattedErrorMessage(const char* fmt, ...) {
553   va_list args;
554   va_start(args, fmt);
555   upb_status_vseterrf(this, fmt, args);
556   va_end(args);
557 }
SetErrorCode(ErrorSpace * space,int code)558 inline void Status::SetErrorCode(ErrorSpace* space, int code) {
559   upb_status_seterrcode(this, space, code);
560 }
Clear()561 inline void Status::Clear() { upb_status_clear(this); }
CopyFrom(const Status & other)562 inline void Status::CopyFrom(const Status& other) {
563   upb_status_copy(this, &other);
564 }
565 
566 }  /* namespace upb */
567 
568 #endif
569 
570 #endif  /* UPB_H_ */
571 
572 #ifdef __cplusplus
573 extern "C" {
574 #endif
575 
576 
577 /* upb_value ******************************************************************/
578 
579 /* A tagged union (stored untagged inside the table) so that we can check that
580  * clients calling table accessors are correctly typed without having to have
581  * an explosion of accessors. */
582 typedef enum {
583   UPB_CTYPE_INT32    = 1,
584   UPB_CTYPE_INT64    = 2,
585   UPB_CTYPE_UINT32   = 3,
586   UPB_CTYPE_UINT64   = 4,
587   UPB_CTYPE_BOOL     = 5,
588   UPB_CTYPE_CSTR     = 6,
589   UPB_CTYPE_PTR      = 7,
590   UPB_CTYPE_CONSTPTR = 8,
591   UPB_CTYPE_FPTR     = 9
592 } upb_ctype_t;
593 
594 typedef struct {
595   uint64_t val;
596 #ifndef NDEBUG
597   /* In debug mode we carry the value type around also so we can check accesses
598    * to be sure the right member is being read. */
599   upb_ctype_t ctype;
600 #endif
601 } upb_value;
602 
603 #ifdef NDEBUG
604 #define SET_TYPE(dest, val)      UPB_UNUSED(val)
605 #else
606 #define SET_TYPE(dest, val) dest = val
607 #endif
608 
609 /* Like strdup(), which isn't always available since it's not ANSI C. */
610 char *upb_strdup(const char *s);
611 /* Variant that works with a length-delimited rather than NULL-delimited string,
612  * as supported by strtable. */
613 char *upb_strdup2(const char *s, size_t len);
614 
_upb_value_setval(upb_value * v,uint64_t val,upb_ctype_t ctype)615 UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val,
616                                   upb_ctype_t ctype) {
617   v->val = val;
618   SET_TYPE(v->ctype, ctype);
619 }
620 
_upb_value_val(uint64_t val,upb_ctype_t ctype)621 UPB_INLINE upb_value _upb_value_val(uint64_t val, upb_ctype_t ctype) {
622   upb_value ret;
623   _upb_value_setval(&ret, val, ctype);
624   return ret;
625 }
626 
627 /* For each value ctype, define the following set of functions:
628  *
629  * // Get/set an int32 from a upb_value.
630  * int32_t upb_value_getint32(upb_value val);
631  * void upb_value_setint32(upb_value *val, int32_t cval);
632  *
633  * // Construct a new upb_value from an int32.
634  * upb_value upb_value_int32(int32_t val); */
635 #define FUNCS(name, membername, type_t, converter, proto_type) \
636   UPB_INLINE void upb_value_set ## name(upb_value *val, type_t cval) { \
637     val->val = (converter)cval; \
638     SET_TYPE(val->ctype, proto_type); \
639   } \
640   UPB_INLINE upb_value upb_value_ ## name(type_t val) { \
641     upb_value ret; \
642     upb_value_set ## name(&ret, val); \
643     return ret; \
644   } \
645   UPB_INLINE type_t upb_value_get ## name(upb_value val) { \
646     assert(val.ctype == proto_type); \
647     return (type_t)(converter)val.val; \
648   }
649 
650 FUNCS(int32,    int32,        int32_t,      int32_t,    UPB_CTYPE_INT32)
651 FUNCS(int64,    int64,        int64_t,      int64_t,    UPB_CTYPE_INT64)
652 FUNCS(uint32,   uint32,       uint32_t,     uint32_t,   UPB_CTYPE_UINT32)
653 FUNCS(uint64,   uint64,       uint64_t,     uint64_t,   UPB_CTYPE_UINT64)
654 FUNCS(bool,     _bool,        bool,         bool,       UPB_CTYPE_BOOL)
655 FUNCS(cstr,     cstr,         char*,        uintptr_t,  UPB_CTYPE_CSTR)
656 FUNCS(ptr,      ptr,          void*,        uintptr_t,  UPB_CTYPE_PTR)
657 FUNCS(constptr, constptr,     const void*,  uintptr_t,  UPB_CTYPE_CONSTPTR)
658 FUNCS(fptr,     fptr,         upb_func*,    uintptr_t,  UPB_CTYPE_FPTR)
659 
660 #undef FUNCS
661 #undef SET_TYPE
662 
663 
664 /* upb_tabkey *****************************************************************/
665 
666 /* Either:
667  *   1. an actual integer key, or
668  *   2. a pointer to a string prefixed by its uint32_t length, owned by us.
669  *
670  * ...depending on whether this is a string table or an int table.  We would
671  * make this a union of those two types, but C89 doesn't support statically
672  * initializing a non-first union member. */
673 typedef uintptr_t upb_tabkey;
674 
675 #define UPB_TABKEY_NUM(n) n
676 #define UPB_TABKEY_NONE 0
677 /* The preprocessor isn't quite powerful enough to turn the compile-time string
678  * length into a byte-wise string representation, so code generation needs to
679  * help it along.
680  *
681  * "len1" is the low byte and len4 is the high byte. */
682 #ifdef UPB_BIG_ENDIAN
683 #define UPB_TABKEY_STR(len1, len2, len3, len4, strval) \
684     (uintptr_t)(len4 len3 len2 len1 strval)
685 #else
686 #define UPB_TABKEY_STR(len1, len2, len3, len4, strval) \
687     (uintptr_t)(len1 len2 len3 len4 strval)
688 #endif
689 
upb_tabstr(upb_tabkey key,uint32_t * len)690 UPB_INLINE char *upb_tabstr(upb_tabkey key, uint32_t *len) {
691   char* mem = (char*)key;
692   if (len) memcpy(len, mem, sizeof(*len));
693   return mem + sizeof(*len);
694 }
695 
696 
697 /* upb_tabval *****************************************************************/
698 
699 #ifdef __cplusplus
700 
701 /* Status initialization not supported.
702  *
703  * This separate definition is necessary because in C++, UINTPTR_MAX isn't
704  * reliably available. */
705 typedef struct {
706   uint64_t val;
707 } upb_tabval;
708 
709 #else
710 
711 /* C -- supports static initialization, but to support static initialization of
712  * both integers and points for both 32 and 64 bit targets, it takes a little
713  * bit of doing. */
714 
715 #if UINTPTR_MAX == 0xffffffffffffffffULL
716 #define UPB_PTR_IS_64BITS
717 #elif UINTPTR_MAX != 0xffffffff
718 #error Could not determine how many bits pointers are.
719 #endif
720 
721 typedef union {
722   /* For static initialization.
723    *
724    * Unfortunately this ugliness is necessary -- it is the only way that we can,
725    * with -std=c89 -pedantic, statically initialize this to either a pointer or
726    * an integer on 32-bit platforms. */
727   struct {
728 #ifdef UPB_PTR_IS_64BITS
729     uintptr_t val;
730 #else
731     uintptr_t val1;
732     uintptr_t val2;
733 #endif
734   } staticinit;
735 
736   /* The normal accessor that we use for everything at runtime. */
737   uint64_t val;
738 } upb_tabval;
739 
740 #ifdef UPB_PTR_IS_64BITS
741 #define UPB_TABVALUE_INT_INIT(v) {{v}}
742 #define UPB_TABVALUE_EMPTY_INIT  {{-1}}
743 #else
744 
745 /* 32-bit pointers */
746 
747 #ifdef UPB_BIG_ENDIAN
748 #define UPB_TABVALUE_INT_INIT(v) {{0, v}}
749 #define UPB_TABVALUE_EMPTY_INIT  {{-1, -1}}
750 #else
751 #define UPB_TABVALUE_INT_INIT(v) {{v, 0}}
752 #define UPB_TABVALUE_EMPTY_INIT  {{-1, -1}}
753 #endif
754 
755 #endif
756 
757 #define UPB_TABVALUE_PTR_INIT(v) UPB_TABVALUE_INT_INIT((uintptr_t)v)
758 
759 #undef UPB_PTR_IS_64BITS
760 
761 #endif  /* __cplusplus */
762 
763 
764 /* upb_table ******************************************************************/
765 
766 typedef struct _upb_tabent {
767   upb_tabkey key;
768   upb_tabval val;
769 
770   /* Internal chaining.  This is const so we can create static initializers for
771    * tables.  We cast away const sometimes, but *only* when the containing
772    * upb_table is known to be non-const.  This requires a bit of care, but
773    * the subtlety is confined to table.c. */
774   const struct _upb_tabent *next;
775 } upb_tabent;
776 
777 typedef struct {
778   size_t count;          /* Number of entries in the hash part. */
779   size_t mask;           /* Mask to turn hash value -> bucket. */
780   upb_ctype_t ctype;     /* Type of all values. */
781   uint8_t size_lg2;      /* Size of the hashtable part is 2^size_lg2 entries. */
782 
783   /* Hash table entries.
784    * Making this const isn't entirely accurate; what we really want is for it to
785    * have the same const-ness as the table it's inside.  But there's no way to
786    * declare that in C.  So we have to make it const so that we can statically
787    * initialize const hash tables.  Then we cast away const when we have to.
788    */
789   const upb_tabent *entries;
790 } upb_table;
791 
792 typedef struct {
793   upb_table t;
794 } upb_strtable;
795 
796 #define UPB_STRTABLE_INIT(count, mask, ctype, size_lg2, entries) \
797   {{count, mask, ctype, size_lg2, entries}}
798 
799 #define UPB_EMPTY_STRTABLE_INIT(ctype)                           \
800   UPB_STRTABLE_INIT(0, 0, ctype, 0, NULL)
801 
802 typedef struct {
803   upb_table t;              /* For entries that don't fit in the array part. */
804   const upb_tabval *array;  /* Array part of the table. See const note above. */
805   size_t array_size;        /* Array part size. */
806   size_t array_count;       /* Array part number of elements. */
807 } upb_inttable;
808 
809 #define UPB_INTTABLE_INIT(count, mask, ctype, size_lg2, ent, a, asize, acount) \
810   {{count, mask, ctype, size_lg2, ent}, a, asize, acount}
811 
812 #define UPB_EMPTY_INTTABLE_INIT(ctype) \
813   UPB_INTTABLE_INIT(0, 0, ctype, 0, NULL, NULL, 0, 0)
814 
815 #define UPB_ARRAY_EMPTYENT -1
816 
upb_table_size(const upb_table * t)817 UPB_INLINE size_t upb_table_size(const upb_table *t) {
818   if (t->size_lg2 == 0)
819     return 0;
820   else
821     return 1 << t->size_lg2;
822 }
823 
824 /* Internal-only functions, in .h file only out of necessity. */
upb_tabent_isempty(const upb_tabent * e)825 UPB_INLINE bool upb_tabent_isempty(const upb_tabent *e) {
826   return e->key == 0;
827 }
828 
829 /* Used by some of the unit tests for generic hashing functionality. */
830 uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed);
831 
upb_intkey(uintptr_t key)832 UPB_INLINE uintptr_t upb_intkey(uintptr_t key) {
833   return key;
834 }
835 
upb_inthash(uintptr_t key)836 UPB_INLINE uint32_t upb_inthash(uintptr_t key) {
837   return (uint32_t)key;
838 }
839 
upb_getentry(const upb_table * t,uint32_t hash)840 static const upb_tabent *upb_getentry(const upb_table *t, uint32_t hash) {
841   return t->entries + (hash & t->mask);
842 }
843 
upb_arrhas(upb_tabval key)844 UPB_INLINE bool upb_arrhas(upb_tabval key) {
845   return key.val != (uint64_t)-1;
846 }
847 
848 /* Initialize and uninitialize a table, respectively.  If memory allocation
849  * failed, false is returned that the table is uninitialized. */
850 bool upb_inttable_init(upb_inttable *table, upb_ctype_t ctype);
851 bool upb_strtable_init(upb_strtable *table, upb_ctype_t ctype);
852 void upb_inttable_uninit(upb_inttable *table);
853 void upb_strtable_uninit(upb_strtable *table);
854 
855 /* Returns the number of values in the table. */
856 size_t upb_inttable_count(const upb_inttable *t);
upb_strtable_count(const upb_strtable * t)857 UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) {
858   return t->t.count;
859 }
860 
861 /* Inserts the given key into the hashtable with the given value.  The key must
862  * not already exist in the hash table.  For string tables, the key must be
863  * NULL-terminated, and the table will make an internal copy of the key.
864  * Inttables must not insert a value of UINTPTR_MAX.
865  *
866  * If a table resize was required but memory allocation failed, false is
867  * returned and the table is unchanged. */
868 bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val);
869 bool upb_strtable_insert2(upb_strtable *t, const char *key, size_t len,
870                           upb_value val);
871 
872 /* For NULL-terminated strings. */
upb_strtable_insert(upb_strtable * t,const char * key,upb_value val)873 UPB_INLINE bool upb_strtable_insert(upb_strtable *t, const char *key,
874                                     upb_value val) {
875   return upb_strtable_insert2(t, key, strlen(key), val);
876 }
877 
878 /* Looks up key in this table, returning "true" if the key was found.
879  * If v is non-NULL, copies the value for this key into *v. */
880 bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v);
881 bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
882                           upb_value *v);
883 
884 /* For NULL-terminated strings. */
upb_strtable_lookup(const upb_strtable * t,const char * key,upb_value * v)885 UPB_INLINE bool upb_strtable_lookup(const upb_strtable *t, const char *key,
886                                     upb_value *v) {
887   return upb_strtable_lookup2(t, key, strlen(key), v);
888 }
889 
890 /* Removes an item from the table.  Returns true if the remove was successful,
891  * and stores the removed item in *val if non-NULL. */
892 bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val);
893 bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
894                           upb_value *val);
895 
896 /* For NULL-terminated strings. */
upb_strtable_remove(upb_strtable * t,const char * key,upb_value * v)897 UPB_INLINE bool upb_strtable_remove(upb_strtable *t, const char *key,
898                                     upb_value *v) {
899   return upb_strtable_remove2(t, key, strlen(key), v);
900 }
901 
902 /* Updates an existing entry in an inttable.  If the entry does not exist,
903  * returns false and does nothing.  Unlike insert/remove, this does not
904  * invalidate iterators. */
905 bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val);
906 
907 /* Handy routines for treating an inttable like a stack.  May not be mixed with
908  * other insert/remove calls. */
909 bool upb_inttable_push(upb_inttable *t, upb_value val);
910 upb_value upb_inttable_pop(upb_inttable *t);
911 
912 /* Convenience routines for inttables with pointer keys. */
913 bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val);
914 bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val);
915 bool upb_inttable_lookupptr(
916     const upb_inttable *t, const void *key, upb_value *val);
917 
918 /* Optimizes the table for the current set of entries, for both memory use and
919  * lookup time.  Client should call this after all entries have been inserted;
920  * inserting more entries is legal, but will likely require a table resize. */
921 void upb_inttable_compact(upb_inttable *t);
922 
923 /* A special-case inlinable version of the lookup routine for 32-bit
924  * integers. */
upb_inttable_lookup32(const upb_inttable * t,uint32_t key,upb_value * v)925 UPB_INLINE bool upb_inttable_lookup32(const upb_inttable *t, uint32_t key,
926                                       upb_value *v) {
927   *v = upb_value_int32(0);  /* Silence compiler warnings. */
928   if (key < t->array_size) {
929     upb_tabval arrval = t->array[key];
930     if (upb_arrhas(arrval)) {
931       _upb_value_setval(v, arrval.val, t->t.ctype);
932       return true;
933     } else {
934       return false;
935     }
936   } else {
937     const upb_tabent *e;
938     if (t->t.entries == NULL) return false;
939     for (e = upb_getentry(&t->t, upb_inthash(key)); true; e = e->next) {
940       if ((uint32_t)e->key == key) {
941         _upb_value_setval(v, e->val.val, t->t.ctype);
942         return true;
943       }
944       if (e->next == NULL) return false;
945     }
946   }
947 }
948 
949 /* Exposed for testing only. */
950 bool upb_strtable_resize(upb_strtable *t, size_t size_lg2);
951 
952 /* Iterators ******************************************************************/
953 
954 /* Iterators for int and string tables.  We are subject to some kind of unusual
955  * design constraints:
956  *
957  * For high-level languages:
958  *  - we must be able to guarantee that we don't crash or corrupt memory even if
959  *    the program accesses an invalidated iterator.
960  *
961  * For C++11 range-based for:
962  *  - iterators must be copyable
963  *  - iterators must be comparable
964  *  - it must be possible to construct an "end" value.
965  *
966  * Iteration order is undefined.
967  *
968  * Modifying the table invalidates iterators.  upb_{str,int}table_done() is
969  * guaranteed to work even on an invalidated iterator, as long as the table it
970  * is iterating over has not been freed.  Calling next() or accessing data from
971  * an invalidated iterator yields unspecified elements from the table, but it is
972  * guaranteed not to crash and to return real table elements (except when done()
973  * is true). */
974 
975 
976 /* upb_strtable_iter **********************************************************/
977 
978 /*   upb_strtable_iter i;
979  *   upb_strtable_begin(&i, t);
980  *   for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
981  *     const char *key = upb_strtable_iter_key(&i);
982  *     const upb_value val = upb_strtable_iter_value(&i);
983  *     // ...
984  *   }
985  */
986 
987 typedef struct {
988   const upb_strtable *t;
989   size_t index;
990 } upb_strtable_iter;
991 
992 void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t);
993 void upb_strtable_next(upb_strtable_iter *i);
994 bool upb_strtable_done(const upb_strtable_iter *i);
995 const char *upb_strtable_iter_key(upb_strtable_iter *i);
996 size_t upb_strtable_iter_keylength(upb_strtable_iter *i);
997 upb_value upb_strtable_iter_value(const upb_strtable_iter *i);
998 void upb_strtable_iter_setdone(upb_strtable_iter *i);
999 bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
1000                                const upb_strtable_iter *i2);
1001 
1002 
1003 /* upb_inttable_iter **********************************************************/
1004 
1005 /*   upb_inttable_iter i;
1006  *   upb_inttable_begin(&i, t);
1007  *   for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
1008  *     uintptr_t key = upb_inttable_iter_key(&i);
1009  *     upb_value val = upb_inttable_iter_value(&i);
1010  *     // ...
1011  *   }
1012  */
1013 
1014 typedef struct {
1015   const upb_inttable *t;
1016   size_t index;
1017   bool array_part;
1018 } upb_inttable_iter;
1019 
1020 void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t);
1021 void upb_inttable_next(upb_inttable_iter *i);
1022 bool upb_inttable_done(const upb_inttable_iter *i);
1023 uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i);
1024 upb_value upb_inttable_iter_value(const upb_inttable_iter *i);
1025 void upb_inttable_iter_setdone(upb_inttable_iter *i);
1026 bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
1027                                const upb_inttable_iter *i2);
1028 
1029 
1030 #ifdef __cplusplus
1031 }  /* extern "C" */
1032 #endif
1033 
1034 #endif  /* UPB_TABLE_H_ */
1035 
1036 /* Reference tracking will check ref()/unref() operations to make sure the
1037  * ref ownership is correct.  Where possible it will also make tools like
1038  * Valgrind attribute ref leaks to the code that took the leaked ref, not
1039  * the code that originally created the object.
1040  *
1041  * Enabling this requires the application to define upb_lock()/upb_unlock()
1042  * functions that acquire/release a global mutex (or #define UPB_THREAD_UNSAFE).
1043  * For this reason we don't enable it by default, even in debug builds.
1044  */
1045 
1046 /* #define UPB_DEBUG_REFS */
1047 
1048 #ifdef __cplusplus
1049 namespace upb { class RefCounted; }
1050 #endif
1051 
1052 UPB_DECLARE_TYPE(upb::RefCounted, upb_refcounted)
1053 
1054 struct upb_refcounted_vtbl;
1055 
1056 #ifdef __cplusplus
1057 
1058 class upb::RefCounted {
1059  public:
1060   /* Returns true if the given object is frozen. */
1061   bool IsFrozen() const;
1062 
1063   /* Increases the ref count, the new ref is owned by "owner" which must not
1064    * already own a ref (and should not itself be a refcounted object if the ref
1065    * could possibly be circular; see below).
1066    * Thread-safe iff "this" is frozen. */
1067   void Ref(const void *owner) const;
1068 
1069   /* Release a ref that was acquired from upb_refcounted_ref() and collects any
1070    * objects it can. */
1071   void Unref(const void *owner) const;
1072 
1073   /* Moves an existing ref from "from" to "to", without changing the overall
1074    * ref count.  DonateRef(foo, NULL, owner) is the same as Ref(foo, owner),
1075    * but "to" may not be NULL. */
1076   void DonateRef(const void *from, const void *to) const;
1077 
1078   /* Verifies that a ref to the given object is currently held by the given
1079    * owner.  Only effective in UPB_DEBUG_REFS builds. */
1080   void CheckRef(const void *owner) const;
1081 
1082  private:
1083   UPB_DISALLOW_POD_OPS(RefCounted, upb::RefCounted)
1084 #else
1085 struct upb_refcounted {
1086 #endif
1087   /* TODO(haberman): move the actual structure definition to structdefs.int.h.
1088    * The only reason they are here is because inline functions need to see the
1089    * definition of upb_handlers, which needs to see this definition.  But we
1090    * can change the upb_handlers inline functions to deal in raw offsets
1091    * instead.
1092    */
1093 
1094   /* A single reference count shared by all objects in the group. */
1095   uint32_t *group;
1096 
1097   /* A singly-linked list of all objects in the group. */
1098   upb_refcounted *next;
1099 
1100   /* Table of function pointers for this type. */
1101   const struct upb_refcounted_vtbl *vtbl;
1102 
1103   /* Maintained only when mutable, this tracks the number of refs (but not
1104    * ref2's) to this object.  *group should be the sum of all individual_count
1105    * in the group. */
1106   uint32_t individual_count;
1107 
1108   bool is_frozen;
1109 
1110 #ifdef UPB_DEBUG_REFS
1111   upb_inttable *refs;  /* Maps owner -> trackedref for incoming refs. */
1112   upb_inttable *ref2s; /* Set of targets for outgoing ref2s. */
1113 #endif
1114 };
1115 
1116 #ifdef UPB_DEBUG_REFS
1117 #define UPB_REFCOUNT_INIT(refs, ref2s) \
1118     {&static_refcount, NULL, NULL, 0, true, refs, ref2s}
1119 #else
1120 #define UPB_REFCOUNT_INIT(refs, ref2s) {&static_refcount, NULL, NULL, 0, true}
1121 #endif
1122 
1123 UPB_BEGIN_EXTERN_C
1124 
1125 /* It is better to use tracked refs when possible, for the extra debugging
1126  * capability.  But if this is not possible (because you don't have easy access
1127  * to a stable pointer value that is associated with the ref), you can pass
1128  * UPB_UNTRACKED_REF instead.  */
1129 extern const void *UPB_UNTRACKED_REF;
1130 
1131 /* Native C API. */
1132 bool upb_refcounted_isfrozen(const upb_refcounted *r);
1133 void upb_refcounted_ref(const upb_refcounted *r, const void *owner);
1134 void upb_refcounted_unref(const upb_refcounted *r, const void *owner);
1135 void upb_refcounted_donateref(
1136     const upb_refcounted *r, const void *from, const void *to);
1137 void upb_refcounted_checkref(const upb_refcounted *r, const void *owner);
1138 
1139 #define UPB_REFCOUNTED_CMETHODS(type, upcastfunc) \
1140   UPB_INLINE bool type ## _isfrozen(const type *v) { \
1141     return upb_refcounted_isfrozen(upcastfunc(v)); \
1142   } \
1143   UPB_INLINE void type ## _ref(const type *v, const void *owner) { \
1144     upb_refcounted_ref(upcastfunc(v), owner); \
1145   } \
1146   UPB_INLINE void type ## _unref(const type *v, const void *owner) { \
1147     upb_refcounted_unref(upcastfunc(v), owner); \
1148   } \
1149   UPB_INLINE void type ## _donateref(const type *v, const void *from, const void *to) { \
1150     upb_refcounted_donateref(upcastfunc(v), from, to); \
1151   } \
1152   UPB_INLINE void type ## _checkref(const type *v, const void *owner) { \
1153     upb_refcounted_checkref(upcastfunc(v), owner); \
1154   }
1155 
1156 #define UPB_REFCOUNTED_CPPMETHODS \
1157   bool IsFrozen() const { \
1158     return upb::upcast_to<const upb::RefCounted>(this)->IsFrozen(); \
1159   } \
1160   void Ref(const void *owner) const { \
1161     return upb::upcast_to<const upb::RefCounted>(this)->Ref(owner); \
1162   } \
1163   void Unref(const void *owner) const { \
1164     return upb::upcast_to<const upb::RefCounted>(this)->Unref(owner); \
1165   } \
1166   void DonateRef(const void *from, const void *to) const { \
1167     return upb::upcast_to<const upb::RefCounted>(this)->DonateRef(from, to); \
1168   } \
1169   void CheckRef(const void *owner) const { \
1170     return upb::upcast_to<const upb::RefCounted>(this)->CheckRef(owner); \
1171   }
1172 
1173 /* Internal-to-upb Interface **************************************************/
1174 
1175 typedef void upb_refcounted_visit(const upb_refcounted *r,
1176                                   const upb_refcounted *subobj,
1177                                   void *closure);
1178 
1179 struct upb_refcounted_vtbl {
1180   /* Must visit all subobjects that are currently ref'd via upb_refcounted_ref2.
1181    * Must be longjmp()-safe. */
1182   void (*visit)(const upb_refcounted *r, upb_refcounted_visit *visit, void *c);
1183 
1184   /* Must free the object and release all references to other objects. */
1185   void (*free)(upb_refcounted *r);
1186 };
1187 
1188 /* Initializes the refcounted with a single ref for the given owner.  Returns
1189  * false if memory could not be allocated. */
1190 bool upb_refcounted_init(upb_refcounted *r,
1191                          const struct upb_refcounted_vtbl *vtbl,
1192                          const void *owner);
1193 
1194 /* Adds a ref from one refcounted object to another ("from" must not already
1195  * own a ref).  These refs may be circular; cycles will be collected correctly
1196  * (if conservatively).  These refs do not need to be freed in from's free()
1197  * function. */
1198 void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from);
1199 
1200 /* Removes a ref that was acquired from upb_refcounted_ref2(), and collects any
1201  * object it can.  This is only necessary when "from" no longer points to "r",
1202  * and not from from's "free" function. */
1203 void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from);
1204 
1205 #define upb_ref2(r, from) \
1206     upb_refcounted_ref2((const upb_refcounted*)r, (upb_refcounted*)from)
1207 #define upb_unref2(r, from) \
1208     upb_refcounted_unref2((const upb_refcounted*)r, (upb_refcounted*)from)
1209 
1210 /* Freezes all mutable object reachable by ref2() refs from the given roots.
1211  * This will split refcounting groups into precise SCC groups, so that
1212  * refcounting of frozen objects can be more aggressive.  If memory allocation
1213  * fails, or if more than 2**31 mutable objects are reachable from "roots", or
1214  * if the maximum depth of the graph exceeds "maxdepth", false is returned and
1215  * the objects are unchanged.
1216  *
1217  * After this operation succeeds, the objects are frozen/const, and may not be
1218  * used through non-const pointers.  In particular, they may not be passed as
1219  * the second parameter of upb_refcounted_{ref,unref}2().  On the upside, all
1220  * operations on frozen refcounteds are threadsafe, and objects will be freed
1221  * at the precise moment that they become unreachable.
1222  *
1223  * Caller must own refs on each object in the "roots" list. */
1224 bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
1225                            int maxdepth);
1226 
1227 /* Shared by all compiled-in refcounted objects. */
1228 extern uint32_t static_refcount;
1229 
1230 UPB_END_EXTERN_C
1231 
1232 #ifdef __cplusplus
1233 /* C++ Wrappers. */
1234 namespace upb {
IsFrozen()1235 inline bool RefCounted::IsFrozen() const {
1236   return upb_refcounted_isfrozen(this);
1237 }
Ref(const void * owner)1238 inline void RefCounted::Ref(const void *owner) const {
1239   upb_refcounted_ref(this, owner);
1240 }
Unref(const void * owner)1241 inline void RefCounted::Unref(const void *owner) const {
1242   upb_refcounted_unref(this, owner);
1243 }
DonateRef(const void * from,const void * to)1244 inline void RefCounted::DonateRef(const void *from, const void *to) const {
1245   upb_refcounted_donateref(this, from, to);
1246 }
CheckRef(const void * owner)1247 inline void RefCounted::CheckRef(const void *owner) const {
1248   upb_refcounted_checkref(this, owner);
1249 }
1250 }  /* namespace upb */
1251 #endif
1252 
1253 #endif  /* UPB_REFCOUNT_H_ */
1254 
1255 #ifdef __cplusplus
1256 #include <cstring>
1257 #include <string>
1258 #include <vector>
1259 
1260 namespace upb {
1261 class Def;
1262 class EnumDef;
1263 class FieldDef;
1264 class MessageDef;
1265 class OneofDef;
1266 }
1267 #endif
1268 
1269 UPB_DECLARE_DERIVED_TYPE(upb::Def, upb::RefCounted, upb_def, upb_refcounted)
1270 
1271 /* The maximum message depth that the type graph can have.  This is a resource
1272  * limit for the C stack since we sometimes need to recursively traverse the
1273  * graph.  Cycles are ok; the traversal will stop when it detects a cycle, but
1274  * we must hit the cycle before the maximum depth is reached.
1275  *
1276  * If having a single static limit is too inflexible, we can add another variant
1277  * of Def::Freeze that allows specifying this as a parameter. */
1278 #define UPB_MAX_MESSAGE_DEPTH 64
1279 
1280 
1281 /* upb::Def: base class for defs  *********************************************/
1282 
1283 /* All the different kind of defs we support.  These correspond 1:1 with
1284  * declarations in a .proto file. */
1285 typedef enum {
1286   UPB_DEF_MSG,
1287   UPB_DEF_FIELD,
1288   UPB_DEF_ENUM,
1289   UPB_DEF_ONEOF,
1290   UPB_DEF_SERVICE,   /* Not yet implemented. */
1291   UPB_DEF_ANY = -1   /* Wildcard for upb_symtab_get*() */
1292 } upb_deftype_t;
1293 
1294 #ifdef __cplusplus
1295 
1296 /* The base class of all defs.  Its base is upb::RefCounted (use upb::upcast()
1297  * to convert). */
1298 class upb::Def {
1299  public:
1300   typedef upb_deftype_t Type;
1301 
1302   Def* Dup(const void *owner) const;
1303 
1304   /* upb::RefCounted methods like Ref()/Unref(). */
1305   UPB_REFCOUNTED_CPPMETHODS
1306 
1307   Type def_type() const;
1308 
1309   /* "fullname" is the def's fully-qualified name (eg. foo.bar.Message). */
1310   const char *full_name() const;
1311 
1312   /* The def must be mutable.  Caller retains ownership of fullname.  Defs are
1313    * not required to have a name; if a def has no name when it is frozen, it
1314    * will remain an anonymous def.  On failure, returns false and details in "s"
1315    * if non-NULL. */
1316   bool set_full_name(const char* fullname, upb::Status* s);
1317   bool set_full_name(const std::string &fullname, upb::Status* s);
1318 
1319   /* Freezes the given defs; this validates all constraints and marks the defs
1320    * as frozen (read-only).  "defs" may not contain any fielddefs, but fields
1321    * of any msgdefs will be frozen.
1322    *
1323    * Symbolic references to sub-types and enum defaults must have already been
1324    * resolved.  Any mutable defs reachable from any of "defs" must also be in
1325    * the list; more formally, "defs" must be a transitive closure of mutable
1326    * defs.
1327    *
1328    * After this operation succeeds, the finalized defs must only be accessed
1329    * through a const pointer! */
1330   static bool Freeze(Def* const* defs, int n, Status* status);
1331   static bool Freeze(const std::vector<Def*>& defs, Status* status);
1332 
1333  private:
1334   UPB_DISALLOW_POD_OPS(Def, upb::Def)
1335 };
1336 
1337 #endif  /* __cplusplus */
1338 
1339 UPB_BEGIN_EXTERN_C
1340 
1341 /* Native C API. */
1342 upb_def *upb_def_dup(const upb_def *def, const void *owner);
1343 
1344 /* Include upb_refcounted methods like upb_def_ref()/upb_def_unref(). */
1345 UPB_REFCOUNTED_CMETHODS(upb_def, upb_def_upcast)
1346 
1347 upb_deftype_t upb_def_type(const upb_def *d);
1348 const char *upb_def_fullname(const upb_def *d);
1349 bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s);
1350 bool upb_def_freeze(upb_def *const *defs, int n, upb_status *s);
1351 
1352 UPB_END_EXTERN_C
1353 
1354 
1355 /* upb::Def casts *************************************************************/
1356 
1357 #ifdef __cplusplus
1358 #define UPB_CPP_CASTS(cname, cpptype)                                          \
1359   namespace upb {                                                              \
1360   template <>                                                                  \
1361   inline cpptype *down_cast<cpptype *, Def>(Def * def) {                       \
1362     return upb_downcast_##cname##_mutable(def);                                \
1363   }                                                                            \
1364   template <>                                                                  \
1365   inline cpptype *dyn_cast<cpptype *, Def>(Def * def) {                        \
1366     return upb_dyncast_##cname##_mutable(def);                                 \
1367   }                                                                            \
1368   template <>                                                                  \
1369   inline const cpptype *down_cast<const cpptype *, const Def>(                 \
1370       const Def *def) {                                                        \
1371     return upb_downcast_##cname(def);                                          \
1372   }                                                                            \
1373   template <>                                                                  \
1374   inline const cpptype *dyn_cast<const cpptype *, const Def>(const Def *def) { \
1375     return upb_dyncast_##cname(def);                                           \
1376   }                                                                            \
1377   template <>                                                                  \
1378   inline const cpptype *down_cast<const cpptype *, Def>(Def * def) {           \
1379     return upb_downcast_##cname(def);                                          \
1380   }                                                                            \
1381   template <>                                                                  \
1382   inline const cpptype *dyn_cast<const cpptype *, Def>(Def * def) {            \
1383     return upb_dyncast_##cname(def);                                           \
1384   }                                                                            \
1385   }  /* namespace upb */
1386 #else
1387 #define UPB_CPP_CASTS(cname, cpptype)
1388 #endif  /* __cplusplus */
1389 
1390 /* Dynamic casts, for determining if a def is of a particular type at runtime.
1391  * Downcasts, for when some wants to assert that a def is of a particular type.
1392  * These are only checked if we are building debug. */
1393 #define UPB_DEF_CASTS(lower, upper, cpptype)                               \
1394   UPB_INLINE const upb_##lower *upb_dyncast_##lower(const upb_def *def) {  \
1395     if (upb_def_type(def) != UPB_DEF_##upper) return NULL;                 \
1396     return (upb_##lower *)def;                                             \
1397   }                                                                        \
1398   UPB_INLINE const upb_##lower *upb_downcast_##lower(const upb_def *def) { \
1399     assert(upb_def_type(def) == UPB_DEF_##upper);                          \
1400     return (const upb_##lower *)def;                                       \
1401   }                                                                        \
1402   UPB_INLINE upb_##lower *upb_dyncast_##lower##_mutable(upb_def *def) {    \
1403     return (upb_##lower *)upb_dyncast_##lower(def);                        \
1404   }                                                                        \
1405   UPB_INLINE upb_##lower *upb_downcast_##lower##_mutable(upb_def *def) {   \
1406     return (upb_##lower *)upb_downcast_##lower(def);                       \
1407   }                                                                        \
1408   UPB_CPP_CASTS(lower, cpptype)
1409 
1410 #define UPB_DEFINE_DEF(cppname, lower, upper, cppmethods, members)             \
1411   UPB_DEFINE_CLASS2(cppname, upb::Def, upb::RefCounted, cppmethods,            \
1412                    members)                                                    \
1413   UPB_DEF_CASTS(lower, upper, cppname)
1414 
1415 #define UPB_DECLARE_DEF_TYPE(cppname, lower, upper) \
1416   UPB_DECLARE_DERIVED_TYPE2(cppname, upb::Def, upb::RefCounted, \
1417                             upb_ ## lower, upb_def, upb_refcounted) \
1418   UPB_DEF_CASTS(lower, upper, cppname)
1419 
1420 UPB_DECLARE_DEF_TYPE(upb::FieldDef, fielddef, FIELD)
1421 UPB_DECLARE_DEF_TYPE(upb::MessageDef, msgdef, MSG)
1422 UPB_DECLARE_DEF_TYPE(upb::EnumDef, enumdef, ENUM)
1423 UPB_DECLARE_DEF_TYPE(upb::OneofDef, oneofdef, ONEOF)
1424 
1425 #undef UPB_DECLARE_DEF_TYPE
1426 #undef UPB_DEF_CASTS
1427 #undef UPB_CPP_CASTS
1428 
1429 
1430 /* upb::FieldDef **************************************************************/
1431 
1432 /* The types a field can have.  Note that this list is not identical to the
1433  * types defined in descriptor.proto, which gives INT32 and SINT32 separate
1434  * types (we distinguish the two with the "integer encoding" enum below). */
1435 typedef enum {
1436   UPB_TYPE_FLOAT    = 1,
1437   UPB_TYPE_DOUBLE   = 2,
1438   UPB_TYPE_BOOL     = 3,
1439   UPB_TYPE_STRING   = 4,
1440   UPB_TYPE_BYTES    = 5,
1441   UPB_TYPE_MESSAGE  = 6,
1442   UPB_TYPE_ENUM     = 7,  /* Enum values are int32. */
1443   UPB_TYPE_INT32    = 8,
1444   UPB_TYPE_UINT32   = 9,
1445   UPB_TYPE_INT64    = 10,
1446   UPB_TYPE_UINT64   = 11
1447 } upb_fieldtype_t;
1448 
1449 /* The repeated-ness of each field; this matches descriptor.proto. */
1450 typedef enum {
1451   UPB_LABEL_OPTIONAL = 1,
1452   UPB_LABEL_REQUIRED = 2,
1453   UPB_LABEL_REPEATED = 3
1454 } upb_label_t;
1455 
1456 /* How integers should be encoded in serializations that offer multiple
1457  * integer encoding methods. */
1458 typedef enum {
1459   UPB_INTFMT_VARIABLE = 1,
1460   UPB_INTFMT_FIXED = 2,
1461   UPB_INTFMT_ZIGZAG = 3   /* Only for signed types (INT32/INT64). */
1462 } upb_intfmt_t;
1463 
1464 /* Descriptor types, as defined in descriptor.proto. */
1465 typedef enum {
1466   UPB_DESCRIPTOR_TYPE_DOUBLE   = 1,
1467   UPB_DESCRIPTOR_TYPE_FLOAT    = 2,
1468   UPB_DESCRIPTOR_TYPE_INT64    = 3,
1469   UPB_DESCRIPTOR_TYPE_UINT64   = 4,
1470   UPB_DESCRIPTOR_TYPE_INT32    = 5,
1471   UPB_DESCRIPTOR_TYPE_FIXED64  = 6,
1472   UPB_DESCRIPTOR_TYPE_FIXED32  = 7,
1473   UPB_DESCRIPTOR_TYPE_BOOL     = 8,
1474   UPB_DESCRIPTOR_TYPE_STRING   = 9,
1475   UPB_DESCRIPTOR_TYPE_GROUP    = 10,
1476   UPB_DESCRIPTOR_TYPE_MESSAGE  = 11,
1477   UPB_DESCRIPTOR_TYPE_BYTES    = 12,
1478   UPB_DESCRIPTOR_TYPE_UINT32   = 13,
1479   UPB_DESCRIPTOR_TYPE_ENUM     = 14,
1480   UPB_DESCRIPTOR_TYPE_SFIXED32 = 15,
1481   UPB_DESCRIPTOR_TYPE_SFIXED64 = 16,
1482   UPB_DESCRIPTOR_TYPE_SINT32   = 17,
1483   UPB_DESCRIPTOR_TYPE_SINT64   = 18
1484 } upb_descriptortype_t;
1485 
1486 /* Maximum field number allowed for FieldDefs.  This is an inherent limit of the
1487  * protobuf wire format. */
1488 #define UPB_MAX_FIELDNUMBER ((1 << 29) - 1)
1489 
1490 #ifdef __cplusplus
1491 
1492 /* A upb_fielddef describes a single field in a message.  It is most often
1493  * found as a part of a upb_msgdef, but can also stand alone to represent
1494  * an extension.
1495  *
1496  * Its base class is upb::Def (use upb::upcast() to convert). */
1497 class upb::FieldDef {
1498  public:
1499   typedef upb_fieldtype_t Type;
1500   typedef upb_label_t Label;
1501   typedef upb_intfmt_t IntegerFormat;
1502   typedef upb_descriptortype_t DescriptorType;
1503 
1504   /* These return true if the given value is a valid member of the enumeration. */
1505   static bool CheckType(int32_t val);
1506   static bool CheckLabel(int32_t val);
1507   static bool CheckDescriptorType(int32_t val);
1508   static bool CheckIntegerFormat(int32_t val);
1509 
1510   /* These convert to the given enumeration; they require that the value is
1511    * valid. */
1512   static Type ConvertType(int32_t val);
1513   static Label ConvertLabel(int32_t val);
1514   static DescriptorType ConvertDescriptorType(int32_t val);
1515   static IntegerFormat ConvertIntegerFormat(int32_t val);
1516 
1517   /* Returns NULL if memory allocation failed. */
1518   static reffed_ptr<FieldDef> New();
1519 
1520   /* Duplicates the given field, returning NULL if memory allocation failed.
1521    * When a fielddef is duplicated, the subdef (if any) is made symbolic if it
1522    * wasn't already.  If the subdef is set but has no name (which is possible
1523    * since msgdefs are not required to have a name) the new fielddef's subdef
1524    * will be unset. */
1525   FieldDef* Dup(const void* owner) const;
1526 
1527   /* upb::RefCounted methods like Ref()/Unref(). */
1528   UPB_REFCOUNTED_CPPMETHODS
1529 
1530   /* Functionality from upb::Def. */
1531   const char* full_name() const;
1532 
1533   bool type_is_set() const;  /* set_[descriptor_]type() has been called? */
1534   Type type() const;         /* Requires that type_is_set() == true. */
1535   Label label() const;       /* Defaults to UPB_LABEL_OPTIONAL. */
1536   const char* name() const;  /* NULL if uninitialized. */
1537   uint32_t number() const;   /* Returns 0 if uninitialized. */
1538   bool is_extension() const;
1539 
1540   /* For UPB_TYPE_MESSAGE fields only where is_tag_delimited() == false,
1541    * indicates whether this field should have lazy parsing handlers that yield
1542    * the unparsed string for the submessage.
1543    *
1544    * TODO(haberman): I think we want to move this into a FieldOptions container
1545    * when we add support for custom options (the FieldOptions struct will
1546    * contain both regular FieldOptions like "lazy" *and* custom options). */
1547   bool lazy() const;
1548 
1549   /* For non-string, non-submessage fields, this indicates whether binary
1550    * protobufs are encoded in packed or non-packed format.
1551    *
1552    * TODO(haberman): see note above about putting options like this into a
1553    * FieldOptions container. */
1554   bool packed() const;
1555 
1556   /* An integer that can be used as an index into an array of fields for
1557    * whatever message this field belongs to.  Guaranteed to be less than
1558    * f->containing_type()->field_count().  May only be accessed once the def has
1559    * been finalized. */
1560   int index() const;
1561 
1562   /* The MessageDef to which this field belongs.
1563    *
1564    * If this field has been added to a MessageDef, that message can be retrieved
1565    * directly (this is always the case for frozen FieldDefs).
1566    *
1567    * If the field has not yet been added to a MessageDef, you can set the name
1568    * of the containing type symbolically instead.  This is mostly useful for
1569    * extensions, where the extension is declared separately from the message. */
1570   const MessageDef* containing_type() const;
1571   const char* containing_type_name();
1572 
1573   /* The OneofDef to which this field belongs, or NULL if this field is not part
1574    * of a oneof. */
1575   const OneofDef* containing_oneof() const;
1576 
1577   /* The field's type according to the enum in descriptor.proto.  This is not
1578    * the same as UPB_TYPE_*, because it distinguishes between (for example)
1579    * INT32 and SINT32, whereas our "type" enum does not.  This return of
1580    * descriptor_type() is a function of type(), integer_format(), and
1581    * is_tag_delimited().  Likewise set_descriptor_type() sets all three
1582    * appropriately. */
1583   DescriptorType descriptor_type() const;
1584 
1585   /* Convenient field type tests. */
1586   bool IsSubMessage() const;
1587   bool IsString() const;
1588   bool IsSequence() const;
1589   bool IsPrimitive() const;
1590   bool IsMap() const;
1591 
1592   /* How integers are encoded.  Only meaningful for integer types.
1593    * Defaults to UPB_INTFMT_VARIABLE, and is reset when "type" changes. */
1594   IntegerFormat integer_format() const;
1595 
1596   /* Whether a submessage field is tag-delimited or not (if false, then
1597    * length-delimited).  May only be set when type() == UPB_TYPE_MESSAGE. */
1598   bool is_tag_delimited() const;
1599 
1600   /* Returns the non-string default value for this fielddef, which may either
1601    * be something the client set explicitly or the "default default" (0 for
1602    * numbers, empty for strings).  The field's type indicates the type of the
1603    * returned value, except for enum fields that are still mutable.
1604    *
1605    * Requires that the given function matches the field's current type. */
1606   int64_t default_int64() const;
1607   int32_t default_int32() const;
1608   uint64_t default_uint64() const;
1609   uint32_t default_uint32() const;
1610   bool default_bool() const;
1611   float default_float() const;
1612   double default_double() const;
1613 
1614   /* The resulting string is always NULL-terminated.  If non-NULL, the length
1615    * will be stored in *len. */
1616   const char *default_string(size_t* len) const;
1617 
1618   /* For frozen UPB_TYPE_ENUM fields, enum defaults can always be read as either
1619    * string or int32, and both of these methods will always return true.
1620    *
1621    * For mutable UPB_TYPE_ENUM fields, the story is a bit more complicated.
1622    * Enum defaults are unusual. They can be specified either as string or int32,
1623    * but to be valid the enum must have that value as a member.  And if no
1624    * default is specified, the "default default" comes from the EnumDef.
1625    *
1626    * We allow reading the default as either an int32 or a string, but only if
1627    * we have a meaningful value to report.  We have a meaningful value if it was
1628    * set explicitly, or if we could get the "default default" from the EnumDef.
1629    * Also if you explicitly set the name and we find the number in the EnumDef */
1630   bool EnumHasStringDefault() const;
1631   bool EnumHasInt32Default() const;
1632 
1633   /* Submessage and enum fields must reference a "subdef", which is the
1634    * upb::MessageDef or upb::EnumDef that defines their type.  Note that when
1635    * the FieldDef is mutable it may not have a subdef *yet*, but this function
1636    * still returns true to indicate that the field's type requires a subdef. */
1637   bool HasSubDef() const;
1638 
1639   /* Returns the enum or submessage def for this field, if any.  The field's
1640    * type must match (ie. you may only call enum_subdef() for fields where
1641    * type() == UPB_TYPE_ENUM).  Returns NULL if the subdef has not been set or
1642    * is currently set symbolically. */
1643   const EnumDef* enum_subdef() const;
1644   const MessageDef* message_subdef() const;
1645 
1646   /* Returns the generic subdef for this field.  Requires that HasSubDef() (ie.
1647    * only works for UPB_TYPE_ENUM and UPB_TYPE_MESSAGE fields). */
1648   const Def* subdef() const;
1649 
1650   /* Returns the symbolic name of the subdef.  If the subdef is currently set
1651    * unresolved (ie. set symbolically) returns the symbolic name.  If it has
1652    * been resolved to a specific subdef, returns the name from that subdef. */
1653   const char* subdef_name() const;
1654 
1655   /* Setters (non-const methods), only valid for mutable FieldDefs! ***********/
1656 
1657   bool set_full_name(const char* fullname, upb::Status* s);
1658   bool set_full_name(const std::string& fullname, upb::Status* s);
1659 
1660   /* This may only be called if containing_type() == NULL (ie. the field has not
1661    * been added to a message yet). */
1662   bool set_containing_type_name(const char *name, Status* status);
1663   bool set_containing_type_name(const std::string& name, Status* status);
1664 
1665   /* Defaults to false.  When we freeze, we ensure that this can only be true
1666    * for length-delimited message fields.  Prior to freezing this can be true or
1667    * false with no restrictions. */
1668   void set_lazy(bool lazy);
1669 
1670   /* Defaults to true.  Sets whether this field is encoded in packed format. */
1671   void set_packed(bool packed);
1672 
1673   /* "type" or "descriptor_type" MUST be set explicitly before the fielddef is
1674    * finalized.  These setters require that the enum value is valid; if the
1675    * value did not come directly from an enum constant, the caller should
1676    * validate it first with the functions above (CheckFieldType(), etc). */
1677   void set_type(Type type);
1678   void set_label(Label label);
1679   void set_descriptor_type(DescriptorType type);
1680   void set_is_extension(bool is_extension);
1681 
1682   /* "number" and "name" must be set before the FieldDef is added to a
1683    * MessageDef, and may not be set after that.
1684    *
1685    * "name" is the same as full_name()/set_full_name(), but since fielddefs
1686    * most often use simple, non-qualified names, we provide this accessor
1687    * also.  Generally only extensions will want to think of this name as
1688    * fully-qualified. */
1689   bool set_number(uint32_t number, upb::Status* s);
1690   bool set_name(const char* name, upb::Status* s);
1691   bool set_name(const std::string& name, upb::Status* s);
1692 
1693   void set_integer_format(IntegerFormat format);
1694   bool set_tag_delimited(bool tag_delimited, upb::Status* s);
1695 
1696   /* Sets default value for the field.  The call must exactly match the type
1697    * of the field.  Enum fields may use either setint32 or setstring to set
1698    * the default numerically or symbolically, respectively, but symbolic
1699    * defaults must be resolved before finalizing (see ResolveEnumDefault()).
1700    *
1701    * Changing the type of a field will reset its default. */
1702   void set_default_int64(int64_t val);
1703   void set_default_int32(int32_t val);
1704   void set_default_uint64(uint64_t val);
1705   void set_default_uint32(uint32_t val);
1706   void set_default_bool(bool val);
1707   void set_default_float(float val);
1708   void set_default_double(double val);
1709   bool set_default_string(const void *str, size_t len, Status *s);
1710   bool set_default_string(const std::string &str, Status *s);
1711   void set_default_cstr(const char *str, Status *s);
1712 
1713   /* Before a fielddef is frozen, its subdef may be set either directly (with a
1714    * upb::Def*) or symbolically.  Symbolic refs must be resolved before the
1715    * containing msgdef can be frozen (see upb_resolve() above).  upb always
1716    * guarantees that any def reachable from a live def will also be kept alive.
1717    *
1718    * Both methods require that upb_hassubdef(f) (so the type must be set prior
1719    * to calling these methods).  Returns false if this is not the case, or if
1720    * the given subdef is not of the correct type.  The subdef is reset if the
1721    * field's type is changed.  The subdef can be set to NULL to clear it. */
1722   bool set_subdef(const Def* subdef, Status* s);
1723   bool set_enum_subdef(const EnumDef* subdef, Status* s);
1724   bool set_message_subdef(const MessageDef* subdef, Status* s);
1725   bool set_subdef_name(const char* name, Status* s);
1726   bool set_subdef_name(const std::string &name, Status* s);
1727 
1728  private:
1729   UPB_DISALLOW_POD_OPS(FieldDef, upb::FieldDef)
1730 };
1731 
1732 # endif  /* defined(__cplusplus) */
1733 
1734 UPB_BEGIN_EXTERN_C
1735 
1736 /* Native C API. */
1737 upb_fielddef *upb_fielddef_new(const void *owner);
1738 upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner);
1739 
1740 /* Include upb_refcounted methods like upb_fielddef_ref(). */
1741 UPB_REFCOUNTED_CMETHODS(upb_fielddef, upb_fielddef_upcast2)
1742 
1743 /* Methods from upb_def. */
1744 const char *upb_fielddef_fullname(const upb_fielddef *f);
1745 bool upb_fielddef_setfullname(upb_fielddef *f, const char *fullname,
1746                               upb_status *s);
1747 
1748 bool upb_fielddef_typeisset(const upb_fielddef *f);
1749 upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f);
1750 upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f);
1751 upb_label_t upb_fielddef_label(const upb_fielddef *f);
1752 uint32_t upb_fielddef_number(const upb_fielddef *f);
1753 const char *upb_fielddef_name(const upb_fielddef *f);
1754 bool upb_fielddef_isextension(const upb_fielddef *f);
1755 bool upb_fielddef_lazy(const upb_fielddef *f);
1756 bool upb_fielddef_packed(const upb_fielddef *f);
1757 const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f);
1758 const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f);
1759 upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f);
1760 const char *upb_fielddef_containingtypename(upb_fielddef *f);
1761 upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f);
1762 uint32_t upb_fielddef_index(const upb_fielddef *f);
1763 bool upb_fielddef_istagdelim(const upb_fielddef *f);
1764 bool upb_fielddef_issubmsg(const upb_fielddef *f);
1765 bool upb_fielddef_isstring(const upb_fielddef *f);
1766 bool upb_fielddef_isseq(const upb_fielddef *f);
1767 bool upb_fielddef_isprimitive(const upb_fielddef *f);
1768 bool upb_fielddef_ismap(const upb_fielddef *f);
1769 int64_t upb_fielddef_defaultint64(const upb_fielddef *f);
1770 int32_t upb_fielddef_defaultint32(const upb_fielddef *f);
1771 uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f);
1772 uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f);
1773 bool upb_fielddef_defaultbool(const upb_fielddef *f);
1774 float upb_fielddef_defaultfloat(const upb_fielddef *f);
1775 double upb_fielddef_defaultdouble(const upb_fielddef *f);
1776 const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len);
1777 bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f);
1778 bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f);
1779 bool upb_fielddef_hassubdef(const upb_fielddef *f);
1780 const upb_def *upb_fielddef_subdef(const upb_fielddef *f);
1781 const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f);
1782 const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f);
1783 const char *upb_fielddef_subdefname(const upb_fielddef *f);
1784 
1785 void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type);
1786 void upb_fielddef_setdescriptortype(upb_fielddef *f, int type);
1787 void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label);
1788 bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s);
1789 bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s);
1790 bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
1791                                         upb_status *s);
1792 void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension);
1793 void upb_fielddef_setlazy(upb_fielddef *f, bool lazy);
1794 void upb_fielddef_setpacked(upb_fielddef *f, bool packed);
1795 void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt);
1796 void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim);
1797 void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t val);
1798 void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t val);
1799 void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t val);
1800 void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t val);
1801 void upb_fielddef_setdefaultbool(upb_fielddef *f, bool val);
1802 void upb_fielddef_setdefaultfloat(upb_fielddef *f, float val);
1803 void upb_fielddef_setdefaultdouble(upb_fielddef *f, double val);
1804 bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
1805                                 upb_status *s);
1806 void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
1807                                  upb_status *s);
1808 bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
1809                             upb_status *s);
1810 bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
1811                                upb_status *s);
1812 bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
1813                                 upb_status *s);
1814 bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
1815                                 upb_status *s);
1816 
1817 bool upb_fielddef_checklabel(int32_t label);
1818 bool upb_fielddef_checktype(int32_t type);
1819 bool upb_fielddef_checkdescriptortype(int32_t type);
1820 bool upb_fielddef_checkintfmt(int32_t fmt);
1821 
1822 UPB_END_EXTERN_C
1823 
1824 
1825 /* upb::MessageDef ************************************************************/
1826 
1827 typedef upb_inttable_iter upb_msg_field_iter;
1828 typedef upb_strtable_iter upb_msg_oneof_iter;
1829 
1830 #ifdef __cplusplus
1831 
1832 /* Structure that describes a single .proto message type.
1833  *
1834  * Its base class is upb::Def (use upb::upcast() to convert). */
1835 class upb::MessageDef {
1836  public:
1837   /* Returns NULL if memory allocation failed. */
1838   static reffed_ptr<MessageDef> New();
1839 
1840   /* upb::RefCounted methods like Ref()/Unref(). */
1841   UPB_REFCOUNTED_CPPMETHODS
1842 
1843   /* Functionality from upb::Def. */
1844   const char* full_name() const;
1845   bool set_full_name(const char* fullname, Status* s);
1846   bool set_full_name(const std::string& fullname, Status* s);
1847 
1848   /* Call to freeze this MessageDef.
1849    * WARNING: this will fail if this message has any unfrozen submessages!
1850    * Messages with cycles must be frozen as a batch using upb::Def::Freeze(). */
1851   bool Freeze(Status* s);
1852 
1853   /* The number of fields that belong to the MessageDef. */
1854   int field_count() const;
1855 
1856   /* The number of oneofs that belong to the MessageDef. */
1857   int oneof_count() const;
1858 
1859   /* Adds a field (upb_fielddef object) to a msgdef.  Requires that the msgdef
1860    * and the fielddefs are mutable.  The fielddef's name and number must be
1861    * set, and the message may not already contain any field with this name or
1862    * number, and this fielddef may not be part of another message.  In error
1863    * cases false is returned and the msgdef is unchanged.
1864    *
1865    * If the given field is part of a oneof, this call succeeds if and only if
1866    * that oneof is already part of this msgdef. (Note that adding a oneof to a
1867    * msgdef automatically adds all of its fields to the msgdef at the time that
1868    * the oneof is added, so it is usually more idiomatic to add the oneof's
1869    * fields first then add the oneof to the msgdef. This case is supported for
1870    * convenience.)
1871    *
1872    * If |f| is already part of this MessageDef, this method performs no action
1873    * and returns true (success). Thus, this method is idempotent. */
1874   bool AddField(FieldDef* f, Status* s);
1875   bool AddField(const reffed_ptr<FieldDef>& f, Status* s);
1876 
1877   /* Adds a oneof (upb_oneofdef object) to a msgdef. Requires that the msgdef,
1878    * oneof, and any fielddefs are mutable, that the fielddefs contained in the
1879    * oneof do not have any name or number conflicts with existing fields in the
1880    * msgdef, and that the oneof's name is unique among all oneofs in the msgdef.
1881    * If the oneof is added successfully, all of its fields will be added
1882    * directly to the msgdef as well. In error cases, false is returned and the
1883    * msgdef is unchanged. */
1884   bool AddOneof(OneofDef* o, Status* s);
1885   bool AddOneof(const reffed_ptr<OneofDef>& o, Status* s);
1886 
1887   /* These return NULL if the field is not found. */
1888   FieldDef* FindFieldByNumber(uint32_t number);
1889   FieldDef* FindFieldByName(const char *name, size_t len);
1890   const FieldDef* FindFieldByNumber(uint32_t number) const;
1891   const FieldDef* FindFieldByName(const char* name, size_t len) const;
1892 
1893 
FindFieldByName(const char * name)1894   FieldDef* FindFieldByName(const char *name) {
1895     return FindFieldByName(name, strlen(name));
1896   }
FindFieldByName(const char * name)1897   const FieldDef* FindFieldByName(const char *name) const {
1898     return FindFieldByName(name, strlen(name));
1899   }
1900 
1901   template <class T>
FindFieldByName(const T & str)1902   FieldDef* FindFieldByName(const T& str) {
1903     return FindFieldByName(str.c_str(), str.size());
1904   }
1905   template <class T>
FindFieldByName(const T & str)1906   const FieldDef* FindFieldByName(const T& str) const {
1907     return FindFieldByName(str.c_str(), str.size());
1908   }
1909 
1910   OneofDef* FindOneofByName(const char* name, size_t len);
1911   const OneofDef* FindOneofByName(const char* name, size_t len) const;
1912 
FindOneofByName(const char * name)1913   OneofDef* FindOneofByName(const char* name) {
1914     return FindOneofByName(name, strlen(name));
1915   }
FindOneofByName(const char * name)1916   const OneofDef* FindOneofByName(const char* name) const {
1917     return FindOneofByName(name, strlen(name));
1918   }
1919 
1920   template<class T>
FindOneofByName(const T & str)1921   OneofDef* FindOneofByName(const T& str) {
1922     return FindOneofByName(str.c_str(), str.size());
1923   }
1924   template<class T>
FindOneofByName(const T & str)1925   const OneofDef* FindOneofByName(const T& str) const {
1926     return FindOneofByName(str.c_str(), str.size());
1927   }
1928 
1929   /* Returns a new msgdef that is a copy of the given msgdef (and a copy of all
1930    * the fields) but with any references to submessages broken and replaced
1931    * with just the name of the submessage.  Returns NULL if memory allocation
1932    * failed.
1933    *
1934    * TODO(haberman): which is more useful, keeping fields resolved or
1935    * unresolving them?  If there's no obvious answer, Should this functionality
1936    * just be moved into symtab.c? */
1937   MessageDef* Dup(const void* owner) const;
1938 
1939   /* Is this message a map entry? */
1940   void setmapentry(bool map_entry);
1941   bool mapentry() const;
1942 
1943   /* Iteration over fields.  The order is undefined. */
1944   class field_iterator
1945       : public std::iterator<std::forward_iterator_tag, FieldDef*> {
1946    public:
1947     explicit field_iterator(MessageDef* md);
1948     static field_iterator end(MessageDef* md);
1949 
1950     void operator++();
1951     FieldDef* operator*() const;
1952     bool operator!=(const field_iterator& other) const;
1953     bool operator==(const field_iterator& other) const;
1954 
1955    private:
1956     upb_msg_field_iter iter_;
1957   };
1958 
1959   class const_field_iterator
1960       : public std::iterator<std::forward_iterator_tag, const FieldDef*> {
1961    public:
1962     explicit const_field_iterator(const MessageDef* md);
1963     static const_field_iterator end(const MessageDef* md);
1964 
1965     void operator++();
1966     const FieldDef* operator*() const;
1967     bool operator!=(const const_field_iterator& other) const;
1968     bool operator==(const const_field_iterator& other) const;
1969 
1970    private:
1971     upb_msg_field_iter iter_;
1972   };
1973 
1974   /* Iteration over oneofs. The order is undefined. */
1975   class oneof_iterator
1976       : public std::iterator<std::forward_iterator_tag, FieldDef*> {
1977    public:
1978     explicit oneof_iterator(MessageDef* md);
1979     static oneof_iterator end(MessageDef* md);
1980 
1981     void operator++();
1982     OneofDef* operator*() const;
1983     bool operator!=(const oneof_iterator& other) const;
1984     bool operator==(const oneof_iterator& other) const;
1985 
1986    private:
1987     upb_msg_oneof_iter iter_;
1988   };
1989 
1990   class const_oneof_iterator
1991       : public std::iterator<std::forward_iterator_tag, const FieldDef*> {
1992    public:
1993     explicit const_oneof_iterator(const MessageDef* md);
1994     static const_oneof_iterator end(const MessageDef* md);
1995 
1996     void operator++();
1997     const OneofDef* operator*() const;
1998     bool operator!=(const const_oneof_iterator& other) const;
1999     bool operator==(const const_oneof_iterator& other) const;
2000 
2001    private:
2002     upb_msg_oneof_iter iter_;
2003   };
2004 
2005   class FieldAccessor {
2006    public:
FieldAccessor(MessageDef * msg)2007     explicit FieldAccessor(MessageDef* msg) : msg_(msg) {}
begin()2008     field_iterator begin() { return msg_->field_begin(); }
end()2009     field_iterator end() { return msg_->field_end(); }
2010    private:
2011     MessageDef* msg_;
2012   };
2013 
2014   class ConstFieldAccessor {
2015    public:
ConstFieldAccessor(const MessageDef * msg)2016     explicit ConstFieldAccessor(const MessageDef* msg) : msg_(msg) {}
begin()2017     const_field_iterator begin() { return msg_->field_begin(); }
end()2018     const_field_iterator end() { return msg_->field_end(); }
2019    private:
2020     const MessageDef* msg_;
2021   };
2022 
2023   class OneofAccessor {
2024    public:
OneofAccessor(MessageDef * msg)2025     explicit OneofAccessor(MessageDef* msg) : msg_(msg) {}
begin()2026     oneof_iterator begin() { return msg_->oneof_begin(); }
end()2027     oneof_iterator end() { return msg_->oneof_end(); }
2028    private:
2029     MessageDef* msg_;
2030   };
2031 
2032   class ConstOneofAccessor {
2033    public:
ConstOneofAccessor(const MessageDef * msg)2034     explicit ConstOneofAccessor(const MessageDef* msg) : msg_(msg) {}
begin()2035     const_oneof_iterator begin() { return msg_->oneof_begin(); }
end()2036     const_oneof_iterator end() { return msg_->oneof_end(); }
2037    private:
2038     const MessageDef* msg_;
2039   };
2040 
2041   field_iterator field_begin();
2042   field_iterator field_end();
2043   const_field_iterator field_begin() const;
2044   const_field_iterator field_end() const;
2045 
2046   oneof_iterator oneof_begin();
2047   oneof_iterator oneof_end();
2048   const_oneof_iterator oneof_begin() const;
2049   const_oneof_iterator oneof_end() const;
2050 
fields()2051   FieldAccessor fields() { return FieldAccessor(this); }
fields()2052   ConstFieldAccessor fields() const { return ConstFieldAccessor(this); }
oneofs()2053   OneofAccessor oneofs() { return OneofAccessor(this); }
oneofs()2054   ConstOneofAccessor oneofs() const { return ConstOneofAccessor(this); }
2055 
2056  private:
2057   UPB_DISALLOW_POD_OPS(MessageDef, upb::MessageDef)
2058 };
2059 
2060 #endif  /* __cplusplus */
2061 
2062 UPB_BEGIN_EXTERN_C
2063 
2064 /* Returns NULL if memory allocation failed. */
2065 upb_msgdef *upb_msgdef_new(const void *owner);
2066 
2067 /* Include upb_refcounted methods like upb_msgdef_ref(). */
2068 UPB_REFCOUNTED_CMETHODS(upb_msgdef, upb_msgdef_upcast2)
2069 
2070 bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status);
2071 
2072 const char *upb_msgdef_fullname(const upb_msgdef *m);
2073 bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname, upb_status *s);
2074 
2075 upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner);
2076 bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
2077                          upb_status *s);
2078 bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
2079                          upb_status *s);
2080 
2081 /* Field lookup in a couple of different variations:
2082  *   - itof = int to field
2083  *   - ntof = name to field
2084  *   - ntofz = name to field, null-terminated string. */
2085 const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i);
2086 const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
2087                                     size_t len);
2088 int upb_msgdef_numfields(const upb_msgdef *m);
2089 
upb_msgdef_ntofz(const upb_msgdef * m,const char * name)2090 UPB_INLINE const upb_fielddef *upb_msgdef_ntofz(const upb_msgdef *m,
2091                                                 const char *name) {
2092   return upb_msgdef_ntof(m, name, strlen(name));
2093 }
2094 
upb_msgdef_itof_mutable(upb_msgdef * m,uint32_t i)2095 UPB_INLINE upb_fielddef *upb_msgdef_itof_mutable(upb_msgdef *m, uint32_t i) {
2096   return (upb_fielddef*)upb_msgdef_itof(m, i);
2097 }
2098 
upb_msgdef_ntof_mutable(upb_msgdef * m,const char * name,size_t len)2099 UPB_INLINE upb_fielddef *upb_msgdef_ntof_mutable(upb_msgdef *m,
2100                                                  const char *name, size_t len) {
2101   return (upb_fielddef *)upb_msgdef_ntof(m, name, len);
2102 }
2103 
2104 /* Oneof lookup:
2105  *   - ntoo = name to oneof
2106  *   - ntooz = name to oneof, null-terminated string. */
2107 const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
2108                                     size_t len);
2109 int upb_msgdef_numoneofs(const upb_msgdef *m);
2110 
upb_msgdef_ntooz(const upb_msgdef * m,const char * name)2111 UPB_INLINE const upb_oneofdef *upb_msgdef_ntooz(const upb_msgdef *m,
2112                                                const char *name) {
2113   return upb_msgdef_ntoo(m, name, strlen(name));
2114 }
2115 
upb_msgdef_ntoo_mutable(upb_msgdef * m,const char * name,size_t len)2116 UPB_INLINE upb_oneofdef *upb_msgdef_ntoo_mutable(upb_msgdef *m,
2117                                                  const char *name, size_t len) {
2118   return (upb_oneofdef *)upb_msgdef_ntoo(m, name, len);
2119 }
2120 
2121 void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry);
2122 bool upb_msgdef_mapentry(const upb_msgdef *m);
2123 
2124 /* Well-known field tag numbers for map-entry messages. */
2125 #define UPB_MAPENTRY_KEY   1
2126 #define UPB_MAPENTRY_VALUE 2
2127 
2128 const upb_oneofdef *upb_msgdef_findoneof(const upb_msgdef *m,
2129                                           const char *name);
2130 int upb_msgdef_numoneofs(const upb_msgdef *m);
2131 
2132 /* upb_msg_field_iter i;
2133  * for(upb_msg_field_begin(&i, m);
2134  *     !upb_msg_field_done(&i);
2135  *     upb_msg_field_next(&i)) {
2136  *   upb_fielddef *f = upb_msg_iter_field(&i);
2137  *   // ...
2138  * }
2139  *
2140  * For C we don't have separate iterators for const and non-const.
2141  * It is the caller's responsibility to cast the upb_fielddef* to
2142  * const if the upb_msgdef* is const. */
2143 void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m);
2144 void upb_msg_field_next(upb_msg_field_iter *iter);
2145 bool upb_msg_field_done(const upb_msg_field_iter *iter);
2146 upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter);
2147 void upb_msg_field_iter_setdone(upb_msg_field_iter *iter);
2148 
2149 /* Similar to above, we also support iterating through the oneofs in a
2150  * msgdef. */
2151 void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m);
2152 void upb_msg_oneof_next(upb_msg_oneof_iter *iter);
2153 bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter);
2154 upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter);
2155 void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter);
2156 
2157 UPB_END_EXTERN_C
2158 
2159 
2160 /* upb::EnumDef ***************************************************************/
2161 
2162 typedef upb_strtable_iter upb_enum_iter;
2163 
2164 #ifdef __cplusplus
2165 
2166 /* Class that represents an enum.  Its base class is upb::Def (convert with
2167  * upb::upcast()). */
2168 class upb::EnumDef {
2169  public:
2170   /* Returns NULL if memory allocation failed. */
2171   static reffed_ptr<EnumDef> New();
2172 
2173   /* upb::RefCounted methods like Ref()/Unref(). */
2174   UPB_REFCOUNTED_CPPMETHODS
2175 
2176   /* Functionality from upb::Def. */
2177   const char* full_name() const;
2178   bool set_full_name(const char* fullname, Status* s);
2179   bool set_full_name(const std::string& fullname, Status* s);
2180 
2181   /* Call to freeze this EnumDef. */
2182   bool Freeze(Status* s);
2183 
2184   /* The value that is used as the default when no field default is specified.
2185    * If not set explicitly, the first value that was added will be used.
2186    * The default value must be a member of the enum.
2187    * Requires that value_count() > 0. */
2188   int32_t default_value() const;
2189 
2190   /* Sets the default value.  If this value is not valid, returns false and an
2191    * error message in status. */
2192   bool set_default_value(int32_t val, Status* status);
2193 
2194   /* Returns the number of values currently defined in the enum.  Note that
2195    * multiple names can refer to the same number, so this may be greater than
2196    * the total number of unique numbers. */
2197   int value_count() const;
2198 
2199   /* Adds a single name/number pair to the enum.  Fails if this name has
2200    * already been used by another value. */
2201   bool AddValue(const char* name, int32_t num, Status* status);
2202   bool AddValue(const std::string& name, int32_t num, Status* status);
2203 
2204   /* Lookups from name to integer, returning true if found. */
2205   bool FindValueByName(const char* name, int32_t* num) const;
2206 
2207   /* Finds the name corresponding to the given number, or NULL if none was
2208    * found.  If more than one name corresponds to this number, returns the
2209    * first one that was added. */
2210   const char* FindValueByNumber(int32_t num) const;
2211 
2212   /* Returns a new EnumDef with all the same values.  The new EnumDef will be
2213    * owned by the given owner. */
2214   EnumDef* Dup(const void* owner) const;
2215 
2216   /* Iteration over name/value pairs.  The order is undefined.
2217    * Adding an enum val invalidates any iterators.
2218    *
2219    * TODO: make compatible with range-for, with elements as pairs? */
2220   class Iterator {
2221    public:
2222     explicit Iterator(const EnumDef*);
2223 
2224     int32_t number();
2225     const char *name();
2226     bool Done();
2227     void Next();
2228 
2229    private:
2230     upb_enum_iter iter_;
2231   };
2232 
2233  private:
2234   UPB_DISALLOW_POD_OPS(EnumDef, upb::EnumDef)
2235 };
2236 
2237 #endif  /* __cplusplus */
2238 
2239 UPB_BEGIN_EXTERN_C
2240 
2241 /* Native C API. */
2242 upb_enumdef *upb_enumdef_new(const void *owner);
2243 upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner);
2244 
2245 /* Include upb_refcounted methods like upb_enumdef_ref(). */
2246 UPB_REFCOUNTED_CMETHODS(upb_enumdef, upb_enumdef_upcast2)
2247 
2248 bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status);
2249 
2250 /* From upb_def. */
2251 const char *upb_enumdef_fullname(const upb_enumdef *e);
2252 bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
2253                              upb_status *s);
2254 
2255 int32_t upb_enumdef_default(const upb_enumdef *e);
2256 bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s);
2257 int upb_enumdef_numvals(const upb_enumdef *e);
2258 bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
2259                         upb_status *status);
2260 
2261 /* Enum lookups:
2262  * - ntoi:  look up a name with specified length.
2263  * - ntoiz: look up a name provided as a null-terminated string.
2264  * - iton:  look up an integer, returning the name as a null-terminated
2265  *          string. */
2266 bool upb_enumdef_ntoi(const upb_enumdef *e, const char *name, size_t len,
2267                       int32_t *num);
upb_enumdef_ntoiz(const upb_enumdef * e,const char * name,int32_t * num)2268 UPB_INLINE bool upb_enumdef_ntoiz(const upb_enumdef *e,
2269                                   const char *name, int32_t *num) {
2270   return upb_enumdef_ntoi(e, name, strlen(name), num);
2271 }
2272 const char *upb_enumdef_iton(const upb_enumdef *e, int32_t num);
2273 
2274 /*  upb_enum_iter i;
2275  *  for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
2276  *    // ...
2277  *  }
2278  */
2279 void upb_enum_begin(upb_enum_iter *iter, const upb_enumdef *e);
2280 void upb_enum_next(upb_enum_iter *iter);
2281 bool upb_enum_done(upb_enum_iter *iter);
2282 const char *upb_enum_iter_name(upb_enum_iter *iter);
2283 int32_t upb_enum_iter_number(upb_enum_iter *iter);
2284 
2285 UPB_END_EXTERN_C
2286 
2287 /* upb::OneofDef **************************************************************/
2288 
2289 typedef upb_inttable_iter upb_oneof_iter;
2290 
2291 #ifdef __cplusplus
2292 
2293 /* Class that represents a oneof.  Its base class is upb::Def (convert with
2294  * upb::upcast()). */
2295 class upb::OneofDef {
2296  public:
2297   /* Returns NULL if memory allocation failed. */
2298   static reffed_ptr<OneofDef> New();
2299 
2300   /* upb::RefCounted methods like Ref()/Unref(). */
2301   UPB_REFCOUNTED_CPPMETHODS
2302 
2303   /* Functionality from upb::Def. */
2304   const char* full_name() const;
2305 
2306   /* Returns the MessageDef that owns this OneofDef. */
2307   const MessageDef* containing_type() const;
2308 
2309   /* Returns the name of this oneof. This is the name used to look up the oneof
2310    * by name once added to a message def. */
2311   const char* name() const;
2312   bool set_name(const char* name, Status* s);
2313 
2314   /* Returns the number of fields currently defined in the oneof. */
2315   int field_count() const;
2316 
2317   /* Adds a field to the oneof. The field must not have been added to any other
2318    * oneof or msgdef. If the oneof is not yet part of a msgdef, then when the
2319    * oneof is eventually added to a msgdef, all fields added to the oneof will
2320    * also be added to the msgdef at that time. If the oneof is already part of a
2321    * msgdef, the field must either be a part of that msgdef already, or must not
2322    * be a part of any msgdef; in the latter case, the field is added to the
2323    * msgdef as a part of this operation.
2324    *
2325    * The field may only have an OPTIONAL label, never REQUIRED or REPEATED.
2326    *
2327    * If |f| is already part of this MessageDef, this method performs no action
2328    * and returns true (success). Thus, this method is idempotent. */
2329   bool AddField(FieldDef* field, Status* s);
2330   bool AddField(const reffed_ptr<FieldDef>& field, Status* s);
2331 
2332   /* Looks up by name. */
2333   const FieldDef* FindFieldByName(const char* name, size_t len) const;
2334   FieldDef* FindFieldByName(const char* name, size_t len);
FindFieldByName(const char * name)2335   const FieldDef* FindFieldByName(const char* name) const {
2336     return FindFieldByName(name, strlen(name));
2337   }
FindFieldByName(const char * name)2338   FieldDef* FindFieldByName(const char* name) {
2339     return FindFieldByName(name, strlen(name));
2340   }
2341 
2342   template <class T>
FindFieldByName(const T & str)2343   FieldDef* FindFieldByName(const T& str) {
2344     return FindFieldByName(str.c_str(), str.size());
2345   }
2346   template <class T>
FindFieldByName(const T & str)2347   const FieldDef* FindFieldByName(const T& str) const {
2348     return FindFieldByName(str.c_str(), str.size());
2349   }
2350 
2351   /* Looks up by tag number. */
2352   const FieldDef* FindFieldByNumber(uint32_t num) const;
2353 
2354   /* Returns a new OneofDef with all the same fields. The OneofDef will be owned
2355    * by the given owner. */
2356   OneofDef* Dup(const void* owner) const;
2357 
2358   /* Iteration over fields.  The order is undefined. */
2359   class iterator : public std::iterator<std::forward_iterator_tag, FieldDef*> {
2360    public:
2361     explicit iterator(OneofDef* md);
2362     static iterator end(OneofDef* md);
2363 
2364     void operator++();
2365     FieldDef* operator*() const;
2366     bool operator!=(const iterator& other) const;
2367     bool operator==(const iterator& other) const;
2368 
2369    private:
2370     upb_oneof_iter iter_;
2371   };
2372 
2373   class const_iterator
2374       : public std::iterator<std::forward_iterator_tag, const FieldDef*> {
2375    public:
2376     explicit const_iterator(const OneofDef* md);
2377     static const_iterator end(const OneofDef* md);
2378 
2379     void operator++();
2380     const FieldDef* operator*() const;
2381     bool operator!=(const const_iterator& other) const;
2382     bool operator==(const const_iterator& other) const;
2383 
2384    private:
2385     upb_oneof_iter iter_;
2386   };
2387 
2388   iterator begin();
2389   iterator end();
2390   const_iterator begin() const;
2391   const_iterator end() const;
2392 
2393  private:
2394   UPB_DISALLOW_POD_OPS(OneofDef, upb::OneofDef)
2395 };
2396 
2397 #endif  /* __cplusplus */
2398 
2399 UPB_BEGIN_EXTERN_C
2400 
2401 /* Native C API. */
2402 upb_oneofdef *upb_oneofdef_new(const void *owner);
2403 upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner);
2404 
2405 /* Include upb_refcounted methods like upb_oneofdef_ref(). */
2406 UPB_REFCOUNTED_CMETHODS(upb_oneofdef, upb_oneofdef_upcast2)
2407 
2408 const char *upb_oneofdef_name(const upb_oneofdef *o);
2409 bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s);
2410 
2411 const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o);
2412 int upb_oneofdef_numfields(const upb_oneofdef *o);
2413 bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
2414                            const void *ref_donor,
2415                            upb_status *s);
2416 
2417 /* Oneof lookups:
2418  * - ntof:  look up a field by name.
2419  * - ntofz: look up a field by name (as a null-terminated string).
2420  * - itof:  look up a field by number. */
2421 const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
2422                                       const char *name, size_t length);
upb_oneofdef_ntofz(const upb_oneofdef * o,const char * name)2423 UPB_INLINE const upb_fielddef *upb_oneofdef_ntofz(const upb_oneofdef *o,
2424                                                   const char *name) {
2425   return upb_oneofdef_ntof(o, name, strlen(name));
2426 }
2427 const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num);
2428 
2429 /*  upb_oneof_iter i;
2430  *  for(upb_oneof_begin(&i, e); !upb_oneof_done(&i); upb_oneof_next(&i)) {
2431  *    // ...
2432  *  }
2433  */
2434 void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o);
2435 void upb_oneof_next(upb_oneof_iter *iter);
2436 bool upb_oneof_done(upb_oneof_iter *iter);
2437 upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter);
2438 void upb_oneof_iter_setdone(upb_oneof_iter *iter);
2439 
2440 UPB_END_EXTERN_C
2441 
2442 #ifdef __cplusplus
2443 
upb_safecstr(const std::string & str)2444 UPB_INLINE const char* upb_safecstr(const std::string& str) {
2445   assert(str.size() == std::strlen(str.c_str()));
2446   return str.c_str();
2447 }
2448 
2449 /* Inline C++ wrappers. */
2450 namespace upb {
2451 
Dup(const void * owner)2452 inline Def* Def::Dup(const void* owner) const {
2453   return upb_def_dup(this, owner);
2454 }
def_type()2455 inline Def::Type Def::def_type() const { return upb_def_type(this); }
full_name()2456 inline const char* Def::full_name() const { return upb_def_fullname(this); }
set_full_name(const char * fullname,Status * s)2457 inline bool Def::set_full_name(const char* fullname, Status* s) {
2458   return upb_def_setfullname(this, fullname, s);
2459 }
set_full_name(const std::string & fullname,Status * s)2460 inline bool Def::set_full_name(const std::string& fullname, Status* s) {
2461   return upb_def_setfullname(this, upb_safecstr(fullname), s);
2462 }
Freeze(Def * const * defs,int n,Status * status)2463 inline bool Def::Freeze(Def* const* defs, int n, Status* status) {
2464   return upb_def_freeze(defs, n, status);
2465 }
Freeze(const std::vector<Def * > & defs,Status * status)2466 inline bool Def::Freeze(const std::vector<Def*>& defs, Status* status) {
2467   return upb_def_freeze((Def* const*)&defs[0], defs.size(), status);
2468 }
2469 
CheckType(int32_t val)2470 inline bool FieldDef::CheckType(int32_t val) {
2471   return upb_fielddef_checktype(val);
2472 }
CheckLabel(int32_t val)2473 inline bool FieldDef::CheckLabel(int32_t val) {
2474   return upb_fielddef_checklabel(val);
2475 }
CheckDescriptorType(int32_t val)2476 inline bool FieldDef::CheckDescriptorType(int32_t val) {
2477   return upb_fielddef_checkdescriptortype(val);
2478 }
CheckIntegerFormat(int32_t val)2479 inline bool FieldDef::CheckIntegerFormat(int32_t val) {
2480   return upb_fielddef_checkintfmt(val);
2481 }
ConvertType(int32_t val)2482 inline FieldDef::Type FieldDef::ConvertType(int32_t val) {
2483   assert(CheckType(val));
2484   return static_cast<FieldDef::Type>(val);
2485 }
ConvertLabel(int32_t val)2486 inline FieldDef::Label FieldDef::ConvertLabel(int32_t val) {
2487   assert(CheckLabel(val));
2488   return static_cast<FieldDef::Label>(val);
2489 }
ConvertDescriptorType(int32_t val)2490 inline FieldDef::DescriptorType FieldDef::ConvertDescriptorType(int32_t val) {
2491   assert(CheckDescriptorType(val));
2492   return static_cast<FieldDef::DescriptorType>(val);
2493 }
ConvertIntegerFormat(int32_t val)2494 inline FieldDef::IntegerFormat FieldDef::ConvertIntegerFormat(int32_t val) {
2495   assert(CheckIntegerFormat(val));
2496   return static_cast<FieldDef::IntegerFormat>(val);
2497 }
2498 
New()2499 inline reffed_ptr<FieldDef> FieldDef::New() {
2500   upb_fielddef *f = upb_fielddef_new(&f);
2501   return reffed_ptr<FieldDef>(f, &f);
2502 }
Dup(const void * owner)2503 inline FieldDef* FieldDef::Dup(const void* owner) const {
2504   return upb_fielddef_dup(this, owner);
2505 }
full_name()2506 inline const char* FieldDef::full_name() const {
2507   return upb_fielddef_fullname(this);
2508 }
set_full_name(const char * fullname,Status * s)2509 inline bool FieldDef::set_full_name(const char* fullname, Status* s) {
2510   return upb_fielddef_setfullname(this, fullname, s);
2511 }
set_full_name(const std::string & fullname,Status * s)2512 inline bool FieldDef::set_full_name(const std::string& fullname, Status* s) {
2513   return upb_fielddef_setfullname(this, upb_safecstr(fullname), s);
2514 }
type_is_set()2515 inline bool FieldDef::type_is_set() const {
2516   return upb_fielddef_typeisset(this);
2517 }
type()2518 inline FieldDef::Type FieldDef::type() const { return upb_fielddef_type(this); }
descriptor_type()2519 inline FieldDef::DescriptorType FieldDef::descriptor_type() const {
2520   return upb_fielddef_descriptortype(this);
2521 }
label()2522 inline FieldDef::Label FieldDef::label() const {
2523   return upb_fielddef_label(this);
2524 }
number()2525 inline uint32_t FieldDef::number() const { return upb_fielddef_number(this); }
name()2526 inline const char* FieldDef::name() const { return upb_fielddef_name(this); }
is_extension()2527 inline bool FieldDef::is_extension() const {
2528   return upb_fielddef_isextension(this);
2529 }
lazy()2530 inline bool FieldDef::lazy() const {
2531   return upb_fielddef_lazy(this);
2532 }
set_lazy(bool lazy)2533 inline void FieldDef::set_lazy(bool lazy) {
2534   upb_fielddef_setlazy(this, lazy);
2535 }
packed()2536 inline bool FieldDef::packed() const {
2537   return upb_fielddef_packed(this);
2538 }
set_packed(bool packed)2539 inline void FieldDef::set_packed(bool packed) {
2540   upb_fielddef_setpacked(this, packed);
2541 }
containing_type()2542 inline const MessageDef* FieldDef::containing_type() const {
2543   return upb_fielddef_containingtype(this);
2544 }
containing_oneof()2545 inline const OneofDef* FieldDef::containing_oneof() const {
2546   return upb_fielddef_containingoneof(this);
2547 }
containing_type_name()2548 inline const char* FieldDef::containing_type_name() {
2549   return upb_fielddef_containingtypename(this);
2550 }
set_number(uint32_t number,Status * s)2551 inline bool FieldDef::set_number(uint32_t number, Status* s) {
2552   return upb_fielddef_setnumber(this, number, s);
2553 }
set_name(const char * name,Status * s)2554 inline bool FieldDef::set_name(const char *name, Status* s) {
2555   return upb_fielddef_setname(this, name, s);
2556 }
set_name(const std::string & name,Status * s)2557 inline bool FieldDef::set_name(const std::string& name, Status* s) {
2558   return upb_fielddef_setname(this, upb_safecstr(name), s);
2559 }
set_containing_type_name(const char * name,Status * s)2560 inline bool FieldDef::set_containing_type_name(const char *name, Status* s) {
2561   return upb_fielddef_setcontainingtypename(this, name, s);
2562 }
set_containing_type_name(const std::string & name,Status * s)2563 inline bool FieldDef::set_containing_type_name(const std::string &name,
2564                                                Status *s) {
2565   return upb_fielddef_setcontainingtypename(this, upb_safecstr(name), s);
2566 }
set_type(upb_fieldtype_t type)2567 inline void FieldDef::set_type(upb_fieldtype_t type) {
2568   upb_fielddef_settype(this, type);
2569 }
set_is_extension(bool is_extension)2570 inline void FieldDef::set_is_extension(bool is_extension) {
2571   upb_fielddef_setisextension(this, is_extension);
2572 }
set_descriptor_type(FieldDef::DescriptorType type)2573 inline void FieldDef::set_descriptor_type(FieldDef::DescriptorType type) {
2574   upb_fielddef_setdescriptortype(this, type);
2575 }
set_label(upb_label_t label)2576 inline void FieldDef::set_label(upb_label_t label) {
2577   upb_fielddef_setlabel(this, label);
2578 }
IsSubMessage()2579 inline bool FieldDef::IsSubMessage() const {
2580   return upb_fielddef_issubmsg(this);
2581 }
IsString()2582 inline bool FieldDef::IsString() const { return upb_fielddef_isstring(this); }
IsSequence()2583 inline bool FieldDef::IsSequence() const { return upb_fielddef_isseq(this); }
IsMap()2584 inline bool FieldDef::IsMap() const { return upb_fielddef_ismap(this); }
default_int64()2585 inline int64_t FieldDef::default_int64() const {
2586   return upb_fielddef_defaultint64(this);
2587 }
default_int32()2588 inline int32_t FieldDef::default_int32() const {
2589   return upb_fielddef_defaultint32(this);
2590 }
default_uint64()2591 inline uint64_t FieldDef::default_uint64() const {
2592   return upb_fielddef_defaultuint64(this);
2593 }
default_uint32()2594 inline uint32_t FieldDef::default_uint32() const {
2595   return upb_fielddef_defaultuint32(this);
2596 }
default_bool()2597 inline bool FieldDef::default_bool() const {
2598   return upb_fielddef_defaultbool(this);
2599 }
default_float()2600 inline float FieldDef::default_float() const {
2601   return upb_fielddef_defaultfloat(this);
2602 }
default_double()2603 inline double FieldDef::default_double() const {
2604   return upb_fielddef_defaultdouble(this);
2605 }
default_string(size_t * len)2606 inline const char* FieldDef::default_string(size_t* len) const {
2607   return upb_fielddef_defaultstr(this, len);
2608 }
set_default_int64(int64_t value)2609 inline void FieldDef::set_default_int64(int64_t value) {
2610   upb_fielddef_setdefaultint64(this, value);
2611 }
set_default_int32(int32_t value)2612 inline void FieldDef::set_default_int32(int32_t value) {
2613   upb_fielddef_setdefaultint32(this, value);
2614 }
set_default_uint64(uint64_t value)2615 inline void FieldDef::set_default_uint64(uint64_t value) {
2616   upb_fielddef_setdefaultuint64(this, value);
2617 }
set_default_uint32(uint32_t value)2618 inline void FieldDef::set_default_uint32(uint32_t value) {
2619   upb_fielddef_setdefaultuint32(this, value);
2620 }
set_default_bool(bool value)2621 inline void FieldDef::set_default_bool(bool value) {
2622   upb_fielddef_setdefaultbool(this, value);
2623 }
set_default_float(float value)2624 inline void FieldDef::set_default_float(float value) {
2625   upb_fielddef_setdefaultfloat(this, value);
2626 }
set_default_double(double value)2627 inline void FieldDef::set_default_double(double value) {
2628   upb_fielddef_setdefaultdouble(this, value);
2629 }
set_default_string(const void * str,size_t len,Status * s)2630 inline bool FieldDef::set_default_string(const void *str, size_t len,
2631                                          Status *s) {
2632   return upb_fielddef_setdefaultstr(this, str, len, s);
2633 }
set_default_string(const std::string & str,Status * s)2634 inline bool FieldDef::set_default_string(const std::string& str, Status* s) {
2635   return upb_fielddef_setdefaultstr(this, str.c_str(), str.size(), s);
2636 }
set_default_cstr(const char * str,Status * s)2637 inline void FieldDef::set_default_cstr(const char* str, Status* s) {
2638   return upb_fielddef_setdefaultcstr(this, str, s);
2639 }
HasSubDef()2640 inline bool FieldDef::HasSubDef() const { return upb_fielddef_hassubdef(this); }
subdef()2641 inline const Def* FieldDef::subdef() const { return upb_fielddef_subdef(this); }
message_subdef()2642 inline const MessageDef *FieldDef::message_subdef() const {
2643   return upb_fielddef_msgsubdef(this);
2644 }
enum_subdef()2645 inline const EnumDef *FieldDef::enum_subdef() const {
2646   return upb_fielddef_enumsubdef(this);
2647 }
subdef_name()2648 inline const char* FieldDef::subdef_name() const {
2649   return upb_fielddef_subdefname(this);
2650 }
set_subdef(const Def * subdef,Status * s)2651 inline bool FieldDef::set_subdef(const Def* subdef, Status* s) {
2652   return upb_fielddef_setsubdef(this, subdef, s);
2653 }
set_enum_subdef(const EnumDef * subdef,Status * s)2654 inline bool FieldDef::set_enum_subdef(const EnumDef* subdef, Status* s) {
2655   return upb_fielddef_setenumsubdef(this, subdef, s);
2656 }
set_message_subdef(const MessageDef * subdef,Status * s)2657 inline bool FieldDef::set_message_subdef(const MessageDef* subdef, Status* s) {
2658   return upb_fielddef_setmsgsubdef(this, subdef, s);
2659 }
set_subdef_name(const char * name,Status * s)2660 inline bool FieldDef::set_subdef_name(const char* name, Status* s) {
2661   return upb_fielddef_setsubdefname(this, name, s);
2662 }
set_subdef_name(const std::string & name,Status * s)2663 inline bool FieldDef::set_subdef_name(const std::string& name, Status* s) {
2664   return upb_fielddef_setsubdefname(this, upb_safecstr(name), s);
2665 }
2666 
New()2667 inline reffed_ptr<MessageDef> MessageDef::New() {
2668   upb_msgdef *m = upb_msgdef_new(&m);
2669   return reffed_ptr<MessageDef>(m, &m);
2670 }
full_name()2671 inline const char *MessageDef::full_name() const {
2672   return upb_msgdef_fullname(this);
2673 }
set_full_name(const char * fullname,Status * s)2674 inline bool MessageDef::set_full_name(const char* fullname, Status* s) {
2675   return upb_msgdef_setfullname(this, fullname, s);
2676 }
set_full_name(const std::string & fullname,Status * s)2677 inline bool MessageDef::set_full_name(const std::string& fullname, Status* s) {
2678   return upb_msgdef_setfullname(this, upb_safecstr(fullname), s);
2679 }
Freeze(Status * status)2680 inline bool MessageDef::Freeze(Status* status) {
2681   return upb_msgdef_freeze(this, status);
2682 }
field_count()2683 inline int MessageDef::field_count() const {
2684   return upb_msgdef_numfields(this);
2685 }
oneof_count()2686 inline int MessageDef::oneof_count() const {
2687   return upb_msgdef_numoneofs(this);
2688 }
AddField(upb_fielddef * f,Status * s)2689 inline bool MessageDef::AddField(upb_fielddef* f, Status* s) {
2690   return upb_msgdef_addfield(this, f, NULL, s);
2691 }
AddField(const reffed_ptr<FieldDef> & f,Status * s)2692 inline bool MessageDef::AddField(const reffed_ptr<FieldDef>& f, Status* s) {
2693   return upb_msgdef_addfield(this, f.get(), NULL, s);
2694 }
AddOneof(upb_oneofdef * o,Status * s)2695 inline bool MessageDef::AddOneof(upb_oneofdef* o, Status* s) {
2696   return upb_msgdef_addoneof(this, o, NULL, s);
2697 }
AddOneof(const reffed_ptr<OneofDef> & o,Status * s)2698 inline bool MessageDef::AddOneof(const reffed_ptr<OneofDef>& o, Status* s) {
2699   return upb_msgdef_addoneof(this, o.get(), NULL, s);
2700 }
FindFieldByNumber(uint32_t number)2701 inline FieldDef* MessageDef::FindFieldByNumber(uint32_t number) {
2702   return upb_msgdef_itof_mutable(this, number);
2703 }
FindFieldByName(const char * name,size_t len)2704 inline FieldDef* MessageDef::FindFieldByName(const char* name, size_t len) {
2705   return upb_msgdef_ntof_mutable(this, name, len);
2706 }
FindFieldByNumber(uint32_t number)2707 inline const FieldDef* MessageDef::FindFieldByNumber(uint32_t number) const {
2708   return upb_msgdef_itof(this, number);
2709 }
FindFieldByName(const char * name,size_t len)2710 inline const FieldDef *MessageDef::FindFieldByName(const char *name,
2711                                                    size_t len) const {
2712   return upb_msgdef_ntof(this, name, len);
2713 }
FindOneofByName(const char * name,size_t len)2714 inline OneofDef* MessageDef::FindOneofByName(const char* name, size_t len) {
2715   return upb_msgdef_ntoo_mutable(this, name, len);
2716 }
FindOneofByName(const char * name,size_t len)2717 inline const OneofDef* MessageDef::FindOneofByName(const char* name,
2718                                                    size_t len) const {
2719   return upb_msgdef_ntoo(this, name, len);
2720 }
Dup(const void * owner)2721 inline MessageDef* MessageDef::Dup(const void *owner) const {
2722   return upb_msgdef_dup(this, owner);
2723 }
setmapentry(bool map_entry)2724 inline void MessageDef::setmapentry(bool map_entry) {
2725   upb_msgdef_setmapentry(this, map_entry);
2726 }
mapentry()2727 inline bool MessageDef::mapentry() const {
2728   return upb_msgdef_mapentry(this);
2729 }
field_begin()2730 inline MessageDef::field_iterator MessageDef::field_begin() {
2731   return field_iterator(this);
2732 }
field_end()2733 inline MessageDef::field_iterator MessageDef::field_end() {
2734   return field_iterator::end(this);
2735 }
field_begin()2736 inline MessageDef::const_field_iterator MessageDef::field_begin() const {
2737   return const_field_iterator(this);
2738 }
field_end()2739 inline MessageDef::const_field_iterator MessageDef::field_end() const {
2740   return const_field_iterator::end(this);
2741 }
2742 
oneof_begin()2743 inline MessageDef::oneof_iterator MessageDef::oneof_begin() {
2744   return oneof_iterator(this);
2745 }
oneof_end()2746 inline MessageDef::oneof_iterator MessageDef::oneof_end() {
2747   return oneof_iterator::end(this);
2748 }
oneof_begin()2749 inline MessageDef::const_oneof_iterator MessageDef::oneof_begin() const {
2750   return const_oneof_iterator(this);
2751 }
oneof_end()2752 inline MessageDef::const_oneof_iterator MessageDef::oneof_end() const {
2753   return const_oneof_iterator::end(this);
2754 }
2755 
field_iterator(MessageDef * md)2756 inline MessageDef::field_iterator::field_iterator(MessageDef* md) {
2757   upb_msg_field_begin(&iter_, md);
2758 }
end(MessageDef * md)2759 inline MessageDef::field_iterator MessageDef::field_iterator::end(
2760     MessageDef* md) {
2761   MessageDef::field_iterator iter(md);
2762   upb_msg_field_iter_setdone(&iter.iter_);
2763   return iter;
2764 }
2765 inline FieldDef* MessageDef::field_iterator::operator*() const {
2766   return upb_msg_iter_field(&iter_);
2767 }
2768 inline void MessageDef::field_iterator::operator++() {
2769   return upb_msg_field_next(&iter_);
2770 }
2771 inline bool MessageDef::field_iterator::operator==(
2772     const field_iterator &other) const {
2773   return upb_inttable_iter_isequal(&iter_, &other.iter_);
2774 }
2775 inline bool MessageDef::field_iterator::operator!=(
2776     const field_iterator &other) const {
2777   return !(*this == other);
2778 }
2779 
const_field_iterator(const MessageDef * md)2780 inline MessageDef::const_field_iterator::const_field_iterator(
2781     const MessageDef* md) {
2782   upb_msg_field_begin(&iter_, md);
2783 }
end(const MessageDef * md)2784 inline MessageDef::const_field_iterator MessageDef::const_field_iterator::end(
2785     const MessageDef *md) {
2786   MessageDef::const_field_iterator iter(md);
2787   upb_msg_field_iter_setdone(&iter.iter_);
2788   return iter;
2789 }
2790 inline const FieldDef* MessageDef::const_field_iterator::operator*() const {
2791   return upb_msg_iter_field(&iter_);
2792 }
2793 inline void MessageDef::const_field_iterator::operator++() {
2794   return upb_msg_field_next(&iter_);
2795 }
2796 inline bool MessageDef::const_field_iterator::operator==(
2797     const const_field_iterator &other) const {
2798   return upb_inttable_iter_isequal(&iter_, &other.iter_);
2799 }
2800 inline bool MessageDef::const_field_iterator::operator!=(
2801     const const_field_iterator &other) const {
2802   return !(*this == other);
2803 }
2804 
oneof_iterator(MessageDef * md)2805 inline MessageDef::oneof_iterator::oneof_iterator(MessageDef* md) {
2806   upb_msg_oneof_begin(&iter_, md);
2807 }
end(MessageDef * md)2808 inline MessageDef::oneof_iterator MessageDef::oneof_iterator::end(
2809     MessageDef* md) {
2810   MessageDef::oneof_iterator iter(md);
2811   upb_msg_oneof_iter_setdone(&iter.iter_);
2812   return iter;
2813 }
2814 inline OneofDef* MessageDef::oneof_iterator::operator*() const {
2815   return upb_msg_iter_oneof(&iter_);
2816 }
2817 inline void MessageDef::oneof_iterator::operator++() {
2818   return upb_msg_oneof_next(&iter_);
2819 }
2820 inline bool MessageDef::oneof_iterator::operator==(
2821     const oneof_iterator &other) const {
2822   return upb_strtable_iter_isequal(&iter_, &other.iter_);
2823 }
2824 inline bool MessageDef::oneof_iterator::operator!=(
2825     const oneof_iterator &other) const {
2826   return !(*this == other);
2827 }
2828 
const_oneof_iterator(const MessageDef * md)2829 inline MessageDef::const_oneof_iterator::const_oneof_iterator(
2830     const MessageDef* md) {
2831   upb_msg_oneof_begin(&iter_, md);
2832 }
end(const MessageDef * md)2833 inline MessageDef::const_oneof_iterator MessageDef::const_oneof_iterator::end(
2834     const MessageDef *md) {
2835   MessageDef::const_oneof_iterator iter(md);
2836   upb_msg_oneof_iter_setdone(&iter.iter_);
2837   return iter;
2838 }
2839 inline const OneofDef* MessageDef::const_oneof_iterator::operator*() const {
2840   return upb_msg_iter_oneof(&iter_);
2841 }
2842 inline void MessageDef::const_oneof_iterator::operator++() {
2843   return upb_msg_oneof_next(&iter_);
2844 }
2845 inline bool MessageDef::const_oneof_iterator::operator==(
2846     const const_oneof_iterator &other) const {
2847   return upb_strtable_iter_isequal(&iter_, &other.iter_);
2848 }
2849 inline bool MessageDef::const_oneof_iterator::operator!=(
2850     const const_oneof_iterator &other) const {
2851   return !(*this == other);
2852 }
2853 
New()2854 inline reffed_ptr<EnumDef> EnumDef::New() {
2855   upb_enumdef *e = upb_enumdef_new(&e);
2856   return reffed_ptr<EnumDef>(e, &e);
2857 }
full_name()2858 inline const char* EnumDef::full_name() const {
2859   return upb_enumdef_fullname(this);
2860 }
set_full_name(const char * fullname,Status * s)2861 inline bool EnumDef::set_full_name(const char* fullname, Status* s) {
2862   return upb_enumdef_setfullname(this, fullname, s);
2863 }
set_full_name(const std::string & fullname,Status * s)2864 inline bool EnumDef::set_full_name(const std::string& fullname, Status* s) {
2865   return upb_enumdef_setfullname(this, upb_safecstr(fullname), s);
2866 }
Freeze(Status * status)2867 inline bool EnumDef::Freeze(Status* status) {
2868   return upb_enumdef_freeze(this, status);
2869 }
default_value()2870 inline int32_t EnumDef::default_value() const {
2871   return upb_enumdef_default(this);
2872 }
set_default_value(int32_t val,Status * status)2873 inline bool EnumDef::set_default_value(int32_t val, Status* status) {
2874   return upb_enumdef_setdefault(this, val, status);
2875 }
value_count()2876 inline int EnumDef::value_count() const { return upb_enumdef_numvals(this); }
AddValue(const char * name,int32_t num,Status * status)2877 inline bool EnumDef::AddValue(const char* name, int32_t num, Status* status) {
2878   return upb_enumdef_addval(this, name, num, status);
2879 }
AddValue(const std::string & name,int32_t num,Status * status)2880 inline bool EnumDef::AddValue(const std::string& name, int32_t num,
2881                               Status* status) {
2882   return upb_enumdef_addval(this, upb_safecstr(name), num, status);
2883 }
FindValueByName(const char * name,int32_t * num)2884 inline bool EnumDef::FindValueByName(const char* name, int32_t *num) const {
2885   return upb_enumdef_ntoiz(this, name, num);
2886 }
FindValueByNumber(int32_t num)2887 inline const char* EnumDef::FindValueByNumber(int32_t num) const {
2888   return upb_enumdef_iton(this, num);
2889 }
Dup(const void * owner)2890 inline EnumDef* EnumDef::Dup(const void* owner) const {
2891   return upb_enumdef_dup(this, owner);
2892 }
2893 
Iterator(const EnumDef * e)2894 inline EnumDef::Iterator::Iterator(const EnumDef* e) {
2895   upb_enum_begin(&iter_, e);
2896 }
number()2897 inline int32_t EnumDef::Iterator::number() {
2898   return upb_enum_iter_number(&iter_);
2899 }
name()2900 inline const char* EnumDef::Iterator::name() {
2901   return upb_enum_iter_name(&iter_);
2902 }
Done()2903 inline bool EnumDef::Iterator::Done() { return upb_enum_done(&iter_); }
Next()2904 inline void EnumDef::Iterator::Next() { return upb_enum_next(&iter_); }
2905 
New()2906 inline reffed_ptr<OneofDef> OneofDef::New() {
2907   upb_oneofdef *o = upb_oneofdef_new(&o);
2908   return reffed_ptr<OneofDef>(o, &o);
2909 }
full_name()2910 inline const char* OneofDef::full_name() const {
2911   return upb_oneofdef_name(this);
2912 }
2913 
containing_type()2914 inline const MessageDef* OneofDef::containing_type() const {
2915   return upb_oneofdef_containingtype(this);
2916 }
name()2917 inline const char* OneofDef::name() const {
2918   return upb_oneofdef_name(this);
2919 }
set_name(const char * name,Status * s)2920 inline bool OneofDef::set_name(const char* name, Status* s) {
2921   return upb_oneofdef_setname(this, name, s);
2922 }
field_count()2923 inline int OneofDef::field_count() const {
2924   return upb_oneofdef_numfields(this);
2925 }
AddField(FieldDef * field,Status * s)2926 inline bool OneofDef::AddField(FieldDef* field, Status* s) {
2927   return upb_oneofdef_addfield(this, field, NULL, s);
2928 }
AddField(const reffed_ptr<FieldDef> & field,Status * s)2929 inline bool OneofDef::AddField(const reffed_ptr<FieldDef>& field, Status* s) {
2930   return upb_oneofdef_addfield(this, field.get(), NULL, s);
2931 }
FindFieldByName(const char * name,size_t len)2932 inline const FieldDef* OneofDef::FindFieldByName(const char* name,
2933                                                  size_t len) const {
2934   return upb_oneofdef_ntof(this, name, len);
2935 }
FindFieldByNumber(uint32_t num)2936 inline const FieldDef* OneofDef::FindFieldByNumber(uint32_t num) const {
2937   return upb_oneofdef_itof(this, num);
2938 }
begin()2939 inline OneofDef::iterator OneofDef::begin() { return iterator(this); }
end()2940 inline OneofDef::iterator OneofDef::end() { return iterator::end(this); }
begin()2941 inline OneofDef::const_iterator OneofDef::begin() const {
2942   return const_iterator(this);
2943 }
end()2944 inline OneofDef::const_iterator OneofDef::end() const {
2945   return const_iterator::end(this);
2946 }
2947 
iterator(OneofDef * o)2948 inline OneofDef::iterator::iterator(OneofDef* o) {
2949   upb_oneof_begin(&iter_, o);
2950 }
end(OneofDef * o)2951 inline OneofDef::iterator OneofDef::iterator::end(OneofDef* o) {
2952   OneofDef::iterator iter(o);
2953   upb_oneof_iter_setdone(&iter.iter_);
2954   return iter;
2955 }
2956 inline FieldDef* OneofDef::iterator::operator*() const {
2957   return upb_oneof_iter_field(&iter_);
2958 }
2959 inline void OneofDef::iterator::operator++() { return upb_oneof_next(&iter_); }
2960 inline bool OneofDef::iterator::operator==(const iterator &other) const {
2961   return upb_inttable_iter_isequal(&iter_, &other.iter_);
2962 }
2963 inline bool OneofDef::iterator::operator!=(const iterator &other) const {
2964   return !(*this == other);
2965 }
2966 
const_iterator(const OneofDef * md)2967 inline OneofDef::const_iterator::const_iterator(const OneofDef* md) {
2968   upb_oneof_begin(&iter_, md);
2969 }
end(const OneofDef * md)2970 inline OneofDef::const_iterator OneofDef::const_iterator::end(
2971     const OneofDef *md) {
2972   OneofDef::const_iterator iter(md);
2973   upb_oneof_iter_setdone(&iter.iter_);
2974   return iter;
2975 }
2976 inline const FieldDef* OneofDef::const_iterator::operator*() const {
2977   return upb_msg_iter_field(&iter_);
2978 }
2979 inline void OneofDef::const_iterator::operator++() {
2980   return upb_oneof_next(&iter_);
2981 }
2982 inline bool OneofDef::const_iterator::operator==(
2983     const const_iterator &other) const {
2984   return upb_inttable_iter_isequal(&iter_, &other.iter_);
2985 }
2986 inline bool OneofDef::const_iterator::operator!=(
2987     const const_iterator &other) const {
2988   return !(*this == other);
2989 }
2990 
2991 }  /* namespace upb */
2992 #endif
2993 
2994 #endif /* UPB_DEF_H_ */
2995 /*
2996 ** This file contains definitions of structs that should be considered private
2997 ** and NOT stable across versions of upb.
2998 **
2999 ** The only reason they are declared here and not in .c files is to allow upb
3000 ** and the application (if desired) to embed statically-initialized instances
3001 ** of structures like defs.
3002 **
3003 ** If you include this file, all guarantees of ABI compatibility go out the
3004 ** window!  Any code that includes this file needs to recompile against the
3005 ** exact same version of upb that they are linking against.
3006 **
3007 ** You also need to recompile if you change the value of the UPB_DEBUG_REFS
3008 ** flag.
3009 */
3010 
3011 
3012 #ifndef UPB_STATICINIT_H_
3013 #define UPB_STATICINIT_H_
3014 
3015 #ifdef __cplusplus
3016 /* Because of how we do our typedefs, this header can't be included from C++. */
3017 #error This file cannot be included from C++
3018 #endif
3019 
3020 /* upb_refcounted *************************************************************/
3021 
3022 
3023 /* upb_def ********************************************************************/
3024 
3025 struct upb_def {
3026   upb_refcounted base;
3027 
3028   const char *fullname;
3029   char type;  /* A upb_deftype_t (char to save space) */
3030 
3031   /* Used as a flag during the def's mutable stage.  Must be false unless
3032    * it is currently being used by a function on the stack.  This allows
3033    * us to easily determine which defs were passed into the function's
3034    * current invocation. */
3035   bool came_from_user;
3036 };
3037 
3038 #define UPB_DEF_INIT(name, type, refs, ref2s) \
3039     { UPB_REFCOUNT_INIT(refs, ref2s), name, type, false }
3040 
3041 
3042 /* upb_fielddef ***************************************************************/
3043 
3044 struct upb_fielddef {
3045   upb_def base;
3046 
3047   union {
3048     int64_t sint;
3049     uint64_t uint;
3050     double dbl;
3051     float flt;
3052     void *bytes;
3053   } defaultval;
3054   union {
3055     const upb_msgdef *def;  /* If !msg_is_symbolic. */
3056     char *name;             /* If msg_is_symbolic. */
3057   } msg;
3058   union {
3059     const upb_def *def;  /* If !subdef_is_symbolic. */
3060     char *name;          /* If subdef_is_symbolic. */
3061   } sub;  /* The msgdef or enumdef for this field, if upb_hassubdef(f). */
3062   bool subdef_is_symbolic;
3063   bool msg_is_symbolic;
3064   const upb_oneofdef *oneof;
3065   bool default_is_string;
3066   bool type_is_set_;     /* False until type is explicitly set. */
3067   bool is_extension_;
3068   bool lazy_;
3069   bool packed_;
3070   upb_intfmt_t intfmt;
3071   bool tagdelim;
3072   upb_fieldtype_t type_;
3073   upb_label_t label_;
3074   uint32_t number_;
3075   uint32_t selector_base;  /* Used to index into a upb::Handlers table. */
3076   uint32_t index_;
3077 };
3078 
3079 #define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy,   \
3080                           packed, name, num, msgdef, subdef, selector_base,    \
3081                           index, defaultval, refs, ref2s)                      \
3082   {                                                                            \
3083     UPB_DEF_INIT(name, UPB_DEF_FIELD, refs, ref2s), defaultval, {msgdef},      \
3084         {subdef}, NULL, false, false,                                          \
3085         type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \
3086         lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \
3087   }
3088 
3089 
3090 /* upb_msgdef *****************************************************************/
3091 
3092 struct upb_msgdef {
3093   upb_def base;
3094 
3095   size_t selector_count;
3096   uint32_t submsg_field_count;
3097 
3098   /* Tables for looking up fields by number and name. */
3099   upb_inttable itof;  /* int to field */
3100   upb_strtable ntof;  /* name to field */
3101 
3102   /* Tables for looking up oneofs by name. */
3103   upb_strtable ntoo;  /* name to oneof */
3104 
3105   /* Is this a map-entry message?
3106    * TODO: set this flag properly for static descriptors; regenerate
3107    * descriptor.upb.c. */
3108   bool map_entry;
3109 
3110   /* TODO(haberman): proper extension ranges (there can be multiple). */
3111 };
3112 
3113 /* TODO: also support static initialization of the oneofs table. This will be
3114  * needed if we compile in descriptors that contain oneofs. */
3115 #define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \
3116                         refs, ref2s)                                          \
3117   {                                                                           \
3118     UPB_DEF_INIT(name, UPB_DEF_MSG, refs, ref2s), selector_count,             \
3119         submsg_field_count, itof, ntof,                                       \
3120         UPB_EMPTY_STRTABLE_INIT(UPB_CTYPE_PTR), false                         \
3121   }
3122 
3123 
3124 /* upb_enumdef ****************************************************************/
3125 
3126 struct upb_enumdef {
3127   upb_def base;
3128 
3129   upb_strtable ntoi;
3130   upb_inttable iton;
3131   int32_t defaultval;
3132 };
3133 
3134 #define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \
3135   { UPB_DEF_INIT(name, UPB_DEF_ENUM, refs, ref2s), ntoi, iton, defaultval }
3136 
3137 
3138 /* upb_oneofdef ***************************************************************/
3139 
3140 struct upb_oneofdef {
3141   upb_def base;
3142 
3143   upb_strtable ntof;
3144   upb_inttable itof;
3145   const upb_msgdef *parent;
3146 };
3147 
3148 #define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \
3149   { UPB_DEF_INIT(name, UPB_DEF_ENUM, refs, ref2s), ntof, itof }
3150 
3151 
3152 /* upb_symtab *****************************************************************/
3153 
3154 struct upb_symtab {
3155   upb_refcounted base;
3156 
3157   upb_strtable symtab;
3158 };
3159 
3160 #define UPB_SYMTAB_INIT(symtab, refs, ref2s) \
3161   { UPB_REFCOUNT_INIT(refs, ref2s), symtab }
3162 
3163 
3164 #endif  /* UPB_STATICINIT_H_ */
3165 /*
3166 ** upb::Handlers (upb_handlers)
3167 **
3168 ** A upb_handlers is like a virtual table for a upb_msgdef.  Each field of the
3169 ** message can have associated functions that will be called when we are
3170 ** parsing or visiting a stream of data.  This is similar to how handlers work
3171 ** in SAX (the Simple API for XML).
3172 **
3173 ** The handlers have no idea where the data is coming from, so a single set of
3174 ** handlers could be used with two completely different data sources (for
3175 ** example, a parser and a visitor over in-memory objects).  This decoupling is
3176 ** the most important feature of upb, because it allows parsers and serializers
3177 ** to be highly reusable.
3178 **
3179 ** This is a mixed C/C++ interface that offers a full API to both languages.
3180 ** See the top-level README for more information.
3181 */
3182 
3183 #ifndef UPB_HANDLERS_H
3184 #define UPB_HANDLERS_H
3185 
3186 
3187 #ifdef __cplusplus
3188 namespace upb {
3189 class BufferHandle;
3190 class BytesHandler;
3191 class HandlerAttributes;
3192 class Handlers;
3193 template <class T> class Handler;
3194 template <class T> struct CanonicalType;
3195 }  /* namespace upb */
3196 #endif
3197 
3198 UPB_DECLARE_TYPE(upb::BufferHandle, upb_bufhandle)
3199 UPB_DECLARE_TYPE(upb::BytesHandler, upb_byteshandler)
3200 UPB_DECLARE_TYPE(upb::HandlerAttributes, upb_handlerattr)
3201 UPB_DECLARE_DERIVED_TYPE(upb::Handlers, upb::RefCounted,
3202                          upb_handlers, upb_refcounted)
3203 
3204 /* The maximum depth that the handler graph can have.  This is a resource limit
3205  * for the C stack since we sometimes need to recursively traverse the graph.
3206  * Cycles are ok; the traversal will stop when it detects a cycle, but we must
3207  * hit the cycle before the maximum depth is reached.
3208  *
3209  * If having a single static limit is too inflexible, we can add another variant
3210  * of Handlers::Freeze that allows specifying this as a parameter. */
3211 #define UPB_MAX_HANDLER_DEPTH 64
3212 
3213 /* All the different types of handlers that can be registered.
3214  * Only needed for the advanced functions in upb::Handlers. */
3215 typedef enum {
3216   UPB_HANDLER_INT32,
3217   UPB_HANDLER_INT64,
3218   UPB_HANDLER_UINT32,
3219   UPB_HANDLER_UINT64,
3220   UPB_HANDLER_FLOAT,
3221   UPB_HANDLER_DOUBLE,
3222   UPB_HANDLER_BOOL,
3223   UPB_HANDLER_STARTSTR,
3224   UPB_HANDLER_STRING,
3225   UPB_HANDLER_ENDSTR,
3226   UPB_HANDLER_STARTSUBMSG,
3227   UPB_HANDLER_ENDSUBMSG,
3228   UPB_HANDLER_STARTSEQ,
3229   UPB_HANDLER_ENDSEQ
3230 } upb_handlertype_t;
3231 
3232 #define UPB_HANDLER_MAX (UPB_HANDLER_ENDSEQ+1)
3233 
3234 #define UPB_BREAK NULL
3235 
3236 /* A convenient definition for when no closure is needed. */
3237 extern char _upb_noclosure;
3238 #define UPB_NO_CLOSURE &_upb_noclosure
3239 
3240 /* A selector refers to a specific field handler in the Handlers object
3241  * (for example: the STARTSUBMSG handler for field "field15"). */
3242 typedef int32_t upb_selector_t;
3243 
3244 UPB_BEGIN_EXTERN_C
3245 
3246 /* Forward-declares for C inline accessors.  We need to declare these here
3247  * so we can "friend" them in the class declarations in C++. */
3248 UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h,
3249                                              upb_selector_t s);
3250 UPB_INLINE const void *upb_handlerattr_handlerdata(const upb_handlerattr *attr);
3251 UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h,
3252                                                    upb_selector_t s);
3253 
3254 UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h);
3255 UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj,
3256                                      const void *type);
3257 UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf,
3258                                      size_t ofs);
3259 UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h);
3260 UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h);
3261 UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h);
3262 
3263 UPB_END_EXTERN_C
3264 
3265 
3266 /* Static selectors for upb::Handlers. */
3267 #define UPB_STARTMSG_SELECTOR 0
3268 #define UPB_ENDMSG_SELECTOR 1
3269 #define UPB_STATIC_SELECTOR_COUNT 2
3270 
3271 /* Static selectors for upb::BytesHandler. */
3272 #define UPB_STARTSTR_SELECTOR 0
3273 #define UPB_STRING_SELECTOR 1
3274 #define UPB_ENDSTR_SELECTOR 2
3275 
3276 typedef void upb_handlerfree(void *d);
3277 
3278 #ifdef __cplusplus
3279 
3280 /* A set of attributes that accompanies a handler's function pointer. */
3281 class upb::HandlerAttributes {
3282  public:
3283   HandlerAttributes();
3284   ~HandlerAttributes();
3285 
3286   /* Sets the handler data that will be passed as the second parameter of the
3287    * handler.  To free this pointer when the handlers are freed, call
3288    * Handlers::AddCleanup(). */
3289   bool SetHandlerData(const void *handler_data);
3290   const void* handler_data() const;
3291 
3292   /* Use this to specify the type of the closure.  This will be checked against
3293    * all other closure types for handler that use the same closure.
3294    * Registration will fail if this does not match all other non-NULL closure
3295    * types. */
3296   bool SetClosureType(const void *closure_type);
3297   const void* closure_type() const;
3298 
3299   /* Use this to specify the type of the returned closure.  Only used for
3300    * Start*{String,SubMessage,Sequence} handlers.  This must match the closure
3301    * type of any handlers that use it (for example, the StringBuf handler must
3302    * match the closure returned from StartString). */
3303   bool SetReturnClosureType(const void *return_closure_type);
3304   const void* return_closure_type() const;
3305 
3306   /* Set to indicate that the handler always returns "ok" (either "true" or a
3307    * non-NULL closure).  This is a hint that can allow code generators to
3308    * generate more efficient code. */
3309   bool SetAlwaysOk(bool always_ok);
3310   bool always_ok() const;
3311 
3312  private:
3313   friend UPB_INLINE const void * ::upb_handlerattr_handlerdata(
3314       const upb_handlerattr *attr);
3315 #else
3316 struct upb_handlerattr {
3317 #endif
3318   const void *handler_data_;
3319   const void *closure_type_;
3320   const void *return_closure_type_;
3321   bool alwaysok_;
3322 };
3323 
3324 #define UPB_HANDLERATTR_INITIALIZER {NULL, NULL, NULL, false}
3325 
3326 typedef struct {
3327   upb_func *func;
3328 
3329   /* It is wasteful to include the entire attributes here:
3330    *
3331    * * Some of the information is redundant (like storing the closure type
3332    *   separately for each handler that must match).
3333    * * Some of the info is only needed prior to freeze() (like closure types).
3334    * * alignment padding wastes a lot of space for alwaysok_.
3335    *
3336    * If/when the size and locality of handlers is an issue, we can optimize this
3337    * not to store the entire attr like this.  We do not expose the table's
3338    * layout to allow this optimization in the future. */
3339   upb_handlerattr attr;
3340 } upb_handlers_tabent;
3341 
3342 #ifdef __cplusplus
3343 
3344 /* Extra information about a buffer that is passed to a StringBuf handler.
3345  * TODO(haberman): allow the handle to be pinned so that it will outlive
3346  * the handler invocation. */
3347 class upb::BufferHandle {
3348  public:
3349   BufferHandle();
3350   ~BufferHandle();
3351 
3352   /* The beginning of the buffer.  This may be different than the pointer
3353    * passed to a StringBuf handler because the handler may receive data
3354    * that is from the middle or end of a larger buffer. */
3355   const char* buffer() const;
3356 
3357   /* The offset within the attached object where this buffer begins.  Only
3358    * meaningful if there is an attached object. */
3359   size_t object_offset() const;
3360 
3361   /* Note that object_offset is the offset of "buf" within the attached
3362    * object. */
3363   void SetBuffer(const char* buf, size_t object_offset);
3364 
3365   /* The BufferHandle can have an "attached object", which can be used to
3366    * tunnel through a pointer to the buffer's underlying representation. */
3367   template <class T>
3368   void SetAttachedObject(const T* obj);
3369 
3370   /* Returns NULL if the attached object is not of this type. */
3371   template <class T>
3372   const T* GetAttachedObject() const;
3373 
3374  private:
3375   friend UPB_INLINE void ::upb_bufhandle_init(upb_bufhandle *h);
3376   friend UPB_INLINE void ::upb_bufhandle_setobj(upb_bufhandle *h,
3377                                                 const void *obj,
3378                                                 const void *type);
3379   friend UPB_INLINE void ::upb_bufhandle_setbuf(upb_bufhandle *h,
3380                                                 const char *buf, size_t ofs);
3381   friend UPB_INLINE const void* ::upb_bufhandle_obj(const upb_bufhandle *h);
3382   friend UPB_INLINE const void* ::upb_bufhandle_objtype(
3383       const upb_bufhandle *h);
3384   friend UPB_INLINE const char* ::upb_bufhandle_buf(const upb_bufhandle *h);
3385 #else
3386 struct upb_bufhandle {
3387 #endif
3388   const char *buf_;
3389   const void *obj_;
3390   const void *objtype_;
3391   size_t objofs_;
3392 };
3393 
3394 #ifdef __cplusplus
3395 
3396 /* A upb::Handlers object represents the set of handlers associated with a
3397  * message in the graph of messages.  You can think of it as a big virtual
3398  * table with functions corresponding to all the events that can fire while
3399  * parsing or visiting a message of a specific type.
3400  *
3401  * Any handlers that are not set behave as if they had successfully consumed
3402  * the value.  Any unset Start* handlers will propagate their closure to the
3403  * inner frame.
3404  *
3405  * The easiest way to create the *Handler objects needed by the Set* methods is
3406  * with the UpbBind() and UpbMakeHandler() macros; see below. */
3407 class upb::Handlers {
3408  public:
3409   typedef upb_selector_t Selector;
3410   typedef upb_handlertype_t Type;
3411 
3412   typedef Handler<void *(*)(void *, const void *)> StartFieldHandler;
3413   typedef Handler<bool (*)(void *, const void *)> EndFieldHandler;
3414   typedef Handler<bool (*)(void *, const void *)> StartMessageHandler;
3415   typedef Handler<bool (*)(void *, const void *, Status*)> EndMessageHandler;
3416   typedef Handler<void *(*)(void *, const void *, size_t)> StartStringHandler;
3417   typedef Handler<size_t (*)(void *, const void *, const char *, size_t,
3418                              const BufferHandle *)> StringHandler;
3419 
3420   template <class T> struct ValueHandler {
3421     typedef Handler<bool(*)(void *, const void *, T)> H;
3422   };
3423 
3424   typedef ValueHandler<int32_t>::H     Int32Handler;
3425   typedef ValueHandler<int64_t>::H     Int64Handler;
3426   typedef ValueHandler<uint32_t>::H    UInt32Handler;
3427   typedef ValueHandler<uint64_t>::H    UInt64Handler;
3428   typedef ValueHandler<float>::H       FloatHandler;
3429   typedef ValueHandler<double>::H      DoubleHandler;
3430   typedef ValueHandler<bool>::H        BoolHandler;
3431 
3432   /* Any function pointer can be converted to this and converted back to its
3433    * correct type. */
3434   typedef void GenericFunction();
3435 
3436   typedef void HandlersCallback(const void *closure, upb_handlers *h);
3437 
3438   /* Returns a new handlers object for the given frozen msgdef.
3439    * Returns NULL if memory allocation failed. */
3440   static reffed_ptr<Handlers> New(const MessageDef *m);
3441 
3442   /* Convenience function for registering a graph of handlers that mirrors the
3443    * graph of msgdefs for some message.  For "m" and all its children a new set
3444    * of handlers will be created and the given callback will be invoked,
3445    * allowing the client to register handlers for this message.  Note that any
3446    * subhandlers set by the callback will be overwritten. */
3447   static reffed_ptr<const Handlers> NewFrozen(const MessageDef *m,
3448                                               HandlersCallback *callback,
3449                                               const void *closure);
3450 
3451   /* Functionality from upb::RefCounted. */
3452   UPB_REFCOUNTED_CPPMETHODS
3453 
3454   /* All handler registration functions return bool to indicate success or
3455    * failure; details about failures are stored in this status object.  If a
3456    * failure does occur, it must be cleared before the Handlers are frozen,
3457    * otherwise the freeze() operation will fail.  The functions may *only* be
3458    * used while the Handlers are mutable. */
3459   const Status* status();
3460   void ClearError();
3461 
3462   /* Call to freeze these Handlers.  Requires that any SubHandlers are already
3463    * frozen.  For cycles, you must use the static version below and freeze the
3464    * whole graph at once. */
3465   bool Freeze(Status* s);
3466 
3467   /* Freezes the given set of handlers.  You may not freeze a handler without
3468    * also freezing any handlers they point to. */
3469   static bool Freeze(Handlers*const* handlers, int n, Status* s);
3470   static bool Freeze(const std::vector<Handlers*>& handlers, Status* s);
3471 
3472   /* Returns the msgdef associated with this handlers object. */
3473   const MessageDef* message_def() const;
3474 
3475   /* Adds the given pointer and function to the list of cleanup functions that
3476    * will be run when these handlers are freed.  If this pointer has previously
3477    * been registered, the function returns false and does nothing. */
3478   bool AddCleanup(void *ptr, upb_handlerfree *cleanup);
3479 
3480   /* Sets the startmsg handler for the message, which is defined as follows:
3481    *
3482    *   bool startmsg(MyType* closure) {
3483    *     // Called when the message begins.  Returns true if processing should
3484    *     // continue.
3485    *     return true;
3486    *   }
3487    */
3488   bool SetStartMessageHandler(const StartMessageHandler& handler);
3489 
3490   /* Sets the endmsg handler for the message, which is defined as follows:
3491    *
3492    *   bool endmsg(MyType* closure, upb_status *status) {
3493    *     // Called when processing of this message ends, whether in success or
3494    *     // failure.  "status" indicates the final status of processing, and
3495    *     // can also be modified in-place to update the final status.
3496    *   }
3497    */
3498   bool SetEndMessageHandler(const EndMessageHandler& handler);
3499 
3500   /* Sets the value handler for the given field, which is defined as follows
3501    * (this is for an int32 field; other field types will pass their native
3502    * C/C++ type for "val"):
3503    *
3504    *   bool OnValue(MyClosure* c, const MyHandlerData* d, int32_t val) {
3505    *     // Called when the field's value is encountered.  "d" contains
3506    *     // whatever data was bound to this field when it was registered.
3507    *     // Returns true if processing should continue.
3508    *     return true;
3509    *   }
3510    *
3511    *   handers->SetInt32Handler(f, UpbBind(OnValue, new MyHandlerData(...)));
3512    *
3513    * The value type must exactly match f->type().
3514    * For example, a handler that takes an int32_t parameter may only be used for
3515    * fields of type UPB_TYPE_INT32 and UPB_TYPE_ENUM.
3516    *
3517    * Returns false if the handler failed to register; in this case the cleanup
3518    * handler (if any) will be called immediately.
3519    */
3520   bool SetInt32Handler (const FieldDef* f,  const Int32Handler& h);
3521   bool SetInt64Handler (const FieldDef* f,  const Int64Handler& h);
3522   bool SetUInt32Handler(const FieldDef* f, const UInt32Handler& h);
3523   bool SetUInt64Handler(const FieldDef* f, const UInt64Handler& h);
3524   bool SetFloatHandler (const FieldDef* f,  const FloatHandler& h);
3525   bool SetDoubleHandler(const FieldDef* f, const DoubleHandler& h);
3526   bool SetBoolHandler  (const FieldDef* f,   const BoolHandler& h);
3527 
3528   /* Like the previous, but templated on the type on the value (ie. int32).
3529    * This is mostly useful to call from other templates.  To call this you must
3530    * specify the template parameter explicitly, ie:
3531    *   h->SetValueHandler<T>(f, UpbBind(MyHandler<T>, MyData)); */
3532   template <class T>
3533   bool SetValueHandler(
3534       const FieldDef *f,
3535       const typename ValueHandler<typename CanonicalType<T>::Type>::H& handler);
3536 
3537   /* Sets handlers for a string field, which are defined as follows:
3538    *
3539    *   MySubClosure* startstr(MyClosure* c, const MyHandlerData* d,
3540    *                          size_t size_hint) {
3541    *     // Called when a string value begins.  The return value indicates the
3542    *     // closure for the string.  "size_hint" indicates the size of the
3543    *     // string if it is known, however if the string is length-delimited
3544    *     // and the end-of-string is not available size_hint will be zero.
3545    *     // This case is indistinguishable from the case where the size is
3546    *     // known to be zero.
3547    *     //
3548    *     // TODO(haberman): is it important to distinguish these cases?
3549    *     // If we had ssize_t as a type we could make -1 "unknown", but
3550    *     // ssize_t is POSIX (not ANSI) and therefore less portable.
3551    *     // In practice I suspect it won't be important to distinguish.
3552    *     return closure;
3553    *   }
3554    *
3555    *   size_t str(MyClosure* closure, const MyHandlerData* d,
3556    *              const char *str, size_t len) {
3557    *     // Called for each buffer of string data; the multiple physical buffers
3558    *     // are all part of the same logical string.  The return value indicates
3559    *     // how many bytes were consumed.  If this number is less than "len",
3560    *     // this will also indicate that processing should be halted for now,
3561    *     // like returning false or UPB_BREAK from any other callback.  If
3562    *     // number is greater than "len", the excess bytes will be skipped over
3563    *     // and not passed to the callback.
3564    *     return len;
3565    *   }
3566    *
3567    *   bool endstr(MyClosure* c, const MyHandlerData* d) {
3568    *     // Called when a string value ends.  Return value indicates whether
3569    *     // processing should continue.
3570    *     return true;
3571    *   }
3572    */
3573   bool SetStartStringHandler(const FieldDef* f, const StartStringHandler& h);
3574   bool SetStringHandler(const FieldDef* f, const StringHandler& h);
3575   bool SetEndStringHandler(const FieldDef* f, const EndFieldHandler& h);
3576 
3577   /* Sets the startseq handler, which is defined as follows:
3578    *
3579    *   MySubClosure *startseq(MyClosure* c, const MyHandlerData* d) {
3580    *     // Called when a sequence (repeated field) begins.  The returned
3581    *     // pointer indicates the closure for the sequence (or UPB_BREAK
3582    *     // to interrupt processing).
3583    *     return closure;
3584    *   }
3585    *
3586    *   h->SetStartSequenceHandler(f, UpbBind(startseq, new MyHandlerData(...)));
3587    *
3588    * Returns "false" if "f" does not belong to this message or is not a
3589    * repeated field.
3590    */
3591   bool SetStartSequenceHandler(const FieldDef* f, const StartFieldHandler& h);
3592 
3593   /* Sets the startsubmsg handler for the given field, which is defined as
3594    * follows:
3595    *
3596    *   MySubClosure* startsubmsg(MyClosure* c, const MyHandlerData* d) {
3597    *     // Called when a submessage begins.  The returned pointer indicates the
3598    *     // closure for the sequence (or UPB_BREAK to interrupt processing).
3599    *     return closure;
3600    *   }
3601    *
3602    *   h->SetStartSubMessageHandler(f, UpbBind(startsubmsg,
3603    *                                           new MyHandlerData(...)));
3604    *
3605    * Returns "false" if "f" does not belong to this message or is not a
3606    * submessage/group field.
3607    */
3608   bool SetStartSubMessageHandler(const FieldDef* f, const StartFieldHandler& h);
3609 
3610   /* Sets the endsubmsg handler for the given field, which is defined as
3611    * follows:
3612    *
3613    *   bool endsubmsg(MyClosure* c, const MyHandlerData* d) {
3614    *     // Called when a submessage ends.  Returns true to continue processing.
3615    *     return true;
3616    *   }
3617    *
3618    * Returns "false" if "f" does not belong to this message or is not a
3619    * submessage/group field.
3620    */
3621   bool SetEndSubMessageHandler(const FieldDef *f, const EndFieldHandler &h);
3622 
3623   /* Starts the endsubseq handler for the given field, which is defined as
3624    * follows:
3625    *
3626    *   bool endseq(MyClosure* c, const MyHandlerData* d) {
3627    *     // Called when a sequence ends.  Returns true continue processing.
3628    *     return true;
3629    *   }
3630    *
3631    * Returns "false" if "f" does not belong to this message or is not a
3632    * repeated field.
3633    */
3634   bool SetEndSequenceHandler(const FieldDef* f, const EndFieldHandler& h);
3635 
3636   /* Sets or gets the object that specifies handlers for the given field, which
3637    * must be a submessage or group.  Returns NULL if no handlers are set. */
3638   bool SetSubHandlers(const FieldDef* f, const Handlers* sub);
3639   const Handlers* GetSubHandlers(const FieldDef* f) const;
3640 
3641   /* Equivalent to GetSubHandlers, but takes the STARTSUBMSG selector for the
3642    * field. */
3643   const Handlers* GetSubHandlers(Selector startsubmsg) const;
3644 
3645   /* A selector refers to a specific field handler in the Handlers object
3646    * (for example: the STARTSUBMSG handler for field "field15").
3647    * On success, returns true and stores the selector in "s".
3648    * If the FieldDef or Type are invalid, returns false.
3649    * The returned selector is ONLY valid for Handlers whose MessageDef
3650    * contains this FieldDef. */
3651   static bool GetSelector(const FieldDef* f, Type type, Selector* s);
3652 
3653   /* Given a START selector of any kind, returns the corresponding END selector. */
3654   static Selector GetEndSelector(Selector start_selector);
3655 
3656   /* Returns the function pointer for this handler.  It is the client's
3657    * responsibility to cast to the correct function type before calling it. */
3658   GenericFunction* GetHandler(Selector selector);
3659 
3660   /* Sets the given attributes to the attributes for this selector. */
3661   bool GetAttributes(Selector selector, HandlerAttributes* attr);
3662 
3663   /* Returns the handler data that was registered with this handler. */
3664   const void* GetHandlerData(Selector selector);
3665 
3666   /* Could add any of the following functions as-needed, with some minor
3667    * implementation changes:
3668    *
3669    * const FieldDef* GetFieldDef(Selector selector);
3670    * static bool IsSequence(Selector selector); */
3671 
3672  private:
3673   UPB_DISALLOW_POD_OPS(Handlers, upb::Handlers)
3674 
3675   friend UPB_INLINE GenericFunction *::upb_handlers_gethandler(
3676       const upb_handlers *h, upb_selector_t s);
3677   friend UPB_INLINE const void *::upb_handlers_gethandlerdata(
3678       const upb_handlers *h, upb_selector_t s);
3679 #else
3680 struct upb_handlers {
3681 #endif
3682   upb_refcounted base;
3683 
3684   const upb_msgdef *msg;
3685   const upb_handlers **sub;
3686   const void *top_closure_type;
3687   upb_inttable cleanup_;
3688   upb_status status_;  /* Used only when mutable. */
3689   upb_handlers_tabent table[1];  /* Dynamically-sized field handler array. */
3690 };
3691 
3692 #ifdef __cplusplus
3693 
3694 namespace upb {
3695 
3696 /* Convenience macros for creating a Handler object that is wrapped with a
3697  * type-safe wrapper function that converts the "void*" parameters/returns
3698  * of the underlying C API into nice C++ function.
3699  *
3700  * Sample usage:
3701  *   void OnValue1(MyClosure* c, const MyHandlerData* d, int32_t val) {
3702  *     // do stuff ...
3703  *   }
3704  *
3705  *   // Handler that doesn't need any data bound to it.
3706  *   void OnValue2(MyClosure* c, int32_t val) {
3707  *     // do stuff ...
3708  *   }
3709  *
3710  *   // Handler that returns bool so it can return failure if necessary.
3711  *   bool OnValue3(MyClosure* c, int32_t val) {
3712  *     // do stuff ...
3713  *     return ok;
3714  *   }
3715  *
3716  *   // Member function handler.
3717  *   class MyClosure {
3718  *    public:
3719  *     void OnValue(int32_t val) {
3720  *       // do stuff ...
3721  *     }
3722  *   };
3723  *
3724  *   // Takes ownership of the MyHandlerData.
3725  *   handlers->SetInt32Handler(f1, UpbBind(OnValue1, new MyHandlerData(...)));
3726  *   handlers->SetInt32Handler(f2, UpbMakeHandler(OnValue2));
3727  *   handlers->SetInt32Handler(f1, UpbMakeHandler(OnValue3));
3728  *   handlers->SetInt32Handler(f2, UpbMakeHandler(&MyClosure::OnValue));
3729  */
3730 
3731 #ifdef UPB_CXX11
3732 
3733 /* In C++11, the "template" disambiguator can appear even outside templates,
3734  * so all calls can safely use this pair of macros. */
3735 
3736 #define UpbMakeHandler(f) upb::MatchFunc(f).template GetFunc<f>()
3737 
3738 /* We have to be careful to only evaluate "d" once. */
3739 #define UpbBind(f, d) upb::MatchFunc(f).template GetFunc<f>((d))
3740 
3741 #else
3742 
3743 /* Prior to C++11, the "template" disambiguator may only appear inside a
3744  * template, so the regular macro must not use "template" */
3745 
3746 #define UpbMakeHandler(f) upb::MatchFunc(f).GetFunc<f>()
3747 
3748 #define UpbBind(f, d) upb::MatchFunc(f).GetFunc<f>((d))
3749 
3750 #endif  /* UPB_CXX11 */
3751 
3752 /* This macro must be used in C++98 for calls from inside a template.  But we
3753  * define this variant in all cases; code that wants to be compatible with both
3754  * C++98 and C++11 should always use this macro when calling from a template. */
3755 #define UpbMakeHandlerT(f) upb::MatchFunc(f).template GetFunc<f>()
3756 
3757 /* We have to be careful to only evaluate "d" once. */
3758 #define UpbBindT(f, d) upb::MatchFunc(f).template GetFunc<f>((d))
3759 
3760 /* Handler: a struct that contains the (handler, data, deleter) tuple that is
3761  * used to register all handlers.  Users can Make() these directly but it's
3762  * more convenient to use the UpbMakeHandler/UpbBind macros above. */
3763 template <class T> class Handler {
3764  public:
3765   /* The underlying, handler function signature that upb uses internally. */
3766   typedef T FuncPtr;
3767 
3768   /* Intentionally implicit. */
3769   template <class F> Handler(F func);
3770   ~Handler();
3771 
3772  private:
AddCleanup(Handlers * h)3773   void AddCleanup(Handlers* h) const {
3774     if (cleanup_func_) {
3775       bool ok = h->AddCleanup(cleanup_data_, cleanup_func_);
3776       UPB_ASSERT_VAR(ok, ok);
3777     }
3778   }
3779 
3780   UPB_DISALLOW_COPY_AND_ASSIGN(Handler)
3781   friend class Handlers;
3782   FuncPtr handler_;
3783   mutable HandlerAttributes attr_;
3784   mutable bool registered_;
3785   void *cleanup_data_;
3786   upb_handlerfree *cleanup_func_;
3787 };
3788 
3789 }  /* namespace upb */
3790 
3791 #endif  /* __cplusplus */
3792 
3793 UPB_BEGIN_EXTERN_C
3794 
3795 /* Native C API. */
3796 
3797 /* Handler function typedefs. */
3798 typedef bool upb_startmsg_handlerfunc(void *c, const void*);
3799 typedef bool upb_endmsg_handlerfunc(void *c, const void *, upb_status *status);
3800 typedef void* upb_startfield_handlerfunc(void *c, const void *hd);
3801 typedef bool upb_endfield_handlerfunc(void *c, const void *hd);
3802 typedef bool upb_int32_handlerfunc(void *c, const void *hd, int32_t val);
3803 typedef bool upb_int64_handlerfunc(void *c, const void *hd, int64_t val);
3804 typedef bool upb_uint32_handlerfunc(void *c, const void *hd, uint32_t val);
3805 typedef bool upb_uint64_handlerfunc(void *c, const void *hd, uint64_t val);
3806 typedef bool upb_float_handlerfunc(void *c, const void *hd, float val);
3807 typedef bool upb_double_handlerfunc(void *c, const void *hd, double val);
3808 typedef bool upb_bool_handlerfunc(void *c, const void *hd, bool val);
3809 typedef void *upb_startstr_handlerfunc(void *c, const void *hd,
3810                                        size_t size_hint);
3811 typedef size_t upb_string_handlerfunc(void *c, const void *hd, const char *buf,
3812                                       size_t n, const upb_bufhandle* handle);
3813 
3814 /* upb_bufhandle */
3815 size_t upb_bufhandle_objofs(const upb_bufhandle *h);
3816 
3817 /* upb_handlerattr */
3818 void upb_handlerattr_init(upb_handlerattr *attr);
3819 void upb_handlerattr_uninit(upb_handlerattr *attr);
3820 
3821 bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd);
3822 bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type);
3823 const void *upb_handlerattr_closuretype(const upb_handlerattr *attr);
3824 bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
3825                                           const void *type);
3826 const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr);
3827 bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok);
3828 bool upb_handlerattr_alwaysok(const upb_handlerattr *attr);
3829 
upb_handlerattr_handlerdata(const upb_handlerattr * attr)3830 UPB_INLINE const void *upb_handlerattr_handlerdata(
3831     const upb_handlerattr *attr) {
3832   return attr->handler_data_;
3833 }
3834 
3835 /* upb_handlers */
3836 typedef void upb_handlers_callback(const void *closure, upb_handlers *h);
3837 upb_handlers *upb_handlers_new(const upb_msgdef *m,
3838                                const void *owner);
3839 const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
3840                                            const void *owner,
3841                                            upb_handlers_callback *callback,
3842                                            const void *closure);
3843 
3844 /* Include refcounted methods like upb_handlers_ref(). */
3845 UPB_REFCOUNTED_CMETHODS(upb_handlers, upb_handlers_upcast)
3846 
3847 const upb_status *upb_handlers_status(upb_handlers *h);
3848 void upb_handlers_clearerr(upb_handlers *h);
3849 const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h);
3850 bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *hfree);
3851 
3852 bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
3853                               upb_handlerattr *attr);
3854 bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
3855                             upb_handlerattr *attr);
3856 bool upb_handlers_setint32(upb_handlers *h, const upb_fielddef *f,
3857                            upb_int32_handlerfunc *func, upb_handlerattr *attr);
3858 bool upb_handlers_setint64(upb_handlers *h, const upb_fielddef *f,
3859                            upb_int64_handlerfunc *func, upb_handlerattr *attr);
3860 bool upb_handlers_setuint32(upb_handlers *h, const upb_fielddef *f,
3861                             upb_uint32_handlerfunc *func,
3862                             upb_handlerattr *attr);
3863 bool upb_handlers_setuint64(upb_handlers *h, const upb_fielddef *f,
3864                             upb_uint64_handlerfunc *func,
3865                             upb_handlerattr *attr);
3866 bool upb_handlers_setfloat(upb_handlers *h, const upb_fielddef *f,
3867                            upb_float_handlerfunc *func, upb_handlerattr *attr);
3868 bool upb_handlers_setdouble(upb_handlers *h, const upb_fielddef *f,
3869                             upb_double_handlerfunc *func,
3870                             upb_handlerattr *attr);
3871 bool upb_handlers_setbool(upb_handlers *h, const upb_fielddef *f,
3872                           upb_bool_handlerfunc *func,
3873                           upb_handlerattr *attr);
3874 bool upb_handlers_setstartstr(upb_handlers *h, const upb_fielddef *f,
3875                               upb_startstr_handlerfunc *func,
3876                               upb_handlerattr *attr);
3877 bool upb_handlers_setstring(upb_handlers *h, const upb_fielddef *f,
3878                             upb_string_handlerfunc *func,
3879                             upb_handlerattr *attr);
3880 bool upb_handlers_setendstr(upb_handlers *h, const upb_fielddef *f,
3881                             upb_endfield_handlerfunc *func,
3882                             upb_handlerattr *attr);
3883 bool upb_handlers_setstartseq(upb_handlers *h, const upb_fielddef *f,
3884                               upb_startfield_handlerfunc *func,
3885                               upb_handlerattr *attr);
3886 bool upb_handlers_setstartsubmsg(upb_handlers *h, const upb_fielddef *f,
3887                                  upb_startfield_handlerfunc *func,
3888                                  upb_handlerattr *attr);
3889 bool upb_handlers_setendsubmsg(upb_handlers *h, const upb_fielddef *f,
3890                                upb_endfield_handlerfunc *func,
3891                                upb_handlerattr *attr);
3892 bool upb_handlers_setendseq(upb_handlers *h, const upb_fielddef *f,
3893                             upb_endfield_handlerfunc *func,
3894                             upb_handlerattr *attr);
3895 
3896 bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
3897                                  const upb_handlers *sub);
3898 const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
3899                                                 const upb_fielddef *f);
3900 const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
3901                                                     upb_selector_t sel);
3902 
upb_handlers_gethandler(const upb_handlers * h,upb_selector_t s)3903 UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h,
3904                                              upb_selector_t s) {
3905   return (upb_func *)h->table[s].func;
3906 }
3907 
3908 bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t s,
3909                           upb_handlerattr *attr);
3910 
upb_handlers_gethandlerdata(const upb_handlers * h,upb_selector_t s)3911 UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h,
3912                                                    upb_selector_t s) {
3913   return upb_handlerattr_handlerdata(&h->table[s].attr);
3914 }
3915 
3916 #ifdef __cplusplus
3917 
3918 /* Handler types for single fields.
3919  * Right now we only have one for TYPE_BYTES but ones for other types
3920  * should follow.
3921  *
3922  * These follow the same handlers protocol for fields of a message. */
3923 class upb::BytesHandler {
3924  public:
3925   BytesHandler();
3926   ~BytesHandler();
3927 #else
3928 struct upb_byteshandler {
3929 #endif
3930   upb_handlers_tabent table[3];
3931 };
3932 
3933 void upb_byteshandler_init(upb_byteshandler *h);
3934 
3935 /* Caller must ensure that "d" outlives the handlers.
3936  * TODO(haberman): should this have a "freeze" operation?  It's not necessary
3937  * for memory management, but could be useful to force immutability and provide
3938  * a convenient moment to verify that all registration succeeded. */
3939 bool upb_byteshandler_setstartstr(upb_byteshandler *h,
3940                                   upb_startstr_handlerfunc *func, void *d);
3941 bool upb_byteshandler_setstring(upb_byteshandler *h,
3942                                 upb_string_handlerfunc *func, void *d);
3943 bool upb_byteshandler_setendstr(upb_byteshandler *h,
3944                                 upb_endfield_handlerfunc *func, void *d);
3945 
3946 /* "Static" methods */
3947 bool upb_handlers_freeze(upb_handlers *const *handlers, int n, upb_status *s);
3948 upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f);
3949 bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
3950                               upb_selector_t *s);
upb_handlers_getendselector(upb_selector_t start)3951 UPB_INLINE upb_selector_t upb_handlers_getendselector(upb_selector_t start) {
3952   return start + 1;
3953 }
3954 
3955 /* Internal-only. */
3956 uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f);
3957 uint32_t upb_handlers_selectorcount(const upb_fielddef *f);
3958 
3959 UPB_END_EXTERN_C
3960 
3961 /*
3962 ** Inline definitions for handlers.h, which are particularly long and a bit
3963 ** tricky.
3964 */
3965 
3966 #ifndef UPB_HANDLERS_INL_H_
3967 #define UPB_HANDLERS_INL_H_
3968 
3969 #include <limits.h>
3970 
3971 /* C inline methods. */
3972 
3973 /* upb_bufhandle */
upb_bufhandle_init(upb_bufhandle * h)3974 UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h) {
3975   h->obj_ = NULL;
3976   h->objtype_ = NULL;
3977   h->buf_ = NULL;
3978   h->objofs_ = 0;
3979 }
upb_bufhandle_uninit(upb_bufhandle * h)3980 UPB_INLINE void upb_bufhandle_uninit(upb_bufhandle *h) {
3981   UPB_UNUSED(h);
3982 }
upb_bufhandle_setobj(upb_bufhandle * h,const void * obj,const void * type)3983 UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj,
3984                                      const void *type) {
3985   h->obj_ = obj;
3986   h->objtype_ = type;
3987 }
upb_bufhandle_setbuf(upb_bufhandle * h,const char * buf,size_t ofs)3988 UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf,
3989                                      size_t ofs) {
3990   h->buf_ = buf;
3991   h->objofs_ = ofs;
3992 }
upb_bufhandle_obj(const upb_bufhandle * h)3993 UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h) {
3994   return h->obj_;
3995 }
upb_bufhandle_objtype(const upb_bufhandle * h)3996 UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h) {
3997   return h->objtype_;
3998 }
upb_bufhandle_buf(const upb_bufhandle * h)3999 UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h) {
4000   return h->buf_;
4001 }
4002 
4003 
4004 #ifdef __cplusplus
4005 
4006 /* Type detection and typedefs for integer types.
4007  * For platforms where there are multiple 32-bit or 64-bit types, we need to be
4008  * able to enumerate them so we can properly create overloads for all variants.
4009  *
4010  * If any platform existed where there were three integer types with the same
4011  * size, this would have to become more complicated.  For example, short, int,
4012  * and long could all be 32-bits.  Even more diabolically, short, int, long,
4013  * and long long could all be 64 bits and still be standard-compliant.
4014  * However, few platforms are this strange, and it's unlikely that upb will be
4015  * used on the strangest ones. */
4016 
4017 /* Can't count on stdint.h limits like INT32_MAX, because in C++ these are
4018  * only defined when __STDC_LIMIT_MACROS are defined before the *first* include
4019  * of stdint.h.  We can't guarantee that someone else didn't include these first
4020  * without defining __STDC_LIMIT_MACROS. */
4021 #define UPB_INT32_MAX 0x7fffffffLL
4022 #define UPB_INT32_MIN (-UPB_INT32_MAX - 1)
4023 #define UPB_INT64_MAX 0x7fffffffffffffffLL
4024 #define UPB_INT64_MIN (-UPB_INT64_MAX - 1)
4025 
4026 #if INT_MAX == UPB_INT32_MAX && INT_MIN == UPB_INT32_MIN
4027 #define UPB_INT_IS_32BITS 1
4028 #endif
4029 
4030 #if LONG_MAX == UPB_INT32_MAX && LONG_MIN == UPB_INT32_MIN
4031 #define UPB_LONG_IS_32BITS 1
4032 #endif
4033 
4034 #if LONG_MAX == UPB_INT64_MAX && LONG_MIN == UPB_INT64_MIN
4035 #define UPB_LONG_IS_64BITS 1
4036 #endif
4037 
4038 #if LLONG_MAX == UPB_INT64_MAX && LLONG_MIN == UPB_INT64_MIN
4039 #define UPB_LLONG_IS_64BITS 1
4040 #endif
4041 
4042 /* We use macros instead of typedefs so we can undefine them later and avoid
4043  * leaking them outside this header file. */
4044 #if UPB_INT_IS_32BITS
4045 #define UPB_INT32_T int
4046 #define UPB_UINT32_T unsigned int
4047 
4048 #if UPB_LONG_IS_32BITS
4049 #define UPB_TWO_32BIT_TYPES 1
4050 #define UPB_INT32ALT_T long
4051 #define UPB_UINT32ALT_T unsigned long
4052 #endif  /* UPB_LONG_IS_32BITS */
4053 
4054 #elif UPB_LONG_IS_32BITS  /* && !UPB_INT_IS_32BITS */
4055 #define UPB_INT32_T long
4056 #define UPB_UINT32_T unsigned long
4057 #endif  /* UPB_INT_IS_32BITS */
4058 
4059 
4060 #if UPB_LONG_IS_64BITS
4061 #define UPB_INT64_T long
4062 #define UPB_UINT64_T unsigned long
4063 
4064 #if UPB_LLONG_IS_64BITS
4065 #define UPB_TWO_64BIT_TYPES 1
4066 #define UPB_INT64ALT_T long long
4067 #define UPB_UINT64ALT_T unsigned long long
4068 #endif  /* UPB_LLONG_IS_64BITS */
4069 
4070 #elif UPB_LLONG_IS_64BITS  /* && !UPB_LONG_IS_64BITS */
4071 #define UPB_INT64_T long long
4072 #define UPB_UINT64_T unsigned long long
4073 #endif  /* UPB_LONG_IS_64BITS */
4074 
4075 #undef UPB_INT32_MAX
4076 #undef UPB_INT32_MIN
4077 #undef UPB_INT64_MAX
4078 #undef UPB_INT64_MIN
4079 #undef UPB_INT_IS_32BITS
4080 #undef UPB_LONG_IS_32BITS
4081 #undef UPB_LONG_IS_64BITS
4082 #undef UPB_LLONG_IS_64BITS
4083 
4084 
4085 namespace upb {
4086 
4087 typedef void CleanupFunc(void *ptr);
4088 
4089 /* Template to remove "const" from "const T*" and just return "T*".
4090  *
4091  * We define a nonsense default because otherwise it will fail to instantiate as
4092  * a function parameter type even in cases where we don't expect any caller to
4093  * actually match the overload. */
4094 class CouldntRemoveConst {};
4095 template <class T> struct remove_constptr { typedef CouldntRemoveConst type; };
4096 template <class T> struct remove_constptr<const T *> { typedef T *type; };
4097 
4098 /* Template that we use below to remove a template specialization from
4099  * consideration if it matches a specific type. */
4100 template <class T, class U> struct disable_if_same { typedef void Type; };
4101 template <class T> struct disable_if_same<T, T> {};
4102 
4103 template <class T> void DeletePointer(void *p) { delete static_cast<T>(p); }
4104 
4105 template <class T1, class T2>
4106 struct FirstUnlessVoidOrBool {
4107   typedef T1 value;
4108 };
4109 
4110 template <class T2>
4111 struct FirstUnlessVoidOrBool<void, T2> {
4112   typedef T2 value;
4113 };
4114 
4115 template <class T2>
4116 struct FirstUnlessVoidOrBool<bool, T2> {
4117   typedef T2 value;
4118 };
4119 
4120 template<class T, class U>
4121 struct is_same {
4122   static bool value;
4123 };
4124 
4125 template<class T>
4126 struct is_same<T, T> {
4127   static bool value;
4128 };
4129 
4130 template<class T, class U>
4131 bool is_same<T, U>::value = false;
4132 
4133 template<class T>
4134 bool is_same<T, T>::value = true;
4135 
4136 /* FuncInfo *******************************************************************/
4137 
4138 /* Info about the user's original, pre-wrapped function. */
4139 template <class C, class R = void>
4140 struct FuncInfo {
4141   /* The type of the closure that the function takes (its first param). */
4142   typedef C Closure;
4143 
4144   /* The return type. */
4145   typedef R Return;
4146 };
4147 
4148 /* Func ***********************************************************************/
4149 
4150 /* Func1, Func2, Func3: Template classes representing a function and its
4151  * signature.
4152  *
4153  * Since the function is a template parameter, calling the function can be
4154  * inlined at compile-time and does not require a function pointer at runtime.
4155  * These functions are not bound to a handler data so have no data or cleanup
4156  * handler. */
4157 struct UnboundFunc {
4158   CleanupFunc *GetCleanup() { return NULL; }
4159   void *GetData() { return NULL; }
4160 };
4161 
4162 template <class R, class P1, R F(P1), class I>
4163 struct Func1 : public UnboundFunc {
4164   typedef R Return;
4165   typedef I FuncInfo;
4166   static R Call(P1 p1) { return F(p1); }
4167 };
4168 
4169 template <class R, class P1, class P2, R F(P1, P2), class I>
4170 struct Func2 : public UnboundFunc {
4171   typedef R Return;
4172   typedef I FuncInfo;
4173   static R Call(P1 p1, P2 p2) { return F(p1, p2); }
4174 };
4175 
4176 template <class R, class P1, class P2, class P3, R F(P1, P2, P3), class I>
4177 struct Func3 : public UnboundFunc {
4178   typedef R Return;
4179   typedef I FuncInfo;
4180   static R Call(P1 p1, P2 p2, P3 p3) { return F(p1, p2, p3); }
4181 };
4182 
4183 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4),
4184           class I>
4185 struct Func4 : public UnboundFunc {
4186   typedef R Return;
4187   typedef I FuncInfo;
4188   static R Call(P1 p1, P2 p2, P3 p3, P4 p4) { return F(p1, p2, p3, p4); }
4189 };
4190 
4191 template <class R, class P1, class P2, class P3, class P4, class P5,
4192           R F(P1, P2, P3, P4, P5), class I>
4193 struct Func5 : public UnboundFunc {
4194   typedef R Return;
4195   typedef I FuncInfo;
4196   static R Call(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
4197     return F(p1, p2, p3, p4, p5);
4198   }
4199 };
4200 
4201 /* BoundFunc ******************************************************************/
4202 
4203 /* BoundFunc2, BoundFunc3: Like Func2/Func3 except also contains a value that
4204  * shall be bound to the function's second parameter.
4205  *
4206  * Note that the second parameter is a const pointer, but our stored bound value
4207  * is non-const so we can free it when the handlers are destroyed. */
4208 template <class T>
4209 struct BoundFunc {
4210   typedef typename remove_constptr<T>::type MutableP2;
4211   explicit BoundFunc(MutableP2 data_) : data(data_) {}
4212   CleanupFunc *GetCleanup() { return &DeletePointer<MutableP2>; }
4213   MutableP2 GetData() { return data; }
4214   MutableP2 data;
4215 };
4216 
4217 template <class R, class P1, class P2, R F(P1, P2), class I>
4218 struct BoundFunc2 : public BoundFunc<P2> {
4219   typedef BoundFunc<P2> Base;
4220   typedef I FuncInfo;
4221   explicit BoundFunc2(typename Base::MutableP2 arg) : Base(arg) {}
4222 };
4223 
4224 template <class R, class P1, class P2, class P3, R F(P1, P2, P3), class I>
4225 struct BoundFunc3 : public BoundFunc<P2> {
4226   typedef BoundFunc<P2> Base;
4227   typedef I FuncInfo;
4228   explicit BoundFunc3(typename Base::MutableP2 arg) : Base(arg) {}
4229 };
4230 
4231 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4),
4232           class I>
4233 struct BoundFunc4 : public BoundFunc<P2> {
4234   typedef BoundFunc<P2> Base;
4235   typedef I FuncInfo;
4236   explicit BoundFunc4(typename Base::MutableP2 arg) : Base(arg) {}
4237 };
4238 
4239 template <class R, class P1, class P2, class P3, class P4, class P5,
4240           R F(P1, P2, P3, P4, P5), class I>
4241 struct BoundFunc5 : public BoundFunc<P2> {
4242   typedef BoundFunc<P2> Base;
4243   typedef I FuncInfo;
4244   explicit BoundFunc5(typename Base::MutableP2 arg) : Base(arg) {}
4245 };
4246 
4247 /* FuncSig ********************************************************************/
4248 
4249 /* FuncSig1, FuncSig2, FuncSig3: template classes reflecting a function
4250  * *signature*, but without a specific function attached.
4251  *
4252  * These classes contain member functions that can be invoked with a
4253  * specific function to return a Func/BoundFunc class. */
4254 template <class R, class P1>
4255 struct FuncSig1 {
4256   template <R F(P1)>
4257   Func1<R, P1, F, FuncInfo<P1, R> > GetFunc() {
4258     return Func1<R, P1, F, FuncInfo<P1, R> >();
4259   }
4260 };
4261 
4262 template <class R, class P1, class P2>
4263 struct FuncSig2 {
4264   template <R F(P1, P2)>
4265   Func2<R, P1, P2, F, FuncInfo<P1, R> > GetFunc() {
4266     return Func2<R, P1, P2, F, FuncInfo<P1, R> >();
4267   }
4268 
4269   template <R F(P1, P2)>
4270   BoundFunc2<R, P1, P2, F, FuncInfo<P1, R> > GetFunc(
4271       typename remove_constptr<P2>::type param2) {
4272     return BoundFunc2<R, P1, P2, F, FuncInfo<P1, R> >(param2);
4273   }
4274 };
4275 
4276 template <class R, class P1, class P2, class P3>
4277 struct FuncSig3 {
4278   template <R F(P1, P2, P3)>
4279   Func3<R, P1, P2, P3, F, FuncInfo<P1, R> > GetFunc() {
4280     return Func3<R, P1, P2, P3, F, FuncInfo<P1, R> >();
4281   }
4282 
4283   template <R F(P1, P2, P3)>
4284   BoundFunc3<R, P1, P2, P3, F, FuncInfo<P1, R> > GetFunc(
4285       typename remove_constptr<P2>::type param2) {
4286     return BoundFunc3<R, P1, P2, P3, F, FuncInfo<P1, R> >(param2);
4287   }
4288 };
4289 
4290 template <class R, class P1, class P2, class P3, class P4>
4291 struct FuncSig4 {
4292   template <R F(P1, P2, P3, P4)>
4293   Func4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> > GetFunc() {
4294     return Func4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> >();
4295   }
4296 
4297   template <R F(P1, P2, P3, P4)>
4298   BoundFunc4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> > GetFunc(
4299       typename remove_constptr<P2>::type param2) {
4300     return BoundFunc4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> >(param2);
4301   }
4302 };
4303 
4304 template <class R, class P1, class P2, class P3, class P4, class P5>
4305 struct FuncSig5 {
4306   template <R F(P1, P2, P3, P4, P5)>
4307   Func5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> > GetFunc() {
4308     return Func5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> >();
4309   }
4310 
4311   template <R F(P1, P2, P3, P4, P5)>
4312   BoundFunc5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> > GetFunc(
4313       typename remove_constptr<P2>::type param2) {
4314     return BoundFunc5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> >(param2);
4315   }
4316 };
4317 
4318 /* Overloaded template function that can construct the appropriate FuncSig*
4319  * class given a function pointer by deducing the template parameters. */
4320 template <class R, class P1>
4321 inline FuncSig1<R, P1> MatchFunc(R (*f)(P1)) {
4322   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4323   return FuncSig1<R, P1>();
4324 }
4325 
4326 template <class R, class P1, class P2>
4327 inline FuncSig2<R, P1, P2> MatchFunc(R (*f)(P1, P2)) {
4328   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4329   return FuncSig2<R, P1, P2>();
4330 }
4331 
4332 template <class R, class P1, class P2, class P3>
4333 inline FuncSig3<R, P1, P2, P3> MatchFunc(R (*f)(P1, P2, P3)) {
4334   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4335   return FuncSig3<R, P1, P2, P3>();
4336 }
4337 
4338 template <class R, class P1, class P2, class P3, class P4>
4339 inline FuncSig4<R, P1, P2, P3, P4> MatchFunc(R (*f)(P1, P2, P3, P4)) {
4340   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4341   return FuncSig4<R, P1, P2, P3, P4>();
4342 }
4343 
4344 template <class R, class P1, class P2, class P3, class P4, class P5>
4345 inline FuncSig5<R, P1, P2, P3, P4, P5> MatchFunc(R (*f)(P1, P2, P3, P4, P5)) {
4346   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4347   return FuncSig5<R, P1, P2, P3, P4, P5>();
4348 }
4349 
4350 /* MethodSig ******************************************************************/
4351 
4352 /* CallMethod*: a function template that calls a given method. */
4353 template <class R, class C, R (C::*F)()>
4354 R CallMethod0(C *obj) {
4355   return ((*obj).*F)();
4356 }
4357 
4358 template <class R, class C, class P1, R (C::*F)(P1)>
4359 R CallMethod1(C *obj, P1 arg1) {
4360   return ((*obj).*F)(arg1);
4361 }
4362 
4363 template <class R, class C, class P1, class P2, R (C::*F)(P1, P2)>
4364 R CallMethod2(C *obj, P1 arg1, P2 arg2) {
4365   return ((*obj).*F)(arg1, arg2);
4366 }
4367 
4368 template <class R, class C, class P1, class P2, class P3, R (C::*F)(P1, P2, P3)>
4369 R CallMethod3(C *obj, P1 arg1, P2 arg2, P3 arg3) {
4370   return ((*obj).*F)(arg1, arg2, arg3);
4371 }
4372 
4373 template <class R, class C, class P1, class P2, class P3, class P4,
4374           R (C::*F)(P1, P2, P3, P4)>
4375 R CallMethod4(C *obj, P1 arg1, P2 arg2, P3 arg3, P4 arg4) {
4376   return ((*obj).*F)(arg1, arg2, arg3, arg4);
4377 }
4378 
4379 /* MethodSig: like FuncSig, but for member functions.
4380  *
4381  * GetFunc() returns a normal FuncN object, so after calling GetFunc() no
4382  * more logic is required to special-case methods. */
4383 template <class R, class C>
4384 struct MethodSig0 {
4385   template <R (C::*F)()>
4386   Func1<R, C *, CallMethod0<R, C, F>, FuncInfo<C *, R> > GetFunc() {
4387     return Func1<R, C *, CallMethod0<R, C, F>, FuncInfo<C *, R> >();
4388   }
4389 };
4390 
4391 template <class R, class C, class P1>
4392 struct MethodSig1 {
4393   template <R (C::*F)(P1)>
4394   Func2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> > GetFunc() {
4395     return Func2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> >();
4396   }
4397 
4398   template <R (C::*F)(P1)>
4399   BoundFunc2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> > GetFunc(
4400       typename remove_constptr<P1>::type param1) {
4401     return BoundFunc2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> >(
4402         param1);
4403   }
4404 };
4405 
4406 template <class R, class C, class P1, class P2>
4407 struct MethodSig2 {
4408   template <R (C::*F)(P1, P2)>
4409   Func3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>, FuncInfo<C *, R> >
4410   GetFunc() {
4411     return Func3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>,
4412                  FuncInfo<C *, R> >();
4413   }
4414 
4415   template <R (C::*F)(P1, P2)>
4416   BoundFunc3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>, FuncInfo<C *, R> >
4417   GetFunc(typename remove_constptr<P1>::type param1) {
4418     return BoundFunc3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>,
4419                       FuncInfo<C *, R> >(param1);
4420   }
4421 };
4422 
4423 template <class R, class C, class P1, class P2, class P3>
4424 struct MethodSig3 {
4425   template <R (C::*F)(P1, P2, P3)>
4426   Func4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>, FuncInfo<C *, R> >
4427   GetFunc() {
4428     return Func4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>,
4429                  FuncInfo<C *, R> >();
4430   }
4431 
4432   template <R (C::*F)(P1, P2, P3)>
4433   BoundFunc4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>,
4434              FuncInfo<C *, R> >
4435   GetFunc(typename remove_constptr<P1>::type param1) {
4436     return BoundFunc4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>,
4437                       FuncInfo<C *, R> >(param1);
4438   }
4439 };
4440 
4441 template <class R, class C, class P1, class P2, class P3, class P4>
4442 struct MethodSig4 {
4443   template <R (C::*F)(P1, P2, P3, P4)>
4444   Func5<R, C *, P1, P2, P3, P4, CallMethod4<R, C, P1, P2, P3, P4, F>,
4445         FuncInfo<C *, R> >
4446   GetFunc() {
4447     return Func5<R, C *, P1, P2, P3, P4, CallMethod4<R, C, P1, P2, P3, P4, F>,
4448                  FuncInfo<C *, R> >();
4449   }
4450 
4451   template <R (C::*F)(P1, P2, P3, P4)>
4452   BoundFunc5<R, C *, P1, P2, P3, P4, CallMethod4<R, C, P1, P2, P3, P4, F>,
4453              FuncInfo<C *, R> >
4454   GetFunc(typename remove_constptr<P1>::type param1) {
4455     return BoundFunc5<R, C *, P1, P2, P3, P4,
4456                       CallMethod4<R, C, P1, P2, P3, P4, F>, FuncInfo<C *, R> >(
4457         param1);
4458   }
4459 };
4460 
4461 template <class R, class C>
4462 inline MethodSig0<R, C> MatchFunc(R (C::*f)()) {
4463   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4464   return MethodSig0<R, C>();
4465 }
4466 
4467 template <class R, class C, class P1>
4468 inline MethodSig1<R, C, P1> MatchFunc(R (C::*f)(P1)) {
4469   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4470   return MethodSig1<R, C, P1>();
4471 }
4472 
4473 template <class R, class C, class P1, class P2>
4474 inline MethodSig2<R, C, P1, P2> MatchFunc(R (C::*f)(P1, P2)) {
4475   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4476   return MethodSig2<R, C, P1, P2>();
4477 }
4478 
4479 template <class R, class C, class P1, class P2, class P3>
4480 inline MethodSig3<R, C, P1, P2, P3> MatchFunc(R (C::*f)(P1, P2, P3)) {
4481   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4482   return MethodSig3<R, C, P1, P2, P3>();
4483 }
4484 
4485 template <class R, class C, class P1, class P2, class P3, class P4>
4486 inline MethodSig4<R, C, P1, P2, P3, P4> MatchFunc(R (C::*f)(P1, P2, P3, P4)) {
4487   UPB_UNUSED(f);  /* Only used for template parameter deduction. */
4488   return MethodSig4<R, C, P1, P2, P3, P4>();
4489 }
4490 
4491 /* MaybeWrapReturn ************************************************************/
4492 
4493 /* Template class that attempts to wrap the return value of the function so it
4494  * matches the expected type.  There are two main adjustments it may make:
4495  *
4496  *   1. If the function returns void, make it return the expected type and with
4497  *      a value that always indicates success.
4498  *   2. If the function returns bool, make it return the expected type with a
4499  *      value that indicates success or failure.
4500  *
4501  * The "expected type" for return is:
4502  *   1. void* for start handlers.  If the closure parameter has a different type
4503  *      we will cast it to void* for the return in the success case.
4504  *   2. size_t for string buffer handlers.
4505  *   3. bool for everything else. */
4506 
4507 /* Template parameters are FuncN type and desired return type. */
4508 template <class F, class R, class Enable = void>
4509 struct MaybeWrapReturn;
4510 
4511 /* If the return type matches, return the given function unwrapped. */
4512 template <class F>
4513 struct MaybeWrapReturn<F, typename F::Return> {
4514   typedef F Func;
4515 };
4516 
4517 /* Function wrapper that munges the return value from void to (bool)true. */
4518 template <class P1, class P2, void F(P1, P2)>
4519 bool ReturnTrue2(P1 p1, P2 p2) {
4520   F(p1, p2);
4521   return true;
4522 }
4523 
4524 template <class P1, class P2, class P3, void F(P1, P2, P3)>
4525 bool ReturnTrue3(P1 p1, P2 p2, P3 p3) {
4526   F(p1, p2, p3);
4527   return true;
4528 }
4529 
4530 /* Function wrapper that munges the return value from void to (void*)arg1  */
4531 template <class P1, class P2, void F(P1, P2)>
4532 void *ReturnClosure2(P1 p1, P2 p2) {
4533   F(p1, p2);
4534   return p1;
4535 }
4536 
4537 template <class P1, class P2, class P3, void F(P1, P2, P3)>
4538 void *ReturnClosure3(P1 p1, P2 p2, P3 p3) {
4539   F(p1, p2, p3);
4540   return p1;
4541 }
4542 
4543 /* Function wrapper that munges the return value from R to void*. */
4544 template <class R, class P1, class P2, R F(P1, P2)>
4545 void *CastReturnToVoidPtr2(P1 p1, P2 p2) {
4546   return F(p1, p2);
4547 }
4548 
4549 template <class R, class P1, class P2, class P3, R F(P1, P2, P3)>
4550 void *CastReturnToVoidPtr3(P1 p1, P2 p2, P3 p3) {
4551   return F(p1, p2, p3);
4552 }
4553 
4554 /* Function wrapper that munges the return value from bool to void*. */
4555 template <class P1, class P2, bool F(P1, P2)>
4556 void *ReturnClosureOrBreak2(P1 p1, P2 p2) {
4557   return F(p1, p2) ? p1 : UPB_BREAK;
4558 }
4559 
4560 template <class P1, class P2, class P3, bool F(P1, P2, P3)>
4561 void *ReturnClosureOrBreak3(P1 p1, P2 p2, P3 p3) {
4562   return F(p1, p2, p3) ? p1 : UPB_BREAK;
4563 }
4564 
4565 /* For the string callback, which takes five params, returns the size param. */
4566 template <class P1, class P2,
4567           void F(P1, P2, const char *, size_t, const BufferHandle *)>
4568 size_t ReturnStringLen(P1 p1, P2 p2, const char *p3, size_t p4,
4569                        const BufferHandle *p5) {
4570   F(p1, p2, p3, p4, p5);
4571   return p4;
4572 }
4573 
4574 /* For the string callback, which takes five params, returns the size param or
4575  * zero. */
4576 template <class P1, class P2,
4577           bool F(P1, P2, const char *, size_t, const BufferHandle *)>
4578 size_t ReturnNOr0(P1 p1, P2 p2, const char *p3, size_t p4,
4579                   const BufferHandle *p5) {
4580   return F(p1, p2, p3, p4, p5) ? p4 : 0;
4581 }
4582 
4583 /* If we have a function returning void but want a function returning bool, wrap
4584  * it in a function that returns true. */
4585 template <class P1, class P2, void F(P1, P2), class I>
4586 struct MaybeWrapReturn<Func2<void, P1, P2, F, I>, bool> {
4587   typedef Func2<bool, P1, P2, ReturnTrue2<P1, P2, F>, I> Func;
4588 };
4589 
4590 template <class P1, class P2, class P3, void F(P1, P2, P3), class I>
4591 struct MaybeWrapReturn<Func3<void, P1, P2, P3, F, I>, bool> {
4592   typedef Func3<bool, P1, P2, P3, ReturnTrue3<P1, P2, P3, F>, I> Func;
4593 };
4594 
4595 /* If our function returns void but we want one returning void*, wrap it in a
4596  * function that returns the first argument. */
4597 template <class P1, class P2, void F(P1, P2), class I>
4598 struct MaybeWrapReturn<Func2<void, P1, P2, F, I>, void *> {
4599   typedef Func2<void *, P1, P2, ReturnClosure2<P1, P2, F>, I> Func;
4600 };
4601 
4602 template <class P1, class P2, class P3, void F(P1, P2, P3), class I>
4603 struct MaybeWrapReturn<Func3<void, P1, P2, P3, F, I>, void *> {
4604   typedef Func3<void *, P1, P2, P3, ReturnClosure3<P1, P2, P3, F>, I> Func;
4605 };
4606 
4607 /* If our function returns R* but we want one returning void*, wrap it in a
4608  * function that casts to void*. */
4609 template <class R, class P1, class P2, R *F(P1, P2), class I>
4610 struct MaybeWrapReturn<Func2<R *, P1, P2, F, I>, void *,
4611                        typename disable_if_same<R *, void *>::Type> {
4612   typedef Func2<void *, P1, P2, CastReturnToVoidPtr2<R *, P1, P2, F>, I> Func;
4613 };
4614 
4615 template <class R, class P1, class P2, class P3, R *F(P1, P2, P3), class I>
4616 struct MaybeWrapReturn<Func3<R *, P1, P2, P3, F, I>, void *,
4617                        typename disable_if_same<R *, void *>::Type> {
4618   typedef Func3<void *, P1, P2, P3, CastReturnToVoidPtr3<R *, P1, P2, P3, F>, I>
4619       Func;
4620 };
4621 
4622 /* If our function returns bool but we want one returning void*, wrap it in a
4623  * function that returns either the first param or UPB_BREAK. */
4624 template <class P1, class P2, bool F(P1, P2), class I>
4625 struct MaybeWrapReturn<Func2<bool, P1, P2, F, I>, void *> {
4626   typedef Func2<void *, P1, P2, ReturnClosureOrBreak2<P1, P2, F>, I> Func;
4627 };
4628 
4629 template <class P1, class P2, class P3, bool F(P1, P2, P3), class I>
4630 struct MaybeWrapReturn<Func3<bool, P1, P2, P3, F, I>, void *> {
4631   typedef Func3<void *, P1, P2, P3, ReturnClosureOrBreak3<P1, P2, P3, F>, I>
4632       Func;
4633 };
4634 
4635 /* If our function returns void but we want one returning size_t, wrap it in a
4636  * function that returns the size argument. */
4637 template <class P1, class P2,
4638           void F(P1, P2, const char *, size_t, const BufferHandle *), class I>
4639 struct MaybeWrapReturn<
4640     Func5<void, P1, P2, const char *, size_t, const BufferHandle *, F, I>,
4641           size_t> {
4642   typedef Func5<size_t, P1, P2, const char *, size_t, const BufferHandle *,
4643                 ReturnStringLen<P1, P2, F>, I> Func;
4644 };
4645 
4646 /* If our function returns bool but we want one returning size_t, wrap it in a
4647  * function that returns either 0 or the buf size. */
4648 template <class P1, class P2,
4649           bool F(P1, P2, const char *, size_t, const BufferHandle *), class I>
4650 struct MaybeWrapReturn<
4651     Func5<bool, P1, P2, const char *, size_t, const BufferHandle *, F, I>,
4652     size_t> {
4653   typedef Func5<size_t, P1, P2, const char *, size_t, const BufferHandle *,
4654                 ReturnNOr0<P1, P2, F>, I> Func;
4655 };
4656 
4657 /* ConvertParams **************************************************************/
4658 
4659 /* Template class that converts the function parameters if necessary, and
4660  * ignores the HandlerData parameter if appropriate.
4661  *
4662  * Template parameter is the are FuncN function type. */
4663 template <class F, class T>
4664 struct ConvertParams;
4665 
4666 /* Function that discards the handler data parameter. */
4667 template <class R, class P1, R F(P1)>
4668 R IgnoreHandlerData2(void *p1, const void *hd) {
4669   UPB_UNUSED(hd);
4670   return F(static_cast<P1>(p1));
4671 }
4672 
4673 template <class R, class P1, class P2Wrapper, class P2Wrapped,
4674           R F(P1, P2Wrapped)>
4675 R IgnoreHandlerData3(void *p1, const void *hd, P2Wrapper p2) {
4676   UPB_UNUSED(hd);
4677   return F(static_cast<P1>(p1), p2);
4678 }
4679 
4680 template <class R, class P1, class P2, class P3, R F(P1, P2, P3)>
4681 R IgnoreHandlerData4(void *p1, const void *hd, P2 p2, P3 p3) {
4682   UPB_UNUSED(hd);
4683   return F(static_cast<P1>(p1), p2, p3);
4684 }
4685 
4686 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4)>
4687 R IgnoreHandlerData5(void *p1, const void *hd, P2 p2, P3 p3, P4 p4) {
4688   UPB_UNUSED(hd);
4689   return F(static_cast<P1>(p1), p2, p3, p4);
4690 }
4691 
4692 template <class R, class P1, R F(P1, const char*, size_t)>
4693 R IgnoreHandlerDataIgnoreHandle(void *p1, const void *hd, const char *p2,
4694                                 size_t p3, const BufferHandle *handle) {
4695   UPB_UNUSED(hd);
4696   UPB_UNUSED(handle);
4697   return F(static_cast<P1>(p1), p2, p3);
4698 }
4699 
4700 /* Function that casts the handler data parameter. */
4701 template <class R, class P1, class P2, R F(P1, P2)>
4702 R CastHandlerData2(void *c, const void *hd) {
4703   return F(static_cast<P1>(c), static_cast<P2>(hd));
4704 }
4705 
4706 template <class R, class P1, class P2, class P3Wrapper, class P3Wrapped,
4707           R F(P1, P2, P3Wrapped)>
4708 R CastHandlerData3(void *c, const void *hd, P3Wrapper p3) {
4709   return F(static_cast<P1>(c), static_cast<P2>(hd), p3);
4710 }
4711 
4712 template <class R, class P1, class P2, class P3, class P4, class P5,
4713           R F(P1, P2, P3, P4, P5)>
4714 R CastHandlerData5(void *c, const void *hd, P3 p3, P4 p4, P5 p5) {
4715   return F(static_cast<P1>(c), static_cast<P2>(hd), p3, p4, p5);
4716 }
4717 
4718 template <class R, class P1, class P2, R F(P1, P2, const char *, size_t)>
4719 R CastHandlerDataIgnoreHandle(void *c, const void *hd, const char *p3,
4720                               size_t p4, const BufferHandle *handle) {
4721   UPB_UNUSED(handle);
4722   return F(static_cast<P1>(c), static_cast<P2>(hd), p3, p4);
4723 }
4724 
4725 /* For unbound functions, ignore the handler data. */
4726 template <class R, class P1, R F(P1), class I, class T>
4727 struct ConvertParams<Func1<R, P1, F, I>, T> {
4728   typedef Func2<R, void *, const void *, IgnoreHandlerData2<R, P1, F>, I> Func;
4729 };
4730 
4731 template <class R, class P1, class P2, R F(P1, P2), class I,
4732           class R2, class P1_2, class P2_2, class P3_2>
4733 struct ConvertParams<Func2<R, P1, P2, F, I>,
4734                      R2 (*)(P1_2, P2_2, P3_2)> {
4735   typedef Func3<R, void *, const void *, P3_2,
4736                 IgnoreHandlerData3<R, P1, P3_2, P2, F>, I> Func;
4737 };
4738 
4739 /* For StringBuffer only; this ignores both the handler data and the
4740  * BufferHandle. */
4741 template <class R, class P1, R F(P1, const char *, size_t), class I, class T>
4742 struct ConvertParams<Func3<R, P1, const char *, size_t, F, I>, T> {
4743   typedef Func5<R, void *, const void *, const char *, size_t,
4744                 const BufferHandle *, IgnoreHandlerDataIgnoreHandle<R, P1, F>,
4745                 I> Func;
4746 };
4747 
4748 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4),
4749           class I, class T>
4750 struct ConvertParams<Func4<R, P1, P2, P3, P4, F, I>, T> {
4751   typedef Func5<R, void *, const void *, P2, P3, P4,
4752                 IgnoreHandlerData5<R, P1, P2, P3, P4, F>, I> Func;
4753 };
4754 
4755 /* For bound functions, cast the handler data. */
4756 template <class R, class P1, class P2, R F(P1, P2), class I, class T>
4757 struct ConvertParams<BoundFunc2<R, P1, P2, F, I>, T> {
4758   typedef Func2<R, void *, const void *, CastHandlerData2<R, P1, P2, F>, I>
4759       Func;
4760 };
4761 
4762 template <class R, class P1, class P2, class P3, R F(P1, P2, P3), class I,
4763           class R2, class P1_2, class P2_2, class P3_2>
4764 struct ConvertParams<BoundFunc3<R, P1, P2, P3, F, I>,
4765                      R2 (*)(P1_2, P2_2, P3_2)> {
4766   typedef Func3<R, void *, const void *, P3_2,
4767                 CastHandlerData3<R, P1, P2, P3_2, P3, F>, I> Func;
4768 };
4769 
4770 /* For StringBuffer only; this ignores the BufferHandle. */
4771 template <class R, class P1, class P2, R F(P1, P2, const char *, size_t),
4772           class I, class T>
4773 struct ConvertParams<BoundFunc4<R, P1, P2, const char *, size_t, F, I>, T> {
4774   typedef Func5<R, void *, const void *, const char *, size_t,
4775                 const BufferHandle *, CastHandlerDataIgnoreHandle<R, P1, P2, F>,
4776                 I> Func;
4777 };
4778 
4779 template <class R, class P1, class P2, class P3, class P4, class P5,
4780           R F(P1, P2, P3, P4, P5), class I, class T>
4781 struct ConvertParams<BoundFunc5<R, P1, P2, P3, P4, P5, F, I>, T> {
4782   typedef Func5<R, void *, const void *, P3, P4, P5,
4783                 CastHandlerData5<R, P1, P2, P3, P4, P5, F>, I> Func;
4784 };
4785 
4786 /* utype/ltype are upper/lower-case, ctype is canonical C type, vtype is
4787  * variant C type. */
4788 #define TYPE_METHODS(utype, ltype, ctype, vtype)                               \
4789   template <> struct CanonicalType<vtype> {                                    \
4790     typedef ctype Type;                                                        \
4791   };                                                                           \
4792   template <>                                                                  \
4793   inline bool Handlers::SetValueHandler<vtype>(                                \
4794       const FieldDef *f,                                                       \
4795       const Handlers::utype ## Handler& handler) {                             \
4796     assert(!handler.registered_);                                              \
4797     handler.AddCleanup(this);                                                  \
4798     handler.registered_ = true;                                                \
4799     return upb_handlers_set##ltype(this, f, handler.handler_, &handler.attr_); \
4800   }                                                                            \
4801 
4802 TYPE_METHODS(Double, double, double,   double)
4803 TYPE_METHODS(Float,  float,  float,    float)
4804 TYPE_METHODS(UInt64, uint64, uint64_t, UPB_UINT64_T)
4805 TYPE_METHODS(UInt32, uint32, uint32_t, UPB_UINT32_T)
4806 TYPE_METHODS(Int64,  int64,  int64_t,  UPB_INT64_T)
4807 TYPE_METHODS(Int32,  int32,  int32_t,  UPB_INT32_T)
4808 TYPE_METHODS(Bool,   bool,   bool,     bool)
4809 
4810 #ifdef UPB_TWO_32BIT_TYPES
4811 TYPE_METHODS(Int32,  int32,  int32_t,  UPB_INT32ALT_T)
4812 TYPE_METHODS(UInt32, uint32, uint32_t, UPB_UINT32ALT_T)
4813 #endif
4814 
4815 #ifdef UPB_TWO_64BIT_TYPES
4816 TYPE_METHODS(Int64,  int64,  int64_t,  UPB_INT64ALT_T)
4817 TYPE_METHODS(UInt64, uint64, uint64_t, UPB_UINT64ALT_T)
4818 #endif
4819 #undef TYPE_METHODS
4820 
4821 template <> struct CanonicalType<Status*> {
4822   typedef Status* Type;
4823 };
4824 
4825 /* Type methods that are only one-per-canonical-type and not
4826  * one-per-cvariant. */
4827 
4828 #define TYPE_METHODS(utype, ctype) \
4829     inline bool Handlers::Set##utype##Handler(const FieldDef *f, \
4830                                               const utype##Handler &h) { \
4831       return SetValueHandler<ctype>(f, h); \
4832     } \
4833 
4834 TYPE_METHODS(Double, double)
4835 TYPE_METHODS(Float,  float)
4836 TYPE_METHODS(UInt64, uint64_t)
4837 TYPE_METHODS(UInt32, uint32_t)
4838 TYPE_METHODS(Int64,  int64_t)
4839 TYPE_METHODS(Int32,  int32_t)
4840 TYPE_METHODS(Bool,   bool)
4841 #undef TYPE_METHODS
4842 
4843 template <class F> struct ReturnOf;
4844 
4845 template <class R, class P1, class P2>
4846 struct ReturnOf<R (*)(P1, P2)> {
4847   typedef R Return;
4848 };
4849 
4850 template <class R, class P1, class P2, class P3>
4851 struct ReturnOf<R (*)(P1, P2, P3)> {
4852   typedef R Return;
4853 };
4854 
4855 template <class R, class P1, class P2, class P3, class P4>
4856 struct ReturnOf<R (*)(P1, P2, P3, P4)> {
4857   typedef R Return;
4858 };
4859 
4860 template <class R, class P1, class P2, class P3, class P4, class P5>
4861 struct ReturnOf<R (*)(P1, P2, P3, P4, P5)> {
4862   typedef R Return;
4863 };
4864 
4865 template<class T> const void *UniquePtrForType() {
4866   static const char ch = 0;
4867   return &ch;
4868 }
4869 
4870 template <class T>
4871 template <class F>
4872 inline Handler<T>::Handler(F func)
4873     : registered_(false),
4874       cleanup_data_(func.GetData()),
4875       cleanup_func_(func.GetCleanup()) {
4876   upb_handlerattr_sethandlerdata(&attr_, func.GetData());
4877   typedef typename ReturnOf<T>::Return Return;
4878   typedef typename ConvertParams<F, T>::Func ConvertedParamsFunc;
4879   typedef typename MaybeWrapReturn<ConvertedParamsFunc, Return>::Func
4880       ReturnWrappedFunc;
4881   handler_ = ReturnWrappedFunc().Call;
4882 
4883   /* Set attributes based on what templates can statically tell us about the
4884    * user's function. */
4885 
4886   /* If the original function returns void, then we know that we wrapped it to
4887    * always return ok. */
4888   bool always_ok = is_same<typename F::FuncInfo::Return, void>::value;
4889   attr_.SetAlwaysOk(always_ok);
4890 
4891   /* Closure parameter and return type. */
4892   attr_.SetClosureType(UniquePtrForType<typename F::FuncInfo::Closure>());
4893 
4894   /* We use the closure type (from the first parameter) if the return type is
4895    * void or bool, since these are the two cases we wrap to return the closure's
4896    * type anyway.
4897    *
4898    * This is all nonsense for non START* handlers, but it doesn't matter because
4899    * in that case the value will be ignored. */
4900   typedef typename FirstUnlessVoidOrBool<typename F::FuncInfo::Return,
4901                                          typename F::FuncInfo::Closure>::value
4902       EffectiveReturn;
4903   attr_.SetReturnClosureType(UniquePtrForType<EffectiveReturn>());
4904 }
4905 
4906 template <class T>
4907 inline Handler<T>::~Handler() {
4908   assert(registered_);
4909 }
4910 
4911 inline HandlerAttributes::HandlerAttributes() { upb_handlerattr_init(this); }
4912 inline HandlerAttributes::~HandlerAttributes() { upb_handlerattr_uninit(this); }
4913 inline bool HandlerAttributes::SetHandlerData(const void *hd) {
4914   return upb_handlerattr_sethandlerdata(this, hd);
4915 }
4916 inline const void* HandlerAttributes::handler_data() const {
4917   return upb_handlerattr_handlerdata(this);
4918 }
4919 inline bool HandlerAttributes::SetClosureType(const void *type) {
4920   return upb_handlerattr_setclosuretype(this, type);
4921 }
4922 inline const void* HandlerAttributes::closure_type() const {
4923   return upb_handlerattr_closuretype(this);
4924 }
4925 inline bool HandlerAttributes::SetReturnClosureType(const void *type) {
4926   return upb_handlerattr_setreturnclosuretype(this, type);
4927 }
4928 inline const void* HandlerAttributes::return_closure_type() const {
4929   return upb_handlerattr_returnclosuretype(this);
4930 }
4931 inline bool HandlerAttributes::SetAlwaysOk(bool always_ok) {
4932   return upb_handlerattr_setalwaysok(this, always_ok);
4933 }
4934 inline bool HandlerAttributes::always_ok() const {
4935   return upb_handlerattr_alwaysok(this);
4936 }
4937 
4938 inline BufferHandle::BufferHandle() { upb_bufhandle_init(this); }
4939 inline BufferHandle::~BufferHandle() { upb_bufhandle_uninit(this); }
4940 inline const char* BufferHandle::buffer() const {
4941   return upb_bufhandle_buf(this);
4942 }
4943 inline size_t BufferHandle::object_offset() const {
4944   return upb_bufhandle_objofs(this);
4945 }
4946 inline void BufferHandle::SetBuffer(const char* buf, size_t ofs) {
4947   upb_bufhandle_setbuf(this, buf, ofs);
4948 }
4949 template <class T>
4950 void BufferHandle::SetAttachedObject(const T* obj) {
4951   upb_bufhandle_setobj(this, obj, UniquePtrForType<T>());
4952 }
4953 template <class T>
4954 const T* BufferHandle::GetAttachedObject() const {
4955   return upb_bufhandle_objtype(this) == UniquePtrForType<T>()
4956       ? static_cast<const T *>(upb_bufhandle_obj(this))
4957                                : NULL;
4958 }
4959 
4960 inline reffed_ptr<Handlers> Handlers::New(const MessageDef *m) {
4961   upb_handlers *h = upb_handlers_new(m, &h);
4962   return reffed_ptr<Handlers>(h, &h);
4963 }
4964 inline reffed_ptr<const Handlers> Handlers::NewFrozen(
4965     const MessageDef *m, upb_handlers_callback *callback,
4966     const void *closure) {
4967   const upb_handlers *h = upb_handlers_newfrozen(m, &h, callback, closure);
4968   return reffed_ptr<const Handlers>(h, &h);
4969 }
4970 inline const Status* Handlers::status() {
4971   return upb_handlers_status(this);
4972 }
4973 inline void Handlers::ClearError() {
4974   return upb_handlers_clearerr(this);
4975 }
4976 inline bool Handlers::Freeze(Status *s) {
4977   upb::Handlers* h = this;
4978   return upb_handlers_freeze(&h, 1, s);
4979 }
4980 inline bool Handlers::Freeze(Handlers *const *handlers, int n, Status *s) {
4981   return upb_handlers_freeze(handlers, n, s);
4982 }
4983 inline bool Handlers::Freeze(const std::vector<Handlers*>& h, Status* status) {
4984   return upb_handlers_freeze((Handlers* const*)&h[0], h.size(), status);
4985 }
4986 inline const MessageDef *Handlers::message_def() const {
4987   return upb_handlers_msgdef(this);
4988 }
4989 inline bool Handlers::AddCleanup(void *p, upb_handlerfree *func) {
4990   return upb_handlers_addcleanup(this, p, func);
4991 }
4992 inline bool Handlers::SetStartMessageHandler(
4993     const Handlers::StartMessageHandler &handler) {
4994   assert(!handler.registered_);
4995   handler.registered_ = true;
4996   handler.AddCleanup(this);
4997   return upb_handlers_setstartmsg(this, handler.handler_, &handler.attr_);
4998 }
4999 inline bool Handlers::SetEndMessageHandler(
5000     const Handlers::EndMessageHandler &handler) {
5001   assert(!handler.registered_);
5002   handler.registered_ = true;
5003   handler.AddCleanup(this);
5004   return upb_handlers_setendmsg(this, handler.handler_, &handler.attr_);
5005 }
5006 inline bool Handlers::SetStartStringHandler(const FieldDef *f,
5007                                             const StartStringHandler &handler) {
5008   assert(!handler.registered_);
5009   handler.registered_ = true;
5010   handler.AddCleanup(this);
5011   return upb_handlers_setstartstr(this, f, handler.handler_, &handler.attr_);
5012 }
5013 inline bool Handlers::SetEndStringHandler(const FieldDef *f,
5014                                           const EndFieldHandler &handler) {
5015   assert(!handler.registered_);
5016   handler.registered_ = true;
5017   handler.AddCleanup(this);
5018   return upb_handlers_setendstr(this, f, handler.handler_, &handler.attr_);
5019 }
5020 inline bool Handlers::SetStringHandler(const FieldDef *f,
5021                                        const StringHandler& handler) {
5022   assert(!handler.registered_);
5023   handler.registered_ = true;
5024   handler.AddCleanup(this);
5025   return upb_handlers_setstring(this, f, handler.handler_, &handler.attr_);
5026 }
5027 inline bool Handlers::SetStartSequenceHandler(
5028     const FieldDef *f, const StartFieldHandler &handler) {
5029   assert(!handler.registered_);
5030   handler.registered_ = true;
5031   handler.AddCleanup(this);
5032   return upb_handlers_setstartseq(this, f, handler.handler_, &handler.attr_);
5033 }
5034 inline bool Handlers::SetStartSubMessageHandler(
5035     const FieldDef *f, const StartFieldHandler &handler) {
5036   assert(!handler.registered_);
5037   handler.registered_ = true;
5038   handler.AddCleanup(this);
5039   return upb_handlers_setstartsubmsg(this, f, handler.handler_, &handler.attr_);
5040 }
5041 inline bool Handlers::SetEndSubMessageHandler(const FieldDef *f,
5042                                               const EndFieldHandler &handler) {
5043   assert(!handler.registered_);
5044   handler.registered_ = true;
5045   handler.AddCleanup(this);
5046   return upb_handlers_setendsubmsg(this, f, handler.handler_, &handler.attr_);
5047 }
5048 inline bool Handlers::SetEndSequenceHandler(const FieldDef *f,
5049                                             const EndFieldHandler &handler) {
5050   assert(!handler.registered_);
5051   handler.registered_ = true;
5052   handler.AddCleanup(this);
5053   return upb_handlers_setendseq(this, f, handler.handler_, &handler.attr_);
5054 }
5055 inline bool Handlers::SetSubHandlers(const FieldDef *f, const Handlers *sub) {
5056   return upb_handlers_setsubhandlers(this, f, sub);
5057 }
5058 inline const Handlers *Handlers::GetSubHandlers(const FieldDef *f) const {
5059   return upb_handlers_getsubhandlers(this, f);
5060 }
5061 inline const Handlers *Handlers::GetSubHandlers(Handlers::Selector sel) const {
5062   return upb_handlers_getsubhandlers_sel(this, sel);
5063 }
5064 inline bool Handlers::GetSelector(const FieldDef *f, Handlers::Type type,
5065                                   Handlers::Selector *s) {
5066   return upb_handlers_getselector(f, type, s);
5067 }
5068 inline Handlers::Selector Handlers::GetEndSelector(Handlers::Selector start) {
5069   return upb_handlers_getendselector(start);
5070 }
5071 inline Handlers::GenericFunction *Handlers::GetHandler(
5072     Handlers::Selector selector) {
5073   return upb_handlers_gethandler(this, selector);
5074 }
5075 inline const void *Handlers::GetHandlerData(Handlers::Selector selector) {
5076   return upb_handlers_gethandlerdata(this, selector);
5077 }
5078 
5079 inline BytesHandler::BytesHandler() {
5080   upb_byteshandler_init(this);
5081 }
5082 
5083 inline BytesHandler::~BytesHandler() {}
5084 
5085 }  /* namespace upb */
5086 
5087 #endif  /* __cplusplus */
5088 
5089 
5090 #undef UPB_TWO_32BIT_TYPES
5091 #undef UPB_TWO_64BIT_TYPES
5092 #undef UPB_INT32_T
5093 #undef UPB_UINT32_T
5094 #undef UPB_INT32ALT_T
5095 #undef UPB_UINT32ALT_T
5096 #undef UPB_INT64_T
5097 #undef UPB_UINT64_T
5098 #undef UPB_INT64ALT_T
5099 #undef UPB_UINT64ALT_T
5100 
5101 #endif  /* UPB_HANDLERS_INL_H_ */
5102 
5103 #endif  /* UPB_HANDLERS_H */
5104 /*
5105 ** upb::Environment (upb_env)
5106 **
5107 ** A upb::Environment provides a means for injecting malloc and an
5108 ** error-reporting callback into encoders/decoders.  This allows them to be
5109 ** independent of nearly all assumptions about their actual environment.
5110 **
5111 ** It is also a container for allocating the encoders/decoders themselves that
5112 ** insulates clients from knowing their actual size.  This provides ABI
5113 ** compatibility even if the size of the objects change.  And this allows the
5114 ** structure definitions to be in the .c files instead of the .h files, making
5115 ** the .h files smaller and more readable.
5116 */
5117 
5118 
5119 #ifndef UPB_ENV_H_
5120 #define UPB_ENV_H_
5121 
5122 #ifdef __cplusplus
5123 namespace upb {
5124 class Environment;
5125 class SeededAllocator;
5126 }
5127 #endif
5128 
5129 UPB_DECLARE_TYPE(upb::Environment, upb_env)
5130 UPB_DECLARE_TYPE(upb::SeededAllocator, upb_seededalloc)
5131 
5132 typedef void *upb_alloc_func(void *ud, void *ptr, size_t oldsize, size_t size);
5133 typedef void upb_cleanup_func(void *ud);
5134 typedef bool upb_error_func(void *ud, const upb_status *status);
5135 
5136 #ifdef __cplusplus
5137 
5138 /* An environment is *not* thread-safe. */
5139 class upb::Environment {
5140  public:
5141   Environment();
5142   ~Environment();
5143 
5144   /* Set a custom memory allocation function for the environment.  May ONLY
5145    * be called before any calls to Malloc()/Realloc()/AddCleanup() below.
5146    * If this is not called, the system realloc() function will be used.
5147    * The given user pointer "ud" will be passed to the allocation function.
5148    *
5149    * The allocation function will not receive corresponding "free" calls.  it
5150    * must ensure that the memory is valid for the lifetime of the Environment,
5151    * but it may be reclaimed any time thereafter.  The likely usage is that
5152    * "ud" points to a stateful allocator, and that the allocator frees all
5153    * memory, arena-style, when it is destroyed.  In this case the allocator must
5154    * outlive the Environment.  Another possibility is that the allocation
5155    * function returns GC-able memory that is guaranteed to be GC-rooted for the
5156    * life of the Environment. */
5157   void SetAllocationFunction(upb_alloc_func* alloc, void* ud);
5158 
5159   template<class T>
5160   void SetAllocator(T* allocator) {
5161     SetAllocationFunction(allocator->GetAllocationFunction(), allocator);
5162   }
5163 
5164   /* Set a custom error reporting function. */
5165   void SetErrorFunction(upb_error_func* func, void* ud);
5166 
5167   /* Set the error reporting function to simply copy the status to the given
5168    * status and abort. */
5169   void ReportErrorsTo(Status* status);
5170 
5171   /* Returns true if all allocations and AddCleanup() calls have succeeded,
5172    * and no errors were reported with ReportError() (except ones that recovered
5173    * successfully). */
5174   bool ok() const;
5175 
5176   /* Functions for use by encoders/decoders. **********************************/
5177 
5178   /* Reports an error to this environment's callback, returning true if
5179    * the caller should try to recover. */
5180   bool ReportError(const Status* status);
5181 
5182   /* Allocate memory.  Uses the environment's allocation function.
5183    *
5184    * There is no need to free(). All memory will be freed automatically, but is
5185    * guaranteed to outlive the Environment. */
5186   void* Malloc(size_t size);
5187 
5188   /* Reallocate memory.  Preserves "oldsize" bytes from the existing buffer
5189    * Requires: oldsize <= existing_size.
5190    *
5191    * TODO(haberman): should we also enforce that oldsize <= size? */
5192   void* Realloc(void* ptr, size_t oldsize, size_t size);
5193 
5194   /* Add a cleanup function to run when the environment is destroyed.
5195    * Returns false on out-of-memory.
5196    *
5197    * The first call to AddCleanup() after SetAllocationFunction() is guaranteed
5198    * to return true -- this makes it possible to robustly set a cleanup handler
5199    * for a custom allocation function. */
5200   bool AddCleanup(upb_cleanup_func* func, void* ud);
5201 
5202   /* Total number of bytes that have been allocated.  It is undefined what
5203    * Realloc() does to this counter. */
5204   size_t BytesAllocated() const;
5205 
5206  private:
5207   UPB_DISALLOW_COPY_AND_ASSIGN(Environment)
5208 
5209 #else
5210 struct upb_env {
5211 #endif  /* __cplusplus */
5212 
5213   bool ok_;
5214   size_t bytes_allocated;
5215 
5216   /* Alloc function. */
5217   upb_alloc_func *alloc;
5218   void *alloc_ud;
5219 
5220   /* Error-reporting function. */
5221   upb_error_func *err;
5222   void *err_ud;
5223 
5224   /* Userdata for default alloc func. */
5225   void *default_alloc_ud;
5226 
5227   /* Cleanup entries.  Pointer to a cleanup_ent, defined in env.c */
5228   void *cleanup_head;
5229 
5230   /* For future expansion, since the size of this struct is exposed to users. */
5231   void *future1;
5232   void *future2;
5233 };
5234 
5235 UPB_BEGIN_EXTERN_C
5236 
5237 void upb_env_init(upb_env *e);
5238 void upb_env_uninit(upb_env *e);
5239 void upb_env_setallocfunc(upb_env *e, upb_alloc_func *func, void *ud);
5240 void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud);
5241 void upb_env_reporterrorsto(upb_env *e, upb_status *status);
5242 bool upb_env_ok(const upb_env *e);
5243 bool upb_env_reporterror(upb_env *e, const upb_status *status);
5244 void *upb_env_malloc(upb_env *e, size_t size);
5245 void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size);
5246 bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud);
5247 size_t upb_env_bytesallocated(const upb_env *e);
5248 
5249 UPB_END_EXTERN_C
5250 
5251 #ifdef __cplusplus
5252 
5253 /* An allocator that allocates from an initial memory region (likely the stack)
5254  * before falling back to another allocator. */
5255 class upb::SeededAllocator {
5256  public:
5257   SeededAllocator(void *mem, size_t len);
5258   ~SeededAllocator();
5259 
5260   /* Set a custom fallback memory allocation function for the allocator, to use
5261    * once the initial region runs out.
5262    *
5263    * May ONLY be called before GetAllocationFunction().  If this is not
5264    * called, the system realloc() will be the fallback allocator. */
5265   void SetFallbackAllocator(upb_alloc_func *alloc, void *ud);
5266 
5267   /* Gets the allocation function for this allocator. */
5268   upb_alloc_func* GetAllocationFunction();
5269 
5270  private:
5271   UPB_DISALLOW_COPY_AND_ASSIGN(SeededAllocator)
5272 
5273 #else
5274 struct upb_seededalloc {
5275 #endif  /* __cplusplus */
5276 
5277   /* Fallback alloc function.  */
5278   upb_alloc_func *alloc;
5279   upb_cleanup_func *alloc_cleanup;
5280   void *alloc_ud;
5281   bool need_cleanup;
5282   bool returned_allocfunc;
5283 
5284   /* Userdata for default alloc func. */
5285   void *default_alloc_ud;
5286 
5287   /* Pointers for the initial memory region. */
5288   char *mem_base;
5289   char *mem_ptr;
5290   char *mem_limit;
5291 
5292   /* For future expansion, since the size of this struct is exposed to users. */
5293   void *future1;
5294   void *future2;
5295 };
5296 
5297 UPB_BEGIN_EXTERN_C
5298 
5299 void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len);
5300 void upb_seededalloc_uninit(upb_seededalloc *a);
5301 void upb_seededalloc_setfallbackalloc(upb_seededalloc *a, upb_alloc_func *func,
5302                                       void *ud);
5303 upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a);
5304 
5305 UPB_END_EXTERN_C
5306 
5307 #ifdef __cplusplus
5308 
5309 namespace upb {
5310 
5311 inline Environment::Environment() {
5312   upb_env_init(this);
5313 }
5314 inline Environment::~Environment() {
5315   upb_env_uninit(this);
5316 }
5317 inline void Environment::SetAllocationFunction(upb_alloc_func *alloc,
5318                                                void *ud) {
5319   upb_env_setallocfunc(this, alloc, ud);
5320 }
5321 inline void Environment::SetErrorFunction(upb_error_func *func, void *ud) {
5322   upb_env_seterrorfunc(this, func, ud);
5323 }
5324 inline void Environment::ReportErrorsTo(Status* status) {
5325   upb_env_reporterrorsto(this, status);
5326 }
5327 inline bool Environment::ok() const {
5328   return upb_env_ok(this);
5329 }
5330 inline bool Environment::ReportError(const Status* status) {
5331   return upb_env_reporterror(this, status);
5332 }
5333 inline void *Environment::Malloc(size_t size) {
5334   return upb_env_malloc(this, size);
5335 }
5336 inline void *Environment::Realloc(void *ptr, size_t oldsize, size_t size) {
5337   return upb_env_realloc(this, ptr, oldsize, size);
5338 }
5339 inline bool Environment::AddCleanup(upb_cleanup_func *func, void *ud) {
5340   return upb_env_addcleanup(this, func, ud);
5341 }
5342 inline size_t Environment::BytesAllocated() const {
5343   return upb_env_bytesallocated(this);
5344 }
5345 
5346 inline SeededAllocator::SeededAllocator(void *mem, size_t len) {
5347   upb_seededalloc_init(this, mem, len);
5348 }
5349 inline SeededAllocator::~SeededAllocator() {
5350   upb_seededalloc_uninit(this);
5351 }
5352 inline void SeededAllocator::SetFallbackAllocator(upb_alloc_func *alloc,
5353                                                   void *ud) {
5354   upb_seededalloc_setfallbackalloc(this, alloc, ud);
5355 }
5356 inline upb_alloc_func *SeededAllocator::GetAllocationFunction() {
5357   return upb_seededalloc_getallocfunc(this);
5358 }
5359 
5360 }  /* namespace upb */
5361 
5362 #endif  /* __cplusplus */
5363 
5364 #endif  /* UPB_ENV_H_ */
5365 /*
5366 ** upb::Sink (upb_sink)
5367 ** upb::BytesSink (upb_bytessink)
5368 **
5369 ** A upb_sink is an object that binds a upb_handlers object to some runtime
5370 ** state.  It is the object that can actually receive data via the upb_handlers
5371 ** interface.
5372 **
5373 ** Unlike upb_def and upb_handlers, upb_sink is never frozen, immutable, or
5374 ** thread-safe.  You can create as many of them as you want, but each one may
5375 ** only be used in a single thread at a time.
5376 **
5377 ** If we compare with class-based OOP, a you can think of a upb_def as an
5378 ** abstract base class, a upb_handlers as a concrete derived class, and a
5379 ** upb_sink as an object (class instance).
5380 */
5381 
5382 #ifndef UPB_SINK_H
5383 #define UPB_SINK_H
5384 
5385 
5386 #ifdef __cplusplus
5387 namespace upb {
5388 class BufferSource;
5389 class BytesSink;
5390 class Sink;
5391 }
5392 #endif
5393 
5394 UPB_DECLARE_TYPE(upb::BufferSource, upb_bufsrc)
5395 UPB_DECLARE_TYPE(upb::BytesSink, upb_bytessink)
5396 UPB_DECLARE_TYPE(upb::Sink, upb_sink)
5397 
5398 #ifdef __cplusplus
5399 
5400 /* A upb::Sink is an object that binds a upb::Handlers object to some runtime
5401  * state.  It represents an endpoint to which data can be sent.
5402  *
5403  * TODO(haberman): right now all of these functions take selectors.  Should they
5404  * take selectorbase instead?
5405  *
5406  * ie. instead of calling:
5407  *   sink->StartString(FOO_FIELD_START_STRING, ...)
5408  * a selector base would let you say:
5409  *   sink->StartString(FOO_FIELD, ...)
5410  *
5411  * This would make call sites a little nicer and require emitting fewer selector
5412  * definitions in .h files.
5413  *
5414  * But the current scheme has the benefit that you can retrieve a function
5415  * pointer for any handler with handlers->GetHandler(selector), without having
5416  * to have a separate GetHandler() function for each handler type.  The JIT
5417  * compiler uses this.  To accommodate we'd have to expose a separate
5418  * GetHandler() for every handler type.
5419  *
5420  * Also to ponder: selectors right now are independent of a specific Handlers
5421  * instance.  In other words, they allocate a number to every possible handler
5422  * that *could* be registered, without knowing anything about what handlers
5423  * *are* registered.  That means that using selectors as table offsets prohibits
5424  * us from compacting the handler table at Freeze() time.  If the table is very
5425  * sparse, this could be wasteful.
5426  *
5427  * Having another selector-like thing that is specific to a Handlers instance
5428  * would allow this compacting, but then it would be impossible to write code
5429  * ahead-of-time that can be bound to any Handlers instance at runtime.  For
5430  * example, a .proto file parser written as straight C will not know what
5431  * Handlers it will be bound to, so when it calls sink->StartString() what
5432  * selector will it pass?  It needs a selector like we have today, that is
5433  * independent of any particular upb::Handlers.
5434  *
5435  * Is there a way then to allow Handlers table compaction? */
5436 class upb::Sink {
5437  public:
5438   /* Constructor with no initialization; must be Reset() before use. */
5439   Sink() {}
5440 
5441   /* Constructs a new sink for the given frozen handlers and closure.
5442    *
5443    * TODO: once the Handlers know the expected closure type, verify that T
5444    * matches it. */
5445   template <class T> Sink(const Handlers* handlers, T* closure);
5446 
5447   /* Resets the value of the sink. */
5448   template <class T> void Reset(const Handlers* handlers, T* closure);
5449 
5450   /* Returns the top-level object that is bound to this sink.
5451    *
5452    * TODO: once the Handlers know the expected closure type, verify that T
5453    * matches it. */
5454   template <class T> T* GetObject() const;
5455 
5456   /* Functions for pushing data into the sink.
5457    *
5458    * These return false if processing should stop (either due to error or just
5459    * to suspend).
5460    *
5461    * These may not be called from within one of the same sink's handlers (in
5462    * other words, handlers are not re-entrant). */
5463 
5464   /* Should be called at the start and end of every message; both the top-level
5465    * message and submessages.  This means that submessages should use the
5466    * following sequence:
5467    *   sink->StartSubMessage(startsubmsg_selector);
5468    *   sink->StartMessage();
5469    *   // ...
5470    *   sink->EndMessage(&status);
5471    *   sink->EndSubMessage(endsubmsg_selector); */
5472   bool StartMessage();
5473   bool EndMessage(Status* status);
5474 
5475   /* Putting of individual values.  These work for both repeated and
5476    * non-repeated fields, but for repeated fields you must wrap them in
5477    * calls to StartSequence()/EndSequence(). */
5478   bool PutInt32(Handlers::Selector s, int32_t val);
5479   bool PutInt64(Handlers::Selector s, int64_t val);
5480   bool PutUInt32(Handlers::Selector s, uint32_t val);
5481   bool PutUInt64(Handlers::Selector s, uint64_t val);
5482   bool PutFloat(Handlers::Selector s, float val);
5483   bool PutDouble(Handlers::Selector s, double val);
5484   bool PutBool(Handlers::Selector s, bool val);
5485 
5486   /* Putting of string/bytes values.  Each string can consist of zero or more
5487    * non-contiguous buffers of data.
5488    *
5489    * For StartString(), the function will write a sink for the string to "sub."
5490    * The sub-sink must be used for any/all PutStringBuffer() calls. */
5491   bool StartString(Handlers::Selector s, size_t size_hint, Sink* sub);
5492   size_t PutStringBuffer(Handlers::Selector s, const char *buf, size_t len,
5493                          const BufferHandle *handle);
5494   bool EndString(Handlers::Selector s);
5495 
5496   /* For submessage fields.
5497    *
5498    * For StartSubMessage(), the function will write a sink for the string to
5499    * "sub." The sub-sink must be used for any/all handlers called within the
5500    * submessage. */
5501   bool StartSubMessage(Handlers::Selector s, Sink* sub);
5502   bool EndSubMessage(Handlers::Selector s);
5503 
5504   /* For repeated fields of any type, the sequence of values must be wrapped in
5505    * these calls.
5506    *
5507    * For StartSequence(), the function will write a sink for the string to
5508    * "sub." The sub-sink must be used for any/all handlers called within the
5509    * sequence. */
5510   bool StartSequence(Handlers::Selector s, Sink* sub);
5511   bool EndSequence(Handlers::Selector s);
5512 
5513   /* Copy and assign specifically allowed.
5514    * We don't even bother making these members private because so many
5515    * functions need them and this is mainly just a dumb data container anyway.
5516    */
5517 #else
5518 struct upb_sink {
5519 #endif
5520   const upb_handlers *handlers;
5521   void *closure;
5522 };
5523 
5524 #ifdef __cplusplus
5525 class upb::BytesSink {
5526  public:
5527   BytesSink() {}
5528 
5529   /* Constructs a new sink for the given frozen handlers and closure.
5530    *
5531    * TODO(haberman): once the Handlers know the expected closure type, verify
5532    * that T matches it. */
5533   template <class T> BytesSink(const BytesHandler* handler, T* closure);
5534 
5535   /* Resets the value of the sink. */
5536   template <class T> void Reset(const BytesHandler* handler, T* closure);
5537 
5538   bool Start(size_t size_hint, void **subc);
5539   size_t PutBuffer(void *subc, const char *buf, size_t len,
5540                    const BufferHandle *handle);
5541   bool End();
5542 #else
5543 struct upb_bytessink {
5544 #endif
5545   const upb_byteshandler *handler;
5546   void *closure;
5547 };
5548 
5549 #ifdef __cplusplus
5550 
5551 /* A class for pushing a flat buffer of data to a BytesSink.
5552  * You can construct an instance of this to get a resumable source,
5553  * or just call the static PutBuffer() to do a non-resumable push all in one
5554  * go. */
5555 class upb::BufferSource {
5556  public:
5557   BufferSource();
5558   BufferSource(const char* buf, size_t len, BytesSink* sink);
5559 
5560   /* Returns true if the entire buffer was pushed successfully.  Otherwise the
5561    * next call to PutNext() will resume where the previous one left off.
5562    * TODO(haberman): implement this. */
5563   bool PutNext();
5564 
5565   /* A static version; with this version is it not possible to resume in the
5566    * case of failure or a partially-consumed buffer. */
5567   static bool PutBuffer(const char* buf, size_t len, BytesSink* sink);
5568 
5569   template <class T> static bool PutBuffer(const T& str, BytesSink* sink) {
5570     return PutBuffer(str.c_str(), str.size(), sink);
5571   }
5572 #else
5573 struct upb_bufsrc {
5574   char dummy;
5575 #endif
5576 };
5577 
5578 UPB_BEGIN_EXTERN_C
5579 
5580 /* Inline definitions. */
5581 
5582 UPB_INLINE void upb_bytessink_reset(upb_bytessink *s, const upb_byteshandler *h,
5583                                     void *closure) {
5584   s->handler = h;
5585   s->closure = closure;
5586 }
5587 
5588 UPB_INLINE bool upb_bytessink_start(upb_bytessink *s, size_t size_hint,
5589                                     void **subc) {
5590   typedef upb_startstr_handlerfunc func;
5591   func *start;
5592   *subc = s->closure;
5593   if (!s->handler) return true;
5594   start = (func *)s->handler->table[UPB_STARTSTR_SELECTOR].func;
5595 
5596   if (!start) return true;
5597   *subc = start(s->closure, upb_handlerattr_handlerdata(
5598                                 &s->handler->table[UPB_STARTSTR_SELECTOR].attr),
5599                 size_hint);
5600   return *subc != NULL;
5601 }
5602 
5603 UPB_INLINE size_t upb_bytessink_putbuf(upb_bytessink *s, void *subc,
5604                                        const char *buf, size_t size,
5605                                        const upb_bufhandle* handle) {
5606   typedef upb_string_handlerfunc func;
5607   func *putbuf;
5608   if (!s->handler) return true;
5609   putbuf = (func *)s->handler->table[UPB_STRING_SELECTOR].func;
5610 
5611   if (!putbuf) return true;
5612   return putbuf(subc, upb_handlerattr_handlerdata(
5613                           &s->handler->table[UPB_STRING_SELECTOR].attr),
5614                 buf, size, handle);
5615 }
5616 
5617 UPB_INLINE bool upb_bytessink_end(upb_bytessink *s) {
5618   typedef upb_endfield_handlerfunc func;
5619   func *end;
5620   if (!s->handler) return true;
5621   end = (func *)s->handler->table[UPB_ENDSTR_SELECTOR].func;
5622 
5623   if (!end) return true;
5624   return end(s->closure,
5625              upb_handlerattr_handlerdata(
5626                  &s->handler->table[UPB_ENDSTR_SELECTOR].attr));
5627 }
5628 
5629 UPB_INLINE bool upb_bufsrc_putbuf(const char *buf, size_t len,
5630                                   upb_bytessink *sink) {
5631   void *subc;
5632   bool ret;
5633   upb_bufhandle handle;
5634   upb_bufhandle_init(&handle);
5635   upb_bufhandle_setbuf(&handle, buf, 0);
5636   ret = upb_bytessink_start(sink, len, &subc);
5637   if (ret && len != 0) {
5638     ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
5639   }
5640   if (ret) {
5641     ret = upb_bytessink_end(sink);
5642   }
5643   upb_bufhandle_uninit(&handle);
5644   return ret;
5645 }
5646 
5647 #define PUTVAL(type, ctype)                                                    \
5648   UPB_INLINE bool upb_sink_put##type(upb_sink *s, upb_selector_t sel,          \
5649                                      ctype val) {                              \
5650     typedef upb_##type##_handlerfunc functype;                                 \
5651     functype *func;                                                            \
5652     const void *hd;                                                            \
5653     if (!s->handlers) return true;                                             \
5654     func = (functype *)upb_handlers_gethandler(s->handlers, sel);              \
5655     if (!func) return true;                                                    \
5656     hd = upb_handlers_gethandlerdata(s->handlers, sel);                        \
5657     return func(s->closure, hd, val);                                          \
5658   }
5659 
5660 PUTVAL(int32,  int32_t)
5661 PUTVAL(int64,  int64_t)
5662 PUTVAL(uint32, uint32_t)
5663 PUTVAL(uint64, uint64_t)
5664 PUTVAL(float,  float)
5665 PUTVAL(double, double)
5666 PUTVAL(bool,   bool)
5667 #undef PUTVAL
5668 
5669 UPB_INLINE void upb_sink_reset(upb_sink *s, const upb_handlers *h, void *c) {
5670   s->handlers = h;
5671   s->closure = c;
5672 }
5673 
5674 UPB_INLINE size_t upb_sink_putstring(upb_sink *s, upb_selector_t sel,
5675                                      const char *buf, size_t n,
5676                                      const upb_bufhandle *handle) {
5677   typedef upb_string_handlerfunc func;
5678   func *handler;
5679   const void *hd;
5680   if (!s->handlers) return n;
5681   handler = (func *)upb_handlers_gethandler(s->handlers, sel);
5682 
5683   if (!handler) return n;
5684   hd = upb_handlers_gethandlerdata(s->handlers, sel);
5685   return handler(s->closure, hd, buf, n, handle);
5686 }
5687 
5688 UPB_INLINE bool upb_sink_startmsg(upb_sink *s) {
5689   typedef upb_startmsg_handlerfunc func;
5690   func *startmsg;
5691   const void *hd;
5692   if (!s->handlers) return true;
5693   startmsg = (func*)upb_handlers_gethandler(s->handlers, UPB_STARTMSG_SELECTOR);
5694 
5695   if (!startmsg) return true;
5696   hd = upb_handlers_gethandlerdata(s->handlers, UPB_STARTMSG_SELECTOR);
5697   return startmsg(s->closure, hd);
5698 }
5699 
5700 UPB_INLINE bool upb_sink_endmsg(upb_sink *s, upb_status *status) {
5701   typedef upb_endmsg_handlerfunc func;
5702   func *endmsg;
5703   const void *hd;
5704   if (!s->handlers) return true;
5705   endmsg = (func *)upb_handlers_gethandler(s->handlers, UPB_ENDMSG_SELECTOR);
5706 
5707   if (!endmsg) return true;
5708   hd = upb_handlers_gethandlerdata(s->handlers, UPB_ENDMSG_SELECTOR);
5709   return endmsg(s->closure, hd, status);
5710 }
5711 
5712 UPB_INLINE bool upb_sink_startseq(upb_sink *s, upb_selector_t sel,
5713                                   upb_sink *sub) {
5714   typedef upb_startfield_handlerfunc func;
5715   func *startseq;
5716   const void *hd;
5717   sub->closure = s->closure;
5718   sub->handlers = s->handlers;
5719   if (!s->handlers) return true;
5720   startseq = (func*)upb_handlers_gethandler(s->handlers, sel);
5721 
5722   if (!startseq) return true;
5723   hd = upb_handlers_gethandlerdata(s->handlers, sel);
5724   sub->closure = startseq(s->closure, hd);
5725   return sub->closure ? true : false;
5726 }
5727 
5728 UPB_INLINE bool upb_sink_endseq(upb_sink *s, upb_selector_t sel) {
5729   typedef upb_endfield_handlerfunc func;
5730   func *endseq;
5731   const void *hd;
5732   if (!s->handlers) return true;
5733   endseq = (func*)upb_handlers_gethandler(s->handlers, sel);
5734 
5735   if (!endseq) return true;
5736   hd = upb_handlers_gethandlerdata(s->handlers, sel);
5737   return endseq(s->closure, hd);
5738 }
5739 
5740 UPB_INLINE bool upb_sink_startstr(upb_sink *s, upb_selector_t sel,
5741                                   size_t size_hint, upb_sink *sub) {
5742   typedef upb_startstr_handlerfunc func;
5743   func *startstr;
5744   const void *hd;
5745   sub->closure = s->closure;
5746   sub->handlers = s->handlers;
5747   if (!s->handlers) return true;
5748   startstr = (func*)upb_handlers_gethandler(s->handlers, sel);
5749 
5750   if (!startstr) return true;
5751   hd = upb_handlers_gethandlerdata(s->handlers, sel);
5752   sub->closure = startstr(s->closure, hd, size_hint);
5753   return sub->closure ? true : false;
5754 }
5755 
5756 UPB_INLINE bool upb_sink_endstr(upb_sink *s, upb_selector_t sel) {
5757   typedef upb_endfield_handlerfunc func;
5758   func *endstr;
5759   const void *hd;
5760   if (!s->handlers) return true;
5761   endstr = (func*)upb_handlers_gethandler(s->handlers, sel);
5762 
5763   if (!endstr) return true;
5764   hd = upb_handlers_gethandlerdata(s->handlers, sel);
5765   return endstr(s->closure, hd);
5766 }
5767 
5768 UPB_INLINE bool upb_sink_startsubmsg(upb_sink *s, upb_selector_t sel,
5769                                      upb_sink *sub) {
5770   typedef upb_startfield_handlerfunc func;
5771   func *startsubmsg;
5772   const void *hd;
5773   sub->closure = s->closure;
5774   if (!s->handlers) {
5775     sub->handlers = NULL;
5776     return true;
5777   }
5778   sub->handlers = upb_handlers_getsubhandlers_sel(s->handlers, sel);
5779   startsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel);
5780 
5781   if (!startsubmsg) return true;
5782   hd = upb_handlers_gethandlerdata(s->handlers, sel);
5783   sub->closure = startsubmsg(s->closure, hd);
5784   return sub->closure ? true : false;
5785 }
5786 
5787 UPB_INLINE bool upb_sink_endsubmsg(upb_sink *s, upb_selector_t sel) {
5788   typedef upb_endfield_handlerfunc func;
5789   func *endsubmsg;
5790   const void *hd;
5791   if (!s->handlers) return true;
5792   endsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel);
5793 
5794   if (!endsubmsg) return s->closure;
5795   hd = upb_handlers_gethandlerdata(s->handlers, sel);
5796   return endsubmsg(s->closure, hd);
5797 }
5798 
5799 UPB_END_EXTERN_C
5800 
5801 #ifdef __cplusplus
5802 
5803 namespace upb {
5804 
5805 template <class T> Sink::Sink(const Handlers* handlers, T* closure) {
5806   upb_sink_reset(this, handlers, closure);
5807 }
5808 template <class T>
5809 inline void Sink::Reset(const Handlers* handlers, T* closure) {
5810   upb_sink_reset(this, handlers, closure);
5811 }
5812 inline bool Sink::StartMessage() {
5813   return upb_sink_startmsg(this);
5814 }
5815 inline bool Sink::EndMessage(Status* status) {
5816   return upb_sink_endmsg(this, status);
5817 }
5818 inline bool Sink::PutInt32(Handlers::Selector sel, int32_t val) {
5819   return upb_sink_putint32(this, sel, val);
5820 }
5821 inline bool Sink::PutInt64(Handlers::Selector sel, int64_t val) {
5822   return upb_sink_putint64(this, sel, val);
5823 }
5824 inline bool Sink::PutUInt32(Handlers::Selector sel, uint32_t val) {
5825   return upb_sink_putuint32(this, sel, val);
5826 }
5827 inline bool Sink::PutUInt64(Handlers::Selector sel, uint64_t val) {
5828   return upb_sink_putuint64(this, sel, val);
5829 }
5830 inline bool Sink::PutFloat(Handlers::Selector sel, float val) {
5831   return upb_sink_putfloat(this, sel, val);
5832 }
5833 inline bool Sink::PutDouble(Handlers::Selector sel, double val) {
5834   return upb_sink_putdouble(this, sel, val);
5835 }
5836 inline bool Sink::PutBool(Handlers::Selector sel, bool val) {
5837   return upb_sink_putbool(this, sel, val);
5838 }
5839 inline bool Sink::StartString(Handlers::Selector sel, size_t size_hint,
5840                               Sink *sub) {
5841   return upb_sink_startstr(this, sel, size_hint, sub);
5842 }
5843 inline size_t Sink::PutStringBuffer(Handlers::Selector sel, const char *buf,
5844                                     size_t len, const BufferHandle* handle) {
5845   return upb_sink_putstring(this, sel, buf, len, handle);
5846 }
5847 inline bool Sink::EndString(Handlers::Selector sel) {
5848   return upb_sink_endstr(this, sel);
5849 }
5850 inline bool Sink::StartSubMessage(Handlers::Selector sel, Sink* sub) {
5851   return upb_sink_startsubmsg(this, sel, sub);
5852 }
5853 inline bool Sink::EndSubMessage(Handlers::Selector sel) {
5854   return upb_sink_endsubmsg(this, sel);
5855 }
5856 inline bool Sink::StartSequence(Handlers::Selector sel, Sink* sub) {
5857   return upb_sink_startseq(this, sel, sub);
5858 }
5859 inline bool Sink::EndSequence(Handlers::Selector sel) {
5860   return upb_sink_endseq(this, sel);
5861 }
5862 
5863 template <class T>
5864 BytesSink::BytesSink(const BytesHandler* handler, T* closure) {
5865   Reset(handler, closure);
5866 }
5867 
5868 template <class T>
5869 void BytesSink::Reset(const BytesHandler *handler, T *closure) {
5870   upb_bytessink_reset(this, handler, closure);
5871 }
5872 inline bool BytesSink::Start(size_t size_hint, void **subc) {
5873   return upb_bytessink_start(this, size_hint, subc);
5874 }
5875 inline size_t BytesSink::PutBuffer(void *subc, const char *buf, size_t len,
5876                                    const BufferHandle *handle) {
5877   return upb_bytessink_putbuf(this, subc, buf, len, handle);
5878 }
5879 inline bool BytesSink::End() {
5880   return upb_bytessink_end(this);
5881 }
5882 
5883 inline bool BufferSource::PutBuffer(const char *buf, size_t len,
5884                                     BytesSink *sink) {
5885   return upb_bufsrc_putbuf(buf, len, sink);
5886 }
5887 
5888 }  /* namespace upb */
5889 #endif
5890 
5891 #endif
5892 /*
5893 ** For handlers that do very tiny, very simple operations, the function call
5894 ** overhead of calling a handler can be significant.  This file allows the
5895 ** user to define handlers that do something very simple like store the value
5896 ** to memory and/or set a hasbit.  JIT compilers can then special-case these
5897 ** handlers and emit specialized code for them instead of actually calling the
5898 ** handler.
5899 **
5900 ** The functionality is very simple/limited right now but may expand to be able
5901 ** to call another function.
5902 */
5903 
5904 #ifndef UPB_SHIM_H
5905 #define UPB_SHIM_H
5906 
5907 
5908 typedef struct {
5909   size_t offset;
5910   int32_t hasbit;
5911 } upb_shim_data;
5912 
5913 #ifdef __cplusplus
5914 
5915 namespace upb {
5916 
5917 struct Shim {
5918   typedef upb_shim_data Data;
5919 
5920   /* Sets a handler for the given field that writes the value to the given
5921    * offset and, if hasbit >= 0, sets a bit at the given bit offset.  Returns
5922    * true if the handler was set successfully. */
5923   static bool Set(Handlers *h, const FieldDef *f, size_t ofs, int32_t hasbit);
5924 
5925   /* If this handler is a shim, returns the corresponding upb::Shim::Data and
5926    * stores the type in "type".  Otherwise returns NULL. */
5927   static const Data* GetData(const Handlers* h, Handlers::Selector s,
5928                              FieldDef::Type* type);
5929 };
5930 
5931 }  /* namespace upb */
5932 
5933 #endif
5934 
5935 UPB_BEGIN_EXTERN_C
5936 
5937 /* C API. */
5938 bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
5939                   int32_t hasbit);
5940 const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
5941                                       upb_fieldtype_t *type);
5942 
5943 UPB_END_EXTERN_C
5944 
5945 #ifdef __cplusplus
5946 /* C++ Wrappers. */
5947 namespace upb {
5948 inline bool Shim::Set(Handlers* h, const FieldDef* f, size_t ofs,
5949                       int32_t hasbit) {
5950   return upb_shim_set(h, f, ofs, hasbit);
5951 }
5952 inline const Shim::Data* Shim::GetData(const Handlers* h, Handlers::Selector s,
5953                                        FieldDef::Type* type) {
5954   return upb_shim_getdata(h, s, type);
5955 }
5956 }  /* namespace upb */
5957 #endif
5958 
5959 #endif  /* UPB_SHIM_H */
5960 /*
5961 ** upb::SymbolTable (upb_symtab)
5962 **
5963 ** A symtab (symbol table) stores a name->def map of upb_defs.  Clients could
5964 ** always create such tables themselves, but upb_symtab has logic for resolving
5965 ** symbolic references, and in particular, for keeping a whole set of consistent
5966 ** defs when replacing some subset of those defs.  This logic is nontrivial.
5967 **
5968 ** This is a mixed C/C++ interface that offers a full API to both languages.
5969 ** See the top-level README for more information.
5970 */
5971 
5972 #ifndef UPB_SYMTAB_H_
5973 #define UPB_SYMTAB_H_
5974 
5975 
5976 #ifdef __cplusplus
5977 #include <vector>
5978 namespace upb { class SymbolTable; }
5979 #endif
5980 
5981 UPB_DECLARE_DERIVED_TYPE(upb::SymbolTable, upb::RefCounted,
5982                          upb_symtab, upb_refcounted)
5983 
5984 typedef struct {
5985  UPB_PRIVATE_FOR_CPP
5986   upb_strtable_iter iter;
5987   upb_deftype_t type;
5988 } upb_symtab_iter;
5989 
5990 #ifdef __cplusplus
5991 
5992 /* Non-const methods in upb::SymbolTable are NOT thread-safe. */
5993 class upb::SymbolTable {
5994  public:
5995   /* Returns a new symbol table with a single ref owned by "owner."
5996    * Returns NULL if memory allocation failed. */
5997   static reffed_ptr<SymbolTable> New();
5998 
5999   /* Include RefCounted base methods. */
6000   UPB_REFCOUNTED_CPPMETHODS
6001 
6002   /* For all lookup functions, the returned pointer is not owned by the
6003    * caller; it may be invalidated by any non-const call or unref of the
6004    * SymbolTable!  To protect against this, take a ref if desired. */
6005 
6006   /* Freezes the symbol table: prevents further modification of it.
6007    * After the Freeze() operation is successful, the SymbolTable must only be
6008    * accessed via a const pointer.
6009    *
6010    * Unlike with upb::MessageDef/upb::EnumDef/etc, freezing a SymbolTable is not
6011    * a necessary step in using a SymbolTable.  If you have no need for it to be
6012    * immutable, there is no need to freeze it ever.  However sometimes it is
6013    * useful, and SymbolTables that are statically compiled into the binary are
6014    * always frozen by nature. */
6015   void Freeze();
6016 
6017   /* Resolves the given symbol using the rules described in descriptor.proto,
6018    * namely:
6019    *
6020    *    If the name starts with a '.', it is fully-qualified.  Otherwise,
6021    *    C++-like scoping rules are used to find the type (i.e. first the nested
6022    *    types within this message are searched, then within the parent, on up
6023    *    to the root namespace).
6024    *
6025    * If not found, returns NULL. */
6026   const Def* Resolve(const char* base, const char* sym) const;
6027 
6028   /* Finds an entry in the symbol table with this exact name.  If not found,
6029    * returns NULL. */
6030   const Def* Lookup(const char *sym) const;
6031   const MessageDef* LookupMessage(const char *sym) const;
6032   const EnumDef* LookupEnum(const char *sym) const;
6033 
6034   /* TODO: introduce a C++ iterator, but make it nice and templated so that if
6035    * you ask for an iterator of MessageDef the iterated elements are strongly
6036    * typed as MessageDef*. */
6037 
6038   /* Adds the given mutable defs to the symtab, resolving all symbols
6039    * (including enum default values) and finalizing the defs.  Only one def per
6040    * name may be in the list, but defs can replace existing defs in the symtab.
6041    * All defs must have a name -- anonymous defs are not allowed.  Anonymous
6042    * defs can still be frozen by calling upb_def_freeze() directly.
6043    *
6044    * Any existing defs that can reach defs that are being replaced will
6045    * themselves be replaced also, so that the resulting set of defs is fully
6046    * consistent.
6047    *
6048    * This logic implemented in this method is a convenience; ultimately it
6049    * calls some combination of upb_fielddef_setsubdef(), upb_def_dup(), and
6050    * upb_freeze(), any of which the client could call themself.  However, since
6051    * the logic for doing so is nontrivial, we provide it here.
6052    *
6053    * The entire operation either succeeds or fails.  If the operation fails,
6054    * the symtab is unchanged, false is returned, and status indicates the
6055    * error.  The caller passes a ref on all defs to the symtab (even if the
6056    * operation fails).
6057    *
6058    * TODO(haberman): currently failure will leave the symtab unchanged, but may
6059    * leave the defs themselves partially resolved.  Does this matter?  If so we
6060    * could do a prepass that ensures that all symbols are resolvable and bail
6061    * if not, so we don't mutate anything until we know the operation will
6062    * succeed.
6063    *
6064    * TODO(haberman): since the defs must be mutable, refining a frozen def
6065    * requires making mutable copies of the entire tree.  This is wasteful if
6066    * only a few messages are changing.  We may want to add a way of adding a
6067    * tree of frozen defs to the symtab (perhaps an alternate constructor where
6068    * you pass the root of the tree?) */
6069   bool Add(Def*const* defs, int n, void* ref_donor, upb_status* status);
6070 
6071   bool Add(const std::vector<Def*>& defs, void *owner, Status* status) {
6072     return Add((Def*const*)&defs[0], defs.size(), owner, status);
6073   }
6074 
6075  private:
6076   UPB_DISALLOW_POD_OPS(SymbolTable, upb::SymbolTable)
6077 };
6078 
6079 #endif  /* __cplusplus */
6080 
6081 UPB_BEGIN_EXTERN_C
6082 
6083 /* Native C API. */
6084 
6085 /* Include refcounted methods like upb_symtab_ref(). */
6086 UPB_REFCOUNTED_CMETHODS(upb_symtab, upb_symtab_upcast)
6087 
6088 upb_symtab *upb_symtab_new(const void *owner);
6089 void upb_symtab_freeze(upb_symtab *s);
6090 const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
6091                                   const char *sym);
6092 const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym);
6093 const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
6094 const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym);
6095 bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
6096                     upb_status *status);
6097 
6098 /* upb_symtab_iter i;
6099  * for(upb_symtab_begin(&i, s, type); !upb_symtab_done(&i);
6100  *     upb_symtab_next(&i)) {
6101  *   const upb_def *def = upb_symtab_iter_def(&i);
6102  *    // ...
6103  * }
6104  *
6105  * For C we don't have separate iterators for const and non-const.
6106  * It is the caller's responsibility to cast the upb_fielddef* to
6107  * const if the upb_msgdef* is const. */
6108 void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
6109                       upb_deftype_t type);
6110 void upb_symtab_next(upb_symtab_iter *iter);
6111 bool upb_symtab_done(const upb_symtab_iter *iter);
6112 const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter);
6113 
6114 UPB_END_EXTERN_C
6115 
6116 #ifdef __cplusplus
6117 /* C++ inline wrappers. */
6118 namespace upb {
6119 inline reffed_ptr<SymbolTable> SymbolTable::New() {
6120   upb_symtab *s = upb_symtab_new(&s);
6121   return reffed_ptr<SymbolTable>(s, &s);
6122 }
6123 
6124 inline void SymbolTable::Freeze() {
6125   return upb_symtab_freeze(this);
6126 }
6127 inline const Def *SymbolTable::Resolve(const char *base,
6128                                        const char *sym) const {
6129   return upb_symtab_resolve(this, base, sym);
6130 }
6131 inline const Def* SymbolTable::Lookup(const char *sym) const {
6132   return upb_symtab_lookup(this, sym);
6133 }
6134 inline const MessageDef *SymbolTable::LookupMessage(const char *sym) const {
6135   return upb_symtab_lookupmsg(this, sym);
6136 }
6137 inline bool SymbolTable::Add(
6138     Def*const* defs, int n, void* ref_donor, upb_status* status) {
6139   return upb_symtab_add(this, (upb_def*const*)defs, n, ref_donor, status);
6140 }
6141 }  /* namespace upb */
6142 #endif
6143 
6144 #endif  /* UPB_SYMTAB_H_ */
6145 /*
6146 ** upb::descriptor::Reader (upb_descreader)
6147 **
6148 ** Provides a way of building upb::Defs from data in descriptor.proto format.
6149 */
6150 
6151 #ifndef UPB_DESCRIPTOR_H
6152 #define UPB_DESCRIPTOR_H
6153 
6154 
6155 #ifdef __cplusplus
6156 namespace upb {
6157 namespace descriptor {
6158 class Reader;
6159 }  /* namespace descriptor */
6160 }  /* namespace upb */
6161 #endif
6162 
6163 UPB_DECLARE_TYPE(upb::descriptor::Reader, upb_descreader)
6164 
6165 #ifdef __cplusplus
6166 
6167 /* Class that receives descriptor data according to the descriptor.proto schema
6168  * and use it to build upb::Defs corresponding to that schema. */
6169 class upb::descriptor::Reader {
6170  public:
6171   /* These handlers must have come from NewHandlers() and must outlive the
6172    * Reader.
6173    *
6174    * TODO: generate the handlers statically (like we do with the
6175    * descriptor.proto defs) so that there is no need to pass this parameter (or
6176    * to build/memory-manage the handlers at runtime at all).  Unfortunately this
6177    * is a bit tricky to implement for Handlers, but necessary to simplify this
6178    * interface. */
6179   static Reader* Create(Environment* env, const Handlers* handlers);
6180 
6181   /* The reader's input; this is where descriptor.proto data should be sent. */
6182   Sink* input();
6183 
6184   /* Returns an array of all defs that have been parsed, and transfers ownership
6185    * of them to "owner".  The number of defs is stored in *n.  Ownership of the
6186    * returned array is retained and is invalidated by any other call into
6187    * Reader.
6188    *
6189    * These defs are not frozen or resolved; they are ready to be added to a
6190    * symtab. */
6191   upb::Def** GetDefs(void* owner, int* n);
6192 
6193   /* Builds and returns handlers for the reader, owned by "owner." */
6194   static Handlers* NewHandlers(const void* owner);
6195 
6196  private:
6197   UPB_DISALLOW_POD_OPS(Reader, upb::descriptor::Reader)
6198 };
6199 
6200 #endif
6201 
6202 UPB_BEGIN_EXTERN_C
6203 
6204 /* C API. */
6205 upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h);
6206 upb_sink *upb_descreader_input(upb_descreader *r);
6207 upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n);
6208 const upb_handlers *upb_descreader_newhandlers(const void *owner);
6209 
6210 UPB_END_EXTERN_C
6211 
6212 #ifdef __cplusplus
6213 /* C++ implementation details. ************************************************/
6214 namespace upb {
6215 namespace descriptor {
6216 inline Reader* Reader::Create(Environment* e, const Handlers *h) {
6217   return upb_descreader_create(e, h);
6218 }
6219 inline Sink* Reader::input() { return upb_descreader_input(this); }
6220 inline upb::Def** Reader::GetDefs(void* owner, int* n) {
6221   return upb_descreader_getdefs(this, owner, n);
6222 }
6223 }  /* namespace descriptor */
6224 }  /* namespace upb */
6225 #endif
6226 
6227 #endif  /* UPB_DESCRIPTOR_H */
6228 /* This file contains accessors for a set of compiled-in defs.
6229  * Note that unlike Google's protobuf, it does *not* define
6230  * generated classes or any other kind of data structure for
6231  * actually storing protobufs.  It only contains *defs* which
6232  * let you reflect over a protobuf *schema*.
6233  */
6234 /* This file was generated by upbc (the upb compiler).
6235  * Do not edit -- your changes will be discarded when the file is
6236  * regenerated. */
6237 
6238 #ifndef GOOGLE_PROTOBUF_DESCRIPTOR_UPB_H_
6239 #define GOOGLE_PROTOBUF_DESCRIPTOR_UPB_H_
6240 
6241 
6242 #ifdef __cplusplus
6243 UPB_BEGIN_EXTERN_C
6244 #endif
6245 
6246 /* Enums */
6247 
6248 typedef enum {
6249   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_LABEL_OPTIONAL = 1,
6250   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_LABEL_REQUIRED = 2,
6251   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_LABEL_REPEATED = 3
6252 } google_protobuf_FieldDescriptorProto_Label;
6253 
6254 typedef enum {
6255   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_DOUBLE = 1,
6256   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_FLOAT = 2,
6257   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_INT64 = 3,
6258   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_UINT64 = 4,
6259   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_INT32 = 5,
6260   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_FIXED64 = 6,
6261   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_FIXED32 = 7,
6262   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_BOOL = 8,
6263   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_STRING = 9,
6264   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_GROUP = 10,
6265   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_MESSAGE = 11,
6266   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_BYTES = 12,
6267   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_UINT32 = 13,
6268   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_ENUM = 14,
6269   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_SFIXED32 = 15,
6270   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_SFIXED64 = 16,
6271   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_SINT32 = 17,
6272   GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_SINT64 = 18
6273 } google_protobuf_FieldDescriptorProto_Type;
6274 
6275 typedef enum {
6276   GOOGLE_PROTOBUF_FIELDOPTIONS_STRING = 0,
6277   GOOGLE_PROTOBUF_FIELDOPTIONS_CORD = 1,
6278   GOOGLE_PROTOBUF_FIELDOPTIONS_STRING_PIECE = 2
6279 } google_protobuf_FieldOptions_CType;
6280 
6281 typedef enum {
6282   GOOGLE_PROTOBUF_FILEOPTIONS_SPEED = 1,
6283   GOOGLE_PROTOBUF_FILEOPTIONS_CODE_SIZE = 2,
6284   GOOGLE_PROTOBUF_FILEOPTIONS_LITE_RUNTIME = 3
6285 } google_protobuf_FileOptions_OptimizeMode;
6286 
6287 /* Selectors */
6288 
6289 /* google.protobuf.DescriptorProto */
6290 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_STARTSUBMSG 2
6291 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_STARTSUBMSG 3
6292 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_STARTSUBMSG 4
6293 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_STARTSUBMSG 5
6294 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_STARTSUBMSG 6
6295 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_OPTIONS_STARTSUBMSG 7
6296 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_STARTSEQ 8
6297 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_ENDSEQ 9
6298 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_ENDSUBMSG 10
6299 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_STARTSEQ 11
6300 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_ENDSEQ 12
6301 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_ENDSUBMSG 13
6302 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_STARTSEQ 14
6303 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_ENDSEQ 15
6304 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_ENDSUBMSG 16
6305 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_STARTSEQ 17
6306 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_ENDSEQ 18
6307 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_ENDSUBMSG 19
6308 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_STARTSEQ 20
6309 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_ENDSEQ 21
6310 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_ENDSUBMSG 22
6311 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_OPTIONS_ENDSUBMSG 23
6312 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NAME_STRING 24
6313 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NAME_STARTSTR 25
6314 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NAME_ENDSTR 26
6315 
6316 /* google.protobuf.DescriptorProto.ExtensionRange */
6317 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSIONRANGE_START_INT32 2
6318 #define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSIONRANGE_END_INT32 3
6319 
6320 /* google.protobuf.EnumDescriptorProto */
6321 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_STARTSUBMSG 2
6322 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 3
6323 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_STARTSEQ 4
6324 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_ENDSEQ 5
6325 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_ENDSUBMSG 6
6326 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 7
6327 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_NAME_STRING 8
6328 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_NAME_STARTSTR 9
6329 #define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_NAME_ENDSTR 10
6330 
6331 /* google.protobuf.EnumOptions */
6332 #define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
6333 #define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
6334 #define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
6335 #define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
6336 #define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_ALLOW_ALIAS_BOOL 6
6337 
6338 /* google.protobuf.EnumValueDescriptorProto */
6339 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 2
6340 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 3
6341 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NAME_STRING 4
6342 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NAME_STARTSTR 5
6343 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NAME_ENDSTR 6
6344 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NUMBER_INT32 7
6345 
6346 /* google.protobuf.EnumValueOptions */
6347 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
6348 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
6349 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
6350 #define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
6351 
6352 /* google.protobuf.FieldDescriptorProto */
6353 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 2
6354 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 3
6355 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NAME_STRING 4
6356 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NAME_STARTSTR 5
6357 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NAME_ENDSTR 6
6358 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_EXTENDEE_STRING 7
6359 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_EXTENDEE_STARTSTR 8
6360 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_EXTENDEE_ENDSTR 9
6361 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NUMBER_INT32 10
6362 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_LABEL_INT32 11
6363 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_INT32 12
6364 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_NAME_STRING 13
6365 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_NAME_STARTSTR 14
6366 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_NAME_ENDSTR 15
6367 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_DEFAULT_VALUE_STRING 16
6368 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_DEFAULT_VALUE_STARTSTR 17
6369 #define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_DEFAULT_VALUE_ENDSTR 18
6370 
6371 /* google.protobuf.FieldOptions */
6372 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
6373 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
6374 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
6375 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
6376 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_CTYPE_INT32 6
6377 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_PACKED_BOOL 7
6378 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_DEPRECATED_BOOL 8
6379 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_LAZY_BOOL 9
6380 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_EXPERIMENTAL_MAP_KEY_STRING 10
6381 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_EXPERIMENTAL_MAP_KEY_STARTSTR 11
6382 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_EXPERIMENTAL_MAP_KEY_ENDSTR 12
6383 #define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_WEAK_BOOL 13
6384 
6385 /* google.protobuf.FileDescriptorProto */
6386 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_STARTSUBMSG 2
6387 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_STARTSUBMSG 3
6388 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_STARTSUBMSG 4
6389 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_STARTSUBMSG 5
6390 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 6
6391 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SOURCE_CODE_INFO_STARTSUBMSG 7
6392 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_STARTSEQ 8
6393 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_ENDSEQ 9
6394 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_ENDSUBMSG 10
6395 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_STARTSEQ 11
6396 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_ENDSEQ 12
6397 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_ENDSUBMSG 13
6398 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_STARTSEQ 14
6399 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_ENDSEQ 15
6400 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_ENDSUBMSG 16
6401 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_STARTSEQ 17
6402 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_ENDSEQ 18
6403 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_ENDSUBMSG 19
6404 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 20
6405 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SOURCE_CODE_INFO_ENDSUBMSG 21
6406 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_NAME_STRING 22
6407 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_NAME_STARTSTR 23
6408 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_NAME_ENDSTR 24
6409 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PACKAGE_STRING 25
6410 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PACKAGE_STARTSTR 26
6411 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PACKAGE_ENDSTR 27
6412 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_STARTSEQ 28
6413 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_ENDSEQ 29
6414 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_STRING 30
6415 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_STARTSTR 31
6416 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_ENDSTR 32
6417 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PUBLIC_DEPENDENCY_STARTSEQ 33
6418 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PUBLIC_DEPENDENCY_ENDSEQ 34
6419 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PUBLIC_DEPENDENCY_INT32 35
6420 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_WEAK_DEPENDENCY_STARTSEQ 36
6421 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_WEAK_DEPENDENCY_ENDSEQ 37
6422 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_WEAK_DEPENDENCY_INT32 38
6423 
6424 /* google.protobuf.FileDescriptorSet */
6425 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_STARTSUBMSG 2
6426 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_STARTSEQ 3
6427 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_ENDSEQ 4
6428 #define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_ENDSUBMSG 5
6429 
6430 /* google.protobuf.FileOptions */
6431 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
6432 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
6433 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
6434 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
6435 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_PACKAGE_STRING 6
6436 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_PACKAGE_STARTSTR 7
6437 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_PACKAGE_ENDSTR 8
6438 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_OUTER_CLASSNAME_STRING 9
6439 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_OUTER_CLASSNAME_STARTSTR 10
6440 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_OUTER_CLASSNAME_ENDSTR 11
6441 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_OPTIMIZE_FOR_INT32 12
6442 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_MULTIPLE_FILES_BOOL 13
6443 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_GO_PACKAGE_STRING 14
6444 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_GO_PACKAGE_STARTSTR 15
6445 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_GO_PACKAGE_ENDSTR 16
6446 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_CC_GENERIC_SERVICES_BOOL 17
6447 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_GENERIC_SERVICES_BOOL 18
6448 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_PY_GENERIC_SERVICES_BOOL 19
6449 #define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_GENERATE_EQUALS_AND_HASH_BOOL 20
6450 
6451 /* google.protobuf.MessageOptions */
6452 #define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
6453 #define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
6454 #define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
6455 #define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
6456 #define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_MESSAGE_SET_WIRE_FORMAT_BOOL 6
6457 #define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_NO_STANDARD_DESCRIPTOR_ACCESSOR_BOOL 7
6458 
6459 /* google.protobuf.MethodDescriptorProto */
6460 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 2
6461 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 3
6462 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_NAME_STRING 4
6463 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_NAME_STARTSTR 5
6464 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_NAME_ENDSTR 6
6465 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_INPUT_TYPE_STRING 7
6466 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_INPUT_TYPE_STARTSTR 8
6467 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_INPUT_TYPE_ENDSTR 9
6468 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OUTPUT_TYPE_STRING 10
6469 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OUTPUT_TYPE_STARTSTR 11
6470 #define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OUTPUT_TYPE_ENDSTR 12
6471 
6472 /* google.protobuf.MethodOptions */
6473 #define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
6474 #define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
6475 #define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
6476 #define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
6477 
6478 /* google.protobuf.ServiceDescriptorProto */
6479 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_STARTSUBMSG 2
6480 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 3
6481 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_STARTSEQ 4
6482 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_ENDSEQ 5
6483 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_ENDSUBMSG 6
6484 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 7
6485 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_NAME_STRING 8
6486 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_NAME_STARTSTR 9
6487 #define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_NAME_ENDSTR 10
6488 
6489 /* google.protobuf.ServiceOptions */
6490 #define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
6491 #define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
6492 #define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
6493 #define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
6494 
6495 /* google.protobuf.SourceCodeInfo */
6496 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_STARTSUBMSG 2
6497 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_STARTSEQ 3
6498 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_ENDSEQ 4
6499 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_ENDSUBMSG 5
6500 
6501 /* google.protobuf.SourceCodeInfo.Location */
6502 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_PATH_STARTSEQ 2
6503 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_PATH_ENDSEQ 3
6504 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_PATH_INT32 4
6505 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_SPAN_STARTSEQ 5
6506 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_SPAN_ENDSEQ 6
6507 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_SPAN_INT32 7
6508 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_LEADING_COMMENTS_STRING 8
6509 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_LEADING_COMMENTS_STARTSTR 9
6510 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_LEADING_COMMENTS_ENDSTR 10
6511 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_TRAILING_COMMENTS_STRING 11
6512 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_TRAILING_COMMENTS_STARTSTR 12
6513 #define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_TRAILING_COMMENTS_ENDSTR 13
6514 
6515 /* google.protobuf.UninterpretedOption */
6516 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_STARTSUBMSG 2
6517 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_STARTSEQ 3
6518 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_ENDSEQ 4
6519 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_ENDSUBMSG 5
6520 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_IDENTIFIER_VALUE_STRING 6
6521 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_IDENTIFIER_VALUE_STARTSTR 7
6522 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_IDENTIFIER_VALUE_ENDSTR 8
6523 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_POSITIVE_INT_VALUE_UINT64 9
6524 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NEGATIVE_INT_VALUE_INT64 10
6525 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_DOUBLE_VALUE_DOUBLE 11
6526 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_STRING_VALUE_STRING 12
6527 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_STRING_VALUE_STARTSTR 13
6528 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_STRING_VALUE_ENDSTR 14
6529 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_AGGREGATE_VALUE_STRING 15
6530 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_AGGREGATE_VALUE_STARTSTR 16
6531 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_AGGREGATE_VALUE_ENDSTR 17
6532 
6533 /* google.protobuf.UninterpretedOption.NamePart */
6534 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_NAME_PART_STRING 2
6535 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_NAME_PART_STARTSTR 3
6536 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_NAME_PART_ENDSTR 4
6537 #define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_IS_EXTENSION_BOOL 5
6538 
6539 const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner);
6540 
6541 /* MessageDefs */
6542 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_DescriptorProto(const upb_symtab *s) {
6543   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.DescriptorProto");
6544   assert(m);
6545   return m;
6546 }
6547 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange(const upb_symtab *s) {
6548   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.DescriptorProto.ExtensionRange");
6549   assert(m);
6550   return m;
6551 }
6552 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto(const upb_symtab *s) {
6553   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumDescriptorProto");
6554   assert(m);
6555   return m;
6556 }
6557 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumOptions(const upb_symtab *s) {
6558   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumOptions");
6559   assert(m);
6560   return m;
6561 }
6562 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto(const upb_symtab *s) {
6563   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumValueDescriptorProto");
6564   assert(m);
6565   return m;
6566 }
6567 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions(const upb_symtab *s) {
6568   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumValueOptions");
6569   assert(m);
6570   return m;
6571 }
6572 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto(const upb_symtab *s) {
6573   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FieldDescriptorProto");
6574   assert(m);
6575   return m;
6576 }
6577 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FieldOptions(const upb_symtab *s) {
6578   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FieldOptions");
6579   assert(m);
6580   return m;
6581 }
6582 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto(const upb_symtab *s) {
6583   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FileDescriptorProto");
6584   assert(m);
6585   return m;
6586 }
6587 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet(const upb_symtab *s) {
6588   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FileDescriptorSet");
6589   assert(m);
6590   return m;
6591 }
6592 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FileOptions(const upb_symtab *s) {
6593   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FileOptions");
6594   assert(m);
6595   return m;
6596 }
6597 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_MessageOptions(const upb_symtab *s) {
6598   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.MessageOptions");
6599   assert(m);
6600   return m;
6601 }
6602 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto(const upb_symtab *s) {
6603   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.MethodDescriptorProto");
6604   assert(m);
6605   return m;
6606 }
6607 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_MethodOptions(const upb_symtab *s) {
6608   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.MethodOptions");
6609   assert(m);
6610   return m;
6611 }
6612 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto(const upb_symtab *s) {
6613   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.ServiceDescriptorProto");
6614   assert(m);
6615   return m;
6616 }
6617 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_ServiceOptions(const upb_symtab *s) {
6618   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.ServiceOptions");
6619   assert(m);
6620   return m;
6621 }
6622 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo(const upb_symtab *s) {
6623   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.SourceCodeInfo");
6624   assert(m);
6625   return m;
6626 }
6627 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location(const upb_symtab *s) {
6628   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.SourceCodeInfo.Location");
6629   assert(m);
6630   return m;
6631 }
6632 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption(const upb_symtab *s) {
6633   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.UninterpretedOption");
6634   assert(m);
6635   return m;
6636 }
6637 UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart(const upb_symtab *s) {
6638   const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.UninterpretedOption.NamePart");
6639   assert(m);
6640   return m;
6641 }
6642 
6643 
6644 /* EnumDefs */
6645 UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label(const upb_symtab *s) {
6646   const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FieldDescriptorProto.Label");
6647   assert(e);
6648   return e;
6649 }
6650 UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type(const upb_symtab *s) {
6651   const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FieldDescriptorProto.Type");
6652   assert(e);
6653   return e;
6654 }
6655 UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType(const upb_symtab *s) {
6656   const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FieldOptions.CType");
6657   assert(e);
6658   return e;
6659 }
6660 UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode(const upb_symtab *s) {
6661   const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FileOptions.OptimizeMode");
6662   assert(e);
6663   return e;
6664 }
6665 
6666 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_end(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto_ExtensionRange(s), 2); }
6667 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_start(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto_ExtensionRange(s), 1); }
6668 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_enum_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 4); }
6669 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_extension(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 6); }
6670 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_extension_range(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 5); }
6671 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_field(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 2); }
6672 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 1); }
6673 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_nested_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 3); }
6674 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 7); }
6675 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumDescriptorProto(s), 1); }
6676 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumDescriptorProto(s), 3); }
6677 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumDescriptorProto(s), 2); }
6678 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_allow_alias(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumOptions(s), 2); }
6679 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumOptions(s), 999); }
6680 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueDescriptorProto(s), 1); }
6681 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_number(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueDescriptorProto(s), 2); }
6682 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueDescriptorProto(s), 3); }
6683 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueOptions(s), 999); }
6684 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_default_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 7); }
6685 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_extendee(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 2); }
6686 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_label(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 4); }
6687 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 1); }
6688 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_number(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 3); }
6689 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 8); }
6690 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 5); }
6691 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_type_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 6); }
6692 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_ctype(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 1); }
6693 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_deprecated(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 3); }
6694 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_experimental_map_key(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 9); }
6695 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_lazy(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 5); }
6696 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_packed(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 2); }
6697 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 999); }
6698 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_weak(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 10); }
6699 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_dependency(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 3); }
6700 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_enum_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 5); }
6701 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_extension(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 7); }
6702 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_message_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 4); }
6703 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 1); }
6704 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 8); }
6705 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_package(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 2); }
6706 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_public_dependency(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 10); }
6707 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_service(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 6); }
6708 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_source_code_info(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 9); }
6709 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_weak_dependency(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 11); }
6710 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorSet_file(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorSet(s), 1); }
6711 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_cc_generic_services(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 16); }
6712 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_go_package(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 11); }
6713 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_generate_equals_and_hash(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 20); }
6714 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_generic_services(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 17); }
6715 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_multiple_files(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 10); }
6716 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_outer_classname(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 8); }
6717 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_package(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 1); }
6718 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_optimize_for(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 9); }
6719 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_py_generic_services(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 18); }
6720 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 999); }
6721 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_message_set_wire_format(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MessageOptions(s), 1); }
6722 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_no_standard_descriptor_accessor(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MessageOptions(s), 2); }
6723 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MessageOptions(s), 999); }
6724 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_input_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 2); }
6725 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 1); }
6726 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 4); }
6727 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_output_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 3); }
6728 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodOptions(s), 999); }
6729 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_method(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceDescriptorProto(s), 2); }
6730 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceDescriptorProto(s), 1); }
6731 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceDescriptorProto(s), 3); }
6732 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceOptions(s), 999); }
6733 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_leading_comments(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 3); }
6734 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_path(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 1); }
6735 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_span(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 2); }
6736 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_trailing_comments(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 4); }
6737 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_location(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo(s), 1); }
6738 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_is_extension(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption_NamePart(s), 2); }
6739 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_name_part(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption_NamePart(s), 1); }
6740 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_aggregate_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 8); }
6741 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_double_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 6); }
6742 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_identifier_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 3); }
6743 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 2); }
6744 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_negative_int_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 5); }
6745 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_positive_int_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 4); }
6746 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_string_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 7); }
6747 
6748 UPB_END_EXTERN_C
6749 
6750 #ifdef __cplusplus
6751 
6752 namespace upbdefs {
6753 namespace google {
6754 namespace protobuf {
6755 namespace descriptor {
6756 inline upb::reffed_ptr<const upb::SymbolTable> SymbolTable() {
6757   const upb::SymbolTable* s = upbdefs_google_protobuf_descriptor(&s);
6758   return upb::reffed_ptr<const upb::SymbolTable>(s, &s);
6759 }
6760 }  /* namespace descriptor */
6761 }  /* namespace protobuf */
6762 }  /* namespace google */
6763 
6764 #define RETURN_REFFED(type, func) \
6765     const type* obj = func(upbdefs::google::protobuf::descriptor::SymbolTable().get()); \
6766     return upb::reffed_ptr<const type>(obj);
6767 
6768 namespace google {
6769 namespace protobuf {
6770 namespace DescriptorProto {
6771 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_DescriptorProto) }
6772 inline upb::reffed_ptr<const upb::FieldDef> enum_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_enum_type) }
6773 inline upb::reffed_ptr<const upb::FieldDef> extension() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_extension) }
6774 inline upb::reffed_ptr<const upb::FieldDef> extension_range() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_extension_range) }
6775 inline upb::reffed_ptr<const upb::FieldDef> field() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_field) }
6776 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_name) }
6777 inline upb::reffed_ptr<const upb::FieldDef> nested_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_nested_type) }
6778 inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_options) }
6779 }  /* namespace DescriptorProto */
6780 }  /* namespace protobuf */
6781 }  /* namespace google */
6782 
6783 namespace google {
6784 namespace protobuf {
6785 namespace DescriptorProto {
6786 namespace ExtensionRange {
6787 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_DescriptorProto_ExtensionRange) }
6788 inline upb::reffed_ptr<const upb::FieldDef> end() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_ExtensionRange_end) }
6789 inline upb::reffed_ptr<const upb::FieldDef> start() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_ExtensionRange_start) }
6790 }  /* namespace ExtensionRange */
6791 }  /* namespace DescriptorProto */
6792 }  /* namespace protobuf */
6793 }  /* namespace google */
6794 
6795 namespace google {
6796 namespace protobuf {
6797 namespace EnumDescriptorProto {
6798 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumDescriptorProto) }
6799 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumDescriptorProto_name) }
6800 inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumDescriptorProto_options) }
6801 inline upb::reffed_ptr<const upb::FieldDef> value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumDescriptorProto_value) }
6802 }  /* namespace EnumDescriptorProto */
6803 }  /* namespace protobuf */
6804 }  /* namespace google */
6805 
6806 namespace google {
6807 namespace protobuf {
6808 namespace EnumOptions {
6809 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumOptions) }
6810 inline upb::reffed_ptr<const upb::FieldDef> allow_alias() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumOptions_allow_alias) }
6811 inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumOptions_uninterpreted_option) }
6812 }  /* namespace EnumOptions */
6813 }  /* namespace protobuf */
6814 }  /* namespace google */
6815 
6816 namespace google {
6817 namespace protobuf {
6818 namespace EnumValueDescriptorProto {
6819 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumValueDescriptorProto) }
6820 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueDescriptorProto_name) }
6821 inline upb::reffed_ptr<const upb::FieldDef> number() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueDescriptorProto_number) }
6822 inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueDescriptorProto_options) }
6823 }  /* namespace EnumValueDescriptorProto */
6824 }  /* namespace protobuf */
6825 }  /* namespace google */
6826 
6827 namespace google {
6828 namespace protobuf {
6829 namespace EnumValueOptions {
6830 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumValueOptions) }
6831 inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueOptions_uninterpreted_option) }
6832 }  /* namespace EnumValueOptions */
6833 }  /* namespace protobuf */
6834 }  /* namespace google */
6835 
6836 namespace google {
6837 namespace protobuf {
6838 namespace FieldDescriptorProto {
6839 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FieldDescriptorProto) }
6840 inline upb::reffed_ptr<const upb::FieldDef> default_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_default_value) }
6841 inline upb::reffed_ptr<const upb::FieldDef> extendee() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_extendee) }
6842 inline upb::reffed_ptr<const upb::FieldDef> label() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_label) }
6843 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_name) }
6844 inline upb::reffed_ptr<const upb::FieldDef> number() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_number) }
6845 inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_options) }
6846 inline upb::reffed_ptr<const upb::FieldDef> type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_type) }
6847 inline upb::reffed_ptr<const upb::FieldDef> type_name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_type_name) }
6848 inline upb::reffed_ptr<const upb::EnumDef> Label() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FieldDescriptorProto_Label) }
6849 inline upb::reffed_ptr<const upb::EnumDef> Type() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FieldDescriptorProto_Type) }
6850 }  /* namespace FieldDescriptorProto */
6851 }  /* namespace protobuf */
6852 }  /* namespace google */
6853 
6854 namespace google {
6855 namespace protobuf {
6856 namespace FieldOptions {
6857 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FieldOptions) }
6858 inline upb::reffed_ptr<const upb::FieldDef> ctype() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_ctype) }
6859 inline upb::reffed_ptr<const upb::FieldDef> deprecated() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_deprecated) }
6860 inline upb::reffed_ptr<const upb::FieldDef> experimental_map_key() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_experimental_map_key) }
6861 inline upb::reffed_ptr<const upb::FieldDef> lazy() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_lazy) }
6862 inline upb::reffed_ptr<const upb::FieldDef> packed() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_packed) }
6863 inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_uninterpreted_option) }
6864 inline upb::reffed_ptr<const upb::FieldDef> weak() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_weak) }
6865 inline upb::reffed_ptr<const upb::EnumDef> CType() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FieldOptions_CType) }
6866 }  /* namespace FieldOptions */
6867 }  /* namespace protobuf */
6868 }  /* namespace google */
6869 
6870 namespace google {
6871 namespace protobuf {
6872 namespace FileDescriptorProto {
6873 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FileDescriptorProto) }
6874 inline upb::reffed_ptr<const upb::FieldDef> dependency() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_dependency) }
6875 inline upb::reffed_ptr<const upb::FieldDef> enum_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_enum_type) }
6876 inline upb::reffed_ptr<const upb::FieldDef> extension() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_extension) }
6877 inline upb::reffed_ptr<const upb::FieldDef> message_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_message_type) }
6878 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_name) }
6879 inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_options) }
6880 inline upb::reffed_ptr<const upb::FieldDef> package() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_package) }
6881 inline upb::reffed_ptr<const upb::FieldDef> public_dependency() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_public_dependency) }
6882 inline upb::reffed_ptr<const upb::FieldDef> service() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_service) }
6883 inline upb::reffed_ptr<const upb::FieldDef> source_code_info() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_source_code_info) }
6884 inline upb::reffed_ptr<const upb::FieldDef> weak_dependency() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_weak_dependency) }
6885 }  /* namespace FileDescriptorProto */
6886 }  /* namespace protobuf */
6887 }  /* namespace google */
6888 
6889 namespace google {
6890 namespace protobuf {
6891 namespace FileDescriptorSet {
6892 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FileDescriptorSet) }
6893 inline upb::reffed_ptr<const upb::FieldDef> file() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorSet_file) }
6894 }  /* namespace FileDescriptorSet */
6895 }  /* namespace protobuf */
6896 }  /* namespace google */
6897 
6898 namespace google {
6899 namespace protobuf {
6900 namespace FileOptions {
6901 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FileOptions) }
6902 inline upb::reffed_ptr<const upb::FieldDef> cc_generic_services() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_cc_generic_services) }
6903 inline upb::reffed_ptr<const upb::FieldDef> go_package() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_go_package) }
6904 inline upb::reffed_ptr<const upb::FieldDef> java_generate_equals_and_hash() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_generate_equals_and_hash) }
6905 inline upb::reffed_ptr<const upb::FieldDef> java_generic_services() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_generic_services) }
6906 inline upb::reffed_ptr<const upb::FieldDef> java_multiple_files() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_multiple_files) }
6907 inline upb::reffed_ptr<const upb::FieldDef> java_outer_classname() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_outer_classname) }
6908 inline upb::reffed_ptr<const upb::FieldDef> java_package() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_package) }
6909 inline upb::reffed_ptr<const upb::FieldDef> optimize_for() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_optimize_for) }
6910 inline upb::reffed_ptr<const upb::FieldDef> py_generic_services() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_py_generic_services) }
6911 inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_uninterpreted_option) }
6912 inline upb::reffed_ptr<const upb::EnumDef> OptimizeMode() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FileOptions_OptimizeMode) }
6913 }  /* namespace FileOptions */
6914 }  /* namespace protobuf */
6915 }  /* namespace google */
6916 
6917 namespace google {
6918 namespace protobuf {
6919 namespace MessageOptions {
6920 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_MessageOptions) }
6921 inline upb::reffed_ptr<const upb::FieldDef> message_set_wire_format() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MessageOptions_message_set_wire_format) }
6922 inline upb::reffed_ptr<const upb::FieldDef> no_standard_descriptor_accessor() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MessageOptions_no_standard_descriptor_accessor) }
6923 inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MessageOptions_uninterpreted_option) }
6924 }  /* namespace MessageOptions */
6925 }  /* namespace protobuf */
6926 }  /* namespace google */
6927 
6928 namespace google {
6929 namespace protobuf {
6930 namespace MethodDescriptorProto {
6931 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_MethodDescriptorProto) }
6932 inline upb::reffed_ptr<const upb::FieldDef> input_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_input_type) }
6933 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_name) }
6934 inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_options) }
6935 inline upb::reffed_ptr<const upb::FieldDef> output_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_output_type) }
6936 }  /* namespace MethodDescriptorProto */
6937 }  /* namespace protobuf */
6938 }  /* namespace google */
6939 
6940 namespace google {
6941 namespace protobuf {
6942 namespace MethodOptions {
6943 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_MethodOptions) }
6944 inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodOptions_uninterpreted_option) }
6945 }  /* namespace MethodOptions */
6946 }  /* namespace protobuf */
6947 }  /* namespace google */
6948 
6949 namespace google {
6950 namespace protobuf {
6951 namespace ServiceDescriptorProto {
6952 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_ServiceDescriptorProto) }
6953 inline upb::reffed_ptr<const upb::FieldDef> method() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceDescriptorProto_method) }
6954 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceDescriptorProto_name) }
6955 inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceDescriptorProto_options) }
6956 }  /* namespace ServiceDescriptorProto */
6957 }  /* namespace protobuf */
6958 }  /* namespace google */
6959 
6960 namespace google {
6961 namespace protobuf {
6962 namespace ServiceOptions {
6963 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_ServiceOptions) }
6964 inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceOptions_uninterpreted_option) }
6965 }  /* namespace ServiceOptions */
6966 }  /* namespace protobuf */
6967 }  /* namespace google */
6968 
6969 namespace google {
6970 namespace protobuf {
6971 namespace SourceCodeInfo {
6972 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_SourceCodeInfo) }
6973 inline upb::reffed_ptr<const upb::FieldDef> location() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_location) }
6974 }  /* namespace SourceCodeInfo */
6975 }  /* namespace protobuf */
6976 }  /* namespace google */
6977 
6978 namespace google {
6979 namespace protobuf {
6980 namespace SourceCodeInfo {
6981 namespace Location {
6982 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_SourceCodeInfo_Location) }
6983 inline upb::reffed_ptr<const upb::FieldDef> leading_comments() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_leading_comments) }
6984 inline upb::reffed_ptr<const upb::FieldDef> path() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_path) }
6985 inline upb::reffed_ptr<const upb::FieldDef> span() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_span) }
6986 inline upb::reffed_ptr<const upb::FieldDef> trailing_comments() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_trailing_comments) }
6987 }  /* namespace Location */
6988 }  /* namespace SourceCodeInfo */
6989 }  /* namespace protobuf */
6990 }  /* namespace google */
6991 
6992 namespace google {
6993 namespace protobuf {
6994 namespace UninterpretedOption {
6995 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_UninterpretedOption) }
6996 inline upb::reffed_ptr<const upb::FieldDef> aggregate_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_aggregate_value) }
6997 inline upb::reffed_ptr<const upb::FieldDef> double_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_double_value) }
6998 inline upb::reffed_ptr<const upb::FieldDef> identifier_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_identifier_value) }
6999 inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_name) }
7000 inline upb::reffed_ptr<const upb::FieldDef> negative_int_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_negative_int_value) }
7001 inline upb::reffed_ptr<const upb::FieldDef> positive_int_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_positive_int_value) }
7002 inline upb::reffed_ptr<const upb::FieldDef> string_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_string_value) }
7003 }  /* namespace UninterpretedOption */
7004 }  /* namespace protobuf */
7005 }  /* namespace google */
7006 
7007 namespace google {
7008 namespace protobuf {
7009 namespace UninterpretedOption {
7010 namespace NamePart {
7011 inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_UninterpretedOption_NamePart) }
7012 inline upb::reffed_ptr<const upb::FieldDef> is_extension() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_NamePart_is_extension) }
7013 inline upb::reffed_ptr<const upb::FieldDef> name_part() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_NamePart_name_part) }
7014 }  /* namespace NamePart */
7015 }  /* namespace UninterpretedOption */
7016 }  /* namespace protobuf */
7017 }  /* namespace google */
7018 
7019 }  /* namespace upbdefs */
7020 
7021 
7022 #undef RETURN_REFFED
7023 #endif /* __cplusplus */
7024 
7025 #endif  /* GOOGLE_PROTOBUF_DESCRIPTOR_UPB_H_ */
7026 /*
7027 ** Internal-only definitions for the decoder.
7028 */
7029 
7030 #ifndef UPB_DECODER_INT_H_
7031 #define UPB_DECODER_INT_H_
7032 
7033 #include <stdlib.h>
7034 /*
7035 ** upb::pb::Decoder
7036 **
7037 ** A high performance, streaming, resumable decoder for the binary protobuf
7038 ** format.
7039 **
7040 ** This interface works the same regardless of what decoder backend is being
7041 ** used.  A client of this class does not need to know whether decoding is using
7042 ** a JITted decoder (DynASM, LLVM, etc) or an interpreted decoder.  By default,
7043 ** it will always use the fastest available decoder.  However, you can call
7044 ** set_allow_jit(false) to disable any JIT decoder that might be available.
7045 ** This is primarily useful for testing purposes.
7046 */
7047 
7048 #ifndef UPB_DECODER_H_
7049 #define UPB_DECODER_H_
7050 
7051 
7052 #ifdef __cplusplus
7053 namespace upb {
7054 namespace pb {
7055 class CodeCache;
7056 class Decoder;
7057 class DecoderMethod;
7058 class DecoderMethodOptions;
7059 }  /* namespace pb */
7060 }  /* namespace upb */
7061 #endif
7062 
7063 UPB_DECLARE_TYPE(upb::pb::CodeCache, upb_pbcodecache)
7064 UPB_DECLARE_TYPE(upb::pb::Decoder, upb_pbdecoder)
7065 UPB_DECLARE_TYPE(upb::pb::DecoderMethodOptions, upb_pbdecodermethodopts)
7066 
7067 UPB_DECLARE_DERIVED_TYPE(upb::pb::DecoderMethod, upb::RefCounted,
7068                          upb_pbdecodermethod, upb_refcounted)
7069 
7070 #ifdef __cplusplus
7071 
7072 /* The parameters one uses to construct a DecoderMethod.
7073  * TODO(haberman): move allowjit here?  Seems more convenient for users.
7074  * TODO(haberman): move this to be heap allocated for ABI stability. */
7075 class upb::pb::DecoderMethodOptions {
7076  public:
7077   /* Parameter represents the destination handlers that this method will push
7078    * to. */
7079   explicit DecoderMethodOptions(const Handlers* dest_handlers);
7080 
7081   /* Should the decoder push submessages to lazy handlers for fields that have
7082    * them?  The caller should set this iff the lazy handlers expect data that is
7083    * in protobuf binary format and the caller wishes to lazy parse it. */
7084   void set_lazy(bool lazy);
7085 #else
7086 struct upb_pbdecodermethodopts {
7087 #endif
7088   const upb_handlers *handlers;
7089   bool lazy;
7090 };
7091 
7092 #ifdef __cplusplus
7093 
7094 /* Represents the code to parse a protobuf according to a destination
7095  * Handlers. */
7096 class upb::pb::DecoderMethod {
7097  public:
7098   /* Include base methods from upb::ReferenceCounted. */
7099   UPB_REFCOUNTED_CPPMETHODS
7100 
7101   /* The destination handlers that are statically bound to this method.
7102    * This method is only capable of outputting to a sink that uses these
7103    * handlers. */
7104   const Handlers* dest_handlers() const;
7105 
7106   /* The input handlers for this decoder method. */
7107   const BytesHandler* input_handler() const;
7108 
7109   /* Whether this method is native. */
7110   bool is_native() const;
7111 
7112   /* Convenience method for generating a DecoderMethod without explicitly
7113    * creating a CodeCache. */
7114   static reffed_ptr<const DecoderMethod> New(const DecoderMethodOptions& opts);
7115 
7116  private:
7117   UPB_DISALLOW_POD_OPS(DecoderMethod, upb::pb::DecoderMethod)
7118 };
7119 
7120 #endif
7121 
7122 /* Preallocation hint: decoder won't allocate more bytes than this when first
7123  * constructed.  This hint may be an overestimate for some build configurations.
7124  * But if the decoder library is upgraded without recompiling the application,
7125  * it may be an underestimate. */
7126 #define UPB_PB_DECODER_SIZE 4408
7127 
7128 #ifdef __cplusplus
7129 
7130 /* A Decoder receives binary protobuf data on its input sink and pushes the
7131  * decoded data to its output sink. */
7132 class upb::pb::Decoder {
7133  public:
7134   /* Constructs a decoder instance for the given method, which must outlive this
7135    * decoder.  Any errors during parsing will be set on the given status, which
7136    * must also outlive this decoder.
7137    *
7138    * The sink must match the given method. */
7139   static Decoder* Create(Environment* env, const DecoderMethod* method,
7140                          Sink* output);
7141 
7142   /* Returns the DecoderMethod this decoder is parsing from. */
7143   const DecoderMethod* method() const;
7144 
7145   /* The sink on which this decoder receives input. */
7146   BytesSink* input();
7147 
7148   /* Returns number of bytes successfully parsed.
7149    *
7150    * This can be useful for determining the stream position where an error
7151    * occurred.
7152    *
7153    * This value may not be up-to-date when called from inside a parsing
7154    * callback. */
7155   uint64_t BytesParsed() const;
7156 
7157   /* Gets/sets the parsing nexting limit.  If the total number of nested
7158    * submessages and repeated fields hits this limit, parsing will fail.  This
7159    * is a resource limit that controls the amount of memory used by the parsing
7160    * stack.
7161    *
7162    * Setting the limit will fail if the parser is currently suspended at a depth
7163    * greater than this, or if memory allocation of the stack fails. */
7164   size_t max_nesting() const;
7165   bool set_max_nesting(size_t max);
7166 
7167   void Reset();
7168 
7169   static const size_t kSize = UPB_PB_DECODER_SIZE;
7170 
7171  private:
7172   UPB_DISALLOW_POD_OPS(Decoder, upb::pb::Decoder)
7173 };
7174 
7175 #endif  /* __cplusplus */
7176 
7177 #ifdef __cplusplus
7178 
7179 /* A class for caching protobuf processing code, whether bytecode for the
7180  * interpreted decoder or machine code for the JIT.
7181  *
7182  * This class is not thread-safe.
7183  *
7184  * TODO(haberman): move this to be heap allocated for ABI stability. */
7185 class upb::pb::CodeCache {
7186  public:
7187   CodeCache();
7188   ~CodeCache();
7189 
7190   /* Whether the cache is allowed to generate machine code.  Defaults to true.
7191    * There is no real reason to turn it off except for testing or if you are
7192    * having a specific problem with the JIT.
7193    *
7194    * Note that allow_jit = true does not *guarantee* that the code will be JIT
7195    * compiled.  If this platform is not supported or the JIT was not compiled
7196    * in, the code may still be interpreted. */
7197   bool allow_jit() const;
7198 
7199   /* This may only be called when the object is first constructed, and prior to
7200    * any code generation, otherwise returns false and does nothing. */
7201   bool set_allow_jit(bool allow);
7202 
7203   /* Returns a DecoderMethod that can push data to the given handlers.
7204    * If a suitable method already exists, it will be returned from the cache.
7205    *
7206    * Specifying the destination handlers here allows the DecoderMethod to be
7207    * statically bound to the destination handlers if possible, which can allow
7208    * more efficient decoding.  However the returned method may or may not
7209    * actually be statically bound.  But in all cases, the returned method can
7210    * push data to the given handlers. */
7211   const DecoderMethod *GetDecoderMethod(const DecoderMethodOptions& opts);
7212 
7213   /* If/when someone needs to explicitly create a dynamically-bound
7214    * DecoderMethod*, we can add a method to get it here. */
7215 
7216  private:
7217   UPB_DISALLOW_COPY_AND_ASSIGN(CodeCache)
7218 #else
7219 struct upb_pbcodecache {
7220 #endif
7221   bool allow_jit_;
7222 
7223   /* Array of mgroups. */
7224   upb_inttable groups;
7225 };
7226 
7227 UPB_BEGIN_EXTERN_C
7228 
7229 upb_pbdecoder *upb_pbdecoder_create(upb_env *e,
7230                                     const upb_pbdecodermethod *method,
7231                                     upb_sink *output);
7232 const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d);
7233 upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d);
7234 uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d);
7235 size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d);
7236 bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max);
7237 void upb_pbdecoder_reset(upb_pbdecoder *d);
7238 
7239 void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
7240                                   const upb_handlers *h);
7241 void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy);
7242 
7243 
7244 /* Include refcounted methods like upb_pbdecodermethod_ref(). */
7245 UPB_REFCOUNTED_CMETHODS(upb_pbdecodermethod, upb_pbdecodermethod_upcast)
7246 
7247 const upb_handlers *upb_pbdecodermethod_desthandlers(
7248     const upb_pbdecodermethod *m);
7249 const upb_byteshandler *upb_pbdecodermethod_inputhandler(
7250     const upb_pbdecodermethod *m);
7251 bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m);
7252 const upb_pbdecodermethod *upb_pbdecodermethod_new(
7253     const upb_pbdecodermethodopts *opts, const void *owner);
7254 
7255 void upb_pbcodecache_init(upb_pbcodecache *c);
7256 void upb_pbcodecache_uninit(upb_pbcodecache *c);
7257 bool upb_pbcodecache_allowjit(const upb_pbcodecache *c);
7258 bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow);
7259 const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
7260     upb_pbcodecache *c, const upb_pbdecodermethodopts *opts);
7261 
7262 UPB_END_EXTERN_C
7263 
7264 #ifdef __cplusplus
7265 
7266 namespace upb {
7267 
7268 namespace pb {
7269 
7270 /* static */
7271 inline Decoder* Decoder::Create(Environment* env, const DecoderMethod* m,
7272                                 Sink* sink) {
7273   return upb_pbdecoder_create(env, m, sink);
7274 }
7275 inline const DecoderMethod* Decoder::method() const {
7276   return upb_pbdecoder_method(this);
7277 }
7278 inline BytesSink* Decoder::input() {
7279   return upb_pbdecoder_input(this);
7280 }
7281 inline uint64_t Decoder::BytesParsed() const {
7282   return upb_pbdecoder_bytesparsed(this);
7283 }
7284 inline size_t Decoder::max_nesting() const {
7285   return upb_pbdecoder_maxnesting(this);
7286 }
7287 inline bool Decoder::set_max_nesting(size_t max) {
7288   return upb_pbdecoder_setmaxnesting(this, max);
7289 }
7290 inline void Decoder::Reset() { upb_pbdecoder_reset(this); }
7291 
7292 inline DecoderMethodOptions::DecoderMethodOptions(const Handlers* h) {
7293   upb_pbdecodermethodopts_init(this, h);
7294 }
7295 inline void DecoderMethodOptions::set_lazy(bool lazy) {
7296   upb_pbdecodermethodopts_setlazy(this, lazy);
7297 }
7298 
7299 inline const Handlers* DecoderMethod::dest_handlers() const {
7300   return upb_pbdecodermethod_desthandlers(this);
7301 }
7302 inline const BytesHandler* DecoderMethod::input_handler() const {
7303   return upb_pbdecodermethod_inputhandler(this);
7304 }
7305 inline bool DecoderMethod::is_native() const {
7306   return upb_pbdecodermethod_isnative(this);
7307 }
7308 /* static */
7309 inline reffed_ptr<const DecoderMethod> DecoderMethod::New(
7310     const DecoderMethodOptions &opts) {
7311   const upb_pbdecodermethod *m = upb_pbdecodermethod_new(&opts, &m);
7312   return reffed_ptr<const DecoderMethod>(m, &m);
7313 }
7314 
7315 inline CodeCache::CodeCache() {
7316   upb_pbcodecache_init(this);
7317 }
7318 inline CodeCache::~CodeCache() {
7319   upb_pbcodecache_uninit(this);
7320 }
7321 inline bool CodeCache::allow_jit() const {
7322   return upb_pbcodecache_allowjit(this);
7323 }
7324 inline bool CodeCache::set_allow_jit(bool allow) {
7325   return upb_pbcodecache_setallowjit(this, allow);
7326 }
7327 inline const DecoderMethod *CodeCache::GetDecoderMethod(
7328     const DecoderMethodOptions& opts) {
7329   return upb_pbcodecache_getdecodermethod(this, &opts);
7330 }
7331 
7332 }  /* namespace pb */
7333 }  /* namespace upb */
7334 
7335 #endif  /* __cplusplus */
7336 
7337 #endif  /* UPB_DECODER_H_ */
7338 
7339 /* C++ names are not actually used since this type isn't exposed to users. */
7340 #ifdef __cplusplus
7341 namespace upb {
7342 namespace pb {
7343 class MessageGroup;
7344 }  /* namespace pb */
7345 }  /* namespace upb */
7346 #endif
7347 UPB_DECLARE_DERIVED_TYPE(upb::pb::MessageGroup, upb::RefCounted,
7348                          mgroup, upb_refcounted)
7349 
7350 /* Opcode definitions.  The canonical meaning of each opcode is its
7351  * implementation in the interpreter (the JIT is written to match this).
7352  *
7353  * All instructions have the opcode in the low byte.
7354  * Instruction format for most instructions is:
7355  *
7356  * +-------------------+--------+
7357  * |     arg (24)      | op (8) |
7358  * +-------------------+--------+
7359  *
7360  * Exceptions are indicated below.  A few opcodes are multi-word. */
7361 typedef enum {
7362   /* Opcodes 1-8, 13, 15-18 parse their respective descriptor types.
7363    * Arg for all of these is the upb selector for this field. */
7364 #define T(type) OP_PARSE_ ## type = UPB_DESCRIPTOR_TYPE_ ## type
7365   T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32),
7366   T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64),
7367 #undef T
7368   OP_STARTMSG       = 9,   /* No arg. */
7369   OP_ENDMSG         = 10,  /* No arg. */
7370   OP_STARTSEQ       = 11,
7371   OP_ENDSEQ         = 12,
7372   OP_STARTSUBMSG    = 14,
7373   OP_ENDSUBMSG      = 19,
7374   OP_STARTSTR       = 20,
7375   OP_STRING         = 21,
7376   OP_ENDSTR         = 22,
7377 
7378   OP_PUSHTAGDELIM   = 23,  /* No arg. */
7379   OP_PUSHLENDELIM   = 24,  /* No arg. */
7380   OP_POP            = 25,  /* No arg. */
7381   OP_SETDELIM       = 26,  /* No arg. */
7382   OP_SETBIGGROUPNUM = 27,  /* two words:
7383                             *   | unused (24)     | opc (8) |
7384                             *   |        groupnum (32)      | */
7385   OP_CHECKDELIM     = 28,
7386   OP_CALL           = 29,
7387   OP_RET            = 30,
7388   OP_BRANCH         = 31,
7389 
7390   /* Different opcodes depending on how many bytes expected. */
7391   OP_TAG1           = 32,  /* | match tag (16) | jump target (8) | opc (8) | */
7392   OP_TAG2           = 33,  /* | match tag (16) | jump target (8) | opc (8) | */
7393   OP_TAGN           = 34,  /* three words: */
7394                            /*   | unused (16) | jump target(8) | opc (8) | */
7395                            /*   |           match tag 1 (32)             | */
7396                            /*   |           match tag 2 (32)             | */
7397 
7398   OP_SETDISPATCH    = 35,  /* N words: */
7399                            /*   | unused (24)         | opc | */
7400                            /*   | upb_inttable* (32 or 64)  | */
7401 
7402   OP_DISPATCH       = 36,  /* No arg. */
7403 
7404   OP_HALT           = 37   /* No arg. */
7405 } opcode;
7406 
7407 #define OP_MAX OP_HALT
7408 
7409 UPB_INLINE opcode getop(uint32_t instr) { return instr & 0xff; }
7410 
7411 /* Method group; represents a set of decoder methods that had their code
7412  * emitted together, and must therefore be freed together.  Immutable once
7413  * created.  It is possible we may want to expose this to users at some point.
7414  *
7415  * Overall ownership of Decoder objects looks like this:
7416  *
7417  *                +----------+
7418  *                |          | <---> DecoderMethod
7419  *                | method   |
7420  * CodeCache ---> |  group   | <---> DecoderMethod
7421  *                |          |
7422  *                | (mgroup) | <---> DecoderMethod
7423  *                +----------+
7424  */
7425 struct mgroup {
7426   upb_refcounted base;
7427 
7428   /* Maps upb_msgdef/upb_handlers -> upb_pbdecodermethod.  We own refs on the
7429    * methods. */
7430   upb_inttable methods;
7431 
7432   /* When we add the ability to link to previously existing mgroups, we'll
7433    * need an array of mgroups we reference here, and own refs on them. */
7434 
7435   /* The bytecode for our methods, if any exists.  Owned by us. */
7436   uint32_t *bytecode;
7437   uint32_t *bytecode_end;
7438 
7439 #ifdef UPB_USE_JIT_X64
7440   /* JIT-generated machine code, if any. */
7441   upb_string_handlerfunc *jit_code;
7442   /* The size of the jit_code (required to munmap()). */
7443   size_t jit_size;
7444   char *debug_info;
7445   void *dl;
7446 #endif
7447 };
7448 
7449 /* The maximum that any submessages can be nested.  Matches proto2's limit.
7450  * This specifies the size of the decoder's statically-sized array and therefore
7451  * setting it high will cause the upb::pb::Decoder object to be larger.
7452  *
7453  * If necessary we can add a runtime-settable property to Decoder that allow
7454  * this to be larger than the compile-time setting, but this would add
7455  * complexity, particularly since we would have to decide how/if to give users
7456  * the ability to set a custom memory allocation function. */
7457 #define UPB_DECODER_MAX_NESTING 64
7458 
7459 /* Internal-only struct used by the decoder. */
7460 typedef struct {
7461   /* Space optimization note: we store two pointers here that the JIT
7462    * doesn't need at all; the upb_handlers* inside the sink and
7463    * the dispatch table pointer.  We can optimze so that the JIT uses
7464    * smaller stack frames than the interpreter.  The only thing we need
7465    * to guarantee is that the fallback routines can find end_ofs. */
7466   upb_sink sink;
7467 
7468   /* The absolute stream offset of the end-of-frame delimiter.
7469    * Non-delimited frames (groups and non-packed repeated fields) reuse the
7470    * delimiter of their parent, even though the frame may not end there.
7471    *
7472    * NOTE: the JIT stores a slightly different value here for non-top frames.
7473    * It stores the value relative to the end of the enclosed message.  But the
7474    * top frame is still stored the same way, which is important for ensuring
7475    * that calls from the JIT into C work correctly. */
7476   uint64_t end_ofs;
7477   const uint32_t *base;
7478 
7479   /* 0 indicates a length-delimited field.
7480    * A positive number indicates a known group.
7481    * A negative number indicates an unknown group. */
7482   int32_t groupnum;
7483   upb_inttable *dispatch;  /* Not used by the JIT. */
7484 } upb_pbdecoder_frame;
7485 
7486 struct upb_pbdecodermethod {
7487   upb_refcounted base;
7488 
7489   /* While compiling, the base is relative in "ofs", after compiling it is
7490    * absolute in "ptr". */
7491   union {
7492     uint32_t ofs;     /* PC offset of method. */
7493     void *ptr;        /* Pointer to bytecode or machine code for this method. */
7494   } code_base;
7495 
7496   /* The decoder method group to which this method belongs.  We own a ref.
7497    * Owning a ref on the entire group is more coarse-grained than is strictly
7498    * necessary; all we truly require is that methods we directly reference
7499    * outlive us, while the group could contain many other messages we don't
7500    * require.  But the group represents the messages that were
7501    * allocated+compiled together, so it makes the most sense to free them
7502    * together also. */
7503   const upb_refcounted *group;
7504 
7505   /* Whether this method is native code or bytecode. */
7506   bool is_native_;
7507 
7508   /* The handler one calls to invoke this method. */
7509   upb_byteshandler input_handler_;
7510 
7511   /* The destination handlers this method is bound to.  We own a ref. */
7512   const upb_handlers *dest_handlers_;
7513 
7514   /* Dispatch table -- used by both bytecode decoder and JIT when encountering a
7515    * field number that wasn't the one we were expecting to see.  See
7516    * decoder.int.h for the layout of this table. */
7517   upb_inttable dispatch;
7518 };
7519 
7520 struct upb_pbdecoder {
7521   upb_env *env;
7522 
7523   /* Our input sink. */
7524   upb_bytessink input_;
7525 
7526   /* The decoder method we are parsing with (owned). */
7527   const upb_pbdecodermethod *method_;
7528 
7529   size_t call_len;
7530   const uint32_t *pc, *last;
7531 
7532   /* Current input buffer and its stream offset. */
7533   const char *buf, *ptr, *end, *checkpoint;
7534 
7535   /* End of the delimited region, relative to ptr, NULL if not in this buf. */
7536   const char *delim_end;
7537 
7538   /* End of the delimited region, relative to ptr, end if not in this buf. */
7539   const char *data_end;
7540 
7541   /* Overall stream offset of "buf." */
7542   uint64_t bufstart_ofs;
7543 
7544   /* Buffer for residual bytes not parsed from the previous buffer.
7545    * The maximum number of residual bytes we require is 12; a five-byte
7546    * unknown tag plus an eight-byte value, less one because the value
7547    * is only a partial value. */
7548   char residual[12];
7549   char *residual_end;
7550 
7551   /* Bytes of data that should be discarded from the input beore we start
7552    * parsing again.  We set this when we internally determine that we can
7553    * safely skip the next N bytes, but this region extends past the current
7554    * user buffer. */
7555   size_t skip;
7556 
7557   /* Stores the user buffer passed to our decode function. */
7558   const char *buf_param;
7559   size_t size_param;
7560   const upb_bufhandle *handle;
7561 
7562   /* Our internal stack. */
7563   upb_pbdecoder_frame *stack, *top, *limit;
7564   const uint32_t **callstack;
7565   size_t stack_size;
7566 
7567   upb_status *status;
7568 
7569 #ifdef UPB_USE_JIT_X64
7570   /* Used momentarily by the generated code to store a value while a user
7571    * function is called. */
7572   uint32_t tmp_len;
7573 
7574   const void *saved_rsp;
7575 #endif
7576 };
7577 
7578 /* Decoder entry points; used as handlers. */
7579 void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint);
7580 void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint);
7581 size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
7582                             size_t size, const upb_bufhandle *handle);
7583 bool upb_pbdecoder_end(void *closure, const void *handler_data);
7584 
7585 /* Decoder-internal functions that the JIT calls to handle fallback paths. */
7586 int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
7587                              size_t size, const upb_bufhandle *handle);
7588 size_t upb_pbdecoder_suspend(upb_pbdecoder *d);
7589 int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
7590                                   uint8_t wire_type);
7591 int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d, uint64_t expected);
7592 int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d, uint64_t *u64);
7593 int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32);
7594 int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64);
7595 void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg);
7596 
7597 /* Error messages that are shared between the bytecode and JIT decoders. */
7598 extern const char *kPbDecoderStackOverflow;
7599 extern const char *kPbDecoderSubmessageTooLong;
7600 
7601 /* Access to decoderplan members needed by the decoder. */
7602 const char *upb_pbdecoder_getopname(unsigned int op);
7603 
7604 /* JIT codegen entry point. */
7605 void upb_pbdecoder_jit(mgroup *group);
7606 void upb_pbdecoder_freejit(mgroup *group);
7607 UPB_REFCOUNTED_CMETHODS(mgroup, mgroup_upcast)
7608 
7609 /* A special label that means "do field dispatch for this message and branch to
7610  * wherever that takes you." */
7611 #define LABEL_DISPATCH 0
7612 
7613 /* A special slot in the dispatch table that stores the epilogue (ENDMSG and/or
7614  * RET) for branching to when we find an appropriate ENDGROUP tag. */
7615 #define DISPATCH_ENDMSG 0
7616 
7617 /* It's important to use this invalid wire type instead of 0 (which is a valid
7618  * wire type). */
7619 #define NO_WIRE_TYPE 0xff
7620 
7621 /* The dispatch table layout is:
7622  *   [field number] -> [ 48-bit offset ][ 8-bit wt2 ][ 8-bit wt1 ]
7623  *
7624  * If wt1 matches, jump to the 48-bit offset.  If wt2 matches, lookup
7625  * (UPB_MAX_FIELDNUMBER + fieldnum) and jump there.
7626  *
7627  * We need two wire types because of packed/non-packed compatibility.  A
7628  * primitive repeated field can use either wire type and be valid.  While we
7629  * could key the table on fieldnum+wiretype, the table would be 8x sparser.
7630  *
7631  * Storing two wire types in the primary value allows us to quickly rule out
7632  * the second wire type without needing to do a separate lookup (this case is
7633  * less common than an unknown field). */
7634 UPB_INLINE uint64_t upb_pbdecoder_packdispatch(uint64_t ofs, uint8_t wt1,
7635                                                uint8_t wt2) {
7636   return (ofs << 16) | (wt2 << 8) | wt1;
7637 }
7638 
7639 UPB_INLINE void upb_pbdecoder_unpackdispatch(uint64_t dispatch, uint64_t *ofs,
7640                                              uint8_t *wt1, uint8_t *wt2) {
7641   *wt1 = (uint8_t)dispatch;
7642   *wt2 = (uint8_t)(dispatch >> 8);
7643   *ofs = dispatch >> 16;
7644 }
7645 
7646 /* All of the functions in decoder.c that return int32_t return values according
7647  * to the following scheme:
7648  *   1. negative values indicate a return code from the following list.
7649  *   2. positive values indicate that error or end of buffer was hit, and
7650  *      that the decode function should immediately return the given value
7651  *      (the decoder state has already been suspended and is ready to be
7652  *      resumed). */
7653 #define DECODE_OK -1
7654 #define DECODE_MISMATCH -2  /* Used only from checktag_slow(). */
7655 #define DECODE_ENDGROUP -3  /* Used only from checkunknown(). */
7656 
7657 #define CHECK_RETURN(x) { int32_t ret = x; if (ret >= 0) return ret; }
7658 
7659 #endif  /* UPB_DECODER_INT_H_ */
7660 /*
7661 ** A number of routines for varint manipulation (we keep them all around to
7662 ** have multiple approaches available for benchmarking).
7663 */
7664 
7665 #ifndef UPB_VARINT_DECODER_H_
7666 #define UPB_VARINT_DECODER_H_
7667 
7668 #include <assert.h>
7669 #include <stdint.h>
7670 #include <string.h>
7671 
7672 #ifdef __cplusplus
7673 extern "C" {
7674 #endif
7675 
7676 /* A list of types as they are encoded on-the-wire. */
7677 typedef enum {
7678   UPB_WIRE_TYPE_VARINT      = 0,
7679   UPB_WIRE_TYPE_64BIT       = 1,
7680   UPB_WIRE_TYPE_DELIMITED   = 2,
7681   UPB_WIRE_TYPE_START_GROUP = 3,
7682   UPB_WIRE_TYPE_END_GROUP   = 4,
7683   UPB_WIRE_TYPE_32BIT       = 5
7684 } upb_wiretype_t;
7685 
7686 #define UPB_MAX_WIRE_TYPE 5
7687 
7688 /* The maximum number of bytes that it takes to encode a 64-bit varint.
7689  * Note that with a better encoding this could be 9 (TODO: write up a
7690  * wiki document about this). */
7691 #define UPB_PB_VARINT_MAX_LEN 10
7692 
7693 /* Array of the "native" (ie. non-packed-repeated) wire type for the given a
7694  * descriptor type (upb_descriptortype_t). */
7695 extern const uint8_t upb_pb_native_wire_types[];
7696 
7697 /* Zig-zag encoding/decoding **************************************************/
7698 
7699 UPB_INLINE int32_t upb_zzdec_32(uint32_t n) {
7700   return (n >> 1) ^ -(int32_t)(n & 1);
7701 }
7702 UPB_INLINE int64_t upb_zzdec_64(uint64_t n) {
7703   return (n >> 1) ^ -(int64_t)(n & 1);
7704 }
7705 UPB_INLINE uint32_t upb_zzenc_32(int32_t n) { return (n << 1) ^ (n >> 31); }
7706 UPB_INLINE uint64_t upb_zzenc_64(int64_t n) { return (n << 1) ^ (n >> 63); }
7707 
7708 /* Decoding *******************************************************************/
7709 
7710 /* All decoding functions return this struct by value. */
7711 typedef struct {
7712   const char *p;  /* NULL if the varint was unterminated. */
7713   uint64_t val;
7714 } upb_decoderet;
7715 
7716 UPB_INLINE upb_decoderet upb_decoderet_make(const char *p, uint64_t val) {
7717   upb_decoderet ret;
7718   ret.p = p;
7719   ret.val = val;
7720   return ret;
7721 }
7722 
7723 /* Four functions for decoding a varint of at most eight bytes.  They are all
7724  * functionally identical, but are implemented in different ways and likely have
7725  * different performance profiles.  We keep them around for performance testing.
7726  *
7727  * Note that these functions may not read byte-by-byte, so they must not be used
7728  * unless there are at least eight bytes left in the buffer! */
7729 upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r);
7730 upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r);
7731 upb_decoderet upb_vdecode_max8_wright(upb_decoderet r);
7732 upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r);
7733 
7734 /* Template for a function that checks the first two bytes with branching
7735  * and dispatches 2-10 bytes with a separate function.  Note that this may read
7736  * up to 10 bytes, so it must not be used unless there are at least ten bytes
7737  * left in the buffer! */
7738 #define UPB_VARINT_DECODER_CHECK2(name, decode_max8_function)                  \
7739 UPB_INLINE upb_decoderet upb_vdecode_check2_ ## name(const char *_p) {         \
7740   uint8_t *p = (uint8_t*)_p;                                                   \
7741   upb_decoderet r;                                                             \
7742   if ((*p & 0x80) == 0) {                                                      \
7743   /* Common case: one-byte varint. */                                          \
7744     return upb_decoderet_make(_p + 1, *p & 0x7fU);                             \
7745   }                                                                            \
7746   r = upb_decoderet_make(_p + 2, (*p & 0x7fU) | ((*(p + 1) & 0x7fU) << 7));    \
7747   if ((*(p + 1) & 0x80) == 0) {                                                \
7748     /* Two-byte varint. */                                                     \
7749     return r;                                                                  \
7750   }                                                                            \
7751   /* Longer varint, fallback to out-of-line function. */                       \
7752   return decode_max8_function(r);                                              \
7753 }
7754 
7755 UPB_VARINT_DECODER_CHECK2(branch32, upb_vdecode_max8_branch32)
7756 UPB_VARINT_DECODER_CHECK2(branch64, upb_vdecode_max8_branch64)
7757 UPB_VARINT_DECODER_CHECK2(wright, upb_vdecode_max8_wright)
7758 UPB_VARINT_DECODER_CHECK2(massimino, upb_vdecode_max8_massimino)
7759 #undef UPB_VARINT_DECODER_CHECK2
7760 
7761 /* Our canonical functions for decoding varints, based on the currently
7762  * favored best-performing implementations. */
7763 UPB_INLINE upb_decoderet upb_vdecode_fast(const char *p) {
7764   if (sizeof(long) == 8)
7765     return upb_vdecode_check2_branch64(p);
7766   else
7767     return upb_vdecode_check2_branch32(p);
7768 }
7769 
7770 UPB_INLINE upb_decoderet upb_vdecode_max8_fast(upb_decoderet r) {
7771   return upb_vdecode_max8_massimino(r);
7772 }
7773 
7774 
7775 /* Encoding *******************************************************************/
7776 
7777 UPB_INLINE int upb_value_size(uint64_t val) {
7778 #ifdef __GNUC__
7779   int high_bit = 63 - __builtin_clzll(val);  /* 0-based, undef if val == 0. */
7780 #else
7781   int high_bit = 0;
7782   uint64_t tmp = val;
7783   while(tmp >>= 1) high_bit++;
7784 #endif
7785   return val == 0 ? 1 : high_bit / 8 + 1;
7786 }
7787 
7788 /* Encodes a 64-bit varint into buf (which must be >=UPB_PB_VARINT_MAX_LEN
7789  * bytes long), returning how many bytes were used.
7790  *
7791  * TODO: benchmark and optimize if necessary. */
7792 UPB_INLINE size_t upb_vencode64(uint64_t val, char *buf) {
7793   size_t i;
7794   if (val == 0) { buf[0] = 0; return 1; }
7795   i = 0;
7796   while (val) {
7797     uint8_t byte = val & 0x7fU;
7798     val >>= 7;
7799     if (val) byte |= 0x80U;
7800     buf[i++] = byte;
7801   }
7802   return i;
7803 }
7804 
7805 UPB_INLINE size_t upb_varint_size(uint64_t val) {
7806   char buf[UPB_PB_VARINT_MAX_LEN];
7807   return upb_vencode64(val, buf);
7808 }
7809 
7810 /* Encodes a 32-bit varint, *not* sign-extended. */
7811 UPB_INLINE uint64_t upb_vencode32(uint32_t val) {
7812   char buf[UPB_PB_VARINT_MAX_LEN];
7813   size_t bytes = upb_vencode64(val, buf);
7814   uint64_t ret = 0;
7815   assert(bytes <= 5);
7816   memcpy(&ret, buf, bytes);
7817   assert(ret <= 0xffffffffffU);
7818   return ret;
7819 }
7820 
7821 #ifdef __cplusplus
7822 }  /* extern "C" */
7823 #endif
7824 
7825 #endif  /* UPB_VARINT_DECODER_H_ */
7826 /*
7827 ** upb::pb::Encoder (upb_pb_encoder)
7828 **
7829 ** Implements a set of upb_handlers that write protobuf data to the binary wire
7830 ** format.
7831 **
7832 ** This encoder implementation does not have any access to any out-of-band or
7833 ** precomputed lengths for submessages, so it must buffer submessages internally
7834 ** before it can emit the first byte.
7835 */
7836 
7837 #ifndef UPB_ENCODER_H_
7838 #define UPB_ENCODER_H_
7839 
7840 
7841 #ifdef __cplusplus
7842 namespace upb {
7843 namespace pb {
7844 class Encoder;
7845 }  /* namespace pb */
7846 }  /* namespace upb */
7847 #endif
7848 
7849 UPB_DECLARE_TYPE(upb::pb::Encoder, upb_pb_encoder)
7850 
7851 #define UPB_PBENCODER_MAX_NESTING 100
7852 
7853 /* upb::pb::Encoder ***********************************************************/
7854 
7855 /* Preallocation hint: decoder won't allocate more bytes than this when first
7856  * constructed.  This hint may be an overestimate for some build configurations.
7857  * But if the decoder library is upgraded without recompiling the application,
7858  * it may be an underestimate. */
7859 #define UPB_PB_ENCODER_SIZE 768
7860 
7861 #ifdef __cplusplus
7862 
7863 class upb::pb::Encoder {
7864  public:
7865   /* Creates a new encoder in the given environment.  The Handlers must have
7866    * come from NewHandlers() below. */
7867   static Encoder* Create(Environment* env, const Handlers* handlers,
7868                          BytesSink* output);
7869 
7870   /* The input to the encoder. */
7871   Sink* input();
7872 
7873   /* Creates a new set of handlers for this MessageDef. */
7874   static reffed_ptr<const Handlers> NewHandlers(const MessageDef* msg);
7875 
7876   static const size_t kSize = UPB_PB_ENCODER_SIZE;
7877 
7878  private:
7879   UPB_DISALLOW_POD_OPS(Encoder, upb::pb::Encoder)
7880 };
7881 
7882 #endif
7883 
7884 UPB_BEGIN_EXTERN_C
7885 
7886 const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
7887                                                const void *owner);
7888 upb_sink *upb_pb_encoder_input(upb_pb_encoder *p);
7889 upb_pb_encoder* upb_pb_encoder_create(upb_env* e, const upb_handlers* h,
7890                                       upb_bytessink* output);
7891 
7892 UPB_END_EXTERN_C
7893 
7894 #ifdef __cplusplus
7895 
7896 namespace upb {
7897 namespace pb {
7898 inline Encoder* Encoder::Create(Environment* env, const Handlers* handlers,
7899                                 BytesSink* output) {
7900   return upb_pb_encoder_create(env, handlers, output);
7901 }
7902 inline Sink* Encoder::input() {
7903   return upb_pb_encoder_input(this);
7904 }
7905 inline reffed_ptr<const Handlers> Encoder::NewHandlers(
7906     const upb::MessageDef *md) {
7907   const Handlers* h = upb_pb_encoder_newhandlers(md, &h);
7908   return reffed_ptr<const Handlers>(h, &h);
7909 }
7910 }  /* namespace pb */
7911 }  /* namespace upb */
7912 
7913 #endif
7914 
7915 #endif  /* UPB_ENCODER_H_ */
7916 /*
7917 ** upb's core components like upb_decoder and upb_msg are carefully designed to
7918 ** avoid depending on each other for maximum orthogonality.  In other words,
7919 ** you can use a upb_decoder to decode into *any* kind of structure; upb_msg is
7920 ** just one such structure.  A upb_msg can be serialized/deserialized into any
7921 ** format, protobuf binary format is just one such format.
7922 **
7923 ** However, for convenience we provide functions here for doing common
7924 ** operations like deserializing protobuf binary format into a upb_msg.  The
7925 ** compromise is that this file drags in almost all of upb as a dependency,
7926 ** which could be undesirable if you're trying to use a trimmed-down build of
7927 ** upb.
7928 **
7929 ** While these routines are convenient, they do not reuse any encoding/decoding
7930 ** state.  For example, if a decoder is JIT-based, it will be re-JITted every
7931 ** time these functions are called.  For this reason, if you are parsing lots
7932 ** of data and efficiency is an issue, these may not be the best functions to
7933 ** use (though they are useful for prototyping, before optimizing).
7934 */
7935 
7936 #ifndef UPB_GLUE_H
7937 #define UPB_GLUE_H
7938 
7939 #include <stdbool.h>
7940 
7941 #ifdef __cplusplus
7942 extern "C" {
7943 #endif
7944 
7945 /* Loads all defs from the given protobuf binary descriptor, setting default
7946  * accessors and a default layout on all messages.  The caller owns the
7947  * returned array of defs, which will be of length *n.  On error NULL is
7948  * returned and status is set (if non-NULL). */
7949 upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
7950                                         void *owner, upb_status *status);
7951 
7952 /* Like the previous but also adds the loaded defs to the given symtab. */
7953 bool upb_load_descriptor_into_symtab(upb_symtab *symtab, const char *str,
7954                                      size_t len, upb_status *status);
7955 
7956 /* Like the previous but also reads the descriptor from the given filename. */
7957 bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
7958                                           upb_status *status);
7959 
7960 /* Reads the given filename into a character string, returning NULL if there
7961  * was an error. */
7962 char *upb_readfile(const char *filename, size_t *len);
7963 
7964 #ifdef __cplusplus
7965 }  /* extern "C" */
7966 
7967 namespace upb {
7968 
7969 /* All routines that load descriptors expect the descriptor to be a
7970  * FileDescriptorSet. */
7971 inline bool LoadDescriptorFileIntoSymtab(SymbolTable* s, const char *fname,
7972                                          Status* status) {
7973   return upb_load_descriptor_file_into_symtab(s, fname, status);
7974 }
7975 
7976 inline bool LoadDescriptorIntoSymtab(SymbolTable* s, const char* str,
7977                                      size_t len, Status* status) {
7978   return upb_load_descriptor_into_symtab(s, str, len, status);
7979 }
7980 
7981 /* Templated so it can accept both string and std::string. */
7982 template <typename T>
7983 bool LoadDescriptorIntoSymtab(SymbolTable* s, const T& desc, Status* status) {
7984   return upb_load_descriptor_into_symtab(s, desc.c_str(), desc.size(), status);
7985 }
7986 
7987 }  /* namespace upb */
7988 
7989 #endif
7990 
7991 #endif  /* UPB_GLUE_H */
7992 /*
7993 ** upb::pb::TextPrinter (upb_textprinter)
7994 **
7995 ** Handlers for writing to protobuf text format.
7996 */
7997 
7998 #ifndef UPB_TEXT_H_
7999 #define UPB_TEXT_H_
8000 
8001 
8002 #ifdef __cplusplus
8003 namespace upb {
8004 namespace pb {
8005 class TextPrinter;
8006 }  /* namespace pb */
8007 }  /* namespace upb */
8008 #endif
8009 
8010 UPB_DECLARE_TYPE(upb::pb::TextPrinter, upb_textprinter)
8011 
8012 #ifdef __cplusplus
8013 
8014 class upb::pb::TextPrinter {
8015  public:
8016   /* The given handlers must have come from NewHandlers().  It must outlive the
8017    * TextPrinter. */
8018   static TextPrinter *Create(Environment *env, const upb::Handlers *handlers,
8019                              BytesSink *output);
8020 
8021   void SetSingleLineMode(bool single_line);
8022 
8023   Sink* input();
8024 
8025   /* If handler caching becomes a requirement we can add a code cache as in
8026    * decoder.h */
8027   static reffed_ptr<const Handlers> NewHandlers(const MessageDef* md);
8028 };
8029 
8030 #endif
8031 
8032 UPB_BEGIN_EXTERN_C
8033 
8034 /* C API. */
8035 upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
8036                                         upb_bytessink *output);
8037 void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line);
8038 upb_sink *upb_textprinter_input(upb_textprinter *p);
8039 
8040 const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
8041                                                 const void *owner);
8042 
8043 UPB_END_EXTERN_C
8044 
8045 #ifdef __cplusplus
8046 
8047 namespace upb {
8048 namespace pb {
8049 inline TextPrinter *TextPrinter::Create(Environment *env,
8050                                         const upb::Handlers *handlers,
8051                                         BytesSink *output) {
8052   return upb_textprinter_create(env, handlers, output);
8053 }
8054 inline void TextPrinter::SetSingleLineMode(bool single_line) {
8055   upb_textprinter_setsingleline(this, single_line);
8056 }
8057 inline Sink* TextPrinter::input() {
8058   return upb_textprinter_input(this);
8059 }
8060 inline reffed_ptr<const Handlers> TextPrinter::NewHandlers(
8061     const MessageDef *md) {
8062   const Handlers* h = upb_textprinter_newhandlers(md, &h);
8063   return reffed_ptr<const Handlers>(h, &h);
8064 }
8065 }  /* namespace pb */
8066 }  /* namespace upb */
8067 
8068 #endif
8069 
8070 #endif  /* UPB_TEXT_H_ */
8071 /*
8072 ** upb::json::Parser (upb_json_parser)
8073 **
8074 ** Parses JSON according to a specific schema.
8075 ** Support for parsing arbitrary JSON (schema-less) will be added later.
8076 */
8077 
8078 #ifndef UPB_JSON_PARSER_H_
8079 #define UPB_JSON_PARSER_H_
8080 
8081 
8082 #ifdef __cplusplus
8083 namespace upb {
8084 namespace json {
8085 class Parser;
8086 }  /* namespace json */
8087 }  /* namespace upb */
8088 #endif
8089 
8090 UPB_DECLARE_TYPE(upb::json::Parser, upb_json_parser)
8091 
8092 /* upb::json::Parser **********************************************************/
8093 
8094 /* Preallocation hint: parser won't allocate more bytes than this when first
8095  * constructed.  This hint may be an overestimate for some build configurations.
8096  * But if the parser library is upgraded without recompiling the application,
8097  * it may be an underestimate. */
8098 #define UPB_JSON_PARSER_SIZE 3704
8099 
8100 #ifdef __cplusplus
8101 
8102 /* Parses an incoming BytesStream, pushing the results to the destination
8103  * sink. */
8104 class upb::json::Parser {
8105  public:
8106   static Parser* Create(Environment* env, Sink* output);
8107 
8108   BytesSink* input();
8109 
8110  private:
8111   UPB_DISALLOW_POD_OPS(Parser, upb::json::Parser)
8112 };
8113 
8114 #endif
8115 
8116 UPB_BEGIN_EXTERN_C
8117 
8118 upb_json_parser *upb_json_parser_create(upb_env *e, upb_sink *output);
8119 upb_bytessink *upb_json_parser_input(upb_json_parser *p);
8120 
8121 UPB_END_EXTERN_C
8122 
8123 #ifdef __cplusplus
8124 
8125 namespace upb {
8126 namespace json {
8127 inline Parser* Parser::Create(Environment* env, Sink* output) {
8128   return upb_json_parser_create(env, output);
8129 }
8130 inline BytesSink* Parser::input() {
8131   return upb_json_parser_input(this);
8132 }
8133 }  /* namespace json */
8134 }  /* namespace upb */
8135 
8136 #endif
8137 
8138 
8139 #endif  /* UPB_JSON_PARSER_H_ */
8140 /*
8141 ** upb::json::Printer
8142 **
8143 ** Handlers that emit JSON according to a specific protobuf schema.
8144 */
8145 
8146 #ifndef UPB_JSON_TYPED_PRINTER_H_
8147 #define UPB_JSON_TYPED_PRINTER_H_
8148 
8149 
8150 #ifdef __cplusplus
8151 namespace upb {
8152 namespace json {
8153 class Printer;
8154 }  /* namespace json */
8155 }  /* namespace upb */
8156 #endif
8157 
8158 UPB_DECLARE_TYPE(upb::json::Printer, upb_json_printer)
8159 
8160 
8161 /* upb::json::Printer *********************************************************/
8162 
8163 #define UPB_JSON_PRINTER_SIZE 168
8164 
8165 #ifdef __cplusplus
8166 
8167 /* Prints an incoming stream of data to a BytesSink in JSON format. */
8168 class upb::json::Printer {
8169  public:
8170   static Printer* Create(Environment* env, const upb::Handlers* handlers,
8171                          BytesSink* output);
8172 
8173   /* The input to the printer. */
8174   Sink* input();
8175 
8176   /* Returns handlers for printing according to the specified schema. */
8177   static reffed_ptr<const Handlers> NewHandlers(const upb::MessageDef* md);
8178 
8179   static const size_t kSize = UPB_JSON_PRINTER_SIZE;
8180 
8181  private:
8182   UPB_DISALLOW_POD_OPS(Printer, upb::json::Printer)
8183 };
8184 
8185 #endif
8186 
8187 UPB_BEGIN_EXTERN_C
8188 
8189 /* Native C API. */
8190 upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
8191                                           upb_bytessink *output);
8192 upb_sink *upb_json_printer_input(upb_json_printer *p);
8193 const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
8194                                                  const void *owner);
8195 
8196 UPB_END_EXTERN_C
8197 
8198 #ifdef __cplusplus
8199 
8200 namespace upb {
8201 namespace json {
8202 inline Printer* Printer::Create(Environment* env, const upb::Handlers* handlers,
8203                                 BytesSink* output) {
8204   return upb_json_printer_create(env, handlers, output);
8205 }
8206 inline Sink* Printer::input() { return upb_json_printer_input(this); }
8207 inline reffed_ptr<const Handlers> Printer::NewHandlers(
8208     const upb::MessageDef *md) {
8209   const Handlers* h = upb_json_printer_newhandlers(md, &h);
8210   return reffed_ptr<const Handlers>(h, &h);
8211 }
8212 }  /* namespace json */
8213 }  /* namespace upb */
8214 
8215 #endif
8216 
8217 #endif  /* UPB_JSON_TYPED_PRINTER_H_ */
8218