diff options
author | Derek Bailey <derekbailey@google.com> | 2019-11-07 12:22:54 -0800 |
---|---|---|
committer | Wouter van Oortmerssen <aardappel@gmail.com> | 2019-11-07 12:22:54 -0800 |
commit | f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4 (patch) | |
tree | eb0c5f977400166f7c6f8067d7764d9753aa1ea3 | |
parent | e837d5a296c725d141802777808aaff944e7b427 (diff) | |
download | flatbuffers-f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4.tar.gz flatbuffers-f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4.tar.bz2 flatbuffers-f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4.zip |
[C++] Refactor to conform to Google C++ style guide (#5608)
* Automatic refractor of C++ headers to Google C++ style guide
* Automatic refractor of C++ source to Google C++ style guide
* Automatic refractor of C++ tests to Google C++ style guide
* Fixed clang-format issues by running clang-format twice to correct itself. Kotlin was missing clang-format on after turning it off, so it was changed,
36 files changed, 3118 insertions, 3255 deletions
diff --git a/include/flatbuffers/code_generators.h b/include/flatbuffers/code_generators.h index 0bcec910..618e4978 100644 --- a/include/flatbuffers/code_generators.h +++ b/include/flatbuffers/code_generators.h @@ -19,6 +19,7 @@ #include <map> #include <sstream> + #include "flatbuffers/idl.h" namespace flatbuffers { @@ -95,8 +96,7 @@ class BaseGenerator { protected: BaseGenerator(const Parser &parser, const std::string &path, - const std::string &file_name, - std::string qualifying_start, + const std::string &file_name, std::string qualifying_start, std::string qualifying_separator) : parser_(parser), path_(path), diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 250db7c3..5c846a6d 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -20,7 +20,7 @@ #include "flatbuffers/base.h" #if defined(FLATBUFFERS_NAN_DEFAULTS) -#include <cmath> +# include <cmath> #endif namespace flatbuffers { @@ -203,11 +203,10 @@ template<typename T, typename IT> struct VectorIterator { const uint8_t *data_; }; -template<typename Iterator> struct VectorReverseIterator : - public std::reverse_iterator<Iterator> { - - explicit VectorReverseIterator(Iterator iter) : - std::reverse_iterator<Iterator>(iter) {} +template<typename Iterator> +struct VectorReverseIterator : public std::reverse_iterator<Iterator> { + explicit VectorReverseIterator(Iterator iter) + : std::reverse_iterator<Iterator>(iter) {} typename Iterator::value_type operator*() const { return *(std::reverse_iterator<Iterator>::current); @@ -277,10 +276,14 @@ template<typename T> class Vector { const_iterator end() const { return const_iterator(Data(), size()); } reverse_iterator rbegin() { return reverse_iterator(end() - 1); } - const_reverse_iterator rbegin() const { return const_reverse_iterator(end() - 1); } + const_reverse_iterator rbegin() const { + return const_reverse_iterator(end() - 1); + } reverse_iterator rend() { return reverse_iterator(begin() - 1); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin() - 1); } + const_reverse_iterator rend() const { + return const_reverse_iterator(begin() - 1); + } const_iterator cbegin() const { return begin(); } @@ -403,7 +406,8 @@ template<typename T> static inline size_t VectorLength(const Vector<T> *v) { // This is used as a helper type for accessing arrays. template<typename T, uint16_t length> class Array { typedef - typename flatbuffers::integral_constant<bool, flatbuffers::is_scalar<T>::value> + typename flatbuffers::integral_constant<bool, + flatbuffers::is_scalar<T>::value> scalar_tag; typedef typename flatbuffers::conditional<scalar_tag::value, T, const T *>::type @@ -449,9 +453,7 @@ template<typename T, uint16_t length> class Array { } // Change elements if you have a non-const pointer to this object. - void Mutate(uoffset_t i, const T &val) { - MutateImpl(scalar_tag(), i, val); - } + void Mutate(uoffset_t i, const T &val) { MutateImpl(scalar_tag(), i, val); } // The raw data in little endian format. Use with care. const uint8_t *Data() const { return data_; } @@ -544,13 +546,13 @@ struct String : public Vector<char> { // Convenience function to get std::string from a String returning an empty // string on null pointer. -static inline std::string GetString(const String * str) { +static inline std::string GetString(const String *str) { return str ? str->str() : ""; } // Convenience function to get char* from a String returning an empty string on // null pointer. -static inline const char * GetCstring(const String * str) { +static inline const char *GetCstring(const String *str) { return str ? str->c_str() : ""; } @@ -587,9 +589,9 @@ class Allocator { // to `new_p` of `new_size`. Only memory of size `in_use_front` and // `in_use_back` will be copied from the front and back of the old memory // allocation. - void memcpy_downward(uint8_t *old_p, size_t old_size, - uint8_t *new_p, size_t new_size, - size_t in_use_back, size_t in_use_front) { + void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p, + size_t new_size, size_t in_use_back, + size_t in_use_front) { memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back, in_use_back); memcpy(new_p, old_p, in_use_front); @@ -603,13 +605,9 @@ class DefaultAllocator : public Allocator { return new uint8_t[size]; } - void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { - delete[] p; - } + void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; } - static void dealloc(void *p, size_t) { - delete[] static_cast<uint8_t *>(p); - } + static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); } }; // These functions allow for a null allocator to mean use the default allocator, @@ -622,18 +620,19 @@ inline uint8_t *Allocate(Allocator *allocator, size_t size) { } inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) { - if (allocator) allocator->deallocate(p, size); - else DefaultAllocator().deallocate(p, size); + if (allocator) + allocator->deallocate(p, size); + else + DefaultAllocator().deallocate(p, size); } inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p, size_t old_size, size_t new_size, size_t in_use_back, size_t in_use_front) { - return allocator - ? allocator->reallocate_downward(old_p, old_size, new_size, - in_use_back, in_use_front) - : DefaultAllocator().reallocate_downward(old_p, old_size, new_size, - in_use_back, in_use_front); + return allocator ? allocator->reallocate_downward(old_p, old_size, new_size, + in_use_back, in_use_front) + : DefaultAllocator().reallocate_downward( + old_p, old_size, new_size, in_use_back, in_use_front); } // DetachedBuffer is a finished flatbuffer memory region, detached from its @@ -678,8 +677,7 @@ class DetachedBuffer { #if !defined(FLATBUFFERS_CPP98_STL) // clang-format on DetachedBuffer &operator=(DetachedBuffer &&other) { - if (this == &other) - return *this; + if (this == &other) return *this; destroy(); @@ -737,7 +735,7 @@ class DetachedBuffer { #endif // !defined(FLATBUFFERS_CPP98_STL) // clang-format on -protected: + protected: Allocator *allocator_; bool own_allocator_; uint8_t *buf_; @@ -769,10 +767,8 @@ protected: // Essentially, this supports 2 std::vectors in a single buffer. class vector_downward { public: - explicit vector_downward(size_t initial_size, - Allocator *allocator, - bool own_allocator, - size_t buffer_minalign) + explicit vector_downward(size_t initial_size, Allocator *allocator, + bool own_allocator, size_t buffer_minalign) : allocator_(allocator), own_allocator_(own_allocator), initial_size_(initial_size), @@ -788,15 +784,15 @@ class vector_downward { #else vector_downward(vector_downward &other) #endif // defined(FLATBUFFERS_CPP98_STL) - // clang-format on - : allocator_(other.allocator_), - own_allocator_(other.own_allocator_), - initial_size_(other.initial_size_), - buffer_minalign_(other.buffer_minalign_), - reserved_(other.reserved_), - buf_(other.buf_), - cur_(other.cur_), - scratch_(other.scratch_) { + // clang-format on + : allocator_(other.allocator_), + own_allocator_(other.own_allocator_), + initial_size_(other.initial_size_), + buffer_minalign_(other.buffer_minalign_), + reserved_(other.reserved_), + buf_(other.buf_), + cur_(other.cur_), + scratch_(other.scratch_) { // No change in other.allocator_ // No change in other.initial_size_ // No change in other.buffer_minalign_ @@ -840,9 +836,7 @@ class vector_downward { clear_scratch(); } - void clear_scratch() { - scratch_ = buf_; - } + void clear_scratch() { scratch_ = buf_; } void clear_allocator() { if (own_allocator_ && allocator_) { delete allocator_; } @@ -995,8 +989,8 @@ class vector_downward { auto old_reserved = reserved_; auto old_size = size(); auto old_scratch_size = scratch_size(); - reserved_ += (std::max)(len, - old_reserved ? old_reserved / 2 : initial_size_); + reserved_ += + (std::max)(len, old_reserved ? old_reserved / 2 : initial_size_); reserved_ = (reserved_ + buffer_minalign_ - 1) & ~(buffer_minalign_ - 1); if (buf_) { buf_ = ReallocateDownward(allocator_, buf_, old_reserved, reserved_, @@ -1021,13 +1015,13 @@ const T *data(const std::vector<T, Alloc> &v) { // Eventually the returned pointer gets passed down to memcpy, so // we need it to be non-null to avoid undefined behavior. static uint8_t t; - return v.empty() ? reinterpret_cast<const T*>(&t) : &v.front(); + return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front(); } template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) { // Eventually the returned pointer gets passed down to memcpy, so // we need it to be non-null to avoid undefined behavior. static uint8_t t; - return v.empty() ? reinterpret_cast<T*>(&t) : &v.front(); + return v.empty() ? reinterpret_cast<T *>(&t) : &v.front(); } /// @endcond @@ -1054,11 +1048,10 @@ class FlatBufferBuilder { /// minimum alignment upon reallocation. Only needed if you intend to store /// types with custom alignment AND you wish to read the buffer in-place /// directly after creation. - explicit FlatBufferBuilder(size_t initial_size = 1024, - Allocator *allocator = nullptr, - bool own_allocator = false, - size_t buffer_minalign = - AlignOf<largest_scalar_t>()) + explicit FlatBufferBuilder( + size_t initial_size = 1024, Allocator *allocator = nullptr, + bool own_allocator = false, + size_t buffer_minalign = AlignOf<largest_scalar_t>()) : buf_(initial_size, allocator, own_allocator, buffer_minalign), num_field_loc(0), max_voffset_(0), @@ -1161,8 +1154,8 @@ class FlatBufferBuilder { /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards! /// @return A `FlatBuffer` that owns the buffer and its allocator and /// behaves similar to a `unique_ptr` with a deleter. - FLATBUFFERS_ATTRIBUTE(deprecated("use Release() instead")) DetachedBuffer - ReleaseBufferPointer() { + FLATBUFFERS_ATTRIBUTE(deprecated("use Release() instead")) + DetachedBuffer ReleaseBufferPointer() { Finished(); return buf_.release(); } @@ -1181,7 +1174,8 @@ class FlatBufferBuilder { /// `FlatBuffer` starts. /// @return A raw pointer to the start of the memory block containing /// the serialized `FlatBuffer`. - /// @remark If the allocator is owned, it gets deleted when the destructor is called.. + /// @remark If the allocator is owned, it gets deleted when the destructor is + /// called.. uint8_t *ReleaseRaw(size_t &size, size_t &offset) { Finished(); return buf_.release_raw(size, offset); @@ -1210,8 +1204,9 @@ class FlatBufferBuilder { /// @brief In order to save space, fields that are set to their default value /// don't get serialized into the buffer. - /// @param[in] fd When set to `true`, always serializes default values that are set. - /// Optional fields which are not set explicitly, will still not be serialized. + /// @param[in] fd When set to `true`, always serializes default values that + /// are set. Optional fields which are not set explicitly, will still not be + /// serialized. void ForceDefaults(bool fd) { force_defaults_ = fd; } /// @brief By default vtables are deduped in order to save space. @@ -1835,7 +1830,7 @@ class FlatBufferBuilder { extern T Pack(const S &); typedef T (*Pack_t)(const S &); std::vector<T> vv(len); - std::transform(v, v + len, vv.begin(), static_cast<Pack_t&>(Pack)); + std::transform(v, v + len, vv.begin(), static_cast<Pack_t &>(Pack)); return CreateVectorOfSortedStructs<T>(vv, len); } @@ -1916,12 +1911,12 @@ class FlatBufferBuilder { } template<typename T> - Offset<Vector<const T*>> CreateUninitializedVectorOfStructs(size_t len, T **buf) { + Offset<Vector<const T *>> CreateUninitializedVectorOfStructs(size_t len, + T **buf) { return CreateUninitializedVector(len, sizeof(T), reinterpret_cast<uint8_t **>(buf)); } - // @brief Create a vector of scalar type T given as input a vector of scalar // type U, useful with e.g. pre "enum class" enums, or any existing scalar // data of the wrong type. @@ -1970,8 +1965,7 @@ class FlatBufferBuilder { buf_.swap_allocator(other.buf_); } -protected: - + protected: // You shouldn't really be copying instances of this class. FlatBufferBuilder(const FlatBufferBuilder &); FlatBufferBuilder &operator=(const FlatBufferBuilder &); @@ -2024,8 +2018,8 @@ protected: bool operator()(const Offset<String> &a, const Offset<String> &b) const { auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o)); auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o)); - return StringLessThan(stra->data(), stra->size(), - strb->data(), strb->size()); + return StringLessThan(stra->data(), stra->size(), strb->data(), + strb->size()); } const vector_downward *buf_; }; @@ -2089,13 +2083,15 @@ const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) { /// This function is UNDEFINED for FlatBuffers whose schema does not include /// a file_identifier (likely points at padding or the start of a the root /// vtable). -inline const char *GetBufferIdentifier(const void *buf, bool size_prefixed = false) { +inline const char *GetBufferIdentifier(const void *buf, + bool size_prefixed = false) { return reinterpret_cast<const char *>(buf) + ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t)); } // Helper to see if the identifier in a buffer has the expected value. -inline bool BufferHasIdentifier(const void *buf, const char *identifier, bool size_prefixed = false) { +inline bool BufferHasIdentifier(const void *buf, const char *identifier, + bool size_prefixed = false) { return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier, FlatBufferBuilder::kFileIdentifierLength) == 0; } @@ -2112,8 +2108,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS { num_tables_(0), max_tables_(_max_tables), upper_bound_(0), - check_alignment_(_check_alignment) - { + check_alignment_(_check_alignment) { FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE); } @@ -2162,8 +2157,8 @@ class Verifier FLATBUFFERS_FINAL_CLASS { return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len); } - template<typename T> bool Verify(const uint8_t *base, voffset_t elem_off) - const { + template<typename T> + bool Verify(const uint8_t *base, voffset_t elem_off) const { return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T)); } @@ -2186,16 +2181,15 @@ class Verifier FLATBUFFERS_FINAL_CLASS { // Verify a pointer (may be NULL) to string. bool VerifyString(const String *str) const { size_t end; - return !str || - (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str), - 1, &end) && - Verify(end, 1) && // Must have terminator - Check(buf_[end] == '\0')); // Terminating byte must be 0. + return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str), + 1, &end) && + Verify(end, 1) && // Must have terminator + Check(buf_[end] == '\0')); // Terminating byte must be 0. } // Common code between vectors and strings. bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size, - size_t *end = nullptr) const { + size_t *end = nullptr) const { auto veco = static_cast<size_t>(vec - buf_); // Check we can read the size field. if (!Verify<uoffset_t>(veco)) return false; @@ -2230,8 +2224,8 @@ class Verifier FLATBUFFERS_FINAL_CLASS { return true; } - __supress_ubsan__("unsigned-integer-overflow") - bool VerifyTableStart(const uint8_t *table) { + __supress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart( + const uint8_t *table) { // Check the vtable offset. auto tableo = static_cast<size_t>(table - buf_); if (!Verify<soffset_t>(tableo)) return false; @@ -2246,9 +2240,8 @@ class Verifier FLATBUFFERS_FINAL_CLASS { template<typename T> bool VerifyBufferFromStart(const char *identifier, size_t start) { - if (identifier && - (size_ < 2 * sizeof(flatbuffers::uoffset_t) || - !BufferHasIdentifier(buf_ + start, identifier))) { + if (identifier && (size_ < 2 * sizeof(flatbuffers::uoffset_t) || + !BufferHasIdentifier(buf_ + start, identifier))) { return false; } @@ -2496,8 +2489,8 @@ class Table { uint8_t data_[1]; }; -template<typename T> void FlatBufferBuilder::Required(Offset<T> table, - voffset_t field) { +template<typename T> +void FlatBufferBuilder::Required(Offset<T> table, voffset_t field) { auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o)); bool ok = table_ptr->GetOptionalFieldOffset(field) != 0; // If this fails, the caller will show what field needs to be set. @@ -2544,7 +2537,9 @@ inline const uint8_t *GetBufferStartFromRootPointer(const void *root) { } /// @brief This return the prefixed size of a FlatBuffer. -inline uoffset_t GetPrefixedSize(const uint8_t* buf){ return ReadScalar<uoffset_t>(buf); } +inline uoffset_t GetPrefixedSize(const uint8_t *buf) { + return ReadScalar<uoffset_t>(buf); +} // Base class for native objects (FlatBuffer data de-serialized into native // C++ data structures). @@ -2687,10 +2682,10 @@ typedef const TypeTable *(*TypeFunction)(); struct TypeTable { SequenceType st; size_t num_elems; // of type_codes, values, names (but not type_refs). - const TypeCode *type_codes; // num_elems count + const TypeCode *type_codes; // num_elems count const TypeFunction *type_refs; // less than num_elems entries (see TypeCode). const int64_t *values; // Only set for non-consecutive enum/union or structs. - const char * const *names; // Only set if compiled with --reflect-names. + const char *const *names; // Only set if compiled with --reflect-names. }; // String which identifies the current version of FlatBuffers. diff --git a/include/flatbuffers/flatc.h b/include/flatbuffers/flatc.h index f2765d23..5afe3bc9 100644 --- a/include/flatbuffers/flatc.h +++ b/include/flatbuffers/flatc.h @@ -17,6 +17,7 @@ #include <functional> #include <limits> #include <string> + #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" diff --git a/include/flatbuffers/flexbuffers.h b/include/flatbuffers/flexbuffers.h index 583c90bb..870bc83a 100644 --- a/include/flatbuffers/flexbuffers.h +++ b/include/flatbuffers/flexbuffers.h @@ -339,12 +339,12 @@ class Map : public Vector { template<typename T> void AppendToString(std::string &s, T &&v, bool keys_quoted) { - s += "[ "; - for (size_t i = 0; i < v.size(); i++) { - if (i) s += ", "; - v[i].ToString(true, keys_quoted, s); - } - s += " ]"; + s += "[ "; + for (size_t i = 0; i < v.size(); i++) { + if (i) s += ", "; + v[i].ToString(true, keys_quoted, s); + } + s += " ]"; } class Reference { @@ -386,13 +386,17 @@ class Reference { bool IsVector() const { return type_ == FBT_VECTOR || type_ == FBT_MAP; } bool IsUntypedVector() const { return type_ == FBT_VECTOR; } bool IsTypedVector() const { return flexbuffers::IsTypedVector(type_); } - bool IsFixedTypedVector() const { return flexbuffers::IsFixedTypedVector(type_); } - bool IsAnyVector() const { return (IsTypedVector() || IsFixedTypedVector() || IsVector());} + bool IsFixedTypedVector() const { + return flexbuffers::IsFixedTypedVector(type_); + } + bool IsAnyVector() const { + return (IsTypedVector() || IsFixedTypedVector() || IsVector()); + } bool IsMap() const { return type_ == FBT_MAP; } bool IsBlob() const { return type_ == FBT_BLOB; } bool AsBool() const { return (type_ == FBT_BOOL ? ReadUInt64(data_, parent_width_) - : AsUInt64()) != 0; + : AsUInt64()) != 0; } // Reads any type as a int64_t. Never fails, does most sensible conversion. @@ -555,7 +559,8 @@ class Reference { AppendToString<FixedTypedVector>(s, AsFixedTypedVector(), keys_quoted); } else if (IsBlob()) { auto blob = AsBlob(); - flatbuffers::EscapeString(reinterpret_cast<const char*>(blob.data()), blob.size(), &s, true, false); + flatbuffers::EscapeString(reinterpret_cast<const char *>(blob.data()), + blob.size(), &s, true, false); } else { s += "(?)"; } @@ -729,9 +734,15 @@ template<> inline int32_t Reference::As<int32_t>() const { return AsInt32(); } template<> inline int64_t Reference::As<int64_t>() const { return AsInt64(); } template<> inline uint8_t Reference::As<uint8_t>() const { return AsUInt8(); } -template<> inline uint16_t Reference::As<uint16_t>() const { return AsUInt16(); } -template<> inline uint32_t Reference::As<uint32_t>() const { return AsUInt32(); } -template<> inline uint64_t Reference::As<uint64_t>() const { return AsUInt64(); } +template<> inline uint16_t Reference::As<uint16_t>() const { + return AsUInt16(); +} +template<> inline uint32_t Reference::As<uint32_t>() const { + return AsUInt32(); +} +template<> inline uint64_t Reference::As<uint64_t>() const { + return AsUInt64(); +} template<> inline double Reference::As<double>() const { return AsDouble(); } template<> inline float Reference::As<float>() const { return AsFloat(); } @@ -920,9 +931,7 @@ class Builder FLATBUFFERS_FINAL_CLASS { Bool(b); } - void IndirectInt(int64_t i) { - PushIndirect(i, FBT_INDIRECT_INT, WidthI(i)); - } + void IndirectInt(int64_t i) { PushIndirect(i, FBT_INDIRECT_INT, WidthI(i)); } void IndirectInt(const char *key, int64_t i) { Key(key); IndirectInt(i); @@ -1214,9 +1223,7 @@ class Builder FLATBUFFERS_FINAL_CLASS { // Works on any data type. struct Value; Value LastValue() { return stack_.back(); } - void ReuseValue(Value v) { - stack_.push_back(v); - } + void ReuseValue(Value v) { stack_.push_back(v); } void ReuseValue(const char *key, Value v) { Key(key); ReuseValue(v); @@ -1462,7 +1469,9 @@ class Builder FLATBUFFERS_FINAL_CLASS { Value CreateVector(size_t start, size_t vec_len, size_t step, bool typed, bool fixed, const Value *keys = nullptr) { - FLATBUFFERS_ASSERT(!fixed || typed); // typed=false, fixed=true combination is not supported. + FLATBUFFERS_ASSERT( + !fixed || + typed); // typed=false, fixed=true combination is not supported. // Figure out smallest bit width we can store this vector with. auto bit_width = (std::max)(force_min_bit_width_, WidthU(vec_len)); auto prefix_elems = 1; @@ -1542,7 +1551,8 @@ class Builder FLATBUFFERS_FINAL_CLASS { typedef std::pair<size_t, size_t> StringOffset; struct StringOffsetCompare { - explicit StringOffsetCompare(const std::vector<uint8_t> &buf) : buf_(&buf) {} + explicit StringOffsetCompare(const std::vector<uint8_t> &buf) + : buf_(&buf) {} bool operator()(const StringOffset &a, const StringOffset &b) const { auto stra = reinterpret_cast<const char *>( flatbuffers::vector_data(*buf_) + a.first); @@ -1562,8 +1572,8 @@ class Builder FLATBUFFERS_FINAL_CLASS { } // namespace flexbuffers -# if defined(_MSC_VER) -# pragma warning(pop) -# endif +#if defined(_MSC_VER) +# pragma warning(pop) +#endif #endif // FLATBUFFERS_FLEXBUFFERS_H_ diff --git a/include/flatbuffers/grpc.h b/include/flatbuffers/grpc.h index 7070aba6..bd24c501 100644 --- a/include/flatbuffers/grpc.h +++ b/include/flatbuffers/grpc.h @@ -88,8 +88,7 @@ class SliceAllocator : public Allocator { SliceAllocator(const SliceAllocator &other) = delete; SliceAllocator &operator=(const SliceAllocator &other) = delete; - SliceAllocator(SliceAllocator &&other) - : slice_(grpc_empty_slice()) { + SliceAllocator(SliceAllocator &&other) : slice_(grpc_empty_slice()) { // default-construct and swap idiom swap(other); } @@ -164,34 +163,36 @@ class MessageBuilder : private detail::SliceAllocatorMember, public FlatBufferBuilder { public: explicit MessageBuilder(uoffset_t initial_size = 1024) - : FlatBufferBuilder(initial_size, &slice_allocator_, false) {} + : FlatBufferBuilder(initial_size, &slice_allocator_, false) {} MessageBuilder(const MessageBuilder &other) = delete; MessageBuilder &operator=(const MessageBuilder &other) = delete; MessageBuilder(MessageBuilder &&other) - : FlatBufferBuilder(1024, &slice_allocator_, false) { + : FlatBufferBuilder(1024, &slice_allocator_, false) { // Default construct and swap idiom. Swap(other); } /// Create a MessageBuilder from a FlatBufferBuilder. - explicit MessageBuilder(FlatBufferBuilder &&src, void (*dealloc)(void*, size_t) = &DefaultAllocator::dealloc) - : FlatBufferBuilder(1024, &slice_allocator_, false) { + explicit MessageBuilder(FlatBufferBuilder &&src, + void (*dealloc)(void *, + size_t) = &DefaultAllocator::dealloc) + : FlatBufferBuilder(1024, &slice_allocator_, false) { src.Swap(*this); src.SwapBufAllocator(*this); if (buf_.capacity()) { - uint8_t *buf = buf_.scratch_data(); // pointer to memory - size_t capacity = buf_.capacity(); // size of memory + uint8_t *buf = buf_.scratch_data(); // pointer to memory + size_t capacity = buf_.capacity(); // size of memory slice_allocator_.slice_ = grpc_slice_new_with_len(buf, capacity, dealloc); - } - else { + } else { slice_allocator_.slice_ = grpc_empty_slice(); } } /// Move-assign a FlatBufferBuilder to a MessageBuilder. - /// Only FlatBufferBuilder with default allocator (basically, nullptr) is supported. + /// Only FlatBufferBuilder with default allocator (basically, nullptr) is + /// supported. MessageBuilder &operator=(FlatBufferBuilder &&src) { // Move construct a temporary and swap MessageBuilder temp(std::move(src)); @@ -209,10 +210,11 @@ class MessageBuilder : private detail::SliceAllocatorMember, void Swap(MessageBuilder &other) { slice_allocator_.swap(other.slice_allocator_); FlatBufferBuilder::Swap(other); - // After swapping the FlatBufferBuilder, we swap back the allocator, which restores - // the original allocator back in place. This is necessary because MessageBuilder's - // allocator is its own member (SliceAllocatorMember). The allocator passed to - // FlatBufferBuilder::vector_downward must point to this member. + // After swapping the FlatBufferBuilder, we swap back the allocator, which + // restores the original allocator back in place. This is necessary because + // MessageBuilder's allocator is its own member (SliceAllocatorMember). The + // allocator passed to FlatBufferBuilder::vector_downward must point to this + // member. buf_.swap_allocator(other.buf_); } @@ -232,10 +234,10 @@ class MessageBuilder : private detail::SliceAllocatorMember, // flatbuffers-encoded region and wraps it in a `Message<T>` to handle buffer // ownership. template<class T> Message<T> GetMessage() { - auto buf_data = buf_.scratch_data(); // pointer to memory - auto buf_size = buf_.capacity(); // size of memory - auto msg_data = buf_.data(); // pointer to msg - auto msg_size = buf_.size(); // size of msg + auto buf_data = buf_.scratch_data(); // pointer to memory + auto buf_size = buf_.capacity(); // size of memory + auto msg_data = buf_.data(); // pointer to msg + auto msg_size = buf_.size(); // size of msg // Do some sanity checks on data/size FLATBUFFERS_ASSERT(msg_data); FLATBUFFERS_ASSERT(msg_size); diff --git a/include/flatbuffers/hash.h b/include/flatbuffers/hash.h index 16536cb4..aebf0713 100644 --- a/include/flatbuffers/hash.h +++ b/include/flatbuffers/hash.h @@ -57,17 +57,17 @@ template<typename T> T HashFnv1a(const char *input) { return hash; } -template <> inline uint16_t HashFnv1<uint16_t>(const char *input) { +template<> inline uint16_t HashFnv1<uint16_t>(const char *input) { uint32_t hash = HashFnv1<uint32_t>(input); return (hash >> 16) ^ (hash & 0xffff); } -template <> inline uint16_t HashFnv1a<uint16_t>(const char *input) { +template<> inline uint16_t HashFnv1a<uint16_t>(const char *input) { uint32_t hash = HashFnv1a<uint32_t>(input); return (hash >> 16) ^ (hash & 0xffff); } -template <typename T> struct NamedHashFunction { +template<typename T> struct NamedHashFunction { const char *name; typedef T (*HashFunction)(const char *); @@ -75,7 +75,7 @@ template <typename T> struct NamedHashFunction { }; const NamedHashFunction<uint16_t> kHashFunctions16[] = { - { "fnv1_16", HashFnv1<uint16_t> }, + { "fnv1_16", HashFnv1<uint16_t> }, { "fnv1a_16", HashFnv1a<uint16_t> }, }; diff --git a/include/flatbuffers/idl.h b/include/flatbuffers/idl.h index f7707df2..a4ad4964 100644 --- a/include/flatbuffers/idl.h +++ b/include/flatbuffers/idl.h @@ -338,13 +338,12 @@ struct StructDef : public Definition { flatbuffers::unique_ptr<std::string> original_location; }; - - struct EnumDef; struct EnumValBuilder; struct EnumVal { - Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder, const Parser &parser) const; + Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder, + const Parser &parser) const; bool Deserialize(const Parser &parser, const reflection::EnumVal *val); @@ -449,21 +448,21 @@ inline bool IsEnum(const Type &type) { inline size_t InlineSize(const Type &type) { return IsStruct(type) - ? type.struct_def->bytesize - : (IsArray(type) - ? InlineSize(type.VectorType()) * type.fixed_length - : SizeOf(type.base_type)); + ? type.struct_def->bytesize + : (IsArray(type) + ? InlineSize(type.VectorType()) * type.fixed_length + : SizeOf(type.base_type)); } inline size_t InlineAlignment(const Type &type) { - if (IsStruct(type)) { - return type.struct_def->minalign; - } else if (IsArray(type)) { - return IsStruct(type.VectorType()) ? type.struct_def->minalign - : SizeOf(type.element); - } else { - return SizeOf(type.base_type); - } + if (IsStruct(type)) { + return type.struct_def->minalign; + } else if (IsArray(type)) { + return IsStruct(type.VectorType()) ? type.struct_def->minalign + : SizeOf(type.element); + } else { + return SizeOf(type.base_type); + } } inline bool operator==(const EnumVal &lhs, const EnumVal &rhs) { return lhs.value == rhs.value; @@ -480,7 +479,8 @@ inline bool EqualByName(const Type &a, const Type &b) { } struct RPCCall : public Definition { - Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder, const Parser &parser) const; + Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder, + const Parser &parser) const; bool Deserialize(Parser &parser, const reflection::RPCCall *call); @@ -488,7 +488,8 @@ struct RPCCall : public Definition { }; struct ServiceDef : public Definition { - Offset<reflection::Service> Serialize(FlatBufferBuilder *builder, const Parser &parser) const; + Offset<reflection::Service> Serialize(FlatBufferBuilder *builder, + const Parser &parser) const; bool Deserialize(Parser &parser, const reflection::Service *service); SymbolTable<RPCCall> calls; @@ -722,9 +723,7 @@ class Parser : public ParserState { source_(nullptr), anonymous_counter(0), recurse_protection_counter(0) { - if (opts.force_defaults) { - builder_.ForceDefaults(true); - } + if (opts.force_defaults) { builder_.ForceDefaults(true); } // Start out with the empty namespace being current. empty_namespace_ = new Namespace(); namespaces_.push_back(empty_namespace_); @@ -795,9 +794,9 @@ class Parser : public ParserState { // Fills internal structure as if the schema passed had been loaded by parsing // with Parse except that included filenames will not be populated. - bool Deserialize(const reflection::Schema* schema); + bool Deserialize(const reflection::Schema *schema); - Type* DeserializeType(const reflection::Type* type); + Type *DeserializeType(const reflection::Type *type); // Checks that the schema represented by this parser is a safe evolution // of the schema provided. Returns non-empty error on any problems. @@ -854,16 +853,19 @@ class Parser : public ParserState { FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue, FieldDef *field, size_t fieldn); FLATBUFFERS_CHECKED_ERROR ParseArray(Value &array); - FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer(Value &val, FieldDef *field, - size_t fieldn, - const StructDef *parent_struct_def); + FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer( + Value &val, FieldDef *field, size_t fieldn, + const StructDef *parent_struct_def); FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value> *attributes); - FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken, bool check, Value &e, - BaseType req, bool *destmatch); - FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef* field); + FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken, + bool check, Value &e, BaseType req, + bool *destmatch); + FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef *field); FLATBUFFERS_CHECKED_ERROR TokenError(); - FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e, bool check_now); - FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type &type, std::string *result); + FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e, + bool check_now); + FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type &type, + std::string *result); StructDef *LookupCreateStruct(const std::string &name, bool create_if_new = true, bool definition = false); @@ -871,8 +873,7 @@ class Parser : public ParserState { FLATBUFFERS_CHECKED_ERROR ParseNamespace(); FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string &name, StructDef **dest); - FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name, - bool is_union, + FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name, bool is_union, EnumDef **dest); FLATBUFFERS_CHECKED_ERROR ParseDecl(); FLATBUFFERS_CHECKED_ERROR ParseService(); @@ -888,16 +889,15 @@ class Parser : public ParserState { FLATBUFFERS_CHECKED_ERROR StartParseFile(const char *source, const char *source_filename); FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source, - const char **include_paths, - const char *source_filename); + const char **include_paths, + const char *source_filename); FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source, - const char **include_paths, - const char *source_filename, - const char *include_filename); - FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef*> &fields, + const char **include_paths, + const char *source_filename, + const char *include_filename); + FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef *> &fields, StructDef *struct_def, - const char *suffix, - BaseType baseType); + const char *suffix, BaseType baseType); bool SupportsAdvancedUnionFeatures() const; bool SupportsAdvancedArrayFeatures() const; @@ -914,7 +914,7 @@ class Parser : public ParserState { std::vector<Namespace *> namespaces_; Namespace *current_namespace_; Namespace *empty_namespace_; - std::string error_; // User readable error_ if Parse() == false + std::string error_; // User readable error_ if Parse() == false FlatBufferBuilder builder_; // any data contained in the file flexbuffers::Builder flex_builder_; @@ -957,121 +957,101 @@ extern std::string MakeScreamingCamel(const std::string &in); // strict_json adds "quotes" around field names if true. // If the flatbuffer cannot be encoded in JSON (e.g., it contains non-UTF-8 // byte arrays in String values), returns false. -extern bool GenerateTextFromTable(const Parser &parser, - const void *table, +extern bool GenerateTextFromTable(const Parser &parser, const void *table, const std::string &tablename, std::string *text); -extern bool GenerateText(const Parser &parser, - const void *flatbuffer, +extern bool GenerateText(const Parser &parser, const void *flatbuffer, std::string *text); -extern bool GenerateTextFile(const Parser &parser, - const std::string &path, +extern bool GenerateTextFile(const Parser &parser, const std::string &path, const std::string &file_name); // Generate binary files from a given FlatBuffer, and a given Parser // object that has been populated with the corresponding schema. // See idl_gen_general.cpp. -extern bool GenerateBinary(const Parser &parser, - const std::string &path, +extern bool GenerateBinary(const Parser &parser, const std::string &path, const std::string &file_name); // Generate a C++ header from the definitions in the Parser object. // See idl_gen_cpp. -extern bool GenerateCPP(const Parser &parser, - const std::string &path, +extern bool GenerateCPP(const Parser &parser, const std::string &path, const std::string &file_name); -extern bool GenerateDart(const Parser &parser, - const std::string &path, +extern bool GenerateDart(const Parser &parser, const std::string &path, const std::string &file_name); -// Generate JavaScript or TypeScript code from the definitions in the Parser object. -// See idl_gen_js. -extern bool GenerateJSTS(const Parser &parser, - const std::string &path, - const std::string &file_name); +// Generate JavaScript or TypeScript code from the definitions in the Parser +// object. See idl_gen_js. +extern bool GenerateJSTS(const Parser &parser, const std::string &path, + const std::string &file_name); // Generate Go files from the definitions in the Parser object. // See idl_gen_go.cpp. -extern bool GenerateGo(const Parser &parser, - const std::string &path, +extern bool GenerateGo(const Parser &parser, const std::string &path, const std::string &file_name); // Generate Php code from the definitions in the Parser object. // See idl_gen_php. -extern bool GeneratePhp(const Parser &parser, - const std::string &path, +extern bool GeneratePhp(const Parser &parser, const std::string &path, const std::string &file_name); // Generate Python files from the definitions in the Parser object. // See idl_gen_python.cpp. -extern bool GeneratePython(const Parser &parser, - const std::string &path, +extern bool GeneratePython(const Parser &parser, const std::string &path, const std::string &file_name); // Generate Lobster files from the definitions in the Parser object. // See idl_gen_lobster.cpp. -extern bool GenerateLobster(const Parser &parser, - const std::string &path, +extern bool GenerateLobster(const Parser &parser, const std::string &path, const std::string &file_name); // Generate Lua files from the definitions in the Parser object. // See idl_gen_lua.cpp. -extern bool GenerateLua(const Parser &parser, - const std::string &path, - const std::string &file_name); +extern bool GenerateLua(const Parser &parser, const std::string &path, + const std::string &file_name); // Generate Rust files from the definitions in the Parser object. // See idl_gen_rust.cpp. -extern bool GenerateRust(const Parser &parser, - const std::string &path, +extern bool GenerateRust(const Parser &parser, const std::string &path, const std::string &file_name); // Generate Json schema file // See idl_gen_json_schema.cpp. -extern bool GenerateJsonSchema(const Parser &parser, - const std::string &path, - const std::string &file_name); +extern bool GenerateJsonSchema(const Parser &parser, const std::string &path, + const std::string &file_name); extern bool GenerateKotlin(const Parser &parser, const std::string &path, const std::string &file_name); // Generate Java/C#/.. files from the definitions in the Parser object. // See idl_gen_general.cpp. -extern bool GenerateGeneral(const Parser &parser, - const std::string &path, +extern bool GenerateGeneral(const Parser &parser, const std::string &path, const std::string &file_name); // Generate a schema file from the internal representation, useful after // parsing a .proto schema. extern std::string GenerateFBS(const Parser &parser, const std::string &file_name); -extern bool GenerateFBS(const Parser &parser, - const std::string &path, +extern bool GenerateFBS(const Parser &parser, const std::string &path, const std::string &file_name); // Generate a make rule for the generated JavaScript or TypeScript code. // See idl_gen_js.cpp. -extern std::string JSTSMakeRule(const Parser &parser, - const std::string &path, - const std::string &file_name); +extern std::string JSTSMakeRule(const Parser &parser, const std::string &path, + const std::string &file_name); // Generate a make rule for the generated C++ header. // See idl_gen_cpp.cpp. -extern std::string CPPMakeRule(const Parser &parser, - const std::string &path, +extern std::string CPPMakeRule(const Parser &parser, const std::string &path, const std::string &file_name); // Generate a make rule for the generated Dart code // see idl_gen_dart.cpp -extern std::string DartMakeRule(const Parser &parser, - const std::string &path, +extern std::string DartMakeRule(const Parser &parser, const std::string &path, const std::string &file_name); // Generate a make rule for the generated Rust code. // See idl_gen_rust.cpp. -extern std::string RustMakeRule(const Parser &parser, - const std::string &path, +extern std::string RustMakeRule(const Parser &parser, const std::string &path, const std::string &file_name); // Generate a make rule for the generated Java/C#/... files. @@ -1082,32 +1062,27 @@ extern std::string GeneralMakeRule(const Parser &parser, // Generate a make rule for the generated text (JSON) files. // See idl_gen_text.cpp. -extern std::string TextMakeRule(const Parser &parser, - const std::string &path, +extern std::string TextMakeRule(const Parser &parser, const std::string &path, const std::string &file_names); // Generate a make rule for the generated binary files. // See idl_gen_general.cpp. -extern std::string BinaryMakeRule(const Parser &parser, - const std::string &path, +extern std::string BinaryMakeRule(const Parser &parser, const std::string &path, const std::string &file_name); // Generate GRPC Cpp interfaces. // See idl_gen_grpc.cpp. -bool GenerateCppGRPC(const Parser &parser, - const std::string &path, +bool GenerateCppGRPC(const Parser &parser, const std::string &path, const std::string &file_name); // Generate GRPC Go interfaces. // See idl_gen_grpc.cpp. -bool GenerateGoGRPC(const Parser &parser, - const std::string &path, +bool GenerateGoGRPC(const Parser &parser, const std::string &path, const std::string &file_name); // Generate GRPC Java classes. // See idl_gen_grpc.cpp -bool GenerateJavaGRPC(const Parser &parser, - const std::string &path, +bool GenerateJavaGRPC(const Parser &parser, const std::string &path, const std::string &file_name); } // namespace flatbuffers diff --git a/include/flatbuffers/minireflect.h b/include/flatbuffers/minireflect.h index 9d648ec0..67a79a93 100644 --- a/include/flatbuffers/minireflect.h +++ b/include/flatbuffers/minireflect.h @@ -88,7 +88,8 @@ inline size_t InlineSize(ElementaryType type, const TypeTable *type_table) { switch (type_table->st) { case ST_TABLE: case ST_UNION: return 4; - case ST_STRUCT: return static_cast<size_t>(type_table->values[type_table->num_elems]); + case ST_STRUCT: + return static_cast<size_t>(type_table->values[type_table->num_elems]); default: FLATBUFFERS_ASSERT(false); return 1; } default: FLATBUFFERS_ASSERT(false); return 1; diff --git a/include/flatbuffers/util.h b/include/flatbuffers/util.h index 072fe9e1..d10d2f17 100644 --- a/include/flatbuffers/util.h +++ b/include/flatbuffers/util.h @@ -17,10 +17,10 @@ #ifndef FLATBUFFERS_UTIL_H_ #define FLATBUFFERS_UTIL_H_ -#include "flatbuffers/base.h" - #include <errno.h> +#include "flatbuffers/base.h" + #ifndef FLATBUFFERS_PREFER_PRINTF # include <sstream> #else // FLATBUFFERS_PREFER_PRINTF diff --git a/src/code_generators.cpp b/src/code_generators.cpp index 52ca3056..a46c4b73 100644 --- a/src/code_generators.cpp +++ b/src/code_generators.cpp @@ -15,12 +15,14 @@ */ #include "flatbuffers/code_generators.h" + #include <assert.h> -#include "flatbuffers/base.h" -#include "flatbuffers/util.h" #include <cmath> +#include "flatbuffers/base.h" +#include "flatbuffers/util.h" + #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4127) // C4127: conditional expression is constant diff --git a/src/flatc.cpp b/src/flatc.cpp index ab2b1faf..74f2e238 100644 --- a/src/flatc.cpp +++ b/src/flatc.cpp @@ -42,7 +42,7 @@ void FlatCompiler::LoadBinarySchema(flatbuffers::Parser &parser, const std::string &filename, const std::string &contents) { if (!parser.Deserialize(reinterpret_cast<const uint8_t *>(contents.c_str()), - contents.size())) { + contents.size())) { Error("failed to load binary schema: " + filename, false, false); } } @@ -402,7 +402,8 @@ int FlatCompiler::Compile(int argc, const char **argv) { "\" matches the schema, use --raw-binary to read this file" " anyway."); } else if (!flatbuffers::BufferHasIdentifier( - contents.c_str(), parser->file_identifier_.c_str(), opts.size_prefixed)) { + contents.c_str(), parser->file_identifier_.c_str(), + opts.size_prefixed)) { Error("binary \"" + filename + "\" does not have expected file_identifier \"" + parser->file_identifier_ + diff --git a/src/flatc_main.cpp b/src/flatc_main.cpp index 72bb4a2f..352c3145 100644 --- a/src/flatc_main.cpp +++ b/src/flatc_main.cpp @@ -61,13 +61,15 @@ int main(int argc, const char *argv[]) { flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateJSTS, "-s", "--js", "JavaScript", true, nullptr, flatbuffers::IDLOptions::kJs, - "Generate JavaScript code for tables/structs", flatbuffers::JSTSMakeRule }, + "Generate JavaScript code for tables/structs", + flatbuffers::JSTSMakeRule }, { flatbuffers::GenerateDart, "-d", "--dart", "Dart", true, nullptr, flatbuffers::IDLOptions::kDart, "Generate Dart classes for tables/structs", flatbuffers::DartMakeRule }, { flatbuffers::GenerateJSTS, "-T", "--ts", "TypeScript", true, nullptr, flatbuffers::IDLOptions::kTs, - "Generate TypeScript code for tables/structs", flatbuffers::JSTSMakeRule }, + "Generate TypeScript code for tables/structs", + flatbuffers::JSTSMakeRule }, { flatbuffers::GenerateGeneral, "-n", "--csharp", "C#", true, nullptr, flatbuffers::IDLOptions::kCSharp, "Generate C# classes for tables/structs", flatbuffers::GeneralMakeRule }, @@ -75,23 +77,22 @@ int main(int argc, const char *argv[]) { flatbuffers::IDLOptions::kPython, "Generate Python files for tables/structs", flatbuffers::GeneralMakeRule }, - { flatbuffers::GenerateLobster, nullptr, "--lobster", "Lobster", true, nullptr, - flatbuffers::IDLOptions::kLobster, + { flatbuffers::GenerateLobster, nullptr, "--lobster", "Lobster", true, + nullptr, flatbuffers::IDLOptions::kLobster, "Generate Lobster files for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateLua, "-l", "--lua", "Lua", true, nullptr, - flatbuffers::IDLOptions::kLua, - "Generate Lua files for tables/structs", + flatbuffers::IDLOptions::kLua, "Generate Lua files for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateRust, "-r", "--rust", "Rust", true, nullptr, - flatbuffers::IDLOptions::kRust, - "Generate Rust files for tables/structs", + flatbuffers::IDLOptions::kRust, "Generate Rust files for tables/structs", flatbuffers::RustMakeRule }, { flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true, nullptr, flatbuffers::IDLOptions::kPhp, "Generate PHP files for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateKotlin, nullptr, "--kotlin", "Kotlin", true, nullptr, - flatbuffers::IDLOptions::kKotlin, "Generate Kotlin classes for tables/structs", + flatbuffers::IDLOptions::kKotlin, + "Generate Kotlin classes for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema", true, nullptr, flatbuffers::IDLOptions::kJsonSchema, diff --git a/src/flathash.cpp b/src/flathash.cpp index bc3d2df2..1264f821 100644 --- a/src/flathash.cpp +++ b/src/flathash.cpp @@ -15,9 +15,11 @@ */ #include <stdio.h> + #include <iostream> #include <sstream> #include <string> + #include "flatbuffers/hash.h" enum OutputFormat { kDecimal, kHexadecimal, kHexadecimal0x }; @@ -35,7 +37,7 @@ int main(int argc, char *argv[]) { } printf(" 32 bit:\n"); size = sizeof(flatbuffers::kHashFunctions32) / - sizeof(flatbuffers::kHashFunctions32[0]); + sizeof(flatbuffers::kHashFunctions32[0]); for (size_t i = 0; i < size; ++i) { printf(" * %s\n", flatbuffers::kHashFunctions32[i].name); } diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp index d7b3abb5..706732b0 100644 --- a/src/idl_gen_cpp.cpp +++ b/src/idl_gen_cpp.cpp @@ -16,13 +16,13 @@ // independent from idl_parser, since this code is not needed for most clients +#include <unordered_set> + #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include <unordered_set> - namespace flatbuffers { // Pedantic warning free version of toupper(). @@ -208,9 +208,7 @@ class CppGenerator : public BaseGenerator { for (std::size_t i = 0; i < parser_.opts.cpp_includes.size(); ++i) { code_ += "#include \"" + parser_.opts.cpp_includes[i] + "\""; } - if (!parser_.opts.cpp_includes.empty()) { - code_ += ""; - } + if (!parser_.opts.cpp_includes.empty()) { code_ += ""; } } std::string EscapeKeyword(const std::string &name) const { @@ -577,7 +575,9 @@ class CppGenerator : public BaseGenerator { } case BASE_TYPE_UNION: // fall through - default: { return "void"; } + default: { + return "void"; + } } } @@ -696,7 +696,9 @@ class CppGenerator : public BaseGenerator { case BASE_TYPE_UNION: { return type.enum_def->name + "Union"; } - default: { return GenTypeBasic(type, true); } + default: { + return GenTypeBasic(type, true); + } } } @@ -1163,7 +1165,8 @@ class CppGenerator : public BaseGenerator { code_ += " void Set(T&& val) {"; code_ += " using RT = typename std::remove_reference<T>::type;"; code_ += " Reset();"; - code_ += " type = {{NAME}}Traits<typename RT::TableType>::enum_value;"; + code_ += + " type = {{NAME}}Traits<typename RT::TableType>::enum_value;"; code_ += " if (type != {{NONE}}) {"; code_ += " value = new RT(std::forward<T>(val));"; code_ += " }"; @@ -1276,7 +1279,8 @@ class CppGenerator : public BaseGenerator { " auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);"; if (ev.union_type.base_type == BASE_TYPE_STRUCT) { if (ev.union_type.struct_def->fixed) { - code_ += " return verifier.Verify<{{TYPE}}>(static_cast<const " + code_ += + " return verifier.Verify<{{TYPE}}>(static_cast<const " "uint8_t *>(obj), 0);"; } else { code_ += getptr; @@ -1295,7 +1299,7 @@ class CppGenerator : public BaseGenerator { code_ += " }"; } } - code_ += " default: return true;"; // unknown values are OK. + code_ += " default: return true;"; // unknown values are OK. code_ += " }"; code_ += "}"; code_ += ""; @@ -1763,7 +1767,9 @@ class CppGenerator : public BaseGenerator { } break; } - default: { break; } + default: { + break; + } } } @@ -1925,7 +1931,8 @@ class CppGenerator : public BaseGenerator { } } - if (parser_.opts.mutable_buffer && !(is_scalar && IsUnion(field.value.type))) { + if (parser_.opts.mutable_buffer && + !(is_scalar && IsUnion(field.value.type))) { if (is_scalar) { const auto type = GenTypeWire(field.value.type, "", false); code_.SetValue("SET_FN", "SetField<" + type + ">"); @@ -2901,8 +2908,8 @@ class CppGenerator : public BaseGenerator { } else if (IsArray(field.value.type)) { auto underlying = GenTypeGet(field.value.type, "", "", "", false); code_ += " flatbuffers::Array<" + mut_field_type + ", " + - NumToString(field.value.type.fixed_length) + - "> *" + "mutable_{{FIELD_NAME}}() {"; + NumToString(field.value.type.fixed_length) + "> *" + + "mutable_{{FIELD_NAME}}() {"; code_ += " return reinterpret_cast<flatbuffers::Array<" + mut_field_type + ", " + NumToString(field.value.type.fixed_length) + diff --git a/src/idl_gen_dart.cpp b/src/idl_gen_dart.cpp index b97d4ea2..ab9425f8 100644 --- a/src/idl_gen_dart.cpp +++ b/src/idl_gen_dart.cpp @@ -71,9 +71,7 @@ class DartGenerator : public BaseGenerator { "// ignore_for_file: unused_import, unused_field, " "unused_local_variable\n\n"; - if (!kv->first.empty()) { - code += "library " + kv->first + ";\n\n"; - } + if (!kv->first.empty()) { code += "library " + kv->first + ";\n\n"; } code += "import 'dart:typed_data' show Uint8List;\n"; code += "import 'package:flat_buffers/flat_buffers.dart' as " + _kFb + @@ -87,16 +85,20 @@ class DartGenerator : public BaseGenerator { ++kv2) { if (kv2->first != kv->first) { code += "import '" + - GeneratedFileName("./", file_name_ + (!kv2->first.empty() ? "_" + kv2->first : "")) + + GeneratedFileName( + "./", file_name_ + + (!kv2->first.empty() ? "_" + kv2->first : "")) + "' as " + ImportAliasName(kv2->first) + ";\n"; } } code += "\n"; code += kv->second; - if (!SaveFile( - GeneratedFileName(path_, file_name_ + (!kv->first.empty() ? "_" + kv->first : "")).c_str(), - code, false)) { + if (!SaveFile(GeneratedFileName( + path_, file_name_ + + (!kv->first.empty() ? "_" + kv->first : "")) + .c_str(), + code, false)) { return false; } } @@ -117,9 +119,7 @@ class DartGenerator : public BaseGenerator { } static std::string BuildNamespaceName(const Namespace &ns) { - if (ns.components.empty()) { - return ""; - } + if (ns.components.empty()) { return ""; } std::stringstream sstream; std::copy(ns.components.begin(), ns.components.end() - 1, std::ostream_iterator<std::string>(sstream, ".")); @@ -139,7 +139,8 @@ class DartGenerator : public BaseGenerator { return ret; } - void GenIncludeDependencies(std::string* code, const std::string& the_namespace) { + void GenIncludeDependencies(std::string *code, + const std::string &the_namespace) { for (auto it = parser_.included_files_.begin(); it != parser_.included_files_.end(); ++it) { if (it->second.empty()) continue; @@ -147,7 +148,11 @@ class DartGenerator : public BaseGenerator { auto noext = flatbuffers::StripExtension(it->second); auto basename = flatbuffers::StripPath(noext); - *code += "import '" + GeneratedFileName("", basename + (the_namespace == "" ? "" : "_" + the_namespace)) + "';\n"; + *code += + "import '" + + GeneratedFileName( + "", basename + (the_namespace == "" ? "" : "_" + the_namespace)) + + "';\n"; } } @@ -798,7 +803,8 @@ class DartGenerator : public BaseGenerator { } code += "\n : null;\n"; } else if (field.value.type.base_type == BASE_TYPE_STRING) { - code += " = fbBuilder.writeString(_" + MakeCamel(field.name, false) + ");\n"; + code += " = fbBuilder.writeString(_" + MakeCamel(field.name, false) + + ");\n"; } else { code += " = _" + MakeCamel(field.name, false) + "?.getOrCreateOffset(fbBuilder);\n"; diff --git a/src/idl_gen_general.cpp b/src/idl_gen_general.cpp index bb2920f5..48ec2b73 100644 --- a/src/idl_gen_general.cpp +++ b/src/idl_gen_general.cpp @@ -69,75 +69,71 @@ const LanguageParameters &GetLangParams(IDLOptions::Language lang) { "Double.", "Float.", "NaN", "POSITIVE_INFINITY", "NEGATIVE_INFINITY"); static const LanguageParameters language_parameters[] = { - { - IDLOptions::kJava, - false, - ".java", - "String", - "boolean ", - " {\n", - "class ", - " final ", - "final ", - "final class ", - ";\n", - "()", - "", - " extends ", - "package ", - ";", - "", - "_bb.order(ByteOrder.LITTLE_ENDIAN); ", - "position()", - "offset()", - "", - "", - "", - "import java.nio.*;\nimport java.lang.*;\nimport " - "java.util.*;\nimport com.google.flatbuffers.*;\n", - "\n@SuppressWarnings(\"unused\")\n", - "\n@javax.annotation.Generated(value=\"flatc\")\n", - { - "/**", - " *", - " */", - }, - &JavaFloatGen - }, - { - IDLOptions::kCSharp, - true, - ".cs", - "string", - "bool ", - "\n{\n", - "struct ", - " readonly ", - "", - "enum ", - ",\n", - " { get", - "} ", - " : ", - "namespace ", - "\n{", - "\n}\n", - "", - "Position", - "Offset", - "__p.", - "Table.", - "?", - "using global::System;\nusing global::FlatBuffers;\n\n", - "", - "", - { - nullptr, - "///", - nullptr, - }, - &CSharpFloatGen - }, + { IDLOptions::kJava, + false, + ".java", + "String", + "boolean ", + " {\n", + "class ", + " final ", + "final ", + "final class ", + ";\n", + "()", + "", + " extends ", + "package ", + ";", + "", + "_bb.order(ByteOrder.LITTLE_ENDIAN); ", + "position()", + "offset()", + "", + "", + "", + "import java.nio.*;\nimport java.lang.*;\nimport " + "java.util.*;\nimport com.google.flatbuffers.*;\n", + "\n@SuppressWarnings(\"unused\")\n", + "\n@javax.annotation.Generated(value=\"flatc\")\n", + { + "/**", + " *", + " */", + }, + &JavaFloatGen }, + { IDLOptions::kCSharp, + true, + ".cs", + "string", + "bool ", + "\n{\n", + "struct ", + " readonly ", + "", + "enum ", + ",\n", + " { get", + "} ", + " : ", + "namespace ", + "\n{", + "\n}\n", + "", + "Position", + "Offset", + "__p.", + "Table.", + "?", + "using global::System;\nusing global::FlatBuffers;\n\n", + "", + "", + { + nullptr, + "///", + nullptr, + }, + &CSharpFloatGen }, }; if (lang == IDLOptions::kJava) { @@ -233,9 +229,7 @@ class GeneralGenerator : public BaseGenerator { } code += lang_.class_annotation; } - if (parser_.opts.gen_generated) { - code += lang_.generated_type_annotation; - } + if (parser_.opts.gen_generated) { code += lang_.generated_type_annotation; } code += classcode; if (!namespace_name.empty()) code += lang_.namespace_end; auto filename = NamespaceDir(ns) + defname + lang_.file_extension; @@ -339,7 +333,7 @@ class GeneralGenerator : public BaseGenerator { case BASE_TYPE_ARRAY: case BASE_TYPE_VECTOR: if (vectorelem) return DestinationType(type.VectorType(), vectorelem); - FLATBUFFERS_FALLTHROUGH(); // else fall thru + FLATBUFFERS_FALLTHROUGH(); // else fall thru default: return type; } } @@ -383,7 +377,7 @@ class GeneralGenerator : public BaseGenerator { case BASE_TYPE_UINT: return " & 0xFFFFFFFFL"; case BASE_TYPE_VECTOR: if (vectorelem) return DestinationMask(type.VectorType(), vectorelem); - FLATBUFFERS_FALLTHROUGH(); // else fall thru + FLATBUFFERS_FALLTHROUGH(); // else fall thru default: return ""; } } @@ -440,7 +434,9 @@ class GeneralGenerator : public BaseGenerator { return ""; } - std::string SourceCast(const Type &type) const { return SourceCast(type, true); } + std::string SourceCast(const Type &type) const { + return SourceCast(type, true); + } std::string SourceCastBasic(const Type &type, bool castFromDest) const { return IsScalar(type.base_type) ? SourceCast(type, castFromDest) : ""; @@ -459,8 +455,9 @@ class GeneralGenerator : public BaseGenerator { : value.constant; } - std::string GenDefaultValue(const FieldDef &field, bool enableLangOverrides) const { - auto& value = field.value; + std::string GenDefaultValue(const FieldDef &field, + bool enableLangOverrides) const { + auto &value = field.value; if (enableLangOverrides) { // handles both enum case and vector of enum case if (lang_.language == IDLOptions::kCSharp && @@ -482,7 +479,7 @@ class GeneralGenerator : public BaseGenerator { case BASE_TYPE_UINT: case BASE_TYPE_LONG: return value.constant + longSuffix; default: - if(IsFloat(value.type.base_type)) + if (IsFloat(value.type.base_type)) return lang_.float_gen->GenFloatConstant(field); else return value.constant; @@ -495,7 +492,7 @@ class GeneralGenerator : public BaseGenerator { std::string GenDefaultValueBasic(const FieldDef &field, bool enableLangOverrides) const { - auto& value = field.value; + auto &value = field.value; if (!IsScalar(value.type.base_type)) { if (enableLangOverrides) { if (lang_.language == IDLOptions::kCSharp) { @@ -530,15 +527,14 @@ class GeneralGenerator : public BaseGenerator { GenComment(enum_def.doc_comment, code_ptr, &lang_.comment_config); // In C# this indicates enumeration values can be treated as bit flags. - if (lang_.language == IDLOptions::kCSharp && enum_def.attributes.Lookup("bit_flags")) { + if (lang_.language == IDLOptions::kCSharp && + enum_def.attributes.Lookup("bit_flags")) { code += "[System.FlagsAttribute]\n"; } if (enum_def.attributes.Lookup("private")) { // For Java, we leave the enum unmarked to indicate package-private // For C# we mark the enum as internal - if (lang_.language == IDLOptions::kCSharp) { - code += "internal "; - } + if (lang_.language == IDLOptions::kCSharp) { code += "internal "; } } else { code += "public "; } @@ -870,9 +866,7 @@ class GeneralGenerator : public BaseGenerator { if (struct_def.attributes.Lookup("private")) { // For Java, we leave the struct unmarked to indicate package-private // For C# we mark the struct as internal - if (lang_.language == IDLOptions::kCSharp) { - code += "internal "; - } + if (lang_.language == IDLOptions::kCSharp) { code += "internal "; } } else { code += "public "; } @@ -1016,8 +1010,8 @@ class GeneralGenerator : public BaseGenerator { code += "(new " + type_name + "(), j); }\n"; } } else if (field.value.type.base_type == BASE_TYPE_UNION || - (field.value.type.base_type == BASE_TYPE_VECTOR && - field.value.type.VectorType().base_type == BASE_TYPE_UNION)) { + (field.value.type.base_type == BASE_TYPE_VECTOR && + field.value.type.VectorType().base_type == BASE_TYPE_UNION)) { if (lang_.language == IDLOptions::kCSharp) { // Union types in C# use generic Table-derived type for better type // safety. @@ -1092,8 +1086,8 @@ class GeneralGenerator : public BaseGenerator { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_UNION && lang_.language == IDLOptions::kCSharp) { - conditional_cast = "(TTable?)"; - getter += "<TTable>"; + conditional_cast = "(TTable?)"; + getter += "<TTable>"; } code += "("; if (vectortype.base_type == BASE_TYPE_STRUCT) { @@ -1145,7 +1139,8 @@ class GeneralGenerator : public BaseGenerator { if (lang_.language == IDLOptions::kCSharp) { code += "() where TTable : struct, IFlatbufferObject"; code += offset_prefix + "(TTable?)" + getter; - code += "<TTable>(o + " + lang_.accessor_prefix + "bb_pos) : null"; + code += + "<TTable>(o + " + lang_.accessor_prefix + "bb_pos) : null"; } else { code += "(" + type_name + " obj)" + offset_prefix + getter; code += "(obj, o + " + lang_.accessor_prefix + "bb_pos) : null"; @@ -1174,19 +1169,21 @@ class GeneralGenerator : public BaseGenerator { auto &key_field = **kit; if (key_field.key) { auto qualified_name = WrapInNameSpace(sd); - code += " public " + qualified_name + lang_.optional_suffix + " "; + code += + " public " + qualified_name + lang_.optional_suffix + " "; code += MakeCamel(field.name, lang_.first_camel_upper) + "ByKey("; code += GenTypeNameDest(key_field.value.type) + " key)"; code += offset_prefix; code += qualified_name + ".__lookup_by_key("; - if (lang_.language == IDLOptions::kJava) - code += "null, "; + if (lang_.language == IDLOptions::kJava) code += "null, "; code += lang_.accessor_prefix + "__vector(o), key, "; code += lang_.accessor_prefix + "bb) : null; "; code += "}\n"; if (lang_.language == IDLOptions::kJava) { - code += " public " + qualified_name + lang_.optional_suffix + " "; - code += MakeCamel(field.name, lang_.first_camel_upper) + "ByKey("; + code += + " public " + qualified_name + lang_.optional_suffix + " "; + code += + MakeCamel(field.name, lang_.first_camel_upper) + "ByKey("; code += qualified_name + lang_.optional_suffix + " obj, "; code += GenTypeNameDest(key_field.value.type) + " key)"; code += offset_prefix; @@ -1259,12 +1256,15 @@ class GeneralGenerator : public BaseGenerator { break; case IDLOptions::kCSharp: code += "#if ENABLE_SPAN_T\n"; - code += " public Span<" + GenTypeBasic(field.value.type.VectorType()) + "> Get"; + code += " public Span<" + + GenTypeBasic(field.value.type.VectorType()) + "> Get"; code += MakeCamel(field.name, lang_.first_camel_upper); code += "Bytes() { return "; - code += lang_.accessor_prefix + "__vector_as_span<"+ GenTypeBasic(field.value.type.VectorType()) +">("; + code += lang_.accessor_prefix + "__vector_as_span<" + + GenTypeBasic(field.value.type.VectorType()) + ">("; code += NumToString(field.value.offset); - code += ", " + NumToString(SizeOf(field.value.type.VectorType().base_type)); + code += ", " + NumToString( + SizeOf(field.value.type.VectorType().base_type)); code += "); }\n"; code += "#else\n"; code += " public ArraySegment<byte>? Get"; @@ -1596,10 +1596,10 @@ class GeneralGenerator : public BaseGenerator { std::string size_prefix[] = { "", "SizePrefixed" }; for (int i = 0; i < 2; ++i) { code += " public static void "; - code += FunctionStart('F') + "inish" + size_prefix[i] + - struct_def.name; - code += "Buffer(FlatBufferBuilder builder, " + - GenOffsetType(struct_def); + code += + FunctionStart('F') + "inish" + size_prefix[i] + struct_def.name; + code += + "Buffer(FlatBufferBuilder builder, " + GenOffsetType(struct_def); code += " offset) {"; code += " builder." + FunctionStart('F') + "inish" + size_prefix[i] + "(offset"; @@ -1636,7 +1636,7 @@ class GeneralGenerator : public BaseGenerator { code += "\n public static " + struct_def.name + lang_.optional_suffix; code += " __lookup_by_key("; if (lang_.language == IDLOptions::kJava) - code += struct_def.name + " obj, "; + code += struct_def.name + " obj, "; code += "int vectorLocation, "; code += GenTypeNameDest(key_field->value.type); code += " key, ByteBuffer bb) {\n"; @@ -1684,8 +1684,7 @@ class GeneralGenerator : public BaseGenerator { // Generate a vector of structs accessor class. code += "\n"; code += " "; - if (!struct_def.attributes.Lookup("private")) - code += "public "; + if (!struct_def.attributes.Lookup("private")) code += "public "; code += "static "; code += lang_.unsubclassable_decl; code += lang_.accessor_type + "Vector" + lang_.inheritance_marker; diff --git a/src/idl_gen_go.cpp b/src/idl_gen_go.cpp index aa25751d..4ed1a80b 100644 --- a/src/idl_gen_go.cpp +++ b/src/idl_gen_go.cpp @@ -43,7 +43,7 @@ static std::string GeneratedFileName(const std::string &path, namespace go { // see https://golang.org/ref/spec#Keywords -static const char * const g_golang_keywords[] = { +static const char *const g_golang_keywords[] = { "break", "default", "func", "interface", "select", "case", "defer", "go", "map", "struct", "chan", "else", "goto", "package", "switch", "const", "fallthrough", "if", "range", "type", "continue", @@ -151,7 +151,8 @@ class GoGenerator : public BaseGenerator { // Construct the name of the type for this enum. std::string GetEnumTypeName(const EnumDef &enum_def) { - return WrapInNameSpaceAndTrack(enum_def.defined_namespace, GoIdentity(enum_def.name)); + return WrapInNameSpaceAndTrack(enum_def.defined_namespace, + GoIdentity(enum_def.name)); } // Create a type for the enum values. @@ -222,7 +223,7 @@ class GoGenerator : public BaseGenerator { code += "\tif s, ok := EnumNames" + enum_def.name + "[v]; ok {\n"; code += "\t\treturn s\n"; code += "\t}\n"; - code += "\treturn \""+ enum_def.name; + code += "\treturn \"" + enum_def.name; code += "(\" + strconv.FormatInt(int64(v), 10) + \")\"\n"; code += "}\n\n"; } @@ -325,23 +326,21 @@ class GoGenerator : public BaseGenerator { // Get the value of a struct's scalar. void GetScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); GenReceiver(struct_def, code_ptr); code += " " + MakeCamel(field.name); code += "() " + TypeName(field) + " {\n"; - code += "\treturn " + CastToEnum( - field.value.type, - getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" + - NumToString(field.value.offset) + "))"); + code += "\treturn " + + CastToEnum(field.value.type, + getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" + + NumToString(field.value.offset) + "))"); code += "\n}\n"; } // Get the value of a table's scalar. - void GetScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); @@ -358,8 +357,7 @@ class GoGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Struct. void GetStructFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); code += " " + MakeCamel(field.name); @@ -377,8 +375,7 @@ class GoGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Table. - void GetStructFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -400,8 +397,7 @@ class GoGenerator : public BaseGenerator { } // Get the value of a string. - void GetStringField(const StructDef &struct_def, - const FieldDef &field, + void GetStringField(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -428,8 +424,7 @@ class GoGenerator : public BaseGenerator { // Get the value of a vector's struct member. void GetMemberOfVectorOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; auto vectortype = field.value.type.VectorType(); @@ -461,10 +456,11 @@ class GoGenerator : public BaseGenerator { code += "(j int) " + TypeName(field) + " "; code += OffsetPrefix(field); code += "\t\ta := rcv._tab.Vector(o)\n"; - code += "\t\treturn " + CastToEnum( - field.value.type, - GenGetter(field.value.type) + "(a + flatbuffers.UOffsetT(j*" + - NumToString(InlineSize(vectortype)) + "))"); + code += "\t\treturn " + + CastToEnum(field.value.type, + GenGetter(field.value.type) + + "(a + flatbuffers.UOffsetT(j*" + + NumToString(InlineSize(vectortype)) + "))"); code += "\n\t}\n"; if (vectortype.base_type == BASE_TYPE_STRING) { code += "\treturn nil\n"; @@ -518,8 +514,8 @@ class GoGenerator : public BaseGenerator { // Recursively generate struct construction statements and instert manual // padding. - void StructBuilderBody(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderBody(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { std::string &code = *code_ptr; code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", "; code += NumToString(struct_def.bytesize) + ")\n"; @@ -533,7 +529,9 @@ class GoGenerator : public BaseGenerator { (nameprefix + (field.name + "_")).c_str(), code_ptr); } else { code += "\tbuilder.Prepend" + GenMethod(field) + "("; - code += CastToBaseType(field.value.type, nameprefix + GoIdentity(field.name)) + ")\n"; + code += CastToBaseType(field.value.type, + nameprefix + GoIdentity(field.name)) + + ")\n"; } } } @@ -582,8 +580,8 @@ class GoGenerator : public BaseGenerator { } // Set the value of one of the members of a table's vector. - void BuildVectorOfTable(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { std::string &code = *code_ptr; code += "func " + struct_def.name + "Start"; code += MakeCamel(field.name); @@ -612,8 +610,8 @@ class GoGenerator : public BaseGenerator { } // Generate a struct field getter, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { GenComment(field.doc_comment, code_ptr, nullptr, ""); if (IsScalar(field.value.type.base_type)) { if (struct_def.fixed) { @@ -630,7 +628,9 @@ class GoGenerator : public BaseGenerator { GetStructFieldOfTable(struct_def, field, code_ptr); } break; - case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break; + case BASE_TYPE_STRING: + GetStringField(struct_def, field, code_ptr); + break; case BASE_TYPE_VECTOR: { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_STRUCT) { @@ -652,10 +652,9 @@ class GoGenerator : public BaseGenerator { } } - // Mutate the value of a struct's scalar. + // Mutate the value of a struct's scalar. void MutateScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string type = MakeCamel(GenTypeBasic(field.value.type)); std::string setter = "rcv._tab.Mutate" + type; @@ -669,8 +668,7 @@ class GoGenerator : public BaseGenerator { // Mutate the value of a table's scalar. void MutateScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string type = MakeCamel(GenTypeBasic(field.value.type)); std::string setter = "rcv._tab.Mutate" + type + "Slot"; @@ -916,9 +914,9 @@ class GoGenerator : public BaseGenerator { if (IsScalar(field.value.type.element)) { code += "\t\t\tbuilder.Prepend" + MakeCamel(GenTypeBasic(field.value.type.VectorType())) + "(" + - CastToBaseType( - field.value.type.VectorType(), - "t." + MakeCamel(field.name) + "[j]") + ")\n"; + CastToBaseType(field.value.type.VectorType(), + "t." + MakeCamel(field.name) + "[j]") + + ")\n"; } else if (field.value.type.element == BASE_TYPE_STRUCT && field.value.type.struct_def->fixed) { code += "\t\t\t" + @@ -979,8 +977,8 @@ class GoGenerator : public BaseGenerator { code += "}\n\n"; } - void GenNativeTableUnPack( - const StructDef &struct_def, std::string *code_ptr) { + void GenNativeTableUnPack(const StructDef &struct_def, + std::string *code_ptr) { std::string &code = *code_ptr; code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" + @@ -995,8 +993,8 @@ class GoGenerator : public BaseGenerator { if (field.value.type.enum_def != nullptr && field.value.type.enum_def->is_union) continue; - code += "\tt." + field_name_camel + " = rcv." + field_name_camel + - "()\n"; + code += + "\tt." + field_name_camel + " = rcv." + field_name_camel + "()\n"; } else if (field.value.type.base_type == BASE_TYPE_STRING) { code += "\tt." + field_name_camel + " = string(rcv." + field_name_camel + "())\n"; @@ -1084,8 +1082,8 @@ class GoGenerator : public BaseGenerator { } } - void GenNativeStructUnPack( - const StructDef &struct_def, std::string *code_ptr) { + void GenNativeStructUnPack(const StructDef &struct_def, + std::string *code_ptr) { std::string &code = *code_ptr; code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" + @@ -1137,8 +1135,7 @@ class GoGenerator : public BaseGenerator { EndEnumNames(code_ptr); BeginEnumValues(enum_def, code_ptr); - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); - ++it) { + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { auto &ev = **it; EnumValueMember(enum_def, ev, max_name_length, code_ptr); } @@ -1189,9 +1186,7 @@ class GoGenerator : public BaseGenerator { } std::string GenTypeGet(const Type &type) { - if (type.enum_def != nullptr) { - return GetEnumTypeName(*type.enum_def); - } + if (type.enum_def != nullptr) { return GetEnumTypeName(*type.enum_def); } return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type); } @@ -1221,7 +1216,8 @@ class GoGenerator : public BaseGenerator { std::string GenConstant(const FieldDef &field) { switch (field.value.type.base_type) { - case BASE_TYPE_BOOL: return field.value.constant == "0" ? "false" : "true"; + case BASE_TYPE_BOOL: + return field.value.constant == "0" ? "false" : "true"; default: return field.value.constant; } } @@ -1248,11 +1244,11 @@ class GoGenerator : public BaseGenerator { } else if (type.base_type == BASE_TYPE_VECTOR) { return "[]" + NativeType(type.VectorType()); } else if (type.base_type == BASE_TYPE_STRUCT) { - return "*" + WrapInNameSpaceAndTrack( - type.struct_def->defined_namespace, NativeName(*type.struct_def)); + return "*" + WrapInNameSpaceAndTrack(type.struct_def->defined_namespace, + NativeName(*type.struct_def)); } else if (type.base_type == BASE_TYPE_UNION) { - return "*" + WrapInNameSpaceAndTrack( - type.enum_def->defined_namespace, NativeName(*type.enum_def)); + return "*" + WrapInNameSpaceAndTrack(type.enum_def->defined_namespace, + NativeName(*type.enum_def)); } FLATBUFFERS_ASSERT(0); return std::string(); @@ -1271,13 +1267,12 @@ class GoGenerator : public BaseGenerator { void BeginFile(const std::string &name_space_name, const bool needs_imports, const bool is_enum, std::string *code_ptr) { std::string &code = *code_ptr; - code = code + "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n"; + code = code + + "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n"; code += "package " + name_space_name + "\n\n"; if (needs_imports) { code += "import (\n"; - if (is_enum) { - code += "\t\"strconv\"\n\n"; - } + if (is_enum) { code += "\t\"strconv\"\n\n"; } if (!parser_.opts.go_import.empty()) { code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n"; } else { @@ -1286,17 +1281,14 @@ class GoGenerator : public BaseGenerator { if (tracked_imported_namespaces_.size() > 0) { code += "\n"; for (auto it = tracked_imported_namespaces_.begin(); - it != tracked_imported_namespaces_.end(); - ++it) { - code += "\t" + NamespaceImportName(*it) + " \"" + \ - NamespaceImportPath(*it) + "\"\n"; + it != tracked_imported_namespaces_.end(); ++it) { + code += "\t" + NamespaceImportName(*it) + " \"" + + NamespaceImportPath(*it) + "\"\n"; } } code += ")\n\n"; } else { - if (is_enum) { - code += "import \"strconv\"\n\n"; - } + if (is_enum) { code += "import \"strconv\"\n\n"; } } } @@ -1364,8 +1356,7 @@ class GoGenerator : public BaseGenerator { static size_t MaxNameLength(const EnumDef &enum_def) { size_t max = 0; - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); - ++it) { + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { max = std::max((*it)->name.length(), max); } return max; diff --git a/src/idl_gen_grpc.cpp b/src/idl_gen_grpc.cpp index 1d5e8e5e..ec129902 100644 --- a/src/idl_gen_grpc.cpp +++ b/src/idl_gen_grpc.cpp @@ -20,7 +20,6 @@ #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" - #include "src/compiler/cpp_generator.h" #include "src/compiler/go_generator.h" #include "src/compiler/java_generator.h" @@ -35,9 +34,7 @@ namespace flatbuffers { class FlatBufMethod : public grpc_generator::Method { public: - enum Streaming { - kNone, kClient, kServer, kBiDi - }; + enum Streaming { kNone, kClient, kServer, kBiDi }; FlatBufMethod(const RPCCall *method) : method_(method) { streaming_ = kNone; @@ -171,7 +168,7 @@ class FlatBufPrinter : public grpc_generator::Printer { void Outdent() { indent_--; - FLATBUFFERS_ASSERT(indent_ >= 0); + FLATBUFFERS_ASSERT(indent_ >= 0); } private: @@ -182,9 +179,7 @@ class FlatBufPrinter : public grpc_generator::Printer { class FlatBufFile : public grpc_generator::File { public: - enum Language { - kLanguageGo, kLanguageCpp, kLanguageJava - }; + enum Language { kLanguageGo, kLanguageCpp, kLanguageJava }; FlatBufFile(const Parser &parser, const std::string &file_name, Language language) @@ -270,7 +265,8 @@ class GoGRPCGenerator : public flatbuffers::BaseGenerator { auto service = file.service(i); const Definition *def = parser_.services_.vec[i]; p.package_name = LastNamespacePart(*(def->defined_namespace)); - p.service_prefix = def->defined_namespace->GetFullyQualifiedName(""); // file.package(); + p.service_prefix = + def->defined_namespace->GetFullyQualifiedName(""); // file.package(); std::string output = grpc_go_generator::GenerateServiceSource(&file, service.get(), &p); std::string filename = @@ -313,20 +309,20 @@ bool GenerateCppGRPC(const Parser &parser, const std::string &path, std::string header_code = grpc_cpp_generator::GetHeaderPrologue(&fbfile, generator_parameters) + - grpc_cpp_generator::GetHeaderIncludes(&fbfile, generator_parameters) + - grpc_cpp_generator::GetHeaderServices(&fbfile, generator_parameters) + - grpc_cpp_generator::GetHeaderEpilogue(&fbfile, generator_parameters); + grpc_cpp_generator::GetHeaderIncludes(&fbfile, generator_parameters) + + grpc_cpp_generator::GetHeaderServices(&fbfile, generator_parameters) + + grpc_cpp_generator::GetHeaderEpilogue(&fbfile, generator_parameters); std::string source_code = grpc_cpp_generator::GetSourcePrologue(&fbfile, generator_parameters) + - grpc_cpp_generator::GetSourceIncludes(&fbfile, generator_parameters) + - grpc_cpp_generator::GetSourceServices(&fbfile, generator_parameters) + - grpc_cpp_generator::GetSourceEpilogue(&fbfile, generator_parameters); + grpc_cpp_generator::GetSourceIncludes(&fbfile, generator_parameters) + + grpc_cpp_generator::GetSourceServices(&fbfile, generator_parameters) + + grpc_cpp_generator::GetSourceEpilogue(&fbfile, generator_parameters); return flatbuffers::SaveFile((path + file_name + ".grpc.fb.h").c_str(), header_code, false) && - flatbuffers::SaveFile((path + file_name + ".grpc.fb.cc").c_str(), - source_code, false); + flatbuffers::SaveFile((path + file_name + ".grpc.fb.cc").c_str(), + source_code, false); } class JavaGRPCGenerator : public flatbuffers::BaseGenerator { diff --git a/src/idl_gen_js_ts.cpp b/src/idl_gen_js_ts.cpp index 84dc7374..8d86d302 100644 --- a/src/idl_gen_js_ts.cpp +++ b/src/idl_gen_js_ts.cpp @@ -127,9 +127,7 @@ class JsTsGenerator : public BaseGenerator { const auto &file = *it; const auto basename = flatbuffers::StripPath(flatbuffers::StripExtension(file)); - if (basename != file_name_) { - code += GenPrefixedImport(file, basename); - } + if (basename != file_name_) { code += GenPrefixedImport(file, basename); } } } @@ -309,14 +307,12 @@ class JsTsGenerator : public BaseGenerator { result += " " + type_name; break; } - default: { result += " {" + type_name + "}"; } - } - if (!arg_name.empty()) { - result += " " + arg_name; - } - if (include_newline) { - result += "\n"; + default: { + result += " {" + type_name + "}"; + } } + if (!arg_name.empty()) { result += " " + arg_name; } + if (include_newline) { result += "\n"; } return result; } @@ -605,7 +601,8 @@ class JsTsGenerator : public BaseGenerator { } void GenerateRootAccessor(StructDef &struct_def, std::string *code_ptr, - std::string &code, std::string &object_name, bool size_prefixed) { + std::string &code, std::string &object_name, + bool size_prefixed) { if (!struct_def.fixed) { GenDocComment(code_ptr, GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") + @@ -613,11 +610,13 @@ class JsTsGenerator : public BaseGenerator { GenTypeAnnotation(kReturns, object_name, "", false)); std::string sizePrefixed("SizePrefixed"); if (lang_.language == IDLOptions::kTs) { - code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" + Verbose(struct_def, "As"); + code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" + + Verbose(struct_def, "As"); code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name + "):" + object_name + " {\n"; } else { - code += object_name + ".get" + (size_prefixed ? sizePrefixed : "") + "Root" + Verbose(struct_def, "As"); + code += object_name + ".get" + (size_prefixed ? sizePrefixed : "") + + "Root" + Verbose(struct_def, "As"); code += " = function(bb, obj) {\n"; } code += " return (obj || new " + object_name; @@ -627,21 +626,22 @@ class JsTsGenerator : public BaseGenerator { } void GenerateFinisher(StructDef &struct_def, std::string *code_ptr, - std::string &code, std::string &object_name, bool size_prefixed) { + std::string &code, std::string &object_name, + bool size_prefixed) { if (parser_.root_struct_def_ == &struct_def) { std::string sizePrefixed("SizePrefixed"); GenDocComment( code_ptr, GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") + - GenTypeAnnotation(kParam, "flatbuffers.Offset", "offset", - false)); + GenTypeAnnotation(kParam, "flatbuffers.Offset", "offset", false)); if (lang_.language == IDLOptions::kTs) { - code += "static finish" + (size_prefixed ? sizePrefixed : "") + Verbose(struct_def) + "Buffer"; - code += - "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n"; + code += "static finish" + (size_prefixed ? sizePrefixed : "") + + Verbose(struct_def) + "Buffer"; + code += "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n"; } else { - code += object_name + ".finish" + (size_prefixed ? sizePrefixed : "") + Verbose(struct_def) + "Buffer"; + code += object_name + ".finish" + (size_prefixed ? sizePrefixed : "") + + Verbose(struct_def) + "Buffer"; code += " = function(builder, offset) {\n"; } @@ -650,9 +650,7 @@ class JsTsGenerator : public BaseGenerator { code += ", '" + parser_.file_identifier_ + "'"; } if (size_prefixed) { - if (parser_.file_identifier_.empty()) { - code += ", undefined"; - } + if (parser_.file_identifier_.empty()) { code += ", undefined"; } code += ", true"; } code += ");\n"; @@ -682,7 +680,8 @@ class JsTsGenerator : public BaseGenerator { code += " {\n"; if (lang_.language != IDLOptions::kTs) { code += " /**\n"; - code += " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", ""); + code += + " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", ""); code += " */\n"; } code += " bb: flatbuffers.ByteBuffer|null = null;\n"; @@ -752,10 +751,9 @@ class JsTsGenerator : public BaseGenerator { // Generate the identifier check method if (!struct_def.fixed && parser_.root_struct_def_ == &struct_def && !parser_.file_identifier_.empty()) { - GenDocComment( - code_ptr, - GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") + - GenTypeAnnotation(kReturns, "boolean", "", false)); + GenDocComment(code_ptr, + GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") + + GenTypeAnnotation(kReturns, "boolean", "", false)); if (lang_.language == IDLOptions::kTs) { code += "static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean " @@ -872,7 +870,8 @@ class JsTsGenerator : public BaseGenerator { code += ", " + GenBBAccess() + ") : null;\n"; } - if (lang_.language == IDLOptions::kTs && !parser_.opts.generate_all) { + if (lang_.language == IDLOptions::kTs && + !parser_.opts.generate_all) { imported_files.insert(field.value.type.struct_def->file); } @@ -1290,8 +1289,7 @@ class JsTsGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) - continue; + if (field.deprecated) continue; paramDoc += GenTypeAnnotation(kParam, GetArgType(field), GetArgName(field)); } @@ -1311,8 +1309,7 @@ class JsTsGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) - continue; + if (field.deprecated) continue; if (lang_.language == IDLOptions::kTs) { code += ", " + GetArgName(field) + ":" + GetArgType(field); @@ -1336,8 +1333,7 @@ class JsTsGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) - continue; + if (field.deprecated) continue; code += " " + methodPrefix + ".add" + MakeCamel(field.name) + "("; code += "builder, " + GetArgName(field) + ");\n"; @@ -1346,14 +1342,11 @@ class JsTsGenerator : public BaseGenerator { code += " return " + methodPrefix + ".end" + Verbose(struct_def) + "(builder);\n"; code += "}\n"; - if (lang_.language == IDLOptions::kJs) - code += "\n"; + if (lang_.language == IDLOptions::kJs) code += "\n"; } if (lang_.language == IDLOptions::kTs) { - if (!object_namespace.empty()) { - code += "}\n"; - } + if (!object_namespace.empty()) { code += "}\n"; } code += "}\n"; } } @@ -1372,9 +1365,7 @@ class JsTsGenerator : public BaseGenerator { return argname; } - std::string Verbose(const StructDef &struct_def, - const char* prefix = "") - { + std::string Verbose(const StructDef &struct_def, const char *prefix = "") { return parser_.opts.js_ts_short_names ? "" : prefix + struct_def.name; } }; diff --git a/src/idl_gen_json_schema.cpp b/src/idl_gen_json_schema.cpp index 27e2cd46..5d7bad6d 100644 --- a/src/idl_gen_json_schema.cpp +++ b/src/idl_gen_json_schema.cpp @@ -15,6 +15,7 @@ */ #include <iostream> + #include "flatbuffers/code_generators.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" diff --git a/src/idl_gen_kotlin.cpp b/src/idl_gen_kotlin.cpp index d11599fe..b12e554d 100644 --- a/src/idl_gen_kotlin.cpp +++ b/src/idl_gen_kotlin.cpp @@ -18,12 +18,13 @@ #include <functional> #include <unordered_set> + #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" #if defined(FLATBUFFERS_CPP98_STL) -#include <cctype> +# include <cctype> #endif // defined(FLATBUFFERS_CPP98_STL) namespace flatbuffers { @@ -35,21 +36,20 @@ static TypedFloatConstantGenerator KotlinFloatGen("Double.", "Float.", "NaN", "POSITIVE_INFINITY", "NEGATIVE_INFINITY"); -static const CommentConfig comment_config = {"/**", " *", " */"}; +static const CommentConfig comment_config = { "/**", " *", " */" }; static const std::string ident_pad = " "; static const char *keywords[] = { - "package", "as", "typealias", "class", "this", "super", - "val", "var", "fun", "for", "null", "true", - "false", "is", "in", "throw", "return", "break", - "continue", "object", "if", "try", "else", "while", - "do", "when", "interface", "typeof", "Any", "Character"}; + "package", "as", "typealias", "class", "this", "super", + "val", "var", "fun", "for", "null", "true", + "false", "is", "in", "throw", "return", "break", + "continue", "object", "if", "try", "else", "while", + "do", "when", "interface", "typeof", "Any", "Character" +}; // Escape Keywords static std::string Esc(const std::string &name) { for (size_t i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) { - if (name == keywords[i]) { - return MakeCamel(name + "_", false); - } + if (name == keywords[i]) { return MakeCamel(name + "_", false); } } return MakeCamel(name, false); @@ -145,1380 +145,1298 @@ class KotlinGenerator : public BaseGenerator { #KTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD - }; - return kotlin_typename[type]; + // clang-format on + }; + return kotlin_typename[type]; + } + std::string GenTypePointer(const Type &type) const { + switch (type.base_type) { + case BASE_TYPE_STRING: return "String"; + case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType()); + case BASE_TYPE_STRUCT: return WrapInNameSpace(*type.struct_def); + default: return "Table"; } + } - std::string GenTypePointer(const Type &type) const { - switch (type.base_type) { - case BASE_TYPE_STRING: - return "String"; - case BASE_TYPE_VECTOR: - return GenTypeGet(type.VectorType()); - case BASE_TYPE_STRUCT: - return WrapInNameSpace(*type.struct_def); - default: - return "Table"; - } - } + std::string GenTypeGet(const Type &type) const { + return IsScalar(type.base_type) ? GenTypeBasic(type.base_type) + : GenTypePointer(type); + } - std::string GenTypeGet(const Type &type) const { - return IsScalar(type.base_type) ? GenTypeBasic(type.base_type) - : GenTypePointer(type); - } + std::string GenEnumDefaultValue(const FieldDef &field) const { + auto &value = field.value; + FLATBUFFERS_ASSERT(value.type.enum_def); + auto &enum_def = *value.type.enum_def; + auto enum_val = enum_def.FindByValue(value.constant); + return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name) + : value.constant; + } - std::string GenEnumDefaultValue(const FieldDef &field) const { - auto &value = field.value; - FLATBUFFERS_ASSERT(value.type.enum_def); - auto &enum_def = *value.type.enum_def; - auto enum_val = enum_def.FindByValue(value.constant); - return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name) - : value.constant; + // Generate default values to compare against a default value when + // `force_defaults` is `false`. + // Main differences are: + // - Floats are upcasted to doubles + // - Unsigned are casted to signed + std::string GenFBBDefaultValue(const FieldDef &field) const { + auto out = GenDefaultValue(field, true); + // All FlatBufferBuilder default floating point values are doubles + if (field.value.type.base_type == BASE_TYPE_FLOAT) { + if (out.find("Float") != std::string::npos) { + out.replace(0, 5, "Double"); + } } + // Guarantee all values are doubles + if (out.back() == 'f') out.pop_back(); + return out; + } - - // Generate default values to compare against a default value when - // `force_defaults` is `false`. - // Main differences are: - // - Floats are upcasted to doubles - // - Unsigned are casted to signed - std::string GenFBBDefaultValue(const FieldDef &field) const { - auto out = GenDefaultValue(field, true); - // All FlatBufferBuilder default floating point values are doubles - if (field.value.type.base_type == BASE_TYPE_FLOAT) { - if (out.find("Float") != std::string::npos) { - out.replace(0, 5, "Double"); - } - } - //Guarantee all values are doubles - if (out.back() == 'f') - out.pop_back(); - return out; + // FlatBufferBuilder only store signed types, so this function + // returns a cast for unsigned values + std::string GenFBBValueCast(const FieldDef &field) const { + if (IsUnsigned(field.value.type.base_type)) { + return CastToSigned(field.value.type); } + return ""; + } - - // FlatBufferBuilder only store signed types, so this function - // returns a cast for unsigned values - std::string GenFBBValueCast(const FieldDef &field) const { - if (IsUnsigned(field.value.type.base_type)) { - return CastToSigned(field.value.type); - } - return ""; + std::string GenDefaultValue(const FieldDef &field, + bool force_signed = false) const { + auto &value = field.value; + auto base_type = field.value.type.base_type; + if (IsFloat(base_type)) { + auto val = KotlinFloatGen.GenFloatConstant(field); + if (base_type == BASE_TYPE_DOUBLE && val.back() == 'f') { + val.pop_back(); + } + return val; } - std::string GenDefaultValue(const FieldDef &field, - bool force_signed = false) const { - auto &value = field.value; - auto base_type = field.value.type.base_type; - if (IsFloat(base_type)) { - auto val = KotlinFloatGen.GenFloatConstant(field); - if (base_type == BASE_TYPE_DOUBLE && - val.back() == 'f') { - val.pop_back(); - } - return val; - } - - if (base_type == BASE_TYPE_BOOL) { - return value.constant == "0" ? "false" : "true"; - } + if (base_type == BASE_TYPE_BOOL) { + return value.constant == "0" ? "false" : "true"; + } - std::string suffix = ""; + std::string suffix = ""; - if (base_type == BASE_TYPE_LONG || !force_signed) { - suffix = LiteralSuffix(base_type); - } - return value.constant + suffix; + if (base_type == BASE_TYPE_LONG || !force_signed) { + suffix = LiteralSuffix(base_type); } + return value.constant + suffix; + } - void GenEnum(EnumDef &enum_def, CodeWriter &writer) const { - if (enum_def.generated) return; - - GenerateComment(enum_def.doc_comment, writer, &comment_config); - - writer += "@Suppress(\"unused\")"; - writer += "@ExperimentalUnsignedTypes"; - writer += "class " + Esc(enum_def.name) + " private constructor() {"; - writer.IncrementIdentLevel(); - - GenerateCompanionObject(writer, [&](){ - // Write all properties - auto vals = enum_def.Vals(); - for (auto it = vals.begin(); it != vals.end(); ++it) { - auto &ev = **it; - auto field_type = GenTypeBasic(enum_def.underlying_type.base_type); - auto val = enum_def.ToString(ev); - auto suffix = LiteralSuffix(enum_def.underlying_type.base_type); - writer.SetValue("name", Esc(ev.name)); - writer.SetValue("type", field_type); - writer.SetValue("val", val + suffix); - GenerateComment(ev.doc_comment, writer, &comment_config); - writer += "const val {{name}}: {{type}} = {{val}}"; - } + void GenEnum(EnumDef &enum_def, CodeWriter &writer) const { + if (enum_def.generated) return; + + GenerateComment(enum_def.doc_comment, writer, &comment_config); + + writer += "@Suppress(\"unused\")"; + writer += "@ExperimentalUnsignedTypes"; + writer += "class " + Esc(enum_def.name) + " private constructor() {"; + writer.IncrementIdentLevel(); + + GenerateCompanionObject(writer, [&]() { + // Write all properties + auto vals = enum_def.Vals(); + for (auto it = vals.begin(); it != vals.end(); ++it) { + auto &ev = **it; + auto field_type = GenTypeBasic(enum_def.underlying_type.base_type); + auto val = enum_def.ToString(ev); + auto suffix = LiteralSuffix(enum_def.underlying_type.base_type); + writer.SetValue("name", Esc(ev.name)); + writer.SetValue("type", field_type); + writer.SetValue("val", val + suffix); + GenerateComment(ev.doc_comment, writer, &comment_config); + writer += "const val {{name}}: {{type}} = {{val}}"; + } - // Generate a generate string table for enum values. - // Problem is, if values are very sparse that could generate really - // big tables. Ideally in that case we generate a map lookup - // instead, but for the moment we simply don't output a table at all. - auto range = enum_def.Distance(); - // Average distance between values above which we consider a table - // "too sparse". Change at will. - static const uint64_t kMaxSparseness = 5; - if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness) { - GeneratePropertyOneLine(writer, "names", "Array<String>", - [&](){ - writer += "arrayOf(\\"; - auto val = enum_def.Vals().front(); - for (auto it = vals.begin(); it != vals.end(); ++it) { - auto ev = *it; - for (auto k = enum_def.Distance(val, ev); k > 1; --k) - writer += "\"\", \\"; - val = ev; - writer += "\"" + (*it)->name + "\"\\"; - if (it+1 != vals.end()) { - writer += ", \\"; - } - } - writer += ")"; - }); - GenerateFunOneLine(writer, "name", "e: Int", "String", [&](){ - writer += "names[e\\"; - if (enum_def.MinValue()->IsNonZero()) - writer += " - " + enum_def.MinValue()->name + ".toInt()\\"; - writer += "]"; - }); - } + // Generate a generate string table for enum values. + // Problem is, if values are very sparse that could generate really + // big tables. Ideally in that case we generate a map lookup + // instead, but for the moment we simply don't output a table at all. + auto range = enum_def.Distance(); + // Average distance between values above which we consider a table + // "too sparse". Change at will. + static const uint64_t kMaxSparseness = 5; + if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness) { + GeneratePropertyOneLine(writer, "names", "Array<String>", [&]() { + writer += "arrayOf(\\"; + auto val = enum_def.Vals().front(); + for (auto it = vals.begin(); it != vals.end(); ++it) { + auto ev = *it; + for (auto k = enum_def.Distance(val, ev); k > 1; --k) + writer += "\"\", \\"; + val = ev; + writer += "\"" + (*it)->name + "\"\\"; + if (it + 1 != vals.end()) { writer += ", \\"; } + } + writer += ")"; + }); + GenerateFunOneLine(writer, "name", "e: Int", "String", [&]() { + writer += "names[e\\"; + if (enum_def.MinValue()->IsNonZero()) + writer += " - " + enum_def.MinValue()->name + ".toInt()\\"; + writer += "]"; }); - writer.DecrementIdentLevel(); - writer += "}"; + } + }); + writer.DecrementIdentLevel(); + writer += "}"; + } + + // Returns the function name that is able to read a value of the given type. + std::string ByteBufferGetter(const Type &type, + std::string bb_var_name) const { + switch (type.base_type) { + case BASE_TYPE_STRING: return "__string"; + case BASE_TYPE_STRUCT: return "__struct"; + case BASE_TYPE_UNION: return "__union"; + case BASE_TYPE_VECTOR: + return ByteBufferGetter(type.VectorType(), bb_var_name); + case BASE_TYPE_INT: + case BASE_TYPE_UINT: return bb_var_name + ".getInt"; + case BASE_TYPE_SHORT: + case BASE_TYPE_USHORT: return bb_var_name + ".getShort"; + case BASE_TYPE_ULONG: + case BASE_TYPE_LONG: return bb_var_name + ".getLong"; + case BASE_TYPE_FLOAT: return bb_var_name + ".getFloat"; + case BASE_TYPE_DOUBLE: return bb_var_name + ".getDouble"; + case BASE_TYPE_CHAR: + case BASE_TYPE_UCHAR: + case BASE_TYPE_NONE: + case BASE_TYPE_UTYPE: return bb_var_name + ".get"; + case BASE_TYPE_BOOL: return "0.toByte() != " + bb_var_name + ".get"; + default: + return bb_var_name + ".get" + MakeCamel(GenTypeBasic(type.base_type)); } + } - // Returns the function name that is able to read a value of the given type. - std::string ByteBufferGetter(const Type &type, std::string bb_var_name) const { - switch (type.base_type) { - case BASE_TYPE_STRING: - return "__string"; - case BASE_TYPE_STRUCT: - return "__struct"; - case BASE_TYPE_UNION: - return "__union"; - case BASE_TYPE_VECTOR: - return ByteBufferGetter(type.VectorType(), bb_var_name); + std::string ByteBufferSetter(const Type &type) const { + if (IsScalar(type.base_type)) { + switch (type.base_type) { case BASE_TYPE_INT: - case BASE_TYPE_UINT: - return bb_var_name + ".getInt"; + case BASE_TYPE_UINT: return "bb.putInt"; case BASE_TYPE_SHORT: - case BASE_TYPE_USHORT: - return bb_var_name + ".getShort"; + case BASE_TYPE_USHORT: return "bb.putShort"; case BASE_TYPE_ULONG: - case BASE_TYPE_LONG: - return bb_var_name + ".getLong"; - case BASE_TYPE_FLOAT: - return bb_var_name + ".getFloat"; - case BASE_TYPE_DOUBLE: - return bb_var_name + ".getDouble"; + case BASE_TYPE_LONG: return "bb.putLong"; + case BASE_TYPE_FLOAT: return "bb.putFloat"; + case BASE_TYPE_DOUBLE: return "bb.putDouble"; case BASE_TYPE_CHAR: case BASE_TYPE_UCHAR: - case BASE_TYPE_NONE: - case BASE_TYPE_UTYPE: - return bb_var_name + ".get"; case BASE_TYPE_BOOL: - return "0.toByte() != " + bb_var_name + ".get"; - default: - return bb_var_name + ".get" + MakeCamel(GenTypeBasic(type.base_type)); - } + case BASE_TYPE_NONE: + case BASE_TYPE_UTYPE: return "bb.put"; + default: return "bb.put" + MakeCamel(GenTypeBasic(type.base_type)); + } } + return ""; + } - std::string ByteBufferSetter(const Type &type) const { - if (IsScalar(type.base_type)) { - switch (type.base_type) { - case BASE_TYPE_INT: - case BASE_TYPE_UINT: - return "bb.putInt"; - case BASE_TYPE_SHORT: - case BASE_TYPE_USHORT: - return "bb.putShort"; - case BASE_TYPE_ULONG: - case BASE_TYPE_LONG: - return "bb.putLong"; - case BASE_TYPE_FLOAT: - return "bb.putFloat"; - case BASE_TYPE_DOUBLE: - return "bb.putDouble"; - case BASE_TYPE_CHAR: - case BASE_TYPE_UCHAR: - case BASE_TYPE_BOOL: - case BASE_TYPE_NONE: - case BASE_TYPE_UTYPE: - return "bb.put"; - default: - return "bb.put" + MakeCamel(GenTypeBasic(type.base_type)); - } - } - return ""; - } + // Returns the function name that is able to read a value of the given type. + std::string GenLookupByKey(flatbuffers::FieldDef *key_field, + const std::string &bb_var_name, + const char *num = nullptr) const { + auto type = key_field->value.type; + return ByteBufferGetter(type, bb_var_name) + "(" + + GenOffsetGetter(key_field, num) + ")"; + } - // Returns the function name that is able to read a value of the given type. - std::string GenLookupByKey(flatbuffers::FieldDef *key_field, - const std::string &bb_var_name, - const char *num = nullptr) const { - auto type = key_field->value.type; - return ByteBufferGetter(type, bb_var_name) + "(" + GenOffsetGetter(key_field, num) + ")"; + // Returns the method name for use with add/put calls. + static std::string GenMethod(const Type &type) { + return IsScalar(type.base_type) ? ToSignedType(type) + : (IsStruct(type) ? "Struct" : "Offset"); + } + // Recursively generate arguments for a constructor, to deal with nested + // structs. + static void GenStructArgs(const StructDef &struct_def, CodeWriter &writer, + const char *nameprefix) { + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (IsStruct(field.value.type)) { + // Generate arguments for a struct inside a struct. To ensure + // names don't clash, and to make it obvious these arguments are + // constructing a nested struct, prefix the name with the field + // name. + GenStructArgs(*field.value.type.struct_def, writer, + (nameprefix + (field.name + "_")).c_str()); + } else { + writer += std::string(", ") + nameprefix + "\\"; + writer += MakeCamel(field.name) + ": \\"; + writer += GenTypeBasic(field.value.type.base_type) + "\\"; + } } + } - // Returns the method name for use with add/put calls. - static std::string GenMethod(const Type &type) { - return IsScalar(type.base_type) ? ToSignedType(type) - : (IsStruct(type) ? "Struct" : "Offset"); + // Recusively generate struct construction statements of the form: + // builder.putType(name); + // and insert manual padding. + static void GenStructBody(const StructDef &struct_def, CodeWriter &writer, + const char *nameprefix) { + writer.SetValue("align", NumToString(struct_def.minalign)); + writer.SetValue("size", NumToString(struct_def.bytesize)); + writer += "builder.prep({{align}}, {{size}})"; + auto fields_vec = struct_def.fields.vec; + for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) { + auto &field = **it; + + if (field.padding) { + writer.SetValue("pad", NumToString(field.padding)); + writer += "builder.pad({{pad}})"; + } + if (IsStruct(field.value.type)) { + GenStructBody(*field.value.type.struct_def, writer, + (nameprefix + (field.name + "_")).c_str()); + } else { + writer.SetValue("type", GenMethod(field.value.type)); + writer.SetValue("argname", nameprefix + MakeCamel(field.name, false)); + writer.SetValue("cast", CastToSigned(field.value.type)); + writer += "builder.put{{type}}({{argname}}{{cast}})"; + } } + } - // Recursively generate arguments for a constructor, to deal with nested - // structs. - static void GenStructArgs(const StructDef &struct_def, CodeWriter &writer, - const char *nameprefix) { - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (IsStruct(field.value.type)) { - // Generate arguments for a struct inside a struct. To ensure - // names don't clash, and to make it obvious these arguments are - // constructing a nested struct, prefix the name with the field - // name. - GenStructArgs(*field.value.type.struct_def, writer, - (nameprefix + (field.name + "_")).c_str()); - } else { - writer += std::string(", ") + nameprefix + "\\"; - writer += MakeCamel(field.name) + ": \\"; - writer += GenTypeBasic(field.value.type.base_type) + "\\"; - } - } + std::string GenByteBufferLength(const char *bb_name) const { + std::string bb_len = bb_name; + bb_len += ".capacity()"; + return bb_len; + } + + std::string GenOffsetGetter(flatbuffers::FieldDef *key_field, + const char *num = nullptr) const { + std::string key_offset = + "__offset(" + NumToString(key_field->value.offset) + ", "; + if (num) { + key_offset += num; + key_offset += ", _bb)"; + } else { + key_offset += GenByteBufferLength("bb"); + key_offset += " - tableOffset, bb)"; } + return key_offset; + } - // Recusively generate struct construction statements of the form: - // builder.putType(name); - // and insert manual padding. - static void GenStructBody(const StructDef &struct_def, CodeWriter &writer, - const char *nameprefix) { - writer.SetValue("align", NumToString(struct_def.minalign)); - writer.SetValue("size", NumToString(struct_def.bytesize)); - writer += "builder.prep({{align}}, {{size}})"; - auto fields_vec = struct_def.fields.vec; - for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) { - auto &field = **it; + void GenStruct(StructDef &struct_def, CodeWriter &writer) const { + if (struct_def.generated) return; - if (field.padding) { - writer.SetValue("pad", NumToString(field.padding)); - writer += "builder.pad({{pad}})"; - } - if (IsStruct(field.value.type)) { - GenStructBody(*field.value.type.struct_def, writer, - (nameprefix + (field.name + "_")).c_str()); - } else { - writer.SetValue("type", GenMethod(field.value.type)); - writer.SetValue("argname", nameprefix + - MakeCamel(field.name, false)); - writer.SetValue("cast", CastToSigned(field.value.type)); - writer += "builder.put{{type}}({{argname}}{{cast}})"; - } - } - } + GenerateComment(struct_def.doc_comment, writer, &comment_config); + auto fixed = struct_def.fixed; - std::string GenByteBufferLength(const char *bb_name) const { - std::string bb_len = bb_name; - bb_len += ".capacity()"; - return bb_len; - } + writer.SetValue("struct_name", Esc(struct_def.name)); + writer.SetValue("superclass", fixed ? "Struct" : "Table"); - std::string GenOffsetGetter(flatbuffers::FieldDef *key_field, - const char *num = nullptr) const { - std::string key_offset = "__offset(" + - NumToString(key_field->value.offset) + ", "; - if (num) { - key_offset += num; - key_offset += ", _bb)"; - } else { - key_offset += GenByteBufferLength("bb"); - key_offset += " - tableOffset, bb)"; - } - return key_offset; - } + writer += "@Suppress(\"unused\")"; + writer += "@ExperimentalUnsignedTypes"; + writer += "class {{struct_name}} : {{superclass}}() {\n"; - void GenStruct(StructDef &struct_def, CodeWriter &writer) const { - if (struct_def.generated) return; + writer.IncrementIdentLevel(); - GenerateComment(struct_def.doc_comment, writer, &comment_config); - auto fixed = struct_def.fixed; + { + // Generate the __init() method that sets the field in a pre-existing + // accessor object. This is to allow object reuse. + GenerateFun(writer, "__init", "_i: Int, _bb: ByteBuffer", "", + [&]() { writer += "__reset(_i, _bb)"; }); - writer.SetValue("struct_name", Esc(struct_def.name)); - writer.SetValue("superclass", fixed ? "Struct" : "Table"); + // Generate assign method + GenerateFun(writer, "__assign", "_i: Int, _bb: ByteBuffer", + Esc(struct_def.name), [&]() { + writer += "__init(_i, _bb)"; + writer += "return this"; + }); - writer += "@Suppress(\"unused\")"; - writer += "@ExperimentalUnsignedTypes"; - writer += "class {{struct_name}} : {{superclass}}() {\n"; + // Generate all getters + GenerateStructGetters(struct_def, writer); - writer.IncrementIdentLevel(); + // Generate Static Fields + GenerateCompanionObject(writer, [&]() { + if (!struct_def.fixed) { + FieldDef *key_field = nullptr; - { - // Generate the __init() method that sets the field in a pre-existing - // accessor object. This is to allow object reuse. - GenerateFun(writer, "__init", "_i: Int, _bb: ByteBuffer", "", [&]() { - writer += "__reset(_i, _bb)"; - }); + // Generate verson check method. + // Force compile time error if not using the same version + // runtime. + GenerateFunOneLine(writer, "validateVersion", "", "", [&]() { + writer += "Constants.FLATBUFFERS_1_11_1()"; + }); - // Generate assign method - GenerateFun(writer, "__assign", "_i: Int, _bb: ByteBuffer", - Esc(struct_def.name), [&]() { - writer += "__init(_i, _bb)"; - writer += "return this"; - }); + GenerateGetRootAsAccessors(Esc(struct_def.name), writer); + GenerateBufferHasIdentifier(struct_def, writer); + GenerateTableCreator(struct_def, writer); - // Generate all getters - GenerateStructGetters(struct_def, writer); + GenerateStartStructMethod(struct_def, writer); - // Generate Static Fields - GenerateCompanionObject(writer, [&](){ + // Static Add for fields + auto fields = struct_def.fields.vec; + int field_pos = -1; + for (auto it = fields.begin(); it != fields.end(); ++it) { + auto &field = **it; + field_pos++; + if (field.deprecated) continue; + if (field.key) key_field = &field; + GenerateAddField(NumToString(field_pos), field, writer); + + if (field.value.type.base_type == BASE_TYPE_VECTOR) { + auto vector_type = field.value.type.VectorType(); + if (!IsStruct(vector_type)) { + GenerateCreateVectorField(field, writer); + } + GenerateStartVectorField(field, writer); + } + } + + GenerateEndStructMethod(struct_def, writer); + auto file_identifier = parser_.file_identifier_; + if (parser_.root_struct_def_ == &struct_def) { + GenerateFinishStructBuffer(struct_def, file_identifier, writer); + GenerateFinishSizePrefixed(struct_def, file_identifier, writer); + } + + if (struct_def.has_key) { + GenerateLookupByKey(key_field, struct_def, writer); + } + } else { + GenerateStaticConstructor(struct_def, writer); + } + }); + } - if (!struct_def.fixed) { - FieldDef *key_field = nullptr; + // class closing + writer.DecrementIdentLevel(); + writer += "}"; + } - // Generate verson check method. - // Force compile time error if not using the same version - // runtime. - GenerateFunOneLine(writer, "validateVersion", "", "", [&](){ - writer += "Constants.FLATBUFFERS_1_11_1()"; - }); + // TODO: move key_field to reference instead of pointer + void GenerateLookupByKey(FieldDef *key_field, StructDef &struct_def, + CodeWriter &writer) const { + std::stringstream params; + params << "obj: " << Esc(struct_def.name) << "?" + << ", "; + params << "vectorLocation: Int, "; + params << "key: " << GenTypeGet(key_field->value.type) << ", "; + params << "bb: ByteBuffer"; + + auto statements = [&]() { + auto base_type = key_field->value.type.base_type; + writer.SetValue("struct_name", Esc(struct_def.name)); + if (base_type == BASE_TYPE_STRING) { + writer += + "val byteKey = key." + "toByteArray(Table.UTF8_CHARSET.get()!!)"; + } + writer += "var span = bb.getInt(vectorLocation - 4)"; + writer += "var start = 0"; + writer += "while (span != 0) {"; + writer.IncrementIdentLevel(); + writer += "var middle = span / 2"; + writer += + "val tableOffset = __indirect(vector" + "Location + 4 * (start + middle), bb)"; + if (key_field->value.type.base_type == BASE_TYPE_STRING) { + writer += "val comp = compareStrings(\\"; + writer += GenOffsetGetter(key_field) + "\\"; + writer += ", byteKey, bb)"; + } else { + auto cast = CastToUsigned(key_field->value.type); + auto get_val = GenLookupByKey(key_field, "bb"); + writer += "val value = " + get_val + cast; + writer += "val comp = value.compareTo(key)"; + } + writer += "when {"; + writer.IncrementIdentLevel(); + writer += "comp > 0 -> span = middle"; + writer += "comp < 0 -> {"; + writer.IncrementIdentLevel(); + writer += "middle++"; + writer += "start += middle"; + writer += "span -= middle"; + writer.DecrementIdentLevel(); + writer += "}"; // end comp < 0 + writer += "else -> {"; + writer.IncrementIdentLevel(); + writer += "return (obj ?: {{struct_name}}()).__assign(tableOffset, bb)"; + writer.DecrementIdentLevel(); + writer += "}"; // end else + writer.DecrementIdentLevel(); + writer += "}"; // end when + writer.DecrementIdentLevel(); + writer += "}"; // end while + writer += "return null"; + }; + GenerateFun(writer, "__lookup_by_key", params.str(), + Esc(struct_def.name) + "?", statements); + } - GenerateGetRootAsAccessors(Esc(struct_def.name), writer); - GenerateBufferHasIdentifier(struct_def, writer); - GenerateTableCreator(struct_def, writer); - - GenerateStartStructMethod(struct_def, writer); - - // Static Add for fields - auto fields = struct_def.fields.vec; - int field_pos = -1; - for (auto it = fields.begin(); it != fields.end(); ++it) { - auto &field = **it; - field_pos++; - if (field.deprecated) continue; - if (field.key) key_field = &field; - GenerateAddField(NumToString(field_pos), field, writer); - - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - auto vector_type = field.value.type.VectorType(); - if (!IsStruct(vector_type)) { - GenerateCreateVectorField(field, writer); - } - GenerateStartVectorField(field, writer); - } - } - - GenerateEndStructMethod(struct_def, writer); - auto file_identifier = parser_.file_identifier_; - if (parser_.root_struct_def_ == &struct_def) { - GenerateFinishStructBuffer(struct_def, - file_identifier, - writer); - GenerateFinishSizePrefixed(struct_def, - file_identifier, - writer); - } - - if (struct_def.has_key) { - GenerateLookupByKey(key_field, struct_def, writer); - } - } else { - GenerateStaticConstructor(struct_def, writer); - } - }); - } + void GenerateFinishSizePrefixed(StructDef &struct_def, + const std::string &identifier, + CodeWriter &writer) const { + auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; + auto params = "builder: FlatBufferBuilder, offset: Int"; + auto method_name = "finishSizePrefixed" + Esc(struct_def.name) + "Buffer"; + GenerateFunOneLine(writer, method_name, params, "", [&]() { + writer += "builder.finishSizePrefixed(offset" + id + ")"; + }); + } + void GenerateFinishStructBuffer(StructDef &struct_def, + const std::string &identifier, + CodeWriter &writer) const { + auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; + auto params = "builder: FlatBufferBuilder, offset: Int"; + auto method_name = "finish" + Esc(struct_def.name) + "Buffer"; + GenerateFunOneLine(writer, method_name, params, "", + [&]() { writer += "builder.finish(offset" + id + ")"; }); + } - // class closing - writer.DecrementIdentLevel(); - writer += "}"; - } + void GenerateEndStructMethod(StructDef &struct_def, + CodeWriter &writer) const { + // Generate end{{TableName}}(builder: FlatBufferBuilder) method + auto name = "end" + Esc(struct_def.name); + auto params = "builder: FlatBufferBuilder"; + auto returns = "Int"; + auto field_vec = struct_def.fields.vec; + + GenerateFun(writer, name, params, returns, [&]() { + writer += "val o = builder.endTable()"; + writer.IncrementIdentLevel(); + for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated || !field.required) { continue; } + writer.SetValue("offset", NumToString(field.value.offset)); + writer += "builder.required(o, {{offset}})"; + } + writer.DecrementIdentLevel(); + writer += "return o"; + }); + } - // TODO: move key_field to reference instead of pointer - void GenerateLookupByKey(FieldDef *key_field, StructDef &struct_def, - CodeWriter &writer) const { - std::stringstream params; - params << "obj: " << Esc(struct_def.name) << "?" << ", "; - params << "vectorLocation: Int, "; - params << "key: " << GenTypeGet(key_field->value.type) << ", "; - params << "bb: ByteBuffer"; - - auto statements = [&]() { - auto base_type = key_field->value.type.base_type; - writer.SetValue("struct_name", Esc(struct_def.name)); - if (base_type == BASE_TYPE_STRING) { - writer += "val byteKey = key." - "toByteArray(Table.UTF8_CHARSET.get()!!)"; - } - writer += "var span = bb.getInt(vectorLocation - 4)"; - writer += "var start = 0"; - writer += "while (span != 0) {"; - writer.IncrementIdentLevel(); - writer += "var middle = span / 2"; - writer += "val tableOffset = __indirect(vector" - "Location + 4 * (start + middle), bb)"; - if (key_field->value.type.base_type == BASE_TYPE_STRING) { - writer += "val comp = compareStrings(\\"; - writer += GenOffsetGetter(key_field) + "\\"; - writer += ", byteKey, bb)"; - } else { - auto cast = CastToUsigned(key_field->value.type); - auto get_val = GenLookupByKey(key_field, "bb"); - writer += "val value = " + get_val + cast; - writer += "val comp = value.compareTo(key)"; - } - writer += "when {"; - writer.IncrementIdentLevel(); - writer += "comp > 0 -> span = middle"; - writer += "comp < 0 -> {"; - writer.IncrementIdentLevel(); - writer += "middle++"; - writer += "start += middle"; - writer += "span -= middle"; - writer.DecrementIdentLevel(); - writer += "}"; // end comp < 0 - writer += "else -> {"; - writer.IncrementIdentLevel(); - writer += "return (obj ?: {{struct_name}}()).__assign(tableOffset, bb)"; - writer.DecrementIdentLevel(); - writer += "}"; // end else - writer.DecrementIdentLevel(); - writer += "}"; // end when - writer.DecrementIdentLevel(); - writer += "}"; // end while - writer += "return null"; - }; - GenerateFun(writer, "__lookup_by_key", - params.str(), - Esc(struct_def.name) + "?", - statements); - } + // Generate a method to create a vector from a Kotlin array. + void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer) const { + auto vector_type = field.value.type.VectorType(); + auto method_name = "create" + MakeCamel(Esc(field.name)) + "Vector"; + auto params = "builder: FlatBufferBuilder, data: " + + GenTypeBasic(vector_type.base_type) + "Array"; + writer.SetValue("size", NumToString(InlineSize(vector_type))); + writer.SetValue("align", NumToString(InlineAlignment(vector_type))); + writer.SetValue("root", GenMethod(vector_type)); + writer.SetValue("cast", CastToSigned(vector_type)); + + GenerateFun(writer, method_name, params, "Int", [&]() { + writer += "builder.startVector({{size}}, data.size, {{align}})"; + writer += "for (i in data.size - 1 downTo 0) {"; + writer.IncrementIdentLevel(); + writer += "builder.add{{root}}(data[i]{{cast}})"; + writer.DecrementIdentLevel(); + writer += "}"; + writer += "return builder.endVector()"; + }); + } - void GenerateFinishSizePrefixed(StructDef &struct_def, - const std::string &identifier, - CodeWriter &writer) const { - auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; - auto params = "builder: FlatBufferBuilder, offset: Int"; - auto method_name = "finishSizePrefixed" + Esc(struct_def.name) + "Buffer"; - GenerateFunOneLine(writer, method_name, params, "", [&]() { - writer += "builder.finishSizePrefixed(offset" + id + ")"; - }); - } - void GenerateFinishStructBuffer(StructDef &struct_def, - const std::string &identifier, - CodeWriter &writer) const { - auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; - auto params = "builder: FlatBufferBuilder, offset: Int"; - auto method_name = "finish" + Esc(struct_def.name) + "Buffer"; - GenerateFunOneLine(writer, method_name, params, "", [&]() { - writer += "builder.finish(offset" + id + ")"; + void GenerateStartVectorField(FieldDef &field, CodeWriter &writer) const { + // Generate a method to start a vector, data to be added manually + // after. + auto vector_type = field.value.type.VectorType(); + auto params = "builder: FlatBufferBuilder, numElems: Int"; + writer.SetValue("size", NumToString(InlineSize(vector_type))); + writer.SetValue("align", NumToString(InlineAlignment(vector_type))); + + GenerateFunOneLine( + writer, "start" + MakeCamel(Esc(field.name) + "Vector", true), params, + "", [&]() { + writer += "builder.startVector({{size}}, numElems, {{align}})"; }); - } + } - void GenerateEndStructMethod(StructDef &struct_def, CodeWriter &writer) const { - // Generate end{{TableName}}(builder: FlatBufferBuilder) method - auto name = "end" + Esc(struct_def.name); - auto params = "builder: FlatBufferBuilder"; - auto returns = "Int"; - auto field_vec = struct_def.fields.vec; - - GenerateFun(writer, name, params, returns, [&](){ - writer += "val o = builder.endTable()"; - writer.IncrementIdentLevel(); - for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated || !field.required) { - continue; - } - writer.SetValue("offset", NumToString(field.value.offset)); - writer += "builder.required(o, {{offset}})"; - } - writer.DecrementIdentLevel(); - writer += "return o"; - }); - } + void GenerateAddField(std::string field_pos, FieldDef &field, + CodeWriter &writer) const { + auto field_type = GenTypeBasic(field.value.type.base_type); + auto secondArg = MakeCamel(Esc(field.name), false) + ": " + field_type; + GenerateFunOneLine(writer, "add" + MakeCamel(Esc(field.name), true), + "builder: FlatBufferBuilder, " + secondArg, "", [&]() { + auto method = GenMethod(field.value.type); + writer.SetValue("field_name", + MakeCamel(Esc(field.name), false)); + writer.SetValue("method_name", method); + writer.SetValue("pos", field_pos); + writer.SetValue("default", GenFBBDefaultValue(field)); + writer.SetValue("cast", GenFBBValueCast(field)); + + writer += "builder.add{{method_name}}({{pos}}, \\"; + writer += "{{field_name}}{{cast}}, {{default}})"; + }); + } - // Generate a method to create a vector from a Kotlin array. - void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer) const { - auto vector_type = field.value.type.VectorType(); - auto method_name = "create" + MakeCamel(Esc(field.name)) + "Vector"; - auto params = "builder: FlatBufferBuilder, data: " + - GenTypeBasic(vector_type.base_type) + "Array"; - writer.SetValue("size", NumToString(InlineSize(vector_type))); - writer.SetValue("align", NumToString(InlineAlignment(vector_type))); - writer.SetValue("root", GenMethod(vector_type)); - writer.SetValue("cast", CastToSigned(vector_type)); - - GenerateFun(writer, method_name, params, "Int", [&](){ - writer += "builder.startVector({{size}}, data.size, {{align}})"; - writer += "for (i in data.size - 1 downTo 0) {"; - writer.IncrementIdentLevel(); - writer += "builder.add{{root}}(data[i]{{cast}})"; - writer.DecrementIdentLevel(); - writer += "}"; - writer += "return builder.endVector()"; - }); + static std::string ToSignedType(const Type &type) { + switch (type.base_type) { + case BASE_TYPE_UINT: return GenTypeBasic(BASE_TYPE_INT); + case BASE_TYPE_ULONG: return GenTypeBasic(BASE_TYPE_LONG); + case BASE_TYPE_UCHAR: + case BASE_TYPE_NONE: + case BASE_TYPE_UTYPE: return GenTypeBasic(BASE_TYPE_CHAR); + case BASE_TYPE_USHORT: return GenTypeBasic(BASE_TYPE_SHORT); + case BASE_TYPE_VECTOR: return ToSignedType(type.VectorType()); + default: return GenTypeBasic(type.base_type); } + } - void GenerateStartVectorField(FieldDef &field, CodeWriter &writer) const { - // Generate a method to start a vector, data to be added manually - // after. - auto vector_type = field.value.type.VectorType(); - auto params = "builder: FlatBufferBuilder, numElems: Int"; - writer.SetValue("size", NumToString(InlineSize(vector_type))); - writer.SetValue("align", NumToString(InlineAlignment(vector_type))); - - GenerateFunOneLine(writer, - "start" + MakeCamel(Esc(field.name) + "Vector", true), - params, - "", - [&]() { - writer += "builder.startVector({{size}}, numElems, {{align}})"; - }); - } + static std::string FlexBufferBuilderCast(const std::string &method, + FieldDef &field, bool isFirst) { + auto field_type = GenTypeBasic(field.value.type.base_type); + std::string to_type; + if (method == "Boolean") + to_type = "Boolean"; + else if (method == "Long") + to_type = "Long"; + else if (method == "Int" || method == "Offset" || method == "Struct") + to_type = "Int"; + else if (method == "Byte" || method.empty()) + to_type = isFirst ? "Byte" : "Int"; + else if (method == "Short") + to_type = isFirst ? "Short" : "Int"; + else if (method == "Double") + to_type = "Double"; + else if (method == "Float") + to_type = isFirst ? "Float" : "Double"; + else if (method == "UByte") + + if (field_type != to_type) return ".to" + to_type + "()"; + return ""; + } - void GenerateAddField(std::string field_pos, FieldDef &field, - CodeWriter &writer) const { - auto field_type = GenTypeBasic(field.value.type.base_type); - auto secondArg = MakeCamel(Esc(field.name), false) + ": " + field_type; - GenerateFunOneLine(writer, "add" + MakeCamel(Esc(field.name), true), - "builder: FlatBufferBuilder, " + secondArg, "", [&](){ - auto method = GenMethod(field.value.type); - writer.SetValue("field_name", MakeCamel(Esc(field.name), false)); - writer.SetValue("method_name", method); - writer.SetValue("pos", field_pos); - writer.SetValue("default", GenFBBDefaultValue(field)); - writer.SetValue("cast", GenFBBValueCast(field)); - - writer += "builder.add{{method_name}}({{pos}}, \\"; - writer += "{{field_name}}{{cast}}, {{default}})"; - }); - } + // fun startMonster(builder: FlatBufferBuilder) = builder.startTable(11) + void GenerateStartStructMethod(StructDef &struct_def, + CodeWriter &code) const { + GenerateFunOneLine(code, "start" + Esc(struct_def.name), + "builder: FlatBufferBuilder", "", [&]() { + code += "builder.startTable(" + + NumToString(struct_def.fields.vec.size()) + + ")"; + }); + } - static std::string ToSignedType(const Type & type) { - switch(type.base_type) { - case BASE_TYPE_UINT: - return GenTypeBasic(BASE_TYPE_INT); - case BASE_TYPE_ULONG: - return GenTypeBasic(BASE_TYPE_LONG); - case BASE_TYPE_UCHAR: - case BASE_TYPE_NONE: - case BASE_TYPE_UTYPE: - return GenTypeBasic(BASE_TYPE_CHAR); - case BASE_TYPE_USHORT: - return GenTypeBasic(BASE_TYPE_SHORT); - case BASE_TYPE_VECTOR: - return ToSignedType(type.VectorType()); - default: - return GenTypeBasic(type.base_type); - } + void GenerateTableCreator(StructDef &struct_def, CodeWriter &writer) const { + // Generate a method that creates a table in one go. This is only possible + // when the table has no struct fields, since those have to be created + // inline, and there's no way to do so in Java. + bool has_no_struct_fields = true; + int num_fields = 0; + auto fields_vec = struct_def.fields.vec; + + for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; + if (IsStruct(field.value.type)) { + has_no_struct_fields = false; + } else { + num_fields++; + } } + // JVM specifications restrict default constructor params to be < 255. + // Longs and doubles take up 2 units, so we set the limit to be < 127. + if (has_no_struct_fields && num_fields && num_fields < 127) { + // Generate a table constructor of the form: + // public static int createName(FlatBufferBuilder builder, args...) + + auto name = "create" + Esc(struct_def.name); + std::stringstream params; + params << "builder: FlatBufferBuilder"; + for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; + params << ", " << MakeCamel(Esc(field.name), false); + if (!IsScalar(field.value.type.base_type)) { + params << "Offset: "; + } else { + params << ": "; + } + params << GenTypeBasic(field.value.type.base_type); + } - static std::string FlexBufferBuilderCast(const std::string &method, - FieldDef &field, - bool isFirst) { - auto field_type = GenTypeBasic(field.value.type.base_type); - std::string to_type; - if (method == "Boolean") - to_type = "Boolean"; - else if (method == "Long") - to_type = "Long"; - else if (method == "Int" || method == "Offset" || method == "Struct") - to_type = "Int"; - else if (method == "Byte" || method.empty()) - to_type = isFirst ? "Byte" : "Int"; - else if (method == "Short") - to_type = isFirst ? "Short" : "Int"; - else if (method == "Double") - to_type = "Double"; - else if (method == "Float") - to_type = isFirst ? "Float" : "Double"; - else if (method == "UByte") - - if (field_type != to_type) - return ".to" + to_type + "()"; - return ""; - } + GenerateFun(writer, name, params.str(), "Int", [&]() { + writer.SetValue("vec_size", NumToString(fields_vec.size())); - // fun startMonster(builder: FlatBufferBuilder) = builder.startTable(11) - void GenerateStartStructMethod(StructDef &struct_def, CodeWriter &code) const { - GenerateFunOneLine(code, "start" + Esc(struct_def.name), - "builder: FlatBufferBuilder", "", [&] () { - code += "builder.startTable("+ NumToString(struct_def.fields.vec.size()) + ")"; - }); + writer += "builder.startTable({{vec_size}})"; + + auto sortbysize = struct_def.sortbysize; + auto largest = sortbysize ? sizeof(largest_scalar_t) : 1; + for (size_t size = largest; size; size /= 2) { + for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) { + auto &field = **it; + auto base_type_size = SizeOf(field.value.type.base_type); + if (!field.deprecated && (!sortbysize || size == base_type_size)) { + writer.SetValue("camel_field_name", + MakeCamel(Esc(field.name), true)); + writer.SetValue("field_name", MakeCamel(Esc(field.name), false)); + + writer += "add{{camel_field_name}}(builder, {{field_name}}\\"; + if (!IsScalar(field.value.type.base_type)) { + writer += "Offset\\"; + } + writer += ")"; + } + } + } + writer += "return end{{struct_name}}(builder)"; + }); } + } + void GenerateBufferHasIdentifier(StructDef &struct_def, + CodeWriter &writer) const { + auto file_identifier = parser_.file_identifier_; + // Check if a buffer has the identifier. + if (parser_.root_struct_def_ != &struct_def || !file_identifier.length()) + return; + auto name = MakeCamel(Esc(struct_def.name), false); + GenerateFunOneLine(writer, name + "BufferHasIdentifier", "_bb: ByteBuffer", + "Boolean", [&]() { + writer += "__has_identifier(_bb, \"" + + file_identifier + "\")"; + }); + } - void GenerateTableCreator(StructDef &struct_def, CodeWriter &writer) const { - // Generate a method that creates a table in one go. This is only possible - // when the table has no struct fields, since those have to be created - // inline, and there's no way to do so in Java. - bool has_no_struct_fields = true; - int num_fields = 0; - auto fields_vec = struct_def.fields.vec; + void GenerateStructGetters(StructDef &struct_def, CodeWriter &writer) const { + auto fields_vec = struct_def.fields.vec; + FieldDef *key_field = nullptr; + for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; + if (field.key) key_field = &field; + + GenerateComment(field.doc_comment, writer, &comment_config); + + auto field_name = MakeCamel(Esc(field.name), false); + auto field_type = GenTypeGet(field.value.type); + auto field_default_value = GenDefaultValue(field); + auto return_type = GenTypeGet(field.value.type); + auto bbgetter = ByteBufferGetter(field.value.type, "bb"); + auto ucast = CastToUsigned(field); + auto offset_val = NumToString(field.value.offset); + auto offset_prefix = + "val o = __offset(" + offset_val + "); return o != 0 ? "; + auto value_base_type = field.value.type.base_type; + // Most field accessors need to retrieve and test the field offset + // first, this is the offset value for that: + writer.SetValue("offset", NumToString(field.value.offset)); + writer.SetValue("return_type", return_type); + writer.SetValue("field_type", field_type); + writer.SetValue("field_name", field_name); + writer.SetValue("field_default", field_default_value); + writer.SetValue("bbgetter", bbgetter); + writer.SetValue("ucast", ucast); + + auto opt_ret_type = return_type + "?"; + // Generate the accessors that don't do object reuse. + if (value_base_type == BASE_TYPE_STRUCT) { + // Calls the accessor that takes an accessor object with a + // new object. + // val pos + // get() = pos(Vec3()) + GenerateGetterOneLine(writer, field_name, opt_ret_type, [&]() { + writer += "{{field_name}}({{field_type}}())"; + }); + } else if (value_base_type == BASE_TYPE_VECTOR && + field.value.type.element == BASE_TYPE_STRUCT) { + // Accessors for vectors of structs also take accessor objects, + // this generates a variant without that argument. + // ex: fun weapons(j: Int) = weapons(Weapon(), j) + GenerateFunOneLine(writer, field_name, "j: Int", opt_ret_type, [&]() { + writer += "{{field_name}}({{return_type}}(), j)"; + }); + } - for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; - if (IsStruct(field.value.type)) { - has_no_struct_fields = false; + if (IsScalar(value_base_type)) { + if (struct_def.fixed) { + GenerateGetterOneLine(writer, field_name, return_type, [&]() { + writer += "{{bbgetter}}(bb_pos + {{offset}}){{ucast}}"; + }); + } else { + GenerateGetter(writer, field_name, return_type, [&]() { + writer += "val o = __offset({{offset}})"; + writer += + "return if(o != 0) {{bbgetter}}" + "(o + bb_pos){{ucast}} else " + "{{field_default}}"; + }); + } + } else { + switch (value_base_type) { + case BASE_TYPE_STRUCT: + if (struct_def.fixed) { + // create getter with object reuse + // ex: + // fun pos(obj: Vec3) : Vec3? = obj.__assign(bb_pos + 4, bb) + // ? adds nullability annotation + GenerateFunOneLine( + writer, field_name, "obj: " + field_type, return_type + "?", + [&]() { writer += "obj.__assign(bb_pos + {{offset}}, bb)"; }); } else { - num_fields++; + // create getter with object reuse + // ex: + // fun pos(obj: Vec3) : Vec3? { + // val o = __offset(4) + // return if(o != 0) { + // obj.__assign(o + bb_pos, bb) + // else { + // null + // } + // } + // ? adds nullability annotation + GenerateFun( + writer, field_name, "obj: " + field_type, return_type + "?", + [&]() { + auto fixed = field.value.type.struct_def->fixed; + + writer.SetValue("seek", Indirect("o + bb_pos", fixed)); + OffsetWrapper( + writer, offset_val, + [&]() { writer += "obj.__assign({{seek}}, bb)"; }, + [&]() { writer += "null"; }); + }); } - } - // JVM specifications restrict default constructor params to be < 255. - // Longs and doubles take up 2 units, so we set the limit to be < 127. - if (has_no_struct_fields && num_fields && num_fields < 127) { - // Generate a table constructor of the form: - // public static int createName(FlatBufferBuilder builder, args...) - - auto name = "create" + Esc(struct_def.name); - std::stringstream params; - params << "builder: FlatBufferBuilder"; - for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; - params << ", " << MakeCamel(Esc(field.name), false); - if (!IsScalar(field.value.type.base_type)){ - params << "Offset: "; - } else { - params << ": "; - } - params << GenTypeBasic(field.value.type.base_type); + break; + case BASE_TYPE_STRING: + // create string getter + // e.g. + // val Name : String? + // get() = { + // val o = __offset(10) + // return if (o != 0) __string(o + bb_pos) else null + // } + // ? adds nullability annotation + GenerateGetter(writer, field_name, return_type + "?", [&]() { + writer += "val o = __offset({{offset}})"; + writer += "return if (o != 0) __string(o + bb_pos) else null"; + }); + break; + case BASE_TYPE_VECTOR: { + // e.g. + // fun inventory(j: Int) : UByte { + // val o = __offset(14) + // return if (o != 0) { + // bb.get(__vector(o) + j * 1).toUByte() + // } else { + // 0 + // } + // } + + auto vectortype = field.value.type.VectorType(); + std::string params = "j: Int"; + std::string nullable = IsScalar(vectortype.base_type) ? "" : "?"; + + if (vectortype.base_type == BASE_TYPE_STRUCT || + vectortype.base_type == BASE_TYPE_UNION) { + params = "obj: " + field_type + ", j: Int"; } - GenerateFun(writer, name, params.str(), "Int", [&]() { - writer.SetValue("vec_size", NumToString(fields_vec.size())); - - writer += "builder.startTable({{vec_size}})"; - - auto sortbysize = struct_def.sortbysize; - auto largest = sortbysize ? sizeof(largest_scalar_t) : 1; - for (size_t size = largest; size; size /= 2) { - for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); - ++it) { - auto &field = **it; - auto base_type_size = SizeOf(field.value.type.base_type); - if (!field.deprecated && - (!sortbysize || size == base_type_size)) { - writer.SetValue("camel_field_name", - MakeCamel(Esc(field.name), true)); - writer.SetValue("field_name", - MakeCamel(Esc(field.name), false)); - - writer += "add{{camel_field_name}}(builder, {{field_name}}\\"; - if (!IsScalar(field.value.type.base_type)){ - writer += "Offset\\"; - } - writer += ")"; - } - } + auto ret_type = return_type + nullable; + GenerateFun(writer, field_name, params, ret_type, [&]() { + auto inline_size = NumToString(InlineSize(vectortype)); + auto index = "__vector(o) + j * " + inline_size; + auto not_found = NotFoundReturn(field.value.type.element); + auto found = ""; + writer.SetValue("index", index); + switch (vectortype.base_type) { + case BASE_TYPE_STRUCT: { + bool fixed = vectortype.struct_def->fixed; + writer.SetValue("index", Indirect(index, fixed)); + found = "obj.__assign({{index}}, bb)"; + break; } - writer += "return end{{struct_name}}(builder)"; + case BASE_TYPE_UNION: + found = "{{bbgetter}}(obj, {{index}} - bb_pos){{ucast}}"; + break; + default: found = "{{bbgetter}}({{index}}){{ucast}}"; + } + OffsetWrapper( + writer, offset_val, [&]() { writer += found; }, + [&]() { writer += not_found; }); }); + break; + } + case BASE_TYPE_UNION: + GenerateFun(writer, field_name, "obj: " + field_type, + return_type + "?", [&]() { + writer += OffsetWrapperOneLine( + offset_val, bbgetter + "(obj, o + bb_pos)", + "null"); + }); + break; + default: FLATBUFFERS_ASSERT(0); } + } - } - void GenerateBufferHasIdentifier(StructDef &struct_def, - CodeWriter &writer) const { - auto file_identifier = parser_.file_identifier_; - // Check if a buffer has the identifier. - if (parser_.root_struct_def_ != &struct_def || !file_identifier.length()) - return; - auto name = MakeCamel(Esc(struct_def.name), false); - GenerateFunOneLine(writer, name + "BufferHasIdentifier", - "_bb: ByteBuffer", - "Boolean", - [&]() { - writer += "__has_identifier(_bb, \"" + file_identifier + "\")"; + if (value_base_type == BASE_TYPE_VECTOR) { + // Generate Lenght functions for vectors + GenerateGetter(writer, field_name + "Length", "Int", [&]() { + writer += OffsetWrapperOneLine(offset_val, "__vector_len(o)", "0"); }); - } - - void GenerateStructGetters(StructDef &struct_def, CodeWriter &writer) const { - auto fields_vec = struct_def.fields.vec; - FieldDef *key_field = nullptr; - for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; - if (field.key) key_field = &field; - GenerateComment(field.doc_comment, writer, &comment_config); - - auto field_name = MakeCamel(Esc(field.name), false); - auto field_type = GenTypeGet(field.value.type); - auto field_default_value = GenDefaultValue(field); - auto return_type = GenTypeGet(field.value.type); - auto bbgetter = ByteBufferGetter(field.value.type, "bb"); - auto ucast = CastToUsigned(field); - auto offset_val = NumToString(field.value.offset); - auto offset_prefix = "val o = __offset(" + offset_val - + "); return o != 0 ? "; - auto value_base_type = field.value.type.base_type; - // Most field accessors need to retrieve and test the field offset - // first, this is the offset value for that: - writer.SetValue("offset", NumToString(field.value.offset)); - writer.SetValue("return_type", return_type); - writer.SetValue("field_type", field_type); - writer.SetValue("field_name", field_name); - writer.SetValue("field_default", field_default_value); - writer.SetValue("bbgetter", bbgetter); - writer.SetValue("ucast", ucast); - - auto opt_ret_type = return_type + "?"; - // Generate the accessors that don't do object reuse. - if (value_base_type == BASE_TYPE_STRUCT) { - // Calls the accessor that takes an accessor object with a - // new object. - // val pos - // get() = pos(Vec3()) - GenerateGetterOneLine(writer, field_name, opt_ret_type, [&](){ - writer += "{{field_name}}({{field_type}}())"; - }); - } else if (value_base_type == BASE_TYPE_VECTOR && - field.value.type.element == BASE_TYPE_STRUCT) { - // Accessors for vectors of structs also take accessor objects, - // this generates a variant without that argument. - // ex: fun weapons(j: Int) = weapons(Weapon(), j) - GenerateFunOneLine(writer, field_name, "j: Int", opt_ret_type, [&](){ - writer += "{{field_name}}({{return_type}}(), j)"; - }); + // See if we should generate a by-key accessor. + if (field.value.type.element == BASE_TYPE_STRUCT && + !field.value.type.struct_def->fixed) { + auto &sd = *field.value.type.struct_def; + auto &fields = sd.fields.vec; + for (auto kit = fields.begin(); kit != fields.end(); ++kit) { + auto &kfield = **kit; + if (kfield.key) { + auto qualified_name = WrapInNameSpace(sd); + auto name = MakeCamel(Esc(field.name), false) + "ByKey"; + auto params = "key: " + GenTypeGet(kfield.value.type); + auto rtype = qualified_name + "?"; + GenerateFun(writer, name, params, rtype, [&]() { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += qualified_name + + ".__lookup_by_key(null, __vector(o), key, bb)"; + }, + [&]() { writer += "null"; }); + }); + + auto param2 = "obj: " + qualified_name + + ", key: " + GenTypeGet(kfield.value.type); + GenerateFun(writer, name, param2, rtype, [&]() { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += qualified_name + + ".__lookup_by_key(obj, __vector(o), key, bb)"; + }, + [&]() { writer += "null"; }); + }); + + break; } + } + } + } - if (IsScalar(value_base_type)) { - if (struct_def.fixed) { - GenerateGetterOneLine(writer, field_name, return_type, [&](){ - writer += "{{bbgetter}}(bb_pos + {{offset}}){{ucast}}"; - }); - } else { - GenerateGetter(writer, field_name, return_type, [&](){ - writer += "val o = __offset({{offset}})"; - writer += "return if(o != 0) {{bbgetter}}" - "(o + bb_pos){{ucast}} else " - "{{field_default}}"; - }); - } - } else { - switch (value_base_type) { - case BASE_TYPE_STRUCT: - if (struct_def.fixed) { - // create getter with object reuse - // ex: - // fun pos(obj: Vec3) : Vec3? = obj.__assign(bb_pos + 4, bb) - // ? adds nullability annotation - GenerateFunOneLine(writer, - field_name, "obj: " + field_type , - return_type + "?", [&](){ - writer += "obj.__assign(bb_pos + {{offset}}, bb)"; - }); - } else { - // create getter with object reuse - // ex: - // fun pos(obj: Vec3) : Vec3? { - // val o = __offset(4) - // return if(o != 0) { - // obj.__assign(o + bb_pos, bb) - // else { - // null - // } - // } - // ? adds nullability annotation - GenerateFun(writer, field_name, "obj: " + field_type, - return_type + "?", [&](){ - auto fixed = field.value.type.struct_def->fixed; - - writer.SetValue("seek", Indirect("o + bb_pos", fixed)); - OffsetWrapper(writer, - offset_val, - [&]() { writer += "obj.__assign({{seek}}, bb)"; }, - [&]() { writer += "null"; }); - }); - } - break; - case BASE_TYPE_STRING: - // create string getter - // e.g. - // val Name : String? - // get() = { - // val o = __offset(10) - // return if (o != 0) __string(o + bb_pos) else null - // } - // ? adds nullability annotation - GenerateGetter(writer, field_name, return_type + "?", [&](){ - - writer += "val o = __offset({{offset}})"; - writer += "return if (o != 0) __string(o + bb_pos) else null"; - }); - break; - case BASE_TYPE_VECTOR: { - // e.g. - // fun inventory(j: Int) : UByte { - // val o = __offset(14) - // return if (o != 0) { - // bb.get(__vector(o) + j * 1).toUByte() - // } else { - // 0 - // } - // } - - auto vectortype = field.value.type.VectorType(); - std::string params = "j: Int"; - std::string nullable = IsScalar(vectortype.base_type) ? "" - : "?"; - - if (vectortype.base_type == BASE_TYPE_STRUCT || - vectortype.base_type == BASE_TYPE_UNION) { - params = "obj: " + field_type + ", j: Int"; - } - - auto ret_type = return_type + nullable; - GenerateFun(writer, field_name, params, ret_type, [&](){ - auto inline_size = NumToString(InlineSize(vectortype)); - auto index = "__vector(o) + j * " + inline_size; - auto not_found = NotFoundReturn(field.value.type.element); - auto found = ""; - writer.SetValue("index", index); - switch(vectortype.base_type) { - case BASE_TYPE_STRUCT: { - bool fixed = vectortype.struct_def->fixed; - writer.SetValue("index", Indirect(index, fixed)); - found = "obj.__assign({{index}}, bb)"; - break; - } - case BASE_TYPE_UNION: - found = "{{bbgetter}}(obj, {{index}} - bb_pos){{ucast}}"; - break; - default: - found = "{{bbgetter}}({{index}}){{ucast}}"; - } - OffsetWrapper(writer, offset_val, - [&]() { writer += found; } , - [&]() { writer += not_found; }); - }); - break; - } - case BASE_TYPE_UNION: - GenerateFun(writer, field_name, "obj: " + field_type, - return_type + "?", [&](){ - writer += OffsetWrapperOneLine(offset_val, - bbgetter + "(obj, o + bb_pos)", - "null"); - }); - break; - default: - FLATBUFFERS_ASSERT(0); - } - } + if ((value_base_type == BASE_TYPE_VECTOR && + IsScalar(field.value.type.VectorType().base_type)) || + value_base_type == BASE_TYPE_STRING) { + auto end_idx = + NumToString(value_base_type == BASE_TYPE_STRING + ? 1 + : InlineSize(field.value.type.VectorType())); + // Generate a ByteBuffer accessor for strings & vectors of scalars. + // e.g. + // val inventoryByteBuffer: ByteBuffer + // get = __vector_as_bytebuffer(14, 1) + + GenerateGetterOneLine( + writer, field_name + "AsByteBuffer", "ByteBuffer", [&]() { + writer.SetValue("end", end_idx); + writer += "__vector_as_bytebuffer({{offset}}, {{end}})"; + }); - if (value_base_type == BASE_TYPE_VECTOR) { - // Generate Lenght functions for vectors - GenerateGetter(writer, field_name + "Length", "Int", [&](){ - writer += OffsetWrapperOneLine(offset_val, - "__vector_len(o)", "0"); - }); - - // See if we should generate a by-key accessor. - if (field.value.type.element == BASE_TYPE_STRUCT && - !field.value.type.struct_def->fixed) { - auto &sd = *field.value.type.struct_def; - auto &fields = sd.fields.vec; - for (auto kit = fields.begin(); kit != fields.end(); ++kit) { - auto &kfield = **kit; - if (kfield.key) { - auto qualified_name = WrapInNameSpace(sd); - auto name = MakeCamel(Esc(field.name), false) + "ByKey"; - auto params = "key: " + GenTypeGet(kfield.value.type); - auto rtype = qualified_name + "?"; - GenerateFun(writer, name, params, rtype, [&] () { - OffsetWrapper(writer, offset_val, - [&] () { - writer += qualified_name + - ".__lookup_by_key(null, __vector(o), key, bb)"; - }, - [&] () { - writer += "null"; - }); - }); - - auto param2 = "obj: " + qualified_name + - ", key: " + - GenTypeGet(kfield.value.type); - GenerateFun(writer, name, param2, rtype, [&](){ - OffsetWrapper(writer, offset_val, - [&] () { - writer += qualified_name + - ".__lookup_by_key(obj, __vector(o), key, bb)"; - }, - [&]() { writer += "null"; }); - }); - - break; - } - } - } - } + // Generate a ByteBuffer accessor for strings & vectors of scalars. + // e.g. + // fun inventoryInByteBuffer(_bb: Bytebuffer): + // ByteBuffer = __vector_as_bytebuffer(_bb, 14, 1) + GenerateFunOneLine( + writer, field_name + "InByteBuffer", "_bb: ByteBuffer", + "ByteBuffer", [&]() { + writer.SetValue("end", end_idx); + writer += "__vector_in_bytebuffer(_bb, {{offset}}, {{end}})"; + }); + } - if ((value_base_type == BASE_TYPE_VECTOR && - IsScalar(field.value.type.VectorType().base_type)) || - value_base_type == BASE_TYPE_STRING) { - - auto end_idx = NumToString(value_base_type == BASE_TYPE_STRING - ? 1 - : InlineSize(field.value.type.VectorType())); - // Generate a ByteBuffer accessor for strings & vectors of scalars. - // e.g. - // val inventoryByteBuffer: ByteBuffer - // get = __vector_as_bytebuffer(14, 1) - - GenerateGetterOneLine(writer, field_name + "AsByteBuffer", - "ByteBuffer", [&](){ - writer.SetValue("end", end_idx); - writer += "__vector_as_bytebuffer({{offset}}, {{end}})"; - }); - - // Generate a ByteBuffer accessor for strings & vectors of scalars. - // e.g. - // fun inventoryInByteBuffer(_bb: Bytebuffer): - // ByteBuffer = __vector_as_bytebuffer(_bb, 14, 1) - GenerateFunOneLine(writer, field_name + "InByteBuffer", - "_bb: ByteBuffer", "ByteBuffer", [&](){ - writer.SetValue("end", end_idx); - writer += "__vector_in_bytebuffer(_bb, {{offset}}, {{end}})"; - }); - } + // generate object accessors if is nested_flatbuffer + // fun testnestedflatbufferAsMonster() : Monster? + //{ return testnestedflatbufferAsMonster(new Monster()); } - // generate object accessors if is nested_flatbuffer - //fun testnestedflatbufferAsMonster() : Monster? - //{ return testnestedflatbufferAsMonster(new Monster()); } - - if (field.nested_flatbuffer) { - auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer); - auto nested_method_name = - field_name + "As" + - field.nested_flatbuffer->name; - - GenerateGetterOneLine(writer, - nested_method_name, - nested_type_name + "?", [&](){ - writer += nested_method_name + "(" + nested_type_name + "())"; - }); - - GenerateFun(writer, - nested_method_name, - "obj: " + nested_type_name, - nested_type_name + "?", [&](){ - OffsetWrapper(writer, offset_val, - [&]() { writer += "obj.__assign(__indirect(__vector(o)), bb)"; }, - [&]() { writer += "null";}); - }); - } + if (field.nested_flatbuffer) { + auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer); + auto nested_method_name = + field_name + "As" + field.nested_flatbuffer->name; - // Generate mutators for scalar fields or vectors of scalars. - if (parser_.opts.mutable_buffer) { - auto value_type = field.value.type; - auto underlying_type = value_base_type == BASE_TYPE_VECTOR - ? value_type.VectorType() - : value_type; - auto name = "mutate" + MakeCamel(Esc(field.name), true); - auto size = NumToString(InlineSize(underlying_type)); - auto params = Esc(field.name) + ": " + GenTypeGet(underlying_type); - // A vector mutator also needs the index of the vector element it should - // mutate. - if (value_base_type == BASE_TYPE_VECTOR) - params.insert(0, "j: Int, "); - - // Boolean parameters have to be explicitly converted to byte - // representation. - auto setter_parameter = underlying_type.base_type == BASE_TYPE_BOOL - ? "(if(" + Esc(field.name) + ") 1 else 0).toByte()" - : Esc(field.name); - - auto setter_index = value_base_type == BASE_TYPE_VECTOR - ? "__vector(o) + j * " + size - : (struct_def.fixed - ? "bb_pos + " + offset_val - : "o + bb_pos"); - if (IsScalar(value_base_type) || (value_base_type == BASE_TYPE_VECTOR && - IsScalar(value_type.VectorType().base_type))) { - - auto statements = [&] () { - writer.SetValue("bbsetter", ByteBufferSetter(underlying_type)); - writer.SetValue("index", setter_index); - writer.SetValue("params", setter_parameter); - writer.SetValue("cast", CastToSigned(field)); - if (struct_def.fixed) { - writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; - } else { - OffsetWrapper(writer, offset_val, [&](){ - writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; - writer += "true"; - }, [&](){ writer += "false";}); - } - }; - - if (struct_def.fixed) { - GenerateFunOneLine(writer, name, params, "ByteBuffer", - statements); - } else { - GenerateFun(writer, name, params, "Boolean", - statements); - } - } - } - } - if (struct_def.has_key && !struct_def.fixed) { - // Key Comparison method - GenerateOverrideFun( - writer, - "keysCompare", - "o1: Int, o2: Int, _bb: ByteBuffer", "Int", [&]() { - if (key_field->value.type.base_type == BASE_TYPE_STRING) { - writer.SetValue("offset", NumToString(key_field->value.offset)); - writer += " return compareStrings(__offset({{offset}}, o1, " - "_bb), __offset({{offset}}, o2, _bb), _bb)"; - - } else { - auto getter1 = GenLookupByKey(key_field, "_bb", "o1"); - auto getter2 = GenLookupByKey(key_field, "_bb", "o2"); - writer += "val val_1 = " + getter1; - writer += "val val_2 = " + getter2; - writer += "return (val_1 - val_2).sign"; - } + GenerateGetterOneLine( + writer, nested_method_name, nested_type_name + "?", [&]() { + writer += nested_method_name + "(" + nested_type_name + "())"; }); - } - } - static std::string CastToUsigned(const FieldDef &field) { - return CastToUsigned(field.value.type); - } - - static std::string CastToUsigned(const Type type) { - switch (type.base_type) { - case BASE_TYPE_UINT: - return ".toUInt()"; - case BASE_TYPE_UCHAR: - case BASE_TYPE_UTYPE: - return ".toUByte()"; - case BASE_TYPE_USHORT: - return ".toUShort()"; - case BASE_TYPE_ULONG: - return ".toULong()"; - case BASE_TYPE_VECTOR: - return CastToUsigned(type.VectorType()); - default: - return ""; - } - } + GenerateFun(writer, nested_method_name, "obj: " + nested_type_name, + nested_type_name + "?", [&]() { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += + "obj.__assign(__indirect(__vector(o)), bb)"; + }, + [&]() { writer += "null"; }); + }); + } - static std::string CastToSigned(const FieldDef &field) { - return CastToSigned(field.value.type); - } + // Generate mutators for scalar fields or vectors of scalars. + if (parser_.opts.mutable_buffer) { + auto value_type = field.value.type; + auto underlying_type = value_base_type == BASE_TYPE_VECTOR + ? value_type.VectorType() + : value_type; + auto name = "mutate" + MakeCamel(Esc(field.name), true); + auto size = NumToString(InlineSize(underlying_type)); + auto params = Esc(field.name) + ": " + GenTypeGet(underlying_type); + // A vector mutator also needs the index of the vector element it should + // mutate. + if (value_base_type == BASE_TYPE_VECTOR) params.insert(0, "j: Int, "); + + // Boolean parameters have to be explicitly converted to byte + // representation. + auto setter_parameter = + underlying_type.base_type == BASE_TYPE_BOOL + ? "(if(" + Esc(field.name) + ") 1 else 0).toByte()" + : Esc(field.name); + + auto setter_index = + value_base_type == BASE_TYPE_VECTOR + ? "__vector(o) + j * " + size + : (struct_def.fixed ? "bb_pos + " + offset_val : "o + bb_pos"); + if (IsScalar(value_base_type) || + (value_base_type == BASE_TYPE_VECTOR && + IsScalar(value_type.VectorType().base_type))) { + auto statements = [&]() { + writer.SetValue("bbsetter", ByteBufferSetter(underlying_type)); + writer.SetValue("index", setter_index); + writer.SetValue("params", setter_parameter); + writer.SetValue("cast", CastToSigned(field)); + if (struct_def.fixed) { + writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; + } else { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; + writer += "true"; + }, + [&]() { writer += "false"; }); + } + }; - static std::string CastToSigned(const Type type) { - switch (type.base_type) { - case BASE_TYPE_UINT: - return ".toInt()"; - case BASE_TYPE_UCHAR: - case BASE_TYPE_UTYPE: - return ".toByte()"; - case BASE_TYPE_USHORT: - return ".toShort()"; - case BASE_TYPE_ULONG: - return ".toLong()"; - case BASE_TYPE_VECTOR: - return CastToSigned(type.VectorType()); - default: - return ""; + if (struct_def.fixed) { + GenerateFunOneLine(writer, name, params, "ByteBuffer", statements); + } else { + GenerateFun(writer, name, params, "Boolean", statements); + } } + } } + if (struct_def.has_key && !struct_def.fixed) { + // Key Comparison method + GenerateOverrideFun( + writer, "keysCompare", "o1: Int, o2: Int, _bb: ByteBuffer", "Int", + [&]() { + if (key_field->value.type.base_type == BASE_TYPE_STRING) { + writer.SetValue("offset", NumToString(key_field->value.offset)); + writer += + " return compareStrings(__offset({{offset}}, o1, " + "_bb), __offset({{offset}}, o2, _bb), _bb)"; - static std::string LiteralSuffix(const BaseType type) { - switch (type) { - case BASE_TYPE_UINT: - case BASE_TYPE_UCHAR: - case BASE_TYPE_UTYPE: - case BASE_TYPE_USHORT: - return "u"; - case BASE_TYPE_ULONG: - return "UL"; - case BASE_TYPE_LONG: - return "L"; - default: - return ""; - } + } else { + auto getter1 = GenLookupByKey(key_field, "_bb", "o1"); + auto getter2 = GenLookupByKey(key_field, "_bb", "o2"); + writer += "val val_1 = " + getter1; + writer += "val val_2 = " + getter2; + writer += "return (val_1 - val_2).sign"; + } + }); } + } + + static std::string CastToUsigned(const FieldDef &field) { + return CastToUsigned(field.value.type); + } - void GenerateCompanionObject(CodeWriter &code, - const std::function<void()> &callback) const { - code += "companion object {"; - code.IncrementIdentLevel(); - callback(); - code.DecrementIdentLevel(); - code += "}"; + static std::string CastToUsigned(const Type type) { + switch (type.base_type) { + case BASE_TYPE_UINT: return ".toUInt()"; + case BASE_TYPE_UCHAR: + case BASE_TYPE_UTYPE: return ".toUByte()"; + case BASE_TYPE_USHORT: return ".toUShort()"; + case BASE_TYPE_ULONG: return ".toULong()"; + case BASE_TYPE_VECTOR: return CastToUsigned(type.VectorType()); + default: return ""; } + } - // Generate a documentation comment, if available. - void GenerateComment(const std::vector<std::string> &dc, CodeWriter &writer, - const CommentConfig *config) const { - if (dc.begin() == dc.end()) { - // Don't output empty comment blocks with 0 lines of comment content. - return; - } + static std::string CastToSigned(const FieldDef &field) { + return CastToSigned(field.value.type); + } - if (config != nullptr && config->first_line != nullptr) { - writer += std::string(config->first_line); - } - std::string line_prefix = - ((config != nullptr && config->content_line_prefix != nullptr) - ? config->content_line_prefix - : "///"); - for (auto it = dc.begin(); it != dc.end(); ++it) { - writer += line_prefix + *it; - } - if (config != nullptr && config->last_line != nullptr) { - writer += std::string(config->last_line); - } + static std::string CastToSigned(const Type type) { + switch (type.base_type) { + case BASE_TYPE_UINT: return ".toInt()"; + case BASE_TYPE_UCHAR: + case BASE_TYPE_UTYPE: return ".toByte()"; + case BASE_TYPE_USHORT: return ".toShort()"; + case BASE_TYPE_ULONG: return ".toLong()"; + case BASE_TYPE_VECTOR: return CastToSigned(type.VectorType()); + default: return ""; } + } - static void GenerateGetRootAsAccessors(const std::string &struct_name, - CodeWriter &writer) { - // Generate a special accessor for the table that when used as the root - // ex: fun getRootAsMonster(_bb: ByteBuffer): Monster {...} - writer.SetValue("gr_name", struct_name); - writer.SetValue("gr_method", "getRootAs" + struct_name); - - // create convenience method that doesn't require an existing object - writer += "fun {{gr_method}}(_bb: ByteBuffer): {{gr_name}} = \\"; - writer += "{{gr_method}}(_bb, {{gr_name}}())"; - - // create method that allows object reuse - // ex: fun Monster getRootAsMonster(_bb: ByteBuffer, obj: Monster) {...} - writer += "fun {{gr_method}}" - "(_bb: ByteBuffer, obj: {{gr_name}}): {{gr_name}} {"; - writer.IncrementIdentLevel(); - writer += "_bb.order(ByteOrder.LITTLE_ENDIAN)"; - writer += "return (obj.__assign(_bb.getInt(_bb.position())" - " + _bb.position(), _bb))"; - writer.DecrementIdentLevel(); - writer += "}"; + static std::string LiteralSuffix(const BaseType type) { + switch (type) { + case BASE_TYPE_UINT: + case BASE_TYPE_UCHAR: + case BASE_TYPE_UTYPE: + case BASE_TYPE_USHORT: return "u"; + case BASE_TYPE_ULONG: return "UL"; + case BASE_TYPE_LONG: return "L"; + default: return ""; } + } - static void GenerateStaticConstructor(const StructDef &struct_def, - CodeWriter &code) { - // create a struct constructor function - auto params = StructConstructorParams(struct_def); - GenerateFun(code, "create" + Esc(struct_def.name), params, "Int", [&](){ - GenStructBody(struct_def, code, ""); - code += "return builder.offset()"; - }); - } + void GenerateCompanionObject(CodeWriter &code, + const std::function<void()> &callback) const { + code += "companion object {"; + code.IncrementIdentLevel(); + callback(); + code.DecrementIdentLevel(); + code += "}"; + } - static std::string StructConstructorParams(const StructDef &struct_def, - const std::string &prefix = "") { - //builder: FlatBufferBuilder - std::stringstream out; - auto field_vec = struct_def.fields.vec; - if (prefix.empty()) { - out << "builder: FlatBufferBuilder"; - } - for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { - auto &field = **it; - if (IsStruct(field.value.type)) { - // Generate arguments for a struct inside a struct. To ensure - // names don't clash, and to make it obvious these arguments are - // constructing a nested struct, prefix the name with the field - // name. - out << StructConstructorParams(*field.value.type.struct_def, - prefix + (Esc(field.name) + "_")); - } else { - out << ", " << prefix << MakeCamel(Esc(field.name), false) - << ": " - << GenTypeBasic(field.value.type.base_type); - } - } - return out.str(); + // Generate a documentation comment, if available. + void GenerateComment(const std::vector<std::string> &dc, CodeWriter &writer, + const CommentConfig *config) const { + if (dc.begin() == dc.end()) { + // Don't output empty comment blocks with 0 lines of comment content. + return; } - static void GeneratePropertyOneLine(CodeWriter &writer, - const std::string &name, - const std::string &type, - const std::function<void()> &body) { - // Generates Kotlin getter for properties - // e.g.: - // val prop: Mytype = x - writer.SetValue("_name", name); - writer.SetValue("_type", type); - writer += "val {{_name}} : {{_type}} = \\"; - body(); + if (config != nullptr && config->first_line != nullptr) { + writer += std::string(config->first_line); } - static void GenerateGetterOneLine(CodeWriter &writer, - const std::string &name, - const std::string &type, - const std::function<void()> &body) { - // Generates Kotlin getter for properties - // e.g.: - // val prop: Mytype get() = x - writer.SetValue("_name", name); - writer.SetValue("_type", type); - writer += "val {{_name}} : {{_type}} get() = \\"; - body(); + std::string line_prefix = + ((config != nullptr && config->content_line_prefix != nullptr) + ? config->content_line_prefix + : "///"); + for (auto it = dc.begin(); it != dc.end(); ++it) { + writer += line_prefix + *it; } - - static void GenerateGetter(CodeWriter &writer, - const std::string &name, - const std::string &type, - const std::function<void()> &body) { - // Generates Kotlin getter for properties - // e.g.: - // val prop: Mytype - // get() = { - // return x - // } - writer.SetValue("name", name); - writer.SetValue("type", type); - writer += "val {{name}} : {{type}}"; - writer.IncrementIdentLevel(); - writer += "get() {"; - writer.IncrementIdentLevel(); - body(); - writer.DecrementIdentLevel(); - writer += "}"; - writer.DecrementIdentLevel(); + if (config != nullptr && config->last_line != nullptr) { + writer += std::string(config->last_line); } + } - static void GenerateFun(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::function<void()> &body) { - // Generates Kotlin function - // e.g.: - // fun path(j: Int): Vec3 { - // return path(Vec3(), j) - // } - auto noreturn = returnType.empty(); - writer.SetValue("name", name); - writer.SetValue("params", params); - writer.SetValue("return_type", noreturn ? "" : ": " + returnType); - writer += "fun {{name}}({{params}}) {{return_type}} {"; - writer.IncrementIdentLevel(); - body(); - writer.DecrementIdentLevel(); - writer += "}"; - } + static void GenerateGetRootAsAccessors(const std::string &struct_name, + CodeWriter &writer) { + // Generate a special accessor for the table that when used as the root + // ex: fun getRootAsMonster(_bb: ByteBuffer): Monster {...} + writer.SetValue("gr_name", struct_name); + writer.SetValue("gr_method", "getRootAs" + struct_name); + + // create convenience method that doesn't require an existing object + writer += "fun {{gr_method}}(_bb: ByteBuffer): {{gr_name}} = \\"; + writer += "{{gr_method}}(_bb, {{gr_name}}())"; + + // create method that allows object reuse + // ex: fun Monster getRootAsMonster(_bb: ByteBuffer, obj: Monster) {...} + writer += + "fun {{gr_method}}" + "(_bb: ByteBuffer, obj: {{gr_name}}): {{gr_name}} {"; + writer.IncrementIdentLevel(); + writer += "_bb.order(ByteOrder.LITTLE_ENDIAN)"; + writer += + "return (obj.__assign(_bb.getInt(_bb.position())" + " + _bb.position(), _bb))"; + writer.DecrementIdentLevel(); + writer += "}"; + } - static void GenerateFunOneLine(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::function<void()> &body) { - // Generates Kotlin function - // e.g.: - // fun path(j: Int): Vec3 = return path(Vec3(), j) - writer.SetValue("name", name); - writer.SetValue("params", params); - writer.SetValue("return_type_p", returnType.empty() ? "" : - " : " + returnType); - writer += "fun {{name}}({{params}}){{return_type_p}} = \\"; - body(); - } + static void GenerateStaticConstructor(const StructDef &struct_def, + CodeWriter &code) { + // create a struct constructor function + auto params = StructConstructorParams(struct_def); + GenerateFun(code, "create" + Esc(struct_def.name), params, "Int", [&]() { + GenStructBody(struct_def, code, ""); + code += "return builder.offset()"; + }); + } - static void GenerateOverrideFun(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::function<void()> &body) { - // Generates Kotlin function - // e.g.: - // override fun path(j: Int): Vec3 = return path(Vec3(), j) - writer += "override \\"; - GenerateFun(writer, name, params, returnType, body); + static std::string StructConstructorParams(const StructDef &struct_def, + const std::string &prefix = "") { + // builder: FlatBufferBuilder + std::stringstream out; + auto field_vec = struct_def.fields.vec; + if (prefix.empty()) { out << "builder: FlatBufferBuilder"; } + for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { + auto &field = **it; + if (IsStruct(field.value.type)) { + // Generate arguments for a struct inside a struct. To ensure + // names don't clash, and to make it obvious these arguments are + // constructing a nested struct, prefix the name with the field + // name. + out << StructConstructorParams(*field.value.type.struct_def, + prefix + (Esc(field.name) + "_")); + } else { + out << ", " << prefix << MakeCamel(Esc(field.name), false) << ": " + << GenTypeBasic(field.value.type.base_type); + } } + return out.str(); + } - static void GenerateOverrideFunOneLine(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::string &statement) { - // Generates Kotlin function - // e.g.: - // override fun path(j: Int): Vec3 = return path(Vec3(), j) - writer.SetValue("name", name); - writer.SetValue("params", params); - writer.SetValue("return_type", returnType.empty() ? "" : - " : " + returnType); - writer += "override fun {{name}}({{params}}){{return_type}} = \\"; - writer += statement; - } + static void GeneratePropertyOneLine(CodeWriter &writer, + const std::string &name, + const std::string &type, + const std::function<void()> &body) { + // Generates Kotlin getter for properties + // e.g.: + // val prop: Mytype = x + writer.SetValue("_name", name); + writer.SetValue("_type", type); + writer += "val {{_name}} : {{_type}} = \\"; + body(); + } + static void GenerateGetterOneLine(CodeWriter &writer, const std::string &name, + const std::string &type, + const std::function<void()> &body) { + // Generates Kotlin getter for properties + // e.g.: + // val prop: Mytype get() = x + writer.SetValue("_name", name); + writer.SetValue("_type", type); + writer += "val {{_name}} : {{_type}} get() = \\"; + body(); + } - static std::string OffsetWrapperOneLine(const std::string &offset, - const std::string &found, - const std::string ¬_found) { - return "val o = __offset(" + offset + "); return if (o != 0) " + found + - " else " + not_found; - } + static void GenerateGetter(CodeWriter &writer, const std::string &name, + const std::string &type, + const std::function<void()> &body) { + // Generates Kotlin getter for properties + // e.g.: + // val prop: Mytype + // get() = { + // return x + // } + writer.SetValue("name", name); + writer.SetValue("type", type); + writer += "val {{name}} : {{type}}"; + writer.IncrementIdentLevel(); + writer += "get() {"; + writer.IncrementIdentLevel(); + body(); + writer.DecrementIdentLevel(); + writer += "}"; + writer.DecrementIdentLevel(); + } - static void OffsetWrapper(CodeWriter &code, - const std::string &offset, - const std::function<void()> &found, - const std::function<void()> ¬_found) { - code += "val o = __offset(" + offset + ")"; - code +="return if (o != 0) {"; - code.IncrementIdentLevel(); - found(); - code.DecrementIdentLevel(); - code += "} else {"; - code.IncrementIdentLevel(); - not_found(); - code.DecrementIdentLevel(); - code += "}"; - } + static void GenerateFun(CodeWriter &writer, const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::function<void()> &body) { + // Generates Kotlin function + // e.g.: + // fun path(j: Int): Vec3 { + // return path(Vec3(), j) + // } + auto noreturn = returnType.empty(); + writer.SetValue("name", name); + writer.SetValue("params", params); + writer.SetValue("return_type", noreturn ? "" : ": " + returnType); + writer += "fun {{name}}({{params}}) {{return_type}} {"; + writer.IncrementIdentLevel(); + body(); + writer.DecrementIdentLevel(); + writer += "}"; + } - static std::string Indirect(const std::string &index, bool fixed) { - // We apply __indirect() and struct is not fixed. - if (!fixed) - return "__indirect(" + index + ")"; - return index; - } + static void GenerateFunOneLine(CodeWriter &writer, const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::function<void()> &body) { + // Generates Kotlin function + // e.g.: + // fun path(j: Int): Vec3 = return path(Vec3(), j) + writer.SetValue("name", name); + writer.SetValue("params", params); + writer.SetValue("return_type_p", + returnType.empty() ? "" : " : " + returnType); + writer += "fun {{name}}({{params}}){{return_type_p}} = \\"; + body(); + } - static std::string NotFoundReturn(BaseType el) { - switch (el) { - case BASE_TYPE_FLOAT: - return "0.0f"; - case BASE_TYPE_DOUBLE: - return "0.0"; - case BASE_TYPE_BOOL: - return "false"; - case BASE_TYPE_LONG: - case BASE_TYPE_INT: - case BASE_TYPE_CHAR: - case BASE_TYPE_SHORT: - return "0"; - case BASE_TYPE_UINT: - case BASE_TYPE_UCHAR: - case BASE_TYPE_USHORT: - case BASE_TYPE_UTYPE: - return "0u"; - case BASE_TYPE_ULONG: - return "0uL"; - default: - return "null"; - } + static void GenerateOverrideFun(CodeWriter &writer, const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::function<void()> &body) { + // Generates Kotlin function + // e.g.: + // override fun path(j: Int): Vec3 = return path(Vec3(), j) + writer += "override \\"; + GenerateFun(writer, name, params, returnType, body); + } + + static void GenerateOverrideFunOneLine(CodeWriter &writer, + const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::string &statement) { + // Generates Kotlin function + // e.g.: + // override fun path(j: Int): Vec3 = return path(Vec3(), j) + writer.SetValue("name", name); + writer.SetValue("params", params); + writer.SetValue("return_type", + returnType.empty() ? "" : " : " + returnType); + writer += "override fun {{name}}({{params}}){{return_type}} = \\"; + writer += statement; + } + + static std::string OffsetWrapperOneLine(const std::string &offset, + const std::string &found, + const std::string ¬_found) { + return "val o = __offset(" + offset + "); return if (o != 0) " + found + + " else " + not_found; + } + + static void OffsetWrapper(CodeWriter &code, const std::string &offset, + const std::function<void()> &found, + const std::function<void()> ¬_found) { + code += "val o = __offset(" + offset + ")"; + code += "return if (o != 0) {"; + code.IncrementIdentLevel(); + found(); + code.DecrementIdentLevel(); + code += "} else {"; + code.IncrementIdentLevel(); + not_found(); + code.DecrementIdentLevel(); + code += "}"; + } + + static std::string Indirect(const std::string &index, bool fixed) { + // We apply __indirect() and struct is not fixed. + if (!fixed) return "__indirect(" + index + ")"; + return index; + } + + static std::string NotFoundReturn(BaseType el) { + switch (el) { + case BASE_TYPE_FLOAT: return "0.0f"; + case BASE_TYPE_DOUBLE: return "0.0"; + case BASE_TYPE_BOOL: return "false"; + case BASE_TYPE_LONG: + case BASE_TYPE_INT: + case BASE_TYPE_CHAR: + case BASE_TYPE_SHORT: return "0"; + case BASE_TYPE_UINT: + case BASE_TYPE_UCHAR: + case BASE_TYPE_USHORT: + case BASE_TYPE_UTYPE: return "0u"; + case BASE_TYPE_ULONG: return "0uL"; + default: return "null"; } + } - // This tracks the current namespace used to determine if a type need to be - // prefixed by its namespace - const Namespace *cur_name_space_; + // This tracks the current namespace used to determine if a type need to be + // prefixed by its namespace + const Namespace *cur_name_space_; }; } // namespace kotlin bool GenerateKotlin(const Parser &parser, const std::string &path, const std::string &file_name) { - kotlin::KotlinGenerator generator(parser, path, file_name); - return generator.generate(); + kotlin::KotlinGenerator generator(parser, path, file_name); + return generator.generate(); } } // namespace flatbuffers diff --git a/src/idl_gen_lobster.cpp b/src/idl_gen_lobster.cpp index ef9e474c..d5c99f7e 100644 --- a/src/idl_gen_lobster.cpp +++ b/src/idl_gen_lobster.cpp @@ -27,14 +27,16 @@ namespace lobster { class LobsterGenerator : public BaseGenerator { public: - LobsterGenerator(const Parser &parser, const std::string &path, - const std::string &file_name) + LobsterGenerator(const Parser &parser, const std::string &path, + const std::string &file_name) : BaseGenerator(parser, path, file_name, "" /* not used */, "_") { - static const char * const keywords[] = { - "nil", "true", "false", "return", "struct", "class", "import", "int", - "float", "string", "any", "def", "is", "from", "program", "private", - "coroutine", "resource", "enum", "typeof", "var", "let", "pakfile", - "switch", "case", "default", "namespace", "not", "and", "or", "bool", + static const char *const keywords[] = { + "nil", "true", "false", "return", "struct", "class", + "import", "int", "float", "string", "any", "def", + "is", "from", "program", "private", "coroutine", "resource", + "enum", "typeof", "var", "let", "pakfile", "switch", + "case", "default", "namespace", "not", "and", "or", + "bool", }; keywords_.insert(std::begin(keywords), std::end(keywords)); } @@ -66,7 +68,8 @@ class LobsterGenerator : public BaseGenerator { std::string LobsterType(const Type &type) { if (IsFloat(type.base_type)) return "float"; - if (IsScalar(type.base_type) && type.enum_def) return NormalizedName(*type.enum_def); + if (IsScalar(type.base_type) && type.enum_def) + return NormalizedName(*type.enum_def); if (!IsScalar(type.base_type)) return "flatbuffers_offset"; return "int"; } @@ -74,14 +77,14 @@ class LobsterGenerator : public BaseGenerator { // Returns the method name for use with add/put calls. std::string GenMethod(const Type &type) { return IsScalar(type.base_type) - ? MakeCamel(GenTypeBasic(type)) - : (IsStruct(type) ? "Struct" : "UOffsetTRelative"); + ? MakeCamel(GenTypeBasic(type)) + : (IsStruct(type) ? "Struct" : "UOffsetTRelative"); } // This uses Python names for now.. std::string GenTypeBasic(const Type &type) { static const char *ctypename[] = { - // clang-format off + // clang-format off #define FLATBUFFERS_TD(ENUM, IDLTYPE, \ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \ #PTYPE, @@ -93,8 +96,8 @@ class LobsterGenerator : public BaseGenerator { } // Generate a struct field, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { GenComment(field.doc_comment, code_ptr, nullptr, " "); std::string &code = *code_ptr; auto offsets = NumToString(field.value.offset); @@ -102,13 +105,12 @@ class LobsterGenerator : public BaseGenerator { if (IsScalar(field.value.type.base_type)) { std::string acc; if (struct_def.fixed) { - acc = "buf_.read_" + GenTypeName(field.value.type) + - "_le(pos_ + " + offsets + ")"; + acc = "buf_.read_" + GenTypeName(field.value.type) + "_le(pos_ + " + + offsets + ")"; } else { - acc = "buf_.flatbuffers_field_" + - GenTypeName(field.value.type) + "(pos_, " + offsets + ", " + - field.value.constant + ")"; + acc = "buf_.flatbuffers_field_" + GenTypeName(field.value.type) + + "(pos_, " + offsets + ", " + field.value.constant + ")"; } if (field.value.type.enum_def) acc = NormalizedName(*field.value.type.enum_def) + "(" + acc + ")"; @@ -130,7 +132,8 @@ class LobsterGenerator : public BaseGenerator { break; } case BASE_TYPE_STRING: - code += def + "():\n return buf_.flatbuffers_field_string(pos_, " + + code += def + + "():\n return buf_.flatbuffers_field_string(pos_, " + offsets + ")\n"; break; case BASE_TYPE_VECTOR: { @@ -171,19 +174,20 @@ class LobsterGenerator : public BaseGenerator { } if (field.value.type.base_type == BASE_TYPE_VECTOR) { code += def + - "_length():\n return buf_.flatbuffers_field_vector_len(pos_, " + + "_length():\n return " + "buf_.flatbuffers_field_vector_len(pos_, " + offsets + ")\n"; } } // Generate table constructors, conditioned on its members' types. - void GenTableBuilders(const StructDef &struct_def, - std::string *code_ptr) { + void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "struct " + NormalizedName(struct_def) + "Builder:\n b_:flatbuffers_builder\n"; code += " def start():\n b_.StartObject(" + - NumToString(struct_def.fields.vec.size()) + ")\n return this\n"; + NumToString(struct_def.fields.vec.size()) + + ")\n return this\n"; for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { auto &field = **it; @@ -209,8 +213,8 @@ class LobsterGenerator : public BaseGenerator { auto vector_type = field.value.type.VectorType(); auto alignment = InlineAlignment(vector_type); auto elem_size = InlineSize(vector_type); - code += NumToString(elem_size) + ", n_, " + NumToString(alignment) + - ")\n"; + code += + NumToString(elem_size) + ", n_, " + NumToString(alignment) + ")\n"; if (vector_type.base_type != BASE_TYPE_STRUCT || !vector_type.struct_def->fixed) { code += "def " + NormalizedName(struct_def) + "Create" + @@ -218,8 +222,7 @@ class LobsterGenerator : public BaseGenerator { "Vector(b_:flatbuffers_builder, v_:[" + LobsterType(vector_type) + "]):\n b_.StartVector(" + NumToString(elem_size) + ", v_.length, " + - NumToString(alignment) + - ")\n reverse(v_) e_: b_.Prepend" + + NumToString(alignment) + ")\n reverse(v_) e_: b_.Prepend" + GenMethod(vector_type) + "(e_)\n return b_.EndVector(v_.length)\n"; } @@ -243,7 +246,7 @@ class LobsterGenerator : public BaseGenerator { GenComment(struct_def.doc_comment, code_ptr, nullptr, ""); code += "class " + NormalizedName(struct_def) + " : flatbuffers_handle\n"; for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; if (field.deprecated) continue; GenStructAccessor(struct_def, field, code_ptr); @@ -252,8 +255,8 @@ class LobsterGenerator : public BaseGenerator { if (!struct_def.fixed) { // Generate a special accessor for the table that has been declared as // the root type. - code += "def GetRootAs" + NormalizedName(struct_def) + "(buf:string): return " + - NormalizedName(struct_def) + + code += "def GetRootAs" + NormalizedName(struct_def) + + "(buf:string): return " + NormalizedName(struct_def) + " { buf, buf.flatbuffers_indirect(0) }\n\n"; } if (struct_def.fixed) { @@ -283,8 +286,8 @@ class LobsterGenerator : public BaseGenerator { // Recursively generate arguments for a constructor, to deal with nested // structs. - void StructBuilderArgs(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { auto &field = **it; @@ -293,7 +296,8 @@ class LobsterGenerator : public BaseGenerator { // don't clash, and to make it obvious these arguments are constructing // a nested struct, prefix the name with the field name. StructBuilderArgs(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); } else { std::string &code = *code_ptr; code += ", " + (nameprefix + NormalizedName(field)) + ":" + @@ -304,8 +308,8 @@ class LobsterGenerator : public BaseGenerator { // Recursively generate struct construction statements and instert manual // padding. - void StructBuilderBody(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderBody(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { std::string &code = *code_ptr; code += " b_.Prep(" + NumToString(struct_def.minalign) + ", " + NumToString(struct_def.bytesize) + ")\n"; @@ -316,7 +320,8 @@ class LobsterGenerator : public BaseGenerator { code += " b_.Pad(" + NumToString(field.padding) + ")\n"; if (IsStruct(field.value.type)) { StructBuilderBody(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); } else { code += " b_.Prepend" + GenMethod(field.value.type) + "(" + nameprefix + NormalizedName(field) + ")\n"; @@ -325,11 +330,10 @@ class LobsterGenerator : public BaseGenerator { } // Create a struct with a builder and the struct's arguments. - void GenStructBuilder(const StructDef &struct_def, - std::string *code_ptr) { + void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; - code += "def Create" + NormalizedName(struct_def) + - "(b_:flatbuffers_builder"; + code += + "def Create" + NormalizedName(struct_def) + "(b_:flatbuffers_builder"; StructBuilderArgs(struct_def, "", code_ptr); code += "):\n"; StructBuilderBody(struct_def, "", code_ptr); @@ -363,8 +367,8 @@ class LobsterGenerator : public BaseGenerator { auto &struct_def = **it; GenStruct(struct_def, &code); } - return SaveFile((path_ + file_name_ + "_generated.lobster").c_str(), - code, false); + return SaveFile((path_ + file_name_ + "_generated.lobster").c_str(), code, + false); } private: @@ -375,7 +379,7 @@ class LobsterGenerator : public BaseGenerator { } // namespace lobster bool GenerateLobster(const Parser &parser, const std::string &path, - const std::string &file_name) { + const std::string &file_name) { lobster::LobsterGenerator generator(parser, path, file_name); return generator.generate(); } diff --git a/src/idl_gen_lua.cpp b/src/idl_gen_lua.cpp index 10df2311..6ae7dd4c 100644 --- a/src/idl_gen_lua.cpp +++ b/src/idl_gen_lua.cpp @@ -14,716 +14,710 @@ * limitations under the License. */ - // independent from idl_parser, since this code is not needed for most clients +// independent from idl_parser, since this code is not needed for most clients #include <string> +#include <unordered_set> #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include <unordered_set> - namespace flatbuffers { namespace lua { - // Hardcode spaces per indentation. - const CommentConfig def_comment = { nullptr, "--", nullptr }; - const char * Indent = " "; - const char * Comment = "-- "; - const char * End = "end\n"; - const char * EndFunc = "end\n"; - const char * SelfData = "self.view"; - const char * SelfDataPos = "self.view.pos"; - const char * SelfDataBytes = "self.view.bytes"; - - class LuaGenerator : public BaseGenerator { - public: - LuaGenerator(const Parser &parser, const std::string &path, - const std::string &file_name) +// Hardcode spaces per indentation. +const CommentConfig def_comment = { nullptr, "--", nullptr }; +const char *Indent = " "; +const char *Comment = "-- "; +const char *End = "end\n"; +const char *EndFunc = "end\n"; +const char *SelfData = "self.view"; +const char *SelfDataPos = "self.view.pos"; +const char *SelfDataBytes = "self.view.bytes"; + +class LuaGenerator : public BaseGenerator { + public: + LuaGenerator(const Parser &parser, const std::string &path, + const std::string &file_name) : BaseGenerator(parser, path, file_name, "" /* not used */, - "" /* not used */) { - static const char * const keywords[] = { - "and", - "break", - "do", - "else", - "elseif", - "end", - "false", - "for", - "function", - "goto", - "if", - "in", - "local", - "nil", - "not", - "or", - "repeat", - "return", - "then", - "true", - "until", - "while" - }; - keywords_.insert(std::begin(keywords), std::end(keywords)); - } - - // Most field accessors need to retrieve and test the field offset first, - // this is the prefix code for that. - std::string OffsetPrefix(const FieldDef &field) { - return std::string(Indent) + - "local o = " + SelfData + ":Offset(" + NumToString(field.value.offset) + ")\n" + - Indent + "if o ~= 0 then\n"; - } - - // Begin a class declaration. - void BeginClass(const StructDef &struct_def, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "local " + NormalizedName(struct_def) + " = {} -- the module\n"; - code += "local " + NormalizedMetaName(struct_def) + " = {} -- the class metatable\n"; - code += "\n"; - } - - // Begin enum code with a class declaration. - void BeginEnum(const std::string &class_name, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "local " + class_name + " = {\n"; - } - - std::string EscapeKeyword(const std::string &name) const { - return keywords_.find(name) == keywords_.end() ? name : "_" + name; - } - - std::string NormalizedName(const Definition &definition) const { - return EscapeKeyword(definition.name); - } - - std::string NormalizedName(const EnumVal &ev) const { - return EscapeKeyword(ev.name); - } - - std::string NormalizedMetaName(const Definition &definition) const { - return EscapeKeyword(definition.name) + "_mt"; - } - - // A single enum member. - void EnumMember(const EnumDef &enum_def, const EnumVal &ev, std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Indent) + NormalizedName(ev) + " = " + - enum_def.ToString(ev) + ",\n"; - } - - // End enum code. - void EndEnum(std::string *code_ptr) { - std::string &code = *code_ptr; - code += "}\n"; - } - - void GenerateNewObjectPrototype(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - code += "function " + NormalizedName(struct_def) + ".New()\n"; - code += std::string(Indent) + "local o = {}\n"; - code += std::string(Indent) + "setmetatable(o, {__index = " + NormalizedMetaName(struct_def) + "})\n"; - code += std::string(Indent) + "return o\n"; - code += EndFunc; - } - - // Initialize a new struct or table from existing data. - void NewRootTypeFromBuffer(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - code += "function " + NormalizedName(struct_def) + ".GetRootAs" + NormalizedName(struct_def) + "(buf, offset)\n"; - code += std::string(Indent) + "local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n"; - code += std::string(Indent) + "local o = " + NormalizedName(struct_def) + ".New()\n"; - code += std::string(Indent) + "o:Init(buf, n + offset)\n"; - code += std::string(Indent) + "return o\n"; - code += EndFunc; - } - - // Initialize an existing object with other data, to avoid an allocation. - void InitializeExisting(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - GenReceiver(struct_def, code_ptr); - code += "Init(buf, pos)\n"; - code += std::string(Indent) + SelfData + " = flatbuffers.view.New(buf, pos)\n"; - code += EndFunc; - } - - // Get the length of a vector. - void GetVectorLen(const StructDef &struct_def, const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)) + "Length()\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "return " + SelfData + ":VectorLen(o)\n"; - code += std::string(Indent) + End; + "" /* not used */) { + static const char *const keywords[] = { + "and", "break", "do", "else", "elseif", "end", "false", "for", + "function", "goto", "if", "in", "local", "nil", "not", "or", + "repeat", "return", "then", "true", "until", "while" + }; + keywords_.insert(std::begin(keywords), std::end(keywords)); + } + + // Most field accessors need to retrieve and test the field offset first, + // this is the prefix code for that. + std::string OffsetPrefix(const FieldDef &field) { + return std::string(Indent) + "local o = " + SelfData + ":Offset(" + + NumToString(field.value.offset) + ")\n" + Indent + + "if o ~= 0 then\n"; + } + + // Begin a class declaration. + void BeginClass(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "local " + NormalizedName(struct_def) + " = {} -- the module\n"; + code += "local " + NormalizedMetaName(struct_def) + + " = {} -- the class metatable\n"; + code += "\n"; + } + + // Begin enum code with a class declaration. + void BeginEnum(const std::string &class_name, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "local " + class_name + " = {\n"; + } + + std::string EscapeKeyword(const std::string &name) const { + return keywords_.find(name) == keywords_.end() ? name : "_" + name; + } + + std::string NormalizedName(const Definition &definition) const { + return EscapeKeyword(definition.name); + } + + std::string NormalizedName(const EnumVal &ev) const { + return EscapeKeyword(ev.name); + } + + std::string NormalizedMetaName(const Definition &definition) const { + return EscapeKeyword(definition.name) + "_mt"; + } + + // A single enum member. + void EnumMember(const EnumDef &enum_def, const EnumVal &ev, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Indent) + NormalizedName(ev) + " = " + + enum_def.ToString(ev) + ",\n"; + } + + // End enum code. + void EndEnum(std::string *code_ptr) { + std::string &code = *code_ptr; + code += "}\n"; + } + + void GenerateNewObjectPrototype(const StructDef &struct_def, + std::string *code_ptr) { + std::string &code = *code_ptr; + + code += "function " + NormalizedName(struct_def) + ".New()\n"; + code += std::string(Indent) + "local o = {}\n"; + code += std::string(Indent) + + "setmetatable(o, {__index = " + NormalizedMetaName(struct_def) + + "})\n"; + code += std::string(Indent) + "return o\n"; + code += EndFunc; + } + + // Initialize a new struct or table from existing data. + void NewRootTypeFromBuffer(const StructDef &struct_def, + std::string *code_ptr) { + std::string &code = *code_ptr; + + code += "function " + NormalizedName(struct_def) + ".GetRootAs" + + NormalizedName(struct_def) + "(buf, offset)\n"; + code += std::string(Indent) + + "local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n"; + code += std::string(Indent) + "local o = " + NormalizedName(struct_def) + + ".New()\n"; + code += std::string(Indent) + "o:Init(buf, n + offset)\n"; + code += std::string(Indent) + "return o\n"; + code += EndFunc; + } + + // Initialize an existing object with other data, to avoid an allocation. + void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + + GenReceiver(struct_def, code_ptr); + code += "Init(buf, pos)\n"; + code += + std::string(Indent) + SelfData + " = flatbuffers.view.New(buf, pos)\n"; + code += EndFunc; + } + + // Get the length of a vector. + void GetVectorLen(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)) + "Length()\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "return " + SelfData + ":VectorLen(o)\n"; + code += std::string(Indent) + End; + code += std::string(Indent) + "return 0\n"; + code += EndFunc; + } + + // Get the value of a struct's scalar. + void GetScalarFieldOfStruct(const StructDef &struct_def, + const FieldDef &field, std::string *code_ptr) { + std::string &code = *code_ptr; + std::string getter = GenGetter(field.value.type); + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += std::string(Indent) + "return " + getter; + code += std::string(SelfDataPos) + " + " + NumToString(field.value.offset) + + ")\n"; + code += EndFunc; + } + + // Get the value of a table's scalar. + void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + std::string getter = GenGetter(field.value.type); + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += OffsetPrefix(field); + getter += std::string("o + ") + SelfDataPos + ")"; + auto is_bool = field.value.type.base_type == BASE_TYPE_BOOL; + if (is_bool) { getter = "(" + getter + " ~= 0)"; } + code += std::string(Indent) + Indent + "return " + getter + "\n"; + code += std::string(Indent) + End; + std::string default_value; + if (is_bool) { + default_value = field.value.constant == "0" ? "false" : "true"; + } else { + default_value = field.value.constant; + } + code += std::string(Indent) + "return " + default_value + "\n"; + code += EndFunc; + } + + // Get a struct by initializing an existing struct. + // Specific to Struct. + void GetStructFieldOfStruct(const StructDef &struct_def, + const FieldDef &field, std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "(obj)\n"; + code += std::string(Indent) + "obj:Init(" + SelfDataBytes + ", " + + SelfDataPos + " + "; + code += NumToString(field.value.offset) + ")\n"; + code += std::string(Indent) + "return obj\n"; + code += EndFunc; + } + + // Get a struct by initializing an existing struct. + // Specific to Table. + void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += OffsetPrefix(field); + if (field.value.type.struct_def->fixed) { + code += + std::string(Indent) + Indent + "local x = o + " + SelfDataPos + "\n"; + } else { + code += std::string(Indent) + Indent + "local x = " + SelfData + + ":Indirect(o + " + SelfDataPos + ")\n"; + } + code += std::string(Indent) + Indent + "local obj = require('" + + TypeNameWithNamespace(field) + "').New()\n"; + code += + std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; + code += std::string(Indent) + Indent + "return obj\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a string. + void GetStringField(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "return " + GenGetter(field.value.type); + code += std::string("o + ") + SelfDataPos + ")\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a union from an object. + void GetUnionField(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)) + "()\n"; + code += OffsetPrefix(field); + + // TODO(rw): this works and is not the good way to it: + // bool is_native_table = TypeName(field) == "*flatbuffers.Table"; + // if (is_native_table) { + // code += std::string(Indent) + Indent + "from flatbuffers.table import + // Table\n"; + //} else { + // code += std::string(Indent) + Indent + + // code += "from ." + TypeName(field) + " import " + TypeName(field) + + // "\n"; + //} + code += + std::string(Indent) + Indent + + "local obj = " + "flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)\n"; + code += std::string(Indent) + Indent + GenGetter(field.value.type) + + "obj, o)\n"; + code += std::string(Indent) + Indent + "return obj\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a vector's struct member. + void GetMemberOfVectorOfStruct(const StructDef &struct_def, + const FieldDef &field, std::string *code_ptr) { + std::string &code = *code_ptr; + auto vectortype = field.value.type.VectorType(); + + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "(j)\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "local x = " + SelfData + ":Vector(o)\n"; + code += std::string(Indent) + Indent + "x = x + ((j-1) * "; + code += NumToString(InlineSize(vectortype)) + ")\n"; + if (!(vectortype.struct_def->fixed)) { + code += + std::string(Indent) + Indent + "x = " + SelfData + ":Indirect(x)\n"; + } + code += std::string(Indent) + Indent + "local obj = require('" + + TypeNameWithNamespace(field) + "').New()\n"; + code += + std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; + code += std::string(Indent) + Indent + "return obj\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a vector's non-struct member. Uses a named return + // argument to conveniently set the zero value for the result. + void GetMemberOfVectorOfNonStruct(const StructDef &struct_def, + const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + auto vectortype = field.value.type.VectorType(); + + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "(j)\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "local a = " + SelfData + ":Vector(o)\n"; + code += std::string(Indent) + Indent; + code += "return " + GenGetter(field.value.type); + code += "a + ((j-1) * "; + code += NumToString(InlineSize(vectortype)) + "))\n"; + code += std::string(Indent) + End; + if (vectortype.base_type == BASE_TYPE_STRING) { + code += std::string(Indent) + "return ''\n"; + } else { code += std::string(Indent) + "return 0\n"; - code += EndFunc; - } - - // Get the value of a struct's scalar. - void GetScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - std::string getter = GenGetter(field.value.type); - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += std::string(Indent) + "return " + getter; - code += std::string(SelfDataPos) + " + " + NumToString(field.value.offset) + ")\n"; - code += EndFunc; } - - // Get the value of a table's scalar. - void GetScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - std::string getter = GenGetter(field.value.type); - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += OffsetPrefix(field); - getter += std::string("o + ") + SelfDataPos + ")"; - auto is_bool = field.value.type.base_type == BASE_TYPE_BOOL; - if (is_bool) { - getter = "(" + getter + " ~= 0)"; - } - code += std::string(Indent) + Indent + "return " + getter + "\n"; - code += std::string(Indent) + End; - std::string default_value; - if (is_bool) { - default_value = field.value.constant == "0" ? "false" : "true"; - } - else { - default_value = field.value.constant; - } - code += std::string(Indent) + "return " + default_value + "\n"; - code += EndFunc; - } - - // Get a struct by initializing an existing struct. - // Specific to Struct. - void GetStructFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "(obj)\n"; - code += std::string(Indent) + "obj:Init(" + SelfDataBytes + ", " + SelfDataPos + " + "; - code += NumToString(field.value.offset) + ")\n"; - code += std::string(Indent) + "return obj\n"; - code += EndFunc; - } - - // Get a struct by initializing an existing struct. - // Specific to Table. - void GetStructFieldOfTable(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += OffsetPrefix(field); - if (field.value.type.struct_def->fixed) { - code += std::string(Indent) + Indent + "local x = o + " + SelfDataPos + "\n"; - } - else { - code += std::string(Indent) + Indent + "local x = " + SelfData + ":Indirect(o + " + SelfDataPos + ")\n"; + code += EndFunc; + } + + // Begin the creator function signature. + void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + + code += "function " + NormalizedName(struct_def) + ".Create" + + NormalizedName(struct_def); + code += "(builder"; + } + + // Recursively generate arguments for a constructor, to deal with nested + // structs. + void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (IsStruct(field.value.type)) { + // Generate arguments for a struct inside a struct. To ensure names + // don't clash, and to make it obvious these arguments are constructing + // a nested struct, prefix the name with the field name. + StructBuilderArgs(*field.value.type.struct_def, + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); + } else { + std::string &code = *code_ptr; + code += std::string(", ") + nameprefix; + code += MakeCamel(NormalizedName(field), false); } - code += std::string(Indent) + Indent + "local obj = require('" + TypeNameWithNamespace(field) + "').New()\n"; - code += std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; - code += std::string(Indent) + Indent + "return obj\n"; - code += std::string(Indent) + End; - code += EndFunc; } - - // Get the value of a string. - void GetStringField(const StructDef &struct_def, const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "return " + GenGetter(field.value.type); - code += std::string("o + ") + SelfDataPos + ")\n"; - code += std::string(Indent) + End; - code += EndFunc; - } - - // Get the value of a union from an object. - void GetUnionField(const StructDef &struct_def, const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)) + "()\n"; - code += OffsetPrefix(field); - - // TODO(rw): this works and is not the good way to it: - //bool is_native_table = TypeName(field) == "*flatbuffers.Table"; - //if (is_native_table) { - // code += std::string(Indent) + Indent + "from flatbuffers.table import Table\n"; - //} else { - // code += std::string(Indent) + Indent + - // code += "from ." + TypeName(field) + " import " + TypeName(field) + "\n"; - //} - code += std::string(Indent) + Indent + "local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)\n"; - code += std::string(Indent) + Indent + GenGetter(field.value.type) + "obj, o)\n"; - code += std::string(Indent) + Indent + "return obj\n"; - code += std::string(Indent) + End; - code += EndFunc; - } - - // Get the value of a vector's struct member. - void GetMemberOfVectorOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - auto vectortype = field.value.type.VectorType(); - - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "(j)\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "local x = " + SelfData + ":Vector(o)\n"; - code += std::string(Indent) + Indent + "x = x + ((j-1) * "; - code += NumToString(InlineSize(vectortype)) + ")\n"; - if (!(vectortype.struct_def->fixed)) { - code += std::string(Indent) + Indent + "x = " + SelfData + ":Indirect(x)\n"; - } - code += std::string(Indent) + Indent + "local obj = require('" + TypeNameWithNamespace(field) + "').New()\n"; - code += std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; - code += std::string(Indent) + Indent + "return obj\n"; - code += std::string(Indent) + End; - code += EndFunc; - } - - // Get the value of a vector's non-struct member. Uses a named return - // argument to conveniently set the zero value for the result. - void GetMemberOfVectorOfNonStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - auto vectortype = field.value.type.VectorType(); - - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "(j)\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "local a = " + SelfData + ":Vector(o)\n"; - code += std::string(Indent) + Indent; - code += "return " + GenGetter(field.value.type); - code += "a + ((j-1) * "; - code += NumToString(InlineSize(vectortype)) + "))\n"; - code += std::string(Indent) + End; - if (vectortype.base_type == BASE_TYPE_STRING) { - code += std::string(Indent) + "return ''\n"; - } - else { - code += std::string(Indent) + "return 0\n"; - } - code += EndFunc; - } - - // Begin the creator function signature. - void BeginBuilderArgs(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - code += "function " + NormalizedName(struct_def) + ".Create" + NormalizedName(struct_def); - code += "(builder"; - } - - // Recursively generate arguments for a constructor, to deal with nested - // structs. - void StructBuilderArgs(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (IsStruct(field.value.type)) { - // Generate arguments for a struct inside a struct. To ensure names - // don't clash, and to make it obvious these arguments are constructing - // a nested struct, prefix the name with the field name. - StructBuilderArgs(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); - } - else { - std::string &code = *code_ptr; - code += std::string(", ") + nameprefix; - code += MakeCamel(NormalizedName(field), false); - } - } - } - - // End the creator function signature. - void EndBuilderArgs(std::string *code_ptr) { - std::string &code = *code_ptr; - code += ")\n"; - } - - // Recursively generate struct construction statements and instert manual - // padding. - void StructBuilderBody(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Indent) + "builder:Prep(" + NumToString(struct_def.minalign) + ", "; - code += NumToString(struct_def.bytesize) + ")\n"; - for (auto it = struct_def.fields.vec.rbegin(); - it != struct_def.fields.vec.rend(); ++it) { - auto &field = **it; - if (field.padding) - code += std::string(Indent) + "builder:Pad(" + NumToString(field.padding) + ")\n"; - if (IsStruct(field.value.type)) { - StructBuilderBody(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); - } - else { - code += std::string(Indent) + "builder:Prepend" + GenMethod(field) + "("; - code += nameprefix + MakeCamel(NormalizedName(field), false) + ")\n"; - } + } + + // End the creator function signature. + void EndBuilderArgs(std::string *code_ptr) { + std::string &code = *code_ptr; + code += ")\n"; + } + + // Recursively generate struct construction statements and instert manual + // padding. + void StructBuilderBody(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Indent) + "builder:Prep(" + + NumToString(struct_def.minalign) + ", "; + code += NumToString(struct_def.bytesize) + ")\n"; + for (auto it = struct_def.fields.vec.rbegin(); + it != struct_def.fields.vec.rend(); ++it) { + auto &field = **it; + if (field.padding) + code += std::string(Indent) + "builder:Pad(" + + NumToString(field.padding) + ")\n"; + if (IsStruct(field.value.type)) { + StructBuilderBody(*field.value.type.struct_def, + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); + } else { + code += + std::string(Indent) + "builder:Prepend" + GenMethod(field) + "("; + code += nameprefix + MakeCamel(NormalizedName(field), false) + ")\n"; } } - - void EndBuilderBody(std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Indent) + "return builder:Offset()\n"; - code += EndFunc; - } - - // Get the value of a table's starting offset. - void GetStartOfTable(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".Start"; - code += "(builder) "; - code += "builder:StartObject("; - code += NumToString(struct_def.fields.vec.size()); - code += ") end\n"; - } - - // Set the value of a table's field. - void BuildFieldOfTable(const StructDef &struct_def, - const FieldDef &field, const size_t offset, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".Add" + MakeCamel(NormalizedName(field)); - code += "(builder, "; - code += MakeCamel(NormalizedName(field), false); - code += ") "; - code += "builder:Prepend"; - code += GenMethod(field) + "Slot("; - code += NumToString(offset) + ", "; - // todo: i don't need to cast in Lua, but am I missing something? + } + + void EndBuilderBody(std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Indent) + "return builder:Offset()\n"; + code += EndFunc; + } + + // Get the value of a table's starting offset. + void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".Start"; + code += "(builder) "; + code += "builder:StartObject("; + code += NumToString(struct_def.fields.vec.size()); + code += ") end\n"; + } + + // Set the value of a table's field. + void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field, + const size_t offset, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".Add" + + MakeCamel(NormalizedName(field)); + code += "(builder, "; + code += MakeCamel(NormalizedName(field), false); + code += ") "; + code += "builder:Prepend"; + code += GenMethod(field) + "Slot("; + code += NumToString(offset) + ", "; + // todo: i don't need to cast in Lua, but am I missing something? // if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) { // code += "flatbuffers.N.UOffsetTFlags.py_type"; // code += "("; // code += MakeCamel(NormalizedName(field), false) + ")"; // } else { - code += MakeCamel(NormalizedName(field), false); - // } - code += ", " + field.value.constant; - code += ") end\n"; - } - - // Set the value of one of the members of a table's vector. - void BuildVectorOfTable(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".Start"; - code += MakeCamel(NormalizedName(field)); - code += "Vector(builder, numElems) return builder:StartVector("; - auto vector_type = field.value.type.VectorType(); - auto alignment = InlineAlignment(vector_type); - auto elem_size = InlineSize(vector_type); - code += NumToString(elem_size); - code += ", numElems, " + NumToString(alignment); - code += ") end\n"; - } - - // Get the offset of the end of a table. - void GetEndOffsetOnTable(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".End"; - code += "(builder) "; - code += "return builder:EndObject() end\n"; - } - - // Generate the receiver for function signatures. - void GenReceiver(const StructDef &struct_def, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedMetaName(struct_def) + ":"; - } - - // Generate a struct field, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { - GenComment(field.doc_comment, code_ptr, &def_comment); - if (IsScalar(field.value.type.base_type)) { - if (struct_def.fixed) { - GetScalarFieldOfStruct(struct_def, field, code_ptr); - } - else { - GetScalarFieldOfTable(struct_def, field, code_ptr); - } + code += MakeCamel(NormalizedName(field), false); + // } + code += ", " + field.value.constant; + code += ") end\n"; + } + + // Set the value of one of the members of a table's vector. + void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".Start"; + code += MakeCamel(NormalizedName(field)); + code += "Vector(builder, numElems) return builder:StartVector("; + auto vector_type = field.value.type.VectorType(); + auto alignment = InlineAlignment(vector_type); + auto elem_size = InlineSize(vector_type); + code += NumToString(elem_size); + code += ", numElems, " + NumToString(alignment); + code += ") end\n"; + } + + // Get the offset of the end of a table. + void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".End"; + code += "(builder) "; + code += "return builder:EndObject() end\n"; + } + + // Generate the receiver for function signatures. + void GenReceiver(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedMetaName(struct_def) + ":"; + } + + // Generate a struct field, conditioned on its child type(s). + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + GenComment(field.doc_comment, code_ptr, &def_comment); + if (IsScalar(field.value.type.base_type)) { + if (struct_def.fixed) { + GetScalarFieldOfStruct(struct_def, field, code_ptr); + } else { + GetScalarFieldOfTable(struct_def, field, code_ptr); } - else { - switch (field.value.type.base_type) { + } else { + switch (field.value.type.base_type) { case BASE_TYPE_STRUCT: if (struct_def.fixed) { GetStructFieldOfStruct(struct_def, field, code_ptr); - } - else { + } else { GetStructFieldOfTable(struct_def, field, code_ptr); } break; - case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break; + case BASE_TYPE_STRING: + GetStringField(struct_def, field, code_ptr); + break; case BASE_TYPE_VECTOR: { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_STRUCT) { GetMemberOfVectorOfStruct(struct_def, field, code_ptr); - } - else { + } else { GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr); } break; } case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break; default: FLATBUFFERS_ASSERT(0); - } - } - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - GetVectorLen(struct_def, field, code_ptr); } } + if (field.value.type.base_type == BASE_TYPE_VECTOR) { + GetVectorLen(struct_def, field, code_ptr); + } + } - // Generate table constructors, conditioned on its members' types. - void GenTableBuilders(const StructDef &struct_def, - std::string *code_ptr) { - GetStartOfTable(struct_def, code_ptr); + // Generate table constructors, conditioned on its members' types. + void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) { + GetStartOfTable(struct_def, code_ptr); - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; - auto offset = it - struct_def.fields.vec.begin(); - BuildFieldOfTable(struct_def, field, offset, code_ptr); - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - BuildVectorOfTable(struct_def, field, code_ptr); - } + auto offset = it - struct_def.fields.vec.begin(); + BuildFieldOfTable(struct_def, field, offset, code_ptr); + if (field.value.type.base_type == BASE_TYPE_VECTOR) { + BuildVectorOfTable(struct_def, field, code_ptr); } - - GetEndOffsetOnTable(struct_def, code_ptr); } - // Generate struct or table methods. - void GenStruct(const StructDef &struct_def, std::string *code_ptr) { - if (struct_def.generated) return; + GetEndOffsetOnTable(struct_def, code_ptr); + } - GenComment(struct_def.doc_comment, code_ptr, &def_comment); - BeginClass(struct_def, code_ptr); + // Generate struct or table methods. + void GenStruct(const StructDef &struct_def, std::string *code_ptr) { + if (struct_def.generated) return; - GenerateNewObjectPrototype(struct_def, code_ptr); + GenComment(struct_def.doc_comment, code_ptr, &def_comment); + BeginClass(struct_def, code_ptr); - if (!struct_def.fixed) { - // Generate a special accessor for the table that has been declared as - // the root type. - NewRootTypeFromBuffer(struct_def, code_ptr); - } + GenerateNewObjectPrototype(struct_def, code_ptr); - // Generate the Init method that sets the field in a pre-existing - // accessor object. This is to allow object reuse. - InitializeExisting(struct_def, code_ptr); - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; + if (!struct_def.fixed) { + // Generate a special accessor for the table that has been declared as + // the root type. + NewRootTypeFromBuffer(struct_def, code_ptr); + } - GenStructAccessor(struct_def, field, code_ptr); - } + // Generate the Init method that sets the field in a pre-existing + // accessor object. This is to allow object reuse. + InitializeExisting(struct_def, code_ptr); + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; - if (struct_def.fixed) { - // create a struct constructor function - GenStructBuilder(struct_def, code_ptr); - } - else { - // Create a set of functions that allow table construction. - GenTableBuilders(struct_def, code_ptr); - } + GenStructAccessor(struct_def, field, code_ptr); } - // Generate enum declarations. - void GenEnum(const EnumDef &enum_def, std::string *code_ptr) { - if (enum_def.generated) return; - - GenComment(enum_def.doc_comment, code_ptr, &def_comment); - BeginEnum(NormalizedName(enum_def), code_ptr); - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); - ++it) { - auto &ev = **it; - GenComment(ev.doc_comment, code_ptr, &def_comment, Indent); - EnumMember(enum_def, ev, code_ptr); - } - EndEnum(code_ptr); + if (struct_def.fixed) { + // create a struct constructor function + GenStructBuilder(struct_def, code_ptr); + } else { + // Create a set of functions that allow table construction. + GenTableBuilders(struct_def, code_ptr); } + } + + // Generate enum declarations. + void GenEnum(const EnumDef &enum_def, std::string *code_ptr) { + if (enum_def.generated) return; - // Returns the function name that is able to read a value of the given type. - std::string GenGetter(const Type &type) { - switch (type.base_type) { + GenComment(enum_def.doc_comment, code_ptr, &def_comment); + BeginEnum(NormalizedName(enum_def), code_ptr); + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { + auto &ev = **it; + GenComment(ev.doc_comment, code_ptr, &def_comment, Indent); + EnumMember(enum_def, ev, code_ptr); + } + EndEnum(code_ptr); + } + + // Returns the function name that is able to read a value of the given type. + std::string GenGetter(const Type &type) { + switch (type.base_type) { case BASE_TYPE_STRING: return std::string(SelfData) + ":String("; - case BASE_TYPE_UNION: return std::string(SelfData) + ":Union("; + case BASE_TYPE_UNION: return std::string(SelfData) + ":Union("; case BASE_TYPE_VECTOR: return GenGetter(type.VectorType()); default: return std::string(SelfData) + ":Get(flatbuffers.N." + - MakeCamel(GenTypeGet(type)) + ", "; - } + MakeCamel(GenTypeGet(type)) + ", "; } + } - // Returns the method name for use with add/put calls. - std::string GenMethod(const FieldDef &field) { - return IsScalar(field.value.type.base_type) - ? MakeCamel(GenTypeBasic(field.value.type)) - : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative"); - } + // Returns the method name for use with add/put calls. + std::string GenMethod(const FieldDef &field) { + return IsScalar(field.value.type.base_type) + ? MakeCamel(GenTypeBasic(field.value.type)) + : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative"); + } - std::string GenTypeBasic(const Type &type) { - static const char *ctypename[] = { - // clang-format off + std::string GenTypeBasic(const Type &type) { + static const char *ctypename[] = { + // clang-format off #define FLATBUFFERS_TD(ENUM, IDLTYPE, \ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \ #PTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD - // clang-format on - }; - return ctypename[type.base_type]; - } + // clang-format on + }; + return ctypename[type.base_type]; + } - std::string GenTypePointer(const Type &type) { - switch (type.base_type) { + std::string GenTypePointer(const Type &type) { + switch (type.base_type) { case BASE_TYPE_STRING: return "string"; case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType()); case BASE_TYPE_STRUCT: return type.struct_def->name; case BASE_TYPE_UNION: // fall through default: return "*flatbuffers.Table"; - } - } - - std::string GenTypeGet(const Type &type) { - return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type); - } - - std::string GetNamespace(const Type &type) { - return type.struct_def->defined_namespace->GetFullyQualifiedName(type.struct_def->name); - } - - std::string TypeName(const FieldDef &field) { - return GenTypeGet(field.value.type); - } - - std::string TypeNameWithNamespace(const FieldDef &field) { - return GetNamespace(field.value.type); - } - - // Create a struct with a builder and the struct's arguments. - void GenStructBuilder(const StructDef &struct_def, - std::string *code_ptr) { - BeginBuilderArgs(struct_def, code_ptr); - StructBuilderArgs(struct_def, "", code_ptr); - EndBuilderArgs(code_ptr); - - StructBuilderBody(struct_def, "", code_ptr); - EndBuilderBody(code_ptr); } - - bool generate() { - if (!generateEnums()) return false; - if (!generateStructs()) return false; - return true; - } - - private: - bool generateEnums() { - for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end(); - ++it) { - auto &enum_def = **it; - std::string enumcode; - GenEnum(enum_def, &enumcode); - if (!SaveType(enum_def, enumcode, false)) return false; - } - return true; - } - - bool generateStructs() { - for (auto it = parser_.structs_.vec.begin(); - it != parser_.structs_.vec.end(); ++it) { - auto &struct_def = **it; - std::string declcode; - GenStruct(struct_def, &declcode); - if (!SaveType(struct_def, declcode, true)) return false; - } - return true; - } - - // Begin by declaring namespace and imports. - void BeginFile(const std::string &name_space_name, const bool needs_imports, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Comment) + FlatBuffersGeneratedWarning() + "\n\n"; - code += std::string(Comment) + "namespace: " + name_space_name + "\n\n"; - if (needs_imports) { - code += "local flatbuffers = require('flatbuffers')\n\n"; - } - } - - // Save out the generated code for a Lua Table type. - bool SaveType(const Definition &def, const std::string &classcode, - bool needs_imports) { - if (!classcode.length()) return true; - - std::string namespace_dir = path_; - auto &namespaces = def.defined_namespace->components; - for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { - if (it != namespaces.begin()) namespace_dir += kPathSeparator; - namespace_dir += *it; - //std::string init_py_filename = namespace_dir + "/__init__.py"; - //SaveFile(init_py_filename.c_str(), "", false); - } - - std::string code = ""; - BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code); - code += classcode; - code += "\n"; - code += "return " + NormalizedName(def) + " " + Comment + "return the module"; - std::string filename = + } + + std::string GenTypeGet(const Type &type) { + return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type); + } + + std::string GetNamespace(const Type &type) { + return type.struct_def->defined_namespace->GetFullyQualifiedName( + type.struct_def->name); + } + + std::string TypeName(const FieldDef &field) { + return GenTypeGet(field.value.type); + } + + std::string TypeNameWithNamespace(const FieldDef &field) { + return GetNamespace(field.value.type); + } + + // Create a struct with a builder and the struct's arguments. + void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) { + BeginBuilderArgs(struct_def, code_ptr); + StructBuilderArgs(struct_def, "", code_ptr); + EndBuilderArgs(code_ptr); + + StructBuilderBody(struct_def, "", code_ptr); + EndBuilderBody(code_ptr); + } + + bool generate() { + if (!generateEnums()) return false; + if (!generateStructs()) return false; + return true; + } + + private: + bool generateEnums() { + for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end(); + ++it) { + auto &enum_def = **it; + std::string enumcode; + GenEnum(enum_def, &enumcode); + if (!SaveType(enum_def, enumcode, false)) return false; + } + return true; + } + + bool generateStructs() { + for (auto it = parser_.structs_.vec.begin(); + it != parser_.structs_.vec.end(); ++it) { + auto &struct_def = **it; + std::string declcode; + GenStruct(struct_def, &declcode); + if (!SaveType(struct_def, declcode, true)) return false; + } + return true; + } + + // Begin by declaring namespace and imports. + void BeginFile(const std::string &name_space_name, const bool needs_imports, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Comment) + FlatBuffersGeneratedWarning() + "\n\n"; + code += std::string(Comment) + "namespace: " + name_space_name + "\n\n"; + if (needs_imports) { + code += "local flatbuffers = require('flatbuffers')\n\n"; + } + } + + // Save out the generated code for a Lua Table type. + bool SaveType(const Definition &def, const std::string &classcode, + bool needs_imports) { + if (!classcode.length()) return true; + + std::string namespace_dir = path_; + auto &namespaces = def.defined_namespace->components; + for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { + if (it != namespaces.begin()) namespace_dir += kPathSeparator; + namespace_dir += *it; + // std::string init_py_filename = namespace_dir + "/__init__.py"; + // SaveFile(init_py_filename.c_str(), "", false); + } + + std::string code = ""; + BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code); + code += classcode; + code += "\n"; + code += + "return " + NormalizedName(def) + " " + Comment + "return the module"; + std::string filename = NamespaceDir(*def.defined_namespace) + NormalizedName(def) + ".lua"; - return SaveFile(filename.c_str(), code, false); - } - private: - std::unordered_set<std::string> keywords_; - }; + return SaveFile(filename.c_str(), code, false); + } + + private: + std::unordered_set<std::string> keywords_; +}; } // namespace lua bool GenerateLua(const Parser &parser, const std::string &path, - const std::string &file_name) { + const std::string &file_name) { lua::LuaGenerator generator(parser, path, file_name); return generator.generate(); } diff --git a/src/idl_gen_php.cpp b/src/idl_gen_php.cpp index 9d814159..16e47816 100644 --- a/src/idl_gen_php.cpp +++ b/src/idl_gen_php.cpp @@ -826,7 +826,8 @@ class PhpGenerator : public BaseGenerator { code += Indent + "private static $names = array(\n"; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { auto &ev = **it; - code += Indent + Indent + enum_def.name + "::" + ev.name + "=>" + "\"" + ev.name + "\",\n"; + code += Indent + Indent + enum_def.name + "::" + ev.name + "=>" + "\"" + + ev.name + "\",\n"; } code += Indent + ");\n\n"; diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp index c8db3597..bff0d849 100644 --- a/src/idl_gen_python.cpp +++ b/src/idl_gen_python.cpp @@ -17,14 +17,13 @@ // independent from idl_parser, since this code is not needed for most clients #include <string> +#include <unordered_set> #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include <unordered_set> - namespace flatbuffers { namespace python { @@ -39,40 +38,12 @@ class PythonGenerator : public BaseGenerator { : BaseGenerator(parser, path, file_name, "" /* not used */, "" /* not used */), float_const_gen_("float('nan')", "float('inf')", "float('-inf')") { - static const char * const keywords[] = { - "False", - "None", - "True", - "and", - "as", - "assert", - "break", - "class", - "continue", - "def", - "del", - "elif", - "else", - "except", - "finally", - "for", - "from", - "global", - "if", - "import", - "in", - "is", - "lambda", - "nonlocal", - "not", - "or", - "pass", - "raise", - "return", - "try", - "while", - "with", - "yield" + static const char *const keywords[] = { + "False", "None", "True", "and", "as", "assert", "break", + "class", "continue", "def", "del", "elif", "else", "except", + "finally", "for", "from", "global", "if", "import", "in", + "is", "lambda", "nonlocal", "not", "or", "pass", "raise", + "return", "try", "while", "with", "yield" }; keywords_.insert(std::begin(keywords), std::end(keywords)); } @@ -81,9 +52,9 @@ class PythonGenerator : public BaseGenerator { // this is the prefix code for that. std::string OffsetPrefix(const FieldDef &field) { return "\n" + Indent + Indent + - "o = flatbuffers.number_types.UOffsetTFlags.py_type" + - "(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" + - Indent + Indent + "if o != 0:\n"; + "o = flatbuffers.number_types.UOffsetTFlags.py_type" + + "(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" + + Indent + Indent + "if o != 0:\n"; } // Begin a class declaration. @@ -148,8 +119,7 @@ class PythonGenerator : public BaseGenerator { } // Initialize an existing object with other data, to avoid an allocation. - void InitializeExisting(const StructDef &struct_def, - std::string *code_ptr) { + void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -172,8 +142,7 @@ class PythonGenerator : public BaseGenerator { // Get the value of a struct's scalar. void GetScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); GenReceiver(struct_def, code_ptr); @@ -184,8 +153,7 @@ class PythonGenerator : public BaseGenerator { } // Get the value of a table's scalar. - void GetScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); @@ -195,9 +163,7 @@ class PythonGenerator : public BaseGenerator { code += OffsetPrefix(field); getter += "o + self._tab.Pos)"; auto is_bool = IsBool(field.value.type.base_type); - if (is_bool) { - getter = "bool(" + getter + ")"; - } + if (is_bool) { getter = "bool(" + getter + ")"; } code += Indent + Indent + Indent + "return " + getter + "\n"; std::string default_value; if (is_bool) { @@ -213,8 +179,7 @@ class PythonGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Struct. void GetStructFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); code += MakeCamel(NormalizedName(field)); @@ -250,8 +215,7 @@ class PythonGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Table. - void GetStructFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -296,7 +260,8 @@ class PythonGenerator : public BaseGenerator { // TODO(rw): this works and is not the good way to it: bool is_native_table = TypeName(field) == "*flatbuffers.Table"; if (is_native_table) { - code += Indent + Indent + Indent + "from flatbuffers.table import Table\n"; + code += + Indent + Indent + Indent + "from flatbuffers.table import Table\n"; } else { code += Indent + Indent + Indent; code += "from ." + TypeName(field) + " import " + TypeName(field) + "\n"; @@ -309,8 +274,7 @@ class PythonGenerator : public BaseGenerator { // Get the value of a vector's struct member. void GetMemberOfVectorOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; auto vectortype = field.value.type.VectorType(); @@ -388,8 +352,7 @@ class PythonGenerator : public BaseGenerator { } // Begin the creator function signature. - void BeginBuilderArgs(const StructDef &struct_def, - std::string *code_ptr) { + void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "\n"; @@ -399,10 +362,10 @@ class PythonGenerator : public BaseGenerator { // Recursively generate arguments for a constructor, to deal with nested // structs. - void StructBuilderArgs(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; const auto &field_type = field.value.type; const auto &type = @@ -439,7 +402,7 @@ class PythonGenerator : public BaseGenerator { indent + " builder.Prep(" + NumToString(struct_def.minalign) + ", "; code += NumToString(struct_def.bytesize) + ")\n"; for (auto it = struct_def.fields.vec.rbegin(); - it != struct_def.fields.vec.rend(); ++it) { + it != struct_def.fields.vec.rend(); ++it) { auto &field = **it; const auto &field_type = field.value.type; const auto &type = @@ -484,8 +447,7 @@ class PythonGenerator : public BaseGenerator { } // Get the value of a table's starting offset. - void GetStartOfTable(const StructDef &struct_def, - std::string *code_ptr) { + void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "def " + NormalizedName(struct_def) + "Start"; code += "(builder): "; @@ -495,11 +457,11 @@ class PythonGenerator : public BaseGenerator { } // Set the value of a table's field. - void BuildFieldOfTable(const StructDef &struct_def, - const FieldDef &field, const size_t offset, - std::string *code_ptr) { + void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field, + const size_t offset, std::string *code_ptr) { std::string &code = *code_ptr; - code += "def " + NormalizedName(struct_def) + "Add" + MakeCamel(NormalizedName(field)); + code += "def " + NormalizedName(struct_def) + "Add" + + MakeCamel(NormalizedName(field)); code += "(builder, "; code += MakeCamel(NormalizedName(field), false); code += "): "; @@ -521,8 +483,8 @@ class PythonGenerator : public BaseGenerator { } // Set the value of one of the members of a table's vector. - void BuildVectorOfTable(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { std::string &code = *code_ptr; code += "def " + NormalizedName(struct_def) + "Start"; code += MakeCamel(NormalizedName(field)); @@ -536,8 +498,7 @@ class PythonGenerator : public BaseGenerator { } // Get the offset of the end of a table. - void GetEndOffsetOnTable(const StructDef &struct_def, - std::string *code_ptr) { + void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "def " + NormalizedName(struct_def) + "End"; code += "(builder): "; @@ -552,8 +513,8 @@ class PythonGenerator : public BaseGenerator { } // Generate a struct field, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { GenComment(field.doc_comment, code_ptr, &def_comment, Indent.c_str()); if (IsScalar(field.value.type.base_type)) { if (struct_def.fixed) { @@ -572,7 +533,9 @@ class PythonGenerator : public BaseGenerator { GetStructFieldOfTable(struct_def, field, code_ptr); } break; - case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break; + case BASE_TYPE_STRING: + GetStringField(struct_def, field, code_ptr); + break; case BASE_TYPE_VECTOR: { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_STRUCT) { @@ -593,12 +556,11 @@ class PythonGenerator : public BaseGenerator { } // Generate table constructors, conditioned on its members' types. - void GenTableBuilders(const StructDef &struct_def, - std::string *code_ptr) { + void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) { GetStartOfTable(struct_def, code_ptr); for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; if (field.deprecated) continue; @@ -635,7 +597,7 @@ class PythonGenerator : public BaseGenerator { code += "\", size_prefixed=size_prefixed)\n"; code += "\n"; } - + // Generate struct or table methods. void GenStruct(const StructDef &struct_def, std::string *code_ptr) { if (struct_def.generated) return; @@ -646,7 +608,7 @@ class PythonGenerator : public BaseGenerator { // Generate a special accessor for the table that has been declared as // the root type. NewRootTypeFromBuffer(struct_def, code_ptr); - if (parser_.file_identifier_.length()){ + if (parser_.file_identifier_.length()) { // Generate a special function to test file_identifier GenHasFileIdentifier(struct_def, code_ptr); } @@ -655,7 +617,7 @@ class PythonGenerator : public BaseGenerator { // accessor object. This is to allow object reuse. InitializeExisting(struct_def, code_ptr); for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; if (field.deprecated) continue; @@ -693,7 +655,7 @@ class PythonGenerator : public BaseGenerator { case BASE_TYPE_VECTOR: return GenGetter(type.VectorType()); default: return "self._tab.Get(flatbuffers.number_types." + - MakeCamel(GenTypeGet(type)) + "Flags, "; + MakeCamel(GenTypeGet(type)) + "Flags, "; } } @@ -738,8 +700,7 @@ class PythonGenerator : public BaseGenerator { } // Create a struct with a builder and the struct's arguments. - void GenStructBuilder(const StructDef &struct_def, - std::string *code_ptr) { + void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) { BeginBuilderArgs(struct_def, code_ptr); StructBuilderArgs(struct_def, "", code_ptr); EndBuilderArgs(code_ptr); @@ -807,6 +768,7 @@ class PythonGenerator : public BaseGenerator { NamespaceDir(*def.defined_namespace) + NormalizedName(def) + ".py"; return SaveFile(filename.c_str(), code, false); } + private: std::unordered_set<std::string> keywords_; const SimpleFloatConstantGenerator float_const_gen_; diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index 936ac836..3c23f2f9 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -40,9 +40,7 @@ std::string MakeSnakeCase(const std::string &in) { } else if (!islower(in[i])) { // Prevent duplicate underscores for Upper_Snake_Case strings // and UPPERCASE strings. - if (islower(in[i - 1])) { - s += '_'; - } + if (islower(in[i - 1])) { s += '_'; } s += static_cast<char>(tolower(in[i])); } else { s += in[i]; @@ -200,77 +198,19 @@ class RustGenerator : public BaseGenerator { // changes to that webpage in the future. // currently-used keywords - "as", - "break", - "const", - "continue", - "crate", - "else", - "enum", - "extern", - "false", - "fn", - "for", - "if", - "impl", - "in", - "let", - "loop", - "match", - "mod", - "move", - "mut", - "pub", - "ref", - "return", - "Self", - "self", - "static", - "struct", - "super", - "trait", - "true", - "type", - "unsafe", - "use", - "where", - "while", + "as", "break", "const", "continue", "crate", "else", "enum", "extern", + "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", + "move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct", + "super", "trait", "true", "type", "unsafe", "use", "where", "while", // future possible keywords - "abstract", - "alignof", - "become", - "box", - "do", - "final", - "macro", - "offsetof", - "override", - "priv", - "proc", - "pure", - "sizeof", - "typeof", - "unsized", - "virtual", - "yield", + "abstract", "alignof", "become", "box", "do", "final", "macro", + "offsetof", "override", "priv", "proc", "pure", "sizeof", "typeof", + "unsized", "virtual", "yield", // other rust terms we should not use - "std", - "usize", - "isize", - "u8", - "i8", - "u16", - "i16", - "u32", - "i32", - "u64", - "i64", - "u128", - "i128", - "f32", - "f64", + "std", "usize", "isize", "u8", "i8", "u16", "i16", "u32", "i32", "u64", + "i64", "u128", "i128", "f32", "f64", // These are terms the code generator can implement on types. // @@ -281,13 +221,9 @@ class RustGenerator : public BaseGenerator { // implementation detail, and how we implement methods could change in // the future. as a result, we proactively block these out as reserved // words. - "follow", - "push", - "size", - "alignment", - "to_little_endian", - "from_little_endian", - nullptr }; + "follow", "push", "size", "alignment", "to_little_endian", + "from_little_endian", nullptr + }; for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw); } @@ -310,8 +246,7 @@ class RustGenerator : public BaseGenerator { // TODO(rw): Use a set data structure to reduce namespace evaluations from // O(n**2) to O(n). for (auto ns_it = parser_.namespaces_.begin(); - ns_it != parser_.namespaces_.end(); - ++ns_it) { + ns_it != parser_.namespaces_.end(); ++ns_it) { const auto &ns = *ns_it; // Generate code for all the enum declarations. @@ -381,8 +316,12 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftEnumKey: case ftUnionKey: - case ftUnionValue: { return false; } - default: { return true; } + case ftUnionValue: { + return false; + } + default: { + return true; + } } } @@ -393,13 +332,9 @@ class RustGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) { - continue; - } + if (field.deprecated) { continue; } - if (TableBuilderTypeNeedsLifetime(field.value.type)) { - return true; - } + if (TableBuilderTypeNeedsLifetime(field.value.type)) { return true; } } return false; @@ -410,14 +345,18 @@ class RustGenerator : public BaseGenerator { bool StructMemberAccessNeedsCopy(const Type &type) const { switch (GetFullType(type)) { case ftInteger: // requires endian swap - case ftFloat: // requires endian swap - case ftBool: // no endian-swap, but do the copy for UX consistency - case ftEnumKey: { return true; } // requires endian swap - case ftStruct: { return false; } // no endian swap + case ftFloat: // requires endian swap + case ftBool: // no endian-swap, but do the copy for UX consistency + case ftEnumKey: { + return true; + } // requires endian swap + case ftStruct: { + return false; + } // no endian swap default: { // logic error: no other types can be struct members. FLATBUFFERS_ASSERT(false && "invalid struct member type"); - return false; // only to satisfy compiler's return analysis + return false; // only to satisfy compiler's return analysis } } } @@ -477,7 +416,7 @@ class RustGenerator : public BaseGenerator { auto s = src->components.begin(); auto d = dst->components.begin(); - for(;;) { + for (;;) { if (s == src->components.end()) { break; } if (d == dst->components.end()) { break; } if (*s != *d) { break; } @@ -486,9 +425,7 @@ class RustGenerator : public BaseGenerator { ++i; } - for (; s != src->components.end(); ++s) { - stream << "super::"; - } + for (; s != src->components.end(); ++s) { stream << "super::"; } for (; d != dst->components.end(); ++d) { stream << MakeSnakeCase(*d) + "::"; } @@ -509,8 +446,12 @@ class RustGenerator : public BaseGenerator { case ftFloat: case ftBool: case ftEnumKey: - case ftUnionKey: { break; } - default: { FLATBUFFERS_ASSERT(false && "incorrect type given");} + case ftUnionKey: { + break; + } + default: { + FLATBUFFERS_ASSERT(false && "incorrect type given"); + } } // clang-format off @@ -560,13 +501,17 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftEnumKey: case ftUnionKey: { - return GetTypeBasic(type); } + return GetTypeBasic(type); + } case ftTable: { return WrapInNameSpace(type.struct_def->defined_namespace, - type.struct_def->name) + "<'a>"; } + type.struct_def->name) + + "<'a>"; + } default: { return WrapInNameSpace(type.struct_def->defined_namespace, - type.struct_def->name); } + type.struct_def->name); + } } } @@ -586,7 +531,8 @@ class RustGenerator : public BaseGenerator { GenComment(enum_def.doc_comment); code_ += "#[allow(non_camel_case_types)]"; code_ += "#[repr({{BASE_TYPE}})]"; - code_ += "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]"; + code_ += + "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]"; code_ += "pub enum " + Name(enum_def) + " {"; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { @@ -644,8 +590,9 @@ class RustGenerator : public BaseGenerator { code_ += " type Output = {{ENUM_NAME}};"; code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; - code_ += " flatbuffers::emplace_scalar::<{{ENUM_NAME}}>" - "(dst, *self);"; + code_ += + " flatbuffers::emplace_scalar::<{{ENUM_NAME}}>" + "(dst, *self);"; code_ += " }"; code_ += "}"; code_ += ""; @@ -654,7 +601,7 @@ class RustGenerator : public BaseGenerator { auto num_fields = NumToString(enum_def.size()); code_ += "#[allow(non_camel_case_types)]"; code_ += "const ENUM_VALUES_{{ENUM_NAME_CAPS}}:[{{ENUM_NAME}}; " + - num_fields + "] = ["; + num_fields + "] = ["; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { const auto &ev = **it; auto value = GetEnumValUse(enum_def, ev); @@ -727,8 +674,12 @@ class RustGenerator : public BaseGenerator { std::string GetDefaultScalarValue(const FieldDef &field) { switch (GetFullType(field.value.type)) { - case ftInteger: { return GetDefaultConstant(field); } - case ftFloat: { return GetDefaultConstant(field); } + case ftInteger: { + return GetDefaultConstant(field); + } + case ftFloat: { + return GetDefaultConstant(field); + } case ftBool: { return field.value.constant == "0" ? "false" : "true"; } @@ -742,7 +693,9 @@ class RustGenerator : public BaseGenerator { // All pointer-ish types have a default value of None, because they are // wrapped in Option. - default: { return "None"; } + default: { + return "None"; + } } } @@ -759,7 +712,7 @@ class RustGenerator : public BaseGenerator { // 3) return a hardcoded value because the vtable field value is set to zero. std::string TableBuilderArgsDefnType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(type)) { case ftInteger: @@ -774,7 +727,7 @@ class RustGenerator : public BaseGenerator { } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime + \ + return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime + ">>>"; } case ftString: { @@ -792,43 +745,43 @@ class RustGenerator : public BaseGenerator { case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", " + typname + ">>>"; } case ftVectorOfBool: { - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", bool>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", bool>>>"; } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", " + typname + ">>>"; } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", " + typname + ">>>"; } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", flatbuffers::ForwardsUOffset<" + typname + \ - "<" + lifetime + ">>>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime + + ">>>>>"; } case ftVectorOfString: { - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", flatbuffers::ForwardsUOffset<&" + lifetime + \ - " str>>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>>"; } case ftVectorOfUnionValue: { - const auto typname = WrapInNameSpace(*type.enum_def) + \ - "UnionTableOffset"; - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", flatbuffers::ForwardsUOffset<" - "flatbuffers::Table<" + lifetime + ">>>>"; + const auto typname = + WrapInNameSpace(*type.enum_def) + "UnionTableOffset"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + "flatbuffers::Table<" + + lifetime + ">>>>"; } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string TableBuilderArgsDefaultValue(const FieldDef &field) { @@ -839,53 +792,56 @@ class RustGenerator : public BaseGenerator { switch (GetFullType(field.value.type)) { case ftUnionKey: case ftEnumKey: { - const std::string basetype = GetTypeBasic(field.value.type); //<- never used + const std::string basetype = + GetTypeBasic(field.value.type); //<- never used return GetDefaultScalarValue(field); } - default: { return GetDefaultScalarValue(field); } + default: { + return GetDefaultScalarValue(field); + } } } std::string TableBuilderArgsAddFuncType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", " + typname + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", flatbuffers::ForwardsUOffset<" + typname + \ - "<" + lifetime + ">>>>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime + + ">>>>"; } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", " + typname + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfBool: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", bool>>"; } case ftVectorOfString: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>"; } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", " + typname + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfUnionValue: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + \ - lifetime + ">>>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + lifetime + + ">>>"; } case ftEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); @@ -919,11 +875,11 @@ class RustGenerator : public BaseGenerator { } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string TableBuilderArgsAddFuncBody(const FieldDef &field) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -947,8 +903,8 @@ class RustGenerator : public BaseGenerator { } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" + \ - typname + ">>"; + return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" + + typname + ">>"; } case ftUnionValue: @@ -964,12 +920,12 @@ class RustGenerator : public BaseGenerator { return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>"; } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string GenTableAccessorFuncReturnType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -982,11 +938,13 @@ class RustGenerator : public BaseGenerator { } case ftStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("&" + lifetime + " " + typname, field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " " + typname, + field.required); } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">", field.required); + return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">", + field.required); } case ftEnumKey: case ftUnionKey: { @@ -995,55 +953,68 @@ class RustGenerator : public BaseGenerator { } case ftUnionValue: { - return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">", field.required); + return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">", + field.required); } case ftString: { - return WrapInOptionIfNotRequired("&" + lifetime + " str", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " str", + field.required); } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); if (IsOneByte(type.VectorType().base_type)) { - return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required); + return WrapInOptionIfNotRequired( + "&" + lifetime + " [" + typname + "]", field.required); } - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + ", " + typname + ">", + field.required); } case ftVectorOfBool: { - return WrapInOptionIfNotRequired("&" + lifetime + " [bool]", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " [bool]", + field.required); } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + ", " + typname + ">", + field.required); } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", + field.required); } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<" + \ - typname + "<" + lifetime + ">>>", field.required); + return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + + typname + "<" + lifetime + ">>>", + field.required); } case ftVectorOfString: { - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<&" + \ - lifetime + " str>>", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>", + field.required); } case ftVectorOfUnionValue: { FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported"); // TODO(rw): when we do support these, we should consider using the // Into trait to convert tables to typesafe union values. - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string GenTableAccessorFuncBody(const FieldDef &field, const std::string &lifetime, const std::string &offset_prefix) { - const std::string offset_name = offset_prefix + "::" + \ - GetFieldOffsetName(field); - const Type& type = field.value.type; + const std::string offset_name = + offset_prefix + "::" + GetFieldOffsetName(field); + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -1051,42 +1022,51 @@ class RustGenerator : public BaseGenerator { case ftBool: { const auto typname = GetTypeBasic(type); const auto default_value = GetDefaultScalarValue(field); - return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + \ + return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + default_value + ")).unwrap()"; } case ftStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<" + typname + ">(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<" + typname + ">(" + offset_name + ", None)", + field.required); } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" + \ - typname + "<" + lifetime + ">>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + typname + "<" + + lifetime + ">>>(" + offset_name + ", None)", + field.required); } case ftUnionValue: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Table<" + lifetime + ">>>(" + offset_name + \ - ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Table<" + + lifetime + ">>>(" + offset_name + ", None)", + field.required); } case ftUnionKey: case ftEnumKey: { - const auto underlying_typname = GetTypeBasic(type); //<- never used + const auto underlying_typname = GetTypeBasic(type); //<- never used const auto typname = WrapInNameSpace(*type.enum_def); const auto default_value = GetDefaultScalarValue(field); - return "self._tab.get::<" + typname + ">(" + offset_name + \ - ", Some(" + default_value + ")).unwrap()"; + return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + + default_value + ")).unwrap()"; } case ftString: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" + \ - offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" + + offset_name + ", None)", + field.required); } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - std::string s = "self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", " + typname + \ - ">>>(" + offset_name + ", None)"; + std::string s = + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", " + typname + ">>>(" + offset_name + ", None)"; // single-byte values are safe to slice if (IsOneByte(type.VectorType().base_type)) { s += ".map(|v| v.safe_slice())"; @@ -1094,49 +1074,60 @@ class RustGenerator : public BaseGenerator { return AddUnwrapIfRequired(s, field.required); } case ftVectorOfBool: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", bool>>>(" + \ - offset_name + ", None).map(|v| v.safe_slice())", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", bool>>>(" + offset_name + + ", None).map(|v| v.safe_slice())", + field.required); } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", " + typname + ">>>(" + \ - offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", " + typname + ">>>(" + offset_name + ", None)", + field.required); } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + typname + ">>>(" + \ - offset_name + ", None).map(|v| v.safe_slice() )", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + typname + ">>>(" + offset_name + + ", None).map(|v| v.safe_slice() )", + field.required); } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" + typname + \ - "<" + lifetime + ">>>>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" + + typname + "<" + lifetime + ">>>>>(" + offset_name + ", None)", + field.required); } case ftVectorOfString: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" + \ - lifetime + " str>>>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" + + lifetime + " str>>>>(" + offset_name + ", None)", + field.required); } case ftVectorOfUnionValue: { FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported"); - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } - bool TableFieldReturnsOption(const Type& type) { + bool TableFieldReturnsOption(const Type &type) { switch (GetFullType(type)) { case ftInteger: case ftFloat: case ftBool: case ftEnumKey: - case ftUnionKey: - return false; + case ftUnionKey: return false; default: return true; } } @@ -1172,8 +1163,9 @@ class RustGenerator : public BaseGenerator { code_ += ""; code_ += "impl<'a> {{STRUCT_NAME}}<'a> {"; code_ += " #[inline]"; - code_ += " pub fn init_from_table(table: flatbuffers::Table<'a>) -> " - "Self {"; + code_ += + " pub fn init_from_table(table: flatbuffers::Table<'a>) -> " + "Self {"; code_ += " {{STRUCT_NAME}} {"; code_ += " _tab: table,"; code_ += " }"; @@ -1181,16 +1173,17 @@ class RustGenerator : public BaseGenerator { // Generate a convenient create* function that uses the above builder // to create a table in one function call. - code_.SetValue("MAYBE_US", - struct_def.fields.vec.size() == 0 ? "_" : ""); + code_.SetValue("MAYBE_US", struct_def.fields.vec.size() == 0 ? "_" : ""); code_.SetValue("MAYBE_LT", - TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : ""); + TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : ""); code_ += " #[allow(unused_mut)]"; code_ += " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>("; - code_ += " _fbb: " - "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,"; - code_ += " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})" - " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {"; + code_ += + " _fbb: " + "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,"; + code_ += + " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})" + " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {"; code_ += " let mut builder = {{STRUCT_NAME}}Builder::new(_fbb);"; for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; @@ -1203,8 +1196,9 @@ class RustGenerator : public BaseGenerator { size == SizeOf(field.value.type.base_type))) { code_.SetValue("FIELD_NAME", Name(field)); if (TableFieldReturnsOption(field.value.type)) { - code_ += " if let Some(x) = args.{{FIELD_NAME}} " - "{ builder.add_{{FIELD_NAME}}(x); }"; + code_ += + " if let Some(x) = args.{{FIELD_NAME}} " + "{ builder.add_{{FIELD_NAME}}(x); }"; } else { code_ += " builder.add_{{FIELD_NAME}}(args.{{FIELD_NAME}});"; } @@ -1227,8 +1221,9 @@ class RustGenerator : public BaseGenerator { code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field)); code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset)); - code_ += " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = " - "{{OFFSET_VALUE}};"; + code_ += + " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = " + "{{OFFSET_VALUE}};"; } code_ += ""; } @@ -1266,9 +1261,7 @@ class RustGenerator : public BaseGenerator { code_ += " }"; // Generate a comparison function for this field if it is a key. - if (field.key) { - GenKeyFieldMethods(field); - } + if (field.key) { GenKeyFieldMethods(field); } // Generate a nested flatbuffer field, if applicable. auto nested = field.attributes.Lookup("nested_flatbuffer"); @@ -1285,14 +1278,16 @@ class RustGenerator : public BaseGenerator { code_.SetValue("OFFSET_NAME", offset_prefix + "::" + GetFieldOffsetName(field)); - code_ += " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> " - " Option<{{STRUCT_NAME}}<'a>> {"; + code_ += + " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> " + " Option<{{STRUCT_NAME}}<'a>> {"; code_ += " match self.{{FIELD_NAME}}() {"; code_ += " None => { None }"; code_ += " Some(data) => {"; code_ += " use self::flatbuffers::Follow;"; - code_ += " Some(<flatbuffers::ForwardsUOffset" - "<{{STRUCT_NAME}}<'a>>>::follow(data, 0))"; + code_ += + " Some(<flatbuffers::ForwardsUOffset" + "<{{STRUCT_NAME}}<'a>>>::follow(data, 0))"; code_ += " },"; code_ += " }"; code_ += " }"; @@ -1315,22 +1310,26 @@ class RustGenerator : public BaseGenerator { auto &ev = **u_it; if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; } - auto table_init_type = WrapInNameSpace( - ev.union_type.struct_def->defined_namespace, - ev.union_type.struct_def->name); + auto table_init_type = + WrapInNameSpace(ev.union_type.struct_def->defined_namespace, + ev.union_type.struct_def->name); - code_.SetValue("U_ELEMENT_ENUM_TYPE", - WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev))); + code_.SetValue( + "U_ELEMENT_ENUM_TYPE", + WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev))); code_.SetValue("U_ELEMENT_TABLE_TYPE", table_init_type); code_.SetValue("U_ELEMENT_NAME", MakeSnakeCase(Name(ev))); code_ += " #[inline]"; code_ += " #[allow(non_snake_case)]"; - code_ += " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> " - "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {"; - code_ += " if self.{{FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {"; - code_ += " self.{{FIELD_NAME}}().map(|u| " - "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))"; + code_ += + " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> " + "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {"; + code_ += + " if self.{{FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {"; + code_ += + " self.{{FIELD_NAME}}().map(|u| " + "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))"; code_ += " } else {"; code_ += " None"; code_ += " }"; @@ -1344,7 +1343,7 @@ class RustGenerator : public BaseGenerator { // Generate an args struct: code_.SetValue("MAYBE_LT", - TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : ""); + TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : ""); code_ += "pub struct {{STRUCT_NAME}}Args{{MAYBE_LT}} {"; for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { @@ -1363,7 +1362,7 @@ class RustGenerator : public BaseGenerator { code_ += " fn default() -> Self {"; code_ += " {{STRUCT_NAME}}Args {"; for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; if (!field.deprecated) { code_.SetValue("PARAM_VALUE", TableBuilderArgsDefaultValue(field)); @@ -1379,8 +1378,9 @@ class RustGenerator : public BaseGenerator { // Generate a builder struct: code_ += "pub struct {{STRUCT_NAME}}Builder<'a: 'b, 'b> {"; code_ += " fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,"; - code_ += " start_: flatbuffers::WIPOffset<" - "flatbuffers::TableUnfinishedWIPOffset>,"; + code_ += + " start_: flatbuffers::WIPOffset<" + "flatbuffers::TableUnfinishedWIPOffset>,"; code_ += "}"; // Generate builder functions: @@ -1409,13 +1409,15 @@ class RustGenerator : public BaseGenerator { code_.SetValue("FIELD_TYPE", TableBuilderArgsAddFuncType(field, "'b ")); code_.SetValue("FUNC_BODY", TableBuilderArgsAddFuncBody(field)); code_ += " #[inline]"; - code_ += " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: " - "{{FIELD_TYPE}}) {"; + code_ += + " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: " + "{{FIELD_TYPE}}) {"; if (is_scalar) { code_.SetValue("FIELD_DEFAULT_VALUE", TableBuilderAddFuncDefaultValue(field)); - code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, " - "{{FIELD_DEFAULT_VALUE}});"; + code_ += + " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, " + "{{FIELD_DEFAULT_VALUE}});"; } else { code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}});"; } @@ -1438,8 +1440,9 @@ class RustGenerator : public BaseGenerator { // finish() function. code_ += " #[inline]"; - code_ += " pub fn finish(self) -> " - "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {"; + code_ += + " pub fn finish(self) -> " + "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {"; code_ += " let o = self.fbb_.end_table(self.start_);"; for (auto it = struct_def.fields.vec.begin(); @@ -1448,8 +1451,9 @@ class RustGenerator : public BaseGenerator { if (!field.deprecated && field.required) { code_.SetValue("FIELD_NAME", MakeSnakeCase(Name(field))); code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field)); - code_ += " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}}," - "\"{{FIELD_NAME}}\");"; + code_ += + " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}}," + "\"{{FIELD_NAME}}\");"; } } code_ += " flatbuffers::WIPOffset::new(o.value())"; @@ -1466,14 +1470,16 @@ class RustGenerator : public BaseGenerator { code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, "")); code_ += " #[inline]"; - code_ += " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> " - " bool {"; + code_ += + " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> " + " bool {"; code_ += " self.{{FIELD_NAME}}() < o.{{FIELD_NAME}}()"; code_ += " }"; code_ += ""; code_ += " #[inline]"; - code_ += " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> " - " ::std::cmp::Ordering {"; + code_ += + " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> " + " ::std::cmp::Ordering {"; code_ += " let key = self.{{FIELD_NAME}}();"; code_ += " key.cmp(&val)"; code_ += " }"; @@ -1499,10 +1505,12 @@ class RustGenerator : public BaseGenerator { code_ += ""; code_ += "#[inline]"; - code_ += "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}" - "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {"; - code_ += " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>" - "(buf)"; + code_ += + "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}" + "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {"; + code_ += + " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>" + "(buf)"; code_ += "}"; code_ += ""; @@ -1550,13 +1558,15 @@ class RustGenerator : public BaseGenerator { code_ += "}"; code_ += ""; code_ += "#[inline]"; - code_ += "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer" - "<'a, 'b>(" - "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, " - "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {"; + code_ += + "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer" + "<'a, 'b>(" + "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, " + "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {"; if (parser_.file_identifier_.length()) { - code_ += " fbb.finish_size_prefixed(root, " - "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));"; + code_ += + " fbb.finish_size_prefixed(root, " + "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));"; } else { code_ += " fbb.finish_size_prefixed(root, None);"; } @@ -1577,8 +1587,8 @@ class RustGenerator : public BaseGenerator { } static void PaddingDefinition(int bits, std::string *code_ptr, int *id) { - *code_ptr += " padding" + NumToString((*id)++) + "__: u" + \ - NumToString(bits) + ","; + *code_ptr += + " padding" + NumToString((*id)++) + "__: u" + NumToString(bits) + ","; } static void PaddingInitializer(int bits, std::string *code_ptr, int *id) { @@ -1644,8 +1654,9 @@ class RustGenerator : public BaseGenerator { code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; code_ += " let src = unsafe {"; - code_ += " ::std::slice::from_raw_parts(" - "self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; + code_ += + " ::std::slice::from_raw_parts(" + "self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; code_ += " };"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; @@ -1656,8 +1667,9 @@ class RustGenerator : public BaseGenerator { code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; code_ += " let src = unsafe {"; - code_ += " ::std::slice::from_raw_parts(" - "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; + code_ += + " ::std::slice::from_raw_parts(" + "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; code_ += " };"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; @@ -1674,14 +1686,12 @@ class RustGenerator : public BaseGenerator { it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; const auto member_name = Name(field) + "_"; - const auto reference = StructMemberAccessNeedsCopy(field.value.type) - ? "" : "&'a "; + const auto reference = + StructMemberAccessNeedsCopy(field.value.type) ? "" : "&'a "; const auto arg_name = "_" + Name(field); const auto arg_type = reference + GetTypeGet(field.value.type); - if (it != struct_def.fields.vec.begin()) { - arg_list += ", "; - } + if (it != struct_def.fields.vec.begin()) { arg_list += ", "; } arg_list += arg_name + ": "; arg_list += arg_type; init_list += " " + member_name; @@ -1717,8 +1727,9 @@ class RustGenerator : public BaseGenerator { auto field_type = TableBuilderArgsAddFuncType(field, "'a"); auto member = "self." + Name(field) + "_"; - auto value = StructMemberAccessNeedsCopy(field.value.type) ? - member + ".from_little_endian()" : member; + auto value = StructMemberAccessNeedsCopy(field.value.type) + ? member + ".from_little_endian()" + : member; code_.SetValue("FIELD_NAME", Name(field)); code_.SetValue("FIELD_TYPE", field_type); @@ -1731,22 +1742,20 @@ class RustGenerator : public BaseGenerator { code_ += " }"; // Generate a comparison function for this field if it is a key. - if (field.key) { - GenKeyFieldMethods(field); - } + if (field.key) { GenKeyFieldMethods(field); } } code_ += "}"; code_ += ""; } void GenNamespaceImports(const int white_spaces) { - std::string indent = std::string(white_spaces, ' '); - code_ += ""; - code_ += indent + "use std::mem;"; - code_ += indent + "use std::cmp::Ordering;"; - code_ += ""; - code_ += indent + "extern crate flatbuffers;"; - code_ += indent + "use self::flatbuffers::EndianScalar;"; + std::string indent = std::string(white_spaces, ' '); + code_ += ""; + code_ += indent + "use std::mem;"; + code_ += indent + "use std::cmp::Ordering;"; + code_ += ""; + code_ += indent + "extern crate flatbuffers;"; + code_ += indent + "use self::flatbuffers::EndianScalar;"; } // Set up the correct namespace. This opens a namespace if the current diff --git a/src/idl_gen_text.cpp b/src/idl_gen_text.cpp index 66926a60..1d0a3caa 100644 --- a/src/idl_gen_text.cpp +++ b/src/idl_gen_text.cpp @@ -142,8 +142,8 @@ bool Print<const void *>(const void *val, Type type, int indent, FLATBUFFERS_ASSERT(prev_val); auto union_type_byte = *prev_val; // Always a uint8_t. if (vector_index >= 0) { - auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(prev_val + - ReadScalar<uoffset_t>(prev_val)); + auto type_vec = reinterpret_cast<const Vector<uint8_t> *>( + prev_val + ReadScalar<uoffset_t>(prev_val)); union_type_byte = type_vec->Get(static_cast<uoffset_t>(vector_index)); } auto enum_val = type.enum_def->ReverseLookup(union_type_byte, true); @@ -205,9 +205,7 @@ bool Print<const void *>(const void *val, Type type, int indent, // clang-format on return true; } - default: - FLATBUFFERS_ASSERT(0); - return false; + default: FLATBUFFERS_ASSERT(0); return false; } } @@ -287,7 +285,7 @@ static bool GenStruct(const StructDef &struct_def, const Table *table, text += ":"; text += " "; switch (fd.value.type.base_type) { - // clang-format off + // clang-format off #define FLATBUFFERS_TD(ENUM, IDLTYPE, \ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \ case BASE_TYPE_ ## ENUM: \ @@ -310,7 +308,7 @@ static bool GenStruct(const StructDef &struct_def, const Table *table, return false; } break; - // clang-format on + // clang-format on } // Track prev val for use with union types. if (struct_def.fixed) { @@ -330,15 +328,11 @@ static bool GenStruct(const StructDef &struct_def, const Table *table, bool GenerateTextFromTable(const Parser &parser, const void *table, const std::string &table_name, std::string *_text) { auto struct_def = parser.LookupStruct(table_name); - if (struct_def == nullptr) { - return false; - } + if (struct_def == nullptr) { return false; } auto &text = *_text; text.reserve(1024); // Reduce amount of inevitable reallocs. auto root = static_cast<const Table *>(table); - if (!GenStruct(*struct_def, root, 0, parser.opts, &text)) { - return false; - } + if (!GenStruct(*struct_def, root, 0, parser.opts, &text)) { return false; } text += NewLine(parser.opts); return true; } @@ -348,9 +342,9 @@ bool GenerateText(const Parser &parser, const void *flatbuffer, std::string *_text) { std::string &text = *_text; FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType() - text.reserve(1024); // Reduce amount of inevitable reallocs. - auto root = parser.opts.size_prefixed ? - GetSizePrefixedRoot<Table>(flatbuffer) : GetRoot<Table>(flatbuffer); + text.reserve(1024); // Reduce amount of inevitable reallocs. + auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer) + : GetRoot<Table>(flatbuffer); if (!GenStruct(*parser.root_struct_def_, root, 0, parser.opts, _text)) { return false; } diff --git a/src/idl_parser.cpp b/src/idl_parser.cpp index 37692f98..56b1547c 100644 --- a/src/idl_parser.cpp +++ b/src/idl_parser.cpp @@ -15,12 +15,11 @@ */ #include <algorithm> +#include <cmath> #include <list> #include <string> #include <utility> -#include <cmath> - #include "flatbuffers/idl.h" #include "flatbuffers/util.h" @@ -114,8 +113,8 @@ std::string MakeScreamingCamel(const std::string &in) { return s; } -void DeserializeDoc( std::vector<std::string> &doc, - const Vector<Offset<String>> *documentation) { +void DeserializeDoc(std::vector<std::string> &doc, + const Vector<Offset<String>> *documentation) { if (documentation == nullptr) return; for (uoffset_t index = 0; index < documentation->size(); index++) doc.push_back(documentation->Get(index)->str()); @@ -399,7 +398,8 @@ CheckedError Parser::Next() { "illegal Unicode sequence (unpaired high surrogate)"); } // reset if non-printable - attr_is_trivial_ascii_string_ &= check_ascii_range(*cursor_, ' ', '~'); + attr_is_trivial_ascii_string_ &= + check_ascii_range(*cursor_, ' ', '~'); attribute_ += *cursor_++; } @@ -437,7 +437,7 @@ CheckedError Parser::Next() { cursor_ += 2; break; } - FLATBUFFERS_FALLTHROUGH(); // else fall thru + FLATBUFFERS_FALLTHROUGH(); // else fall thru default: const auto has_sign = (c == '+') || (c == '-'); // '-'/'+' and following identifier - can be a predefined constant like: @@ -451,14 +451,15 @@ CheckedError Parser::Next() { return NoError(); } - auto dot_lvl = (c == '.') ? 0 : 1; // dot_lvl==0 <=> exactly one '.' seen - if (!dot_lvl && !is_digit(*cursor_)) return NoError(); // enum? + auto dot_lvl = + (c == '.') ? 0 : 1; // dot_lvl==0 <=> exactly one '.' seen + if (!dot_lvl && !is_digit(*cursor_)) return NoError(); // enum? // Parser accepts hexadecimal-floating-literal (see C++ 5.13.4). if (is_digit(c) || has_sign || !dot_lvl) { const auto start = cursor_ - 1; auto start_digits = !is_digit(c) ? cursor_ : cursor_ - 1; - if (!is_digit(c) && is_digit(*cursor_)){ - start_digits = cursor_; // see digit in cursor_ position + if (!is_digit(c) && is_digit(*cursor_)) { + start_digits = cursor_; // see digit in cursor_ position c = *cursor_++; } // hex-float can't begind with '.' @@ -501,7 +502,8 @@ CheckedError Parser::Next() { } std::string ch; ch = c; - if (false == check_ascii_range(c, ' ', '~')) ch = "code: " + NumToString(c); + if (false == check_ascii_range(c, ' ', '~')) + ch = "code: " + NumToString(c); return Error("illegal character: " + ch); } } @@ -730,7 +732,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { if (!IsScalar(type.base_type) || (struct_def.fixed && field->value.constant != "0")) return Error( - "default values currently only supported for scalars in tables"); + "default values currently only supported for scalars in tables"); } // Append .0 if the value has not it (skip hex and scientific floats). // This suffix needed for generated C++ code. @@ -738,7 +740,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { auto &text = field->value.constant; FLATBUFFERS_ASSERT(false == text.empty()); auto s = text.c_str(); - while(*s == ' ') s++; + while (*s == ' ') s++; if (*s == '-' || *s == '+') s++; // 1) A float constants (nan, inf, pi, etc) is a kind of identifier. // 2) A float number needn't ".0" at the end if it has exponent. @@ -774,7 +776,8 @@ CheckedError Parser::ParseField(StructDef &struct_def) { field->deprecated = field->attributes.Lookup("deprecated") != nullptr; auto hash_name = field->attributes.Lookup("hash"); if (hash_name) { - switch ((type.base_type == BASE_TYPE_VECTOR) ? type.element : type.base_type) { + switch ((type.base_type == BASE_TYPE_VECTOR) ? type.element + : type.base_type) { case BASE_TYPE_SHORT: case BASE_TYPE_USHORT: { if (FindHashFunction16(hash_name->constant.c_str()) == nullptr) @@ -798,7 +801,8 @@ CheckedError Parser::ParseField(StructDef &struct_def) { } default: return Error( - "only short, ushort, int, uint, long and ulong data types support hashing."); + "only short, ushort, int, uint, long and ulong data types support " + "hashing."); } } auto cpp_type = field->attributes.Lookup("cpp_type"); @@ -817,8 +821,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { if (field->deprecated && struct_def.fixed) return Error("can't deprecate fields in a struct"); field->required = field->attributes.Lookup("required") != nullptr; - if (field->required && - (struct_def.fixed || IsScalar(type.base_type))) + if (field->required && (struct_def.fixed || IsScalar(type.base_type))) return Error("only non-scalar fields in tables may be 'required'"); field->key = field->attributes.Lookup("key") != nullptr; if (field->key) { @@ -861,8 +864,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { if (field->attributes.Lookup("flexbuffer")) { field->flexbuffer = true; uses_flexbuffers_ = true; - if (type.base_type != BASE_TYPE_VECTOR || - type.element != BASE_TYPE_UCHAR) + if (type.base_type != BASE_TYPE_VECTOR || type.element != BASE_TYPE_UCHAR) return Error("flexbuffer attribute may only apply to a vector of ubyte"); } @@ -902,8 +904,7 @@ CheckedError Parser::ParseComma() { CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field, size_t parent_fieldn, const StructDef *parent_struct_def, - uoffset_t count, - bool inside_vector) { + uoffset_t count, bool inside_vector) { switch (val.type.base_type) { case BASE_TYPE_UNION: { FLATBUFFERS_ASSERT(field); @@ -921,8 +922,8 @@ CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field, uoffset_t offset; ECHECK(atot(elem->first.constant.c_str(), *this, &offset)); vector_of_union_types = reinterpret_cast<Vector<uint8_t> *>( - builder_.GetCurrentBufferPointer() + - builder_.GetSize() - offset); + builder_.GetCurrentBufferPointer() + builder_.GetSize() - + offset); break; } } else { @@ -964,8 +965,7 @@ CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field, } } if (constant.empty() && !vector_of_union_types) { - return Error("missing type field for this union value: " + - field->name); + return Error("missing type field for this union value: " + field->name); } uint8_t enum_idx; if (vector_of_union_types) { @@ -1040,10 +1040,9 @@ void Parser::SerializeStruct(FlatBufferBuilder &builder, builder.AddStructOffset(val.offset, builder.GetSize()); } -template <typename F> +template<typename F> CheckedError Parser::ParseTableDelimiters(size_t &fieldn, - const StructDef *struct_def, - F body) { + const StructDef *struct_def, F body) { // We allow tables both as JSON object{ .. } with field names // or vector[..] with all fields in order char terminator = '}'; @@ -1217,7 +1216,7 @@ CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value, reinterpret_cast<const uint8_t*>(field_value.constant.c_str()), InlineSize(field_value.type)); break; - // clang-format on + // clang-format on } } } @@ -1243,7 +1242,7 @@ CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value, return NoError(); } -template <typename F> +template<typename F> CheckedError Parser::ParseVectorDelimiters(uoffset_t &count, F body) { EXPECT('['); for (;;) { @@ -1259,12 +1258,11 @@ CheckedError Parser::ParseVectorDelimiters(uoffset_t &count, F body) { static bool CompareType(const uint8_t *a, const uint8_t *b, BaseType ftype) { switch (ftype) { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, \ - PTYPE, RTYPE, KTYPE) \ - case BASE_TYPE_ ## ENUM: \ - return ReadScalar<CTYPE>(a) < ReadScalar<CTYPE>(b); +#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \ + RTYPE, KTYPE) \ + case BASE_TYPE_##ENUM: return ReadScalar<CTYPE>(a) < ReadScalar<CTYPE>(b); FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD) - #undef FLATBUFFERS_TD +#undef FLATBUFFERS_TD case BASE_TYPE_STRING: // Indirect offset pointer to string pointer. a += ReadScalar<uoffset_t>(a); @@ -1278,21 +1276,21 @@ static bool CompareType(const uint8_t *a, const uint8_t *b, BaseType ftype) { // See below for why we need our own sort :( template<typename T, typename F, typename S> void SimpleQsort(T *begin, T *end, size_t width, F comparator, S swapper) { - if (end - begin <= static_cast<ptrdiff_t>(width)) return; - auto l = begin + width; - auto r = end; - while (l < r) { - if (comparator(begin, l)) { - r -= width; - swapper(l, r); - } else { - l++; - } + if (end - begin <= static_cast<ptrdiff_t>(width)) return; + auto l = begin + width; + auto r = end; + while (l < r) { + if (comparator(begin, l)) { + r -= width; + swapper(l, r); + } else { + l++; } - l -= width; - swapper(begin, l); - SimpleQsort(begin, l, width, comparator, swapper); - SimpleQsort(r, end, width, comparator, swapper); + } + l -= width; + swapper(begin, l); + SimpleQsort(begin, l, width, comparator, swapper); + SimpleQsort(r, end, width, comparator, swapper); } CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue, @@ -1359,46 +1357,49 @@ CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue, static BaseType ftype = key->value.type.base_type; if (type.struct_def->fixed) { - auto v = reinterpret_cast<VectorOfAny *>( - builder_.GetCurrentBufferPointer()); - SimpleQsort<uint8_t>(v->Data(), - v->Data() + v->size() * type.struct_def->bytesize, - type.struct_def->bytesize, - [](const uint8_t *a, const uint8_t *b) -> bool { - return CompareType(a + offset, b + offset, ftype); - }, [&](uint8_t *a, uint8_t *b) { - // FIXME: faster? - for (size_t i = 0; i < type.struct_def->bytesize; i++) { - std::swap(a[i], b[i]); - } - }); + auto v = + reinterpret_cast<VectorOfAny *>(builder_.GetCurrentBufferPointer()); + SimpleQsort<uint8_t>( + v->Data(), v->Data() + v->size() * type.struct_def->bytesize, + type.struct_def->bytesize, + [](const uint8_t *a, const uint8_t *b) -> bool { + return CompareType(a + offset, b + offset, ftype); + }, + [&](uint8_t *a, uint8_t *b) { + // FIXME: faster? + for (size_t i = 0; i < type.struct_def->bytesize; i++) { + std::swap(a[i], b[i]); + } + }); } else { auto v = reinterpret_cast<Vector<Offset<Table>> *>( - builder_.GetCurrentBufferPointer()); + builder_.GetCurrentBufferPointer()); // Here also can't use std::sort. We do have an iterator type for it, // but it is non-standard as it will dereference the offsets, and thus // can't be used to swap elements. - SimpleQsort<Offset<Table>>(v->data(), v->data() + v->size(), 1, - [](const Offset<Table> *_a, const Offset<Table> *_b) -> bool { - // Indirect offset pointer to table pointer. - auto a = reinterpret_cast<const uint8_t *>(_a) + - ReadScalar<uoffset_t>(_a); - auto b = reinterpret_cast<const uint8_t *>(_b) + - ReadScalar<uoffset_t>(_b); - // Fetch field address from table. - a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset); - b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset); - return CompareType(a, b, ftype); - }, [&](Offset<Table> *a, Offset<Table> *b) { - // These are serialized offsets, so are relative where they are - // stored in memory, so compute the distance between these pointers: - ptrdiff_t diff = (b - a) * sizeof(Offset<Table>); - assert(diff >= 0); // Guaranteed by SimpleQsort. - auto udiff = static_cast<uoffset_t>(diff); - a->o = EndianScalar(ReadScalar<uoffset_t>(a) - udiff); - b->o = EndianScalar(ReadScalar<uoffset_t>(b) + udiff); - std::swap(*a, *b); - }); + SimpleQsort<Offset<Table>>( + v->data(), v->data() + v->size(), 1, + [](const Offset<Table> *_a, const Offset<Table> *_b) -> bool { + // Indirect offset pointer to table pointer. + auto a = reinterpret_cast<const uint8_t *>(_a) + + ReadScalar<uoffset_t>(_a); + auto b = reinterpret_cast<const uint8_t *>(_b) + + ReadScalar<uoffset_t>(_b); + // Fetch field address from table. + a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset); + b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset); + return CompareType(a, b, ftype); + }, + [&](Offset<Table> *a, Offset<Table> *b) { + // These are serialized offsets, so are relative where they are + // stored in memory, so compute the distance between these pointers: + ptrdiff_t diff = (b - a) * sizeof(Offset<Table>); + assert(diff >= 0); // Guaranteed by SimpleQsort. + auto udiff = static_cast<uoffset_t>(diff); + a->o = EndianScalar(ReadScalar<uoffset_t>(a) - udiff); + b->o = EndianScalar(ReadScalar<uoffset_t>(b) + udiff); + std::swap(*a, *b); + }); } } return NoError(); @@ -1478,12 +1479,11 @@ CheckedError Parser::ParseNestedFlatbuffer(Value &val, FieldDef *field, nested_parser.enums_.dict.clear(); nested_parser.enums_.vec.clear(); - if (!ok) { - ECHECK(Error(nested_parser.error_)); - } + if (!ok) { ECHECK(Error(nested_parser.error_)); } // Force alignment for nested flatbuffer - builder_.ForceVectorAlignment(nested_parser.builder_.GetSize(), sizeof(uint8_t), - nested_parser.builder_.GetBufferMinAlignment()); + builder_.ForceVectorAlignment( + nested_parser.builder_.GetSize(), sizeof(uint8_t), + nested_parser.builder_.GetBufferMinAlignment()); auto off = builder_.CreateVector(nested_parser.builder_.GetBufferPointer(), nested_parser.builder_.GetSize()); @@ -1499,7 +1499,7 @@ CheckedError Parser::ParseMetaData(SymbolTable<Value> *attributes) { auto name = attribute_; if (false == (Is(kTokenIdentifier) || Is(kTokenStringConstant))) return Error("attribute name must be either identifier or string: " + - name); + name); if (known_attributes_.find(name) == known_attributes_.end()) return Error("user define attributes must be declared before use: " + name); @@ -1648,10 +1648,10 @@ template<typename T> inline void SingleValueRepack(Value &e, T val) { } #if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) // Normilaze defaults NaN to unsigned quiet-NaN(0). -static inline void SingleValueRepack(Value& e, float val) { +static inline void SingleValueRepack(Value &e, float val) { if (val != val) e.constant = "nan"; } -static inline void SingleValueRepack(Value& e, double val) { +static inline void SingleValueRepack(Value &e, double val) { if (val != val) e.constant = "nan"; } #endif @@ -1774,7 +1774,7 @@ CheckedError Parser::ParseSingleValue(const std::string *name, Value &e, "' to value of <" + std::string(kTypeNames[in_type]) + "> type."; return Error(msg); } - const auto match_type = e.type.base_type; // may differ from in_type + const auto match_type = e.type.base_type; // may differ from in_type // The check_now flag must be true when parse a fbs-schema. // This flag forces to check default scalar values or metadata of field. // For JSON parser the flag should be false. @@ -2210,11 +2210,10 @@ CheckedError Parser::CheckClash(std::vector<FieldDef *> &fields, bool Parser::SupportsAdvancedUnionFeatures() const { return opts.lang_to_generate != 0 && - (opts.lang_to_generate & ~(IDLOptions::kCpp | IDLOptions::kJs | - IDLOptions::kTs | IDLOptions::kPhp | - IDLOptions::kJava | IDLOptions::kCSharp | - IDLOptions::kKotlin | - IDLOptions::kBinary)) == 0; + (opts.lang_to_generate & + ~(IDLOptions::kCpp | IDLOptions::kJs | IDLOptions::kTs | + IDLOptions::kPhp | IDLOptions::kJava | IDLOptions::kCSharp | + IDLOptions::kKotlin | IDLOptions::kBinary)) == 0; } bool Parser::SupportsAdvancedArrayFeatures() const { @@ -2486,8 +2485,8 @@ CheckedError Parser::StartEnum(const std::string &enum_name, bool is_union, if (enums_.Add(current_namespace_->GetFullyQualifiedName(enum_name), &enum_def)) return Error("enum already exists: " + enum_name); - enum_def.underlying_type.base_type = is_union ? BASE_TYPE_UTYPE - : BASE_TYPE_INT; + enum_def.underlying_type.base_type = + is_union ? BASE_TYPE_UTYPE : BASE_TYPE_INT; enum_def.underlying_type.enum_def = &enum_def; if (dest) *dest = &enum_def; return NoError(); @@ -2623,8 +2622,8 @@ CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend, if (oneof_type.base_type != BASE_TYPE_STRUCT || !oneof_type.struct_def || oneof_type.struct_def->fixed) return Error("oneof '" + name + - "' cannot be mapped to a union because member '" + - oneof_field.name + "' is not a table type."); + "' cannot be mapped to a union because member '" + + oneof_field.name + "' is not a table type."); EnumValBuilder evb(*this, *oneof_union); auto ev = evb.CreateEnumerator(oneof_type.struct_def->name); ev->union_type = oneof_type; @@ -2989,9 +2988,7 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths, // entered into included_files_. // This is recursive, but only go as deep as the number of include // statements. - if (source_filename) { - included_files_.erase(source_filename); - } + if (source_filename) { included_files_.erase(source_filename); } return DoParse(source, include_paths, source_filename, include_filename); } @@ -3015,9 +3012,9 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths, uoffset_t toff; ECHECK(ParseTable(*root_struct_def_, nullptr, &toff)); if (opts.size_prefixed) { - builder_.FinishSizePrefixed(Offset<Table>(toff), file_identifier_.length() - ? file_identifier_.c_str() - : nullptr); + builder_.FinishSizePrefixed( + Offset<Table>(toff), + file_identifier_.length() ? file_identifier_.c_str() : nullptr); } else { builder_.Finish(Offset<Table>(toff), file_identifier_.length() ? file_identifier_.c_str() @@ -3038,8 +3035,7 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths, if (opts.root_type.empty()) { if (!SetRootType(root_type.c_str())) return Error("unknown root type: " + root_type); - if (root_struct_def_->fixed) - return Error("root type must be a table"); + if (root_struct_def_->fixed) return Error("root type must be a table"); } EXPECT(';'); } else if (IsIdent("file_identifier")) { @@ -3144,10 +3140,9 @@ void Parser::Serialize() { auto fiid__ = builder_.CreateString(file_identifier_); auto fext__ = builder_.CreateString(file_extension_); auto serv__ = builder_.CreateVectorOfSortedTables(&service_offsets); - auto schema_offset = - reflection::CreateSchema(builder_, objs__, enum__, fiid__, fext__, - (root_struct_def_ ? root_struct_def_->serialized_location : 0), - serv__); + auto schema_offset = reflection::CreateSchema( + builder_, objs__, enum__, fiid__, fext__, + (root_struct_def_ ? root_struct_def_->serialized_location : 0), serv__); if (opts.size_prefixed) { builder_.FinishSizePrefixed(schema_offset, reflection::SchemaIdentifier()); } else { @@ -3193,22 +3188,20 @@ Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder, auto flds__ = builder->CreateVectorOfSortedTables(&field_offsets); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; + ? builder->CreateVectorOfStrings(doc_comment) + : 0; return reflection::CreateObject(*builder, name__, flds__, fixed, static_cast<int>(minalign), - static_cast<int>(bytesize), - attr__, docs__); + static_cast<int>(bytesize), attr__, docs__); } bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) { - if (!DeserializeAttributes(parser, object->attributes())) - return false; + if (!DeserializeAttributes(parser, object->attributes())) return false; DeserializeDoc(doc_comment, object->documentation()); name = parser.UnqualifiedName(object->name()->str()); predecl = false; sortbysize = attributes.Lookup("original_order") == nullptr && !fixed; - const auto& of = *(object->fields()); + const auto &of = *(object->fields()); auto indexes = std::vector<uoffset_t>(of.size()); for (uoffset_t i = 0; i < of.size(); i++) indexes[of.Get(i)->id()] = i; size_t tmp_struct_size = 0; @@ -3224,9 +3217,7 @@ bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) { // Recompute padding since that's currently not serialized. auto size = InlineSize(field_def->value.type); auto next_field = - i + 1 < indexes.size() - ? of.Get(indexes[i+1]) - : nullptr; + i + 1 < indexes.size() ? of.Get(indexes[i + 1]) : nullptr; tmp_struct_size += size; field_def->padding = next_field ? (next_field->offset() - field_def->value.offset) - size @@ -3245,9 +3236,10 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder, auto type__ = value.type.Serialize(builder); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; - return reflection::CreateField(*builder, name__, type__, id, value.offset, + ? builder->CreateVectorOfStrings(doc_comment) + : 0; + return reflection::CreateField( + *builder, name__, type__, id, value.offset, // Is uint64>max(int64) tested? IsInteger(value.type.base_type) ? StringToInt(value.constant.c_str()) : 0, // result may be platform-dependent if underlying is float (not double) @@ -3261,8 +3253,7 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder, bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) { name = field->name()->str(); defined_namespace = parser.current_namespace_; - if (!value.type.Deserialize(parser, field->type())) - return false; + if (!value.type.Deserialize(parser, field->type())) return false; value.offset = field->offset(); if (IsInteger(value.type.base_type)) { value.constant = NumToString(field->default_integer()); @@ -3276,8 +3267,7 @@ bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) { deprecated = field->deprecated(); required = field->required(); key = field->key(); - if (!DeserializeAttributes(parser, field->attributes())) - return false; + if (!DeserializeAttributes(parser, field->attributes())) return false; // TODO: this should probably be handled by a separate attribute if (attributes.Lookup("flexbuffer")) { flexbuffer = true; @@ -3301,18 +3291,16 @@ Offset<reflection::RPCCall> RPCCall::Serialize(FlatBufferBuilder *builder, auto name__ = builder->CreateString(name); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; - return reflection::CreateRPCCall(*builder, name__, - request->serialized_location, - response->serialized_location, - attr__, docs__); + ? builder->CreateVectorOfStrings(doc_comment) + : 0; + return reflection::CreateRPCCall( + *builder, name__, request->serialized_location, + response->serialized_location, attr__, docs__); } bool RPCCall::Deserialize(Parser &parser, const reflection::RPCCall *call) { name = call->name()->str(); - if (!DeserializeAttributes(parser, call->attributes())) - return false; + if (!DeserializeAttributes(parser, call->attributes())) return false; DeserializeDoc(doc_comment, call->documentation()); request = parser.structs_.Lookup(call->request()->name()->str()); response = parser.structs_.Lookup(call->response()->name()->str()); @@ -3331,8 +3319,8 @@ Offset<reflection::Service> ServiceDef::Serialize(FlatBufferBuilder *builder, auto call__ = builder->CreateVector(servicecall_offsets); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; + ? builder->CreateVectorOfStrings(doc_comment) + : 0; return reflection::CreateService(*builder, name__, call__, attr__, docs__); } @@ -3349,8 +3337,7 @@ bool ServiceDef::Deserialize(Parser &parser, } } } - if (!DeserializeAttributes(parser, service->attributes())) - return false; + if (!DeserializeAttributes(parser, service->attributes())) return false; DeserializeDoc(doc_comment, service->documentation()); return true; } @@ -3367,8 +3354,8 @@ Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder, auto type__ = underlying_type.Serialize(builder); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; + ? builder->CreateVectorOfStrings(doc_comment) + : 0; return reflection::CreateEnum(*builder, name__, vals__, is_union, type__, attr__, docs__); } @@ -3387,8 +3374,7 @@ bool EnumDef::Deserialize(Parser &parser, const reflection::Enum *_enum) { if (!underlying_type.Deserialize(parser, _enum->underlying_type())) { return false; } - if (!DeserializeAttributes(parser, _enum->attributes())) - return false; + if (!DeserializeAttributes(parser, _enum->attributes())) return false; DeserializeDoc(doc_comment, _enum->documentation()); return true; } @@ -3398,9 +3384,10 @@ Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder, auto name__ = builder->CreateString(name); auto type__ = union_type.Serialize(builder); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; - return reflection::CreateEnumVal(*builder, name__, value, + ? builder->CreateVectorOfStrings(doc_comment) + : 0; + return reflection::CreateEnumVal( + *builder, name__, value, union_type.struct_def ? union_type.struct_def->serialized_location : 0, type__, docs__); } @@ -3409,8 +3396,7 @@ bool EnumVal::Deserialize(const Parser &parser, const reflection::EnumVal *val) { name = val->name()->str(); value = val->value(); - if (!union_type.Deserialize(parser, val->union_type())) - return false; + if (!union_type.Deserialize(parser, val->union_type())) return false; DeserializeDoc(doc_comment, val->documentation()); return true; } @@ -3432,8 +3418,7 @@ bool Type::Deserialize(const Parser &parser, const reflection::Type *type) { bool is_series = type->base_type() == reflection::Vector || type->base_type() == reflection::Array; if (type->base_type() == reflection::Obj || - (is_series && - type->element() == reflection::Obj)) { + (is_series && type->element() == reflection::Obj)) { if (static_cast<size_t>(type->index()) < parser.structs_.vec.size()) { struct_def = parser.structs_.vec[type->index()]; struct_def->refcount++; @@ -3474,8 +3459,7 @@ Definition::SerializeAttributes(FlatBufferBuilder *builder, bool Definition::DeserializeAttributes( Parser &parser, const Vector<Offset<reflection::KeyValue>> *attrs) { - if (attrs == nullptr) - return true; + if (attrs == nullptr) return true; for (uoffset_t i = 0; i < attrs->size(); ++i) { auto kv = attrs->Get(i); auto value = new Value(); @@ -3495,7 +3479,7 @@ bool Definition::DeserializeAttributes( bool Parser::Deserialize(const uint8_t *buf, const size_t size) { flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t *>(buf), size); bool size_prefixed = false; - if(!reflection::SchemaBufferHasIdentifier(buf)) { + if (!reflection::SchemaBufferHasIdentifier(buf)) { if (!flatbuffers::BufferHasIdentifier(buf, reflection::SchemaIdentifier(), true)) return false; @@ -3504,9 +3488,7 @@ bool Parser::Deserialize(const uint8_t *buf, const size_t size) { } auto verify_fn = size_prefixed ? &reflection::VerifySizePrefixedSchemaBuffer : &reflection::VerifySchemaBuffer; - if (!verify_fn(verifier)) { - return false; - } + if (!verify_fn(verifier)) { return false; } auto schema = size_prefixed ? reflection::GetSizePrefixedSchema(buf) : reflection::GetSchema(buf); return Deserialize(schema); @@ -3555,7 +3537,7 @@ bool Parser::Deserialize(const reflection::Schema *schema) { auto struct_def = structs_.Lookup(qualified_name); struct_def->defined_namespace = GetNamespace(qualified_name, namespaces_, namespaces_index); - if (!struct_def->Deserialize(*this, * it)) { return false; } + if (!struct_def->Deserialize(*this, *it)) { return false; } if (schema->root_table() == *it) { root_struct_def_ = struct_def; } } for (auto it = schema->enums()->begin(); it != schema->enums()->end(); ++it) { diff --git a/src/reflection.cpp b/src/reflection.cpp index fc211c5f..409dbd03 100644 --- a/src/reflection.cpp +++ b/src/reflection.cpp @@ -15,6 +15,7 @@ */ #include "flatbuffers/reflection.h" + #include "flatbuffers/util.h" // Helper functionality for reflection. @@ -431,8 +432,8 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb, break; } } - FLATBUFFERS_FALLTHROUGH(); // fall thru - default: { // Scalars and structs. + FLATBUFFERS_FALLTHROUGH(); // fall thru + default: { // Scalars and structs. auto element_size = GetTypeSize(element_base_type); if (elemobjectdef && elemobjectdef->is_struct()) element_size = elemobjectdef->bytesize(); @@ -466,7 +467,7 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb, break; } } - FLATBUFFERS_FALLTHROUGH(); // fall thru + FLATBUFFERS_FALLTHROUGH(); // fall thru case reflection::Union: case reflection::String: case reflection::Vector: @@ -495,9 +496,8 @@ bool VerifyStruct(flatbuffers::Verifier &v, auto offset = parent_table.GetOptionalFieldOffset(field_offset); if (required && !offset) { return false; } - return !offset || - v.Verify(reinterpret_cast<const uint8_t *>(&parent_table), offset, - obj.bytesize()); + return !offset || v.Verify(reinterpret_cast<const uint8_t *>(&parent_table), + offset, obj.bytesize()); } bool VerifyVectorOfStructs(flatbuffers::Verifier &v, @@ -535,9 +535,8 @@ bool VerifyUnion(flatbuffers::Verifier &v, const reflection::Schema &schema, } case reflection::String: return v.VerifyString( - reinterpret_cast<const flatbuffers::String *>(elem)); - default: - return false; + reinterpret_cast<const flatbuffers::String *>(elem)); + default: return false; } } @@ -597,27 +596,24 @@ bool VerifyVector(flatbuffers::Verifier &v, const reflection::Schema &schema, } } case reflection::Union: { - auto vec = flatbuffers::GetFieldV<flatbuffers::Offset<uint8_t>>(table, - vec_field); + auto vec = flatbuffers::GetFieldV<flatbuffers::Offset<uint8_t>>( + table, vec_field); if (!v.VerifyVector(vec)) return false; if (!vec) return true; - auto type_vec = table.GetPointer<Vector<uint8_t> *> - (vec_field.offset() - sizeof(voffset_t)); + auto type_vec = table.GetPointer<Vector<uint8_t> *>(vec_field.offset() - + sizeof(voffset_t)); if (!v.VerifyVector(type_vec)) return false; for (uoffset_t j = 0; j < vec->size(); j++) { // get union type from the prev field auto utype = type_vec->Get(j); auto elem = vec->Get(j); - if (!VerifyUnion(v, schema, utype, elem, vec_field)) - return false; + if (!VerifyUnion(v, schema, utype, elem, vec_field)) return false; } return true; } case reflection::Vector: case reflection::None: - default: - FLATBUFFERS_ASSERT(false); - return false; + default: FLATBUFFERS_ASSERT(false); return false; } } @@ -663,8 +659,7 @@ bool VerifyObject(flatbuffers::Verifier &v, const reflection::Schema &schema, } break; case reflection::Vector: - if (!VerifyVector(v, schema, *table, *field_def)) - return false; + if (!VerifyVector(v, schema, *table, *field_def)) return false; break; case reflection::Obj: { auto child_obj = schema.objects()->Get(field_def->type()->index()); @@ -687,15 +682,11 @@ bool VerifyObject(flatbuffers::Verifier &v, const reflection::Schema &schema, voffset_t utype_offset = field_def->offset() - sizeof(voffset_t); auto utype = table->GetField<uint8_t>(utype_offset, 0); auto uval = reinterpret_cast<const uint8_t *>( - flatbuffers::GetFieldT(*table, *field_def)); - if (!VerifyUnion(v, schema, utype, uval, *field_def)) { - return false; - } + flatbuffers::GetFieldT(*table, *field_def)); + if (!VerifyUnion(v, schema, utype, uval, *field_def)) { return false; } break; } - default: - FLATBUFFERS_ASSERT(false); - break; + default: FLATBUFFERS_ASSERT(false); break; } } diff --git a/src/util.cpp b/src/util.cpp index b80bed25..08b77918 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -242,9 +242,9 @@ bool SetGlobalTestLocale(const char *locale_name, std::string *_value) { } bool ReadEnvironmentVariable(const char *var_name, std::string *_value) { - #ifdef _MSC_VER - __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS - #endif +#ifdef _MSC_VER + __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS +#endif auto env_str = std::getenv(var_name); if (!env_str) return false; if (_value) *_value = std::string(env_str); diff --git a/tests/native_type_test_impl.cpp b/tests/native_type_test_impl.cpp index 04ddb963..edf23ebf 100644 --- a/tests/native_type_test_impl.cpp +++ b/tests/native_type_test_impl.cpp @@ -1,13 +1,13 @@ #include "native_type_test_impl.h" + #include "native_type_test_generated.h" namespace flatbuffers { - Geometry::Vector3D Pack(const Native::Vector3D &obj) { - return Geometry::Vector3D(obj.x, obj.y, obj.z); - } - - const Native::Vector3D UnPack(const Geometry::Vector3D &obj) { - return Native::Vector3D(obj.x(), obj.y(), obj.z()); - } +Geometry::Vector3D Pack(const Native::Vector3D &obj) { + return Geometry::Vector3D(obj.x, obj.y, obj.z); } +const Native::Vector3D UnPack(const Geometry::Vector3D &obj) { + return Native::Vector3D(obj.x(), obj.y(), obj.z()); +} +} // namespace flatbuffers diff --git a/tests/native_type_test_impl.h b/tests/native_type_test_impl.h index 2473ad3c..fb35e0fc 100644 --- a/tests/native_type_test_impl.h +++ b/tests/native_type_test_impl.h @@ -2,23 +2,31 @@ #define NATIVE_TYPE_TEST_IMPL_H namespace Native { - struct Vector3D { - float x; - float y; - float z; +struct Vector3D { + float x; + float y; + float z; - Vector3D() { x = 0; y = 0; z = 0; }; - Vector3D(float _x, float _y, float _z) { this->x = _x; this->y = _y; this->z = _z; } + Vector3D() { + x = 0; + y = 0; + z = 0; }; -} + Vector3D(float _x, float _y, float _z) { + this->x = _x; + this->y = _y; + this->z = _z; + } +}; +} // namespace Native -namespace Geometry { - struct Vector3D; +namespace Geometry { +struct Vector3D; } namespace flatbuffers { - Geometry::Vector3D Pack(const Native::Vector3D &obj); - const Native::Vector3D UnPack(const Geometry::Vector3D &obj); -} +Geometry::Vector3D Pack(const Native::Vector3D &obj); +const Native::Vector3D UnPack(const Geometry::Vector3D &obj); +} // namespace flatbuffers -#endif // VECTOR3D_PACK_H +#endif // VECTOR3D_PACK_H diff --git a/tests/test.cpp b/tests/test.cpp index 6e2dc546..abfae0d5 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -14,6 +14,7 @@ * limitations under the License. */ #include <cmath> + #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/minireflect.h" @@ -35,7 +36,7 @@ #include "union_vector/union_vector_generated.h" #include "monster_extra_generated.h" #if !defined(_MSC_VER) || _MSC_VER >= 1700 -#include "arrays_test_generated.h" +# include "arrays_test_generated.h" #endif #include "native_type_test_generated.h" @@ -43,7 +44,6 @@ #include "flatbuffers/flexbuffers.h" - // clang-format off // Check that char* and uint8_t* are interoperable types. // The reinterpret_cast<> between the pointers are used to simplify data loading. @@ -72,7 +72,8 @@ void FlatBufferBuilderTest(); // http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator uint32_t lcg_seed = 48271; uint32_t lcg_rand() { - return lcg_seed = (static_cast<uint64_t>(lcg_seed) * 279470273UL) % 4294967291UL; + return lcg_seed = + (static_cast<uint64_t>(lcg_seed) * 279470273UL) % 4294967291UL; } void lcg_reset() { lcg_seed = 48271; } @@ -200,14 +201,13 @@ flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) { auto vecofcolors = builder.CreateVectorScalarCast<uint8_t, Color>(colors, 2); // shortcut for creating monster with all fields set: - auto mloc = CreateMonster(builder, &vec, 150, 80, name, inventory, Color_Blue, - Any_Monster, mlocs[1].Union(), // Store a union. - testv, vecofstrings, vecoftables, 0, - nested_flatbuffer_vector, 0, false, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2, - vecofstructs, flex, testv2, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, AnyUniqueAliases_NONE, 0, - AnyAmbiguousAliases_NONE, 0, vecofcolors); + auto mloc = CreateMonster( + builder, &vec, 150, 80, name, inventory, Color_Blue, Any_Monster, + mlocs[1].Union(), // Store a union. + testv, vecofstrings, vecoftables, 0, nested_flatbuffer_vector, 0, false, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2, + vecofstructs, flex, testv2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + AnyUniqueAliases_NONE, 0, AnyAmbiguousAliases_NONE, 0, vecofcolors); FinishMonsterBuffer(builder, mloc); @@ -567,8 +567,7 @@ void SizePrefixedTest() { // Create size prefixed buffer. flatbuffers::FlatBufferBuilder fbb; FinishSizePrefixedMonsterBuffer( - fbb, - CreateMonster(fbb, 0, 200, 300, fbb.CreateString("bob"))); + fbb, CreateMonster(fbb, 0, 200, 300, fbb.CreateString("bob"))); // Verify it. flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize()); @@ -598,7 +597,8 @@ void JsonDefaultTest() { // load FlatBuffer schema (.fbs) from disk std::string schemafile; TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(), - false, &schemafile), true); + false, &schemafile), + true); // parse schema first, so we can use it to parse the data after flatbuffers::Parser parser; auto include_test_path = @@ -771,7 +771,7 @@ void ParseAndGenerateTextTest(bool binary) { true); auto include_test_path = - flatbuffers::ConCatPathFileName(test_data_path, "include_test"); + flatbuffers::ConCatPathFileName(test_data_path, "include_test"); const char *include_directories[] = { test_data_path.c_str(), include_test_path.c_str(), nullptr }; @@ -782,8 +782,10 @@ void ParseAndGenerateTextTest(bool binary) { reinterpret_cast<const uint8_t *>(schemafile.c_str()), schemafile.size()); TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); - //auto schema = reflection::GetSchema(schemafile.c_str()); - TEST_EQ(parser.Deserialize((const uint8_t *)schemafile.c_str(), schemafile.size()), true); + // auto schema = reflection::GetSchema(schemafile.c_str()); + TEST_EQ(parser.Deserialize((const uint8_t *)schemafile.c_str(), + schemafile.size()), + true); } else { TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true); } @@ -1029,7 +1031,8 @@ void ReflectionTest(uint8_t *flatbuf, size_t length) { } void MiniReflectFlatBuffersTest(uint8_t *flatbuf) { - auto s = flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable()); + auto s = + flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable()); TEST_EQ_STR( s.c_str(), "{ " @@ -1060,15 +1063,15 @@ void MiniReflectFlatBuffersTest(uint8_t *flatbuf) { "}"); Test test(16, 32); - Vec3 vec(1,2,3, 1.5, Color_Red, test); + Vec3 vec(1, 2, 3, 1.5, Color_Red, test); flatbuffers::FlatBufferBuilder vec_builder; vec_builder.Finish(vec_builder.CreateStruct(vec)); auto vec_buffer = vec_builder.Release(); auto vec_str = flatbuffers::FlatBufferToString(vec_buffer.data(), Vec3::MiniReflectTypeTable()); - TEST_EQ_STR( - vec_str.c_str(), - "{ x: 1.0, y: 2.0, z: 3.0, test1: 1.5, test2: Red, test3: { a: 16, b: 32 } }"); + TEST_EQ_STR(vec_str.c_str(), + "{ x: 1.0, y: 2.0, z: 3.0, test1: 1.5, test2: Red, test3: { a: " + "16, b: 32 } }"); } // Parse a .proto schema, output as .fbs @@ -1085,11 +1088,10 @@ void ParseProtoTest() { flatbuffers::LoadFile((test_data_path + "prototest/test.golden").c_str(), false, &goldenfile), true); - TEST_EQ( - flatbuffers::LoadFile((test_data_path + - "prototest/test_union.golden").c_str(), - false, &goldenunionfile), - true); + TEST_EQ(flatbuffers::LoadFile( + (test_data_path + "prototest/test_union.golden").c_str(), false, + &goldenunionfile), + true); flatbuffers::IDLOptions opts; opts.include_dependence_headers = false; @@ -1526,9 +1528,9 @@ bool FloatCompare(float a, float b) { return fabs(a - b) < 0.001; } // Additional parser testing not covered elsewhere. void ValueTest() { // Test scientific notation numbers. - TEST_EQ(FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"), - 3.14159f), - true); + TEST_EQ( + FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"), 3.14159f), + true); // number in string TEST_EQ(FloatCompare(TestValue<float>("{ Y:\"0.0314159e+2\" }", "float"), 3.14159f), @@ -1566,7 +1568,6 @@ void ValueTest() { // check comments before and after json object TEST_EQ(TestValue<int>("/*before*/ { Y:1 } /*after*/", "int"), 1); TEST_EQ(TestValue<int>("//before \n { Y:1 } //after", "int"), 1); - } void NestedListTest() { @@ -1608,8 +1609,8 @@ void EnumNamesTest() { // For details see C++17 standard or explanation on the SO: // stackoverflow.com/questions/18195312/what-happens-if-you-static-cast-invalid-value-to-enum-class TEST_EQ_STR("", EnumNameColor(static_cast<Color>(0))); - TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY-1))); - TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY+1))); + TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY - 1))); + TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY + 1))); } void EnumOutOfRangeTest() { @@ -1629,12 +1630,14 @@ void EnumOutOfRangeTest() { TestError("enum X:uint { Y = -1 }", "enum value does not fit"); TestError("enum X:uint { Y = 4294967297 }", "enum value does not fit"); TestError("enum X:long { Y = 9223372036854775808 }", "does not fit"); - TestError("enum X:long { Y = 9223372036854775807, Z }", "enum value does not fit"); + TestError("enum X:long { Y = 9223372036854775807, Z }", + "enum value does not fit"); TestError("enum X:ulong { Y = -1 }", "does not fit"); TestError("enum X:ubyte (bit_flags) { Y=8 }", "bit flag out"); - TestError("enum X:byte (bit_flags) { Y=7 }", "must be unsigned"); // -128 + TestError("enum X:byte (bit_flags) { Y=7 }", "must be unsigned"); // -128 // bit_flgs out of range - TestError("enum X:ubyte (bit_flags) { Y0,Y1,Y2,Y3,Y4,Y5,Y6,Y7,Y8 }", "out of range"); + TestError("enum X:ubyte (bit_flags) { Y0,Y1,Y2,Y3,Y4,Y5,Y6,Y7,Y8 }", + "out of range"); } void EnumValueTest() { @@ -1734,11 +1737,12 @@ void IntegerOutOfRangeTest() { void IntegerBoundaryTest() { // Check numerical compatibility with non-C++ languages. - // By the C++ standard, std::numerical_limits<int64_t>::min() == -9223372036854775807 (-2^63+1) or less* - // The Flatbuffers grammar and most of the languages (C#, Java, Rust) expect - // that minimum values are: -128, -32768,.., -9223372036854775808. - // Since C++20, static_cast<int64>(0x8000000000000000ULL) is well-defined two's complement cast. - // Therefore -9223372036854775808 should be valid negative value. + // By the C++ standard, std::numerical_limits<int64_t>::min() == + // -9223372036854775807 (-2^63+1) or less* The Flatbuffers grammar and most of + // the languages (C#, Java, Rust) expect that minimum values are: -128, + // -32768,.., -9223372036854775808. Since C++20, + // static_cast<int64>(0x8000000000000000ULL) is well-defined two's complement + // cast. Therefore -9223372036854775808 should be valid negative value. TEST_EQ(flatbuffers::numeric_limits<int8_t>::min(), -128); TEST_EQ(flatbuffers::numeric_limits<int8_t>::max(), 127); TEST_EQ(flatbuffers::numeric_limits<int16_t>::min(), -32768); @@ -1810,11 +1814,11 @@ void ValidFloatTest() { TEST_EQ(TestValue<float>("{ Y:5 }", "float"), 5.0f); TEST_EQ(TestValue<float>("{ Y:\"5\" }", "float"), 5.0f); - #if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) +#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) // Old MSVC versions may have problem with this check. // https://www.exploringbinary.com/visual-c-plus-plus-strtod-still-broken/ TEST_EQ(TestValue<double>("{ Y:6.9294956446009195e15 }", "double"), - 6929495644600920.0); + 6929495644600920.0); // check nan's TEST_EQ(std::isnan(TestValue<double>("{ Y:nan }", "double")), true); TEST_EQ(std::isnan(TestValue<float>("{ Y:nan }", "float")), true); @@ -1936,8 +1940,8 @@ void GenerateTableTextTest() { TEST_EQ(ok, true); auto include_test_path = flatbuffers::ConCatPathFileName(test_data_path, "include_test"); - const char *include_directories[] = {test_data_path.c_str(), - include_test_path.c_str(), nullptr}; + const char *include_directories[] = { test_data_path.c_str(), + include_test_path.c_str(), nullptr }; flatbuffers::IDLOptions opt; opt.indent_step = -1; flatbuffers::Parser parser(opt); @@ -2237,7 +2241,7 @@ void InvalidUTF8Test() { // Check independence of identifier from locale. std::string locale_ident; locale_ident += "table T { F"; - locale_ident += static_cast<char>(-32); // unsigned 0xE0 + locale_ident += static_cast<char>(-32); // unsigned 0xE0 locale_ident += " :string; }"; locale_ident += "root_type T;"; locale_ident += "{}"; @@ -2311,8 +2315,8 @@ void UnionVectorTest() { // load FlatBuffer fbs schema and json. std::string schemafile, jsonfile; TEST_EQ(flatbuffers::LoadFile( - (test_data_path + "union_vector/union_vector.fbs").c_str(), - false, &schemafile), + (test_data_path + "union_vector/union_vector.fbs").c_str(), false, + &schemafile), true); TEST_EQ(flatbuffers::LoadFile( (test_data_path + "union_vector/union_vector.json").c_str(), @@ -2420,70 +2424,67 @@ void UnionVectorTest() { "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, " "{ books_read: 2 }, \"Other\", \"Unused\" ] }"); - flatbuffers::ToStringVisitor visitor("\n", true, " "); IterateFlatBuffer(fbb.GetBufferPointer(), MovieTypeTable(), &visitor); - TEST_EQ_STR( - visitor.s.c_str(), - "{\n" - " \"main_character_type\": \"Rapunzel\",\n" - " \"main_character\": {\n" - " \"hair_length\": 6\n" - " },\n" - " \"characters_type\": [\n" - " \"Belle\",\n" - " \"MuLan\",\n" - " \"BookFan\",\n" - " \"Other\",\n" - " \"Unused\"\n" - " ],\n" - " \"characters\": [\n" - " {\n" - " \"books_read\": 7\n" - " },\n" - " {\n" - " \"sword_attack_damage\": 5\n" - " },\n" - " {\n" - " \"books_read\": 2\n" - " },\n" - " \"Other\",\n" - " \"Unused\"\n" - " ]\n" - "}"); + TEST_EQ_STR(visitor.s.c_str(), + "{\n" + " \"main_character_type\": \"Rapunzel\",\n" + " \"main_character\": {\n" + " \"hair_length\": 6\n" + " },\n" + " \"characters_type\": [\n" + " \"Belle\",\n" + " \"MuLan\",\n" + " \"BookFan\",\n" + " \"Other\",\n" + " \"Unused\"\n" + " ],\n" + " \"characters\": [\n" + " {\n" + " \"books_read\": 7\n" + " },\n" + " {\n" + " \"sword_attack_damage\": 5\n" + " },\n" + " {\n" + " \"books_read\": 2\n" + " },\n" + " \"Other\",\n" + " \"Unused\"\n" + " ]\n" + "}"); // Generate text using parsed schema. std::string jsongen; auto result = GenerateText(parser, fbb.GetBufferPointer(), &jsongen); TEST_EQ(result, true); - TEST_EQ_STR( - jsongen.c_str(), - "{\n" - " main_character_type: \"Rapunzel\",\n" - " main_character: {\n" - " hair_length: 6\n" - " },\n" - " characters_type: [\n" - " \"Belle\",\n" - " \"MuLan\",\n" - " \"BookFan\",\n" - " \"Other\",\n" - " \"Unused\"\n" - " ],\n" - " characters: [\n" - " {\n" - " books_read: 7\n" - " },\n" - " {\n" - " sword_attack_damage: 5\n" - " },\n" - " {\n" - " books_read: 2\n" - " },\n" - " \"Other\",\n" - " \"Unused\"\n" - " ]\n" - "}\n"); + TEST_EQ_STR(jsongen.c_str(), + "{\n" + " main_character_type: \"Rapunzel\",\n" + " main_character: {\n" + " hair_length: 6\n" + " },\n" + " characters_type: [\n" + " \"Belle\",\n" + " \"MuLan\",\n" + " \"BookFan\",\n" + " \"Other\",\n" + " \"Unused\"\n" + " ],\n" + " characters: [\n" + " {\n" + " books_read: 7\n" + " },\n" + " {\n" + " sword_attack_damage: 5\n" + " },\n" + " {\n" + " books_read: 2\n" + " },\n" + " \"Other\",\n" + " \"Unused\"\n" + " ]\n" + "}\n"); // Simple test with reflection. parser.Serialize(); @@ -2496,7 +2497,8 @@ void UnionVectorTest() { TEST_EQ(parser2.Parse("struct Bool { b:bool; }" "union Any { Bool }" "table Root { a:Any; }" - "root_type Root;"), true); + "root_type Root;"), + true); TEST_EQ(parser2.Parse("{a_type:Bool,a:{b:true}}"), true); } @@ -2703,7 +2705,7 @@ void TypeAliasesTest() { TEST_EQ(ta->u64(), flatbuffers::numeric_limits<uint64_t>::max()); TEST_EQ(ta->f32(), 2.3f); TEST_EQ(ta->f64(), 2.3); - using namespace flatbuffers; // is_same + using namespace flatbuffers; // is_same static_assert(is_same<decltype(ta->i8()), int8_t>::value, "invalid type"); static_assert(is_same<decltype(ta->i16()), int16_t>::value, "invalid type"); static_assert(is_same<decltype(ta->i32()), int32_t>::value, "invalid type"); @@ -2729,14 +2731,16 @@ void UninitializedVectorTest() { flatbuffers::FlatBufferBuilder builder; Test *buf = nullptr; - auto vector_offset = builder.CreateUninitializedVectorOfStructs<Test>(2, &buf); + auto vector_offset = + builder.CreateUninitializedVectorOfStructs<Test>(2, &buf); TEST_NOTNULL(buf); buf[0] = Test(10, 20); buf[1] = Test(30, 40); auto required_name = builder.CreateString("myMonster"); auto monster_builder = MonsterBuilder(builder); - monster_builder.add_name(required_name); // required field mandated for monster. + monster_builder.add_name( + required_name); // required field mandated for monster. monster_builder.add_test4(vector_offset); builder.Finish(monster_builder.Finish()); @@ -2781,11 +2785,11 @@ void EqualOperatorTest() { // For testing any binaries, e.g. from fuzzing. void LoadVerifyBinaryTest() { std::string binary; - if (flatbuffers::LoadFile((test_data_path + - "fuzzer/your-filename-here").c_str(), - true, &binary)) { + if (flatbuffers::LoadFile( + (test_data_path + "fuzzer/your-filename-here").c_str(), true, + &binary)) { flatbuffers::Verifier verifier( - reinterpret_cast<const uint8_t *>(binary.data()), binary.size()); + reinterpret_cast<const uint8_t *>(binary.data()), binary.size()); TEST_EQ(VerifyMonsterBuffer(verifier), true); } } @@ -2801,24 +2805,28 @@ void CreateSharedStringTest() { TEST_EQ(onetwo.o != two.o, true); // Support for embedded nulls - const char chars_b[] = {'a', '\0', 'b'}; - const char chars_c[] = {'a', '\0', 'c'}; + const char chars_b[] = { 'a', '\0', 'b' }; + const char chars_c[] = { 'a', '\0', 'c' }; const auto null_b1 = builder.CreateSharedString(chars_b, sizeof(chars_b)); const auto null_c = builder.CreateSharedString(chars_c, sizeof(chars_c)); const auto null_b2 = builder.CreateSharedString(chars_b, sizeof(chars_b)); - TEST_EQ(null_b1.o != null_c.o, true); // Issue#5058 repro + TEST_EQ(null_b1.o != null_c.o, true); // Issue#5058 repro TEST_EQ(null_b1.o, null_b2.o); // Put the strings into an array for round trip verification. - const flatbuffers::Offset<flatbuffers::String> array[7] = { one1, two, one2, onetwo, null_b1, null_c, null_b2 }; - const auto vector_offset = builder.CreateVector(array, flatbuffers::uoffset_t(7)); + const flatbuffers::Offset<flatbuffers::String> array[7] = { + one1, two, one2, onetwo, null_b1, null_c, null_b2 + }; + const auto vector_offset = + builder.CreateVector(array, flatbuffers::uoffset_t(7)); MonsterBuilder monster_builder(builder); monster_builder.add_name(two); monster_builder.add_testarrayofstring(vector_offset); builder.Finish(monster_builder.Finish()); // Read the Monster back. - const auto *monster = flatbuffers::GetRoot<Monster>(builder.GetBufferPointer()); + const auto *monster = + flatbuffers::GetRoot<Monster>(builder.GetBufferPointer()); TEST_EQ_STR(monster->name()->c_str(), "two"); const auto *testarrayofstring = monster->testarrayofstring(); TEST_EQ(testarrayofstring->size(), flatbuffers::uoffset_t(7)); @@ -2831,7 +2839,8 @@ void CreateSharedStringTest() { TEST_EQ(a[5]->str(), (std::string(chars_c, sizeof(chars_c)))); TEST_EQ(a[6]->str(), (std::string(chars_b, sizeof(chars_b)))); - // Make sure String::operator< works, too, since it is related to StringOffsetCompare. + // Make sure String::operator< works, too, since it is related to + // StringOffsetCompare. TEST_EQ((*a[0]) < (*a[1]), true); TEST_EQ((*a[1]) < (*a[0]), false); TEST_EQ((*a[1]) < (*a[2]), false); @@ -2943,16 +2952,17 @@ void NativeTypeTest() { src_data.vectors.reserve(N); for (int i = 0; i < N; ++i) { - src_data.vectors.push_back (Native::Vector3D(10 * i + 0.1f, 10 * i + 0.2f, 10 * i + 0.3f)); + src_data.vectors.push_back( + Native::Vector3D(10 * i + 0.1f, 10 * i + 0.2f, 10 * i + 0.3f)); } flatbuffers::FlatBufferBuilder fbb; fbb.Finish(Geometry::ApplicationData::Pack(fbb, &src_data)); - auto dstDataT = Geometry::UnPackApplicationData(fbb.GetBufferPointer()); + auto dstDataT = Geometry::UnPackApplicationData(fbb.GetBufferPointer()); for (int i = 0; i < N; ++i) { - Native::Vector3D& v = dstDataT->vectors[i]; + Native::Vector3D &v = dstDataT->vectors[i]; TEST_EQ(v.x, 10 * i + 0.1f); TEST_EQ(v.y, 10 * i + 0.2f); TEST_EQ(v.z, 10 * i + 0.3f); @@ -3107,7 +3117,7 @@ int FlatBufferTests() { return 0; } -int main(int /*argc*/, const char * /*argv*/ []) { +int main(int /*argc*/, const char * /*argv*/[]) { InitTestEngine(); std::string req_locale; diff --git a/tests/test_assert.cpp b/tests/test_assert.cpp index 794ffe7d..eec77797 100644 --- a/tests/test_assert.cpp +++ b/tests/test_assert.cpp @@ -31,7 +31,7 @@ void TestEqStr(const char *expval, const char *val, const char *exp, #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && defined(_MSC_VER) && \ defined(_DEBUG) -#define FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC +# define FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC #endif void InitTestEngine(TestFailEventListener listener) { @@ -58,12 +58,12 @@ void InitTestEngine(TestFailEventListener listener) { int CloseTestEngine(bool force_report) { if (!testing_fails || force_report) { - #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC) - auto flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); - flags &= ~_CRTDBG_DELAY_FREE_MEM_DF; - flags |= _CRTDBG_LEAK_CHECK_DF; - _CrtSetDbgFlag(flags); - #endif +#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC) + auto flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); + flags &= ~_CRTDBG_DELAY_FREE_MEM_DF; + flags |= _CRTDBG_LEAK_CHECK_DF; + _CrtSetDbgFlag(flags); +#endif } return (0 != testing_fails); } diff --git a/tests/test_builder.cpp b/tests/test_builder.cpp index 8c070c11..685c643c 100644 --- a/tests/test_builder.cpp +++ b/tests/test_builder.cpp @@ -1,7 +1,7 @@ -#include "flatbuffers/stl_emulation.h" +#include "test_builder.h" +#include "flatbuffers/stl_emulation.h" #include "monster_test_generated.h" -#include "test_builder.h" using namespace MyGame::Example; @@ -13,7 +13,7 @@ const Color m2_color = Color_Green; struct OwnedAllocator : public flatbuffers::DefaultAllocator {}; class TestHeapBuilder : public flatbuffers::FlatBufferBuilder { -private: + private: // clang-format off #if !defined(FLATBUFFERS_CPP98_STL) TestHeapBuilder(const TestHeapBuilder &); @@ -21,15 +21,15 @@ private: #endif // !defined(FLATBUFFERS_CPP98_STL) // clang-format on -public: + public: TestHeapBuilder() - : flatbuffers::FlatBufferBuilder(2048, new OwnedAllocator(), true) {} + : flatbuffers::FlatBufferBuilder(2048, new OwnedAllocator(), true) {} // clang-format off #if !defined(FLATBUFFERS_CPP98_STL) // clang-format on TestHeapBuilder(TestHeapBuilder &&other) - : FlatBufferBuilder(std::move(other)) { } + : FlatBufferBuilder(std::move(other)) {} TestHeapBuilder &operator=(TestHeapBuilder &&other) { FlatBufferBuilder::operator=(std::move(other)); @@ -47,16 +47,16 @@ struct AllocatorMember { struct GrpcLikeMessageBuilder : private AllocatorMember, public flatbuffers::FlatBufferBuilder { -private: + private: GrpcLikeMessageBuilder(const GrpcLikeMessageBuilder &); GrpcLikeMessageBuilder &operator=(const GrpcLikeMessageBuilder &); -public: + public: GrpcLikeMessageBuilder() - : flatbuffers::FlatBufferBuilder(1024, &member_allocator_, false) {} + : flatbuffers::FlatBufferBuilder(1024, &member_allocator_, false) {} GrpcLikeMessageBuilder(GrpcLikeMessageBuilder &&other) - : FlatBufferBuilder(1024, &member_allocator_, false) { + : FlatBufferBuilder(1024, &member_allocator_, false) { // Default construct and swap idiom. Swap(other); } @@ -77,53 +77,63 @@ public: void Swap(GrpcLikeMessageBuilder &other) { // No need to swap member_allocator_ because it's stateless. FlatBufferBuilder::Swap(other); - // After swapping the FlatBufferBuilder, we swap back the allocator, which restores - // the original allocator back in place. This is necessary because MessageBuilder's - // allocator is its own member (SliceAllocatorMember). The allocator passed to - // FlatBufferBuilder::vector_downward must point to this member. + // After swapping the FlatBufferBuilder, we swap back the allocator, which + // restores the original allocator back in place. This is necessary because + // MessageBuilder's allocator is its own member (SliceAllocatorMember). The + // allocator passed to FlatBufferBuilder::vector_downward must point to this + // member. buf_.swap_allocator(other.buf_); } }; -flatbuffers::Offset<Monster> populate1(flatbuffers::FlatBufferBuilder &builder) { +flatbuffers::Offset<Monster> populate1( + flatbuffers::FlatBufferBuilder &builder) { auto name_offset = builder.CreateString(m1_name); return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m1_color); } -flatbuffers::Offset<Monster> populate2(flatbuffers::FlatBufferBuilder &builder) { +flatbuffers::Offset<Monster> populate2( + flatbuffers::FlatBufferBuilder &builder) { auto name_offset = builder.CreateString(m2_name); return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m2_color); } -uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size, size_t &offset) { +uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size, + size_t &offset) { return fbb.ReleaseRaw(size, offset); } void free_raw(flatbuffers::grpc::MessageBuilder &, uint8_t *) { - // release_raw_base calls FlatBufferBuilder::ReleaseRaw on the argument MessageBuilder. - // It's semantically wrong as MessageBuilder has its own ReleaseRaw member function that - // takes three arguments. In such cases though, ~MessageBuilder() invokes - // ~SliceAllocator() that takes care of deleting memory as it calls grpc_slice_unref. - // Obviously, this behavior is very surprising as the pointer returned by - // FlatBufferBuilder::ReleaseRaw is not valid as soon as MessageBuilder goes out of scope. - // This problem does not occur with FlatBufferBuilder. + // release_raw_base calls FlatBufferBuilder::ReleaseRaw on the argument + // MessageBuilder. It's semantically wrong as MessageBuilder has its own + // ReleaseRaw member function that takes three arguments. In such cases + // though, ~MessageBuilder() invokes ~SliceAllocator() that takes care of + // deleting memory as it calls grpc_slice_unref. Obviously, this behavior is + // very surprising as the pointer returned by FlatBufferBuilder::ReleaseRaw is + // not valid as soon as MessageBuilder goes out of scope. This problem does + // not occur with FlatBufferBuilder. } void free_raw(flatbuffers::FlatBufferBuilder &, uint8_t *buf) { flatbuffers::DefaultAllocator().deallocate(buf, 0); } -bool verify(const flatbuffers::DetachedBuffer &buf, const std::string &expected_name, Color color) { +bool verify(const flatbuffers::DetachedBuffer &buf, + const std::string &expected_name, Color color) { const Monster *monster = flatbuffers::GetRoot<Monster>(buf.data()); - return (monster->name()->str() == expected_name) && (monster->color() == color); + return (monster->name()->str() == expected_name) && + (monster->color() == color); } -bool verify(const uint8_t *buf, size_t offset, const std::string &expected_name, Color color) { - const Monster *monster = flatbuffers::GetRoot<Monster>(buf+offset); - return (monster->name()->str() == expected_name) && (monster->color() == color); +bool verify(const uint8_t *buf, size_t offset, const std::string &expected_name, + Color color) { + const Monster *monster = flatbuffers::GetRoot<Monster>(buf + offset); + return (monster->name()->str() == expected_name) && + (monster->color() == color); } -bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, const std::string &expected_name, Color color) { +bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, + const std::string &expected_name, Color color) { flatbuffers::DetachedBuffer buf = fbb.Release(); return verify(buf, expected_name, color); } @@ -136,13 +146,15 @@ void FlatBufferBuilderTest() { BuilderTests<GrpcLikeMessageBuilder>::all_tests(); BuilderReuseTestSelector tests[4] = { - REUSABLE_AFTER_RELEASE, - REUSABLE_AFTER_RELEASE_RAW, + REUSABLE_AFTER_RELEASE, REUSABLE_AFTER_RELEASE_RAW, REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN, REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN }; - BuilderReuseTests<FlatBufferBuilder, FlatBufferBuilder>::run_tests(TestSelector(tests, tests+4)); - BuilderReuseTests<TestHeapBuilder, TestHeapBuilder>::run_tests(TestSelector(tests, tests+4)); - BuilderReuseTests<GrpcLikeMessageBuilder, GrpcLikeMessageBuilder>::run_tests(TestSelector(tests, tests+4)); + BuilderReuseTests<FlatBufferBuilder, FlatBufferBuilder>::run_tests( + TestSelector(tests, tests + 4)); + BuilderReuseTests<TestHeapBuilder, TestHeapBuilder>::run_tests( + TestSelector(tests, tests + 4)); + BuilderReuseTests<GrpcLikeMessageBuilder, GrpcLikeMessageBuilder>::run_tests( + TestSelector(tests, tests + 4)); } diff --git a/tests/test_builder.h b/tests/test_builder.h index 1e2fa0ad..eb719a80 100644 --- a/tests/test_builder.h +++ b/tests/test_builder.h @@ -3,8 +3,9 @@ #include <set> #include <type_traits> -#include "monster_test_generated.h" + #include "flatbuffers/flatbuffers.h" +#include "monster_test_generated.h" #include "test_assert.h" using MyGame::Example::Color; @@ -14,17 +15,11 @@ namespace flatbuffers { namespace grpc { class MessageBuilder; } -} +} // namespace flatbuffers -template <class T, class U> -struct is_same { - static const bool value = false; -}; +template<class T, class U> struct is_same { static const bool value = false; }; -template <class T> -struct is_same<T, T> { - static const bool value = true; -}; +template<class T> struct is_same<T, T> { static const bool value = true; }; extern const std::string m1_name; extern const Color m1_color; @@ -34,30 +29,36 @@ extern const Color m2_color; flatbuffers::Offset<Monster> populate1(flatbuffers::FlatBufferBuilder &builder); flatbuffers::Offset<Monster> populate2(flatbuffers::FlatBufferBuilder &builder); -uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size, size_t &offset); +uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size, + size_t &offset); void free_raw(flatbuffers::grpc::MessageBuilder &mbb, uint8_t *buf); void free_raw(flatbuffers::FlatBufferBuilder &fbb, uint8_t *buf); -bool verify(const flatbuffers::DetachedBuffer &buf, const std::string &expected_name, Color color); -bool verify(const uint8_t *buf, size_t offset, const std::string &expected_name, Color color); +bool verify(const flatbuffers::DetachedBuffer &buf, + const std::string &expected_name, Color color); +bool verify(const uint8_t *buf, size_t offset, const std::string &expected_name, + Color color); -bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, const std::string &expected_name, Color color); -bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb, const std::string &expected_name, Color color); +bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, + const std::string &expected_name, Color color); +bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb, + const std::string &expected_name, Color color); // clang-format off #if !defined(FLATBUFFERS_CPP98_STL) // clang-format on // Invokes this function when testing the following Builder types // FlatBufferBuilder, TestHeapBuilder, and GrpcLikeMessageBuilder -template <class Builder> +template<class Builder> void builder_move_assign_after_releaseraw_test(Builder b1) { auto root_offset1 = populate1(b1); b1.Finish(root_offset1); size_t size, offset; - std::shared_ptr<uint8_t> raw(b1.ReleaseRaw(size, offset), [size](uint8_t *ptr) { - flatbuffers::DefaultAllocator::dealloc(ptr, size); - }); + std::shared_ptr<uint8_t> raw( + b1.ReleaseRaw(size, offset), [size](uint8_t *ptr) { + flatbuffers::DefaultAllocator::dealloc(ptr, size); + }); Builder src; auto root_offset2 = populate2(src); src.Finish(root_offset2); @@ -72,9 +73,10 @@ void builder_move_assign_after_releaseraw_test(Builder b1) { #endif // !defined(FLATBUFFERS_CPP98_STL) // clang-format on -void builder_move_assign_after_releaseraw_test(flatbuffers::grpc::MessageBuilder b1); +void builder_move_assign_after_releaseraw_test( + flatbuffers::grpc::MessageBuilder b1); -template <class DestBuilder, class SrcBuilder = DestBuilder> +template<class DestBuilder, class SrcBuilder = DestBuilder> struct BuilderTests { // clang-format off #if !defined(FLATBUFFERS_CPP98_STL) @@ -164,9 +166,10 @@ struct BuilderTests { #endif // !defined(FLATBUFFERS_CPP98_STL) // clang-format on - static void builder_swap_before_finish_test(bool run = is_same<DestBuilder, SrcBuilder>::value) { + static void builder_swap_before_finish_test( + bool run = is_same<DestBuilder, SrcBuilder>::value) { /// Swap is allowed only when lhs and rhs are the same concrete type. - if(run) { + if (run) { SrcBuilder src; auto root_offset1 = populate1(src); auto size1 = src.GetSize(); @@ -183,9 +186,10 @@ struct BuilderTests { } } - static void builder_swap_after_finish_test(bool run = is_same<DestBuilder, SrcBuilder>::value) { + static void builder_swap_after_finish_test( + bool run = is_same<DestBuilder, SrcBuilder>::value) { /// Swap is allowed only when lhs and rhs are the same concrete type. - if(run) { + if (run) { SrcBuilder src; auto root_offset1 = populate1(src); src.Finish(root_offset1); @@ -233,12 +237,9 @@ enum BuilderReuseTestSelector { typedef std::set<BuilderReuseTestSelector> TestSelector; -template <class DestBuilder, class SrcBuilder> -struct BuilderReuseTests { +template<class DestBuilder, class SrcBuilder> struct BuilderReuseTests { static void builder_reusable_after_release_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE)) { - return; - } + if (!selector.count(REUSABLE_AFTER_RELEASE)) { return; } DestBuilder fbb; std::vector<flatbuffers::DetachedBuffer> buffers; @@ -251,9 +252,7 @@ struct BuilderReuseTests { } static void builder_reusable_after_releaseraw_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) { - return; - } + if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) { return; } DestBuilder fbb; for (int i = 0; i < 5; ++i) { @@ -269,10 +268,9 @@ struct BuilderReuseTests { // clang-format off #if !defined(FLATBUFFERS_CPP98_STL) // clang-format on - static void builder_reusable_after_release_and_move_assign_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { - return; - } + static void builder_reusable_after_release_and_move_assign_test( + TestSelector selector) { + if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { return; } DestBuilder dst; std::vector<flatbuffers::DetachedBuffer> buffers; @@ -287,10 +285,9 @@ struct BuilderReuseTests { } } - static void builder_reusable_after_releaseraw_and_move_assign_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) { - return; - } + static void builder_reusable_after_releaseraw_and_move_assign_test( + TestSelector selector) { + if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) { return; } DestBuilder dst; for (int i = 0; i < 5; ++i) { @@ -323,4 +320,4 @@ struct BuilderReuseTests { } }; -#endif // TEST_BUILDER_H +#endif // TEST_BUILDER_H |