def.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // Copyright (c) 2009-2021, Google LLC
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are met:
  6. // * Redistributions of source code must retain the above copyright
  7. // notice, this list of conditions and the following disclaimer.
  8. // * Redistributions in binary form must reproduce the above copyright
  9. // notice, this list of conditions and the following disclaimer in the
  10. // documentation and/or other materials provided with the distribution.
  11. // * Neither the name of Google LLC nor the
  12. // names of its contributors may be used to endorse or promote products
  13. // derived from this software without specific prior written permission.
  14. //
  15. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  16. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. // DISCLAIMED. IN NO EVENT SHALL Google LLC BE LIABLE FOR ANY
  19. // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. #ifndef UPB_DEF_HPP_
  26. #define UPB_DEF_HPP_
  27. #include <cstring>
  28. #include <memory>
  29. #include <string>
  30. #include <vector>
  31. #include "upb/def.h"
  32. #include "upb/reflection.h"
  33. #include "upb/upb.hpp"
  34. namespace upb {
  35. typedef upb_msgval MessageValue;
  36. class EnumDefPtr;
  37. class MessageDefPtr;
  38. class OneofDefPtr;
  39. // A upb::FieldDefPtr describes a single field in a message. It is most often
  40. // found as a part of a upb_msgdef, but can also stand alone to represent
  41. // an extension.
  42. class FieldDefPtr {
  43. public:
  44. FieldDefPtr() : ptr_(nullptr) {}
  45. explicit FieldDefPtr(const upb_fielddef* ptr) : ptr_(ptr) {}
  46. const upb_fielddef* ptr() const { return ptr_; }
  47. explicit operator bool() const { return ptr_ != nullptr; }
  48. typedef upb_fieldtype_t Type;
  49. typedef upb_label_t Label;
  50. typedef upb_descriptortype_t DescriptorType;
  51. const char* full_name() const { return upb_fielddef_fullname(ptr_); }
  52. Type type() const { return upb_fielddef_type(ptr_); }
  53. Label label() const { return upb_fielddef_label(ptr_); }
  54. const char* name() const { return upb_fielddef_name(ptr_); }
  55. const char* json_name() const { return upb_fielddef_jsonname(ptr_); }
  56. uint32_t number() const { return upb_fielddef_number(ptr_); }
  57. bool is_extension() const { return upb_fielddef_isextension(ptr_); }
  58. // For UPB_TYPE_MESSAGE fields only where is_tag_delimited() == false,
  59. // indicates whether this field should have lazy parsing handlers that yield
  60. // the unparsed string for the submessage.
  61. //
  62. // TODO(haberman): I think we want to move this into a FieldOptions container
  63. // when we add support for custom options (the FieldOptions struct will
  64. // contain both regular FieldOptions like "lazy" *and* custom options).
  65. bool lazy() const { return upb_fielddef_lazy(ptr_); }
  66. // For non-string, non-submessage fields, this indicates whether binary
  67. // protobufs are encoded in packed or non-packed format.
  68. //
  69. // TODO(haberman): see note above about putting options like this into a
  70. // FieldOptions container.
  71. bool packed() const { return upb_fielddef_packed(ptr_); }
  72. // An integer that can be used as an index into an array of fields for
  73. // whatever message this field belongs to. Guaranteed to be less than
  74. // f->containing_type()->field_count(). May only be accessed once the def has
  75. // been finalized.
  76. uint32_t index() const { return upb_fielddef_index(ptr_); }
  77. // The MessageDef to which this field belongs.
  78. //
  79. // If this field has been added to a MessageDef, that message can be retrieved
  80. // directly (this is always the case for frozen FieldDefs).
  81. //
  82. // If the field has not yet been added to a MessageDef, you can set the name
  83. // of the containing type symbolically instead. This is mostly useful for
  84. // extensions, where the extension is declared separately from the message.
  85. MessageDefPtr containing_type() const;
  86. // The OneofDef to which this field belongs, or NULL if this field is not part
  87. // of a oneof.
  88. OneofDefPtr containing_oneof() const;
  89. // The field's type according to the enum in descriptor.proto. This is not
  90. // the same as UPB_TYPE_*, because it distinguishes between (for example)
  91. // INT32 and SINT32, whereas our "type" enum does not. This return of
  92. // descriptor_type() is a function of type(), integer_format(), and
  93. // is_tag_delimited().
  94. DescriptorType descriptor_type() const {
  95. return upb_fielddef_descriptortype(ptr_);
  96. }
  97. // Convenient field type tests.
  98. bool IsSubMessage() const { return upb_fielddef_issubmsg(ptr_); }
  99. bool IsString() const { return upb_fielddef_isstring(ptr_); }
  100. bool IsSequence() const { return upb_fielddef_isseq(ptr_); }
  101. bool IsPrimitive() const { return upb_fielddef_isprimitive(ptr_); }
  102. bool IsMap() const { return upb_fielddef_ismap(ptr_); }
  103. // Returns the non-string default value for this fielddef, which may either
  104. // be something the client set explicitly or the "default default" (0 for
  105. // numbers, empty for strings). The field's type indicates the type of the
  106. // returned value, except for enum fields that are still mutable.
  107. //
  108. // Requires that the given function matches the field's current type.
  109. int64_t default_int64() const { return upb_fielddef_defaultint64(ptr_); }
  110. int32_t default_int32() const { return upb_fielddef_defaultint32(ptr_); }
  111. uint64_t default_uint64() const { return upb_fielddef_defaultuint64(ptr_); }
  112. uint32_t default_uint32() const { return upb_fielddef_defaultuint32(ptr_); }
  113. bool default_bool() const { return upb_fielddef_defaultbool(ptr_); }
  114. float default_float() const { return upb_fielddef_defaultfloat(ptr_); }
  115. double default_double() const { return upb_fielddef_defaultdouble(ptr_); }
  116. MessageValue default_value() const { return upb_fielddef_default(ptr_); }
  117. // The resulting string is always NULL-terminated. If non-NULL, the length
  118. // will be stored in *len.
  119. const char* default_string(size_t* len) const {
  120. return upb_fielddef_defaultstr(ptr_, len);
  121. }
  122. // Returns the enum or submessage def for this field, if any. The field's
  123. // type must match (ie. you may only call enum_subdef() for fields where
  124. // type() == UPB_TYPE_ENUM).
  125. EnumDefPtr enum_subdef() const;
  126. MessageDefPtr message_subdef() const;
  127. private:
  128. const upb_fielddef* ptr_;
  129. };
  130. // Class that represents a oneof.
  131. class OneofDefPtr {
  132. public:
  133. OneofDefPtr() : ptr_(nullptr) {}
  134. explicit OneofDefPtr(const upb_oneofdef* ptr) : ptr_(ptr) {}
  135. const upb_oneofdef* ptr() const { return ptr_; }
  136. explicit operator bool() const { return ptr_ != nullptr; }
  137. // Returns the MessageDef that contains this OneofDef.
  138. MessageDefPtr containing_type() const;
  139. // Returns the name of this oneof.
  140. const char* name() const { return upb_oneofdef_name(ptr_); }
  141. // Returns the number of fields in the oneof.
  142. int field_count() const { return upb_oneofdef_numfields(ptr_); }
  143. FieldDefPtr field(int i) const { return FieldDefPtr(upb_oneofdef_field(ptr_, i)); }
  144. // Looks up by name.
  145. FieldDefPtr FindFieldByName(const char* name, size_t len) const {
  146. return FieldDefPtr(upb_oneofdef_ntof(ptr_, name, len));
  147. }
  148. FieldDefPtr FindFieldByName(const char* name) const {
  149. return FieldDefPtr(upb_oneofdef_ntofz(ptr_, name));
  150. }
  151. template <class T>
  152. FieldDefPtr FindFieldByName(const T& str) const {
  153. return FindFieldByName(str.c_str(), str.size());
  154. }
  155. // Looks up by tag number.
  156. FieldDefPtr FindFieldByNumber(uint32_t num) const {
  157. return FieldDefPtr(upb_oneofdef_itof(ptr_, num));
  158. }
  159. private:
  160. const upb_oneofdef* ptr_;
  161. };
  162. // Structure that describes a single .proto message type.
  163. class MessageDefPtr {
  164. public:
  165. MessageDefPtr() : ptr_(nullptr) {}
  166. explicit MessageDefPtr(const upb_msgdef* ptr) : ptr_(ptr) {}
  167. const upb_msgdef* ptr() const { return ptr_; }
  168. explicit operator bool() const { return ptr_ != nullptr; }
  169. const char* full_name() const { return upb_msgdef_fullname(ptr_); }
  170. const char* name() const { return upb_msgdef_name(ptr_); }
  171. // The number of fields that belong to the MessageDef.
  172. int field_count() const { return upb_msgdef_numfields(ptr_); }
  173. FieldDefPtr field(int i) const { return FieldDefPtr(upb_msgdef_field(ptr_, i)); }
  174. // The number of oneofs that belong to the MessageDef.
  175. int oneof_count() const { return upb_msgdef_numoneofs(ptr_); }
  176. OneofDefPtr oneof(int i) const { return OneofDefPtr(upb_msgdef_oneof(ptr_, i)); }
  177. upb_syntax_t syntax() const { return upb_msgdef_syntax(ptr_); }
  178. // These return null pointers if the field is not found.
  179. FieldDefPtr FindFieldByNumber(uint32_t number) const {
  180. return FieldDefPtr(upb_msgdef_itof(ptr_, number));
  181. }
  182. FieldDefPtr FindFieldByName(const char* name, size_t len) const {
  183. return FieldDefPtr(upb_msgdef_ntof(ptr_, name, len));
  184. }
  185. FieldDefPtr FindFieldByName(const char* name) const {
  186. return FieldDefPtr(upb_msgdef_ntofz(ptr_, name));
  187. }
  188. template <class T>
  189. FieldDefPtr FindFieldByName(const T& str) const {
  190. return FindFieldByName(str.c_str(), str.size());
  191. }
  192. OneofDefPtr FindOneofByName(const char* name, size_t len) const {
  193. return OneofDefPtr(upb_msgdef_ntoo(ptr_, name, len));
  194. }
  195. OneofDefPtr FindOneofByName(const char* name) const {
  196. return OneofDefPtr(upb_msgdef_ntooz(ptr_, name));
  197. }
  198. template <class T>
  199. OneofDefPtr FindOneofByName(const T& str) const {
  200. return FindOneofByName(str.c_str(), str.size());
  201. }
  202. // Is this message a map entry?
  203. bool mapentry() const { return upb_msgdef_mapentry(ptr_); }
  204. // Return the type of well known type message. UPB_WELLKNOWN_UNSPECIFIED for
  205. // non-well-known message.
  206. upb_wellknowntype_t wellknowntype() const {
  207. return upb_msgdef_wellknowntype(ptr_);
  208. }
  209. // Whether is a number wrapper.
  210. bool isnumberwrapper() const { return upb_msgdef_isnumberwrapper(ptr_); }
  211. private:
  212. class FieldIter {
  213. public:
  214. explicit FieldIter(const upb_msgdef *m, int i) : m_(m), i_(i) {}
  215. void operator++() { i_++; }
  216. FieldDefPtr operator*() { return FieldDefPtr(upb_msgdef_field(m_, i_)); }
  217. bool operator!=(const FieldIter& other) { return i_ != other.i_; }
  218. bool operator==(const FieldIter& other) { return i_ == other.i_; }
  219. private:
  220. const upb_msgdef *m_;
  221. int i_;
  222. };
  223. class FieldAccessor {
  224. public:
  225. explicit FieldAccessor(const upb_msgdef* md) : md_(md) {}
  226. FieldIter begin() { return FieldIter(md_, 0); }
  227. FieldIter end() { return FieldIter(md_, upb_msgdef_fieldcount(md_)); }
  228. private:
  229. const upb_msgdef* md_;
  230. };
  231. class OneofIter {
  232. public:
  233. explicit OneofIter(const upb_msgdef *m, int i) : m_(m), i_(i) {}
  234. void operator++() { i_++; }
  235. OneofDefPtr operator*() { return OneofDefPtr(upb_msgdef_oneof(m_, i_)); }
  236. bool operator!=(const OneofIter& other) { return i_ != other.i_; }
  237. bool operator==(const OneofIter& other) { return i_ == other.i_; }
  238. private:
  239. const upb_msgdef *m_;
  240. int i_;
  241. };
  242. class OneofAccessor {
  243. public:
  244. explicit OneofAccessor(const upb_msgdef* md) : md_(md) {}
  245. OneofIter begin() { return OneofIter(md_, 0); }
  246. OneofIter end() { return OneofIter(md_, upb_msgdef_oneofcount(md_)); }
  247. private:
  248. const upb_msgdef* md_;
  249. };
  250. public:
  251. FieldAccessor fields() const { return FieldAccessor(ptr()); }
  252. OneofAccessor oneofs() const { return OneofAccessor(ptr()); }
  253. private:
  254. const upb_msgdef* ptr_;
  255. };
  256. class EnumValDefPtr {
  257. public:
  258. EnumValDefPtr() : ptr_(nullptr) {}
  259. explicit EnumValDefPtr(const upb_enumvaldef* ptr) : ptr_(ptr) {}
  260. int32_t number() const { return upb_enumvaldef_number(ptr_); }
  261. const char *full_name() const { return upb_enumvaldef_fullname(ptr_); }
  262. const char *name() const { return upb_enumvaldef_name(ptr_); }
  263. private:
  264. const upb_enumvaldef* ptr_;
  265. };
  266. class EnumDefPtr {
  267. public:
  268. EnumDefPtr() : ptr_(nullptr) {}
  269. explicit EnumDefPtr(const upb_enumdef* ptr) : ptr_(ptr) {}
  270. const upb_enumdef* ptr() const { return ptr_; }
  271. explicit operator bool() const { return ptr_ != nullptr; }
  272. const char* full_name() const { return upb_enumdef_fullname(ptr_); }
  273. const char* name() const { return upb_enumdef_name(ptr_); }
  274. // The value that is used as the default when no field default is specified.
  275. // If not set explicitly, the first value that was added will be used.
  276. // The default value must be a member of the enum.
  277. // Requires that value_count() > 0.
  278. int32_t default_value() const { return upb_enumdef_default(ptr_); }
  279. // Returns the number of values currently defined in the enum. Note that
  280. // multiple names can refer to the same number, so this may be greater than
  281. // the total number of unique numbers.
  282. int value_count() const { return upb_enumdef_numvals(ptr_); }
  283. // Lookups from name to integer, returning true if found.
  284. EnumValDefPtr FindValueByName(const char* name) const {
  285. return EnumValDefPtr(upb_enumdef_lookupnamez(ptr_, name));
  286. }
  287. // Finds the name corresponding to the given number, or NULL if none was
  288. // found. If more than one name corresponds to this number, returns the
  289. // first one that was added.
  290. EnumValDefPtr FindValueByNumber(int32_t num) const {
  291. return EnumValDefPtr(upb_enumdef_lookupnum(ptr_, num));
  292. }
  293. // Iteration over name/value pairs. The order is undefined.
  294. // Adding an enum val invalidates any iterators.
  295. //
  296. // TODO: make compatible with range-for, with elements as pairs?
  297. class Iterator {
  298. public:
  299. explicit Iterator(EnumDefPtr e) { upb_enum_begin(&iter_, e.ptr()); }
  300. int32_t number() { return upb_enum_iter_number(&iter_); }
  301. const char* name() { return upb_enum_iter_name(&iter_); }
  302. bool Done() { return upb_enum_done(&iter_); }
  303. void Next() { return upb_enum_next(&iter_); }
  304. private:
  305. upb_enum_iter iter_;
  306. };
  307. private:
  308. const upb_enumdef* ptr_;
  309. };
  310. // Class that represents a .proto file with some things defined in it.
  311. //
  312. // Many users won't care about FileDefs, but they are necessary if you want to
  313. // read the values of file-level options.
  314. class FileDefPtr {
  315. public:
  316. explicit FileDefPtr(const upb_filedef* ptr) : ptr_(ptr) {}
  317. const upb_filedef* ptr() const { return ptr_; }
  318. explicit operator bool() const { return ptr_ != nullptr; }
  319. // Get/set name of the file (eg. "foo/bar.proto").
  320. const char* name() const { return upb_filedef_name(ptr_); }
  321. // Package name for definitions inside the file (eg. "foo.bar").
  322. const char* package() const { return upb_filedef_package(ptr_); }
  323. // Sets the php class prefix which is prepended to all php generated classes
  324. // from this .proto. Default is empty.
  325. const char* phpprefix() const { return upb_filedef_phpprefix(ptr_); }
  326. // Use this option to change the namespace of php generated classes. Default
  327. // is empty. When this option is empty, the package name will be used for
  328. // determining the namespace.
  329. const char* phpnamespace() const { return upb_filedef_phpnamespace(ptr_); }
  330. // Syntax for the file. Defaults to proto2.
  331. upb_syntax_t syntax() const { return upb_filedef_syntax(ptr_); }
  332. // Get the list of dependencies from the file. These are returned in the
  333. // order that they were added to the FileDefPtr.
  334. int dependency_count() const { return upb_filedef_depcount(ptr_); }
  335. const FileDefPtr dependency(int index) const {
  336. return FileDefPtr(upb_filedef_dep(ptr_, index));
  337. }
  338. private:
  339. const upb_filedef* ptr_;
  340. };
  341. // Non-const methods in upb::SymbolTable are NOT thread-safe.
  342. class SymbolTable {
  343. public:
  344. SymbolTable() : ptr_(upb_symtab_new(), upb_symtab_free) {}
  345. explicit SymbolTable(upb_symtab* s) : ptr_(s, upb_symtab_free) {}
  346. const upb_symtab* ptr() const { return ptr_.get(); }
  347. upb_symtab* ptr() { return ptr_.get(); }
  348. // Finds an entry in the symbol table with this exact name. If not found,
  349. // returns NULL.
  350. MessageDefPtr LookupMessage(const char* sym) const {
  351. return MessageDefPtr(upb_symtab_lookupmsg(ptr_.get(), sym));
  352. }
  353. EnumDefPtr LookupEnum(const char* sym) const {
  354. return EnumDefPtr(upb_symtab_lookupenum(ptr_.get(), sym));
  355. }
  356. FileDefPtr LookupFile(const char* name) const {
  357. return FileDefPtr(upb_symtab_lookupfile(ptr_.get(), name));
  358. }
  359. // TODO: iteration?
  360. // Adds the given serialized FileDescriptorProto to the pool.
  361. FileDefPtr AddFile(const google_protobuf_FileDescriptorProto* file_proto,
  362. Status* status) {
  363. return FileDefPtr(
  364. upb_symtab_addfile(ptr_.get(), file_proto, status->ptr()));
  365. }
  366. private:
  367. std::unique_ptr<upb_symtab, decltype(&upb_symtab_free)> ptr_;
  368. };
  369. inline MessageDefPtr FieldDefPtr::message_subdef() const {
  370. return MessageDefPtr(upb_fielddef_msgsubdef(ptr_));
  371. }
  372. inline MessageDefPtr FieldDefPtr::containing_type() const {
  373. return MessageDefPtr(upb_fielddef_containingtype(ptr_));
  374. }
  375. inline MessageDefPtr OneofDefPtr::containing_type() const {
  376. return MessageDefPtr(upb_oneofdef_containingtype(ptr_));
  377. }
  378. inline OneofDefPtr FieldDefPtr::containing_oneof() const {
  379. return OneofDefPtr(upb_fielddef_containingoneof(ptr_));
  380. }
  381. inline EnumDefPtr FieldDefPtr::enum_subdef() const {
  382. return EnumDefPtr(upb_fielddef_enumsubdef(ptr_));
  383. }
  384. } // namespace upb
  385. #endif // UPB_DEF_HPP_