Made all C++ files clang-formatted.

Also added missing generated files.

Change-Id: Ifd22a643a08e3f2edfce92812ed57b87fc0e1875
parent 5d9930aa
...@@ -3,5 +3,11 @@ Language: Cpp ...@@ -3,5 +3,11 @@ Language: Cpp
BasedOnStyle: Google BasedOnStyle: Google
DerivePointerAlignment: false DerivePointerAlignment: false
PointerAlignment: Right PointerAlignment: Right
IndentPPDirectives: AfterHash
Cpp11BracedListStyle: false
AlwaysBreakTemplateDeclarations: false
AllowShortCaseLabelsOnASingleLine: true
SpaceAfterTemplateKeyword: false
AllowShortBlocksOnASingleLine: true
... ...
...@@ -40,8 +40,8 @@ ...@@ -40,8 +40,8 @@
#include <vector> #include <vector>
#ifndef GRPC_CUSTOM_STRING #ifndef GRPC_CUSTOM_STRING
#include <string> # include <string>
#define GRPC_CUSTOM_STRING std::string # define GRPC_CUSTOM_STRING std::string
#endif #endif
namespace grpc { namespace grpc {
......
...@@ -18,41 +18,43 @@ ...@@ -18,41 +18,43 @@
#include <grpc++/grpc++.h> #include <grpc++/grpc++.h>
#include "monster_test_generated.h"
#include "monster_test.grpc.fb.h" #include "monster_test.grpc.fb.h"
#include "monster_test_generated.h"
using namespace MyGame::Example; using namespace MyGame::Example;
// The callback implementation of our server, that derives from the generated // The callback implementation of our server, that derives from the generated
// code. It implements all rpcs specified in the FlatBuffers schema. // code. It implements all rpcs specified in the FlatBuffers schema.
class ServiceImpl final : public MyGame::Example::MonsterStorage::Service { class ServiceImpl final : public MyGame::Example::MonsterStorage::Service {
virtual ::grpc::Status Store(::grpc::ServerContext* context, virtual ::grpc::Status Store(
::grpc::ServerContext *context,
const flatbuffers::grpc::Message<Monster> *request, const flatbuffers::grpc::Message<Monster> *request,
flatbuffers::grpc::Message<Stat> *response) flatbuffers::grpc::Message<Stat> *response) override {
override {
// Create a response from the incoming request name. // Create a response from the incoming request name.
fbb_.Clear(); fbb_.Clear();
auto stat_offset = CreateStat(fbb_, fbb_.CreateString("Hello, " + auto stat_offset = CreateStat(
request->GetRoot()->name()->str())); fbb_, fbb_.CreateString("Hello, " + request->GetRoot()->name()->str()));
fbb_.Finish(stat_offset); fbb_.Finish(stat_offset);
// Transfer ownership of the message to gRPC // Transfer ownership of the message to gRPC
*response = fbb_.ReleaseMessage<Stat>(); *response = fbb_.ReleaseMessage<Stat>();
return grpc::Status::OK; return grpc::Status::OK;
} }
virtual ::grpc::Status Retrieve(::grpc::ServerContext *context, virtual ::grpc::Status Retrieve(
::grpc::ServerContext *context,
const flatbuffers::grpc::Message<Stat> *request, const flatbuffers::grpc::Message<Stat> *request,
::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* writer) ::grpc::ServerWriter<flatbuffers::grpc::Message<Monster>> *writer)
override { override {
for (int i = 0; i < 10; i++) {
for (int i=0; i<10; i++) {
fbb_.Clear(); fbb_.Clear();
// Create 10 monsters for resposne. // Create 10 monsters for resposne.
auto monster_offset = auto monster_offset =
CreateMonster(fbb_, 0, 0, 0, fbb_.CreateString( CreateMonster(fbb_, 0, 0, 0,
request->GetRoot()->id()->str() + " No." + std::to_string(i))); fbb_.CreateString(request->GetRoot()->id()->str() +
" No." + std::to_string(i)));
fbb_.Finish(monster_offset); fbb_.Finish(monster_offset);
flatbuffers::grpc::Message<Monster> monster = fbb_.ReleaseMessage<Monster>(); flatbuffers::grpc::Message<Monster> monster =
fbb_.ReleaseMessage<Monster>();
// Send monster to client using streaming. // Send monster to client using streaming.
writer->Write(monster); writer->Write(monster);
...@@ -90,7 +92,7 @@ void RunServer() { ...@@ -90,7 +92,7 @@ void RunServer() {
server_instance->Wait(); server_instance->Wait();
} }
int main(int /*argc*/, const char * /*argv*/[]) { int main(int /*argc*/, const char * /*argv*/ []) {
// Launch server. // Launch server.
std::thread server_thread(RunServer); std::thread server_thread(RunServer);
...@@ -103,7 +105,6 @@ int main(int /*argc*/, const char * /*argv*/[]) { ...@@ -103,7 +105,6 @@ int main(int /*argc*/, const char * /*argv*/[]) {
grpc::InsecureChannelCredentials()); grpc::InsecureChannelCredentials());
auto stub = MyGame::Example::MonsterStorage::NewStub(channel); auto stub = MyGame::Example::MonsterStorage::NewStub(channel);
flatbuffers::grpc::MessageBuilder fbb; flatbuffers::grpc::MessageBuilder fbb;
{ {
grpc::ClientContext context; grpc::ClientContext context;
...@@ -138,7 +139,7 @@ int main(int /*argc*/, const char * /*argv*/[]) { ...@@ -138,7 +139,7 @@ int main(int /*argc*/, const char * /*argv*/[]) {
} }
} }
#if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION #if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
{ {
// Test that an invalid request errors out correctly // Test that an invalid request errors out correctly
grpc::ClientContext context; grpc::ClientContext context;
...@@ -149,9 +150,10 @@ int main(int /*argc*/, const char * /*argv*/[]) { ...@@ -149,9 +150,10 @@ int main(int /*argc*/, const char * /*argv*/[]) {
// matches the protobuf gRPC status code for an unparseable message. // matches the protobuf gRPC status code for an unparseable message.
assert(!status.ok()); assert(!status.ok());
assert(status.error_code() == ::grpc::StatusCode::INTERNAL); assert(status.error_code() == ::grpc::StatusCode::INTERNAL);
assert(strcmp(status.error_message().c_str(), "Message verification failed") == 0); assert(strcmp(status.error_message().c_str(),
"Message verification failed") == 0);
} }
#endif #endif
server_instance->Shutdown(); server_instance->Shutdown();
......
#ifndef FLATBUFFERS_BASE_H_ #ifndef FLATBUFFERS_BASE_H_
#define FLATBUFFERS_BASE_H_ #define FLATBUFFERS_BASE_H_
// clang-format off
#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \ #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \
defined(_MSC_VER) && defined(_DEBUG) defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC #define _CRTDBG_MAP_ALLOC
......
...@@ -49,7 +49,7 @@ class CodeWriter { ...@@ -49,7 +49,7 @@ class CodeWriter {
// Associates a key with a value. All subsequent calls to operator+=, where // Associates a key with a value. All subsequent calls to operator+=, where
// the specified key is contained in {{ and }} delimiters will be replaced by // the specified key is contained in {{ and }} delimiters will be replaced by
// the given value. // the given value.
void SetValue(const std::string& key, const std::string& value) { void SetValue(const std::string &key, const std::string &value) {
value_map_[key] = value; value_map_[key] = value;
} }
...@@ -71,8 +71,7 @@ class BaseGenerator { ...@@ -71,8 +71,7 @@ class BaseGenerator {
public: public:
virtual bool generate() = 0; virtual bool generate() = 0;
static std::string NamespaceDir(const Parser &parser, static std::string NamespaceDir(const Parser &parser, const std::string &path,
const std::string &path,
const Namespace &ns); const Namespace &ns);
protected: protected:
...@@ -128,8 +127,7 @@ struct CommentConfig { ...@@ -128,8 +127,7 @@ struct CommentConfig {
}; };
extern void GenComment(const std::vector<std::string> &dc, extern void GenComment(const std::vector<std::string> &dc,
std::string *code_ptr, std::string *code_ptr, const CommentConfig *config,
const CommentConfig *config,
const char *prefix = ""); const char *prefix = "");
} // namespace flatbuffers } // namespace flatbuffers
......
This diff is collapsed.
...@@ -14,15 +14,15 @@ ...@@ -14,15 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <functional> #include <functional>
#include <limits> #include <limits>
#include <string> #include <string>
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#ifndef FLATC_H_ #ifndef FLATC_H_
#define FLATC_H_ # define FLATC_H_
namespace flatbuffers { namespace flatbuffers {
...@@ -49,12 +49,10 @@ class FlatCompiler { ...@@ -49,12 +49,10 @@ class FlatCompiler {
MakeRuleFn make_rule; MakeRuleFn make_rule;
}; };
typedef void (*WarnFn)(const FlatCompiler *flatc, typedef void (*WarnFn)(const FlatCompiler *flatc, const std::string &warn,
const std::string &warn,
bool show_exe_name); bool show_exe_name);
typedef void (*ErrorFn)(const FlatCompiler *flatc, typedef void (*ErrorFn)(const FlatCompiler *flatc, const std::string &err,
const std::string &err,
bool usage, bool show_exe_name); bool usage, bool show_exe_name);
// Parameters required to initialize the FlatCompiler. // Parameters required to initialize the FlatCompiler.
...@@ -65,21 +63,20 @@ class FlatCompiler { ...@@ -65,21 +63,20 @@ class FlatCompiler {
warn_fn(nullptr), warn_fn(nullptr),
error_fn(nullptr) {} error_fn(nullptr) {}
const Generator* generators; const Generator *generators;
size_t num_generators; size_t num_generators;
WarnFn warn_fn; WarnFn warn_fn;
ErrorFn error_fn; ErrorFn error_fn;
}; };
explicit FlatCompiler(const InitParams& params) : params_(params) {} explicit FlatCompiler(const InitParams &params) : params_(params) {}
int Compile(int argc, const char** argv); int Compile(int argc, const char **argv);
std::string GetUsageString(const char* program_name) const; std::string GetUsageString(const char *program_name) const;
private: private:
void ParseFile(flatbuffers::Parser &parser, void ParseFile(flatbuffers::Parser &parser, const std::string &filename,
const std::string &filename,
const std::string &contents, const std::string &contents,
std::vector<const char *> &include_directories) const; std::vector<const char *> &include_directories) const;
...@@ -91,7 +88,6 @@ class FlatCompiler { ...@@ -91,7 +88,6 @@ class FlatCompiler {
InitParams params_; InitParams params_;
}; };
} // namespace flatbuffers } // namespace flatbuffers
#endif // FLATC_H_ #endif // FLATC_H_
This diff is collapsed.
...@@ -30,8 +30,7 @@ namespace grpc { ...@@ -30,8 +30,7 @@ namespace grpc {
// `grpc_slice` and also provides flatbuffers-specific helpers such as `Verify` // `grpc_slice` and also provides flatbuffers-specific helpers such as `Verify`
// and `GetRoot`. Since it is backed by a `grpc_slice`, the underlying buffer // and `GetRoot`. Since it is backed by a `grpc_slice`, the underlying buffer
// is refcounted and ownership is be managed automatically. // is refcounted and ownership is be managed automatically.
template <class T> template<class T> class Message {
class Message {
public: public:
Message() : slice_(grpc_empty_slice()) {} Message() : slice_(grpc_empty_slice()) {}
...@@ -137,7 +136,7 @@ namespace detail { ...@@ -137,7 +136,7 @@ namespace detail {
struct SliceAllocatorMember { struct SliceAllocatorMember {
SliceAllocator slice_allocator_; SliceAllocator slice_allocator_;
}; };
} } // namespace detail
// MessageBuilder is a gRPC-specific FlatBufferBuilder that uses SliceAllocator // MessageBuilder is a gRPC-specific FlatBufferBuilder that uses SliceAllocator
// to allocate gRPC buffers. // to allocate gRPC buffers.
...@@ -155,8 +154,7 @@ class MessageBuilder : private detail::SliceAllocatorMember, ...@@ -155,8 +154,7 @@ class MessageBuilder : private detail::SliceAllocatorMember,
// GetMessage extracts the subslice of the buffer corresponding to the // GetMessage extracts the subslice of the buffer corresponding to the
// flatbuffers-encoded region and wraps it in a `Message<T>` to handle buffer // flatbuffers-encoded region and wraps it in a `Message<T>` to handle buffer
// ownership. // ownership.
template <class T> template<class T> Message<T> GetMessage() {
Message<T> GetMessage() {
auto buf_data = buf_.buf(); // pointer to memory auto buf_data = buf_.buf(); // pointer to memory
auto buf_size = buf_.capacity(); // size of memory auto buf_size = buf_.capacity(); // size of memory
auto msg_data = buf_.data(); // pointer to msg auto msg_data = buf_.data(); // pointer to msg
...@@ -178,8 +176,7 @@ class MessageBuilder : private detail::SliceAllocatorMember, ...@@ -178,8 +176,7 @@ class MessageBuilder : private detail::SliceAllocatorMember,
return msg; return msg;
} }
template <class T> template<class T> Message<T> ReleaseMessage() {
Message<T> ReleaseMessage() {
Message<T> msg = GetMessage<T>(); Message<T> msg = GetMessage<T>();
Reset(); Reset();
return msg; return msg;
...@@ -194,8 +191,7 @@ class MessageBuilder : private detail::SliceAllocatorMember, ...@@ -194,8 +191,7 @@ class MessageBuilder : private detail::SliceAllocatorMember,
namespace grpc { namespace grpc {
template <class T> template<class T> class SerializationTraits<flatbuffers::grpc::Message<T>> {
class SerializationTraits<flatbuffers::grpc::Message<T>> {
public: public:
static grpc::Status Serialize(const flatbuffers::grpc::Message<T> &msg, static grpc::Status Serialize(const flatbuffers::grpc::Message<T> &msg,
grpc_byte_buffer **buffer, bool *own_buffer) { grpc_byte_buffer **buffer, bool *own_buffer) {
...@@ -237,19 +233,19 @@ class SerializationTraits<flatbuffers::grpc::Message<T>> { ...@@ -237,19 +233,19 @@ class SerializationTraits<flatbuffers::grpc::Message<T>> {
*msg = flatbuffers::grpc::Message<T>(slice, false); *msg = flatbuffers::grpc::Message<T>(slice, false);
} }
grpc_byte_buffer_destroy(buffer); grpc_byte_buffer_destroy(buffer);
#if FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION #if FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
return ::grpc::Status::OK; return ::grpc::Status::OK;
#else #else
if (msg->Verify()) { if (msg->Verify()) {
return ::grpc::Status::OK; return ::grpc::Status::OK;
} else { } else {
return ::grpc::Status(::grpc::StatusCode::INTERNAL, return ::grpc::Status(::grpc::StatusCode::INTERNAL,
"Message verification failed"); "Message verification failed");
} }
#endif #endif
} }
}; };
} // namespace grpc; } // namespace grpc
#endif // FLATBUFFERS_GRPC_H_ #endif // FLATBUFFERS_GRPC_H_
...@@ -24,26 +24,22 @@ ...@@ -24,26 +24,22 @@
namespace flatbuffers { namespace flatbuffers {
template <typename T> template<typename T> struct FnvTraits {
struct FnvTraits {
static const T kFnvPrime; static const T kFnvPrime;
static const T kOffsetBasis; static const T kOffsetBasis;
}; };
template <> template<> struct FnvTraits<uint32_t> {
struct FnvTraits<uint32_t> {
static const uint32_t kFnvPrime = 0x01000193; static const uint32_t kFnvPrime = 0x01000193;
static const uint32_t kOffsetBasis = 0x811C9DC5; static const uint32_t kOffsetBasis = 0x811C9DC5;
}; };
template <> template<> struct FnvTraits<uint64_t> {
struct FnvTraits<uint64_t> {
static const uint64_t kFnvPrime = 0x00000100000001b3ULL; static const uint64_t kFnvPrime = 0x00000100000001b3ULL;
static const uint64_t kOffsetBasis = 0xcbf29ce484222645ULL; static const uint64_t kOffsetBasis = 0xcbf29ce484222645ULL;
}; };
template <typename T> template<typename T> T HashFnv1(const char *input) {
T HashFnv1(const char *input) {
T hash = FnvTraits<T>::kOffsetBasis; T hash = FnvTraits<T>::kOffsetBasis;
for (const char *c = input; *c; ++c) { for (const char *c = input; *c; ++c) {
hash *= FnvTraits<T>::kFnvPrime; hash *= FnvTraits<T>::kFnvPrime;
...@@ -52,8 +48,7 @@ T HashFnv1(const char *input) { ...@@ -52,8 +48,7 @@ T HashFnv1(const char *input) {
return hash; return hash;
} }
template <typename T> template<typename T> T HashFnv1a(const char *input) {
T HashFnv1a(const char *input) {
T hash = FnvTraits<T>::kOffsetBasis; T hash = FnvTraits<T>::kOffsetBasis;
for (const char *c = input; *c; ++c) { for (const char *c = input; *c; ++c) {
hash ^= static_cast<unsigned char>(*c); hash ^= static_cast<unsigned char>(*c);
...@@ -62,11 +57,10 @@ T HashFnv1a(const char *input) { ...@@ -62,11 +57,10 @@ T HashFnv1a(const char *input) {
return hash; return hash;
} }
template <typename T> template<typename T> struct NamedHashFunction {
struct NamedHashFunction {
const char *name; const char *name;
typedef T (*HashFunction)(const char*); typedef T (*HashFunction)(const char *);
HashFunction function; HashFunction function;
}; };
......
...@@ -18,17 +18,17 @@ ...@@ -18,17 +18,17 @@
#define FLATBUFFERS_IDL_H_ #define FLATBUFFERS_IDL_H_
#include <map> #include <map>
#include <stack>
#include <memory> #include <memory>
#include <stack>
#include "flatbuffers/base.h" #include "flatbuffers/base.h"
#include "flatbuffers/flatbuffers.h" #include "flatbuffers/flatbuffers.h"
#include "flatbuffers/flexbuffers.h"
#include "flatbuffers/hash.h" #include "flatbuffers/hash.h"
#include "flatbuffers/reflection.h" #include "flatbuffers/reflection.h"
#include "flatbuffers/flexbuffers.h"
#if !defined(FLATBUFFERS_CPP98_STL) #if !defined(FLATBUFFERS_CPP98_STL)
#include <functional> # include <functional>
#endif // !defined(FLATBUFFERS_CPP98_STL) #endif // !defined(FLATBUFFERS_CPP98_STL)
// This file defines the data types representing a parsed IDL (Interface // This file defines the data types representing a parsed IDL (Interface
...@@ -39,6 +39,7 @@ namespace flatbuffers { ...@@ -39,6 +39,7 @@ namespace flatbuffers {
// The order of these matters for Is*() functions below. // The order of these matters for Is*() functions below.
// Additionally, Parser::ParseType assumes bool..string is a contiguous range // Additionally, Parser::ParseType assumes bool..string is a contiguous range
// of type tokens. // of type tokens.
// clang-format off
#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \ #define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
TD(NONE, "", uint8_t, byte, byte, byte, uint8) \ TD(NONE, "", uint8_t, byte, byte, byte, uint8) \
TD(UTYPE, "", uint8_t, byte, byte, byte, uint8) /* begin scalar/int */ \ TD(UTYPE, "", uint8_t, byte, byte, byte, uint8) /* begin scalar/int */ \
...@@ -110,13 +111,12 @@ inline bool IsFloat (BaseType t) { return t == BASE_TYPE_FLOAT || ...@@ -110,13 +111,12 @@ inline bool IsFloat (BaseType t) { return t == BASE_TYPE_FLOAT ||
inline bool IsLong (BaseType t) { return t == BASE_TYPE_LONG || inline bool IsLong (BaseType t) { return t == BASE_TYPE_LONG ||
t == BASE_TYPE_ULONG; } t == BASE_TYPE_ULONG; }
inline bool IsBool (BaseType t) { return t == BASE_TYPE_BOOL; } inline bool IsBool (BaseType t) { return t == BASE_TYPE_BOOL; }
// clang-format on
extern const char *const kTypeNames[]; extern const char *const kTypeNames[];
extern const char kTypeSizes[]; extern const char kTypeSizes[];
inline size_t SizeOf(BaseType t) { inline size_t SizeOf(BaseType t) { return kTypeSizes[t]; }
return kTypeSizes[t];
}
struct StructDef; struct StructDef;
struct EnumDef; struct EnumDef;
...@@ -125,13 +125,12 @@ class Parser; ...@@ -125,13 +125,12 @@ class Parser;
// Represents any type in the IDL, which is a combination of the BaseType // Represents any type in the IDL, which is a combination of the BaseType
// and additional information for vectors/structs_. // and additional information for vectors/structs_.
struct Type { struct Type {
explicit Type(BaseType _base_type = BASE_TYPE_NONE, explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef *_sd = nullptr,
StructDef *_sd = nullptr, EnumDef *_ed = nullptr) EnumDef *_ed = nullptr)
: base_type(_base_type), : base_type(_base_type),
element(BASE_TYPE_NONE), element(BASE_TYPE_NONE),
struct_def(_sd), struct_def(_sd),
enum_def(_ed) enum_def(_ed) {}
{}
bool operator==(const Type &o) { bool operator==(const Type &o) {
return base_type == o.base_type && element == o.element && return base_type == o.base_type && element == o.element &&
...@@ -151,8 +150,9 @@ struct Type { ...@@ -151,8 +150,9 @@ struct Type {
// Represents a parsed scalar value, it's type, and field offset. // Represents a parsed scalar value, it's type, and field offset.
struct Value { struct Value {
Value() : constant("0"), offset(static_cast<voffset_t>( Value()
~(static_cast<voffset_t>(0U)))) {} : constant("0"),
offset(static_cast<voffset_t>(~(static_cast<voffset_t>(0U)))) {}
Type type; Type type;
std::string constant; std::string constant;
voffset_t offset; voffset_t offset;
...@@ -163,9 +163,7 @@ struct Value { ...@@ -163,9 +163,7 @@ struct Value {
template<typename T> class SymbolTable { template<typename T> class SymbolTable {
public: public:
~SymbolTable() { ~SymbolTable() {
for (auto it = vec.begin(); it != vec.end(); ++it) { for (auto it = vec.begin(); it != vec.end(); ++it) { delete *it; }
delete *it;
}
} }
bool Add(const std::string &name, T *e) { bool Add(const std::string &name, T *e) {
...@@ -201,7 +199,6 @@ template<typename T> class SymbolTable { ...@@ -201,7 +199,6 @@ template<typename T> class SymbolTable {
struct Namespace { struct Namespace {
Namespace() : from_table(0) {} Namespace() : from_table(0) {}
// Given a (potentally unqualified) name, return the "fully qualified" name // Given a (potentally unqualified) name, return the "fully qualified" name
// which has a full namespaced descriptor. // which has a full namespaced descriptor.
// With max_components you can request less than the number of components // With max_components you can request less than the number of components
...@@ -215,13 +212,16 @@ struct Namespace { ...@@ -215,13 +212,16 @@ struct Namespace {
// Base class for all definition types (fields, structs_, enums_). // Base class for all definition types (fields, structs_, enums_).
struct Definition { struct Definition {
Definition() : generated(false), defined_namespace(nullptr), Definition()
serialized_location(0), index(-1), refcount(1) {} : generated(false),
defined_namespace(nullptr),
serialized_location(0),
index(-1),
refcount(1) {}
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset< flatbuffers::Offset<
reflection::KeyValue>>> flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
SerializeAttributes(FlatBufferBuilder *builder, SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
const Parser &parser) const;
std::string name; std::string name;
std::string file; std::string file;
...@@ -237,8 +237,13 @@ struct Definition { ...@@ -237,8 +237,13 @@ struct Definition {
}; };
struct FieldDef : public Definition { struct FieldDef : public Definition {
FieldDef() : deprecated(false), required(false), key(false), FieldDef()
native_inline(false), flexbuffer(false), nested_flatbuffer(NULL), : deprecated(false),
required(false),
key(false),
native_inline(false),
flexbuffer(false),
nested_flatbuffer(NULL),
padding(0) {} padding(0) {}
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id, Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
...@@ -263,8 +268,7 @@ struct StructDef : public Definition { ...@@ -263,8 +268,7 @@ struct StructDef : public Definition {
sortbysize(true), sortbysize(true),
has_key(false), has_key(false),
minalign(1), minalign(1),
bytesize(0) bytesize(0) {}
{}
void PadLastField(size_t min_align) { void PadLastField(size_t min_align) {
auto padding = PaddingBytes(bytesize, min_align); auto padding = PaddingBytes(bytesize, min_align);
...@@ -300,8 +304,7 @@ inline size_t InlineAlignment(const Type &type) { ...@@ -300,8 +304,7 @@ inline size_t InlineAlignment(const Type &type) {
} }
struct EnumVal { struct EnumVal {
EnumVal(const std::string &_name, int64_t _val) EnumVal(const std::string &_name, int64_t _val) : name(_name), value(_val) {}
: name(_name), value(_val) {}
Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder) const; Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder) const;
...@@ -315,12 +318,10 @@ struct EnumDef : public Definition { ...@@ -315,12 +318,10 @@ struct EnumDef : public Definition {
EnumDef() : is_union(false), uses_type_aliases(false) {} EnumDef() : is_union(false), uses_type_aliases(false) {}
EnumVal *ReverseLookup(int enum_idx, bool skip_union_default = true) { EnumVal *ReverseLookup(int enum_idx, bool skip_union_default = true) {
for (auto it = vals.vec.begin() + static_cast<int>(is_union && for (auto it = vals.vec.begin() +
skip_union_default); static_cast<int>(is_union && skip_union_default);
it != vals.vec.end(); ++it) { it != vals.vec.end(); ++it) {
if ((*it)->value == enum_idx) { if ((*it)->value == enum_idx) { return *it; }
return *it;
}
} }
return nullptr; return nullptr;
} }
...@@ -338,8 +339,7 @@ inline bool EqualByName(const Type &a, const Type &b) { ...@@ -338,8 +339,7 @@ inline bool EqualByName(const Type &a, const Type &b) {
return a.base_type == b.base_type && a.element == b.element && return a.base_type == b.base_type && a.element == b.element &&
(a.struct_def == b.struct_def || (a.struct_def == b.struct_def ||
a.struct_def->name == b.struct_def->name) && a.struct_def->name == b.struct_def->name) &&
(a.enum_def == b.enum_def || (a.enum_def == b.enum_def || a.enum_def->name == b.enum_def->name);
a.enum_def->name == b.enum_def->name);
} }
struct RPCCall { struct RPCCall {
...@@ -419,7 +419,9 @@ struct IDLOptions { ...@@ -419,7 +419,9 @@ struct IDLOptions {
use_goog_js_export_format(false), use_goog_js_export_format(false),
output_default_scalars_in_json(false), output_default_scalars_in_json(false),
indent_step(2), indent_step(2),
output_enum_identifiers(true), prefixed_enums(true), scoped_enums(false), output_enum_identifiers(true),
prefixed_enums(true),
scoped_enums(false),
include_dependence_headers(true), include_dependence_headers(true),
mutable_buffer(false), mutable_buffer(false),
one_file(false), one_file(false),
...@@ -481,7 +483,10 @@ class CheckedError { ...@@ -481,7 +483,10 @@ class CheckedError {
~CheckedError() { assert(has_been_checked_); } ~CheckedError() { assert(has_been_checked_); }
bool Check() { has_been_checked_ = true; return is_error_; } bool Check() {
has_been_checked_ = true;
return is_error_;
}
private: private:
bool is_error_; bool is_error_;
...@@ -490,12 +495,14 @@ class CheckedError { ...@@ -490,12 +495,14 @@ class CheckedError {
// Additionally, in GCC we can get these errors statically, for additional // Additionally, in GCC we can get these errors statically, for additional
// assurance: // assurance:
// clang-format off
#ifdef __GNUC__ #ifdef __GNUC__
#define FLATBUFFERS_CHECKED_ERROR CheckedError \ #define FLATBUFFERS_CHECKED_ERROR CheckedError \
__attribute__((warn_unused_result)) __attribute__((warn_unused_result))
#else #else
#define FLATBUFFERS_CHECKED_ERROR CheckedError #define FLATBUFFERS_CHECKED_ERROR CheckedError
#endif #endif
// clang-format on
class Parser : public ParserState { class Parser : public ParserState {
public: public:
...@@ -581,7 +588,7 @@ class Parser : public ParserState { ...@@ -581,7 +588,7 @@ class Parser : public ParserState {
StructDef *LookupStruct(const std::string &id) const; StructDef *LookupStruct(const std::string &id) const;
private: private:
void Message(const std::string &msg); void Message(const std::string &msg);
void Warning(const std::string &msg); void Warning(const std::string &msg);
FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg); FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg);
...@@ -606,6 +613,7 @@ private: ...@@ -606,6 +613,7 @@ private:
FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field, FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
size_t parent_fieldn, size_t parent_fieldn,
const StructDef *parent_struct_def); const StructDef *parent_struct_def);
// clang-format off
#if defined(FLATBUFFERS_CPP98_STL) #if defined(FLATBUFFERS_CPP98_STL)
typedef CheckedError (*ParseTableDelimitersBody)( typedef CheckedError (*ParseTableDelimitersBody)(
const std::string &name, size_t &fieldn, const StructDef *struct_def, const std::string &name, size_t &fieldn, const StructDef *struct_def,
...@@ -615,6 +623,7 @@ private: ...@@ -615,6 +623,7 @@ private:
const StructDef*, void*)> const StructDef*, void*)>
ParseTableDelimitersBody; ParseTableDelimitersBody;
#endif // defined(FLATBUFFERS_CPP98_STL) #endif // defined(FLATBUFFERS_CPP98_STL)
// clang-format on
FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn, FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn,
const StructDef *struct_def, const StructDef *struct_def,
ParseTableDelimitersBody body, ParseTableDelimitersBody body,
...@@ -623,6 +632,7 @@ private: ...@@ -623,6 +632,7 @@ private:
std::string *value, uoffset_t *ovalue); std::string *value, uoffset_t *ovalue);
void SerializeStruct(const StructDef &struct_def, const Value &val); void SerializeStruct(const StructDef &struct_def, const Value &val);
void AddVector(bool sortbysize, int count); void AddVector(bool sortbysize, int count);
// clang-format off
#if defined(FLATBUFFERS_CPP98_STL) #if defined(FLATBUFFERS_CPP98_STL)
typedef CheckedError (*ParseVectorDelimitersBody)(size_t &count, typedef CheckedError (*ParseVectorDelimitersBody)(size_t &count,
void *state); void *state);
...@@ -630,6 +640,7 @@ private: ...@@ -630,6 +640,7 @@ private:
typedef std::function<CheckedError(size_t&, void*)> typedef std::function<CheckedError(size_t&, void*)>
ParseVectorDelimitersBody; ParseVectorDelimitersBody;
#endif // defined(FLATBUFFERS_CPP98_STL) #endif // defined(FLATBUFFERS_CPP98_STL)
// clang-format on
FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters( FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(
size_t &count, ParseVectorDelimitersBody body, void *state); size_t &count, ParseVectorDelimitersBody body, void *state);
FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue); FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue);
......
...@@ -65,8 +65,7 @@ struct IterationVisitor { ...@@ -65,8 +65,7 @@ struct IterationVisitor {
virtual void EndVector() {} virtual void EndVector() {}
virtual void Element(size_t /*i*/, ElementaryType /*type*/, virtual void Element(size_t /*i*/, ElementaryType /*type*/,
const TypeTable * /*type_table*/, const TypeTable * /*type_table*/,
const uint8_t * /*val*/) const uint8_t * /*val*/) {}
{}
virtual ~IterationVisitor() {} virtual ~IterationVisitor() {}
}; };
...@@ -75,34 +74,24 @@ inline size_t InlineSize(ElementaryType type, const TypeTable *type_table) { ...@@ -75,34 +74,24 @@ inline size_t InlineSize(ElementaryType type, const TypeTable *type_table) {
case ET_UTYPE: case ET_UTYPE:
case ET_BOOL: case ET_BOOL:
case ET_CHAR: case ET_CHAR:
case ET_UCHAR: case ET_UCHAR: return 1;
return 1;
case ET_SHORT: case ET_SHORT:
case ET_USHORT: case ET_USHORT: return 2;
return 2;
case ET_INT: case ET_INT:
case ET_UINT: case ET_UINT:
case ET_FLOAT: case ET_FLOAT:
case ET_STRING: case ET_STRING: return 4;
return 4;
case ET_LONG: case ET_LONG:
case ET_ULONG: case ET_ULONG:
case ET_DOUBLE: case ET_DOUBLE: return 8;
return 8;
case ET_SEQUENCE: case ET_SEQUENCE:
switch (type_table->st) { switch (type_table->st) {
case ST_TABLE: case ST_TABLE:
case ST_UNION: case ST_UNION: return 4;
return 4; case ST_STRUCT: return type_table->values[type_table->num_elems];
case ST_STRUCT: default: assert(false); return 1;
return type_table->values[type_table->num_elems]; }
default: default: assert(false); return 1;
assert(false);
return 1;
}
default:
assert(false);
return 1;
} }
} }
...@@ -129,10 +118,8 @@ void IterateObject(const uint8_t *obj, const TypeTable *type_table, ...@@ -129,10 +118,8 @@ void IterateObject(const uint8_t *obj, const TypeTable *type_table,
IterationVisitor *visitor); IterationVisitor *visitor);
inline void IterateValue(ElementaryType type, const uint8_t *val, inline void IterateValue(ElementaryType type, const uint8_t *val,
const TypeTable *type_table, const TypeTable *type_table, const uint8_t *prev_val,
const uint8_t *prev_val, soffset_t vector_index, IterationVisitor *visitor) {
soffset_t vector_index,
IterationVisitor *visitor) {
switch (type) { switch (type) {
case ET_UTYPE: { case ET_UTYPE: {
auto tval = *reinterpret_cast<const uint8_t *>(val); auto tval = *reinterpret_cast<const uint8_t *>(val);
...@@ -200,9 +187,7 @@ inline void IterateValue(ElementaryType type, const uint8_t *val, ...@@ -200,9 +187,7 @@ inline void IterateValue(ElementaryType type, const uint8_t *val,
val += ReadScalar<uoffset_t>(val); val += ReadScalar<uoffset_t>(val);
IterateObject(val, type_table, visitor); IterateObject(val, type_table, visitor);
break; break;
case ST_STRUCT: case ST_STRUCT: IterateObject(val, type_table, visitor); break;
IterateObject(val, type_table, visitor);
break;
case ST_UNION: { case ST_UNION: {
val += ReadScalar<uoffset_t>(val); val += ReadScalar<uoffset_t>(val);
assert(prev_val); assert(prev_val);
...@@ -211,10 +196,10 @@ inline void IterateValue(ElementaryType type, const uint8_t *val, ...@@ -211,10 +196,10 @@ inline void IterateValue(ElementaryType type, const uint8_t *val,
auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(prev_val); auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(prev_val);
union_type = type_vec->Get(static_cast<uoffset_t>(vector_index)); union_type = type_vec->Get(static_cast<uoffset_t>(vector_index));
} }
auto type_code_idx = LookupEnum(union_type, type_table->values, auto type_code_idx =
type_table->num_elems); LookupEnum(union_type, type_table->values, type_table->num_elems);
if (type_code_idx >= 0 && type_code_idx < if (type_code_idx >= 0 &&
static_cast<int32_t>(type_table->num_elems)) { type_code_idx < static_cast<int32_t>(type_table->num_elems)) {
auto type_code = type_table->type_codes[type_code_idx]; auto type_code = type_table->type_codes[type_code_idx];
switch (type_code.base_type) { switch (type_code.base_type) {
case ET_SEQUENCE: { case ET_SEQUENCE: {
...@@ -225,17 +210,14 @@ inline void IterateValue(ElementaryType type, const uint8_t *val, ...@@ -225,17 +210,14 @@ inline void IterateValue(ElementaryType type, const uint8_t *val,
case ET_STRING: case ET_STRING:
visitor->String(reinterpret_cast<const String *>(val)); visitor->String(reinterpret_cast<const String *>(val));
break; break;
default: default: visitor->Unknown(val);
visitor->Unknown(val);
} }
} else { } else {
visitor->Unknown(val); visitor->Unknown(val);
} }
break; break;
} }
case ST_ENUM: case ST_ENUM: assert(false); break;
assert(false);
break;
} }
break; break;
} }
...@@ -257,9 +239,7 @@ inline void IterateObject(const uint8_t *obj, const TypeTable *type_table, ...@@ -257,9 +239,7 @@ inline void IterateObject(const uint8_t *obj, const TypeTable *type_table,
auto is_vector = type_code.is_vector != 0; auto is_vector = type_code.is_vector != 0;
auto ref_idx = type_code.sequence_ref; auto ref_idx = type_code.sequence_ref;
const TypeTable *ref = nullptr; const TypeTable *ref = nullptr;
if (ref_idx >= 0) { if (ref_idx >= 0) { ref = type_table->type_refs[ref_idx](); }
ref = type_table->type_refs[ref_idx]();
}
auto name = type_table->names ? type_table->names[i] : nullptr; auto name = type_table->names ? type_table->names[i] : nullptr;
const uint8_t *val = nullptr; const uint8_t *val = nullptr;
if (type_table->st == ST_TABLE) { if (type_table->st == ST_TABLE) {
...@@ -310,24 +290,29 @@ struct ToStringVisitor : public IterationVisitor { ...@@ -310,24 +290,29 @@ struct ToStringVisitor : public IterationVisitor {
const char *name, const uint8_t *val) { const char *name, const uint8_t *val) {
if (!val) return; if (!val) return;
if (set_idx) s += ", "; if (set_idx) s += ", ";
if (name) { s += name; s += ": "; } if (name) {
s += name;
s += ": ";
}
} }
template<typename T> void Named(T x, const char *name) { template<typename T> void Named(T x, const char *name) {
if (name) s+= name; if (name)
else s+= NumToString(x); s += name;
else
s += NumToString(x);
} }
void UType(uint8_t x, const char *name) { Named(x, name); } void UType(uint8_t x, const char *name) { Named(x, name); }
void Bool(bool x) { s+= x ? "true" : "false"; } void Bool(bool x) { s += x ? "true" : "false"; }
void Char(int8_t x, const char *name) { Named(x, name); } void Char(int8_t x, const char *name) { Named(x, name); }
void UChar(uint8_t x, const char *name) { Named(x, name); } void UChar(uint8_t x, const char *name) { Named(x, name); }
void Short(int16_t x, const char *name) { Named(x, name); } void Short(int16_t x, const char *name) { Named(x, name); }
void UShort(uint16_t x, const char *name) { Named(x, name); } void UShort(uint16_t x, const char *name) { Named(x, name); }
void Int(int32_t x, const char *name) { Named(x, name); } void Int(int32_t x, const char *name) { Named(x, name); }
void UInt(uint32_t x, const char *name) { Named(x, name); } void UInt(uint32_t x, const char *name) { Named(x, name); }
void Long(int64_t x) { s+= NumToString(x); } void Long(int64_t x) { s += NumToString(x); }
void ULong(uint64_t x) { s+= NumToString(x); } void ULong(uint64_t x) { s += NumToString(x); }
void Float(float x) { s+= NumToString(x); } void Float(float x) { s += NumToString(x); }
void Double(double x) { s+= NumToString(x); } void Double(double x) { s += NumToString(x); }
void String(const struct String *str) { void String(const struct String *str) {
EscapeString(str->c_str(), str->size(), &s, true); EscapeString(str->c_str(), str->size(), &s, true);
} }
......
This diff is collapsed.
...@@ -37,17 +37,15 @@ class Registry { ...@@ -37,17 +37,15 @@ class Registry {
// Generate text from an arbitrary FlatBuffer by looking up its // Generate text from an arbitrary FlatBuffer by looking up its
// file_identifier in the registry. // file_identifier in the registry.
bool FlatBufferToText(const uint8_t *flatbuf, size_t len, bool FlatBufferToText(const uint8_t *flatbuf, size_t len, std::string *dest) {
std::string *dest) {
// Get the identifier out of the buffer. // Get the identifier out of the buffer.
// If the buffer is truncated, exit. // If the buffer is truncated, exit.
if (len < sizeof(uoffset_t) + if (len < sizeof(uoffset_t) + FlatBufferBuilder::kFileIdentifierLength) {
FlatBufferBuilder::kFileIdentifierLength) {
lasterror_ = "buffer truncated"; lasterror_ = "buffer truncated";
return false; return false;
} }
std::string ident(reinterpret_cast<const char *>(flatbuf) + std::string ident(
sizeof(uoffset_t), reinterpret_cast<const char *>(flatbuf) + sizeof(uoffset_t),
FlatBufferBuilder::kFileIdentifierLength); FlatBufferBuilder::kFileIdentifierLength);
// Load and parse the schema. // Load and parse the schema.
Parser parser; Parser parser;
...@@ -82,9 +80,7 @@ class Registry { ...@@ -82,9 +80,7 @@ class Registry {
// If schemas used contain include statements, call this function for every // If schemas used contain include statements, call this function for every
// directory the parser should search them for. // directory the parser should search them for.
void AddIncludeDirectory(const char *path) { void AddIncludeDirectory(const char *path) { include_paths_.push_back(path); }
include_paths_.push_back(path);
}
// Returns a human readable error if any of the above functions fail. // Returns a human readable error if any of the above functions fail.
const std::string &GetLastError() { return lasterror_; } const std::string &GetLastError() { return lasterror_; }
......
...@@ -17,6 +17,8 @@ ...@@ -17,6 +17,8 @@
#ifndef FLATBUFFERS_STL_EMULATION_H_ #ifndef FLATBUFFERS_STL_EMULATION_H_
#define FLATBUFFERS_STL_EMULATION_H_ #define FLATBUFFERS_STL_EMULATION_H_
// clang-format off
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <vector> #include <vector>
......
...@@ -17,32 +17,31 @@ ...@@ -17,32 +17,31 @@
#ifndef FLATBUFFERS_UTIL_H_ #ifndef FLATBUFFERS_UTIL_H_
#define FLATBUFFERS_UTIL_H_ #define FLATBUFFERS_UTIL_H_
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <fstream> #include <fstream>
#include <iomanip> #include <iomanip>
#include <string>
#include <sstream> #include <sstream>
#include <stdint.h> #include <string>
#include <stdlib.h>
#include <assert.h>
#ifdef _WIN32 #ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN # ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN
#endif # endif
#ifndef NOMINMAX # ifndef NOMINMAX
#define NOMINMAX # define NOMINMAX
#endif # endif
#include <windows.h> # include <direct.h>
#include <winbase.h> # include <winbase.h>
#include <direct.h> # include <windows.h>
#else #else
#include <limits.h> # include <limits.h>
#endif #endif
#include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/types.h>
#include "flatbuffers/base.h" #include "flatbuffers/base.h"
namespace flatbuffers { namespace flatbuffers {
// Convert an integer or floating point value to a string. // Convert an integer or floating point value to a string.
...@@ -61,18 +60,18 @@ template<> inline std::string NumToString<unsigned char>(unsigned char t) { ...@@ -61,18 +60,18 @@ template<> inline std::string NumToString<unsigned char>(unsigned char t) {
return NumToString(static_cast<int>(t)); return NumToString(static_cast<int>(t));
} }
#if defined(FLATBUFFERS_CPP98_STL) #if defined(FLATBUFFERS_CPP98_STL)
template <> inline std::string NumToString<long long>(long long t) { template<> inline std::string NumToString<long long>(long long t) {
char buf[21]; // (log((1 << 63) - 1) / log(10)) + 2 char buf[21]; // (log((1 << 63) - 1) / log(10)) + 2
snprintf(buf, sizeof(buf), "%lld", t); snprintf(buf, sizeof(buf), "%lld", t);
return std::string(buf); return std::string(buf);
} }
template <> inline std::string NumToString<unsigned long long>( template<>
unsigned long long t) { inline std::string NumToString<unsigned long long>(unsigned long long t) {
char buf[22]; // (log((1 << 63) - 1) / log(10)) + 1 char buf[22]; // (log((1 << 63) - 1) / log(10)) + 1
snprintf(buf, sizeof(buf), "%llu", t); snprintf(buf, sizeof(buf), "%llu", t);
return std::string(buf); return std::string(buf);
} }
#endif // defined(FLATBUFFERS_CPP98_STL) #endif // defined(FLATBUFFERS_CPP98_STL)
// Special versions for floats/doubles. // Special versions for floats/doubles.
...@@ -100,10 +99,7 @@ template<> inline std::string NumToString<float>(float t) { ...@@ -100,10 +99,7 @@ template<> inline std::string NumToString<float>(float t) {
// For example, IntToStringHex(0x23, 8) returns the string "00000023". // For example, IntToStringHex(0x23, 8) returns the string "00000023".
inline std::string IntToStringHex(int i, int xdigits) { inline std::string IntToStringHex(int i, int xdigits) {
std::stringstream ss; std::stringstream ss;
ss << std::setw(xdigits) ss << std::setw(xdigits) << std::setfill('0') << std::hex << std::uppercase
<< std::setfill('0')
<< std::hex
<< std::uppercase
<< i; << i;
return ss.str(); return ss.str();
} }
...@@ -111,21 +107,25 @@ inline std::string IntToStringHex(int i, int xdigits) { ...@@ -111,21 +107,25 @@ inline std::string IntToStringHex(int i, int xdigits) {
// Portable implementation of strtoll(). // Portable implementation of strtoll().
inline int64_t StringToInt(const char *str, char **endptr = nullptr, inline int64_t StringToInt(const char *str, char **endptr = nullptr,
int base = 10) { int base = 10) {
// clang-format off
#ifdef _MSC_VER #ifdef _MSC_VER
return _strtoi64(str, endptr, base); return _strtoi64(str, endptr, base);
#else #else
return strtoll(str, endptr, base); return strtoll(str, endptr, base);
#endif #endif
// clang-format on
} }
// Portable implementation of strtoull(). // Portable implementation of strtoull().
inline uint64_t StringToUInt(const char *str, char **endptr = nullptr, inline uint64_t StringToUInt(const char *str, char **endptr = nullptr,
int base = 10) { int base = 10) {
// clang-format off
#ifdef _MSC_VER #ifdef _MSC_VER
return _strtoui64(str, endptr, base); return _strtoui64(str, endptr, base);
#else #else
return strtoull(str, endptr, base); return strtoull(str, endptr, base);
#endif #endif
// clang-format on
} }
typedef bool (*LoadFileFunction)(const char *filename, bool binary, typedef bool (*LoadFileFunction)(const char *filename, bool binary,
...@@ -134,9 +134,8 @@ typedef bool (*FileExistsFunction)(const char *filename); ...@@ -134,9 +134,8 @@ typedef bool (*FileExistsFunction)(const char *filename);
LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function); LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function);
FileExistsFunction SetFileExistsFunction(FileExistsFunction FileExistsFunction SetFileExistsFunction(
file_exists_function); FileExistsFunction file_exists_function);
// Check if file "name" exists. // Check if file "name" exists.
bool FileExists(const char *name); bool FileExists(const char *name);
...@@ -239,16 +238,19 @@ inline std::string PosixPath(const char *path) { ...@@ -239,16 +238,19 @@ inline std::string PosixPath(const char *path) {
inline void EnsureDirExists(const std::string &filepath) { inline void EnsureDirExists(const std::string &filepath) {
auto parent = StripFileName(filepath); auto parent = StripFileName(filepath);
if (parent.length()) EnsureDirExists(parent); if (parent.length()) EnsureDirExists(parent);
// clang-format off
#ifdef _WIN32 #ifdef _WIN32
(void)_mkdir(filepath.c_str()); (void)_mkdir(filepath.c_str());
#else #else
mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP); mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
#endif #endif
// clang-format on
} }
// Obtains the absolute path from any other path. // Obtains the absolute path from any other path.
// Returns the input path if the absolute path couldn't be resolved. // Returns the input path if the absolute path couldn't be resolved.
inline std::string AbsolutePath(const std::string &filepath) { inline std::string AbsolutePath(const std::string &filepath) {
// clang-format off
#ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION #ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
return filepath; return filepath;
#else #else
...@@ -262,6 +264,7 @@ inline std::string AbsolutePath(const std::string &filepath) { ...@@ -262,6 +264,7 @@ inline std::string AbsolutePath(const std::string &filepath) {
? abs_path ? abs_path
: filepath; : filepath;
#endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION #endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
// clang-format on
} }
// To and from UTF-8 unicode conversion functions // To and from UTF-8 unicode conversion functions
...@@ -309,9 +312,7 @@ inline int FromUTF8(const char **in) { ...@@ -309,9 +312,7 @@ inline int FromUTF8(const char **in) {
if ((**in << len) & 0x80) return -1; // Bit after leading 1's must be 0. if ((**in << len) & 0x80) return -1; // Bit after leading 1's must be 0.
if (!len) return *(*in)++; if (!len) return *(*in)++;
// UTF-8 encoded values with a length are between 2 and 4 bytes. // UTF-8 encoded values with a length are between 2 and 4 bytes.
if (len < 2 || len > 4) { if (len < 2 || len > 4) { return -1; }
return -1;
}
// Grab initial bits of the code. // Grab initial bits of the code.
int ucc = *(*in)++ & ((1 << (7 - len)) - 1); int ucc = *(*in)++ & ((1 << (7 - len)) - 1);
for (int i = 0; i < len - 1; i++) { for (int i = 0; i < len - 1; i++) {
...@@ -321,28 +322,20 @@ inline int FromUTF8(const char **in) { ...@@ -321,28 +322,20 @@ inline int FromUTF8(const char **in) {
} }
// UTF-8 cannot encode values between 0xD800 and 0xDFFF (reserved for // UTF-8 cannot encode values between 0xD800 and 0xDFFF (reserved for
// UTF-16 surrogate pairs). // UTF-16 surrogate pairs).
if (ucc >= 0xD800 && ucc <= 0xDFFF) { if (ucc >= 0xD800 && ucc <= 0xDFFF) { return -1; }
return -1;
}
// UTF-8 must represent code points in their shortest possible encoding. // UTF-8 must represent code points in their shortest possible encoding.
switch (len) { switch (len) {
case 2: case 2:
// Two bytes of UTF-8 can represent code points from U+0080 to U+07FF. // Two bytes of UTF-8 can represent code points from U+0080 to U+07FF.
if (ucc < 0x0080 || ucc > 0x07FF) { if (ucc < 0x0080 || ucc > 0x07FF) { return -1; }
return -1;
}
break; break;
case 3: case 3:
// Three bytes of UTF-8 can represent code points from U+0800 to U+FFFF. // Three bytes of UTF-8 can represent code points from U+0800 to U+FFFF.
if (ucc < 0x0800 || ucc > 0xFFFF) { if (ucc < 0x0800 || ucc > 0xFFFF) { return -1; }
return -1;
}
break; break;
case 4: case 4:
// Four bytes of UTF-8 can represent code points from U+10000 to U+10FFFF. // Four bytes of UTF-8 can represent code points from U+10000 to U+10FFFF.
if (ucc < 0x10000 || ucc > 0x10FFFF) { if (ucc < 0x10000 || ucc > 0x10FFFF) { return -1; }
return -1;
}
break; break;
} }
return ucc; return ucc;
...@@ -421,7 +414,8 @@ inline bool EscapeString(const char *s, size_t length, std::string *_text, ...@@ -421,7 +414,8 @@ inline bool EscapeString(const char *s, size_t length, std::string *_text,
text += "\\u"; text += "\\u";
text += IntToStringHex(ucc, 4); text += IntToStringHex(ucc, 4);
} else if (ucc <= 0x10FFFF) { } else if (ucc <= 0x10FFFF) {
// Encode Unicode SMP values to a surrogate pair using two \u escapes. // Encode Unicode SMP values to a surrogate pair using two \u
// escapes.
uint32_t base = ucc - 0x10000; uint32_t base = ucc - 0x10000;
auto high_surrogate = (base >> 10) + 0xD800; auto high_surrogate = (base >> 10) + 0xD800;
auto low_surrogate = (base & 0x03FF) + 0xDC00; auto low_surrogate = (base & 0x03FF) + 0xDC00;
......
...@@ -20,7 +20,7 @@ using namespace MyGame::Sample; ...@@ -20,7 +20,7 @@ using namespace MyGame::Sample;
// Example how to use FlatBuffers to create and read binary buffers. // Example how to use FlatBuffers to create and read binary buffers.
int main(int /*argc*/, const char * /*argv*/[]) { int main(int /*argc*/, const char * /*argv*/ []) {
// Build up a serialized buffer algorithmically: // Build up a serialized buffer algorithmically:
flatbuffers::FlatBufferBuilder builder; flatbuffers::FlatBufferBuilder builder;
...@@ -83,8 +83,8 @@ int main(int /*argc*/, const char * /*argv*/[]) { ...@@ -83,8 +83,8 @@ int main(int /*argc*/, const char * /*argv*/[]) {
(void)inv; (void)inv;
// Get and test the `weapons` FlatBuffers's `vector`. // Get and test the `weapons` FlatBuffers's `vector`.
std::string expected_weapon_names[] = {"Sword", "Axe"}; std::string expected_weapon_names[] = { "Sword", "Axe" };
short expected_weapon_damages[] = {3, 5}; short expected_weapon_damages[] = { 3, 5 };
auto weps = monster->weapons(); auto weps = monster->weapons();
for (unsigned int i = 0; i < weps->size(); i++) { for (unsigned int i = 0; i < weps->size(); i++) {
assert(weps->Get(i)->name()->str() == expected_weapon_names[i]); assert(weps->Get(i)->name()->str() == expected_weapon_names[i]);
...@@ -95,11 +95,10 @@ int main(int /*argc*/, const char * /*argv*/[]) { ...@@ -95,11 +95,10 @@ int main(int /*argc*/, const char * /*argv*/[]) {
// Get and test the `Equipment` union (`equipped` field). // Get and test the `Equipment` union (`equipped` field).
assert(monster->equipped_type() == Equipment_Weapon); assert(monster->equipped_type() == Equipment_Weapon);
auto equipped = static_cast<const Weapon*>(monster->equipped()); auto equipped = static_cast<const Weapon *>(monster->equipped());
assert(equipped->name()->str() == "Axe"); assert(equipped->name()->str() == "Axe");
assert(equipped->damage() == 5); assert(equipped->damage() == 5);
(void)equipped; (void)equipped;
printf("The FlatBuffer was successfully created and verified!\n"); printf("The FlatBuffer was successfully created and verified!\n");
} }
...@@ -23,7 +23,7 @@ using namespace MyGame::Sample; ...@@ -23,7 +23,7 @@ using namespace MyGame::Sample;
// This is an example of parsing text straight into a buffer and then // This is an example of parsing text straight into a buffer and then
// generating flatbuffer (JSON) text from the buffer. // generating flatbuffer (JSON) text from the buffer.
int main(int /*argc*/, const char * /*argv*/[]) { int main(int /*argc*/, const char * /*argv*/ []) {
// load FlatBuffer schema (.fbs) and JSON from disk // load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile; std::string schemafile;
std::string jsonfile; std::string jsonfile;
......
clang-format -i -style=file include/flatbuffers/* src/*.cpp tests/test.cpp samples/*.cpp grpc/src/compiler/schema_interface.h grpc/tests/*.cpp
git checkout include/flatbuffers/reflection_generated.h
...@@ -20,24 +20,19 @@ ...@@ -20,24 +20,19 @@
#include "flatbuffers/util.h" #include "flatbuffers/util.h"
#if defined(_MSC_VER) #if defined(_MSC_VER)
#pragma warning(push) # pragma warning(push)
#pragma warning(disable: 4127) // C4127: conditional expression is constant # pragma warning(disable : 4127) // C4127: conditional expression is constant
#endif #endif
namespace flatbuffers { namespace flatbuffers {
void CodeWriter::operator+=(std::string text) { void CodeWriter::operator+=(std::string text) {
while (true) { while (true) {
auto begin = text.find("{{"); auto begin = text.find("{{");
if (begin == std::string::npos) { if (begin == std::string::npos) { break; }
break;
}
auto end = text.find("}}"); auto end = text.find("}}");
if (end == std::string::npos || end < begin) { if (end == std::string::npos || end < begin) { break; }
break;
}
// Write all the text before the first {{ into the stream. // Write all the text before the first {{ into the stream.
stream_.write(text.c_str(), begin); stream_.write(text.c_str(), begin);
...@@ -119,7 +114,6 @@ std::string BaseGenerator::WrapInNameSpace(const Namespace *ns, ...@@ -119,7 +114,6 @@ std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
return qualified_name + name; return qualified_name + name;
} }
std::string BaseGenerator::WrapInNameSpace(const Definition &def) const { std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
return WrapInNameSpace(def.defined_namespace, def.name); return WrapInNameSpace(def.defined_namespace, def.name);
} }
...@@ -150,12 +144,12 @@ void GenComment(const std::vector<std::string> &dc, std::string *code_ptr, ...@@ -150,12 +144,12 @@ void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
if (config != nullptr && config->first_line != nullptr) { if (config != nullptr && config->first_line != nullptr) {
code += std::string(prefix) + std::string(config->first_line) + "\n"; code += std::string(prefix) + std::string(config->first_line) + "\n";
} }
std::string line_prefix = std::string(prefix) + std::string line_prefix =
((config != nullptr && config->content_line_prefix != nullptr) ? std::string(prefix) +
config->content_line_prefix : "///"); ((config != nullptr && config->content_line_prefix != nullptr)
for (auto it = dc.begin(); ? config->content_line_prefix
it != dc.end(); : "///");
++it) { for (auto it = dc.begin(); it != dc.end(); ++it) {
code += line_prefix + *it + "\n"; code += line_prefix + *it + "\n";
} }
if (config != nullptr && config->last_line != nullptr) { if (config != nullptr && config->last_line != nullptr) {
...@@ -166,5 +160,5 @@ void GenComment(const std::vector<std::string> &dc, std::string *code_ptr, ...@@ -166,5 +160,5 @@ void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
} // namespace flatbuffers } // namespace flatbuffers
#if defined(_MSC_VER) #if defined(_MSC_VER)
#pragma warning(pop) # pragma warning(pop)
#endif #endif
This diff is collapsed.
...@@ -19,26 +19,17 @@ ...@@ -19,26 +19,17 @@
static const char *g_program_name = nullptr; static const char *g_program_name = nullptr;
static void Warn(const flatbuffers::FlatCompiler *flatc, static void Warn(const flatbuffers::FlatCompiler *flatc,
const std::string &warn, const std::string &warn, bool show_exe_name) {
bool show_exe_name) {
(void)flatc; (void)flatc;
if (show_exe_name) { if (show_exe_name) { printf("%s: ", g_program_name); }
printf("%s: ", g_program_name);
}
printf("warning: %s\n", warn.c_str()); printf("warning: %s\n", warn.c_str());
} }
static void Error(const flatbuffers::FlatCompiler *flatc, static void Error(const flatbuffers::FlatCompiler *flatc,
const std::string &err, const std::string &err, bool usage, bool show_exe_name) {
bool usage, if (show_exe_name) { printf("%s: ", g_program_name); }
bool show_exe_name) {
if (show_exe_name) {
printf("%s: ", g_program_name);
}
printf("error: %s\n", err.c_str()); printf("error: %s\n", err.c_str());
if (usage) { if (usage) { printf("%s", flatc->GetUsageString(g_program_name).c_str()); }
printf("%s", flatc->GetUsageString(g_program_name).c_str());
}
exit(1); exit(1);
} }
...@@ -46,61 +37,43 @@ int main(int argc, const char *argv[]) { ...@@ -46,61 +37,43 @@ int main(int argc, const char *argv[]) {
g_program_name = argv[0]; g_program_name = argv[0];
const flatbuffers::FlatCompiler::Generator generators[] = { const flatbuffers::FlatCompiler::Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary", false, { flatbuffers::GenerateBinary, "-b", "--binary", "binary", false, nullptr,
nullptr,
flatbuffers::IDLOptions::kBinary, flatbuffers::IDLOptions::kBinary,
"Generate wire format binaries for any data definitions", "Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule }, flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text", false, { flatbuffers::GenerateTextFile, "-t", "--json", "text", false, nullptr,
nullptr,
flatbuffers::IDLOptions::kJson, flatbuffers::IDLOptions::kJson,
"Generate text output for any data definitions", "Generate text output for any data definitions",
flatbuffers::TextMakeRule }, flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++", true, { flatbuffers::GenerateCPP, "-c", "--cpp", "C++", true,
flatbuffers::GenerateCppGRPC, flatbuffers::GenerateCppGRPC, flatbuffers::IDLOptions::kCpp,
flatbuffers::IDLOptions::kCpp, "Generate C++ headers for tables/structs", flatbuffers::CPPMakeRule },
"Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go", true, { flatbuffers::GenerateGo, "-g", "--go", "Go", true,
flatbuffers::GenerateGoGRPC, flatbuffers::GenerateGoGRPC, flatbuffers::IDLOptions::kGo,
flatbuffers::IDLOptions::kGo, "Generate Go files for tables/structs", flatbuffers::GeneralMakeRule },
"Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java", true, { flatbuffers::GenerateGeneral, "-j", "--java", "Java", true,
flatbuffers::GenerateJavaGRPC, flatbuffers::GenerateJavaGRPC, flatbuffers::IDLOptions::kJava,
flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs", "Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript", true, { flatbuffers::GenerateJS, "-s", "--js", "JavaScript", true, nullptr,
nullptr,
flatbuffers::IDLOptions::kJs, flatbuffers::IDLOptions::kJs,
"Generate JavaScript code for tables/structs", "Generate JavaScript code for tables/structs", flatbuffers::JSMakeRule },
flatbuffers::JSMakeRule }, { flatbuffers::GenerateJS, "-T", "--ts", "TypeScript", true, nullptr,
{ flatbuffers::GenerateJS, "-T", "--ts", "TypeScript", true,
nullptr,
flatbuffers::IDLOptions::kTs, flatbuffers::IDLOptions::kTs,
"Generate TypeScript code for tables/structs", "Generate TypeScript code for tables/structs", flatbuffers::JSMakeRule },
flatbuffers::JSMakeRule }, { flatbuffers::GenerateGeneral, "-n", "--csharp", "C#", true, nullptr,
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#", true,
nullptr,
flatbuffers::IDLOptions::kCSharp, flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs", "Generate C# classes for tables/structs", flatbuffers::GeneralMakeRule },
flatbuffers::GeneralMakeRule }, { flatbuffers::GeneratePython, "-p", "--python", "Python", true, nullptr,
{ flatbuffers::GeneratePython, "-p", "--python", "Python", true,
nullptr,
flatbuffers::IDLOptions::kPython, flatbuffers::IDLOptions::kPython,
"Generate Python files for tables/structs", "Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true, { flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true, nullptr,
nullptr, flatbuffers::IDLOptions::kPhp, "Generate PHP files for tables/structs",
flatbuffers::IDLOptions::kPhp,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema", true,
nullptr,
flatbuffers::IDLOptions::kJsonSchema,
"Generate Json schema",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema",
true, nullptr, flatbuffers::IDLOptions::kJsonSchema,
"Generate Json schema", flatbuffers::GeneralMakeRule },
}; };
flatbuffers::FlatCompiler::InitParams params; flatbuffers::FlatCompiler::InitParams params;
......
...@@ -14,20 +14,16 @@ ...@@ -14,20 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
#include <stdio.h>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include "flatbuffers/hash.h" #include "flatbuffers/hash.h"
#include <stdio.h>
enum OutputFormat { enum OutputFormat { kDecimal, kHexadecimal, kHexadecimal0x };
kDecimal,
kHexadecimal,
kHexadecimal0x
};
int main(int argc, char* argv[]) { int main(int argc, char *argv[]) {
const char* name = argv[0]; const char *name = argv[0];
if (argc <= 1) { if (argc <= 1) {
printf("%s HASH [OPTION]... STRING... [-- STRING...]\n", name); printf("%s HASH [OPTION]... STRING... [-- STRING...]\n", name);
printf("Available hashing algorithms:\n 32 bit:\n"); printf("Available hashing algorithms:\n 32 bit:\n");
...@@ -50,7 +46,7 @@ int main(int argc, char* argv[]) { ...@@ -50,7 +46,7 @@ int main(int argc, char* argv[]) {
return 0; return 0;
} }
const char* hash_algorithm = argv[1]; const char *hash_algorithm = argv[1];
flatbuffers::NamedHashFunction<uint32_t>::HashFunction hash_function32 = flatbuffers::NamedHashFunction<uint32_t>::HashFunction hash_function32 =
flatbuffers::FindHashFunction32(hash_algorithm); flatbuffers::FindHashFunction32(hash_algorithm);
...@@ -66,15 +62,21 @@ int main(int argc, char* argv[]) { ...@@ -66,15 +62,21 @@ int main(int argc, char* argv[]) {
bool annotate = false; bool annotate = false;
bool escape_dash = false; bool escape_dash = false;
for (int i = 2; i < argc; i++) { for (int i = 2; i < argc; i++) {
const char* arg = argv[i]; const char *arg = argv[i];
if (!escape_dash && arg[0] == '-') { if (!escape_dash && arg[0] == '-') {
std::string opt = arg; std::string opt = arg;
if (opt == "-d") output_format = kDecimal; if (opt == "-d")
else if (opt == "-x") output_format = kHexadecimal; output_format = kDecimal;
else if (opt == "-0x") output_format = kHexadecimal0x; else if (opt == "-x")
else if (opt == "-c") annotate = true; output_format = kHexadecimal;
else if (opt == "--") escape_dash = true; else if (opt == "-0x")
else printf("Unrecognized argument: \"%s\"\n", arg); output_format = kHexadecimal0x;
else if (opt == "-c")
annotate = true;
else if (opt == "--")
escape_dash = true;
else
printf("Unrecognized argument: \"%s\"\n", arg);
} else { } else {
std::stringstream ss; std::stringstream ss;
if (output_format == kDecimal) { if (output_format == kDecimal) {
...@@ -90,8 +92,7 @@ int main(int argc, char* argv[]) { ...@@ -90,8 +92,7 @@ int main(int argc, char* argv[]) {
else if (hash_function64) else if (hash_function64)
ss << hash_function64(arg); ss << hash_function64(arg);
if (annotate) if (annotate) ss << " /* \"" << arg << "\" */";
ss << " /* \"" << arg << "\" */";
ss << "\n"; ss << "\n";
...@@ -100,4 +101,3 @@ int main(int argc, char* argv[]) { ...@@ -100,4 +101,3 @@ int main(int argc, char* argv[]) {
} }
return 0; return 0;
} }
This diff is collapsed.
...@@ -16,10 +16,10 @@ ...@@ -16,10 +16,10 @@
// 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 "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h" #include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h" #include "flatbuffers/idl.h"
#include "flatbuffers/util.h" #include "flatbuffers/util.h"
#include "flatbuffers/code_generators.h"
namespace flatbuffers { namespace flatbuffers {
...@@ -28,8 +28,7 @@ static std::string GenType(const Type &type, bool underlying = false) { ...@@ -28,8 +28,7 @@ static std::string GenType(const Type &type, bool underlying = false) {
case BASE_TYPE_STRUCT: case BASE_TYPE_STRUCT:
return type.struct_def->defined_namespace->GetFullyQualifiedName( return type.struct_def->defined_namespace->GetFullyQualifiedName(
type.struct_def->name); type.struct_def->name);
case BASE_TYPE_VECTOR: case BASE_TYPE_VECTOR: return "[" + GenType(type.VectorType()) + "]";
return "[" + GenType(type.VectorType()) + "]";
default: default:
if (type.enum_def && !underlying) { if (type.enum_def && !underlying) {
return type.enum_def->defined_namespace->GetFullyQualifiedName( return type.enum_def->defined_namespace->GetFullyQualifiedName(
...@@ -69,6 +68,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) { ...@@ -69,6 +68,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
std::string schema; std::string schema;
schema += "// Generated from " + file_name + ".proto\n\n"; schema += "// Generated from " + file_name + ".proto\n\n";
if (parser.opts.include_dependence_headers) { if (parser.opts.include_dependence_headers) {
// clang-format off
#ifdef FBS_GEN_INCLUDES // TODO: currently all in one file. #ifdef FBS_GEN_INCLUDES // TODO: currently all in one file.
int num_includes = 0; int num_includes = 0;
for (auto it = parser.included_files_.begin(); for (auto it = parser.included_files_.begin();
...@@ -82,6 +82,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) { ...@@ -82,6 +82,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
} }
if (num_includes) schema += "\n"; if (num_includes) schema += "\n";
#endif #endif
// clang-format on
} }
// Generate code for all the enum declarations. // Generate code for all the enum declarations.
const Namespace *last_namespace = nullptr; const Namespace *last_namespace = nullptr;
...@@ -92,8 +93,8 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) { ...@@ -92,8 +93,8 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
GenComment(enum_def.doc_comment, &schema, nullptr); GenComment(enum_def.doc_comment, &schema, nullptr);
schema += "enum " + enum_def.name + " : "; schema += "enum " + enum_def.name + " : ";
schema += GenType(enum_def.underlying_type, true) + " {\n"; schema += GenType(enum_def.underlying_type, true) + " {\n";
for (auto it = enum_def.vals.vec.begin(); for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
it != enum_def.vals.vec.end(); ++it) { ++it) {
auto &ev = **it; auto &ev = **it;
GenComment(ev.doc_comment, &schema, nullptr, " "); GenComment(ev.doc_comment, &schema, nullptr, " ");
schema += " " + ev.name + " = " + NumToString(ev.value) + ",\n"; schema += " " + ev.name + " = " + NumToString(ev.value) + ",\n";
...@@ -101,8 +102,8 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) { ...@@ -101,8 +102,8 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
schema += "}\n\n"; schema += "}\n\n";
} }
// Generate code for all structs/tables. // Generate code for all structs/tables.
for (auto it = parser.structs_.vec.begin(); for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
it != parser.structs_.vec.end(); ++it) { ++it) {
StructDef &struct_def = **it; StructDef &struct_def = **it;
GenNameSpace(*struct_def.defined_namespace, &schema, &last_namespace); GenNameSpace(*struct_def.defined_namespace, &schema, &last_namespace);
GenComment(struct_def.doc_comment, &schema, nullptr); GenComment(struct_def.doc_comment, &schema, nullptr);
...@@ -123,12 +124,10 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) { ...@@ -123,12 +124,10 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
return schema; return schema;
} }
bool GenerateFBS(const Parser &parser, bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &path,
const std::string &file_name) { const std::string &file_name) {
return SaveFile((path + file_name + ".fbs").c_str(), return SaveFile((path + file_name + ".fbs").c_str(),
GenerateFBS(parser, file_name), false); GenerateFBS(parser, file_name), false);
} }
} // namespace flatbuffers } // namespace flatbuffers
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/* /*
* Copyright 2014 Google Inc. All rights reserved. * Copyright 2014 Google Inc. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <iostream>
#include "flatbuffers/code_generators.h" #include "flatbuffers/code_generators.h"
#include "flatbuffers/idl.h" #include "flatbuffers/idl.h"
#include "flatbuffers/util.h" #include "flatbuffers/util.h"
#include <iostream>
namespace flatbuffers { namespace flatbuffers {
...@@ -30,8 +30,7 @@ namespace jsons { ...@@ -30,8 +30,7 @@ namespace jsons {
std::string GenNativeType(BaseType type) { std::string GenNativeType(BaseType type) {
switch (type) { switch (type) {
case BASE_TYPE_BOOL: case BASE_TYPE_BOOL: return "boolean";
return "boolean";
case BASE_TYPE_CHAR: case BASE_TYPE_CHAR:
case BASE_TYPE_UCHAR: case BASE_TYPE_UCHAR:
case BASE_TYPE_SHORT: case BASE_TYPE_SHORT:
...@@ -41,16 +40,13 @@ std::string GenNativeType(BaseType type) { ...@@ -41,16 +40,13 @@ std::string GenNativeType(BaseType type) {
case BASE_TYPE_LONG: case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: case BASE_TYPE_ULONG:
case BASE_TYPE_FLOAT: case BASE_TYPE_FLOAT:
case BASE_TYPE_DOUBLE: case BASE_TYPE_DOUBLE: return "number";
return "number"; case BASE_TYPE_STRING: return "string";
case BASE_TYPE_STRING: default: return "";
return "string";
default:
return "";
} }
} }
template <class T> std::string GenFullName(const T *enum_def) { template<class T> std::string GenFullName(const T *enum_def) {
std::string full_name; std::string full_name;
const auto &name_spaces = enum_def->defined_namespace->components; const auto &name_spaces = enum_def->defined_namespace->components;
for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) { for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
...@@ -60,7 +56,7 @@ template <class T> std::string GenFullName(const T *enum_def) { ...@@ -60,7 +56,7 @@ template <class T> std::string GenFullName(const T *enum_def) {
return full_name; return full_name;
} }
template <class T> std::string GenTypeRef(const T *enum_def) { template<class T> std::string GenTypeRef(const T *enum_def) {
return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\""; return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
} }
...@@ -93,11 +89,10 @@ std::string GenType(const Type &type) { ...@@ -93,11 +89,10 @@ std::string GenType(const Type &type) {
const auto &union_types = type.enum_def->vals.vec; const auto &union_types = type.enum_def->vals.vec;
for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) { for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
auto &union_type = *ut; auto &union_type = *ut;
if (union_type->union_type.base_type == BASE_TYPE_NONE) { if (union_type->union_type.base_type == BASE_TYPE_NONE) { continue; }
continue;
}
if (union_type->union_type.base_type == BASE_TYPE_STRUCT) { if (union_type->union_type.base_type == BASE_TYPE_STRUCT) {
union_type_string.append("{ " + GenTypeRef(union_type->union_type.struct_def) + " }"); union_type_string.append(
"{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
} }
if (union_type != *type.enum_def->vals.vec.rbegin()) { if (union_type != *type.enum_def->vals.vec.rbegin()) {
union_type_string.append(","); union_type_string.append(",");
...@@ -106,10 +101,8 @@ std::string GenType(const Type &type) { ...@@ -106,10 +101,8 @@ std::string GenType(const Type &type) {
union_type_string.append("]"); union_type_string.append("]");
return union_type_string; return union_type_string;
} }
case BASE_TYPE_UTYPE: case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
return GenTypeRef(type.enum_def); default: return GenType(GenNativeType(type.base_type));
default:
return GenType(GenNativeType(type.base_type));
} }
} }
...@@ -130,35 +123,29 @@ class JsonSchemaGenerator : public BaseGenerator { ...@@ -130,35 +123,29 @@ class JsonSchemaGenerator : public BaseGenerator {
code_ += "{"; code_ += "{";
code_ += " \"$schema\": \"http://json-schema.org/draft-04/schema#\","; code_ += " \"$schema\": \"http://json-schema.org/draft-04/schema#\",";
code_ += " \"definitions\": {"; code_ += " \"definitions\": {";
for (auto e = parser_.enums_.vec.cbegin(); for (auto e = parser_.enums_.vec.cbegin(); e != parser_.enums_.vec.cend();
e != parser_.enums_.vec.cend();
++e) { ++e) {
code_ += " \"" + GenFullName(*e) + "\" : {"; code_ += " \"" + GenFullName(*e) + "\" : {";
code_ += " " + GenType("string") + ","; code_ += " " + GenType("string") + ",";
std::string enumdef(" \"enum\": ["); std::string enumdef(" \"enum\": [");
for (auto enum_value = (*e)->vals.vec.begin(); for (auto enum_value = (*e)->vals.vec.begin();
enum_value != (*e)->vals.vec.end(); enum_value != (*e)->vals.vec.end(); ++enum_value) {
++enum_value) {
enumdef.append("\"" + (*enum_value)->name + "\""); enumdef.append("\"" + (*enum_value)->name + "\"");
if (*enum_value != (*e)->vals.vec.back()) { if (*enum_value != (*e)->vals.vec.back()) { enumdef.append(", "); }
enumdef.append(", ");
}
} }
enumdef.append("]"); enumdef.append("]");
code_ += enumdef; code_ += enumdef;
code_ += " },"; // close type code_ += " },"; // close type
} }
for (auto s = parser_.structs_.vec.cbegin(); for (auto s = parser_.structs_.vec.cbegin();
s != parser_.structs_.vec.cend(); s != parser_.structs_.vec.cend(); ++s) {
++s) {
const auto &structure = *s; const auto &structure = *s;
code_ += " \"" + GenFullName(structure) + "\" : {"; code_ += " \"" + GenFullName(structure) + "\" : {";
code_ += " " + GenType("object") + ","; code_ += " " + GenType("object") + ",";
std::string comment; std::string comment;
const auto &comment_lines = structure->doc_comment; const auto &comment_lines = structure->doc_comment;
for (auto comment_line = comment_lines.cbegin(); for (auto comment_line = comment_lines.cbegin();
comment_line != comment_lines.cend(); comment_line != comment_lines.cend(); ++comment_line) {
++comment_line) {
comment.append(*comment_line); comment.append(*comment_line);
} }
if (comment.size() > 0) { if (comment.size() > 0) {
...@@ -169,10 +156,9 @@ class JsonSchemaGenerator : public BaseGenerator { ...@@ -169,10 +156,9 @@ class JsonSchemaGenerator : public BaseGenerator {
const auto &properties = structure->fields.vec; const auto &properties = structure->fields.vec;
for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) { for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
const auto &property = *prop; const auto &property = *prop;
std::string typeLine(" \"" + property->name + "\" : { " + GenType(property->value.type) + " }"); std::string typeLine(" \"" + property->name + "\" : { " +
if (property != properties.back()) { GenType(property->value.type) + " }");
typeLine.append(","); if (property != properties.back()) { typeLine.append(","); }
}
code_ += typeLine; code_ += typeLine;
} }
code_ += " },"; // close properties code_ += " },"; // close properties
...@@ -184,8 +170,7 @@ class JsonSchemaGenerator : public BaseGenerator { ...@@ -184,8 +170,7 @@ class JsonSchemaGenerator : public BaseGenerator {
if (requiredProperties.size() > 0) { if (requiredProperties.size() > 0) {
std::string required_string(" \"required\" : ["); std::string required_string(" \"required\" : [");
for (auto req_prop = requiredProperties.cbegin(); for (auto req_prop = requiredProperties.cbegin();
req_prop != requiredProperties.cend(); req_prop != requiredProperties.cend(); ++req_prop) {
++req_prop) {
required_string.append("\"" + (*req_prop)->name + "\""); required_string.append("\"" + (*req_prop)->name + "\"");
if (*req_prop != requiredProperties.back()) { if (*req_prop != requiredProperties.back()) {
required_string.append(", "); required_string.append(", ");
...@@ -196,9 +181,7 @@ class JsonSchemaGenerator : public BaseGenerator { ...@@ -196,9 +181,7 @@ class JsonSchemaGenerator : public BaseGenerator {
} }
code_ += " \"additionalProperties\" : false"; code_ += " \"additionalProperties\" : false";
std::string closeType(" }"); std::string closeType(" }");
if (*s != parser_.structs_.vec.back()) { if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
closeType.append(",");
}
code_ += closeType; // close type code_ += closeType; // close type
} }
code_ += " },"; // close definitions code_ += " },"; // close definitions
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment