Use the Google Style for clang-format without exceptions (#8706)

This reduces the friction when merging from github and google repos by
using the exact same clang style guide.

MARKDOWN=true
This commit is contained in:
Derek Bailey
2025-09-23 21:19:33 -07:00
committed by GitHub
parent 881eaab706
commit 0e047869da
84 changed files with 8178 additions and 6653 deletions
+117 -67
View File
@@ -30,18 +30,30 @@ struct OutputConfig {
static std::string ToString(const BinarySectionType type) {
switch (type) {
case BinarySectionType::Header: return "header";
case BinarySectionType::Table: return "table";
case BinarySectionType::RootTable: return "root_table";
case BinarySectionType::VTable: return "vtable";
case BinarySectionType::Struct: return "struct";
case BinarySectionType::String: return "string";
case BinarySectionType::Vector: return "vector";
case BinarySectionType::Vector64: return "vector64";
case BinarySectionType::Unknown: return "unknown";
case BinarySectionType::Union: return "union";
case BinarySectionType::Padding: return "padding";
default: return "todo";
case BinarySectionType::Header:
return "header";
case BinarySectionType::Table:
return "table";
case BinarySectionType::RootTable:
return "root_table";
case BinarySectionType::VTable:
return "vtable";
case BinarySectionType::Struct:
return "struct";
case BinarySectionType::String:
return "string";
case BinarySectionType::Vector:
return "vector";
case BinarySectionType::Vector64:
return "vector64";
case BinarySectionType::Unknown:
return "unknown";
case BinarySectionType::Union:
return "union";
case BinarySectionType::Padding:
return "padding";
default:
return "todo";
}
}
@@ -51,7 +63,8 @@ static bool IsOffset(const BinaryRegionType type) {
type == BinaryRegionType::UOffset64;
}
template<typename T> std::string ToString(T value) {
template <typename T>
std::string ToString(T value) {
if (std::is_floating_point<T>::value) {
std::stringstream ss;
ss << value;
@@ -61,8 +74,8 @@ template<typename T> std::string ToString(T value) {
}
}
template<typename T>
std::string ToValueString(const BinaryRegion &region, const uint8_t *binary) {
template <typename T>
std::string ToValueString(const BinaryRegion& region, const uint8_t* binary) {
std::string s;
s += "0x";
const T val = ReadScalar<T>(binary + region.offset);
@@ -76,16 +89,16 @@ std::string ToValueString(const BinaryRegion &region, const uint8_t *binary) {
return s;
}
template<>
std::string ToValueString<std::string>(const BinaryRegion &region,
const uint8_t *binary) {
return std::string(reinterpret_cast<const char *>(binary + region.offset),
template <>
std::string ToValueString<std::string>(const BinaryRegion& region,
const uint8_t* binary) {
return std::string(reinterpret_cast<const char*>(binary + region.offset),
static_cast<size_t>(region.array_length));
}
static std::string ToValueString(const BinaryRegion &region,
const uint8_t *binary,
const OutputConfig &output_config) {
static std::string ToValueString(const BinaryRegion& region,
const uint8_t* binary,
const OutputConfig& output_config) {
std::string s;
if (region.array_length) {
@@ -106,21 +119,31 @@ static std::string ToValueString(const BinaryRegion &region,
switch (region.type) {
case BinaryRegionType::Uint32:
return ToValueString<uint32_t>(region, binary);
case BinaryRegionType::Int32: return ToValueString<int32_t>(region, binary);
case BinaryRegionType::Int32:
return ToValueString<int32_t>(region, binary);
case BinaryRegionType::Uint16:
return ToValueString<uint16_t>(region, binary);
case BinaryRegionType::Int16: return ToValueString<int16_t>(region, binary);
case BinaryRegionType::Bool: return ToValueString<bool>(region, binary);
case BinaryRegionType::Uint8: return ToValueString<uint8_t>(region, binary);
case BinaryRegionType::Char: return ToValueString<char>(region, binary);
case BinaryRegionType::Int16:
return ToValueString<int16_t>(region, binary);
case BinaryRegionType::Bool:
return ToValueString<bool>(region, binary);
case BinaryRegionType::Uint8:
return ToValueString<uint8_t>(region, binary);
case BinaryRegionType::Char:
return ToValueString<char>(region, binary);
case BinaryRegionType::Byte:
case BinaryRegionType::Int8: return ToValueString<int8_t>(region, binary);
case BinaryRegionType::Int64: return ToValueString<int64_t>(region, binary);
case BinaryRegionType::Int8:
return ToValueString<int8_t>(region, binary);
case BinaryRegionType::Int64:
return ToValueString<int64_t>(region, binary);
case BinaryRegionType::Uint64:
return ToValueString<uint64_t>(region, binary);
case BinaryRegionType::Double: return ToValueString<double>(region, binary);
case BinaryRegionType::Float: return ToValueString<float>(region, binary);
case BinaryRegionType::UType: return ToValueString<uint8_t>(region, binary);
case BinaryRegionType::Double:
return ToValueString<double>(region, binary);
case BinaryRegionType::Float:
return ToValueString<float>(region, binary);
case BinaryRegionType::UType:
return ToValueString<uint8_t>(region, binary);
// Handle Offsets separately, incase they add additional details.
case BinaryRegionType::UOffset64:
@@ -136,7 +159,8 @@ static std::string ToValueString(const BinaryRegion &region,
s += ToValueString<uint16_t>(region, binary);
break;
default: break;
default:
break;
}
// If this is an offset type, include the calculated offset location in the
// value.
@@ -156,26 +180,36 @@ struct DocContinuation {
std::string value;
};
static std::string GenerateTypeString(const BinaryRegion &region) {
static std::string GenerateTypeString(const BinaryRegion& region) {
return ToString(region.type) +
((region.array_length)
? "[" + std::to_string(region.array_length) + "]"
: "");
}
static std::string GenerateComment(const BinaryRegionComment &comment,
const BinarySection &) {
static std::string GenerateComment(const BinaryRegionComment& comment,
const BinarySection&) {
std::string s;
switch (comment.type) {
case BinaryRegionCommentType::Unknown: s = "unknown"; break;
case BinaryRegionCommentType::SizePrefix: s = "size prefix"; break;
case BinaryRegionCommentType::Unknown:
s = "unknown";
break;
case BinaryRegionCommentType::SizePrefix:
s = "size prefix";
break;
case BinaryRegionCommentType::RootTableOffset:
s = "offset to root table `" + comment.name + "`";
break;
// TODO(dbaileychess): make this lowercase to follow the convention.
case BinaryRegionCommentType::FileIdentifier: s = "File Identifier"; break;
case BinaryRegionCommentType::Padding: s = "padding"; break;
case BinaryRegionCommentType::VTableSize: s = "size of this vtable"; break;
case BinaryRegionCommentType::FileIdentifier:
s = "File Identifier";
break;
case BinaryRegionCommentType::Padding:
s = "padding";
break;
case BinaryRegionCommentType::VTableSize:
s = "size of this vtable";
break;
case BinaryRegionCommentType::VTableRefferingTableLength:
s = "size of referring table";
break;
@@ -192,7 +226,9 @@ static std::string GenerateComment(const BinaryRegionComment &comment,
case BinaryRegionCommentType::TableField:
s = "table field `" + comment.name;
break;
case BinaryRegionCommentType::TableUnknownField: s = "unknown field"; break;
case BinaryRegionCommentType::TableUnknownField:
s = "unknown field";
break;
case BinaryRegionCommentType::TableOffsetField:
s = "offset to field `" + comment.name + "`";
break;
@@ -203,8 +239,12 @@ static std::string GenerateComment(const BinaryRegionComment &comment,
s = "array field `" + comment.name + "`[" +
std::to_string(comment.index) + "]";
break;
case BinaryRegionCommentType::StringLength: s = "length of string"; break;
case BinaryRegionCommentType::StringValue: s = "string literal"; break;
case BinaryRegionCommentType::StringLength:
s = "length of string";
break;
case BinaryRegionCommentType::StringValue:
s = "string literal";
break;
case BinaryRegionCommentType::StringTerminator:
s = "string terminator";
break;
@@ -224,13 +264,19 @@ static std::string GenerateComment(const BinaryRegionComment &comment,
s = "offset to union[" + std::to_string(comment.index) + "]";
break;
default: break;
default:
break;
}
if (!comment.default_value.empty()) {
s += " " + comment.default_value;
}
if (!comment.default_value.empty()) { s += " " + comment.default_value; }
switch (comment.status) {
case BinaryRegionStatus::OK: break; // no-op
case BinaryRegionStatus::WARN: s = "WARN: " + s; break;
case BinaryRegionStatus::OK:
break; // no-op
case BinaryRegionStatus::WARN:
s = "WARN: " + s;
break;
case BinaryRegionStatus::WARN_NO_REFERENCES:
s = "WARN: nothing refers to this section.";
break;
@@ -240,7 +286,9 @@ static std::string GenerateComment(const BinaryRegionComment &comment,
case BinaryRegionStatus::WARN_PADDING_LENGTH:
s = "WARN: padding is longer than expected.";
break;
case BinaryRegionStatus::ERROR: s = "ERROR: " + s; break;
case BinaryRegionStatus::ERROR:
s = "ERROR: " + s;
break;
case BinaryRegionStatus::ERROR_OFFSET_OUT_OF_BINARY:
s = "ERROR: " + s + ". Invalid offset, points outside the binary.";
break;
@@ -268,11 +316,11 @@ static std::string GenerateComment(const BinaryRegionComment &comment,
return s;
}
static void GenerateDocumentation(std::ostream &os, const BinaryRegion &region,
const BinarySection &section,
const uint8_t *binary,
DocContinuation &continuation,
const OutputConfig &output_config) {
static void GenerateDocumentation(std::ostream& os, const BinaryRegion& region,
const BinarySection& section,
const uint8_t* binary,
DocContinuation& continuation,
const OutputConfig& output_config) {
// Check if there is a doc continuation that should be prioritized.
if (continuation.value_start_column) {
os << std::string(continuation.value_start_column - 2, ' ');
@@ -321,9 +369,9 @@ static void GenerateDocumentation(std::ostream &os, const BinaryRegion &region,
os << GenerateComment(region.comment, section);
}
static void GenerateRegion(std::ostream &os, const BinaryRegion &region,
const BinarySection &section, const uint8_t *binary,
const OutputConfig &output_config) {
static void GenerateRegion(std::ostream& os, const BinaryRegion& region,
const BinarySection& section, const uint8_t* binary,
const OutputConfig& output_config) {
bool doc_generated = false;
DocContinuation doc_continuation;
for (uint64_t i = 0; i < region.length; ++i) {
@@ -364,12 +412,14 @@ static void GenerateRegion(std::ostream &os, const BinaryRegion &region,
}
}
static void GenerateSection(std::ostream &os, const BinarySection &section,
const uint8_t *binary,
const OutputConfig &output_config) {
static void GenerateSection(std::ostream& os, const BinarySection& section,
const uint8_t* binary,
const OutputConfig& output_config) {
os << std::endl;
os << ToString(section.type);
if (!section.name.empty()) { os << " (" + section.name + ")"; }
if (!section.name.empty()) {
os << " (" + section.name + ")";
}
os << ":";
// As a space saving measure, skip generating every vector element, just put
@@ -394,7 +444,7 @@ static void GenerateSection(std::ostream &os, const BinarySection &section,
return;
}
for (const BinaryRegion &region : section.regions) {
for (const BinaryRegion& region : section.regions) {
GenerateRegion(os, region, section, binary, output_config);
}
os << std::endl;
@@ -402,8 +452,8 @@ static void GenerateSection(std::ostream &os, const BinarySection &section,
} // namespace
bool AnnotatedBinaryTextGenerator::Generate(
const std::string &filename, const std::string &schema_filename,
const std::string &output_filename) {
const std::string& filename, const std::string& schema_filename,
const std::string& output_filename) {
OutputConfig output_config;
output_config.max_bytes_per_line = options_.max_bytes_per_line;
output_config.include_vector_contents = options_.include_vector_contents;
@@ -419,8 +469,8 @@ bool AnnotatedBinaryTextGenerator::Generate(
// Find the largest type string of all the regions in this file, so we can
// align the output nicely.
output_config.largest_type_string = 0;
for (const auto &section : annotations_) {
for (const auto &region : section.second.regions) {
for (const auto& section : annotations_) {
for (const auto& region : section.second.regions) {
std::string s = GenerateTypeString(region);
if (s.size() > output_config.largest_type_string) {
output_config.largest_type_string = s.size();
@@ -456,7 +506,7 @@ bool AnnotatedBinaryTextGenerator::Generate(
ofs << "// Binary file: " << filename << std::endl;
// Generate each of the binary sections
for (const auto &section : annotations_) {
for (const auto& section : annotations_) {
GenerateSection(ofs, section.second, binary_, output_config);
}
+143 -103
View File
@@ -39,38 +39,38 @@ namespace {
namespace r = ::reflection;
std::set<std::string> LuaKeywords() {
return { "and", "break", "do", "else", "elseif", "end",
"false", "for", "function", "goto", "if", "in",
"local", "nil", "not", "or", "repeat", "return",
"then", "true", "until", "while" };
return {"and", "break", "do", "else", "elseif", "end",
"false", "for", "function", "goto", "if", "in",
"local", "nil", "not", "or", "repeat", "return",
"then", "true", "until", "while"};
}
Namer::Config LuaDefaultConfig() {
return { /*types=*/Case::kUpperCamel,
/*constants=*/Case::kUnknown,
/*methods=*/Case::kUpperCamel,
/*functions=*/Case::kUpperCamel,
/*fields=*/Case::kUpperCamel,
/*variables=*/Case::kLowerCamel,
/*variants=*/Case::kKeep,
/*enum_variant_seperator=*/"",
/*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
/*namespaces=*/Case::kKeep,
/*namespace_seperator=*/"__",
/*object_prefix=*/"",
/*object_suffix=*/"",
/*keyword_prefix=*/"",
/*keyword_suffix=*/"_",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"",
/*filename_extension=*/".lua" };
return {/*types=*/Case::kUpperCamel,
/*constants=*/Case::kUnknown,
/*methods=*/Case::kUpperCamel,
/*functions=*/Case::kUpperCamel,
/*fields=*/Case::kUpperCamel,
/*variables=*/Case::kLowerCamel,
/*variants=*/Case::kKeep,
/*enum_variant_seperator=*/"",
/*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
/*namespaces=*/Case::kKeep,
/*namespace_seperator=*/"__",
/*object_prefix=*/"",
/*object_suffix=*/"",
/*keyword_prefix=*/"",
/*keyword_suffix=*/"_",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"",
/*filename_extension=*/".lua"};
}
class LuaBfbsGenerator : public BaseBfbsGenerator {
public:
explicit LuaBfbsGenerator(const std::string &flatc_version)
explicit LuaBfbsGenerator(const std::string& flatc_version)
: BaseBfbsGenerator(),
keywords_(),
requires_(),
@@ -79,11 +79,13 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version),
namer_(LuaDefaultConfig(), LuaKeywords()) {}
Status GenerateFromSchema(const r::Schema *schema,
const CodeGenOptions &options)
Status GenerateFromSchema(const r::Schema* schema,
const CodeGenOptions& options)
FLATBUFFERS_OVERRIDE {
options_ = options;
if (!GenerateEnums(schema->enums())) { return ERROR; }
if (!GenerateEnums(schema->enums())) {
return ERROR;
}
if (!GenerateObjects(schema->objects(), schema->root_table())) {
return ERROR;
}
@@ -92,14 +94,14 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
using BaseBfbsGenerator::GenerateCode;
Status GenerateCode(const Parser &, const std::string &,
const std::string &) override {
Status GenerateCode(const Parser&, const std::string&,
const std::string&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -107,16 +109,16 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
@@ -138,8 +140,8 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
protected:
bool GenerateEnums(
const flatbuffers::Vector<flatbuffers::Offset<r::Enum>> *enums) {
ForAllEnums(enums, [&](const r::Enum *enum_def) {
const flatbuffers::Vector<flatbuffers::Offset<r::Enum>>* enums) {
ForAllEnums(enums, [&](const r::Enum* enum_def) {
std::string code;
StartCodeBlock(enum_def);
@@ -151,7 +153,7 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
GenerateDocumentation(enum_def->documentation(), "", code);
code += "local " + enum_name + " = {\n";
ForAllEnumValues(enum_def, [&](const reflection::EnumVal *enum_val) {
ForAllEnumValues(enum_def, [&](const reflection::EnumVal* enum_val) {
GenerateDocumentation(enum_val->documentation(), " ", code);
code += " " + namer_.Variant(enum_val->name()->str()) + " = " +
NumToString(enum_val->value()) + ",\n";
@@ -165,9 +167,9 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
}
bool GenerateObjects(
const flatbuffers::Vector<flatbuffers::Offset<r::Object>> *objects,
const r::Object *root_object) {
ForAllObjects(objects, [&](const r::Object *object) {
const flatbuffers::Vector<flatbuffers::Offset<r::Object>>* objects,
const r::Object* root_object) {
ForAllObjects(objects, [&](const r::Object* object) {
std::string code;
StartCodeBlock(object);
@@ -215,9 +217,11 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
code += "\n";
// Create all the field accessors.
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
// Skip writing deprecated fields altogether.
if (field->deprecated()) { return; }
if (field->deprecated()) {
return;
}
const std::string field_name = namer_.Field(*field);
const r::BaseType base_type = field->type()->base_type();
@@ -247,7 +251,9 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
std::string getter =
GenerateGetter(field->type()) + "self.view.pos + o)";
if (IsBool(base_type)) { getter = "(" + getter + " ~=0)"; }
if (IsBool(base_type)) {
getter = "(" + getter + " ~=0)";
}
code += " return " + getter + "\n";
code += " end\n";
code += " return " + DefaultValue(field) + "\n";
@@ -280,7 +286,7 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
code += " " + offset_prefix;
code += " " + offset_prefix_2;
const r::Object *field_object = GetObject(field->type());
const r::Object* field_object = GetObject(field->type());
if (!field_object) {
// TODO(derekbailey): this is an error condition. we
// should report it better.
@@ -333,7 +339,7 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
} else {
// Vector of structs are inline, so we need to query the
// size of the struct.
const reflection::Object *obj =
const reflection::Object* obj =
GetObjectByIndex(field->type()->index());
element_size = obj->bytesize();
}
@@ -408,8 +414,10 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
code += "end\n";
code += "\n";
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
if (field->deprecated()) { return; }
ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
if (field->deprecated()) {
return;
}
const std::string field_name = namer_.Field(*field);
const std::string variable_name = namer_.Variable(*field);
@@ -455,21 +463,21 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
private:
void GenerateDocumentation(
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
*documentation,
std::string indent, std::string &code) const {
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>*
documentation,
std::string indent, std::string& code) const {
flatbuffers::ForAllDocumentation(
documentation, [&](const flatbuffers::String *str) {
documentation, [&](const flatbuffers::String* str) {
code += indent + "--" + str->str() + "\n";
});
}
std::string GenerateStructBuilderArgs(const r::Object *object,
std::string GenerateStructBuilderArgs(const r::Object* object,
std::string prefix = "") const {
std::string signature;
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
if (IsStructOrTable(field->type()->base_type())) {
const r::Object *field_object = GetObject(field->type());
const r::Object* field_object = GetObject(field->type());
signature += GenerateStructBuilderArgs(
field_object, prefix + namer_.Variable(*field) + "_");
} else {
@@ -479,7 +487,7 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
return signature;
}
std::string AppendStructBuilderBody(const r::Object *object,
std::string AppendStructBuilderBody(const r::Object* object,
std::string prefix = "") const {
std::string code;
code += " builder:Prep(" + NumToString(object->minalign()) + ", " +
@@ -487,13 +495,13 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
// We need to reverse the order we iterate over, since we build the
// buffer backwards.
ForAllFields(object, /*reverse=*/true, [&](const r::Field *field) {
ForAllFields(object, /*reverse=*/true, [&](const r::Field* field) {
const int32_t num_padding_bytes = field->padding();
if (num_padding_bytes) {
code += " builder:Pad(" + NumToString(num_padding_bytes) + ")\n";
}
if (IsStructOrTable(field->type()->base_type())) {
const r::Object *field_object = GetObject(field->type());
const r::Object* field_object = GetObject(field->type());
code += AppendStructBuilderBody(field_object,
prefix + namer_.Variable(*field) + "_");
} else {
@@ -505,36 +513,49 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
return code;
}
std::string GenerateMethod(const r::Field *field) const {
std::string GenerateMethod(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsScalar(base_type)) { return namer_.Type(GenerateType(base_type)); }
if (IsStructOrTable(base_type)) { return "Struct"; }
if (IsScalar(base_type)) {
return namer_.Type(GenerateType(base_type));
}
if (IsStructOrTable(base_type)) {
return "Struct";
}
return "UOffsetTRelative";
}
std::string GenerateGetter(const r::Type *type,
std::string GenerateGetter(const r::Type* type,
bool element_type = false) const {
switch (element_type ? type->element() : type->base_type()) {
case r::String: return "self.view:String(";
case r::Union: return "self.view:Union(";
case r::Vector: return GenerateGetter(type, true);
case r::String:
return "self.view:String(";
case r::Union:
return "self.view:Union(";
case r::Vector:
return GenerateGetter(type, true);
default:
return "self.view:Get(flatbuffers.N." +
namer_.Type(GenerateType(type, element_type)) + ", ";
}
}
std::string GenerateType(const r::Type *type,
std::string GenerateType(const r::Type* type,
bool element_type = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
if (IsScalar(base_type)) { return GenerateType(base_type); }
if (IsScalar(base_type)) {
return GenerateType(base_type);
}
switch (base_type) {
case r::String: return "string";
case r::Vector: return GenerateGetter(type, true);
case r::Obj: return namer_.Type(namer_.Denamespace(GetObject(type)));
case r::String:
return "string";
case r::Vector:
return GenerateGetter(type, true);
case r::Obj:
return namer_.Type(namer_.Denamespace(GetObject(type)));
default: return "*flatbuffers.Table";
default:
return "*flatbuffers.Table";
}
}
@@ -542,23 +563,36 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
// Need to override the default naming to match the Lua runtime libraries.
// TODO(derekbailey): make overloads in the runtime libraries to avoid this.
switch (base_type) {
case r::None: return "uint8";
case r::UType: return "uint8";
case r::Byte: return "int8";
case r::UByte: return "uint8";
case r::Short: return "int16";
case r::UShort: return "uint16";
case r::Int: return "int32";
case r::UInt: return "uint32";
case r::Long: return "int64";
case r::ULong: return "uint64";
case r::Float: return "Float32";
case r::Double: return "Float64";
default: return r::EnumNameBaseType(base_type);
case r::None:
return "uint8";
case r::UType:
return "uint8";
case r::Byte:
return "int8";
case r::UByte:
return "uint8";
case r::Short:
return "int16";
case r::UShort:
return "uint16";
case r::Int:
return "int32";
case r::UInt:
return "uint32";
case r::Long:
return "int64";
case r::ULong:
return "uint64";
case r::Float:
return "Float32";
case r::Double:
return "Float64";
default:
return r::EnumNameBaseType(base_type);
}
}
std::string DefaultValue(const r::Field *field) const {
std::string DefaultValue(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsFloatingPoint(base_type)) {
return NumToString(field->default_real());
@@ -566,24 +600,26 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
if (IsBool(base_type)) {
return field->default_integer() ? "true" : "false";
}
if (IsScalar(base_type)) { return NumToString((field->default_integer())); }
if (IsScalar(base_type)) {
return NumToString((field->default_integer()));
}
// represents offsets
return "0";
}
void StartCodeBlock(const reflection::Enum *enum_def) {
void StartCodeBlock(const reflection::Enum* enum_def) {
current_enum_ = enum_def;
current_obj_ = nullptr;
requires_.clear();
}
void StartCodeBlock(const reflection::Object *object) {
void StartCodeBlock(const reflection::Object* object) {
current_obj_ = object;
current_enum_ = nullptr;
requires_.clear();
}
std::string RegisterRequires(const r::Field *field,
std::string RegisterRequires(const r::Field* field,
bool use_element = false) {
std::string type_name;
@@ -591,12 +627,16 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
use_element ? field->type()->element() : field->type()->base_type();
if (IsStructOrTable(type)) {
const r::Object *object = GetObjectByIndex(field->type()->index());
if (object == current_obj_) { return namer_.Denamespace(object); }
const r::Object* object = GetObjectByIndex(field->type()->index());
if (object == current_obj_) {
return namer_.Denamespace(object);
}
type_name = object->name()->str();
} else {
const r::Enum *enum_def = GetEnumByIndex(field->type()->index());
if (enum_def == current_enum_) { return namer_.Denamespace(enum_def); }
const r::Enum* enum_def = GetEnumByIndex(field->type()->index());
if (enum_def == current_enum_) {
return namer_.Denamespace(enum_def);
}
type_name = enum_def->name()->str();
}
@@ -609,15 +649,15 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
return RegisterRequires(name, type_name);
}
std::string RegisterRequires(const std::string &local_name,
const std::string &requires_name) {
std::string RegisterRequires(const std::string& local_name,
const std::string& requires_name) {
requires_[local_name] = requires_name;
return local_name;
}
void EmitCodeBlock(const std::string &code_block, const std::string &name,
const std::string &ns,
const std::string &declaring_file) const {
void EmitCodeBlock(const std::string& code_block, const std::string& name,
const std::string& ns,
const std::string& declaring_file) const {
const std::string root_type = schema_->root_table()->name()->str();
const std::string root_file =
schema_->root_table()->declaration_file()->str();
@@ -665,15 +705,15 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
std::map<std::string, std::string> requires_;
CodeGenOptions options_;
const r::Object *current_obj_;
const r::Enum *current_enum_;
const r::Object* current_obj_;
const r::Enum* current_enum_;
const std::string flatc_version_;
const BfbsNamer namer_;
};
} // namespace
std::unique_ptr<CodeGenerator> NewLuaBfbsGenerator(
const std::string &flatc_version) {
const std::string& flatc_version) {
return std::unique_ptr<LuaBfbsGenerator>(new LuaBfbsGenerator(flatc_version));
}
+165 -123
View File
@@ -40,53 +40,52 @@ namespace r = ::reflection;
std::set<std::string> NimKeywords() {
return {
"addr", "and", "as", "asm", "bind", "block",
"break", "case", "cast", "concept", "const", "continue",
"converter", "defer", "discard", "distinct", "div", "do",
"elif", "else", "end", "enum", "except", "export",
"finally", "for", "from", "func", "if", "import",
"in", "include", "interface", "is", "isnot", "iterator",
"let", "macro", "method", "mixin", "mod", "nil",
"not", "notin", "object", "of", "or", "out",
"proc", "ptr", "raise", "ref", "return", "shl",
"shr", "static", "template", "try", "tuple", "type",
"using", "var", "when", "while", "xor", "yield",
"addr", "and", "as", "asm", "bind", "block",
"break", "case", "cast", "concept", "const", "continue",
"converter", "defer", "discard", "distinct", "div", "do",
"elif", "else", "end", "enum", "except", "export",
"finally", "for", "from", "func", "if", "import",
"in", "include", "interface", "is", "isnot", "iterator",
"let", "macro", "method", "mixin", "mod", "nil",
"not", "notin", "object", "of", "or", "out",
"proc", "ptr", "raise", "ref", "return", "shl",
"shr", "static", "template", "try", "tuple", "type",
"using", "var", "when", "while", "xor", "yield",
};
}
Namer::Config NimDefaultConfig() {
return { /*types=*/Case::kUpperCamel,
/*constants=*/Case::kUpperCamel,
/*methods=*/Case::kLowerCamel,
/*functions=*/Case::kUpperCamel,
/*fields=*/Case::kLowerCamel,
/*variable=*/Case::kLowerCamel,
/*variants=*/Case::kUpperCamel,
/*enum_variant_seperator=*/".",
/*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
/*namespaces=*/Case::kKeep,
/*namespace_seperator=*/"/",
/*object_prefix=*/"",
/*object_suffix=*/"T",
/*keyword_prefix=*/"",
/*keyword_suffix=*/"_",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"",
/*filename_extension=*/".nim" };
return {/*types=*/Case::kUpperCamel,
/*constants=*/Case::kUpperCamel,
/*methods=*/Case::kLowerCamel,
/*functions=*/Case::kUpperCamel,
/*fields=*/Case::kLowerCamel,
/*variable=*/Case::kLowerCamel,
/*variants=*/Case::kUpperCamel,
/*enum_variant_seperator=*/".",
/*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
/*namespaces=*/Case::kKeep,
/*namespace_seperator=*/"/",
/*object_prefix=*/"",
/*object_suffix=*/"T",
/*keyword_prefix=*/"",
/*keyword_suffix=*/"_",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"",
/*filename_extension=*/".nim"};
}
const std::string Export = "*";
const std::set<std::string> builtin_types = {
"uint8", "uint8", "bool", "int8", "uint8", "int16",
"uint16", "int32", "uint32", "int64", "uint64", "float32",
"float64", "string", "int", "uint", "uoffset", "Builder"
};
"uint8", "uint8", "bool", "int8", "uint8", "int16",
"uint16", "int32", "uint32", "int64", "uint64", "float32",
"float64", "string", "int", "uint", "uoffset", "Builder"};
class NimBfbsGenerator : public BaseBfbsGenerator {
public:
explicit NimBfbsGenerator(const std::string &flatc_version)
explicit NimBfbsGenerator(const std::string& flatc_version)
: BaseBfbsGenerator(),
keywords_(),
imports_(),
@@ -95,15 +94,15 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version),
namer_(NimDefaultConfig(), NimKeywords()) {}
Status GenerateFromSchema(const r::Schema *schema,
const CodeGenOptions &options)
Status GenerateFromSchema(const r::Schema* schema,
const CodeGenOptions& options)
FLATBUFFERS_OVERRIDE {
options_ = options;
ForAllEnums(schema->enums(), [&](const r::Enum *enum_def) {
ForAllEnums(schema->enums(), [&](const r::Enum* enum_def) {
StartCodeBlock(enum_def);
GenerateEnum(enum_def);
});
ForAllObjects(schema->objects(), [&](const r::Object *object) {
ForAllObjects(schema->objects(), [&](const r::Object* object) {
StartCodeBlock(object);
GenerateObject(object);
});
@@ -112,17 +111,17 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
using BaseBfbsGenerator::GenerateCode;
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -130,16 +129,16 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
return NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return NOT_IMPLEMENTED;
@@ -161,7 +160,7 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
}
protected:
void GenerateEnum(const r::Enum *enum_def) {
void GenerateEnum(const r::Enum* enum_def) {
std::string code;
std::string ns;
@@ -172,7 +171,7 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
GenerateDocumentation(enum_def->documentation(), "", code);
code += "type " + enum_name + Export + "{.pure.} = enum\n";
ForAllEnumValues(enum_def, [&](const reflection::EnumVal *enum_val) {
ForAllEnumValues(enum_def, [&](const reflection::EnumVal* enum_val) {
GenerateDocumentation(enum_val->documentation(), " ", code);
code += " " + namer_.Variant(enum_val->name()->str()) + " = " +
NumToString(enum_val->value()) + "." + enum_type + ",\n";
@@ -181,7 +180,7 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
EmitCodeBlock(code, enum_name, ns, enum_def->declaration_file()->str());
}
void GenerateObject(const r::Object *object) {
void GenerateObject(const r::Object* object) {
// Register the main flatbuffers module.
RegisterImports("flatbuffers", "");
std::string code;
@@ -193,9 +192,11 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
code += "type " + object_name + "* = object of FlatObj\n";
// Create all the field accessors.
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
// Skip writing deprecated fields altogether.
if (field->deprecated()) { return; }
if (field->deprecated()) {
return;
}
const std::string field_name = namer_.Field(*field);
const r::BaseType base_type = field->type()->base_type();
@@ -256,7 +257,9 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
}
}
code += getter_signature + getter_code;
if (IsScalar(base_type)) { code += setter_signature + setter_code; }
if (IsScalar(base_type)) {
code += setter_signature + setter_code;
}
} else if (base_type == r::Array || base_type == r::Vector) {
const r::BaseType vector_base_type = field->type()->element();
uint32_t element_size = field->type()->element_size();
@@ -309,8 +312,10 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
code += " builder.StartObject(" + NumToString(object->fields()->size()) +
")\n";
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
if (field->deprecated()) { return; }
ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
if (field->deprecated()) {
return;
}
const std::string field_name = namer_.Field(*field);
const std::string variable_name = namer_.Variable(*field);
@@ -348,21 +353,21 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
private:
void GenerateDocumentation(
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
*documentation,
std::string indent, std::string &code) const {
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>*
documentation,
std::string indent, std::string& code) const {
flatbuffers::ForAllDocumentation(
documentation, [&](const flatbuffers::String *str) {
documentation, [&](const flatbuffers::String* str) {
code += indent + "# " + str->str() + "\n";
});
}
std::string GenerateStructBuilderArgs(const r::Object *object,
std::string GenerateStructBuilderArgs(const r::Object* object,
std::string prefix = "") const {
std::string signature;
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
if (IsStructOrTable(field->type()->base_type())) {
const r::Object *field_object = GetObject(field->type());
const r::Object* field_object = GetObject(field->type());
signature += GenerateStructBuilderArgs(
field_object, prefix + namer_.Variable(*field) + "_");
} else {
@@ -373,7 +378,7 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
return signature;
}
std::string AppendStructBuilderBody(const r::Object *object,
std::string AppendStructBuilderBody(const r::Object* object,
std::string prefix = "") const {
std::string code;
code += " self.Prep(" + NumToString(object->minalign()) + ", " +
@@ -381,13 +386,13 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
// We need to reverse the order we iterate over, since we build the
// buffer backwards.
ForAllFields(object, /*reverse=*/true, [&](const r::Field *field) {
ForAllFields(object, /*reverse=*/true, [&](const r::Field* field) {
const int32_t num_padding_bytes = field->padding();
if (num_padding_bytes) {
code += " self.Pad(" + NumToString(num_padding_bytes) + ")\n";
}
if (IsStructOrTable(field->type()->base_type())) {
const r::Object *field_object = GetObject(field->type());
const r::Object* field_object = GetObject(field->type());
code += AppendStructBuilderBody(field_object,
prefix + namer_.Variable(*field) + "_");
} else {
@@ -398,28 +403,35 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
return code;
}
std::string GenerateMethod(const r::Field *field) const {
std::string GenerateMethod(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsStructOrTable(base_type)) { return "Struct"; }
if (IsStructOrTable(base_type)) {
return "Struct";
}
return "";
}
std::string GenerateGetter(const r::Type *type, const std::string &offsetval,
std::string GenerateGetter(const r::Type* type, const std::string& offsetval,
bool element_type = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
std::string offset = offsetval;
if (!element_type) { offset = "self.tab.Pos + " + offset; }
if (!element_type) {
offset = "self.tab.Pos + " + offset;
}
switch (base_type) {
case r::String: return "self.tab.String(" + offset + ")";
case r::Union: return "self.tab.Union(" + offsetval + ")";
case r::String:
return "self.tab.String(" + offset + ")";
case r::Union:
return "self.tab.Union(" + offsetval + ")";
case r::Obj: {
return GenerateType(type, element_type) +
"(tab: Vtable(Bytes: self.tab.Bytes, Pos: " + offset + "))";
}
case r::Vector: return GenerateGetter(type, offsetval, true);
case r::Vector:
return GenerateGetter(type, offsetval, true);
default:
const r::Enum *type_enum = GetEnum(type, element_type);
const r::Enum* type_enum = GetEnum(type, element_type);
if (type_enum != nullptr) {
return GenerateType(type, element_type) + "(" + "Get[" +
GenerateType(base_type) + "](self.tab, " + offset + ")" + ")";
@@ -430,46 +442,52 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
}
}
std::string Denamespace(const std::string &s, std::string &importns,
std::string &ns) const {
if (builtin_types.find(s) != builtin_types.end()) { return s; }
std::string Denamespace(const std::string& s, std::string& importns,
std::string& ns) const {
if (builtin_types.find(s) != builtin_types.end()) {
return s;
}
std::string type = namer_.Type(namer_.Denamespace(s, ns));
importns = ns.empty() ? type : ns + "." + type;
std::replace(importns.begin(), importns.end(), '.', '_');
return type;
}
std::string Denamespace(const std::string &s, std::string &importns) const {
std::string Denamespace(const std::string& s, std::string& importns) const {
std::string ns;
return Denamespace(s, importns, ns);
}
std::string Denamespace(const std::string &s) const {
std::string Denamespace(const std::string& s) const {
std::string importns;
return Denamespace(s, importns);
}
std::string GenerateType(const r::Type *type, bool element_type = false,
std::string GenerateType(const r::Type* type, bool element_type = false,
bool enum_inner = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
if (IsScalar(base_type) && !enum_inner) {
const r::Enum *type_enum = GetEnum(type, element_type);
const r::Enum* type_enum = GetEnum(type, element_type);
if (type_enum != nullptr) {
std::string importns;
std::string type_name = Denamespace(type_enum->name()->str(), importns);
return importns + "." + type_name;
}
}
if (IsScalar(base_type)) { return Denamespace(GenerateType(base_type)); }
if (IsScalar(base_type)) {
return Denamespace(GenerateType(base_type));
}
switch (base_type) {
case r::String: return "string";
case r::String:
return "string";
case r::Vector: {
return "seq[" + GenerateType(type, true) + "]";
}
case r::Union: return "Vtable";
case r::Union:
return "Vtable";
case r::Obj: {
const r::Object *type_obj = GetObject(type, element_type);
const r::Object* type_obj = GetObject(type, element_type);
std::string importns;
std::string type_name = Denamespace(type_obj->name()->str(), importns);
if (type_obj == current_obj_) {
@@ -478,11 +496,12 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
return importns + "." + type_name;
}
}
default: return "uoffset";
default:
return "uoffset";
}
}
std::string GenerateTypeBasic(const r::Type *type,
std::string GenerateTypeBasic(const r::Type* type,
bool element_type = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
@@ -495,25 +514,40 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
std::string GenerateType(const r::BaseType base_type) const {
switch (base_type) {
case r::None: return "uint8";
case r::UType: return "uint8";
case r::Bool: return "bool";
case r::Byte: return "int8";
case r::UByte: return "uint8";
case r::Short: return "int16";
case r::UShort: return "uint16";
case r::Int: return "int32";
case r::UInt: return "uint32";
case r::Long: return "int64";
case r::ULong: return "uint64";
case r::Float: return "float32";
case r::Double: return "float64";
case r::String: return "string";
default: return r::EnumNameBaseType(base_type);
case r::None:
return "uint8";
case r::UType:
return "uint8";
case r::Bool:
return "bool";
case r::Byte:
return "int8";
case r::UByte:
return "uint8";
case r::Short:
return "int16";
case r::UShort:
return "uint16";
case r::Int:
return "int32";
case r::UInt:
return "uint32";
case r::Long:
return "int64";
case r::ULong:
return "uint64";
case r::Float:
return "float32";
case r::Double:
return "float64";
case r::String:
return "string";
default:
return r::EnumNameBaseType(base_type);
}
}
std::string DefaultValue(const r::Field *field) const {
std::string DefaultValue(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsFloatingPoint(base_type)) {
if (field->default_real() != field->default_real()) {
@@ -531,24 +565,26 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
return field->default_integer() ? "true" : "false";
}
if (IsScalar(base_type)) {
const r::Enum *type_enum = GetEnum(field->type());
const r::Enum* type_enum = GetEnum(field->type());
if (type_enum != nullptr) {
return "type(result)(" + NumToString((field->default_integer())) + ")";
}
return NumToString((field->default_integer()));
}
if (base_type == r::String) { return "\"\""; }
if (base_type == r::String) {
return "\"\"";
}
// represents offsets
return "0";
}
void StartCodeBlock(const reflection::Enum *enum_def) {
void StartCodeBlock(const reflection::Enum* enum_def) {
current_enum_ = enum_def;
current_obj_ = nullptr;
imports_.clear();
}
void StartCodeBlock(const reflection::Object *object) {
void StartCodeBlock(const reflection::Object* object) {
current_enum_ = nullptr;
current_obj_ = object;
imports_.clear();
@@ -572,8 +608,8 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
return result;
}
std::string GetRelativePathFromNamespace(const std::string &relative_to,
const std::string &str2) {
std::string GetRelativePathFromNamespace(const std::string& relative_to,
const std::string& str2) {
std::vector<std::string> relative_to_vec = StringSplit(relative_to, ".");
std::vector<std::string> str2_vec = StringSplit(str2, ".");
while (relative_to_vec.size() > 0 && str2_vec.size() > 0) {
@@ -592,12 +628,14 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
std::string new_path;
for (size_t i = 0; i < str2_vec.size(); ++i) {
new_path += str2_vec[i];
if (i != str2_vec.size() - 1) { new_path += "/"; }
if (i != str2_vec.size() - 1) {
new_path += "/";
}
}
return new_path;
}
void RegisterImports(const r::Object *object, const r::Field *field,
void RegisterImports(const r::Object* object, const r::Field* field,
bool use_element = false) {
std::string importns;
std::string type_name;
@@ -606,14 +644,18 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
use_element ? field->type()->element() : field->type()->base_type();
if (IsStructOrTable(type)) {
const r::Object *object_def = GetObjectByIndex(field->type()->index());
if (object_def == current_obj_) { return; }
const r::Object* object_def = GetObjectByIndex(field->type()->index());
if (object_def == current_obj_) {
return;
}
std::string ns;
type_name = Denamespace(object_def->name()->str(), importns, ns);
type_name = ns.empty() ? type_name : ns + "." + type_name;
} else {
const r::Enum *enum_def = GetEnumByIndex(field->type()->index());
if (enum_def == current_enum_) { return; }
const r::Enum* enum_def = GetEnumByIndex(field->type()->index());
if (enum_def == current_enum_) {
return;
}
std::string ns;
type_name = Denamespace(enum_def->name()->str(), importns, ns);
type_name = ns.empty() ? type_name : ns + "." + type_name;
@@ -625,13 +667,13 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
RegisterImports(import_path, importns);
}
void RegisterImports(const std::string &local_name,
const std::string &imports_name) {
void RegisterImports(const std::string& local_name,
const std::string& imports_name) {
imports_[local_name] = imports_name;
}
void EmitCodeBlock(const std::string &code_block, const std::string &name,
const std::string &ns, const std::string &declaring_file) {
void EmitCodeBlock(const std::string& code_block, const std::string& name,
const std::string& ns, const std::string& declaring_file) {
const std::string full_qualified_name = ns.empty() ? name : ns + "." + name;
std::string code = "#[ " + full_qualified_name + "\n";
@@ -683,15 +725,15 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
std::map<std::string, std::string> imports_;
CodeGenOptions options_;
const r::Object *current_obj_;
const r::Enum *current_enum_;
const r::Object* current_obj_;
const r::Enum* current_enum_;
const std::string flatc_version_;
const BfbsNamer namer_;
};
} // namespace
std::unique_ptr<CodeGenerator> NewNimBfbsGenerator(
const std::string &flatc_version) {
const std::string& flatc_version) {
return std::unique_ptr<NimBfbsGenerator>(new NimBfbsGenerator(flatc_version));
}
+89 -56
View File
@@ -15,11 +15,11 @@
namespace flatbuffers {
namespace {
static bool BinaryRegionSort(const BinaryRegion &a, const BinaryRegion &b) {
static bool BinaryRegionSort(const BinaryRegion& a, const BinaryRegion& b) {
return a.offset < b.offset;
}
static void SetError(BinaryRegionComment &comment, BinaryRegionStatus status,
static void SetError(BinaryRegionComment& comment, BinaryRegionStatus status,
std::string message = "") {
comment.status = status;
comment.status_message = message;
@@ -40,7 +40,7 @@ static BinaryRegion MakeBinaryRegion(
return region;
}
static BinarySection MakeBinarySection(const std::string &name,
static BinarySection MakeBinarySection(const std::string& name,
const BinarySectionType type,
std::vector<BinaryRegion> regions) {
BinarySection section;
@@ -50,33 +50,37 @@ static BinarySection MakeBinarySection(const std::string &name,
return section;
}
static BinarySection MakeSingleRegionBinarySection(const std::string &name,
static BinarySection MakeSingleRegionBinarySection(const std::string& name,
const BinarySectionType type,
const BinaryRegion &region) {
const BinaryRegion& region) {
std::vector<BinaryRegion> regions;
regions.push_back(region);
return MakeBinarySection(name, type, std::move(regions));
}
static bool IsNonZeroRegion(const uint64_t offset, const uint64_t length,
const uint8_t *const binary) {
const uint8_t* const binary) {
for (uint64_t i = offset; i < offset + length; ++i) {
if (binary[i] != 0) { return true; }
if (binary[i] != 0) {
return true;
}
}
return false;
}
static bool IsPrintableRegion(const uint64_t offset, const uint64_t length,
const uint8_t *const binary) {
const uint8_t* const binary) {
for (uint64_t i = offset; i < offset + length; ++i) {
if (!isprint(binary[i])) { return false; }
if (!isprint(binary[i])) {
return false;
}
}
return true;
}
static BinarySection GenerateMissingSection(const uint64_t offset,
const uint64_t length,
const uint8_t *const binary) {
const uint8_t* const binary) {
std::vector<BinaryRegion> regions;
// Check if the region is all zeros or not, as that can tell us if it is
@@ -130,7 +134,9 @@ std::map<uint64_t, BinarySection> BinaryAnnotator::Annotate() {
}
// The binary is too short to read as a flatbuffers.
if (binary_length_ < FLATBUFFERS_MIN_BUFFER_SIZE) { return {}; }
if (binary_length_ < FLATBUFFERS_MIN_BUFFER_SIZE) {
return {};
}
// Make sure we start with a clean slate.
vtables_.clear();
@@ -234,20 +240,24 @@ uint64_t BinaryAnnotator::BuildHeader(const uint64_t header_offset) {
return root_table_loc;
}
BinaryAnnotator::VTable *BinaryAnnotator::GetOrBuildVTable(
const uint64_t vtable_offset, const reflection::Object *const table,
BinaryAnnotator::VTable* BinaryAnnotator::GetOrBuildVTable(
const uint64_t vtable_offset, const reflection::Object* const table,
const uint64_t offset_of_referring_table) {
// Get a list of vtables (if any) already defined at this offset.
std::list<VTable> &vtables = vtables_[vtable_offset];
std::list<VTable>& vtables = vtables_[vtable_offset];
// See if this vtable for the table type has been generated before.
for (VTable &vtable : vtables) {
if (vtable.referring_table == table) { return &vtable; }
for (VTable& vtable : vtables) {
if (vtable.referring_table == table) {
return &vtable;
}
}
// If we are trying to make a new vtable and it is already encompassed by
// another binary section, something is corrupted.
if (vtables.empty() && ContainsSection(vtable_offset)) { return nullptr; }
if (vtables.empty() && ContainsSection(vtable_offset)) {
return nullptr;
}
const std::string referring_table_name = table->name()->str();
@@ -352,7 +362,7 @@ BinaryAnnotator::VTable *BinaryAnnotator::GetOrBuildVTable(
uint16_t fields_processed = 0;
// Loop over all the fields.
ForAllFields(table, /*reverse=*/false, [&](const reflection::Field *field) {
ForAllFields(table, /*reverse=*/false, [&](const reflection::Field* field) {
const uint64_t field_offset = offset_start + field->id() * sizeof(uint16_t);
if (field_offset >= vtable_offset + vtable_size) {
@@ -497,8 +507,10 @@ BinaryAnnotator::VTable *BinaryAnnotator::GetOrBuildVTable(
void BinaryAnnotator::BuildTable(const uint64_t table_offset,
const BinarySectionType type,
const reflection::Object *const table) {
if (ContainsSection(table_offset)) { return; }
const reflection::Object* const table) {
if (ContainsSection(table_offset)) {
return;
}
BinaryRegionComment vtable_offset_comment;
vtable_offset_comment.type = BinaryRegionCommentType::TableVTableOffset;
@@ -548,7 +560,7 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
// Parse the vtable first so we know what the rest of the fields in the table
// are.
const VTable *const vtable =
const VTable* const vtable =
GetOrBuildVTable(vtable_offset, table, table_offset);
if (vtable == nullptr) {
@@ -571,18 +583,18 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
// not by their IDs. So copy them over to another vector that we can sort on
// the offset_from_table property.
std::vector<VTable::Entry> fields;
for (const auto &vtable_field : vtable->fields) {
for (const auto& vtable_field : vtable->fields) {
fields.push_back(vtable_field.second);
}
std::stable_sort(fields.begin(), fields.end(),
[](const VTable::Entry &a, const VTable::Entry &b) {
[](const VTable::Entry& a, const VTable::Entry& b) {
return a.offset_from_table < b.offset_from_table;
});
// Iterate over all the fields by order of their offset.
for (size_t i = 0; i < fields.size(); ++i) {
const reflection::Field *field = fields[i].field;
const reflection::Field* field = fields[i].field;
const uint16_t offset_from_table = fields[i].offset_from_table;
if (offset_from_table == 0) {
@@ -610,7 +622,9 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
: table_end_offset) -
field_offset;
if (unknown_field_length == 0) { continue; }
if (unknown_field_length == 0) {
continue;
}
std::string hint;
@@ -741,7 +755,7 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
switch (field->type()->base_type()) {
case reflection::BaseType::Obj: {
const reflection::Object *next_object =
const reflection::Object* next_object =
schema_->objects()->Get(field->type()->index());
if (next_object->is_struct()) {
@@ -830,7 +844,8 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
} break;
default: break;
default:
break;
}
}
@@ -855,14 +870,16 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
}
uint64_t BinaryAnnotator::BuildStruct(const uint64_t struct_offset,
std::vector<BinaryRegion> &regions,
std::vector<BinaryRegion>& regions,
const std::string referring_field_name,
const reflection::Object *const object) {
if (!object->is_struct()) { return struct_offset; }
const reflection::Object* const object) {
if (!object->is_struct()) {
return struct_offset;
}
uint64_t offset = struct_offset;
// Loop over all the fields in increasing order
ForAllFields(object, /*reverse=*/false, [&](const reflection::Field *field) {
ForAllFields(object, /*reverse=*/false, [&](const reflection::Field* field) {
if (IsScalar(field->type()->base_type())) {
// Structure Field value
const uint64_t type_size = GetTypeSize(field->type()->base_type());
@@ -971,11 +988,13 @@ uint64_t BinaryAnnotator::BuildStruct(const uint64_t struct_offset,
}
void BinaryAnnotator::BuildString(const uint64_t string_offset,
const reflection::Object *const table,
const reflection::Field *const field) {
const reflection::Object* const table,
const reflection::Field* const field) {
// Check if we have already generated this string section, and this is a
// shared string instance.
if (ContainsSection(string_offset)) { return; }
if (ContainsSection(string_offset)) {
return;
}
std::vector<BinaryRegion> regions;
const auto string_length = ReadScalar<uint32_t>(string_offset);
@@ -1034,10 +1053,12 @@ void BinaryAnnotator::BuildString(const uint64_t string_offset,
}
void BinaryAnnotator::BuildVector(
const uint64_t vector_offset, const reflection::Object *const table,
const reflection::Field *const field, const uint64_t parent_table_offset,
const uint64_t vector_offset, const reflection::Object* const table,
const reflection::Field* const field, const uint64_t parent_table_offset,
const std::map<uint16_t, VTable::Entry> vtable_fields) {
if (ContainsSection(vector_offset)) { return; }
if (ContainsSection(vector_offset)) {
return;
}
BinaryRegionComment vector_length_comment;
vector_length_comment.type = BinaryRegionCommentType::VectorLength;
@@ -1052,13 +1073,17 @@ void BinaryAnnotator::BuildVector(
if (is_64_bit_vector) {
auto v = ReadScalar<uint64_t>(vector_offset);
if (v.has_value()) { vector_length = v.value(); }
if (v.has_value()) {
vector_length = v.value();
}
vector_length_size_type = sizeof(uint64_t);
region_type = BinaryRegionType::Uint64;
section_type = BinarySectionType::Vector64;
} else {
auto v = ReadScalar<uint32_t>(vector_offset);
if (v.has_value()) { vector_length = v.value(); }
if (v.has_value()) {
vector_length = v.value();
}
vector_length_size_type = sizeof(uint32_t);
region_type = BinaryRegionType::Uint32;
section_type = BinarySectionType::Vector;
@@ -1108,7 +1133,7 @@ void BinaryAnnotator::BuildVector(
switch (field->type()->element()) {
case reflection::BaseType::Obj: {
const reflection::Object *object =
const reflection::Object* object =
schema_->objects()->Get(field->type()->index());
if (object->is_struct()) {
@@ -1117,7 +1142,9 @@ void BinaryAnnotator::BuildVector(
// Structs are inline to the vector.
const uint64_t next_offset =
BuildStruct(offset, regions, "[" + NumToString(i) + "]", object);
if (next_offset == offset) { break; }
if (next_offset == offset) {
break;
}
offset = next_offset;
}
} else {
@@ -1382,18 +1409,20 @@ void BinaryAnnotator::BuildVector(
std::string BinaryAnnotator::BuildUnion(const uint64_t union_offset,
const uint8_t realized_type,
const reflection::Field *const field) {
const reflection::Enum *next_enum =
const reflection::Field* const field) {
const reflection::Enum* next_enum =
schema_->enums()->Get(field->type()->index());
const reflection::EnumVal *enum_val = next_enum->values()->Get(realized_type);
const reflection::EnumVal* enum_val = next_enum->values()->Get(realized_type);
if (ContainsSection(union_offset)) { return enum_val->name()->c_str(); }
if (ContainsSection(union_offset)) {
return enum_val->name()->c_str();
}
const reflection::Type *union_type = enum_val->union_type();
const reflection::Type* union_type = enum_val->union_type();
if (union_type->base_type() == reflection::BaseType::Obj) {
const reflection::Object *object =
const reflection::Object* object =
schema_->objects()->Get(union_type->index());
if (object->is_struct()) {
@@ -1418,8 +1447,8 @@ std::string BinaryAnnotator::BuildUnion(const uint64_t union_offset,
void BinaryAnnotator::FixMissingRegions() {
std::vector<BinaryRegion> regions_to_insert;
for (auto &current_section : sections_) {
BinarySection &section = current_section.second;
for (auto& current_section : sections_) {
BinarySection& section = current_section.second;
if (section.regions.empty()) {
// TODO(dbaileychess): is this possible?
continue;
@@ -1427,7 +1456,7 @@ void BinaryAnnotator::FixMissingRegions() {
uint64_t offset = section.regions[0].offset + section.regions[0].length;
for (size_t i = 1; i < section.regions.size(); ++i) {
BinaryRegion &region = section.regions[i];
BinaryRegion& region = section.regions[i];
const uint64_t next_offset = region.offset;
if (!IsValidOffset(next_offset)) {
@@ -1470,8 +1499,8 @@ void BinaryAnnotator::FixMissingSections() {
std::vector<BinarySection> sections_to_insert;
for (auto &current_section : sections_) {
BinarySection &section = current_section.second;
for (auto& current_section : sections_) {
BinarySection& section = current_section.second;
const uint64_t section_start_offset = current_section.first;
const uint64_t section_end_offset =
section.regions.back().offset + section.regions.back().length;
@@ -1494,7 +1523,7 @@ void BinaryAnnotator::FixMissingSections() {
GenerateMissingSection(offset - 1, pad_bytes, binary_));
}
for (const BinarySection &section_to_insert : sections_to_insert) {
for (const BinarySection& section_to_insert : sections_to_insert) {
AddSection(section_to_insert.regions[0].offset, section_to_insert);
}
}
@@ -1502,11 +1531,15 @@ void BinaryAnnotator::FixMissingSections() {
bool BinaryAnnotator::ContainsSection(const uint64_t offset) {
auto it = sections_.lower_bound(offset);
// If the section is found, check that it is exactly equal its offset.
if (it != sections_.end() && it->first == offset) { return true; }
if (it != sections_.end() && it->first == offset) {
return true;
}
// If this was the first section, there are no other previous sections to
// check.
if (it == sections_.begin()) { return false; }
if (it == sections_.begin()) {
return false;
}
// Go back one section.
--it;
@@ -1516,7 +1549,7 @@ bool BinaryAnnotator::ContainsSection(const uint64_t offset) {
it->second.regions.back().length;
}
const reflection::Object *BinaryAnnotator::RootTable() const {
const reflection::Object* BinaryAnnotator::RootTable() const {
if (!root_table_.empty()) {
return schema_->objects()->LookupByKey(root_table_);
}
+57 -51
View File
@@ -24,21 +24,21 @@
#include "flatbuffers/util.h"
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4127) // C4127: conditional expression is constant
#pragma warning(push)
#pragma warning(disable : 4127) // C4127: conditional expression is constant
#endif
namespace flatbuffers {
std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
const std::string &path,
const std::string &file_name) {
std::string JavaCSharpMakeRule(const bool java, const Parser& parser,
const std::string& path,
const std::string& file_name) {
const std::string file_extension = java ? ".java" : ".cs";
std::string make_rule;
for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
++it) {
auto &enum_def = **it;
auto& enum_def = **it;
if (!make_rule.empty()) make_rule += " ";
std::string directory =
BaseGenerator::NamespaceDir(parser, path, *enum_def.defined_namespace);
@@ -47,7 +47,7 @@ std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
++it) {
auto &struct_def = **it;
auto& struct_def = **it;
if (!make_rule.empty()) make_rule += " ";
std::string directory = BaseGenerator::NamespaceDir(
parser, path, *struct_def.defined_namespace);
@@ -67,10 +67,14 @@ void CodeWriter::operator+=(std::string text) {
while (true) {
auto begin = text.find("{{");
if (begin == std::string::npos) { break; }
if (begin == std::string::npos) {
break;
}
auto end = text.find("}}");
if (end == std::string::npos || end < begin) { break; }
if (end == std::string::npos || end < begin) {
break;
}
// Write all the text before the first {{ into the stream.
stream_.write(text.c_str(), begin);
@@ -82,7 +86,7 @@ void CodeWriter::operator+=(std::string text) {
// value into the stream, otherwise write the key itself into the stream.
auto iter = value_map_.find(key);
if (iter != value_map_.end()) {
const std::string &value = iter->second;
const std::string& value = iter->second;
stream_ << value;
} else {
FLATBUFFERS_ASSERT(false && "could not find key");
@@ -102,26 +106,26 @@ void CodeWriter::operator+=(std::string text) {
}
}
void CodeWriter::AppendIdent(std::stringstream &stream) {
void CodeWriter::AppendIdent(std::stringstream& stream) {
int lvl = cur_ident_lvl_;
while (lvl--) {
stream.write(pad_.c_str(), static_cast<std::streamsize>(pad_.size()));
}
}
const char *BaseGenerator::FlatBuffersGeneratedWarning() {
const char* BaseGenerator::FlatBuffersGeneratedWarning() {
return "automatically generated by the FlatBuffers compiler,"
" do not modify";
}
std::string BaseGenerator::NamespaceDir(const Parser &parser,
const std::string &path,
const Namespace &ns,
std::string BaseGenerator::NamespaceDir(const Parser& parser,
const std::string& path,
const Namespace& ns,
const bool dasherize) {
EnsureDirExists(path);
if (parser.opts.one_file) return path;
std::string namespace_dir = path; // Either empty or ends in separator.
auto &namespaces = ns.components;
auto& namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
namespace_dir +=
!dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
@@ -131,15 +135,15 @@ std::string BaseGenerator::NamespaceDir(const Parser &parser,
return namespace_dir;
}
std::string BaseGenerator::NamespaceDir(const Namespace &ns,
std::string BaseGenerator::NamespaceDir(const Namespace& ns,
const bool dasherize) const {
return BaseGenerator::NamespaceDir(parser_, path_, ns, dasherize);
}
std::string BaseGenerator::FullNamespace(const char *separator,
const Namespace &ns) {
std::string BaseGenerator::FullNamespace(const char* separator,
const Namespace& ns) {
std::string namespace_name;
auto &namespaces = ns.components;
auto& namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_name.length()) namespace_name += separator;
namespace_name += *it;
@@ -147,7 +151,7 @@ std::string BaseGenerator::FullNamespace(const char *separator,
return namespace_name;
}
std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
std::string BaseGenerator::LastNamespacePart(const Namespace& ns) {
if (!ns.components.empty())
return ns.components.back();
else
@@ -155,21 +159,21 @@ std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
}
// Ensure that a type is prefixed with its namespace.
std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
const std::string &name) const {
std::string BaseGenerator::WrapInNameSpace(const Namespace* ns,
const std::string& name) const {
std::string qualified_name = qualifying_start_;
for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
qualified_name += *it + qualifying_separator_;
return qualified_name + name;
}
std::string BaseGenerator::WrapInNameSpace(const Definition &def,
const std::string &suffix) const {
std::string BaseGenerator::WrapInNameSpace(const Definition& def,
const std::string& suffix) const {
return WrapInNameSpace(def.defined_namespace, def.name + suffix);
}
std::string BaseGenerator::GetNameSpace(const Definition &def) const {
const Namespace *ns = def.defined_namespace;
std::string BaseGenerator::GetNameSpace(const Definition& def) const {
const Namespace* ns = def.defined_namespace;
if (CurrentNameSpace() == ns) return "";
std::string qualified_name = qualifying_start_;
for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
@@ -182,23 +186,23 @@ std::string BaseGenerator::GetNameSpace(const Definition &def) const {
return qualified_name;
}
std::string BaseGenerator::GeneratedFileName(const std::string &path,
const std::string &file_name,
const IDLOptions &options) const {
std::string BaseGenerator::GeneratedFileName(const std::string& path,
const std::string& file_name,
const IDLOptions& options) const {
return path + file_name + options.filename_suffix + "." +
(options.filename_extension.empty() ? default_extension_
: options.filename_extension);
}
// Generate a documentation comment, if available.
void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
const CommentConfig *config, const char *prefix) {
void GenComment(const std::vector<std::string>& dc, std::string* code_ptr,
const CommentConfig* config, const char* prefix) {
if (dc.begin() == dc.end()) {
// Don't output empty comment blocks with 0 lines of comment content.
return;
}
std::string &code = *code_ptr;
std::string& code = *code_ptr;
if (config != nullptr && config->first_line != nullptr) {
code += std::string(prefix) + std::string(config->first_line) + "\n";
}
@@ -215,10 +219,10 @@ void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
}
}
template<typename T>
template <typename T>
std::string FloatConstantGenerator::GenFloatConstantImpl(
const FieldDef &field) const {
const auto &constant = field.value.constant;
const FieldDef& field) const {
const auto& constant = field.value.constant;
T v;
auto done = StringToNumber(constant.c_str(), &v);
FLATBUFFERS_ASSERT(done);
@@ -233,10 +237,12 @@ std::string FloatConstantGenerator::GenFloatConstantImpl(
}
std::string FloatConstantGenerator::GenFloatConstant(
const FieldDef &field) const {
const FieldDef& field) const {
switch (field.value.type.base_type) {
case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
case BASE_TYPE_FLOAT:
return GenFloatConstantImpl<float>(field);
case BASE_TYPE_DOUBLE:
return GenFloatConstantImpl<double>(field);
default: {
FLATBUFFERS_ASSERT(false);
return "INVALID_BASE_TYPE";
@@ -245,9 +251,9 @@ std::string FloatConstantGenerator::GenFloatConstant(
}
TypedFloatConstantGenerator::TypedFloatConstantGenerator(
const char *double_prefix, const char *single_prefix,
const char *nan_number, const char *pos_inf_number,
const char *neg_inf_number)
const char* double_prefix, const char* single_prefix,
const char* nan_number, const char* pos_inf_number,
const char* neg_inf_number)
: double_prefix_(double_prefix),
single_prefix_(single_prefix),
nan_number_(nan_number),
@@ -255,11 +261,11 @@ TypedFloatConstantGenerator::TypedFloatConstantGenerator(
neg_inf_number_(neg_inf_number) {}
std::string TypedFloatConstantGenerator::MakeNaN(
const std::string &prefix) const {
const std::string& prefix) const {
return prefix + nan_number_;
}
std::string TypedFloatConstantGenerator::MakeInf(
bool neg, const std::string &prefix) const {
bool neg, const std::string& prefix) const {
if (neg)
return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
: ("-" + prefix + pos_inf_number_);
@@ -268,7 +274,7 @@ std::string TypedFloatConstantGenerator::MakeInf(
}
std::string TypedFloatConstantGenerator::Value(double v,
const std::string &src) const {
const std::string& src) const {
(void)v;
return src;
}
@@ -283,7 +289,7 @@ std::string TypedFloatConstantGenerator::NaN(double v) const {
}
std::string TypedFloatConstantGenerator::Value(float v,
const std::string &src) const {
const std::string& src) const {
(void)v;
return src + "f";
}
@@ -298,14 +304,14 @@ std::string TypedFloatConstantGenerator::NaN(float v) const {
}
SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
const char *nan_number, const char *pos_inf_number,
const char *neg_inf_number)
const char* nan_number, const char* pos_inf_number,
const char* neg_inf_number)
: nan_number_(nan_number),
pos_inf_number_(pos_inf_number),
neg_inf_number_(neg_inf_number) {}
std::string SimpleFloatConstantGenerator::Value(double v,
const std::string &src) const {
const std::string& src) const {
(void)v;
return src;
}
@@ -320,7 +326,7 @@ std::string SimpleFloatConstantGenerator::NaN(double v) const {
}
std::string SimpleFloatConstantGenerator::Value(float v,
const std::string &src) const {
const std::string& src) const {
return this->Value(static_cast<double>(v), src);
}
@@ -335,5 +341,5 @@ std::string SimpleFloatConstantGenerator::NaN(float v) const {
} // namespace flatbuffers
#if defined(_MSC_VER)
# pragma warning(pop)
#pragma warning(pop)
#endif
+3 -3
View File
@@ -24,15 +24,15 @@ namespace flatbuffers {
class FileBinaryWriter : public FileManager {
public:
bool SaveFile(const std::string &absolute_file_name,
const std::string &content) override {
bool SaveFile(const std::string& absolute_file_name,
const std::string& content) override {
std::ofstream ofs(absolute_file_name, std::ofstream::binary);
if (!ofs.is_open()) return false;
ofs.write(content.c_str(), content.size());
return !ofs.bad();
}
bool Loadfile(const std::string &absolute_file_name, std::string *output) {
bool Loadfile(const std::string& absolute_file_name, std::string* output) {
if (DirExists(absolute_file_name.c_str())) return false;
std::ifstream ifs(absolute_file_name, std::ifstream::binary);
if (!ifs.is_open()) return false;
+3 -3
View File
@@ -27,8 +27,8 @@ class FileNameSavingFileManager : public FileManager {
FileNameSavingFileManager(std::set<std::string> file_names)
: file_names_(file_names) {}
bool SaveFile(const std::string &absolute_file_name,
const std::string &content) override {
bool SaveFile(const std::string& absolute_file_name,
const std::string& content) override {
(void)content;
auto pair = file_names_.insert(absolute_file_name);
// pair.second indicates whether the insertion is
@@ -36,7 +36,7 @@ class FileNameSavingFileManager : public FileManager {
return pair.second;
}
bool Loadfile(const std::string &absolute_file_name, std::string *content) {
bool Loadfile(const std::string& absolute_file_name, std::string* content) {
(void)absolute_file_name;
(void)content;
return false;
+3 -3
View File
@@ -24,15 +24,15 @@ namespace flatbuffers {
class FileWriter : public FileManager {
public:
bool SaveFile(const std::string &absolute_file_name,
const std::string &content) override {
bool SaveFile(const std::string& absolute_file_name,
const std::string& content) override {
std::ofstream ofs(absolute_file_name, std::ofstream::out);
if (!ofs.is_open()) return false;
ofs.write(content.c_str(), content.size());
return !ofs.bad();
}
bool Loadfile(const std::string &absolute_file_name, std::string *output) {
bool Loadfile(const std::string& absolute_file_name, std::string* output) {
if (DirExists(absolute_file_name.c_str())) return false;
std::ifstream ifs(absolute_file_name, std::ifstream::in);
if (!ifs.is_open()) return false;
+269 -254
View File
@@ -31,15 +31,15 @@
namespace flatbuffers {
static const char *FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
static const char* FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
void FlatCompiler::ParseFile(
flatbuffers::Parser &parser, const std::string &filename,
const std::string &contents,
const std::vector<const char *> &include_directories) const {
flatbuffers::Parser& parser, const std::string& filename,
const std::string& contents,
const std::vector<const char*>& include_directories) const {
auto local_include_directory = flatbuffers::StripFileName(filename);
std::vector<const char *> inc_directories;
std::vector<const char*> inc_directories;
inc_directories.insert(inc_directories.end(), include_directories.begin(),
include_directories.end());
inc_directories.push_back(local_include_directory.c_str());
@@ -48,238 +48,246 @@ void FlatCompiler::ParseFile(
if (!parser.Parse(contents.c_str(), &inc_directories[0], filename.c_str())) {
Error(parser.error_, false, false);
}
if (!parser.error_.empty()) { Warn(parser.error_, false); }
if (!parser.error_.empty()) {
Warn(parser.error_, false);
}
}
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()),
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())) {
Error("failed to load binary schema: " + filename, false, false);
}
}
void FlatCompiler::Warn(const std::string &warn, bool show_exe_name) const {
void FlatCompiler::Warn(const std::string& warn, bool show_exe_name) const {
params_.warn_fn(this, warn, show_exe_name);
}
void FlatCompiler::Error(const std::string &err, bool usage,
void FlatCompiler::Error(const std::string& err, bool usage,
bool show_exe_name) const {
params_.error_fn(this, err, usage, show_exe_name);
}
const static FlatCOption flatc_options[] = {
{ "o", "", "PATH", "Prefix PATH to all generated files." },
{ "I", "", "PATH", "Search for includes in the specified path." },
{ "M", "", "", "Print make rules for generated files." },
{ "", "version", "", "Print the version number of flatc and exit." },
{ "h", "help", "", "Prints this help text and exit." },
{ "", "strict-json", "",
"Strict JSON: field names must be / will be quoted, no trailing commas in "
"tables/vectors." },
{ "", "allow-non-utf8", "",
"Pass non-UTF-8 input through parser and emit nonstandard \\x escapes in "
"JSON. (Default is to raise parse error on non-UTF-8 input.)" },
{ "", "natural-utf8", "",
"Output strings with UTF-8 as human-readable strings. By default, UTF-8 "
"characters are printed as \\uXXXX escapes." },
{ "", "defaults-json", "",
"Output fields whose value is the default when writing JSON" },
{ "", "unknown-json", "",
"Allow fields in JSON that are not defined in the schema. These fields "
"will be discarded when generating binaries." },
{ "", "no-prefix", "",
"Don't prefix enum values with the enum type in C++." },
{ "", "scoped-enums", "",
"Use C++11 style scoped and strongly typed enums. Also implies "
"--no-prefix." },
{ "", "no-emit-min-max-enum-values", "",
"Disable generation of MIN and MAX enumerated values for scoped enums "
"and prefixed enums." },
{ "", "swift-implementation-only", "",
"Adds a @_implementationOnly to swift imports" },
{ "", "gen-includes", "",
"(deprecated), this is the default behavior. If the original behavior is "
"required (no include statements) use --no-includes." },
{ "", "no-includes", "",
"Don't generate include statements for included schemas the generated "
"file depends on (C++, Python, Proto-to-Fbs)." },
{ "", "gen-mutable", "",
"Generate accessors that can mutate buffers in-place." },
{ "", "gen-onefile", "",
"Generate a single output file for C#, Go, Java, Kotlin and Python. "
"Implies --no-include." },
{ "", "gen-name-strings", "",
"Generate type name functions for C++ and Rust." },
{ "", "gen-object-api", "", "Generate an additional object-based API." },
{ "", "gen-compare", "", "Generate operator== for object-based API types." },
{ "", "gen-nullable", "",
"Add Clang _Nullable for C++ pointer. or @Nullable for Java" },
{ "", "java-package-prefix", "",
"Add a prefix to the generated package name for Java." },
{ "", "java-checkerframework", "", "Add @Pure for Java." },
{ "", "gen-generated", "", "Add @Generated annotation for Java." },
{ "", "gen-jvmstatic", "",
"Add @JvmStatic annotation for Kotlin methods in companion object for "
"interop from Java to Kotlin." },
{ "", "gen-all", "",
"Generate not just code for the current schema files, but for all files it "
"includes as well. If the language uses a single file for output (by "
"default the case for C++ and JS), all code will end up in this one "
"file." },
{ "", "gen-json-emit", "",
"Generates encoding code which emits Flatbuffers into JSON" },
{ "", "cpp-include", "", "Adds an #include in generated file." },
{ "", "cpp-ptr-type", "T",
"Set object API pointer type (default std::unique_ptr)." },
{ "", "cpp-str-type", "T",
"Set object API string type (default std::string). T::c_str(), T::length() "
"and T::empty() must be supported. The custom type also needs to be "
"constructible from std::string (see the --cpp-str-flex-ctor option to "
"change this behavior)" },
{ "", "cpp-str-flex-ctor", "",
"Don't construct custom string types by passing std::string from "
"Flatbuffers, but (char* + length)." },
{ "", "cpp-field-case-style", "STYLE",
"Generate C++ fields using selected case style. Supported STYLE values: * "
"'unchanged' - leave unchanged (default) * 'upper' - schema snake_case "
"emits UpperCamel; * 'lower' - schema snake_case emits lowerCamel." },
{ "", "cpp-std", "CPP_STD",
"Generate a C++ code using features of selected C++ standard. Supported "
"CPP_STD values: * 'c++0x' - generate code compatible with old compilers; "
"'c++11' - use C++11 code generator (default); * 'c++17' - use C++17 "
"features in generated code (experimental)." },
{ "", "cpp-static-reflection", "",
"When using C++17, generate extra code to provide compile-time (static) "
"reflection of Flatbuffers types. Requires --cpp-std to be \"c++17\" or "
"higher." },
{ "", "object-prefix", "PREFIX",
"Customize class prefix for C++ object-based API." },
{ "", "object-suffix", "SUFFIX",
"Customize class suffix for C++ object-based API. Default Value is "
"\"T\"." },
{ "", "go-namespace", "", "Generate the overriding namespace in Golang." },
{ "", "go-import", "IMPORT",
"Generate the overriding import for flatbuffers in Golang (default is "
"\"github.com/google/flatbuffers/go\")." },
{ "", "go-module-name", "",
"Prefix local import paths of generated go code with the module name" },
{ "", "raw-binary", "",
"Allow binaries without file_identifier to be read. This may crash flatc "
"given a mismatched schema." },
{ "", "size-prefixed", "", "Input binaries are size prefixed buffers." },
{ "", "proto-namespace-suffix", "SUFFIX",
"Add this namespace to any flatbuffers generated from protobufs." },
{ "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." },
{ "", "keep-proto-id", "", "Keep protobuf field ids in generated fbs file." },
{ "", "proto-id-gap", "",
"Action that should be taken when a gap between protobuf ids found. "
"Supported values: * "
"'nop' - do not care about gap * 'warn' - A warning message will be shown "
"about the gap in protobuf ids"
"(default) "
"* 'error' - An error message will be shown and the fbs generation will be "
"interrupted." },
{ "", "grpc", "", "Generate GRPC interfaces for the specified languages." },
{ "", "schema", "", "Serialize schemas instead of JSON (use with -b)." },
{ "", "bfbs-filenames", "PATH",
"Sets the root path where reflection filenames in reflection.fbs are "
"relative to. The 'root' is denoted with `//`. E.g. if PATH=/a/b/c "
"then /a/d/e.fbs will be serialized as //../d/e.fbs. (PATH defaults to the "
"directory of the first provided schema file." },
{ "", "bfbs-absolute-paths", "", "Uses absolute paths instead of relative paths in the BFBS output." },
{ "", "bfbs-comments", "", "Add doc comments to the binary schema files." },
{ "", "bfbs-builtins", "",
"Add builtin attributes to the binary schema files." },
{ "", "bfbs-gen-embed", "",
"Generate code to embed the bfbs schema to the source." },
{ "", "conform", "FILE",
"Specify a schema the following schemas should be an evolution of. Gives "
"errors if not." },
{ "", "conform-includes", "PATH",
"Include path for the schema given with --conform PATH" },
{ "", "filename-suffix", "SUFFIX",
"The suffix appended to the generated file names (Default is "
"'_generated')." },
{ "", "filename-ext", "EXT",
"The extension appended to the generated file names. Default is "
"language-specific (e.g., '.h' for C++)" },
{ "", "include-prefix", "PATH",
"Prefix this PATH to any generated include statements." },
{ "", "keep-prefix", "",
"Keep original prefix of schema include statement." },
{ "", "reflect-types", "",
"Add minimal type reflection to code generation." },
{ "", "reflect-names", "", "Add minimal type/name reflection." },
{ "", "rust-serialize", "",
"Implement serde::Serialize on generated Rust types." },
{ "", "rust-module-root-file", "",
"Generate rust code in individual files with a module root file." },
{ "", "root-type", "T", "Select or override the default root_type." },
{ "", "require-explicit-ids", "",
"When parsing schemas, require explicit ids (id: x)." },
{ "", "force-defaults", "",
"Emit default values in binary output from JSON" },
{ "", "force-empty", "",
"When serializing from object API representation, force strings and "
"vectors to empty rather than null." },
{ "", "force-empty-vectors", "",
"When serializing from object API representation, force vectors to empty "
"rather than null." },
{ "", "flexbuffers", "",
"Used with \"binary\" and \"json\" options, it generates data using "
"schema-less FlexBuffers." },
{ "", "no-warnings", "", "Inhibit all warnings messages." },
{ "", "warnings-as-errors", "", "Treat all warnings as errors." },
{ "", "cs-global-alias", "",
"Prepend \"global::\" to all user generated csharp classes and "
"structs." },
{ "", "cs-gen-json-serializer", "",
"Allows (de)serialization of JSON text in the Object API. (requires "
"--gen-object-api)." },
{ "", "json-nested-bytes", "",
"Allow a nested_flatbuffer field to be parsed as a vector of bytes "
"in JSON, which is unsafe unless checked by a verifier afterwards." },
{ "", "ts-flat-files", "",
"Generate a single typescript file per .fbs file. Implies "
"ts_entry_points." },
{ "", "ts-entry-points", "",
"Generate entry point typescript per namespace. Implies gen-all." },
{ "", "annotate-sparse-vectors", "", "Don't annotate every vector element." },
{ "", "annotate", "SCHEMA",
"Annotate the provided BINARY_FILE with the specified SCHEMA file." },
{ "", "no-leak-private-annotation", "",
"Prevents multiple type of annotations within a Fbs SCHEMA file. "
"Currently this is required to generate private types in Rust" },
{ "", "python-no-type-prefix-suffix", "",
"Skip emission of Python functions that are prefixed with typenames" },
{ "", "python-typing", "", "Generate Python type annotations" },
{ "", "python-version", "", "Generate code for the given Python version." },
{ "", "python-decode-obj-api-strings", "", "Decode bytes to strings for the Python Object API"},
{ "", "python-gen-numpy", "", "Whether to generate numpy helpers." },
{ "", "ts-omit-entrypoint", "",
"Omit emission of namespace entrypoint file" },
{ "", "file-names-only", "",
"Print out generated file names without writing to the files" },
{ "", "grpc-filename-suffix", "SUFFIX",
"The suffix for the generated file names (Default is '.fb')." },
{ "", "grpc-additional-header", "",
"Additional headers to prepend to the generated files." },
{ "", "grpc-use-system-headers", "",
"Use <> for headers included from the generated code." },
{ "", "grpc-search-path", "PATH", "Prefix to any gRPC includes." },
{ "", "grpc-python-typed-handlers", "",
"The handlers will use the generated classes rather than raw bytes." },
{ "", "grpc-callback-api", "",
"Generate gRPC code using the callback (reactor) API instead of legacy "
"sync/async." },
{"o", "", "PATH", "Prefix PATH to all generated files."},
{"I", "", "PATH", "Search for includes in the specified path."},
{"M", "", "", "Print make rules for generated files."},
{"", "version", "", "Print the version number of flatc and exit."},
{"h", "help", "", "Prints this help text and exit."},
{"", "strict-json", "",
"Strict JSON: field names must be / will be quoted, no trailing commas in "
"tables/vectors."},
{"", "allow-non-utf8", "",
"Pass non-UTF-8 input through parser and emit nonstandard \\x escapes in "
"JSON. (Default is to raise parse error on non-UTF-8 input.)"},
{"", "natural-utf8", "",
"Output strings with UTF-8 as human-readable strings. By default, UTF-8 "
"characters are printed as \\uXXXX escapes."},
{"", "defaults-json", "",
"Output fields whose value is the default when writing JSON"},
{"", "unknown-json", "",
"Allow fields in JSON that are not defined in the schema. These fields "
"will be discarded when generating binaries."},
{"", "no-prefix", "",
"Don't prefix enum values with the enum type in C++."},
{"", "scoped-enums", "",
"Use C++11 style scoped and strongly typed enums. Also implies "
"--no-prefix."},
{"", "no-emit-min-max-enum-values", "",
"Disable generation of MIN and MAX enumerated values for scoped enums "
"and prefixed enums."},
{"", "swift-implementation-only", "",
"Adds a @_implementationOnly to swift imports"},
{"", "gen-includes", "",
"(deprecated), this is the default behavior. If the original behavior is "
"required (no include statements) use --no-includes."},
{"", "no-includes", "",
"Don't generate include statements for included schemas the generated "
"file depends on (C++, Python, Proto-to-Fbs)."},
{"", "gen-mutable", "",
"Generate accessors that can mutate buffers in-place."},
{"", "gen-onefile", "",
"Generate a single output file for C#, Go, Java, Kotlin and Python. "
"Implies --no-include."},
{"", "gen-name-strings", "",
"Generate type name functions for C++ and Rust."},
{"", "gen-object-api", "", "Generate an additional object-based API."},
{"", "gen-compare", "", "Generate operator== for object-based API types."},
{"", "gen-nullable", "",
"Add Clang _Nullable for C++ pointer. or @Nullable for Java"},
{"", "java-package-prefix", "",
"Add a prefix to the generated package name for Java."},
{"", "java-checkerframework", "", "Add @Pure for Java."},
{"", "gen-generated", "", "Add @Generated annotation for Java."},
{"", "gen-jvmstatic", "",
"Add @JvmStatic annotation for Kotlin methods in companion object for "
"interop from Java to Kotlin."},
{"", "gen-all", "",
"Generate not just code for the current schema files, but for all files "
"it "
"includes as well. If the language uses a single file for output (by "
"default the case for C++ and JS), all code will end up in this one "
"file."},
{"", "gen-json-emit", "",
"Generates encoding code which emits Flatbuffers into JSON"},
{"", "cpp-include", "", "Adds an #include in generated file."},
{"", "cpp-ptr-type", "T",
"Set object API pointer type (default std::unique_ptr)."},
{"", "cpp-str-type", "T",
"Set object API string type (default std::string). T::c_str(), "
"T::length() "
"and T::empty() must be supported. The custom type also needs to be "
"constructible from std::string (see the --cpp-str-flex-ctor option to "
"change this behavior)"},
{"", "cpp-str-flex-ctor", "",
"Don't construct custom string types by passing std::string from "
"Flatbuffers, but (char* + length)."},
{"", "cpp-field-case-style", "STYLE",
"Generate C++ fields using selected case style. Supported STYLE values: * "
"'unchanged' - leave unchanged (default) * 'upper' - schema snake_case "
"emits UpperCamel; * 'lower' - schema snake_case emits lowerCamel."},
{"", "cpp-std", "CPP_STD",
"Generate a C++ code using features of selected C++ standard. Supported "
"CPP_STD values: * 'c++0x' - generate code compatible with old compilers; "
"'c++11' - use C++11 code generator (default); * 'c++17' - use C++17 "
"features in generated code (experimental)."},
{"", "cpp-static-reflection", "",
"When using C++17, generate extra code to provide compile-time (static) "
"reflection of Flatbuffers types. Requires --cpp-std to be \"c++17\" or "
"higher."},
{"", "object-prefix", "PREFIX",
"Customize class prefix for C++ object-based API."},
{"", "object-suffix", "SUFFIX",
"Customize class suffix for C++ object-based API. Default Value is "
"\"T\"."},
{"", "go-namespace", "", "Generate the overriding namespace in Golang."},
{"", "go-import", "IMPORT",
"Generate the overriding import for flatbuffers in Golang (default is "
"\"github.com/google/flatbuffers/go\")."},
{"", "go-module-name", "",
"Prefix local import paths of generated go code with the module name"},
{"", "raw-binary", "",
"Allow binaries without file_identifier to be read. This may crash flatc "
"given a mismatched schema."},
{"", "size-prefixed", "", "Input binaries are size prefixed buffers."},
{"", "proto-namespace-suffix", "SUFFIX",
"Add this namespace to any flatbuffers generated from protobufs."},
{"", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions."},
{"", "keep-proto-id", "", "Keep protobuf field ids in generated fbs file."},
{"", "proto-id-gap", "",
"Action that should be taken when a gap between protobuf ids found. "
"Supported values: * "
"'nop' - do not care about gap * 'warn' - A warning message will be shown "
"about the gap in protobuf ids"
"(default) "
"* 'error' - An error message will be shown and the fbs generation will "
"be "
"interrupted."},
{"", "grpc", "", "Generate GRPC interfaces for the specified languages."},
{"", "schema", "", "Serialize schemas instead of JSON (use with -b)."},
{"", "bfbs-filenames", "PATH",
"Sets the root path where reflection filenames in reflection.fbs are "
"relative to. The 'root' is denoted with `//`. E.g. if PATH=/a/b/c "
"then /a/d/e.fbs will be serialized as //../d/e.fbs. (PATH defaults to "
"the "
"directory of the first provided schema file."},
{"", "bfbs-absolute-paths", "",
"Uses absolute paths instead of relative paths in the BFBS output."},
{"", "bfbs-comments", "", "Add doc comments to the binary schema files."},
{"", "bfbs-builtins", "",
"Add builtin attributes to the binary schema files."},
{"", "bfbs-gen-embed", "",
"Generate code to embed the bfbs schema to the source."},
{"", "conform", "FILE",
"Specify a schema the following schemas should be an evolution of. Gives "
"errors if not."},
{"", "conform-includes", "PATH",
"Include path for the schema given with --conform PATH"},
{"", "filename-suffix", "SUFFIX",
"The suffix appended to the generated file names (Default is "
"'_generated')."},
{"", "filename-ext", "EXT",
"The extension appended to the generated file names. Default is "
"language-specific (e.g., '.h' for C++)"},
{"", "include-prefix", "PATH",
"Prefix this PATH to any generated include statements."},
{"", "keep-prefix", "",
"Keep original prefix of schema include statement."},
{"", "reflect-types", "",
"Add minimal type reflection to code generation."},
{"", "reflect-names", "", "Add minimal type/name reflection."},
{"", "rust-serialize", "",
"Implement serde::Serialize on generated Rust types."},
{"", "rust-module-root-file", "",
"Generate rust code in individual files with a module root file."},
{"", "root-type", "T", "Select or override the default root_type."},
{"", "require-explicit-ids", "",
"When parsing schemas, require explicit ids (id: x)."},
{"", "force-defaults", "",
"Emit default values in binary output from JSON"},
{"", "force-empty", "",
"When serializing from object API representation, force strings and "
"vectors to empty rather than null."},
{"", "force-empty-vectors", "",
"When serializing from object API representation, force vectors to empty "
"rather than null."},
{"", "flexbuffers", "",
"Used with \"binary\" and \"json\" options, it generates data using "
"schema-less FlexBuffers."},
{"", "no-warnings", "", "Inhibit all warnings messages."},
{"", "warnings-as-errors", "", "Treat all warnings as errors."},
{"", "cs-global-alias", "",
"Prepend \"global::\" to all user generated csharp classes and "
"structs."},
{"", "cs-gen-json-serializer", "",
"Allows (de)serialization of JSON text in the Object API. (requires "
"--gen-object-api)."},
{"", "json-nested-bytes", "",
"Allow a nested_flatbuffer field to be parsed as a vector of bytes "
"in JSON, which is unsafe unless checked by a verifier afterwards."},
{"", "ts-flat-files", "",
"Generate a single typescript file per .fbs file. Implies "
"ts_entry_points."},
{"", "ts-entry-points", "",
"Generate entry point typescript per namespace. Implies gen-all."},
{"", "annotate-sparse-vectors", "", "Don't annotate every vector element."},
{"", "annotate", "SCHEMA",
"Annotate the provided BINARY_FILE with the specified SCHEMA file."},
{"", "no-leak-private-annotation", "",
"Prevents multiple type of annotations within a Fbs SCHEMA file. "
"Currently this is required to generate private types in Rust"},
{"", "python-no-type-prefix-suffix", "",
"Skip emission of Python functions that are prefixed with typenames"},
{"", "python-typing", "", "Generate Python type annotations"},
{"", "python-version", "", "Generate code for the given Python version."},
{"", "python-decode-obj-api-strings", "",
"Decode bytes to strings for the Python Object API"},
{"", "python-gen-numpy", "", "Whether to generate numpy helpers."},
{"", "ts-omit-entrypoint", "",
"Omit emission of namespace entrypoint file"},
{"", "file-names-only", "",
"Print out generated file names without writing to the files"},
{"", "grpc-filename-suffix", "SUFFIX",
"The suffix for the generated file names (Default is '.fb')."},
{"", "grpc-additional-header", "",
"Additional headers to prepend to the generated files."},
{"", "grpc-use-system-headers", "",
"Use <> for headers included from the generated code."},
{"", "grpc-search-path", "PATH", "Prefix to any gRPC includes."},
{"", "grpc-python-typed-handlers", "",
"The handlers will use the generated classes rather than raw bytes."},
{"", "grpc-callback-api", "",
"Generate gRPC code using the callback (reactor) API instead of legacy "
"sync/async."},
};
auto cmp = [](FlatCOption a, FlatCOption b) { return a.long_opt < b.long_opt; };
static std::set<FlatCOption, decltype(cmp)> language_options(cmp);
static void AppendTextWrappedString(std::stringstream &ss, std::string &text,
static void AppendTextWrappedString(std::stringstream& ss, std::string& text,
size_t max_col, size_t start_col) {
size_t max_line_length = max_col - start_col;
@@ -298,7 +306,7 @@ static void AppendTextWrappedString(std::stringstream &ss, std::string &text,
}
}
static void AppendOption(std::stringstream &ss, const FlatCOption &option,
static void AppendOption(std::stringstream& ss, const FlatCOption& option,
size_t max_col, size_t min_col_for_description) {
size_t chars = 2;
ss << " ";
@@ -337,26 +345,30 @@ static void AppendOption(std::stringstream &ss, const FlatCOption &option,
ss << "\n";
}
static void AppendShortOption(std::stringstream &ss,
const FlatCOption &option) {
static void AppendShortOption(std::stringstream& ss,
const FlatCOption& option) {
if (!option.short_opt.empty()) {
ss << "-" << option.short_opt;
if (!option.long_opt.empty()) { ss << "|"; }
if (!option.long_opt.empty()) {
ss << "|";
}
}
if (!option.long_opt.empty()) {
ss << "--" << option.long_opt;
}
if (!option.long_opt.empty()) { ss << "--" << option.long_opt; }
}
std::string FlatCompiler::GetShortUsageString(
const std::string &program_name) const {
const std::string& program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name << " [";
for (const FlatCOption &option : language_options) {
for (const FlatCOption& option : language_options) {
AppendShortOption(ss, option);
ss << ", ";
}
for (const FlatCOption &option : flatc_options) {
for (const FlatCOption& option : flatc_options) {
AppendShortOption(ss, option);
ss << ", ";
}
@@ -370,17 +382,17 @@ std::string FlatCompiler::GetShortUsageString(
}
std::string FlatCompiler::GetUsageString(
const std::string &program_name) const {
const std::string& program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name
<< " [OPTION]... FILE... [-- BINARY_FILE...]\n";
for (const FlatCOption &option : language_options) {
for (const FlatCOption& option : language_options) {
AppendOption(ss, option, 80, 25);
}
ss << "\n";
for (const FlatCOption &option : flatc_options) {
for (const FlatCOption& option : flatc_options) {
AppendOption(ss, option, 80, 25);
}
ss << "\n";
@@ -397,20 +409,20 @@ std::string FlatCompiler::GetUsageString(
return ss.str();
}
void FlatCompiler::AnnotateBinaries(const uint8_t *binary_schema,
void FlatCompiler::AnnotateBinaries(const uint8_t* binary_schema,
const uint64_t binary_schema_size,
const FlatCOptions &options) {
const std::string &schema_filename = options.annotate_schema;
const FlatCOptions& options) {
const std::string& schema_filename = options.annotate_schema;
for (const std::string &filename : options.filenames) {
for (const std::string& filename : options.filenames) {
std::string binary_contents;
if (!flatbuffers::LoadFile(filename.c_str(), true, &binary_contents)) {
Warn("unable to load binary file: " + filename);
continue;
}
const uint8_t *binary =
reinterpret_cast<const uint8_t *>(binary_contents.c_str());
const uint8_t* binary =
reinterpret_cast<const uint8_t*>(binary_contents.c_str());
const size_t binary_size = binary_contents.size();
const bool is_size_prefixed = options.opts.size_prefixed;
@@ -436,14 +448,16 @@ void FlatCompiler::AnnotateBinaries(const uint8_t *binary_schema,
}
FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
const char **argv) {
if (argc <= 1) { Error("Need to provide at least one argument."); }
const char** argv) {
if (argc <= 1) {
Error("Need to provide at least one argument.");
}
FlatCOptions options;
options.program_name = std::string(argv[0]);
IDLOptions &opts = options.opts;
IDLOptions& opts = options.opts;
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
@@ -741,7 +755,9 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
arg == "--grpc-callback-api=false") {
opts.grpc_callback_api = false;
} else {
if (arg == "--proto") { opts.proto_mode = true; }
if (arg == "--proto") {
opts.proto_mode = true;
}
auto code_generator_it = code_generators_.find(arg);
if (code_generator_it == code_generators_.end()) {
@@ -772,8 +788,8 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
return options;
}
void FlatCompiler::ValidateOptions(const FlatCOptions &options) {
const IDLOptions &opts = options.opts;
void FlatCompiler::ValidateOptions(const FlatCOptions& options) {
const IDLOptions& opts = options.opts;
if (!options.filenames.size()) Error("missing input files", false, true);
@@ -792,7 +808,7 @@ void FlatCompiler::ValidateOptions(const FlatCOptions &options) {
}
flatbuffers::Parser FlatCompiler::GetConformParser(
const FlatCOptions &options) {
const FlatCOptions& options) {
flatbuffers::Parser conform_parser;
// conform parser should check advanced options,
@@ -817,8 +833,8 @@ flatbuffers::Parser FlatCompiler::GetConformParser(
return conform_parser;
}
std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
Parser &conform_parser) {
std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions& options,
Parser& conform_parser) {
std::unique_ptr<Parser> parser =
std::unique_ptr<Parser>(new Parser(options.opts));
@@ -826,7 +842,7 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
file_it != options.filenames.end(); ++file_it) {
IDLOptions opts = options.opts;
auto &filename = *file_it;
auto& filename = *file_it;
std::string contents;
if (!flatbuffers::LoadFile(filename.c_str(), true, &contents))
Error("unable to load file: " + filename);
@@ -842,7 +858,7 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
reinterpret_cast<const uint8_t*>(contents.c_str()),
contents.length());
if (!options.raw_binary) {
// Generally reading binaries that do not correspond to the schema
@@ -882,7 +898,7 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
LoadBinarySchema(*parser, filename, contents);
} else if (opts.use_flexbuffers) {
if (opts.lang_to_generate == IDLOptions::kJson) {
auto data = reinterpret_cast<const uint8_t *>(contents.c_str());
auto data = reinterpret_cast<const uint8_t*>(contents.c_str());
auto size = contents.size();
std::vector<uint8_t> reuse_tracker;
if (!flexbuffers::VerifyBuffer(data, size, &reuse_tracker))
@@ -919,7 +935,7 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
// If one of the generators uses bfbs, serialize the parser and get
// the serialized buffer and length.
const uint8_t *bfbs_buffer = nullptr;
const uint8_t* bfbs_buffer = nullptr;
int64_t bfbs_length = 0;
if (options.requires_bfbs) {
parser->Serialize();
@@ -927,7 +943,7 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
bfbs_length = parser->builder_.GetSize();
}
for (const std::shared_ptr<CodeGenerator> &code_generator :
for (const std::shared_ptr<CodeGenerator>& code_generator :
options.generators) {
if (options.print_make_rules) {
std::string make_rule;
@@ -996,7 +1012,7 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
return parser;
}
int FlatCompiler::Compile(const FlatCOptions &options) {
int FlatCompiler::Compile(const FlatCOptions& options) {
// TODO(derekbailey): change to std::optional<Parser>
Parser conform_parser = GetConformParser(options);
@@ -1016,7 +1032,7 @@ int FlatCompiler::Compile(const FlatCOptions &options) {
Error("unable to load schema: " + options.annotate_schema);
}
const uint8_t *binary_schema = nullptr;
const uint8_t* binary_schema = nullptr;
uint64_t binary_schema_size = 0;
IDLOptions binary_opts;
@@ -1024,8 +1040,7 @@ int FlatCompiler::Compile(const FlatCOptions &options) {
Parser parser(binary_opts);
if (is_binary_schema) {
binary_schema =
reinterpret_cast<const uint8_t *>(schema_contents.c_str());
binary_schema = reinterpret_cast<const uint8_t*>(schema_contents.c_str());
binary_schema_size = schema_contents.size();
} else {
// If we need to generate the .bfbs file from the provided schema file
@@ -1057,7 +1072,7 @@ int FlatCompiler::Compile(const FlatCOptions &options) {
std::unique_ptr<Parser> parser = GenerateCode(options, conform_parser);
for (const auto &code_generator : options.generators) {
for (const auto& code_generator : options.generators) {
if (code_generator->SupportsRootFileGeneration()) {
code_generator->GenerateRootFile(*parser, options.output_path);
}
@@ -1067,7 +1082,7 @@ int FlatCompiler::Compile(const FlatCOptions &options) {
}
bool FlatCompiler::RegisterCodeGenerator(
const FlatCOption &option, std::shared_ptr<CodeGenerator> code_generator) {
const FlatCOption& option, std::shared_ptr<CodeGenerator> code_generator) {
if (!option.short_opt.empty() &&
code_generators_.find("-" + option.short_opt) != code_generators_.end()) {
Error("multiple generators registered under: -" + option.short_opt, false,
+54 -49
View File
@@ -40,18 +40,22 @@
#include "idl_gen_text.h"
#include "idl_gen_ts.h"
static const char *g_program_name = nullptr;
static const char* g_program_name = nullptr;
static void Warn(const flatbuffers::FlatCompiler *flatc,
const std::string &warn, bool show_exe_name) {
static void Warn(const flatbuffers::FlatCompiler* flatc,
const std::string& warn, bool show_exe_name) {
(void)flatc;
if (show_exe_name) { printf("%s: ", g_program_name); }
if (show_exe_name) {
printf("%s: ", g_program_name);
}
fprintf(stderr, "\nwarning:\n %s\n\n", warn.c_str());
}
static void Error(const flatbuffers::FlatCompiler *flatc,
const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) { printf("%s: ", g_program_name); }
static void Error(const flatbuffers::FlatCompiler* flatc,
const std::string& err, bool usage, bool show_exe_name) {
if (show_exe_name) {
printf("%s: ", g_program_name);
}
if (usage && flatc) {
fprintf(stderr, "%s\n", flatc->GetShortUsageString(g_program_name).c_str());
}
@@ -60,16 +64,16 @@ static void Error(const flatbuffers::FlatCompiler *flatc,
}
namespace flatbuffers {
void LogCompilerWarn(const std::string &warn) {
Warn(static_cast<const flatbuffers::FlatCompiler *>(nullptr), warn, true);
void LogCompilerWarn(const std::string& warn) {
Warn(static_cast<const flatbuffers::FlatCompiler*>(nullptr), warn, true);
}
void LogCompilerError(const std::string &err) {
Error(static_cast<const flatbuffers::FlatCompiler *>(nullptr), err, false,
void LogCompilerError(const std::string& err) {
Error(static_cast<const flatbuffers::FlatCompiler*>(nullptr), err, false,
true);
}
} // namespace flatbuffers
int main(int argc, const char *argv[]) {
int main(int argc, const char* argv[]) {
const std::string flatbuffers_version(flatbuffers::FLATBUFFERS_VERSION());
g_program_name = argv[0];
@@ -83,100 +87,101 @@ int main(int argc, const char *argv[]) {
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{
"b", "binary", "",
"Generate wire format binaries for any data definitions" },
"Generate wire format binaries for any data definitions"},
flatbuffers::NewBinaryCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "c", "cpp", "",
"Generate C++ headers for tables/structs" },
flatbuffers::FlatCOption{"c", "cpp", "",
"Generate C++ headers for tables/structs"},
flatbuffers::NewCppCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "n", "csharp", "",
"Generate C# classes for tables/structs" },
flatbuffers::FlatCOption{"n", "csharp", "",
"Generate C# classes for tables/structs"},
flatbuffers::NewCSharpCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "d", "dart", "",
"Generate Dart classes for tables/structs" },
flatbuffers::FlatCOption{"d", "dart", "",
"Generate Dart classes for tables/structs"},
flatbuffers::NewDartCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "proto", "",
"Input is a .proto, translate to .fbs" },
flatbuffers::FlatCOption{"", "proto", "",
"Input is a .proto, translate to .fbs"},
flatbuffers::NewFBSCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "g", "go", "",
"Generate Go files for tables/structs" },
flatbuffers::FlatCOption{"g", "go", "",
"Generate Go files for tables/structs"},
flatbuffers::NewGoCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "j", "java", "",
"Generate Java classes for tables/structs" },
flatbuffers::FlatCOption{"j", "java", "",
"Generate Java classes for tables/structs"},
flatbuffers::NewJavaCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "jsonschema", "", "Generate Json schema" },
flatbuffers::FlatCOption{"", "jsonschema", "", "Generate Json schema"},
flatbuffers::NewJsonSchemaCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "kotlin", "",
"Generate Kotlin classes for tables/structs" },
flatbuffers::FlatCOption{"", "kotlin", "",
"Generate Kotlin classes for tables/structs"},
flatbuffers::NewKotlinCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "kotlin-kmp", "",
"Generate Kotlin multiplatform classes for tables/structs" },
flatbuffers::FlatCOption{
"", "kotlin-kmp", "",
"Generate Kotlin multiplatform classes for tables/structs"},
flatbuffers::NewKotlinKMPCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "lobster", "",
"Generate Lobster files for tables/structs" },
flatbuffers::FlatCOption{"", "lobster", "",
"Generate Lobster files for tables/structs"},
flatbuffers::NewLobsterCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "l", "lua", "",
"Generate Lua files for tables/structs" },
flatbuffers::FlatCOption{"l", "lua", "",
"Generate Lua files for tables/structs"},
flatbuffers::NewLuaBfbsGenerator(flatbuffers_version));
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "nim", "",
"Generate Nim files for tables/structs" },
flatbuffers::FlatCOption{"", "nim", "",
"Generate Nim files for tables/structs"},
flatbuffers::NewNimBfbsGenerator(flatbuffers_version));
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "p", "python", "",
"Generate Python files for tables/structs" },
flatbuffers::FlatCOption{"p", "python", "",
"Generate Python files for tables/structs"},
flatbuffers::NewPythonCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "php", "",
"Generate PHP files for tables/structs" },
flatbuffers::FlatCOption{"", "php", "",
"Generate PHP files for tables/structs"},
flatbuffers::NewPhpCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "r", "rust", "",
"Generate Rust files for tables/structs" },
flatbuffers::FlatCOption{"r", "rust", "",
"Generate Rust files for tables/structs"},
flatbuffers::NewRustCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{
"t", "json", "", "Generate text output for any data definitions" },
flatbuffers::FlatCOption{"t", "json", "",
"Generate text output for any data definitions"},
flatbuffers::NewTextCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "swift", "",
"Generate Swift files for tables/structs" },
flatbuffers::FlatCOption{"", "swift", "",
"Generate Swift files for tables/structs"},
flatbuffers::NewSwiftCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "T", "ts", "",
"Generate TypeScript code for tables/structs" },
flatbuffers::FlatCOption{"T", "ts", "",
"Generate TypeScript code for tables/structs"},
flatbuffers::NewTsCodeGenerator());
// Create the FlatC options by parsing the command line arguments.
const flatbuffers::FlatCOptions &options =
const flatbuffers::FlatCOptions& options =
flatc.ParseFromCommandLineArguments(argc, argv);
// Compile with the extracted FlatC options.
+4 -4
View File
@@ -24,8 +24,8 @@
enum OutputFormat { kDecimal, kHexadecimal, kHexadecimal0x };
int main(int argc, char *argv[]) {
const char *name = argv[0];
int main(int argc, char* argv[]) {
const char* name = argv[0];
if (argc <= 1) {
printf("%s HASH [OPTION]... [--] STRING...\n", name);
printf("Available hashing algorithms:\n");
@@ -55,7 +55,7 @@ int main(int argc, char *argv[]) {
return 1;
}
const char *hash_algorithm = argv[1];
const char* hash_algorithm = argv[1];
flatbuffers::NamedHashFunction<uint16_t>::HashFunction hash_function16 =
flatbuffers::FindHashFunction16(hash_algorithm);
@@ -73,7 +73,7 @@ int main(int argc, char *argv[]) {
bool annotate = false;
bool escape_dash = false;
for (int i = 2; i < argc; i++) {
const char *arg = argv[i];
const char* arg = argv[i];
if (!escape_dash && arg[0] == '-') {
std::string opt = arg;
if (opt == "-d")
+21 -20
View File
@@ -33,17 +33,17 @@
namespace flatbuffers {
namespace {
static std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) {
static std::string BinaryFileName(const Parser& parser, const std::string& path,
const std::string& file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext;
}
static bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) {
static bool GenerateBinary(const Parser& parser, const std::string& path,
const std::string& file_name) {
if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer();
auto data_ptr = reinterpret_cast<char *>(data(data_vec));
auto data_ptr = reinterpret_cast<char*>(data(data_vec));
return !parser.flex_builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(), data_ptr,
@@ -52,12 +52,12 @@ static bool GenerateBinary(const Parser &parser, const std::string &path,
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(),
reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
reinterpret_cast<char*>(parser.builder_.GetBufferPointer()),
parser.builder_.GetSize(), true);
}
static std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
static std::string BinaryMakeRule(const Parser& parser, const std::string& path,
const std::string& file_name) {
if (!parser.builder_.GetSize()) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
@@ -73,36 +73,37 @@ static std::string BinaryMakeRule(const Parser &parser, const std::string &path,
class BinaryCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateBinary(parser, path, filename)) { return Status::ERROR; }
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
if (!GenerateBinary(parser, path, filename)) {
return Status::ERROR;
}
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
output = BinaryMakeRule(parser, path, filename);
return Status::OK;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+571 -417
View File
File diff suppressed because it is too large Load Diff
+291 -214
View File
File diff suppressed because it is too large Load Diff
+234 -176
View File
@@ -33,43 +33,45 @@ namespace dart {
namespace {
static Namer::Config DartDefaultConfig() {
return { /*types=*/Case::kUpperCamel,
/*constants=*/Case::kScreamingSnake,
/*methods=*/Case::kLowerCamel,
/*functions=*/Case::kUnknown, // unused.
/*fields=*/Case::kLowerCamel,
/*variables=*/Case::kLowerCamel,
/*variants=*/Case::kKeep,
/*enum_variant_seperator=*/".",
/*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
/*namespaces=*/Case::kSnake2,
/*namespace_seperator=*/".",
/*object_prefix=*/"",
/*object_suffix=*/"T",
/*keyword_prefix=*/"$",
/*keyword_suffix=*/"",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"_generated",
/*filename_extension=*/".dart" };
return {/*types=*/Case::kUpperCamel,
/*constants=*/Case::kScreamingSnake,
/*methods=*/Case::kLowerCamel,
/*functions=*/Case::kUnknown, // unused.
/*fields=*/Case::kLowerCamel,
/*variables=*/Case::kLowerCamel,
/*variants=*/Case::kKeep,
/*enum_variant_seperator=*/".",
/*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
/*namespaces=*/Case::kSnake2,
/*namespace_seperator=*/".",
/*object_prefix=*/"",
/*object_suffix=*/"T",
/*keyword_prefix=*/"$",
/*keyword_suffix=*/"",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"_generated",
/*filename_extension=*/".dart"};
}
static std::set<std::string> DartKeywords() {
// see https://www.dartlang.org/guides/language/language-tour#keywords
// yield*, async*, and sync* shouldn't be proble
return {
"abstract", "else", "import", "show", "as", "enum",
"in", "static", "assert", "export", "interface", "super",
"async", "extends", "is", "switch", "await", "extension",
"late", "sync", "break", "external", "library", "this",
"case", "factory", "mixin", "throw", "catch", "false",
"new", "true", "class", "final", "null", "try",
"const", "finally", "on", "typedef", "continue", "for",
"operator", "var", "covariant", "Function", "part", "void",
"default", "get", "required", "while", "deferred", "hide",
"rethrow", "with", "do", "if", "return", "yield",
"dynamic", "implements", "set",
"abstract", "else", "import", "show", "as",
"enum", "in", "static", "assert", "export",
"interface", "super", "async", "extends", "is",
"switch", "await", "extension", "late", "sync",
"break", "external", "library", "this", "case",
"factory", "mixin", "throw", "catch", "false",
"new", "true", "class", "final", "null",
"try", "const", "finally", "on", "typedef",
"continue", "for", "operator", "var", "covariant",
"Function", "part", "void", "default", "get",
"required", "while", "deferred", "hide", "rethrow",
"with", "do", "if", "return", "yield",
"dynamic", "implements", "set",
};
}
} // namespace
@@ -82,17 +84,17 @@ class DartGenerator : public BaseGenerator {
public:
typedef std::map<std::string, std::string> namespace_code_map;
DartGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
DartGenerator(const Parser& parser, const std::string& path,
const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", ".", "dart"),
namer_(WithFlagOptions(DartDefaultConfig(), parser.opts, path),
DartKeywords()) {}
template<typename T>
void import_generator(const std::vector<T *> &definitions,
const std::string &included,
std::set<std::string> &imports) {
for (const auto &item : definitions) {
template <typename T>
void import_generator(const std::vector<T*>& definitions,
const std::string& included,
std::set<std::string>& imports) {
for (const auto& item : definitions) {
if (item->file == included) {
std::string component = namer_.Namespace(*item->defined_namespace);
std::string filebase =
@@ -118,7 +120,7 @@ class DartGenerator : public BaseGenerator {
std::set<std::string> imports;
for (const auto &included_file : parser_.GetIncludedFiles()) {
for (const auto& included_file : parser_.GetIncludedFiles()) {
if (included_file.filename == parser_.file_being_parsed_) continue;
import_generator(parser_.structs_.vec, included_file.filename, imports);
@@ -126,7 +128,9 @@ class DartGenerator : public BaseGenerator {
}
std::string import_code = "";
for (const auto &file : imports) { import_code += file; }
for (const auto& file : imports) {
import_code += file;
}
import_code += import_code.empty() ? "" : "\n";
@@ -137,7 +141,9 @@ class DartGenerator : public BaseGenerator {
"// ignore_for_file: unused_import, unused_field, unused_element, "
"unused_local_variable, constant_identifier_names\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 +
@@ -156,18 +162,20 @@ class DartGenerator : public BaseGenerator {
code += kv->second;
if (!SaveFile(Filename(kv->first).c_str(), code, false)) { return false; }
if (!SaveFile(Filename(kv->first).c_str(), code, false)) {
return false;
}
}
return true;
}
std::string Filename(const std::string &suffix, bool path = true) const {
std::string Filename(const std::string& suffix, bool path = true) const {
return (path ? path_ : "") +
namer_.File(file_name_ + (suffix.empty() ? "" : "_" + suffix));
}
private:
static std::string ImportAliasName(const std::string &ns) {
static std::string ImportAliasName(const std::string& ns) {
std::string ret;
ret.assign(ns);
size_t pos = ret.find('.');
@@ -179,25 +187,25 @@ class DartGenerator : public BaseGenerator {
return ret;
}
void GenerateEnums(namespace_code_map &namespace_code) {
void GenerateEnums(namespace_code_map& namespace_code) {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
auto& enum_def = **it;
GenEnum(enum_def, namespace_code);
}
}
void GenerateStructs(namespace_code_map &namespace_code) {
void GenerateStructs(namespace_code_map& namespace_code) {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
auto& struct_def = **it;
GenStruct(struct_def, namespace_code);
}
}
// Generate a documentation comment, if available.
static void GenDocComment(const std::vector<std::string> &dc,
const char *indent, std::string &code) {
static void GenDocComment(const std::vector<std::string>& dc,
const char* indent, std::string& code) {
for (auto it = dc.begin(); it != dc.end(); ++it) {
if (indent) code += indent;
code += "/// " + *it + "\n";
@@ -205,9 +213,9 @@ class DartGenerator : public BaseGenerator {
}
// Generate an enum declaration and an enum string lookup table.
void GenEnum(EnumDef &enum_def, namespace_code_map &namespace_code) {
void GenEnum(EnumDef& enum_def, namespace_code_map& namespace_code) {
if (enum_def.generated) return;
std::string &code =
std::string& code =
namespace_code[namer_.Namespace(*enum_def.defined_namespace)];
GenDocComment(enum_def.doc_comment, "", code);
@@ -222,12 +230,14 @@ class DartGenerator : public BaseGenerator {
code += "enum " + enum_type + " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
auto& ev = **it;
const auto enum_var = namer_.Variant(ev);
if (it != enum_def.Vals().begin()) code += ",\n";
code += " " + enum_var + "(" + enum_def.ToString(ev) + ")";
}
if (auto_default) { code += ",\n _default(0)"; }
if (auto_default) {
code += ",\n _default(0)";
}
code += ";\n\n";
code += " final int value;\n";
@@ -235,7 +245,7 @@ class DartGenerator : public BaseGenerator {
code += " factory " + enum_type + ".fromValue(int value) {\n";
code += " switch (value) {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
auto& ev = **it;
const auto enum_var = namer_.Variant(ev);
code += " case " + enum_def.ToString(ev) + ":";
code += " return " + enum_type + "." + enum_var + ";\n";
@@ -268,8 +278,8 @@ class DartGenerator : public BaseGenerator {
GenEnumReader(enum_def, enum_type, code);
}
void GenEnumReader(EnumDef &enum_def, const std::string &enum_type,
std::string &code) {
void GenEnumReader(EnumDef& enum_def, const std::string& enum_type,
std::string& code) {
code += "class _" + enum_type + "Reader extends " + _kFb + ".Reader<" +
enum_type + "> {\n";
code += " const _" + enum_type + "Reader();\n\n";
@@ -283,48 +293,69 @@ class DartGenerator : public BaseGenerator {
code += "}\n\n";
}
std::string GenType(const Type &type) {
std::string GenType(const Type& type) {
switch (type.base_type) {
case BASE_TYPE_BOOL: return "Bool";
case BASE_TYPE_CHAR: return "Int8";
case BASE_TYPE_BOOL:
return "Bool";
case BASE_TYPE_CHAR:
return "Int8";
case BASE_TYPE_UTYPE:
case BASE_TYPE_UCHAR: return "Uint8";
case BASE_TYPE_SHORT: return "Int16";
case BASE_TYPE_USHORT: return "Uint16";
case BASE_TYPE_INT: return "Int32";
case BASE_TYPE_UINT: return "Uint32";
case BASE_TYPE_LONG: return "Int64";
case BASE_TYPE_ULONG: return "Uint64";
case BASE_TYPE_FLOAT: return "Float32";
case BASE_TYPE_DOUBLE: return "Float64";
case BASE_TYPE_STRING: return "String";
case BASE_TYPE_VECTOR: return GenType(type.VectorType());
case BASE_TYPE_STRUCT: return namer_.Type(*type.struct_def);
case BASE_TYPE_UNION: return namer_.Type(*type.enum_def) + "TypeId";
default: return "Table";
case BASE_TYPE_UCHAR:
return "Uint8";
case BASE_TYPE_SHORT:
return "Int16";
case BASE_TYPE_USHORT:
return "Uint16";
case BASE_TYPE_INT:
return "Int32";
case BASE_TYPE_UINT:
return "Uint32";
case BASE_TYPE_LONG:
return "Int64";
case BASE_TYPE_ULONG:
return "Uint64";
case BASE_TYPE_FLOAT:
return "Float32";
case BASE_TYPE_DOUBLE:
return "Float64";
case BASE_TYPE_STRING:
return "String";
case BASE_TYPE_VECTOR:
return GenType(type.VectorType());
case BASE_TYPE_STRUCT:
return namer_.Type(*type.struct_def);
case BASE_TYPE_UNION:
return namer_.Type(*type.enum_def) + "TypeId";
default:
return "Table";
}
}
static std::string EnumSize(const Type &type) {
static std::string EnumSize(const Type& type) {
switch (type.base_type) {
case BASE_TYPE_BOOL:
case BASE_TYPE_CHAR:
case BASE_TYPE_UTYPE:
case BASE_TYPE_UCHAR: return "1";
case BASE_TYPE_UCHAR:
return "1";
case BASE_TYPE_SHORT:
case BASE_TYPE_USHORT: return "2";
case BASE_TYPE_USHORT:
return "2";
case BASE_TYPE_INT:
case BASE_TYPE_UINT:
case BASE_TYPE_FLOAT: return "4";
case BASE_TYPE_FLOAT:
return "4";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
case BASE_TYPE_DOUBLE: return "8";
default: return "1";
case BASE_TYPE_DOUBLE:
return "8";
default:
return "1";
}
}
std::string GenReaderTypeName(const Type &type, Namespace *current_namespace,
const FieldDef &def,
std::string GenReaderTypeName(const Type& type, Namespace* current_namespace,
const FieldDef& def,
bool parent_is_vector = false, bool lazy = true,
bool constConstruct = true) {
std::string prefix = (constConstruct ? "const " : "") + _kFb;
@@ -357,8 +388,8 @@ class DartGenerator : public BaseGenerator {
}
}
std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
const FieldDef &def,
std::string GenDartTypeName(const Type& type, Namespace* current_namespace,
const FieldDef& def,
std::string struct_type_suffix = "") {
if (type.enum_def) {
if (type.enum_def->is_union && type.base_type != BASE_TYPE_UNION) {
@@ -371,7 +402,8 @@ class DartGenerator : public BaseGenerator {
}
switch (type.base_type) {
case BASE_TYPE_BOOL: return "bool";
case BASE_TYPE_BOOL:
return "bool";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
case BASE_TYPE_INT:
@@ -379,10 +411,13 @@ class DartGenerator : public BaseGenerator {
case BASE_TYPE_SHORT:
case BASE_TYPE_USHORT:
case BASE_TYPE_CHAR:
case BASE_TYPE_UCHAR: return "int";
case BASE_TYPE_UCHAR:
return "int";
case BASE_TYPE_FLOAT:
case BASE_TYPE_DOUBLE: return "double";
case BASE_TYPE_STRING: return "String";
case BASE_TYPE_DOUBLE:
return "double";
case BASE_TYPE_STRING:
return "String";
case BASE_TYPE_STRUCT:
return MaybeWrapNamespace(
namer_.Type(*type.struct_def) + struct_type_suffix,
@@ -392,12 +427,14 @@ class DartGenerator : public BaseGenerator {
GenDartTypeName(type.VectorType(), current_namespace, def,
struct_type_suffix) +
">";
default: assert(0); return "dynamic";
default:
assert(0);
return "dynamic";
}
}
std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
const FieldDef &def, bool nullable,
std::string GenDartTypeName(const Type& type, Namespace* current_namespace,
const FieldDef& def, bool nullable,
std::string struct_type_suffix) {
std::string typeName =
GenDartTypeName(type, current_namespace, def, struct_type_suffix);
@@ -405,9 +442,9 @@ class DartGenerator : public BaseGenerator {
return typeName;
}
std::string MaybeWrapNamespace(const std::string &type_name,
Namespace *current_ns,
const FieldDef &field) const {
std::string MaybeWrapNamespace(const std::string& type_name,
Namespace* current_ns,
const FieldDef& field) const {
const std::string current_namespace = namer_.Namespace(*current_ns);
const std::string field_namespace =
field.value.type.struct_def
@@ -424,14 +461,14 @@ class DartGenerator : public BaseGenerator {
}
// Generate an accessor struct with constructor for a flatbuffers struct.
void GenStruct(const StructDef &struct_def,
namespace_code_map &namespace_code) {
void GenStruct(const StructDef& struct_def,
namespace_code_map& namespace_code) {
if (struct_def.generated) return;
std::string &code =
std::string& code =
namespace_code[namer_.Namespace(*struct_def.defined_namespace)];
const auto &struct_type = namer_.Type(struct_def);
const auto& struct_type = namer_.Type(struct_def);
// Emit constructor
@@ -461,10 +498,10 @@ class DartGenerator : public BaseGenerator {
code += " final " + _kFb + ".BufferContext _bc;\n";
code += " final int _bcOffset;\n\n";
std::vector<std::pair<int, FieldDef *>> non_deprecated_fields;
std::vector<std::pair<int, FieldDef*>> non_deprecated_fields;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
FieldDef &field = **it;
FieldDef& field = **it;
if (field.deprecated) continue;
auto offset = static_cast<int>(it - struct_def.fields.vec.begin());
non_deprecated_fields.push_back(std::make_pair(offset, &field));
@@ -500,8 +537,8 @@ class DartGenerator : public BaseGenerator {
// Generate an accessor struct with constructor for a flatbuffers struct.
std::string GenStructObjectAPI(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string code;
GenDocComment(struct_def.doc_comment, "", code);
@@ -511,7 +548,7 @@ class DartGenerator : public BaseGenerator {
std::string constructor_args;
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
const std::string defaultValue = getDefaultValue(field.value);
@@ -528,7 +565,7 @@ class DartGenerator : public BaseGenerator {
constructor_args += "this." + field_name;
if (!struct_def.fixed && !defaultValue.empty()) {
if (IsEnum(field.value.type)) {
auto &enum_def = *field.value.type.enum_def;
auto& enum_def = *field.value.type.enum_def;
if (auto val = enum_def.FindByValue(defaultValue)) {
constructor_args += " = " + namer_.EnumVariant(enum_def, *val);
} else {
@@ -554,18 +591,18 @@ class DartGenerator : public BaseGenerator {
// Generate function `StructNameT unpack()`
std::string GenStructObjectAPIUnpack(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string constructor_args;
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (!constructor_args.empty()) constructor_args += ",\n";
constructor_args += " " + field_name + ": ";
const Type &type = field.value.type;
const Type& type = field.value.type;
std::string defaultValue = getDefaultValue(field.value);
bool isNullable = defaultValue.empty() && !struct_def.fixed;
std::string nullableValueAccessOperator = isNullable ? "?" : "";
@@ -601,8 +638,8 @@ class DartGenerator : public BaseGenerator {
// Generate function `StructNameT pack()`
std::string GenStructObjectAPIPack(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string code;
code += " @override\n";
@@ -613,8 +650,8 @@ class DartGenerator : public BaseGenerator {
return code;
}
std::string NamespaceAliasFromUnionType(Namespace *root_namespace,
const Type &type) {
std::string NamespaceAliasFromUnionType(Namespace* root_namespace,
const Type& type) {
const std::vector<std::string> qualified_name_parts =
type.struct_def->defined_namespace->components;
if (std::equal(root_namespace->components.begin(),
@@ -627,7 +664,7 @@ class DartGenerator : public BaseGenerator {
for (auto it = qualified_name_parts.begin();
it != qualified_name_parts.end(); ++it) {
auto &part = *it;
auto& part = *it;
for (size_t i = 0; i < part.length(); i++) {
if (i && !isdigit(part[i]) && part[i] == CharToUpper(part[i])) {
@@ -637,19 +674,21 @@ class DartGenerator : public BaseGenerator {
ns += CharToLower(part[i]);
}
}
if (it != qualified_name_parts.end() - 1) { ns += "_"; }
if (it != qualified_name_parts.end() - 1) {
ns += "_";
}
}
return ns + "." + namer_.Type(*type.struct_def);
}
void GenImplementationGetters(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
std::string &code) {
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
std::string& code) {
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
const std::string defaultValue = getDefaultValue(field.value);
@@ -664,10 +703,10 @@ class DartGenerator : public BaseGenerator {
if (field.value.type.base_type == BASE_TYPE_UNION) {
code += " {\n";
code += " switch (" + field_name + "Type?.value) {\n";
const auto &enum_def = *field.value.type.enum_def;
const auto& enum_def = *field.value.type.enum_def;
for (auto en_it = enum_def.Vals().begin() + 1;
en_it != enum_def.Vals().end(); ++en_it) {
const auto &ev = **en_it;
const auto& ev = **en_it;
const auto enum_name = NamespaceAliasFromUnionType(
enum_def.defined_namespace, ev.union_type);
code += " case " + enum_def.ToString(ev) + ": return " +
@@ -713,8 +752,8 @@ class DartGenerator : public BaseGenerator {
}
std::string GenToString(
const std::string &object_name,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
const std::string& object_name,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string code;
code += " @override\n";
code += " String toString() {\n";
@@ -730,16 +769,20 @@ class DartGenerator : public BaseGenerator {
escaped_field.push_back(field[i]);
}
code += escaped_field + ": ${" + field + "}";
if (it != non_deprecated_fields.end() - 1) { code += ", "; }
if (it != non_deprecated_fields.end() - 1) {
code += ", ";
}
}
code += "}';\n";
code += " }\n";
return code;
}
std::string getDefaultValue(const Value &value) const {
std::string getDefaultValue(const Value& value) const {
if (!value.constant.empty() && value.constant != "0") {
if (IsBool(value.type.base_type)) { return "true"; }
if (IsBool(value.type.base_type)) {
return "true";
}
if (IsScalar(value.type.base_type)) {
if (StringIsFlatbufferNan(value.constant)) {
return "double.nan";
@@ -759,8 +802,8 @@ class DartGenerator : public BaseGenerator {
}
}
void GenReader(const StructDef &struct_def, const std::string &reader_name,
std::string &code) {
void GenReader(const StructDef& struct_def, const std::string& reader_name,
std::string& code) {
const auto struct_type = namer_.Type(struct_def);
code += "class " + reader_name + " extends " + _kFb;
@@ -784,10 +827,12 @@ class DartGenerator : public BaseGenerator {
}
void GenBuilder(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
const std::string &builder_name, std::string &code) {
if (non_deprecated_fields.size() == 0) { return; }
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
const std::string& builder_name, std::string& code) {
if (non_deprecated_fields.size() == 0) {
return;
}
code += "class " + builder_name + " {\n";
code += " " + builder_name + "(this.fbBuilder);\n\n";
@@ -803,13 +848,13 @@ class DartGenerator : public BaseGenerator {
}
void StructBuilderBody(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
std::string &code) {
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
std::string& code) {
code += " int finish(";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (IsStruct(field.value.type)) {
@@ -819,13 +864,15 @@ class DartGenerator : public BaseGenerator {
field);
}
code += " " + field_name;
if (it != non_deprecated_fields.end() - 1) { code += ", "; }
if (it != non_deprecated_fields.end() - 1) {
code += ", ";
}
}
code += ") {\n";
for (auto it = non_deprecated_fields.rbegin();
it != non_deprecated_fields.rend(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (field.padding) {
@@ -837,7 +884,9 @@ class DartGenerator : public BaseGenerator {
} else {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
code += field_name;
if (field.value.type.enum_def) { code += ".value"; }
if (field.value.type.enum_def) {
code += ".value";
}
code += ");\n";
}
}
@@ -846,9 +895,9 @@ class DartGenerator : public BaseGenerator {
}
void TableBuilderBody(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
std::string &code) {
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
std::string& code) {
code += " void begin() {\n";
code += " fbBuilder.startTable(" +
NumToString(struct_def.fields.vec.size()) + ");\n";
@@ -856,7 +905,7 @@ class DartGenerator : public BaseGenerator {
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const auto &field = *it->second;
const auto& field = *it->second;
const auto offset = it->first;
const std::string add_field = namer_.Method("add", field);
const std::string field_var = namer_.Variable(field);
@@ -869,7 +918,9 @@ class DartGenerator : public BaseGenerator {
code += " fbBuilder.add" + GenType(field.value.type) + "(" +
NumToString(offset) + ", ";
code += field_var;
if (field.value.type.enum_def) { code += "?.value"; }
if (field.value.type.enum_def) {
code += "?.value";
}
code += ");\n";
} else if (IsStruct(field.value.type)) {
code += " int " + add_field + "(int offset) {\n";
@@ -891,13 +942,13 @@ class DartGenerator : public BaseGenerator {
}
void GenObjectBuilder(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
const std::string &builder_name, std::string &code) {
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
const std::string& builder_name, std::string& code) {
code += "class " + builder_name + " extends " + _kFb + ".ObjectBuilder {\n";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
code += " final " +
GenDartTypeName(field.value.type, struct_def.defined_namespace,
@@ -911,7 +962,7 @@ class DartGenerator : public BaseGenerator {
code += "{\n";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
code += " ";
code += (struct_def.fixed ? "required " : "") +
@@ -923,7 +974,7 @@ class DartGenerator : public BaseGenerator {
code += " : ";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
code += "_" + namer_.Variable(field) + " = " + namer_.Variable(field);
if (it == non_deprecated_fields.end() - 1) {
@@ -954,13 +1005,13 @@ class DartGenerator : public BaseGenerator {
}
std::string GenObjectBuilderImplementation(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
bool prependUnderscore = true, bool pack = false) {
std::string code;
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type))
continue;
@@ -1029,13 +1080,13 @@ class DartGenerator : public BaseGenerator {
}
std::string StructObjectBuilderBody(
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
bool prependUnderscore = true, bool pack = false) {
std::string code;
for (auto it = non_deprecated_fields.rbegin();
it != non_deprecated_fields.rend(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (field.padding) {
@@ -1044,13 +1095,19 @@ class DartGenerator : public BaseGenerator {
if (IsStruct(field.value.type)) {
code += " ";
if (prependUnderscore) { code += "_"; }
if (prependUnderscore) {
code += "_";
}
code += field_name + (pack ? ".pack" : ".finish") + "(fbBuilder);\n";
} else {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
if (prependUnderscore) { code += "_"; }
if (prependUnderscore) {
code += "_";
}
code += field_name;
if (field.value.type.enum_def) { code += ".value"; }
if (field.value.type.enum_def) {
code += ".value";
}
code += ");\n";
}
}
@@ -1060,8 +1117,8 @@ class DartGenerator : public BaseGenerator {
}
std::string TableObjectBuilderBody(
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
const StructDef& struct_def,
const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
bool prependUnderscore = true, bool pack = false) {
std::string code;
code += " fbBuilder.startTable(" +
@@ -1069,7 +1126,7 @@ class DartGenerator : public BaseGenerator {
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
const FieldDef& field = *it->second;
auto offset = it->first;
std::string field_var =
@@ -1101,14 +1158,14 @@ class DartGenerator : public BaseGenerator {
};
} // namespace dart
static bool GenerateDart(const Parser &parser, const std::string &path,
const std::string &file_name) {
static bool GenerateDart(const Parser& parser, const std::string& path,
const std::string& file_name) {
dart::DartGenerator generator(parser, path, file_name);
return generator.generate();
}
static std::string DartMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
static std::string DartMakeRule(const Parser& parser, const std::string& path,
const std::string& file_name) {
auto filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
dart::DartGenerator generator(parser, path, file_name);
@@ -1125,34 +1182,35 @@ namespace {
class DartCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateDart(parser, path, filename)) { return Status::ERROR; }
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
if (!GenerateDart(parser, path, filename)) {
return Status::ERROR;
}
return Status::OK;
}
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
output = DartMakeRule(parser, path, filename);
return Status::OK;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+88 -64
View File
@@ -30,12 +30,13 @@
namespace flatbuffers {
namespace {
static std::string GenType(const Type &type, bool underlying = false) {
static std::string GenType(const Type& type, bool underlying = false) {
switch (type.base_type) {
case BASE_TYPE_STRUCT:
return type.struct_def->defined_namespace->GetFullyQualifiedName(
type.struct_def->name);
case BASE_TYPE_VECTOR: return "[" + GenType(type.VectorType()) + "]";
case BASE_TYPE_VECTOR:
return "[" + GenType(type.VectorType()) + "]";
default:
if (type.enum_def && !underlying) {
return type.enum_def->defined_namespace->GetFullyQualifiedName(
@@ -46,11 +47,11 @@ static std::string GenType(const Type &type, bool underlying = false) {
}
}
static bool HasFieldWithId(const std::vector<FieldDef *> &fields) {
static bool HasFieldWithId(const std::vector<FieldDef*>& fields) {
static const std::string ID = "id";
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
for (const auto* field : fields) {
const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
return true;
}
@@ -58,81 +59,93 @@ static bool HasFieldWithId(const std::vector<FieldDef *> &fields) {
return false;
}
static bool HasNonPositiveFieldId(const std::vector<FieldDef *> &fields) {
static bool HasNonPositiveFieldId(const std::vector<FieldDef*>& fields) {
static const std::string ID = "id";
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
for (const auto* field : fields) {
const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
if (!done) { return true; }
if (!done) {
return true;
}
}
}
return false;
}
static bool HasFieldIdFromReservedIds(
const std::vector<FieldDef *> &fields,
const std::vector<voffset_t> &reserved_ids) {
const std::vector<FieldDef*>& fields,
const std::vector<voffset_t>& reserved_ids) {
static const std::string ID = "id";
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
for (const auto* field : fields) {
const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
if (!done) { return true; }
if (!done) {
return true;
}
auto id_it =
std::find(std::begin(reserved_ids), std::end(reserved_ids), proto_id);
if (id_it != reserved_ids.end()) { return true; }
if (id_it != reserved_ids.end()) {
return true;
}
}
}
return false;
}
static std::vector<voffset_t> ExtractProtobufIds(
const std::vector<FieldDef *> &fields) {
const std::vector<FieldDef*>& fields) {
static const std::string ID = "id";
std::vector<voffset_t> used_proto_ids;
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
for (const auto* field : fields) {
const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
if (done) { used_proto_ids.push_back(proto_id); }
if (done) {
used_proto_ids.push_back(proto_id);
}
}
}
return used_proto_ids;
}
static bool HasTwiceUsedId(const std::vector<FieldDef *> &fields) {
static bool HasTwiceUsedId(const std::vector<FieldDef*>& fields) {
std::vector<voffset_t> used_proto_ids = ExtractProtobufIds(fields);
std::sort(std::begin(used_proto_ids), std::end(used_proto_ids));
for (auto it = std::next(std::begin(used_proto_ids));
it != std::end(used_proto_ids); it++) {
if (*it == *std::prev(it)) { return true; }
if (*it == *std::prev(it)) {
return true;
}
}
return false;
}
static bool HasGapInProtoId(const std::vector<FieldDef *> &fields) {
static bool HasGapInProtoId(const std::vector<FieldDef*>& fields) {
std::vector<voffset_t> used_proto_ids = ExtractProtobufIds(fields);
std::sort(std::begin(used_proto_ids), std::end(used_proto_ids));
for (auto it = std::next(std::begin(used_proto_ids));
it != std::end(used_proto_ids); it++) {
if (*it != *std::prev(it) + 1) { return true; }
if (*it != *std::prev(it) + 1) {
return true;
}
}
return false;
}
static bool ProtobufIdSanityCheck(const StructDef &struct_def,
static bool ProtobufIdSanityCheck(const StructDef& struct_def,
IDLOptions::ProtoIdGapAction gap_action,
bool no_log = false) {
const auto &fields = struct_def.fields.vec;
const auto& fields = struct_def.fields.vec;
if (HasNonPositiveFieldId(fields)) {
// TODO: Use LogCompilerWarn
if (!no_log) {
@@ -167,7 +180,9 @@ static bool ProtobufIdSanityCheck(const StructDef &struct_def,
fprintf(stderr, "Fields in struct %s have gap between ids\n",
struct_def.name.c_str());
}
if (gap_action == IDLOptions::ProtoIdGapAction::ERROR) { return false; }
if (gap_action == IDLOptions::ProtoIdGapAction::ERROR) {
return false;
}
}
}
@@ -184,9 +199,9 @@ struct ProtobufToFbsIdMap {
};
static ProtobufToFbsIdMap MapProtoIdsToFieldsId(
const StructDef &struct_def, IDLOptions::ProtoIdGapAction gap_action,
const StructDef& struct_def, IDLOptions::ProtoIdGapAction gap_action,
bool no_log) {
const auto &fields = struct_def.fields.vec;
const auto& fields = struct_def.fields.vec;
if (!HasFieldWithId(fields)) {
ProtobufToFbsIdMap result;
@@ -194,14 +209,16 @@ static ProtobufToFbsIdMap MapProtoIdsToFieldsId(
return result;
}
if (!ProtobufIdSanityCheck(struct_def, gap_action, no_log)) { return {}; }
if (!ProtobufIdSanityCheck(struct_def, gap_action, no_log)) {
return {};
}
static constexpr int UNION_ID = -1;
using ProtoIdFieldNamePair = std::pair<int, std::string>;
std::vector<ProtoIdFieldNamePair> proto_ids;
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup("id");
for (const auto* field : fields) {
const auto* id_attribute = field->attributes.Lookup("id");
if (id_attribute != nullptr) {
// When we have union but do not use union flag to keep them
if (id_attribute->constant.empty() &&
@@ -224,25 +241,27 @@ static ProtobufToFbsIdMap MapProtoIdsToFieldsId(
std::sort(
std::begin(proto_ids), std::end(proto_ids),
[](const ProtoIdFieldNamePair &rhs, const ProtoIdFieldNamePair &lhs) {
[](const ProtoIdFieldNamePair& rhs, const ProtoIdFieldNamePair& lhs) {
return rhs.first < lhs.first;
});
struct ProtobufToFbsIdMap proto_to_fbs;
voffset_t id = 0;
for (const auto &element : proto_ids) {
if (element.first == UNION_ID) { id++; }
for (const auto& element : proto_ids) {
if (element.first == UNION_ID) {
id++;
}
proto_to_fbs.field_to_id.emplace(element.second, id++);
}
proto_to_fbs.successful = true;
return proto_to_fbs;
}
static void GenNameSpace(const Namespace &name_space, std::string *_schema,
const Namespace **last_namespace) {
static void GenNameSpace(const Namespace& name_space, std::string* _schema,
const Namespace** last_namespace) {
if (*last_namespace == &name_space) return;
*last_namespace = &name_space;
auto &schema = *_schema;
auto& schema = *_schema;
schema += "namespace ";
for (auto it = name_space.components.begin();
it != name_space.components.end(); ++it) {
@@ -253,14 +272,14 @@ static void GenNameSpace(const Namespace &name_space, std::string *_schema,
}
// Generate a flatbuffer schema from the Parser's internal representation.
static std::string GenerateFBS(const Parser &parser,
const std::string &file_name,
static std::string GenerateFBS(const Parser& parser,
const std::string& file_name,
bool no_log = false) {
// Proto namespaces may clash with table names, escape the ones that were
// generated from a table:
for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end();
++it) {
auto &ns = **it;
auto& ns = **it;
for (size_t i = 0; i < ns.from_table; i++) {
ns.components[ns.components.size() - 1 - i] += "_";
}
@@ -298,10 +317,10 @@ static std::string GenerateFBS(const Parser &parser,
}
// Generate code for all the enum declarations.
const Namespace *last_namespace = nullptr;
const Namespace* last_namespace = nullptr;
for (auto enum_def_it = parser.enums_.vec.begin();
enum_def_it != parser.enums_.vec.end(); ++enum_def_it) {
EnumDef &enum_def = **enum_def_it;
EnumDef& enum_def = **enum_def_it;
if (parser.opts.include_dependence_headers && enum_def.generated) {
continue;
}
@@ -316,7 +335,7 @@ static std::string GenerateFBS(const Parser &parser,
schema += GenType(enum_def.underlying_type, true) + " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
auto& ev = **it;
GenComment(ev.doc_comment, &schema, nullptr, " ");
if (enum_def.is_union) {
schema += " " + GenType(ev.union_type) + ",\n";
@@ -329,10 +348,12 @@ static std::string GenerateFBS(const Parser &parser,
// Generate code for all structs/tables.
for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
++it) {
StructDef &struct_def = **it;
StructDef& struct_def = **it;
const auto proto_fbs_ids = MapProtoIdsToFieldsId(
struct_def, parser.opts.proto_id_gap_action, no_log);
if (!proto_fbs_ids.successful) { return {}; }
if (!proto_fbs_ids.successful) {
return {};
}
if (parser.opts.include_dependence_headers && struct_def.generated) {
continue;
@@ -343,7 +364,7 @@ static std::string GenerateFBS(const Parser &parser,
schema += "table " + struct_def.name + " {\n";
for (auto field_it = struct_def.fields.vec.begin();
field_it != struct_def.fields.vec.end(); ++field_it) {
auto &field = **field_it;
auto& field = **field_it;
if (field.value.type.base_type != BASE_TYPE_UTYPE) {
GenComment(field.doc_comment, &schema, nullptr, " ");
schema += " " + field.name + ":" + GenType(field.value.type);
@@ -361,7 +382,7 @@ static std::string GenerateFBS(const Parser &parser,
if (!attributes.empty()) {
schema += " (";
for (const auto &attribute : attributes) {
for (const auto& attribute : attributes) {
schema += attribute + ",";
}
schema.pop_back();
@@ -376,10 +397,12 @@ static std::string GenerateFBS(const Parser &parser,
return schema;
}
static bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name, bool no_log = false) {
static bool GenerateFBS(const Parser& parser, const std::string& path,
const std::string& file_name, bool no_log = false) {
const std::string fbs = GenerateFBS(parser, file_name, no_log);
if (fbs.empty()) { return false; }
if (fbs.empty()) {
return false;
}
// TODO: Use LogCompilerWarn
if (!no_log) {
fprintf(stderr,
@@ -393,28 +416,29 @@ class FBSCodeGenerator : public CodeGenerator {
public:
explicit FBSCodeGenerator(const bool no_log) : no_log_(no_log) {}
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateFBS(parser, path, filename, no_log_)) { return Status::ERROR; }
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
if (!GenerateFBS(parser, path, filename, no_log_)) {
return Status::ERROR;
}
return Status::OK;
}
Status GenerateCodeString(const Parser &parser, const std::string &filename,
std::string &output) override {
Status GenerateCodeString(const Parser& parser, const std::string& filename,
std::string& output) override {
output = GenerateFBS(parser, filename, no_log_);
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -422,16 +446,16 @@ class FBSCodeGenerator : public CodeGenerator {
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+294 -258
View File
File diff suppressed because it is too large Load Diff
+53 -51
View File
@@ -30,8 +30,8 @@
#include "src/compiler/ts_generator.h"
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4512) // C4512: 'class' : assignment operator could
#pragma warning(push)
#pragma warning(disable : 4512) // C4512: 'class' : assignment operator could
// not be generated
#endif
@@ -41,7 +41,7 @@ class FlatBufMethod : public grpc_generator::Method {
public:
enum Streaming { kNone, kClient, kServer, kBiDi };
FlatBufMethod(const RPCCall *method) : method_(method) {
FlatBufMethod(const RPCCall* method) : method_(method) {
streaming_ = kNone;
auto val = method_->attributes.Lookup("streaming");
if (val) {
@@ -63,7 +63,7 @@ class FlatBufMethod : public grpc_generator::Method {
// TODO: This method need to incorporate namespace for C++ side. Other
// language bindings simply don't use this method.
std::string GRPCType(const StructDef &sd) const {
std::string GRPCType(const StructDef& sd) const {
return "flatbuffers::grpc::Message<" + sd.name + ">";
}
@@ -79,7 +79,7 @@ class FlatBufMethod : public grpc_generator::Method {
std::string get_output_type_name() const { return (*method_->response).name; }
bool get_module_and_message_path_input(grpc::string * /*str*/,
bool get_module_and_message_path_input(grpc::string* /*str*/,
grpc::string /*generator_file_name*/,
bool /*generate_in_pb2_grpc*/,
grpc::string /*import_prefix*/) const {
@@ -87,7 +87,7 @@ class FlatBufMethod : public grpc_generator::Method {
}
bool get_module_and_message_path_output(
grpc::string * /*str*/, grpc::string /*generator_file_name*/,
grpc::string* /*str*/, grpc::string /*generator_file_name*/,
bool /*generate_in_pb2_grpc*/, grpc::string /*import_prefix*/) const {
return true;
}
@@ -107,13 +107,13 @@ class FlatBufMethod : public grpc_generator::Method {
bool BidiStreaming() const { return streaming_ == kBiDi; }
private:
const RPCCall *method_;
const RPCCall* method_;
Streaming streaming_;
};
class FlatBufService : public grpc_generator::Service {
public:
FlatBufService(const ServiceDef *service) : service_(service) {}
FlatBufService(const ServiceDef* service) : service_(service) {}
grpc::string GetLeadingComments(const grpc::string) const { return ""; }
@@ -142,20 +142,20 @@ class FlatBufService : public grpc_generator::Service {
}
private:
const ServiceDef *service_;
const ServiceDef* service_;
};
class FlatBufPrinter : public grpc_generator::Printer {
public:
FlatBufPrinter(std::string *str, const char indentation_type)
FlatBufPrinter(std::string* str, const char indentation_type)
: str_(str),
escape_char_('$'),
indent_(0),
indentation_size_(2),
indentation_type_(indentation_type) {}
void Print(const std::map<std::string, std::string> &vars,
const char *string_template) {
void Print(const std::map<std::string, std::string>& vars,
const char* string_template) {
std::string s = string_template;
// Replace any occurrences of strings in "vars" that are surrounded
// by the escape character by what they're mapped to.
@@ -174,14 +174,16 @@ class FlatBufPrinter : public grpc_generator::Printer {
Print(s.c_str());
}
void Print(const char *s) {
if (s == nullptr || *s == '\0') { return; }
void Print(const char* s) {
if (s == nullptr || *s == '\0') {
return;
}
// Add this string, but for each part separated by \n, add indentation.
for (;;) {
// Current indentation.
str_->insert(str_->end(), indent_ * indentation_size_, indentation_type_);
// See if this contains more than one line.
const char *lf = strchr(s, '\n');
const char* lf = strchr(s, '\n');
if (lf) {
(*str_) += std::string(s, lf + 1);
s = lf + 1;
@@ -206,7 +208,7 @@ class FlatBufPrinter : public grpc_generator::Printer {
}
private:
std::string *str_;
std::string* str_;
char escape_char_;
size_t indent_;
size_t indentation_size_;
@@ -224,11 +226,11 @@ class FlatBufFile : public grpc_generator::File {
kLanguageTS
};
FlatBufFile(const Parser &parser, const std::string &file_name,
FlatBufFile(const Parser& parser, const std::string& file_name,
Language language)
: parser_(parser), file_name_(file_name), language_(language) {}
FlatBufFile &operator=(const FlatBufFile &);
FlatBufFile& operator=(const FlatBufFile&);
grpc::string GetLeadingComments(const grpc::string) const { return ""; }
@@ -257,7 +259,7 @@ class FlatBufFile : public grpc_generator::File {
case kLanguageCpp: {
if (!parser_.opts.grpc_additional_headers.empty()) {
std::string result = "";
for (const std::string &header :
for (const std::string& header :
parser_.opts.grpc_additional_headers) {
if (!result.empty()) result += "\n";
result += "#include \"" + header + "\"";
@@ -295,21 +297,21 @@ class FlatBufFile : public grpc_generator::File {
}
std::unique_ptr<grpc_generator::Printer> CreatePrinter(
std::string *str, const char indentation_type = ' ') const {
std::string* str, const char indentation_type = ' ') const {
return std::unique_ptr<grpc_generator::Printer>(
new FlatBufPrinter(str, indentation_type));
}
private:
const Parser &parser_;
const std::string &file_name_;
const Parser& parser_;
const std::string& file_name_;
const Language language_;
};
class GoGRPCGenerator : public flatbuffers::BaseGenerator {
public:
GoGRPCGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
GoGRPCGenerator(const Parser& parser, const std::string& path,
const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "" /*Unused*/, "go"),
parser_(parser),
path_(path),
@@ -321,7 +323,7 @@ class GoGRPCGenerator : public flatbuffers::BaseGenerator {
p.custom_method_io_type = "flatbuffers.Builder";
for (int i = 0; i < file.service_count(); i++) {
auto service = file.service(i);
const Definition *def = parser_.services_.vec[i];
const Definition* def = parser_.services_.vec[i];
p.package_name = LastNamespacePart(*(def->defined_namespace));
p.service_prefix =
def->defined_namespace->GetFullyQualifiedName(""); // file.package();
@@ -335,12 +337,12 @@ class GoGRPCGenerator : public flatbuffers::BaseGenerator {
}
protected:
const Parser &parser_;
const Parser& parser_;
const std::string &path_, &file_name_;
};
bool GenerateGoGRPC(const Parser &parser, const std::string &path,
const std::string &file_name) {
bool GenerateGoGRPC(const Parser& parser, const std::string& path,
const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -350,9 +352,9 @@ bool GenerateGoGRPC(const Parser &parser, const std::string &path,
return GoGRPCGenerator(parser, path, file_name).generate();
}
bool GenerateCppGRPC(const Parser &parser, const std::string &path,
const std::string &file_name) {
const auto &opts = parser.opts;
bool GenerateCppGRPC(const Parser& parser, const std::string& path,
const std::string& file_name) {
const auto& opts = parser.opts;
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -403,8 +405,8 @@ bool GenerateCppGRPC(const Parser &parser, const std::string &path,
class JavaGRPCGenerator : public flatbuffers::BaseGenerator {
public:
JavaGRPCGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
JavaGRPCGenerator(const Parser& parser, const std::string& path,
const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "." /*separator*/, "java") {}
bool generate() {
@@ -412,7 +414,7 @@ class JavaGRPCGenerator : public flatbuffers::BaseGenerator {
grpc_java_generator::Parameters p;
for (int i = 0; i < file.service_count(); i++) {
auto service = file.service(i);
const Definition *def = parser_.services_.vec[i];
const Definition* def = parser_.services_.vec[i];
p.package_name =
def->defined_namespace->GetFullyQualifiedName(""); // file.package();
std::string output =
@@ -425,8 +427,8 @@ class JavaGRPCGenerator : public flatbuffers::BaseGenerator {
}
};
bool GenerateJavaGRPC(const Parser &parser, const std::string &path,
const std::string &file_name) {
bool GenerateJavaGRPC(const Parser& parser, const std::string& path,
const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -436,8 +438,8 @@ bool GenerateJavaGRPC(const Parser &parser, const std::string &path,
return JavaGRPCGenerator(parser, path, file_name).generate();
}
bool GeneratePythonGRPC(const Parser &parser, const std::string &path,
const std::string & /*file_name*/) {
bool GeneratePythonGRPC(const Parser& parser, const std::string& path,
const std::string& /*file_name*/) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -462,8 +464,8 @@ class SwiftGRPCGenerator : public flatbuffers::BaseGenerator {
CodeWriter code_;
public:
SwiftGRPCGenerator(const Parser &parser, const std::string &path,
const std::string &filename)
SwiftGRPCGenerator(const Parser& parser, const std::string& path,
const std::string& filename)
: BaseGenerator(parser, path, filename, "", "" /*Unused*/, "swift") {}
bool generate() {
@@ -480,14 +482,14 @@ class SwiftGRPCGenerator : public flatbuffers::BaseGenerator {
return SaveFile(filename.c_str(), final_code, false);
}
static std::string GeneratedFileName(const std::string &path,
const std::string &file_name) {
static std::string GeneratedFileName(const std::string& path,
const std::string& file_name) {
return path + file_name + ".grpc.swift";
}
};
bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
const std::string &file_name) {
bool GenerateSwiftGRPC(const Parser& parser, const std::string& path,
const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -502,8 +504,8 @@ class TSGRPCGenerator : public flatbuffers::BaseGenerator {
CodeWriter code_;
public:
TSGRPCGenerator(const Parser &parser, const std::string &path,
const std::string &filename)
TSGRPCGenerator(const Parser& parser, const std::string& path,
const std::string& filename)
: BaseGenerator(parser, path, filename, "", "" /*Unused*/, "ts") {}
bool generate() {
@@ -526,16 +528,16 @@ class TSGRPCGenerator : public flatbuffers::BaseGenerator {
return true;
}
static std::string GeneratedFileName(const std::string &path,
const std::string &file_name,
static std::string GeneratedFileName(const std::string& path,
const std::string& file_name,
const bool is_interface = false) {
if (is_interface) return path + file_name + "_grpc.d.ts";
return path + file_name + "_grpc.js";
}
};
bool GenerateTSGRPC(const Parser &parser, const std::string &path,
const std::string &file_name) {
bool GenerateTSGRPC(const Parser& parser, const std::string& path,
const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -548,5 +550,5 @@ bool GenerateTSGRPC(const Parser &parser, const std::string &path,
} // namespace flatbuffers
#if defined(_MSC_VER)
# pragma warning(pop)
#pragma warning(pop)
#endif
+258 -204
View File
File diff suppressed because it is too large Load Diff
+73 -50
View File
@@ -30,9 +30,10 @@ namespace jsons {
namespace {
template<class T> static std::string GenFullName(const T *enum_def) {
template <class T>
static std::string GenFullName(const T* enum_def) {
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) {
full_name.append(*ns + "_");
}
@@ -40,17 +41,19 @@ template<class T> static std::string GenFullName(const T *enum_def) {
return full_name;
}
template<class T> static std::string GenTypeRef(const T *enum_def) {
template <class T>
static std::string GenTypeRef(const T* enum_def) {
return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
}
static std::string GenType(const std::string &name) {
static std::string GenType(const std::string& name) {
return "\"type\" : \"" + name + "\"";
}
static std::string GenType(BaseType type) {
switch (type) {
case BASE_TYPE_BOOL: return "\"type\" : \"boolean\"";
case BASE_TYPE_BOOL:
return "\"type\" : \"boolean\"";
case BASE_TYPE_CHAR:
return "\"type\" : \"integer\", \"minimum\" : " +
NumToString(std::numeric_limits<int8_t>::min()) +
@@ -84,19 +87,26 @@ static std::string GenType(BaseType type) {
return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
NumToString(std::numeric_limits<uint64_t>::max());
case BASE_TYPE_FLOAT:
case BASE_TYPE_DOUBLE: return "\"type\" : \"number\"";
case BASE_TYPE_STRING: return "\"type\" : \"string\"";
default: return "";
case BASE_TYPE_DOUBLE:
return "\"type\" : \"number\"";
case BASE_TYPE_STRING:
return "\"type\" : \"string\"";
default:
return "";
}
}
static std::string GenBaseType(const Type &type) {
if (type.struct_def != nullptr) { return GenTypeRef(type.struct_def); }
if (type.enum_def != nullptr) { return GenTypeRef(type.enum_def); }
static std::string GenBaseType(const Type& type) {
if (type.struct_def != nullptr) {
return GenTypeRef(type.struct_def);
}
if (type.enum_def != nullptr) {
return GenTypeRef(type.enum_def);
}
return GenType(type.base_type);
}
static std::string GenArrayType(const Type &type) {
static std::string GenArrayType(const Type& type) {
std::string element_type;
if (type.struct_def != nullptr) {
element_type = GenTypeRef(type.struct_def);
@@ -109,9 +119,10 @@ static std::string GenArrayType(const Type &type) {
return "\"type\" : \"array\", \"items\" : {" + element_type + "}";
}
static std::string GenType(const Type &type) {
static std::string GenType(const Type& type) {
switch (type.base_type) {
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_ARRAY:
FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
return GenArrayType(type);
}
@@ -120,10 +131,12 @@ static std::string GenType(const Type &type) {
}
case BASE_TYPE_UNION: {
std::string union_type_string("\"anyOf\": [");
const auto &union_types = type.enum_def->Vals();
const auto& union_types = type.enum_def->Vals();
for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
const auto &union_type = *ut;
if (union_type->union_type.base_type == BASE_TYPE_NONE) { continue; }
const auto& union_type = *ut;
if (union_type->union_type.base_type == BASE_TYPE_NONE) {
continue;
}
if (union_type->union_type.base_type == BASE_TYPE_STRUCT) {
union_type_string.append(
"{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
@@ -135,7 +148,8 @@ static std::string GenType(const Type &type) {
union_type_string.append("]");
return union_type_string;
}
case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
case BASE_TYPE_UTYPE:
return GenTypeRef(type.enum_def);
default: {
return GenBaseType(type);
}
@@ -149,16 +163,16 @@ class JsonSchemaGenerator : public BaseGenerator {
std::string code_;
public:
JsonSchemaGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
JsonSchemaGenerator(const Parser& parser, const std::string& path,
const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "", "json") {}
explicit JsonSchemaGenerator(const BaseGenerator &base_generator)
explicit JsonSchemaGenerator(const BaseGenerator& base_generator)
: BaseGenerator(base_generator) {}
std::string GeneratedFileName(const std::string &path,
const std::string &file_name,
const IDLOptions &options /* unused */) const {
std::string GeneratedFileName(const std::string& path,
const std::string& file_name,
const IDLOptions& options /* unused */) const {
(void)options;
return path + file_name + ".schema.json";
}
@@ -175,11 +189,11 @@ class JsonSchemaGenerator : public BaseGenerator {
}
std::string PrepareDescription(
const std::vector<std::string> &comment_lines) {
const std::vector<std::string>& comment_lines) {
std::string comment;
for (auto line_iterator = comment_lines.cbegin();
line_iterator != comment_lines.cend(); ++line_iterator) {
const auto &comment_line = *line_iterator;
const auto& comment_line = *line_iterator;
// remove leading and trailing spaces from comment line
const auto start = std::find_if(comment_line.begin(), comment_line.end(),
@@ -226,7 +240,9 @@ class JsonSchemaGenerator : public BaseGenerator {
for (auto enum_value = (*e)->Vals().begin();
enum_value != (*e)->Vals().end(); ++enum_value) {
enumdef.append("\"" + (*enum_value)->name + "\"");
if (*enum_value != (*e)->Vals().back()) { enumdef.append(", "); }
if (*enum_value != (*e)->Vals().back()) {
enumdef.append(", ");
}
}
enumdef.append("]");
code_ += enumdef + NewLine();
@@ -234,10 +250,10 @@ class JsonSchemaGenerator : public BaseGenerator {
}
for (auto s = parser_.structs_.vec.cbegin();
s != parser_.structs_.vec.cend(); ++s) {
const auto &structure = *s;
const auto& structure = *s;
code_ += Indent(2) + "\"" + GenFullName(structure) + "\" : {" + NewLine();
code_ += Indent(3) + GenType("object") + "," + NewLine();
const auto &comment_lines = structure->doc_comment;
const auto& comment_lines = structure->doc_comment;
auto comment = PrepareDescription(comment_lines);
if (comment != "") {
code_ += Indent(3) + "\"description\" : " + comment + "," + NewLine();
@@ -245,9 +261,9 @@ class JsonSchemaGenerator : public BaseGenerator {
code_ += Indent(3) + "\"properties\" : {" + NewLine();
const auto &properties = structure->fields.vec;
const auto& properties = structure->fields.vec;
for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
const auto &property = *prop;
const auto& property = *prop;
std::string arrayInfo = "";
if (IsArray(property->value.type)) {
arrayInfo = "," + NewLine() + Indent(8) + "\"minItems\": " +
@@ -272,15 +288,17 @@ class JsonSchemaGenerator : public BaseGenerator {
}
typeLine += NewLine() + Indent(7) + "}";
if (property != properties.back()) { typeLine.append(","); }
if (property != properties.back()) {
typeLine.append(",");
}
code_ += typeLine + NewLine();
}
code_ += Indent(3) + "}," + NewLine(); // close properties
std::vector<FieldDef *> requiredProperties;
std::vector<FieldDef*> requiredProperties;
std::copy_if(properties.begin(), properties.end(),
back_inserter(requiredProperties),
[](FieldDef const *prop) { return prop->IsRequired(); });
[](FieldDef const* prop) { return prop->IsRequired(); });
if (!requiredProperties.empty()) {
auto required_string(Indent(3) + "\"required\" : [");
for (auto req_prop = requiredProperties.cbegin();
@@ -295,7 +313,9 @@ class JsonSchemaGenerator : public BaseGenerator {
}
code_ += Indent(3) + "\"additionalProperties\" : false" + NewLine();
auto closeType(Indent(2) + "}");
if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
if (*s != parser_.structs_.vec.back()) {
closeType.append(",");
}
code_ += closeType + NewLine(); // close type
}
code_ += Indent(1) + "}," + NewLine(); // close definitions
@@ -317,10 +337,12 @@ class JsonSchemaGenerator : public BaseGenerator {
};
} // namespace jsons
static bool GenerateJsonSchema(const Parser &parser, const std::string &path,
const std::string &file_name) {
static bool GenerateJsonSchema(const Parser& parser, const std::string& path,
const std::string& file_name) {
jsons::JsonSchemaGenerator generator(parser, path, file_name);
if (!generator.generate()) { return false; }
if (!generator.generate()) {
return false;
}
return generator.save();
}
@@ -328,20 +350,21 @@ namespace {
class JsonSchemaCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateJsonSchema(parser, path, filename)) { return Status::ERROR; }
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
if (!GenerateJsonSchema(parser, path, filename)) {
return Status::ERROR;
}
return Status::OK;
}
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -349,16 +372,16 @@ class JsonSchemaCodeGenerator : public CodeGenerator {
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+279 -214
View File
@@ -38,56 +38,56 @@ 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 std::set<std::string> KotlinKeywords() {
return { "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" };
return {"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"};
}
static Namer::Config KotlinDefaultConfig() {
return { /*types=*/Case::kKeep,
/*constants=*/Case::kKeep,
/*methods=*/Case::kLowerCamel,
/*functions=*/Case::kKeep,
/*fields=*/Case::kLowerCamel,
/*variables=*/Case::kLowerCamel,
/*variants=*/Case::kKeep,
/*enum_variant_seperator=*/"", // I.e. Concatenate.
/*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase,
/*namespaces=*/Case::kKeep,
/*namespace_seperator=*/"__",
/*object_prefix=*/"",
/*object_suffix=*/"T",
/*keyword_prefix=*/"",
/*keyword_suffix=*/"_",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"",
/*filename_extension=*/".kt" };
return {/*types=*/Case::kKeep,
/*constants=*/Case::kKeep,
/*methods=*/Case::kLowerCamel,
/*functions=*/Case::kKeep,
/*fields=*/Case::kLowerCamel,
/*variables=*/Case::kLowerCamel,
/*variants=*/Case::kKeep,
/*enum_variant_seperator=*/"", // I.e. Concatenate.
/*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase,
/*namespaces=*/Case::kKeep,
/*namespace_seperator=*/"__",
/*object_prefix=*/"",
/*object_suffix=*/"T",
/*keyword_prefix=*/"",
/*keyword_suffix=*/"_",
/*filenames=*/Case::kKeep,
/*directories=*/Case::kKeep,
/*output_path=*/"",
/*filename_suffix=*/"",
/*filename_extension=*/".kt"};
}
} // namespace
class KotlinGenerator : public BaseGenerator {
public:
KotlinGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
KotlinGenerator(const Parser& parser, const std::string& path,
const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", ".", "kt"),
namer_(WithFlagOptions(KotlinDefaultConfig(), parser.opts, path),
KotlinKeywords()) {}
KotlinGenerator &operator=(const KotlinGenerator &);
KotlinGenerator& operator=(const KotlinGenerator&);
bool generate() FLATBUFFERS_OVERRIDE {
std::string one_file_code;
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
CodeWriter enumWriter(ident_pad);
auto &enum_def = **it;
auto& enum_def = **it;
GenEnum(enum_def, enumWriter);
if (parser_.opts.one_file) {
one_file_code += enumWriter.ToString();
@@ -101,7 +101,7 @@ class KotlinGenerator : public BaseGenerator {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
CodeWriter structWriter(ident_pad);
auto &struct_def = **it;
auto& struct_def = **it;
GenStruct(struct_def, structWriter, parser_.opts);
if (parser_.opts.one_file) {
one_file_code += structWriter.ToString();
@@ -121,8 +121,8 @@ class KotlinGenerator : public BaseGenerator {
// Save out the generated code for a single class while adding
// declaration boilerplate.
bool SaveType(const std::string &defname, const Namespace &ns,
const std::string &classcode, bool needs_includes) const {
bool SaveType(const std::string& defname, const Namespace& ns,
const std::string& classcode, bool needs_includes) const {
if (!classcode.length()) return true;
std::string code =
@@ -159,11 +159,11 @@ class KotlinGenerator : public BaseGenerator {
return SaveFile(filename.c_str(), code, false);
}
static bool IsEnum(const Type &type) {
static bool IsEnum(const Type& type) {
return type.enum_def != nullptr && IsInteger(type.base_type);
}
static std::string GenTypeBasic(const BaseType &type) {
static std::string GenTypeBasic(const BaseType& type) {
// clang-format off
static const char * const kotlin_typename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -176,18 +176,22 @@ class KotlinGenerator : public BaseGenerator {
return kotlin_typename[type];
}
std::string GenTypePointer(const Type &type) const {
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";
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";
}
}
// with the addition of optional scalar types,
// we are adding the nullable '?' operator to return type of a field.
std::string GetterReturnType(const FieldDef &field) const {
std::string GetterReturnType(const FieldDef& field) const {
auto base_type = field.value.type.base_type;
auto r_type = GenTypeGet(field.value.type);
@@ -204,15 +208,15 @@ class KotlinGenerator : public BaseGenerator {
return r_type;
}
std::string GenTypeGet(const Type &type) const {
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;
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_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name)
: value.constant;
@@ -223,7 +227,7 @@ class KotlinGenerator : public BaseGenerator {
// Main differences are:
// - Floats are upcasted to doubles
// - Unsigned are casted to signed
std::string GenFBBDefaultValue(const FieldDef &field) const {
std::string GenFBBDefaultValue(const FieldDef& field) const {
if (field.IsScalarOptional()) {
// although default value is null, java API forces us to present a real
// default value for scalars, while adding a field to the buffer. This is
@@ -231,9 +235,12 @@ class KotlinGenerator : public BaseGenerator {
// calling builder.addMyField()
switch (field.value.type.base_type) {
case BASE_TYPE_DOUBLE:
case BASE_TYPE_FLOAT: return "0.0";
case BASE_TYPE_BOOL: return "false";
default: return "0";
case BASE_TYPE_FLOAT:
return "0.0";
case BASE_TYPE_BOOL:
return "false";
default:
return "0";
}
}
auto out = GenDefaultValue(field, true);
@@ -250,19 +257,21 @@ class KotlinGenerator : public BaseGenerator {
// FlatBufferBuilder only store signed types, so this function
// returns a cast for unsigned values
std::string GenFBBValueCast(const FieldDef &field) const {
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,
std::string GenDefaultValue(const FieldDef& field,
bool force_signed = false) const {
auto &value = field.value;
auto& value = field.value;
auto base_type = field.value.type.base_type;
if (field.IsScalarOptional()) { return "null"; }
if (field.IsScalarOptional()) {
return "null";
}
if (IsFloat(base_type)) {
auto val = KotlinFloatGen.GenFloatConstant(field);
if (base_type == BASE_TYPE_DOUBLE && val.back() == 'f') {
@@ -283,7 +292,7 @@ class KotlinGenerator : public BaseGenerator {
return value.constant + suffix;
}
void GenEnum(EnumDef &enum_def, CodeWriter &writer) const {
void GenEnum(EnumDef& enum_def, CodeWriter& writer) const {
if (enum_def.generated) return;
GenerateComment(enum_def.doc_comment, writer, &comment_config);
@@ -296,7 +305,7 @@ class KotlinGenerator : public BaseGenerator {
// Write all properties
auto vals = enum_def.Vals();
for (auto it = vals.begin(); it != vals.end(); ++it) {
auto &ev = **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);
@@ -328,7 +337,9 @@ class KotlinGenerator : public BaseGenerator {
writer += "\"\", \\";
val = ev;
writer += "\"" + (*it)->name + "\"\\";
if (it + 1 != vals.end()) { writer += ", \\"; }
if (it + 1 != vals.end()) {
writer += ", \\";
}
}
writer += ")";
});
@@ -348,49 +359,65 @@ class KotlinGenerator : public BaseGenerator {
}
// Returns the function name that is able to read a value of the given type.
std::string ByteBufferGetter(const Type &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_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_UINT:
return bb_var_name + ".getInt";
case BASE_TYPE_SHORT:
case BASE_TYPE_USHORT: return bb_var_name + ".getShort";
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_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";
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 + "." +
namer_.Method("get", GenTypeBasic(type.base_type));
}
}
std::string ByteBufferSetter(const Type &type) const {
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_UINT:
return "bb.putInt";
case BASE_TYPE_SHORT:
case BASE_TYPE_USHORT: return "bb.putShort";
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_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";
case BASE_TYPE_UTYPE:
return "bb.put";
default:
return "bb." + namer_.Method("put", GenTypeBasic(type.base_type));
}
@@ -399,27 +426,27 @@ class KotlinGenerator : public BaseGenerator {
}
// 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 {
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) {
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.
void GenStructArgs(const StructDef &struct_def, CodeWriter &writer,
const char *nameprefix) const {
void GenStructArgs(const StructDef& struct_def, CodeWriter& writer,
const char* nameprefix) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **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
@@ -438,14 +465,14 @@ class KotlinGenerator : public BaseGenerator {
// Recusively generate struct construction statements of the form:
// builder.putType(name);
// and insert manual padding.
void GenStructBody(const StructDef &struct_def, CodeWriter &writer,
const char *nameprefix) const {
void GenStructBody(const StructDef& struct_def, CodeWriter& writer,
const char* nameprefix) const {
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;
auto& field = **it;
if (field.padding) {
writer.SetValue("pad", NumToString(field.padding));
@@ -463,14 +490,14 @@ class KotlinGenerator : public BaseGenerator {
}
}
std::string GenByteBufferLength(const char *bb_name) const {
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 GenOffsetGetter(flatbuffers::FieldDef* key_field,
const char* num = nullptr) const {
std::string key_offset =
"__offset(" + NumToString(key_field->value.offset) + ", ";
if (num) {
@@ -483,7 +510,7 @@ class KotlinGenerator : public BaseGenerator {
return key_offset;
}
void GenStruct(StructDef &struct_def, CodeWriter &writer,
void GenStruct(StructDef& struct_def, CodeWriter& writer,
IDLOptions options) const {
if (struct_def.generated) return;
@@ -517,7 +544,7 @@ class KotlinGenerator : public BaseGenerator {
// Generate Static Fields
GenerateCompanionObject(writer, [&]() {
if (!struct_def.fixed) {
FieldDef *key_field = nullptr;
FieldDef* key_field = nullptr;
// Generate version check method.
// Force compile time error if not using the same version
@@ -537,7 +564,7 @@ class KotlinGenerator : public BaseGenerator {
auto fields = struct_def.fields.vec;
int field_pos = -1;
for (auto it = fields.begin(); it != fields.end(); ++it) {
auto &field = **it;
auto& field = **it;
field_pos++;
if (field.deprecated) continue;
if (field.key) key_field = &field;
@@ -576,8 +603,8 @@ class KotlinGenerator : public BaseGenerator {
}
// TODO: move key_field to reference instead of pointer
void GenerateLookupByKey(FieldDef *key_field, StructDef &struct_def,
CodeWriter &writer, const IDLOptions options) const {
void GenerateLookupByKey(FieldDef* key_field, StructDef& struct_def,
CodeWriter& writer, const IDLOptions options) const {
std::stringstream params;
params << "obj: " << namer_.Type(struct_def) << "?"
<< ", ";
@@ -637,9 +664,9 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
void GenerateFinishSizePrefixed(StructDef &struct_def,
const std::string &identifier,
CodeWriter &writer,
void GenerateFinishSizePrefixed(StructDef& struct_def,
const std::string& identifier,
CodeWriter& writer,
const IDLOptions options) const {
auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : "";
auto params = "builder: FlatBufferBuilder, offset: Int";
@@ -650,9 +677,9 @@ class KotlinGenerator : public BaseGenerator {
[&]() { writer += "builder.finishSizePrefixed(offset" + id + ")"; },
options.gen_jvmstatic);
}
void GenerateFinishStructBuffer(StructDef &struct_def,
const std::string &identifier,
CodeWriter &writer,
void GenerateFinishStructBuffer(StructDef& struct_def,
const std::string& identifier,
CodeWriter& writer,
const IDLOptions options) const {
auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : "";
auto params = "builder: FlatBufferBuilder, offset: Int";
@@ -664,7 +691,7 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
void GenerateEndStructMethod(StructDef &struct_def, CodeWriter &writer,
void GenerateEndStructMethod(StructDef& struct_def, CodeWriter& writer,
const IDLOptions options) const {
// Generate end{{TableName}}(builder: FlatBufferBuilder) method
auto name = namer_.LegacyJavaMethod2("end", struct_def, "");
@@ -678,8 +705,10 @@ class KotlinGenerator : public BaseGenerator {
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.IsRequired()) { continue; }
auto& field = **it;
if (field.deprecated || !field.IsRequired()) {
continue;
}
writer.SetValue("offset", NumToString(field.value.offset));
writer += "builder.required(o, {{offset}})";
}
@@ -690,7 +719,7 @@ class KotlinGenerator : public BaseGenerator {
}
// Generate a method to create a vector from a Kotlin array.
void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer,
void GenerateCreateVectorField(FieldDef& field, CodeWriter& writer,
const IDLOptions options) const {
auto vector_type = field.value.type.VectorType();
auto method_name = namer_.Method("create", field, "vector");
@@ -718,7 +747,7 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
void GenerateStartVectorField(FieldDef &field, CodeWriter &writer,
void GenerateStartVectorField(FieldDef& field, CodeWriter& writer,
const IDLOptions options) const {
// Generate a method to start a vector, data to be added manually
// after.
@@ -735,8 +764,8 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
void GenerateAddField(std::string field_pos, FieldDef &field,
CodeWriter &writer, const IDLOptions options) const {
void GenerateAddField(std::string field_pos, FieldDef& field,
CodeWriter& writer, const IDLOptions options) const {
auto field_type = GenTypeBasic(field.value.type.base_type);
auto secondArg = namer_.Variable(field.name) + ": " + field_type;
@@ -770,21 +799,27 @@ class KotlinGenerator : public BaseGenerator {
}
}
static std::string ToSignedType(const Type &type) {
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_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);
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);
}
}
static std::string FlexBufferBuilderCast(const std::string &method,
FieldDef &field, bool isFirst) {
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")
@@ -808,7 +843,7 @@ class KotlinGenerator : public BaseGenerator {
}
// fun startMonster(builder: FlatBufferBuilder) = builder.startTable(11)
void GenerateStartStructMethod(StructDef &struct_def, CodeWriter &code,
void GenerateStartStructMethod(StructDef& struct_def, CodeWriter& code,
const IDLOptions options) const {
GenerateFunOneLine(
code, namer_.LegacyJavaMethod2("start", struct_def, ""),
@@ -820,7 +855,7 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
void GenerateTableCreator(StructDef &struct_def, CodeWriter &writer,
void GenerateTableCreator(StructDef& struct_def, CodeWriter& writer,
const IDLOptions options) 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
@@ -830,7 +865,7 @@ class KotlinGenerator : public BaseGenerator {
auto fields_vec = struct_def.fields.vec;
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
if (IsStruct(field.value.type)) {
has_no_struct_fields = false;
@@ -848,7 +883,7 @@ class KotlinGenerator : public BaseGenerator {
std::stringstream params;
params << "builder: FlatBufferBuilder";
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
params << ", " << namer_.Variable(field);
if (!IsScalar(field.value.type.base_type)) {
@@ -872,7 +907,7 @@ class KotlinGenerator : public BaseGenerator {
for (size_t size = largest; size; size /= 2) {
for (auto it = fields_vec.rbegin(); it != fields_vec.rend();
++it) {
auto &field = **it;
auto& field = **it;
auto base_type_size = SizeOf(field.value.type.base_type);
if (!field.deprecated &&
(!sortbysize || size == base_type_size)) {
@@ -898,7 +933,7 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
}
void GenerateBufferHasIdentifier(StructDef &struct_def, CodeWriter &writer,
void GenerateBufferHasIdentifier(StructDef& struct_def, CodeWriter& writer,
IDLOptions options) const {
auto file_identifier = parser_.file_identifier_;
// Check if a buffer has the identifier.
@@ -913,11 +948,11 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
void GenerateStructGetters(StructDef &struct_def, CodeWriter &writer) const {
void GenerateStructGetters(StructDef& struct_def, CodeWriter& writer) const {
auto fields_vec = struct_def.fields.vec;
FieldDef *key_field = nullptr;
FieldDef* key_field = nullptr;
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
if (field.key) key_field = &field;
@@ -1090,7 +1125,8 @@ class KotlinGenerator : public BaseGenerator {
case BASE_TYPE_UNION:
found = "{{bbgetter}}(obj, {{index}}){{ucast}}";
break;
default: found = "{{bbgetter}}({{index}}){{ucast}}";
default:
found = "{{bbgetter}}({{index}}){{ucast}}";
}
OffsetWrapper(
writer, offset_val, [&]() { writer += found; },
@@ -1105,7 +1141,8 @@ class KotlinGenerator : public BaseGenerator {
offset_val, bbgetter + "(obj, o + bb_pos)", "null");
});
break;
default: FLATBUFFERS_ASSERT(0);
default:
FLATBUFFERS_ASSERT(0);
}
}
@@ -1118,10 +1155,10 @@ class KotlinGenerator : public BaseGenerator {
// 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;
auto& sd = *field.value.type.struct_def;
auto& fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
auto &kfield = **kit;
auto& kfield = **kit;
if (kfield.key) {
auto qualified_name = WrapInNameSpace(sd);
auto name = namer_.Method(field, "ByKey");
@@ -1286,35 +1323,47 @@ class KotlinGenerator : public BaseGenerator {
}
}
static std::string CastToUsigned(const FieldDef &field) {
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_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 "";
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 "";
}
}
static std::string CastToSigned(const FieldDef &field) {
static std::string CastToSigned(const FieldDef& field) {
return CastToSigned(field.value.type);
}
static std::string CastToSigned(const Type type) {
switch (type.base_type) {
case BASE_TYPE_UINT: return ".toInt()";
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 "";
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 "";
}
}
@@ -1323,15 +1372,19 @@ class KotlinGenerator : public BaseGenerator {
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 "";
case BASE_TYPE_USHORT:
return "u";
case BASE_TYPE_ULONG:
return "UL";
case BASE_TYPE_LONG:
return "L";
default:
return "";
}
}
void GenerateCompanionObject(CodeWriter &code,
const std::function<void()> &callback) const {
void GenerateCompanionObject(CodeWriter& code,
const std::function<void()>& callback) const {
code += "companion object {";
code.IncrementIdentLevel();
callback();
@@ -1340,8 +1393,8 @@ class KotlinGenerator : public BaseGenerator {
}
// Generate a documentation comment, if available.
void GenerateComment(const std::vector<std::string> &dc, CodeWriter &writer,
const CommentConfig *config) const {
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;
@@ -1362,8 +1415,8 @@ class KotlinGenerator : public BaseGenerator {
}
}
void GenerateGetRootAsAccessors(const std::string &struct_name,
CodeWriter &writer,
void GenerateGetRootAsAccessors(const std::string& struct_name,
CodeWriter& writer,
IDLOptions options) const {
// Generate a special accessor for the table that when used as the root
// ex: fun getRootAsMonster(_bb: ByteBuffer): Monster {...}
@@ -1390,7 +1443,7 @@ class KotlinGenerator : public BaseGenerator {
writer += "}";
}
void GenerateStaticConstructor(const StructDef &struct_def, CodeWriter &code,
void GenerateStaticConstructor(const StructDef& struct_def, CodeWriter& code,
const IDLOptions options) const {
// create a struct constructor function
auto params = StructConstructorParams(struct_def);
@@ -1403,14 +1456,16 @@ class KotlinGenerator : public BaseGenerator {
options.gen_jvmstatic);
}
std::string StructConstructorParams(const StructDef &struct_def,
const std::string &prefix = "") const {
std::string StructConstructorParams(const StructDef& struct_def,
const std::string& prefix = "") const {
// builder: FlatBufferBuilder
std::stringstream out;
auto field_vec = struct_def.fields.vec;
if (prefix.empty()) { out << "builder: FlatBufferBuilder"; }
if (prefix.empty()) {
out << "builder: FlatBufferBuilder";
}
for (auto it = field_vec.begin(); it != field_vec.end(); ++it) {
auto &field = **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
@@ -1426,10 +1481,10 @@ class KotlinGenerator : public BaseGenerator {
return out.str();
}
static void GeneratePropertyOneLine(CodeWriter &writer,
const std::string &name,
const std::string &type,
const std::function<void()> &body) {
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
@@ -1438,9 +1493,9 @@ class KotlinGenerator : public BaseGenerator {
writer += "val {{_name}} : {{_type}} = \\";
body();
}
static void GenerateGetterOneLine(CodeWriter &writer, const std::string &name,
const std::string &type,
const std::function<void()> &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
@@ -1450,9 +1505,9 @@ class KotlinGenerator : public BaseGenerator {
body();
}
static void GenerateGetter(CodeWriter &writer, const std::string &name,
const std::string &type,
const std::function<void()> &body) {
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
@@ -1471,10 +1526,10 @@ class KotlinGenerator : public BaseGenerator {
writer.DecrementIdentLevel();
}
static void GenerateFun(CodeWriter &writer, const std::string &name,
const std::string &params,
const std::string &returnType,
const std::function<void()> &body,
static void GenerateFun(CodeWriter& writer, const std::string& name,
const std::string& params,
const std::string& returnType,
const std::function<void()>& body,
bool gen_jvmstatic = false) {
// Generates Kotlin function
// e.g.:
@@ -1493,10 +1548,10 @@ class KotlinGenerator : public BaseGenerator {
writer += "}";
}
static void GenerateFunOneLine(CodeWriter &writer, const std::string &name,
const std::string &params,
const std::string &returnType,
const std::function<void()> &body,
static void GenerateFunOneLine(CodeWriter& writer, const std::string& name,
const std::string& params,
const std::string& returnType,
const std::function<void()>& body,
bool gen_jvmstatic = false) {
// Generates Kotlin function
// e.g.:
@@ -1510,10 +1565,10 @@ class KotlinGenerator : public BaseGenerator {
body();
}
static void GenerateOverrideFun(CodeWriter &writer, const std::string &name,
const std::string &params,
const std::string &returnType,
const std::function<void()> &body) {
static void GenerateOverrideFun(CodeWriter& writer, const std::string& name,
const std::string& params,
const std::string& returnType,
const std::function<void()>& body) {
// Generates Kotlin function
// e.g.:
// override fun path(j: Int): Vec3 = return path(Vec3(), j)
@@ -1521,11 +1576,11 @@ class KotlinGenerator : public BaseGenerator {
GenerateFun(writer, name, params, returnType, body);
}
static void GenerateOverrideFunOneLine(CodeWriter &writer,
const std::string &name,
const std::string &params,
const std::string &returnType,
const std::string &statement) {
static void GenerateOverrideFunOneLine(CodeWriter& writer,
const std::string& name,
const std::string& params,
const std::string& returnType,
const std::string& statement) {
// Generates Kotlin function
// e.g.:
// override fun path(j: Int): Vec3 = return path(Vec3(), j)
@@ -1537,16 +1592,16 @@ class KotlinGenerator : public BaseGenerator {
writer += statement;
}
static std::string OffsetWrapperOneLine(const std::string &offset,
const std::string &found,
const std::string &not_found) {
static std::string OffsetWrapperOneLine(const std::string& offset,
const std::string& found,
const std::string& not_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()> &not_found) {
static void OffsetWrapper(CodeWriter& code, const std::string& offset,
const std::function<void()>& found,
const std::function<void()>& not_found) {
code += "val o = __offset(" + offset + ")";
code += "return if (o != 0) {";
code.IncrementIdentLevel();
@@ -1559,7 +1614,7 @@ class KotlinGenerator : public BaseGenerator {
code += "}";
}
static std::string Indirect(const std::string &index, bool fixed) {
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;
@@ -1567,34 +1622,43 @@ class KotlinGenerator : public BaseGenerator {
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_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_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";
case BASE_TYPE_UTYPE:
return "0u";
case BASE_TYPE_ULONG:
return "0uL";
default:
return "null";
}
}
// Prepend @JvmStatic to methods in companion object.
static void GenerateJvmStaticAnnotation(CodeWriter &code,
static void GenerateJvmStaticAnnotation(CodeWriter& code,
bool gen_jvmstatic) {
if (gen_jvmstatic) { code += "@JvmStatic"; }
if (gen_jvmstatic) {
code += "@JvmStatic";
}
}
const IdlNamer namer_;
};
} // namespace kotlin
static bool GenerateKotlin(const Parser &parser, const std::string &path,
const std::string &file_name) {
static bool GenerateKotlin(const Parser& parser, const std::string& path,
const std::string& file_name) {
kotlin::KotlinGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -1603,20 +1667,21 @@ namespace {
class KotlinCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateKotlin(parser, path, filename)) { return Status::ERROR; }
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
if (!GenerateKotlin(parser, path, filename)) {
return Status::ERROR;
}
return Status::OK;
}
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -1624,16 +1689,16 @@ class KotlinCodeGenerator : public CodeGenerator {
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+328 -242
View File
File diff suppressed because it is too large Load Diff
+65 -63
View File
@@ -29,38 +29,38 @@ 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 */, ".",
"lobster") {
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));
}
std::string EscapeKeyword(const std::string &name) const {
std::string EscapeKeyword(const std::string& name) const {
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
std::string NormalizedName(const Definition &definition) const {
std::string NormalizedName(const Definition& definition) const {
return EscapeKeyword(definition.name);
}
std::string NormalizedName(const EnumVal &ev) const {
std::string NormalizedName(const EnumVal& ev) const {
return EscapeKeyword(ev.name);
}
std::string NamespacedName(const Definition &def) {
std::string NamespacedName(const Definition& def) {
return WrapInNameSpace(def.defined_namespace, NormalizedName(def));
}
std::string GenTypeName(const Type &type) {
std::string GenTypeName(const Type& type) {
auto bits = NumToString(SizeOf(type.base_type) * 8);
if (IsInteger(type.base_type)) {
if (IsUnsigned(type.base_type))
@@ -74,7 +74,7 @@ class LobsterGenerator : public BaseGenerator {
return "none";
}
std::string LobsterType(const Type &type) {
std::string LobsterType(const Type& type) {
if (IsFloat(type.base_type)) return "float";
if (IsBool(type.base_type)) return "bool";
if (IsScalar(type.base_type) && type.enum_def)
@@ -85,14 +85,14 @@ class LobsterGenerator : public BaseGenerator {
}
// Returns the method name for use with add/put calls.
std::string GenMethod(const Type &type) {
std::string GenMethod(const Type& type) {
return IsScalar(type.base_type)
? ConvertCase(GenTypeBasic(type), Case::kUpperCamel)
: (IsStruct(type) ? "Struct" : "UOffsetTRelative");
}
// This uses Python names for now..
std::string GenTypeBasic(const Type &type) {
std::string GenTypeBasic(const Type& type) {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -106,10 +106,10 @@ 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;
std::string& code = *code_ptr;
auto offsets = NumToString(field.value.offset);
auto def = " def " + NormalizedName(field);
if (IsScalar(field.value.type.base_type)) {
@@ -195,7 +195,7 @@ class LobsterGenerator : public BaseGenerator {
case BASE_TYPE_UNION: {
for (auto it = field.value.type.enum_def->Vals().begin();
it != field.value.type.enum_def->Vals().end(); ++it) {
auto &ev = **it;
auto& ev = **it;
if (ev.IsNonZero()) {
code += def + "_as_" + ev.name + "():\n return " +
NamespacedName(*ev.union_type.struct_def) +
@@ -205,7 +205,8 @@ class LobsterGenerator : public BaseGenerator {
}
break;
}
default: FLATBUFFERS_ASSERT(0);
default:
FLATBUFFERS_ASSERT(0);
}
if (IsVector(field.value.type)) {
code += def +
@@ -216,8 +217,8 @@ class LobsterGenerator : public BaseGenerator {
}
// Generate table constructors, conditioned on its members' types.
void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *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(" +
@@ -225,7 +226,7 @@ class LobsterGenerator : public BaseGenerator {
")\n return this\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
auto offset = it - struct_def.fields.vec.begin();
code += " def add_" + NormalizedName(field) + "(" +
@@ -239,7 +240,7 @@ class LobsterGenerator : public BaseGenerator {
code += " def end():\n return b_.EndObject()\n\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
if (IsVector(field.value.type)) {
code += "def " + NormalizedName(struct_def) + "Start" +
@@ -266,23 +267,23 @@ class LobsterGenerator : public BaseGenerator {
}
}
void GenStructPreDecl(const StructDef &struct_def, std::string *code_ptr) {
void GenStructPreDecl(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
std::string &code = *code_ptr;
std::string& code = *code_ptr;
CheckNameSpace(struct_def, &code);
code += "class " + NormalizedName(struct_def) + "\n\n";
}
// Generate struct or table methods.
void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
void GenStruct(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
std::string &code = *code_ptr;
std::string& code = *code_ptr;
CheckNameSpace(struct_def, &code);
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) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr);
}
@@ -304,14 +305,14 @@ class LobsterGenerator : public BaseGenerator {
}
// Generate enum declarations.
void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
void GenEnum(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
std::string &code = *code_ptr;
std::string& code = *code_ptr;
CheckNameSpace(enum_def, &code);
GenComment(enum_def.doc_comment, code_ptr, nullptr, "");
code += "enum " + NormalizedName(enum_def) + ":\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
auto& ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, " ");
code += " " + enum_def.name + "_" + NormalizedName(ev) + " = " +
enum_def.ToString(ev) + "\n";
@@ -321,11 +322,11 @@ 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;
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
@@ -334,7 +335,7 @@ class LobsterGenerator : public BaseGenerator {
(nameprefix + (NormalizedName(field) + "_")).c_str(),
code_ptr);
} else {
std::string &code = *code_ptr;
std::string& code = *code_ptr;
code += ", " + (nameprefix + NormalizedName(field)) + ":" +
LobsterType(field.value.type);
}
@@ -343,14 +344,14 @@ 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) {
std::string &code = *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";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.padding)
code += " b_.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field.value.type)) {
@@ -365,8 +366,8 @@ 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) {
std::string &code = *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";
StructBuilderArgs(struct_def, "", code_ptr);
@@ -375,11 +376,11 @@ class LobsterGenerator : public BaseGenerator {
code += " return b_.Offset()\n\n";
}
void CheckNameSpace(const Definition &def, std::string *code_ptr) {
void CheckNameSpace(const Definition& def, std::string* code_ptr) {
auto ns = GetNameSpace(def);
if (ns == current_namespace_) return;
current_namespace_ = ns;
std::string &code = *code_ptr;
std::string& code = *code_ptr;
code += "namespace " + ns + "\n\n";
}
@@ -389,17 +390,17 @@ class LobsterGenerator : public BaseGenerator {
"\nimport flatbuffers\n\n";
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
auto& enum_def = **it;
GenEnum(enum_def, &code);
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
auto& struct_def = **it;
GenStructPreDecl(struct_def, &code);
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
auto& struct_def = **it;
GenStruct(struct_def, &code);
}
return SaveFile(GeneratedFileName(path_, file_name_, parser_.opts).c_str(),
@@ -413,8 +414,8 @@ class LobsterGenerator : public BaseGenerator {
} // namespace lobster
static bool GenerateLobster(const Parser &parser, const std::string &path,
const std::string &file_name) {
static bool GenerateLobster(const Parser& parser, const std::string& path,
const std::string& file_name) {
lobster::LobsterGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -423,20 +424,21 @@ namespace {
class LobsterCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateLobster(parser, path, filename)) { return Status::ERROR; }
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
if (!GenerateLobster(parser, path, filename)) {
return Status::ERROR;
}
return Status::OK;
}
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -444,16 +446,16 @@ class LobsterCodeGenerator : public CodeGenerator {
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+148 -125
View File
@@ -31,8 +31,8 @@ namespace php {
const std::string Indent = " ";
class PhpGenerator : public BaseGenerator {
public:
PhpGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
PhpGenerator(const Parser& parser, const std::string& path,
const std::string& file_name)
: BaseGenerator(parser, path, file_name, "\\", "\\", "php") {}
bool generate() {
if (!GenerateEnums()) return false;
@@ -44,7 +44,7 @@ class PhpGenerator : public BaseGenerator {
bool GenerateEnums() {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
auto& enum_def = **it;
std::string enumcode;
GenEnum(enum_def, &enumcode);
if (!SaveType(enum_def, enumcode, false)) return false;
@@ -55,7 +55,7 @@ class PhpGenerator : public BaseGenerator {
bool GenerateStructs() {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
auto& struct_def = **it;
std::string declcode;
GenStruct(struct_def, &declcode);
if (!SaveType(struct_def, declcode, true)) return false;
@@ -64,9 +64,9 @@ class PhpGenerator : public BaseGenerator {
}
// Begin by declaring namespace and imports.
void BeginFile(const std::string &name_space_name, const bool needs_imports,
std::string *code_ptr) {
auto &code = *code_ptr;
void BeginFile(const std::string& name_space_name, const bool needs_imports,
std::string* code_ptr) {
auto& code = *code_ptr;
code += "<?php\n";
code = code + "// " + FlatBuffersGeneratedWarning() + "\n\n";
@@ -84,7 +84,7 @@ class PhpGenerator : public BaseGenerator {
}
// Save out the generated code for a Php Table type.
bool SaveType(const Definition &def, const std::string &classcode,
bool SaveType(const Definition& def, const std::string& classcode,
bool needs_imports) {
if (!classcode.length()) return true;
@@ -99,8 +99,8 @@ class PhpGenerator : public BaseGenerator {
}
// Begin a class declaration.
static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
static void BeginClass(const StructDef& struct_def, std::string* code_ptr) {
std::string& code = *code_ptr;
if (struct_def.fixed) {
code += "class " + struct_def.name + " extends Struct\n";
} else {
@@ -109,21 +109,21 @@ class PhpGenerator : public BaseGenerator {
code += "{\n";
}
static void EndClass(std::string *code_ptr) {
std::string &code = *code_ptr;
static void EndClass(std::string* code_ptr) {
std::string& code = *code_ptr;
code += "}\n";
}
// Begin enum code with a class declaration.
static void BeginEnum(const std::string &class_name, std::string *code_ptr) {
std::string &code = *code_ptr;
static void BeginEnum(const std::string& class_name, std::string* code_ptr) {
std::string& code = *code_ptr;
code += "class " + class_name + "\n{\n";
}
// A single enum member.
static void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
std::string *code_ptr) {
std::string &code = *code_ptr;
static void EnumMember(const EnumDef& enum_def, const EnumVal& ev,
std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "const ";
code += ev.name;
code += " = ";
@@ -131,15 +131,15 @@ class PhpGenerator : public BaseGenerator {
}
// End enum code.
static void EndEnum(std::string *code_ptr) {
std::string &code = *code_ptr;
static void EndEnum(std::string* code_ptr) {
std::string& code = *code_ptr;
code += "}\n";
}
// Initialize a new struct or table from existing data.
static void NewRootTypeFromBuffer(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
static void NewRootTypeFromBuffer(const StructDef& struct_def,
std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param ByteBuffer $bb\n";
@@ -158,9 +158,9 @@ class PhpGenerator : public BaseGenerator {
}
// Initialize an existing object with other data, to avoid an allocation.
static void InitializeExisting(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
static void InitializeExisting(const StructDef& struct_def,
std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param int $_i offset\n";
@@ -176,8 +176,8 @@ class PhpGenerator : public BaseGenerator {
}
// Get the length of a vector.
static void GetVectorLen(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
static void GetVectorLen(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return int\n";
@@ -193,8 +193,8 @@ class PhpGenerator : public BaseGenerator {
}
// Get a [ubyte] vector as a byte array.
static void GetUByte(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
static void GetUByte(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return string\n";
@@ -208,9 +208,9 @@ class PhpGenerator : public BaseGenerator {
}
// Get the value of a struct's scalar.
static void GetScalarFieldOfStruct(const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
static void GetScalarFieldOfStruct(const FieldDef& field,
std::string* code_ptr) {
std::string& code = *code_ptr;
std::string getter = GenGetter(field.value.type);
code += Indent + "/**\n";
@@ -232,8 +232,8 @@ class PhpGenerator : public BaseGenerator {
}
// Get the value of a table's scalar.
void GetScalarFieldOfTable(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
void GetScalarFieldOfTable(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
@@ -254,8 +254,8 @@ class PhpGenerator : public BaseGenerator {
// Get a struct by initializing an existing struct.
// Specific to Struct.
void GetStructFieldOfStruct(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
void GetStructFieldOfStruct(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
@@ -273,8 +273,8 @@ class PhpGenerator : public BaseGenerator {
// Get a struct by initializing an existing struct.
// Specific to Table.
void GetStructFieldOfTable(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
void GetStructFieldOfTable(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "public function get";
code += ConvertCase(field.name, Case::kUpperCamel);
@@ -297,8 +297,8 @@ class PhpGenerator : public BaseGenerator {
}
// Get the value of a string.
void GetStringField(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
void GetStringField(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "public function get";
code += ConvertCase(field.name, Case::kUpperCamel);
code += "()\n";
@@ -312,8 +312,8 @@ class PhpGenerator : public BaseGenerator {
}
// Get the value of a union from an object.
void GetUnionField(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
void GetUnionField(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return" + GenTypeBasic(field.value.type) + "\n";
@@ -329,9 +329,9 @@ class PhpGenerator : public BaseGenerator {
}
// 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;
void GetMemberOfVectorOfStruct(const StructDef& struct_def,
const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
code += Indent + "/**\n";
@@ -382,7 +382,8 @@ class PhpGenerator : public BaseGenerator {
code += Indent + Indent + "return $o != 0 ? $this->";
code += GenGetter(field.value.type) + "($obj, $o); null;\n";
break;
default: break;
default:
break;
}
code += Indent + "}\n\n";
@@ -390,9 +391,9 @@ class PhpGenerator : public BaseGenerator {
// 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 FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
void GetMemberOfVectorOfNonStruct(const FieldDef& field,
std::string* code_ptr) {
std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
code += Indent + "/**\n";
@@ -423,8 +424,8 @@ class PhpGenerator : public BaseGenerator {
// Get the value of a vector's union member. Uses a named return
// argument to conveniently set the zero value for the result.
void GetMemberOfVectorOfUnion(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
void GetMemberOfVectorOfUnion(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
code += Indent + "/**\n";
@@ -445,11 +446,11 @@ class PhpGenerator : public BaseGenerator {
// Recursively generate arguments for a constructor, to deal with nested
// structs.
static void StructBuilderArgs(const StructDef &struct_def,
const char *nameprefix, std::string *code_ptr) {
static 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;
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
@@ -458,7 +459,7 @@ class PhpGenerator : public BaseGenerator {
StructBuilderArgs(*field.value.type.struct_def,
(nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
std::string &code = *code_ptr;
std::string& code = *code_ptr;
code += std::string(", $") + nameprefix;
code += ConvertCase(field.name, Case::kLowerCamel);
}
@@ -467,15 +468,15 @@ class PhpGenerator : public BaseGenerator {
// Recursively generate struct construction statements and instert manual
// padding.
static void StructBuilderBody(const StructDef &struct_def,
const char *nameprefix, std::string *code_ptr) {
std::string &code = *code_ptr;
static void StructBuilderBody(const StructDef& struct_def,
const char* nameprefix, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + Indent + "$builder->prep(";
code += 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;
auto& field = **it;
if (field.padding) {
code += Indent + Indent + "$builder->pad(";
code += NumToString(field.padding) + ");\n";
@@ -492,9 +493,9 @@ class PhpGenerator : public BaseGenerator {
}
// Get the value of a table's starting offset.
static void GetStartOfTable(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
static void GetStartOfTable(const StructDef& struct_def,
std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param FlatBufferBuilder $builder\n";
@@ -517,10 +518,12 @@ class PhpGenerator : public BaseGenerator {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
if (it != struct_def.fields.vec.begin()) { code += ", "; }
if (it != struct_def.fields.vec.begin()) {
code += ", ";
}
code += "$" + field.name;
}
code += ")\n";
@@ -530,7 +533,7 @@ class PhpGenerator : public BaseGenerator {
code += ");\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
code += Indent + Indent + "self::add";
@@ -542,7 +545,7 @@ class PhpGenerator : public BaseGenerator {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (!field.deprecated && field.IsRequired()) {
code += Indent + Indent + "$builder->required($o, ";
code += NumToString(field.value.offset);
@@ -554,9 +557,9 @@ class PhpGenerator : public BaseGenerator {
}
// Set the value of a table's field.
static void BuildFieldOfTable(const FieldDef &field, const size_t offset,
std::string *code_ptr) {
std::string &code = *code_ptr;
static void BuildFieldOfTable(const FieldDef& field, const size_t offset,
std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param FlatBufferBuilder $builder\n";
@@ -586,8 +589,8 @@ class PhpGenerator : public BaseGenerator {
}
// Set the value of one of the members of a table's vector.
static void BuildVectorOfTable(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
static void BuildVectorOfTable(const FieldDef& field, std::string* code_ptr) {
std::string& code = *code_ptr;
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
@@ -638,8 +641,8 @@ class PhpGenerator : public BaseGenerator {
}
// Get the offset of the end of a table.
void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
void GetEndOffsetOnTable(const StructDef& struct_def, std::string* code_ptr) {
std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param FlatBufferBuilder $builder\n";
@@ -652,7 +655,7 @@ class PhpGenerator : public BaseGenerator {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (!field.deprecated && field.IsRequired()) {
code += Indent + Indent + "$builder->required($o, ";
code += NumToString(field.value.offset);
@@ -678,8 +681,8 @@ class PhpGenerator : 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, Indent.c_str());
if (IsScalar(field.value.type.base_type)) {
@@ -697,7 +700,9 @@ class PhpGenerator : public BaseGenerator {
GetStructFieldOfTable(field, code_ptr);
}
break;
case BASE_TYPE_STRING: GetStringField(field, code_ptr); break;
case BASE_TYPE_STRING:
GetStringField(field, code_ptr);
break;
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_UNION) {
@@ -709,8 +714,11 @@ class PhpGenerator : public BaseGenerator {
}
break;
}
case BASE_TYPE_UNION: GetUnionField(field, code_ptr); break;
default: FLATBUFFERS_ASSERT(0);
case BASE_TYPE_UNION:
GetUnionField(field, code_ptr);
break;
default:
FLATBUFFERS_ASSERT(0);
}
}
if (IsVector(field.value.type)) {
@@ -722,17 +730,17 @@ class PhpGenerator : 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) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
auto offset = it - struct_def.fields.vec.begin();
if (field.value.type.base_type == BASE_TYPE_UNION) {
std::string &code = *code_ptr;
std::string& code = *code_ptr;
code += Indent + "public static function add";
code += ConvertCase(field.name, Case::kUpperCamel);
code += "(FlatBufferBuilder $builder, $offset)\n";
@@ -743,14 +751,16 @@ class PhpGenerator : public BaseGenerator {
} else {
BuildFieldOfTable(field, offset, code_ptr);
}
if (IsVector(field.value.type)) { BuildVectorOfTable(field, code_ptr); }
if (IsVector(field.value.type)) {
BuildVectorOfTable(field, code_ptr);
}
}
GetEndOffsetOnTable(struct_def, code_ptr);
}
// Generate struct or table methods.
void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
void GenStruct(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, nullptr);
@@ -762,7 +772,7 @@ class PhpGenerator : public BaseGenerator {
NewRootTypeFromBuffer(struct_def, code_ptr);
}
std::string &code = *code_ptr;
std::string& code = *code_ptr;
if (!struct_def.fixed) {
if (parser_.file_identifier_.length()) {
// Return the identifier
@@ -799,7 +809,7 @@ class PhpGenerator : public BaseGenerator {
InitializeExisting(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
auto& field = **it;
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr);
@@ -816,22 +826,22 @@ class PhpGenerator : public BaseGenerator {
}
// Generate enum declarations.
static void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
static void GenEnum(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
GenComment(enum_def.doc_comment, code_ptr, nullptr);
BeginEnum(enum_def.name, code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
auto& ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, Indent.c_str());
EnumMember(enum_def, ev, code_ptr);
}
std::string &code = *code_ptr;
std::string& code = *code_ptr;
code += "\n";
code += Indent + "private static $names = array(\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
auto& ev = **it;
code += Indent + Indent + enum_def.name + "::" + ev.name + "=>" + "\"" +
ev.name + "\",\n";
}
@@ -848,24 +858,29 @@ class PhpGenerator : public BaseGenerator {
}
// Returns the function name that is able to read a value of the given type.
static std::string GenGetter(const Type &type) {
static std::string GenGetter(const Type& type) {
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 GenGetter(type.VectorType());
default: return "Get";
case BASE_TYPE_STRING:
return "__string";
case BASE_TYPE_STRUCT:
return "__struct";
case BASE_TYPE_UNION:
return "__union";
case BASE_TYPE_VECTOR:
return GenGetter(type.VectorType());
default:
return "Get";
}
}
// Returns the method name for use with add/put calls.
static std::string GenMethod(const FieldDef &field) {
static std::string GenMethod(const FieldDef& field) {
return IsScalar(field.value.type.base_type)
? ConvertCase(GenTypeBasic(field.value.type), Case::kUpperCamel)
: (IsStruct(field.value.type) ? "Struct" : "Offset");
}
static std::string GenTypeBasic(const Type &type) {
static std::string GenTypeBasic(const Type& type) {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -878,7 +893,7 @@ class PhpGenerator : public BaseGenerator {
return ctypename[type.base_type];
}
std::string GenDefaultValue(const Value &value) {
std::string GenDefaultValue(const Value& value) {
if (value.type.enum_def) {
if (auto val = value.type.enum_def->FindByValue(value.constant)) {
return WrapInNameSpace(*value.type.enum_def) + "::" + val->name;
@@ -886,9 +901,11 @@ class PhpGenerator : public BaseGenerator {
}
switch (value.type.base_type) {
case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
case BASE_TYPE_BOOL:
return value.constant == "0" ? "false" : "true";
case BASE_TYPE_STRING: return "null";
case BASE_TYPE_STRING:
return "null";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
@@ -898,29 +915,34 @@ class PhpGenerator : public BaseGenerator {
}
return "0";
default: return value.constant;
default:
return value.constant;
}
}
static std::string GenTypePointer(const Type &type) {
static 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_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 "Table";
default:
return "Table";
}
}
static std::string GenTypeGet(const Type &type) {
static std::string GenTypeGet(const Type& type) {
return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
// Create a struct with a builder and the struct's arguments.
static void GenStructBuilder(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
static void GenStructBuilder(const StructDef& struct_def,
std::string* code_ptr) {
std::string& code = *code_ptr;
code += "\n";
code += Indent + "/**\n";
code += Indent + " * @return int offset\n";
@@ -939,8 +961,8 @@ class PhpGenerator : public BaseGenerator {
};
} // namespace php
static bool GeneratePhp(const Parser &parser, const std::string &path,
const std::string &file_name) {
static bool GeneratePhp(const Parser& parser, const std::string& path,
const std::string& file_name) {
php::PhpGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -949,20 +971,21 @@ namespace {
class PhpCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GeneratePhp(parser, path, filename)) { return Status::ERROR; }
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
if (!GeneratePhp(parser, path, filename)) {
return Status::ERROR;
}
return Status::OK;
}
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -970,16 +993,16 @@ class PhpCodeGenerator : public CodeGenerator {
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+522 -420
View File
File diff suppressed because it is too large Load Diff
+296 -263
View File
File diff suppressed because it is too large Load Diff
+290 -250
View File
File diff suppressed because it is too large Load Diff
+88 -80
View File
@@ -30,10 +30,12 @@ namespace flatbuffers {
struct PrintScalarTag {};
struct PrintPointerTag {};
template<typename T> struct PrintTag {
template <typename T>
struct PrintTag {
typedef PrintScalarTag type;
};
template<> struct PrintTag<const void *> {
template <>
struct PrintTag<const void*> {
typedef PrintPointerTag type;
};
@@ -49,7 +51,7 @@ struct JsonPrinter {
int Indent() const { return std::max(opts.indent_step, 0); }
// Output an identifier with or without quotes depending on strictness.
void OutputIdentifier(const std::string &name) {
void OutputIdentifier(const std::string& name) {
if (opts.strict_json) text += '\"';
text += name;
if (opts.strict_json) text += '\"';
@@ -58,15 +60,15 @@ struct JsonPrinter {
// Print (and its template specialization below for pointers) generate text
// for a single FlatBuffer value into JSON format.
// The general case for scalars:
template<typename T>
void PrintScalar(T val, const Type &type, int /*indent*/) {
template <typename T>
void PrintScalar(T val, const Type& type, int /*indent*/) {
if (IsBool(type.base_type)) {
text += val != 0 ? "true" : "false";
return; // done
}
if (opts.output_enum_identifiers && type.enum_def) {
const auto &enum_def = *type.enum_def;
const auto& enum_def = *type.enum_def;
if (auto ev = enum_def.ReverseLookup(static_cast<int64_t>(val))) {
text += '\"';
text += ev->name;
@@ -106,9 +108,9 @@ struct JsonPrinter {
// Print a vector or an array of JSON values, comma seperated, wrapped in
// "[]".
template<typename Container, typename SizeT = typename Container::size_type>
const char *PrintContainer(PrintScalarTag, const Container &c, SizeT size,
const Type &type, int indent, const uint8_t *) {
template <typename Container, typename SizeT = typename Container::size_type>
const char* PrintContainer(PrintScalarTag, const Container& c, SizeT size,
const Type& type, int indent, const uint8_t*) {
const auto elem_indent = indent + Indent();
text += '[';
AddNewLine();
@@ -128,10 +130,10 @@ struct JsonPrinter {
// Print a vector or an array of JSON values, comma seperated, wrapped in
// "[]".
template<typename Container, typename SizeT = typename Container::size_type>
const char *PrintContainer(PrintPointerTag, const Container &c, SizeT size,
const Type &type, int indent,
const uint8_t *prev_val) {
template <typename Container, typename SizeT = typename Container::size_type>
const char* PrintContainer(PrintPointerTag, const Container& c, SizeT size,
const Type& type, int indent,
const uint8_t* prev_val) {
const auto is_struct = IsStruct(type);
const auto elem_indent = indent + Indent();
text += '[';
@@ -142,7 +144,7 @@ struct JsonPrinter {
AddNewLine();
}
AddIndent(elem_indent);
auto ptr = is_struct ? reinterpret_cast<const void *>(
auto ptr = is_struct ? reinterpret_cast<const void*>(
c.Data() + type.struct_def->bytesize * i)
: c[i];
auto err = PrintOffset(ptr, type, elem_indent, prev_val,
@@ -155,29 +157,29 @@ struct JsonPrinter {
return nullptr;
}
template<typename T, typename SizeT = uoffset_t>
const char *PrintVector(const void *val, const Type &type, int indent,
const uint8_t *prev_val) {
template <typename T, typename SizeT = uoffset_t>
const char* PrintVector(const void* val, const Type& type, int indent,
const uint8_t* prev_val) {
typedef Vector<T, SizeT> Container;
typedef typename PrintTag<typename Container::return_type>::type tag;
auto &vec = *reinterpret_cast<const Container *>(val);
auto& vec = *reinterpret_cast<const Container*>(val);
return PrintContainer<Container>(tag(), vec, vec.size(), type, indent,
prev_val);
}
// Print an array a sequence of JSON values, comma separated, wrapped in "[]".
template<typename T>
const char *PrintArray(const void *val, uint16_t size, const Type &type,
template <typename T>
const char* PrintArray(const void* val, uint16_t size, const Type& type,
int indent) {
typedef Array<T, 0xFFFF> Container;
typedef typename PrintTag<typename Container::return_type>::type tag;
auto &arr = *reinterpret_cast<const Container *>(val);
auto& arr = *reinterpret_cast<const Container*>(val);
return PrintContainer<Container>(tag(), arr, size, type, indent, nullptr);
}
const char *PrintOffset(const void *val, const Type &type, int indent,
const uint8_t *prev_val, soffset_t vector_index) {
const char* PrintOffset(const void* val, const Type& type, int indent,
const uint8_t* prev_val, soffset_t vector_index) {
switch (type.base_type) {
case BASE_TYPE_UNION: {
// If this assert hits, you have an corrupt buffer, a union type field
@@ -185,7 +187,7 @@ struct JsonPrinter {
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> *>(
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));
}
@@ -197,10 +199,10 @@ struct JsonPrinter {
}
}
case BASE_TYPE_STRUCT:
return GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val),
return GenStruct(*type.struct_def, reinterpret_cast<const Table*>(val),
indent);
case BASE_TYPE_STRING: {
auto s = reinterpret_cast<const String *>(val);
auto s = reinterpret_cast<const String*>(val);
bool ok = EscapeString(s->c_str(), s->size(), &text,
opts.allow_non_utf8, opts.natural_utf8);
return ok ? nullptr : "string contains non-utf8 bytes";
@@ -240,11 +242,14 @@ struct JsonPrinter {
// clang-format on
return nullptr;
}
default: FLATBUFFERS_ASSERT(0); return "unknown type";
default:
FLATBUFFERS_ASSERT(0);
return "unknown type";
}
}
template<typename T> static T GetFieldDefault(const FieldDef &fd) {
template <typename T>
static T GetFieldDefault(const FieldDef& fd) {
T val{};
auto check = StringToNumber(fd.value.constant.c_str(), &val);
(void)check;
@@ -253,12 +258,12 @@ struct JsonPrinter {
}
// Generate text for a scalar field.
template<typename T>
void GenField(const FieldDef &fd, const Table *table, bool fixed,
template <typename T>
void GenField(const FieldDef& fd, const Table* table, bool fixed,
int indent) {
if (fixed) {
PrintScalar(
reinterpret_cast<const Struct *>(table)->GetField<T>(fd.value.offset),
reinterpret_cast<const Struct*>(table)->GetField<T>(fd.value.offset),
fd.value.type, indent);
} else if (fd.IsOptional()) {
auto opt = table->GetOptional<T, T>(fd.value.offset);
@@ -274,13 +279,13 @@ struct JsonPrinter {
}
// Generate text for non-scalar field.
const char *GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
int indent, const uint8_t *prev_val) {
const void *val = nullptr;
const char* GenFieldOffset(const FieldDef& fd, const Table* table, bool fixed,
int indent, const uint8_t* prev_val) {
const void* val = nullptr;
if (fixed) {
// The only non-scalar fields in structs are structs or arrays.
FLATBUFFERS_ASSERT(IsStruct(fd.value.type) || IsArray(fd.value.type));
val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
val = reinterpret_cast<const Struct*>(table)->GetStruct<const void*>(
fd.value.offset);
} else if (fd.flexbuffer && opts.json_nested_flexbuffers) {
// We could verify this FlexBuffer before access, but since this sits
@@ -289,38 +294,40 @@ struct JsonPrinter {
// The caller should really be verifying the whole.
// If the whole buffer is corrupt, we likely crash before we even get
// here.
auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
auto vec = table->GetPointer<const Vector<uint8_t>*>(fd.value.offset);
auto root = flexbuffers::GetRoot(vec->data(), vec->size());
root.ToString(true, opts.strict_json, text);
return nullptr;
} else if (fd.nested_flatbuffer && opts.json_nested_flatbuffers) {
auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
auto vec = table->GetPointer<const Vector<uint8_t>*>(fd.value.offset);
auto root = GetRoot<Table>(vec->data());
return GenStruct(*fd.nested_flatbuffer, root, indent);
} else {
val = IsStruct(fd.value.type)
? table->GetStruct<const void *>(fd.value.offset)
: table->GetPointer<const void *>(fd.value.offset);
? table->GetStruct<const void*>(fd.value.offset)
: table->GetPointer<const void*>(fd.value.offset);
}
return PrintOffset(val, fd.value.type, indent, prev_val, -1);
}
// Generate text for a struct or table, values separated by commas, indented,
// and bracketed by "{}"
const char *GenStruct(const StructDef &struct_def, const Table *table,
const char* GenStruct(const StructDef& struct_def, const Table* table,
int indent) {
text += '{';
int fieldout = 0;
const uint8_t *prev_val = nullptr;
const uint8_t* prev_val = nullptr;
const auto elem_indent = indent + Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
FieldDef &fd = **it;
FieldDef& fd = **it;
auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
auto output_anyway = (opts.output_default_scalars_in_json || fd.key) &&
IsScalar(fd.value.type.base_type) && !fd.deprecated;
if (is_present || output_anyway) {
if (fieldout++) { AddComma(); }
if (fieldout++) {
AddComma();
}
AddNewLine();
AddIndent(elem_indent);
OutputIdentifier(fd.name);
@@ -352,7 +359,7 @@ struct JsonPrinter {
// clang-format on
// Track prev val for use with union types.
if (struct_def.fixed) {
prev_val = reinterpret_cast<const uint8_t *>(table) + fd.value.offset;
prev_val = reinterpret_cast<const uint8_t*>(table) + fd.value.offset;
} else {
prev_val = table->GetAddressOf(fd.value.offset);
}
@@ -364,18 +371,18 @@ struct JsonPrinter {
return nullptr;
}
JsonPrinter(const Parser &parser, std::string &dest)
JsonPrinter(const Parser& parser, std::string& dest)
: opts(parser.opts), text(dest) {
text.reserve(1024); // Reduce amount of inevitable reallocs.
}
const IDLOptions &opts;
std::string &text;
const IDLOptions& opts;
std::string& text;
};
static const char *GenerateTextImpl(const Parser &parser, const Table *table,
const StructDef &struct_def,
std::string *_text) {
static const char* GenerateTextImpl(const Parser& parser, const Table* table,
const StructDef& struct_def,
std::string* _text) {
JsonPrinter printer(parser, *_text);
auto err = printer.GenStruct(struct_def, table, 0);
if (err) return err;
@@ -385,49 +392,51 @@ static const char *GenerateTextImpl(const Parser &parser, const Table *table,
// Generate a text representation of a flatbuffer in JSON format.
// Deprecated: please use `GenTextFromTable`
bool GenerateTextFromTable(const Parser &parser, const void *table,
const std::string &table_name,
std::string *_text) {
bool GenerateTextFromTable(const Parser& parser, const void* table,
const std::string& table_name, std::string* _text) {
return GenTextFromTable(parser, table, table_name, _text) != nullptr;
}
// Generate a text representation of a flatbuffer in JSON format.
const char *GenTextFromTable(const Parser &parser, const void *table,
const std::string &table_name, std::string *_text) {
const char* GenTextFromTable(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 "unknown struct"; }
auto root = static_cast<const Table *>(table);
if (struct_def == nullptr) {
return "unknown struct";
}
auto root = static_cast<const Table*>(table);
return GenerateTextImpl(parser, root, *struct_def, _text);
}
// Deprecated: please use `GenText`
const char *GenerateText(const Parser &parser, const void *flatbuffer,
std::string *_text) {
const char* GenerateText(const Parser& parser, const void* flatbuffer,
std::string* _text) {
return GenText(parser, flatbuffer, _text);
}
// Generate a text representation of a flatbuffer in JSON format.
const char *GenText(const Parser &parser, const void *flatbuffer,
std::string *_text) {
const char* GenText(const Parser& parser, const void* flatbuffer,
std::string* _text) {
FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType()
auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer)
: GetRoot<Table>(flatbuffer);
return GenerateTextImpl(parser, root, *parser.root_struct_def_, _text);
}
static std::string TextFileName(const std::string &path,
const std::string &file_name) {
static std::string TextFileName(const std::string& path,
const std::string& file_name) {
return path + file_name + ".json";
}
// Deprecated: please use `GenTextFile`
const char *GenerateTextFile(const Parser &parser, const std::string &path,
const std::string &file_name) {
const char* GenerateTextFile(const Parser& parser, const std::string& path,
const std::string& file_name) {
return GenTextFile(parser, path, file_name);
}
const char *GenTextFile(const Parser &parser, const std::string &path,
const std::string &file_name) {
const char* GenTextFile(const Parser& parser, const std::string& path,
const std::string& file_name) {
if (parser.opts.use_flexbuffers) {
std::string json;
parser.flex_root_.ToString(true, parser.opts.strict_json, json);
@@ -446,8 +455,8 @@ const char *GenTextFile(const Parser &parser, const std::string &path,
: "SaveFile failed";
}
static std::string TextMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
static std::string TextMakeRule(const Parser& parser, const std::string& path,
const std::string& file_name) {
if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
@@ -464,8 +473,8 @@ namespace {
class TextCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
auto err = GenTextFile(parser, path, filename);
if (err) {
status_detail = " (" + std::string(err) + ")";
@@ -476,28 +485,27 @@ class TextCodeGenerator : public CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
Status GenerateCode(const uint8_t *, int64_t,
const CodeGenOptions &) override {
Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
Status GenerateMakeRule(const Parser& parser, const std::string& path,
const std::string& filename,
std::string& output) override {
output = TextMakeRule(parser, path, filename);
return Status::OK;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
Status GenerateGrpcCode(const Parser& parser, const std::string& path,
const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
Status GenerateRootFile(const Parser& parser,
const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
+335 -238
View File
File diff suppressed because it is too large Load Diff
+447 -372
View File
File diff suppressed because it is too large Load Diff
+145 -115
View File
@@ -24,47 +24,51 @@ namespace flatbuffers {
namespace {
static void CopyInline(FlatBufferBuilder &fbb,
const reflection::Field &fielddef, const Table &table,
static void CopyInline(FlatBufferBuilder& fbb,
const reflection::Field& fielddef, const Table& table,
size_t align, size_t size) {
fbb.Align(align);
fbb.PushBytes(table.GetStruct<const uint8_t *>(fielddef.offset()), size);
fbb.PushBytes(table.GetStruct<const uint8_t*>(fielddef.offset()), size);
fbb.TrackField(fielddef.offset(), fbb.GetSize());
}
static bool VerifyStruct(flatbuffers::Verifier &v,
const flatbuffers::Table &parent_table,
voffset_t field_offset, const reflection::Object &obj,
static bool VerifyStruct(flatbuffers::Verifier& v,
const flatbuffers::Table& parent_table,
voffset_t field_offset, const reflection::Object& obj,
bool required) {
auto offset = parent_table.GetOptionalFieldOffset(field_offset);
if (required && !offset) { return false; }
if (required && !offset) {
return false;
}
return !offset ||
v.VerifyFieldStruct(reinterpret_cast<const uint8_t *>(&parent_table),
v.VerifyFieldStruct(reinterpret_cast<const uint8_t*>(&parent_table),
offset, obj.bytesize(), obj.minalign());
}
static bool VerifyVectorOfStructs(flatbuffers::Verifier &v,
const flatbuffers::Table &parent_table,
static bool VerifyVectorOfStructs(flatbuffers::Verifier& v,
const flatbuffers::Table& parent_table,
voffset_t field_offset,
const reflection::Object &obj,
const reflection::Object& obj,
bool required) {
auto p = parent_table.GetPointer<const uint8_t *>(field_offset);
if (required && !p) { return false; }
auto p = parent_table.GetPointer<const uint8_t*>(field_offset);
if (required && !p) {
return false;
}
return !p || v.VerifyVectorOrString(p, obj.bytesize());
}
// forward declare to resolve cyclic deps between VerifyObject and VerifyVector
static bool VerifyObject(flatbuffers::Verifier &v,
const reflection::Schema &schema,
const reflection::Object &obj,
const flatbuffers::Table *table, bool required);
static bool VerifyObject(flatbuffers::Verifier& v,
const reflection::Schema& schema,
const reflection::Object& obj,
const flatbuffers::Table* table, bool required);
static bool VerifyUnion(flatbuffers::Verifier &v,
const reflection::Schema &schema, uint8_t utype,
const uint8_t *elem,
const reflection::Field &union_field) {
static bool VerifyUnion(flatbuffers::Verifier& v,
const reflection::Schema& schema, uint8_t utype,
const uint8_t* elem,
const reflection::Field& union_field) {
if (!utype) return true; // Not present.
auto fb_enum = schema.enums()->Get(union_field.type()->index());
if (utype >= fb_enum->values()->size()) return false;
@@ -76,21 +80,21 @@ static bool VerifyUnion(flatbuffers::Verifier &v,
return v.VerifyFromPointer(elem, elem_obj->bytesize());
} else {
return VerifyObject(v, schema, *elem_obj,
reinterpret_cast<const flatbuffers::Table *>(elem),
reinterpret_cast<const flatbuffers::Table*>(elem),
true);
}
}
case reflection::String:
return v.VerifyString(
reinterpret_cast<const flatbuffers::String *>(elem));
default: return false;
return v.VerifyString(reinterpret_cast<const flatbuffers::String*>(elem));
default:
return false;
}
}
static bool VerifyVector(flatbuffers::Verifier &v,
const reflection::Schema &schema,
const flatbuffers::Table &table,
const reflection::Field &vec_field) {
static bool VerifyVector(flatbuffers::Verifier& v,
const reflection::Schema& schema,
const flatbuffers::Table& table,
const reflection::Field& vec_field) {
FLATBUFFERS_ASSERT(vec_field.type()->base_type() == reflection::Vector);
if (!table.VerifyField<uoffset_t>(v, vec_field.offset(), sizeof(uoffset_t)))
return false;
@@ -149,8 +153,8 @@ static bool VerifyVector(flatbuffers::Verifier &v,
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
@@ -162,20 +166,24 @@ static bool VerifyVector(flatbuffers::Verifier &v,
}
case reflection::Vector:
case reflection::None:
default: FLATBUFFERS_ASSERT(false); return false;
default:
FLATBUFFERS_ASSERT(false);
return false;
}
}
static bool VerifyObject(flatbuffers::Verifier &v,
const reflection::Schema &schema,
const reflection::Object &obj,
const flatbuffers::Table *table, bool required) {
static bool VerifyObject(flatbuffers::Verifier& v,
const reflection::Schema& schema,
const reflection::Object& obj,
const flatbuffers::Table* table, bool required) {
if (!table) return !required;
if (!table->VerifyTableStart(v)) return false;
for (uoffset_t i = 0; i < obj.fields()->size(); i++) {
auto field_def = obj.fields()->Get(i);
switch (field_def->type()->base_type()) {
case reflection::None: FLATBUFFERS_ASSERT(false); break;
case reflection::None:
FLATBUFFERS_ASSERT(false);
break;
case reflection::UType:
if (!table->VerifyField<uint8_t>(v, field_def->offset(),
sizeof(uint8_t)))
@@ -243,12 +251,16 @@ static bool VerifyObject(flatbuffers::Verifier &v,
// get union type from the prev field
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 *>(
auto uval = reinterpret_cast<const uint8_t*>(
flatbuffers::GetFieldT(*table, *field_def));
if (!VerifyUnion(v, schema, utype, uval, *field_def)) { return false; }
if (!VerifyUnion(v, schema, utype, uval, *field_def)) {
return false;
}
break;
}
default: FLATBUFFERS_ASSERT(false); break;
default:
FLATBUFFERS_ASSERT(false);
break;
}
}
@@ -259,7 +271,7 @@ static bool VerifyObject(flatbuffers::Verifier &v,
} // namespace
int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data) {
int64_t GetAnyValueI(reflection::BaseType type, const uint8_t* data) {
// clang-format off
#define FLATBUFFERS_GET(T) static_cast<int64_t>(ReadScalar<T>(data))
switch (type) {
@@ -286,13 +298,15 @@ int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data) {
// clang-format on
}
double GetAnyValueF(reflection::BaseType type, const uint8_t *data) {
double GetAnyValueF(reflection::BaseType type, const uint8_t* data) {
switch (type) {
case reflection::Float: return static_cast<double>(ReadScalar<float>(data));
case reflection::Double: return ReadScalar<double>(data);
case reflection::Float:
return static_cast<double>(ReadScalar<float>(data));
case reflection::Double:
return ReadScalar<double>(data);
case reflection::String: {
auto s =
reinterpret_cast<const String *>(ReadScalar<uoffset_t>(data) + data);
reinterpret_cast<const String*>(ReadScalar<uoffset_t>(data) + data);
if (s) {
double d;
StringToNumber(s->c_str(), &d);
@@ -301,18 +315,20 @@ double GetAnyValueF(reflection::BaseType type, const uint8_t *data) {
return 0.0;
}
}
default: return static_cast<double>(GetAnyValueI(type, data));
default:
return static_cast<double>(GetAnyValueI(type, data));
}
}
std::string GetAnyValueS(reflection::BaseType type, const uint8_t *data,
const reflection::Schema *schema, int type_index) {
std::string GetAnyValueS(reflection::BaseType type, const uint8_t* data,
const reflection::Schema* schema, int type_index) {
switch (type) {
case reflection::Float:
case reflection::Double: return NumToString(GetAnyValueF(type, data));
case reflection::Double:
return NumToString(GetAnyValueF(type, data));
case reflection::String: {
auto s =
reinterpret_cast<const String *>(ReadScalar<uoffset_t>(data) + data);
reinterpret_cast<const String*>(ReadScalar<uoffset_t>(data) + data);
return s ? s->c_str() : "";
}
case reflection::Obj:
@@ -320,17 +336,17 @@ std::string GetAnyValueS(reflection::BaseType type, const uint8_t *data,
// Convert the table to a string. This is mostly for debugging purposes,
// and does NOT promise to be JSON compliant.
// Also prefixes the type.
auto &objectdef = *schema->objects()->Get(type_index);
auto& objectdef = *schema->objects()->Get(type_index);
auto s = objectdef.name()->str();
if (objectdef.is_struct()) {
s += "(struct)"; // TODO: implement this as well.
} else {
auto table_field = reinterpret_cast<const Table *>(
auto table_field = reinterpret_cast<const Table*>(
ReadScalar<uoffset_t>(data) + data);
s += " { ";
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
auto &fielddef = **it;
auto& fielddef = **it;
if (!table_field->CheckField(fielddef.offset())) continue;
auto val = GetAnyFieldS(*table_field, fielddef, schema);
if (fielddef.type()->base_type() == reflection::String) {
@@ -351,14 +367,16 @@ std::string GetAnyValueS(reflection::BaseType type, const uint8_t *data,
return "(table)";
}
case reflection::Vector:
return "[(elements)]"; // TODO: implement this as well.
case reflection::Union: return "(union)"; // TODO: implement this as well.
default: return NumToString(GetAnyValueI(type, data));
return "[(elements)]"; // TODO: implement this as well.
case reflection::Union:
return "(union)"; // TODO: implement this as well.
default:
return NumToString(GetAnyValueI(type, data));
}
}
void ForAllFields(const reflection::Object *object, bool reverse,
std::function<void(const reflection::Field *)> func) {
void ForAllFields(const reflection::Object* object, bool reverse,
std::function<void(const reflection::Field*)> func) {
std::vector<uint32_t> field_to_id_map;
field_to_id_map.resize(object->fields()->size());
@@ -374,7 +392,7 @@ void ForAllFields(const reflection::Object *object, bool reverse,
}
}
void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val) {
void SetAnyValueI(reflection::BaseType type, uint8_t* data, int64_t val) {
// clang-format off
#define FLATBUFFERS_SET(T) WriteScalar(data, static_cast<T>(val))
switch (type) {
@@ -397,16 +415,22 @@ void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val) {
// clang-format on
}
void SetAnyValueF(reflection::BaseType type, uint8_t *data, double val) {
void SetAnyValueF(reflection::BaseType type, uint8_t* data, double val) {
switch (type) {
case reflection::Float: WriteScalar(data, static_cast<float>(val)); break;
case reflection::Double: WriteScalar(data, val); break;
case reflection::Float:
WriteScalar(data, static_cast<float>(val));
break;
case reflection::Double:
WriteScalar(data, val);
break;
// TODO: support strings.
default: SetAnyValueI(type, data, static_cast<int64_t>(val)); break;
default:
SetAnyValueI(type, data, static_cast<int64_t>(val));
break;
}
}
void SetAnyValueS(reflection::BaseType type, uint8_t *data, const char *val) {
void SetAnyValueS(reflection::BaseType type, uint8_t* data, const char* val) {
switch (type) {
case reflection::Float:
case reflection::Double: {
@@ -416,7 +440,9 @@ void SetAnyValueS(reflection::BaseType type, uint8_t *data, const char *val) {
break;
}
// TODO: support strings.
default: SetAnyValueI(type, data, StringToInt(val)); break;
default:
SetAnyValueI(type, data, StringToInt(val));
break;
}
}
@@ -430,9 +456,9 @@ void SetAnyValueS(reflection::BaseType type, uint8_t *data, const char *val) {
// pass in your root_table type as well.
class ResizeContext {
public:
ResizeContext(const reflection::Schema &schema, uoffset_t start, int delta,
std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table = nullptr)
ResizeContext(const reflection::Schema& schema, uoffset_t start, int delta,
std::vector<uint8_t>* flatbuf,
const reflection::Object* root_table = nullptr)
: schema_(schema),
startptr_(flatbuf->data() + start),
delta_(delta),
@@ -455,8 +481,8 @@ class ResizeContext {
// Check if the range between first (lower address) and second straddles
// the insertion point. If it does, change the offset at offsetloc (of
// type T, with direction D).
template<typename T, int D>
void Straddle(const void *first, const void *second, void *offsetloc) {
template <typename T, int D>
void Straddle(const void* first, const void* second, void* offsetloc) {
if (first <= startptr_ && second >= startptr_) {
WriteScalar<T>(offsetloc, ReadScalar<T>(offsetloc) + delta_ * D);
DagCheck(offsetloc) = true;
@@ -469,18 +495,18 @@ class ResizeContext {
// resize actually happens.
// This must be checked for every offset, since we can't know which offsets
// will straddle and which won't.
uint8_t &DagCheck(const void *offsetloc) {
auto dag_idx = reinterpret_cast<const uoffset_t *>(offsetloc) -
reinterpret_cast<const uoffset_t *>(buf_.data());
uint8_t& DagCheck(const void* offsetloc) {
auto dag_idx = reinterpret_cast<const uoffset_t*>(offsetloc) -
reinterpret_cast<const uoffset_t*>(buf_.data());
return dag_check_[dag_idx];
}
void ResizeTable(const reflection::Object &objectdef, Table *table) {
void ResizeTable(const reflection::Object& objectdef, Table* table) {
if (DagCheck(table)) return; // Table already visited.
auto vtable = table->GetVTable();
// Early out: since all fields inside the table must point forwards in
// memory, if the insertion point is before the table we can stop here.
auto tableloc = reinterpret_cast<uint8_t *>(table);
auto tableloc = reinterpret_cast<uint8_t*>(table);
if (startptr_ <= tableloc) {
// Check if insertion point is between the table and a vtable that
// precedes it. This can't happen in current construction code, but check
@@ -490,7 +516,7 @@ class ResizeContext {
// Check each field.
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
auto &fielddef = **it;
auto& fielddef = **it;
auto base_type = fielddef.type()->base_type();
// Ignore scalars.
if (base_type <= reflection::Double) continue;
@@ -512,7 +538,7 @@ class ResizeContext {
switch (base_type) {
case reflection::Obj: {
if (subobjectdef) {
ResizeTable(*subobjectdef, reinterpret_cast<Table *>(ref));
ResizeTable(*subobjectdef, reinterpret_cast<Table*>(ref));
}
break;
}
@@ -520,7 +546,7 @@ class ResizeContext {
auto elem_type = fielddef.type()->element();
if (elem_type != reflection::Obj && elem_type != reflection::String)
break;
auto vec = reinterpret_cast<Vector<uoffset_t> *>(ref);
auto vec = reinterpret_cast<Vector<uoffset_t>*>(ref);
auto elemobjectdef =
elem_type == reflection::Obj
? schema_.objects()->Get(fielddef.type()->index())
@@ -532,17 +558,19 @@ class ResizeContext {
auto dest = loc + vec->Get(i);
Straddle<uoffset_t, 1>(loc, dest, loc);
if (elemobjectdef)
ResizeTable(*elemobjectdef, reinterpret_cast<Table *>(dest));
ResizeTable(*elemobjectdef, reinterpret_cast<Table*>(dest));
}
break;
}
case reflection::Union: {
ResizeTable(GetUnionType(schema_, objectdef, fielddef, *table),
reinterpret_cast<Table *>(ref));
reinterpret_cast<Table*>(ref));
break;
}
case reflection::String: break;
default: FLATBUFFERS_ASSERT(false);
case reflection::String:
break;
default:
FLATBUFFERS_ASSERT(false);
}
}
// Check if the vtable offset points beyond the insertion point.
@@ -553,19 +581,19 @@ class ResizeContext {
}
private:
const reflection::Schema &schema_;
uint8_t *startptr_;
const reflection::Schema& schema_;
uint8_t* startptr_;
int delta_;
std::vector<uint8_t> &buf_;
std::vector<uint8_t>& buf_;
std::vector<uint8_t> dag_check_;
};
void SetString(const reflection::Schema &schema, const std::string &val,
const String *str, std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table) {
void SetString(const reflection::Schema& schema, const std::string& val,
const String* str, std::vector<uint8_t>* flatbuf,
const reflection::Object* root_table) {
auto delta = static_cast<int>(val.size()) - static_cast<int>(str->size());
auto str_start = static_cast<uoffset_t>(
reinterpret_cast<const uint8_t *>(str) - flatbuf->data());
reinterpret_cast<const uint8_t*>(str) - flatbuf->data());
auto start = str_start + static_cast<uoffset_t>(sizeof(uoffset_t));
if (delta) {
// Clear the old string, since we don't want parts of it remaining.
@@ -580,13 +608,13 @@ void SetString(const reflection::Schema &schema, const std::string &val,
memcpy(flatbuf->data() + start, val.c_str(), val.size() + 1);
}
uint8_t *ResizeAnyVector(const reflection::Schema &schema, uoffset_t newsize,
const VectorOfAny *vec, uoffset_t num_elems,
uoffset_t elem_size, std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table) {
uint8_t* ResizeAnyVector(const reflection::Schema& schema, uoffset_t newsize,
const VectorOfAny* vec, uoffset_t num_elems,
uoffset_t elem_size, std::vector<uint8_t>* flatbuf,
const reflection::Object* root_table) {
auto delta_elem = static_cast<int>(newsize) - static_cast<int>(num_elems);
auto delta_bytes = delta_elem * static_cast<int>(elem_size);
auto vec_start = reinterpret_cast<const uint8_t *>(vec) - flatbuf->data();
auto vec_start = reinterpret_cast<const uint8_t*>(vec) - flatbuf->data();
auto start = static_cast<uoffset_t>(vec_start) +
static_cast<uoffset_t>(sizeof(uoffset_t)) +
elem_size * num_elems;
@@ -608,8 +636,8 @@ uint8_t *ResizeAnyVector(const reflection::Schema &schema, uoffset_t newsize,
return flatbuf->data() + start;
}
const uint8_t *AddFlatBuffer(std::vector<uint8_t> &flatbuf,
const uint8_t *newbuf, size_t newlen) {
const uint8_t* AddFlatBuffer(std::vector<uint8_t>& flatbuf,
const uint8_t* newbuf, size_t newlen) {
// Align to sizeof(uoffset_t) past sizeof(largest_scalar_t) since we're
// going to chop off the root offset.
while ((flatbuf.size() & (sizeof(uoffset_t) - 1)) ||
@@ -623,16 +651,16 @@ const uint8_t *AddFlatBuffer(std::vector<uint8_t> &flatbuf,
return flatbuf.data() + insertion_point + root_offset;
}
Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
const reflection::Schema &schema,
const reflection::Object &objectdef,
const Table &table, bool use_string_pooling) {
Offset<const Table*> CopyTable(FlatBufferBuilder& fbb,
const reflection::Schema& schema,
const reflection::Object& objectdef,
const Table& table, bool use_string_pooling) {
// Before we can construct the table, we have to first generate any
// subobjects, and collect their offsets.
std::vector<uoffset_t> offsets;
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
auto &fielddef = **it;
auto& fielddef = **it;
// Skip if field is not present in the source.
if (!table.CheckField(fielddef.offset())) continue;
uoffset_t offset = 0;
@@ -644,7 +672,7 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
break;
}
case reflection::Obj: {
auto &subobjectdef = *schema.objects()->Get(fielddef.type()->index());
auto& subobjectdef = *schema.objects()->Get(fielddef.type()->index());
if (!subobjectdef.is_struct()) {
offset = CopyTable(fbb, schema, subobjectdef,
*GetFieldT(table, fielddef), use_string_pooling)
@@ -653,7 +681,7 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
break;
}
case reflection::Union: {
auto &subobjectdef = GetUnionType(schema, objectdef, fielddef, table);
auto& subobjectdef = GetUnionType(schema, objectdef, fielddef, table);
offset = CopyTable(fbb, schema, subobjectdef,
*GetFieldT(table, fielddef), use_string_pooling)
.o;
@@ -661,7 +689,7 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
}
case reflection::Vector: {
auto vec =
table.GetPointer<const Vector<Offset<Table>> *>(fielddef.offset());
table.GetPointer<const Vector<Offset<Table>>*>(fielddef.offset());
auto element_base_type = fielddef.type()->element();
auto elemobjectdef =
element_base_type == reflection::Obj
@@ -669,8 +697,8 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
: nullptr;
switch (element_base_type) {
case reflection::String: {
std::vector<Offset<const String *>> elements(vec->size());
auto vec_s = reinterpret_cast<const Vector<Offset<String>> *>(vec);
std::vector<Offset<const String*>> elements(vec->size());
auto vec_s = reinterpret_cast<const Vector<Offset<String>>*>(vec);
for (uoffset_t i = 0; i < vec_s->size(); i++) {
elements[i] = use_string_pooling
? fbb.CreateSharedString(vec_s->Get(i)).o
@@ -681,7 +709,7 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
}
case reflection::Obj: {
if (!elemobjectdef->is_struct()) {
std::vector<Offset<const Table *>> elements(vec->size());
std::vector<Offset<const Table*>> elements(vec->size());
for (uoffset_t i = 0; i < vec->size(); i++) {
elements[i] = CopyTable(fbb, schema, *elemobjectdef,
*vec->Get(i), use_string_pooling);
@@ -707,19 +735,21 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
default: // Scalars.
break;
}
if (offset) { offsets.push_back(offset); }
if (offset) {
offsets.push_back(offset);
}
}
// Now we can build the actual table from either offsets or scalar data.
auto start = objectdef.is_struct() ? fbb.StartStruct(objectdef.minalign())
: fbb.StartTable();
size_t offset_idx = 0;
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
auto &fielddef = **it;
auto& fielddef = **it;
if (!table.CheckField(fielddef.offset())) continue;
auto base_type = fielddef.type()->base_type();
switch (base_type) {
case reflection::Obj: {
auto &subobjectdef = *schema.objects()->Get(fielddef.type()->index());
auto& subobjectdef = *schema.objects()->Get(fielddef.type()->index());
if (subobjectdef.is_struct()) {
CopyInline(fbb, fielddef, table, subobjectdef.minalign(),
subobjectdef.bytesize());
@@ -748,17 +778,17 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
}
}
bool Verify(const reflection::Schema &schema, const reflection::Object &root,
const uint8_t *const buf, const size_t length,
bool Verify(const reflection::Schema& schema, const reflection::Object& root,
const uint8_t* const buf, const size_t length,
const uoffset_t max_depth, const uoffset_t max_tables) {
Verifier v(buf, length, max_depth, max_tables);
return VerifyObject(v, schema, root, flatbuffers::GetAnyRoot(buf),
/*required=*/true);
}
bool VerifySizePrefixed(const reflection::Schema &schema,
const reflection::Object &root,
const uint8_t *const buf, const size_t length,
bool VerifySizePrefixed(const reflection::Schema& schema,
const reflection::Object& root,
const uint8_t* const buf, const size_t length,
const uoffset_t max_depth, const uoffset_t max_tables) {
Verifier v(buf, length, max_depth, max_tables);
return VerifyObject(v, schema, root, flatbuffers::GetAnySizePrefixedRoot(buf),
+70 -53
View File
@@ -58,12 +58,12 @@ namespace flatbuffers {
namespace {
static bool FileExistsRaw(const char *name) {
static bool FileExistsRaw(const char* name) {
std::ifstream ifs(name);
return ifs.good();
}
static bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
static bool LoadFileRaw(const char* name, bool binary, std::string* buf) {
if (DirExists(name)) return false;
std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
if (!ifs.is_open()) return false;
@@ -86,7 +86,7 @@ static bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
LoadFileFunction g_load_file_function = LoadFileRaw;
FileExistsFunction g_file_exists_function = FileExistsRaw;
static std::string ToCamelCase(const std::string &input, bool is_upper) {
static std::string ToCamelCase(const std::string& input, bool is_upper) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (!i && input[i] == '_') {
@@ -105,7 +105,7 @@ static std::string ToCamelCase(const std::string &input, bool is_upper) {
return s;
}
static std::string ToSnakeCase(const std::string &input, bool screaming) {
static std::string ToSnakeCase(const std::string& input, bool screaming) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (i == 0) {
@@ -127,14 +127,16 @@ static std::string ToSnakeCase(const std::string &input, bool screaming) {
return s;
}
std::string ToAll(const std::string &input,
std::string ToAll(const std::string& input,
std::function<char(const char)> transform) {
std::string s;
for (size_t i = 0; i < input.length(); i++) { s += transform(input[i]); }
for (size_t i = 0; i < input.length(); i++) {
s += transform(input[i]);
}
return s;
}
std::string CamelToSnake(const std::string &input) {
std::string CamelToSnake(const std::string& input) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (i == 0) {
@@ -156,7 +158,7 @@ std::string CamelToSnake(const std::string &input) {
return s;
}
std::string DasherToSnake(const std::string &input) {
std::string DasherToSnake(const std::string& input) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (input[i] == '-') {
@@ -168,11 +170,11 @@ std::string DasherToSnake(const std::string &input) {
return s;
}
std::string ToDasher(const std::string &input) {
std::string ToDasher(const std::string& input) {
std::string s;
char p = 0;
for (size_t i = 0; i < input.length(); i++) {
char const &c = input[i];
char const& c = input[i];
if (c == '_') {
if (i > 0 && p != kPathSeparator &&
// The following is a special case to ignore digits after a _. This is
@@ -190,7 +192,7 @@ std::string ToDasher(const std::string &input) {
}
// Converts foo_bar_123baz_456 to foo_bar123_baz456
std::string SnakeToSnake2(const std::string &s) {
std::string SnakeToSnake2(const std::string& s) {
if (s.length() <= 1) return s;
std::string result;
result.reserve(s.size());
@@ -212,17 +214,17 @@ std::string SnakeToSnake2(const std::string &s) {
} // namespace
bool LoadFile(const char *name, bool binary, std::string *buf) {
bool LoadFile(const char* name, bool binary, std::string* buf) {
FLATBUFFERS_ASSERT(g_load_file_function);
return g_load_file_function(name, binary, buf);
}
bool FileExists(const char *name) {
bool FileExists(const char* name) {
FLATBUFFERS_ASSERT(g_file_exists_function);
return g_file_exists_function(name);
}
bool DirExists(const char *name) {
bool DirExists(const char* name) {
// clang-format off
#ifdef _WIN32
@@ -252,7 +254,7 @@ FileExistsFunction SetFileExistsFunction(
return previous_function;
}
bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
bool SaveFile(const char* name, const char* buf, size_t len, bool binary) {
std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
if (!ofs.is_open()) return false;
ofs.write(buf, len);
@@ -264,30 +266,30 @@ bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
// on Windows when paths are string-compared.
static const char kPathSeparatorWindows = '\\';
static const char *PathSeparatorSet = "\\/"; // Intentionally no ':'
static const char* PathSeparatorSet = "\\/"; // Intentionally no ':'
std::string StripExtension(const std::string &filepath) {
std::string StripExtension(const std::string& filepath) {
size_t i = filepath.find_last_of('.');
return i != std::string::npos ? filepath.substr(0, i) : filepath;
}
std::string GetExtension(const std::string &filepath) {
std::string GetExtension(const std::string& filepath) {
size_t i = filepath.find_last_of('.');
return i != std::string::npos ? filepath.substr(i + 1) : "";
}
std::string StripPath(const std::string &filepath) {
std::string StripPath(const std::string& filepath) {
size_t i = filepath.find_last_of(PathSeparatorSet);
return i != std::string::npos ? filepath.substr(i + 1) : filepath;
}
std::string StripFileName(const std::string &filepath) {
std::string StripFileName(const std::string& filepath) {
size_t i = filepath.find_last_of(PathSeparatorSet);
return i != std::string::npos ? filepath.substr(0, i) : "";
}
std::string StripPrefix(const std::string &filepath,
const std::string &prefix_to_remove) {
std::string StripPrefix(const std::string& filepath,
const std::string& prefix_to_remove) {
if (!strncmp(filepath.c_str(), prefix_to_remove.c_str(),
prefix_to_remove.size())) {
return filepath.substr(prefix_to_remove.size());
@@ -295,11 +297,11 @@ std::string StripPrefix(const std::string &filepath,
return filepath;
}
std::string ConCatPathFileName(const std::string &path,
const std::string &filename) {
std::string ConCatPathFileName(const std::string& path,
const std::string& filename) {
std::string filepath = path;
if (filepath.length()) {
char &filepath_last_character = filepath.back();
char& filepath_last_character = filepath.back();
if (filepath_last_character == kPathSeparatorWindows) {
filepath_last_character = kPathSeparator;
} else if (filepath_last_character != kPathSeparator) {
@@ -314,19 +316,19 @@ std::string ConCatPathFileName(const std::string &path,
return filepath;
}
std::string PosixPath(const char *path) {
std::string PosixPath(const char* path) {
std::string p = path;
std::replace(p.begin(), p.end(), '\\', '/');
return p;
}
std::string PosixPath(const std::string &path) {
std::string PosixPath(const std::string& path) {
return PosixPath(path.c_str());
}
void EnsureDirExists(const std::string &filepath) {
void EnsureDirExists(const std::string& filepath) {
auto parent = StripFileName(filepath);
if (parent.length()) EnsureDirExists(parent);
// clang-format off
// clang-format off
#ifdef _WIN32
(void)_mkdir(filepath.c_str());
@@ -336,11 +338,13 @@ void EnsureDirExists(const std::string &filepath) {
// clang-format on
}
std::string FilePath(const std::string& project, const std::string& filePath, bool absolute) {
return (absolute) ? AbsolutePath(filePath) : RelativeToRootPath(project, filePath);
std::string FilePath(const std::string& project, const std::string& filePath,
bool absolute) {
return (absolute) ? AbsolutePath(filePath)
: RelativeToRootPath(project, filePath);
}
std::string AbsolutePath(const std::string &filepath) {
std::string AbsolutePath(const std::string& filepath) {
// clang-format off
#ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
@@ -365,16 +369,16 @@ std::string AbsolutePath(const std::string &filepath) {
// clang-format on
}
std::string RelativeToRootPath(const std::string &project,
const std::string &filepath) {
std::string RelativeToRootPath(const std::string& project,
const std::string& filepath) {
std::string absolute_project = PosixPath(AbsolutePath(project));
if (absolute_project.back() != '/') absolute_project += "/";
std::string absolute_filepath = PosixPath(AbsolutePath(filepath));
// Find the first character where they disagree.
// The previous directory is the lowest common ancestor;
const char *a = absolute_project.c_str();
const char *b = absolute_filepath.c_str();
const char* a = absolute_project.c_str();
const char* b = absolute_filepath.c_str();
size_t common_prefix_len = 0;
while (*a != '\0' && *b != '\0' && *a == *b) {
if (*a == '/') common_prefix_len = a - absolute_project.c_str();
@@ -383,7 +387,7 @@ std::string RelativeToRootPath(const std::string &project,
}
// the number of ../ to prepend to b depends on the number of remaining
// directories in A.
const char *suffix = absolute_project.c_str() + common_prefix_len;
const char* suffix = absolute_project.c_str() + common_prefix_len;
size_t num_up = 0;
while (*suffix != '\0')
if (*suffix++ == '/') num_up++;
@@ -416,21 +420,21 @@ ClassicLocale ClassicLocale::instance_;
#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
std::string RemoveStringQuotes(const std::string &s) {
std::string RemoveStringQuotes(const std::string& s) {
auto ch = *s.c_str();
return ((s.size() >= 2) && (ch == '\"' || ch == '\'') && (ch == s.back()))
? s.substr(1, s.length() - 2)
: s;
}
bool SetGlobalTestLocale(const char *locale_name, std::string *_value) {
bool SetGlobalTestLocale(const char* locale_name, std::string* _value) {
const auto the_locale = setlocale(LC_ALL, locale_name);
if (!the_locale) return false;
if (_value) *_value = std::string(the_locale);
return true;
}
bool ReadEnvironmentVariable(const char *var_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
@@ -440,7 +444,7 @@ bool ReadEnvironmentVariable(const char *var_name, std::string *_value) {
return true;
}
std::string ConvertCase(const std::string &input, Case output_case,
std::string ConvertCase(const std::string& input, Case output_case,
Case input_case) {
if (output_case == Case::kKeep) return input;
// The output cases expect snake_case inputs, so if we don't have that input
@@ -449,26 +453,39 @@ std::string ConvertCase(const std::string &input, Case output_case,
case Case::kLowerCamel:
case Case::kUpperCamel:
return ConvertCase(CamelToSnake(input), output_case);
case Case::kDasher: return ConvertCase(DasherToSnake(input), output_case);
case Case::kKeep: printf("WARNING: Converting from kKeep case.\n"); break;
case Case::kDasher:
return ConvertCase(DasherToSnake(input), output_case);
case Case::kKeep:
printf("WARNING: Converting from kKeep case.\n");
break;
default:
case Case::kSnake:
case Case::kScreamingSnake:
case Case::kAllLower:
case Case::kAllUpper: break;
case Case::kAllUpper:
break;
}
switch (output_case) {
case Case::kUpperCamel: return ToCamelCase(input, true);
case Case::kLowerCamel: return ToCamelCase(input, false);
case Case::kSnake: return input;
case Case::kScreamingSnake: return ToSnakeCase(input, true);
case Case::kAllUpper: return ToAll(input, CharToUpper);
case Case::kAllLower: return ToAll(input, CharToLower);
case Case::kDasher: return ToDasher(input);
case Case::kSnake2: return SnakeToSnake2(input);
case Case::kUpperCamel:
return ToCamelCase(input, true);
case Case::kLowerCamel:
return ToCamelCase(input, false);
case Case::kSnake:
return input;
case Case::kScreamingSnake:
return ToSnakeCase(input, true);
case Case::kAllUpper:
return ToAll(input, CharToUpper);
case Case::kAllLower:
return ToAll(input, CharToLower);
case Case::kDasher:
return ToDasher(input);
case Case::kSnake2:
return SnakeToSnake2(input);
default:
case Case::kUnknown: return input;
case Case::kUnknown:
return input;
}
}