fixed bfbs gen to pass extra options (#7949)

This commit is contained in:
Derek Bailey
2023-05-09 22:42:31 -07:00
committed by GitHub
parent 10b79d87c1
commit 3e6cd51b63
26 changed files with 572 additions and 305 deletions

View File

@@ -23,9 +23,8 @@ GenerateGo()
GenerateJava() GenerateJava()
GenerateKotlin() GenerateKotlin()
GenerateLobster() GenerateLobster()
# TODO these doesn't respect the output prefix, fix and reenable GenerateLua()
# GenerateLua() GenerateNim()
# GenerateNim()
GeneratePhp() GeneratePhp()
GeneratePython() GeneratePython()
GenerateRust() GenerateRust()

48
goldens/lua/Galaxy.lua Normal file
View File

@@ -0,0 +1,48 @@
--[[ Galaxy
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Galaxy = {}
local mt = {}
function Galaxy.New()
local o = {}
setmetatable(o, {__index = mt})
return o
end
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:NumStars()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
end
return 0
end
function Galaxy.Start(builder)
builder:StartObject(1)
end
function Galaxy.AddNumStars(builder, numStars)
builder:PrependInt64Slot(0, numStars, 0)
end
function Galaxy.End(builder)
return builder:EndObject()
end
return Galaxy

88
goldens/lua/Universe.lua Normal file
View File

@@ -0,0 +1,88 @@
--[[ Universe
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
--]]
local __Galaxy = require('Galaxy')
local flatbuffers = require('flatbuffers')
local Universe = {}
local mt = {}
function Universe.New()
local o = {}
setmetatable(o, {__index = mt})
return o
end
function Universe.GetRootAsUniverse(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Universe.New()
o:Init(buf, n + offset)
return o
end
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:Age()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Float64, self.view.pos + o)
end
return 0.0
end
function mt:Galaxies(j)
local o = self.view:Offset(6)
if o ~= 0 then
local x = self.view:Vector(o)
x = x + ((j-1) * 4)
x = self.view:Indirect(x)
local obj = __Galaxy.New()
obj:Init(self.view.bytes, x)
return obj
end
end
function mt:GalaxiesLength()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function Universe.Start(builder)
builder:StartObject(2)
end
function Universe.AddAge(builder, age)
builder:PrependFloat64Slot(0, age, 0.0)
end
function Universe.AddGalaxies(builder, galaxies)
builder:PrependUOffsetTRelativeSlot(1, galaxies, 0)
end
function Universe.StartGalaxiesVector(builder, numElems)
return builder:StartVector(4, numElems, 4)
end
function Universe.End(builder)
return builder:EndObject()
end
return Universe

26
goldens/nim/Galaxy.nim Normal file
View File

@@ -0,0 +1,26 @@
#[ Galaxy
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
]#
import flatbuffers
type Galaxy* = object of FlatObj
func numStars*(self: Galaxy): int64 =
let o = self.tab.Offset(4)
if o != 0:
return Get[int64](self.tab, self.tab.Pos + o)
return 0
func `numStars=`*(self: var Galaxy, n: int64): bool =
return self.tab.MutateSlot(4, n)
proc GalaxyStart*(builder: var Builder) =
builder.StartObject(1)
proc GalaxyAddnumStars*(builder: var Builder, numStars: int64) =
builder.PrependSlot(0, numStars, default(int64))
proc GalaxyEnd*(builder: var Builder): uoffset =
return builder.EndObject()

46
goldens/nim/Universe.nim Normal file
View File

@@ -0,0 +1,46 @@
#[ Universe
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
]#
import Galaxy as Galaxy
import flatbuffers
import std/options
type Universe* = object of FlatObj
func age*(self: Universe): float64 =
let o = self.tab.Offset(4)
if o != 0:
return Get[float64](self.tab, self.tab.Pos + o)
return 0.0
func `age=`*(self: var Universe, n: float64): bool =
return self.tab.MutateSlot(4, n)
func galaxiesLength*(self: Universe): int =
let o = self.tab.Offset(6)
if o != 0:
return self.tab.VectorLen(o)
func galaxies*(self: Universe, j: int): Galaxy.Galaxy =
let o = self.tab.Offset(6)
if o != 0:
var x = self.tab.Vector(o)
x += j.uoffset * 4.uoffset
return Galaxy.Galaxy(tab: Vtable(Bytes: self.tab.Bytes, Pos: x))
func galaxies*(self: Universe): seq[Galaxy.Galaxy] =
let len = self.galaxiesLength
for i in countup(0, len - 1):
result.add(self.galaxies(i))
proc UniverseStart*(builder: var Builder) =
builder.StartObject(2)
proc UniverseAddage*(builder: var Builder, age: float64) =
builder.PrependSlot(0, age, default(float64))
proc UniverseAddgalaxies*(builder: var Builder, galaxies: uoffset) =
builder.PrependSlot(1, galaxies, default(uoffset))
proc UniverseStartgalaxiesVector*(builder: var Builder, numElems: uoffset) =
builder.StartVector(4, numElems, 4)
proc UniverseEnd*(builder: var Builder): uoffset =
return builder.EndObject()

View File

@@ -23,6 +23,10 @@
namespace flatbuffers { namespace flatbuffers {
struct CodeGenOptions {
std::string output_path;
};
// A code generator interface for producing converting flatbuffer schema into // A code generator interface for producing converting flatbuffer schema into
// code. // code.
class CodeGenerator { class CodeGenerator {
@@ -56,7 +60,8 @@ class CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
virtual Status GenerateCode(const uint8_t *buffer, int64_t length) = 0; virtual Status GenerateCode(const uint8_t *buffer, int64_t length,
const CodeGenOptions &options) = 0;
virtual Status GenerateMakeRule(const Parser &parser, const std::string &path, virtual Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename, const std::string &filename,

View File

@@ -101,15 +101,15 @@ class BaseBfbsGenerator : public CodeGenerator {
virtual ~BaseBfbsGenerator() {} virtual ~BaseBfbsGenerator() {}
BaseBfbsGenerator() : schema_(nullptr) {} BaseBfbsGenerator() : schema_(nullptr) {}
virtual Status GenerateFromSchema( virtual Status GenerateFromSchema(const reflection::Schema *schema,
const reflection::Schema *schema) = 0; const CodeGenOptions &options) = 0;
virtual uint64_t SupportedAdvancedFeatures() const = 0; virtual uint64_t SupportedAdvancedFeatures() const = 0;
// Override of the Generator::GenerateCode method that does the initial // Override of the Generator::GenerateCode method that does the initial
// deserialization and verification steps. // deserialization and verification steps.
Status GenerateCode(const uint8_t *buffer, Status GenerateCode(const uint8_t *buffer, int64_t length,
int64_t length) FLATBUFFERS_OVERRIDE { const CodeGenOptions &options) FLATBUFFERS_OVERRIDE {
flatbuffers::Verifier verifier(buffer, static_cast<size_t>(length)); flatbuffers::Verifier verifier(buffer, static_cast<size_t>(length));
if (!reflection::VerifySchemaBuffer(verifier)) { if (!reflection::VerifySchemaBuffer(verifier)) {
return FAILED_VERIFICATION; return FAILED_VERIFICATION;
@@ -124,7 +124,7 @@ class BaseBfbsGenerator : public CodeGenerator {
return FAILED_VERIFICATION; return FAILED_VERIFICATION;
} }
Status status = GenerateFromSchema(schema_); Status status = GenerateFromSchema(schema_, options);
schema_ = nullptr; schema_ = nullptr;
return status; return status;
} }

View File

@@ -28,6 +28,7 @@
#include "bfbs_namer.h" #include "bfbs_namer.h"
// The intermediate representation schema. // The intermediate representation schema.
#include "flatbuffers/code_generator.h"
#include "flatbuffers/reflection.h" #include "flatbuffers/reflection.h"
#include "flatbuffers/reflection_generated.h" #include "flatbuffers/reflection_generated.h"
@@ -78,7 +79,10 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version), flatc_version_(flatc_version),
namer_(LuaDefaultConfig(), LuaKeywords()) {} namer_(LuaDefaultConfig(), LuaKeywords()) {}
Status GenerateFromSchema(const r::Schema *schema) FLATBUFFERS_OVERRIDE { 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())) { if (!GenerateObjects(schema->objects(), schema->root_table())) {
return ERROR; return ERROR;
@@ -89,7 +93,7 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
using BaseBfbsGenerator::GenerateCode; using BaseBfbsGenerator::GenerateCode;
Status GenerateCode(const Parser &, const std::string &, Status GenerateCode(const Parser &, const std::string &,
const std::string &) FLATBUFFERS_OVERRIDE { const std::string &) override {
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }
@@ -652,12 +656,14 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
// TODO(derekbailey): figure out a save file without depending on util.h // TODO(derekbailey): figure out a save file without depending on util.h
EnsureDirExists(path); EnsureDirExists(path);
const std::string file_name = path + "/" + namer_.File(name); const std::string file_name = options_.output_path + path + "/" + namer_.File(name);
SaveFile(file_name.c_str(), code, false); SaveFile(file_name.c_str(), code, false);
} }
std::unordered_set<std::string> keywords_; std::unordered_set<std::string> keywords_;
std::map<std::string, std::string> requires_; std::map<std::string, std::string> requires_;
CodeGenOptions options_;
const r::Object *current_obj_; const r::Object *current_obj_;
const r::Enum *current_enum_; const r::Enum *current_enum_;
const std::string flatc_version_; const std::string flatc_version_;

View File

@@ -28,6 +28,7 @@
#include "bfbs_namer.h" #include "bfbs_namer.h"
// The intermediate representation schema. // The intermediate representation schema.
#include "flatbuffers/code_generator.h"
#include "flatbuffers/reflection.h" #include "flatbuffers/reflection.h"
#include "flatbuffers/reflection_generated.h" #include "flatbuffers/reflection_generated.h"
@@ -95,7 +96,10 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version), flatc_version_(flatc_version),
namer_(NimDefaultConfig(), NimKeywords()) {} namer_(NimDefaultConfig(), NimKeywords()) {}
Status GenerateFromSchema(const r::Schema *schema) FLATBUFFERS_OVERRIDE { 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); StartCodeBlock(enum_def);
GenerateEnum(enum_def); GenerateEnum(enum_def);
@@ -671,12 +675,15 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
// TODO(derekbailey): figure out a save file without depending on util.h // TODO(derekbailey): figure out a save file without depending on util.h
EnsureDirExists(path); EnsureDirExists(path);
const std::string file_name = path + "/" + namer_.File(name); const std::string file_name =
options_.output_path + path + "/" + namer_.File(name);
SaveFile(file_name.c_str(), code, false); SaveFile(file_name.c_str(), code, false);
} }
std::unordered_set<std::string> keywords_; std::unordered_set<std::string> keywords_;
std::map<std::string, std::string> imports_; std::map<std::string, std::string> imports_;
CodeGenOptions options_;
const r::Object *current_obj_; const r::Object *current_obj_;
const r::Enum *current_enum_; const r::Enum *current_enum_;
const std::string flatc_version_; const std::string flatc_version_;

View File

@@ -866,8 +866,11 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
// Prefer bfbs generators if present. // Prefer bfbs generators if present.
if (code_generator->SupportsBfbsGeneration()) { if (code_generator->SupportsBfbsGeneration()) {
const CodeGenerator::Status status = CodeGenOptions code_gen_options;
code_generator->GenerateCode(bfbs_buffer, bfbs_length); code_gen_options.output_path = options.output_path;
const CodeGenerator::Status status = code_generator->GenerateCode(
bfbs_buffer, bfbs_length, code_gen_options);
if (status != CodeGenerator::Status::OK) { if (status != CodeGenerator::Status::OK) {
Error("Unable to generate " + code_generator->LanguageName() + Error("Unable to generate " + code_generator->LanguageName() +
" for " + filebase + code_generator->status_detail + " for " + filebase + code_generator->status_detail +

View File

@@ -34,13 +34,13 @@ namespace flatbuffers {
namespace { namespace {
static std::string BinaryFileName(const Parser &parser, const std::string &path, static std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin"; auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext; return path + file_name + "." + ext;
} }
static bool GenerateBinary(const Parser &parser, const std::string &path, static bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
if (parser.opts.use_flexbuffers) { if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer(); 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));
@@ -57,7 +57,7 @@ static bool GenerateBinary(const Parser &parser, const std::string &path,
} }
static std::string BinaryMakeRule(const Parser &parser, const std::string &path, static std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
if (!parser.builder_.GetSize()) return ""; if (!parser.builder_.GetSize()) return "";
std::string filebase = std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name)); flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
@@ -81,9 +81,8 @@ class BinaryCodeGenerator : public CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -4067,7 +4067,7 @@ class CppGenerator : public BaseGenerator {
} // namespace cpp } // namespace cpp
static bool GenerateCPP(const Parser &parser, const std::string &path, static bool GenerateCPP(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
cpp::IDLOptionsCpp opts(parser.opts); cpp::IDLOptionsCpp opts(parser.opts);
// The '--cpp_std' argument could be extended (like ASAN): // The '--cpp_std' argument could be extended (like ASAN):
// Example: "flatc --cpp_std c++17:option1:option2". // Example: "flatc --cpp_std c++17:option1:option2".
@@ -4106,7 +4106,7 @@ static bool GenerateCPP(const Parser &parser, const std::string &path,
} }
static std::string CPPMakeRule(const Parser &parser, const std::string &path, static std::string CPPMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
const auto filebase = StripPath(StripExtension(file_name)); const auto filebase = StripPath(StripExtension(file_name));
cpp::CppGenerator geneartor(parser, path, file_name, parser.opts); cpp::CppGenerator geneartor(parser, path, file_name, parser.opts);
const auto included_files = parser.GetIncludedFilesRecursive(file_name); const auto included_files = parser.GetIncludedFilesRecursive(file_name);
@@ -4130,9 +4130,8 @@ class CppCodeGenerator : public CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -625,7 +625,8 @@ class CSharpGenerator : public BaseGenerator {
} }
// Get the value of a table verification function start // Get the value of a table verification function start
void GetStartOfTableVerifier(const StructDef &struct_def, std::string *code_ptr) { void GetStartOfTableVerifier(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr; std::string &code = *code_ptr;
code += "\n"; code += "\n";
code += "static public class " + struct_def.name + "Verify\n"; code += "static public class " + struct_def.name + "Verify\n";
@@ -645,17 +646,18 @@ class CSharpGenerator : public BaseGenerator {
} }
std::string GetNestedFlatBufferName(const FieldDef &field) { std::string GetNestedFlatBufferName(const FieldDef &field) {
std::string name; std::string name;
if (field.nested_flatbuffer) { if (field.nested_flatbuffer) {
name = NamespacedName(*field.nested_flatbuffer); name = NamespacedName(*field.nested_flatbuffer);
} else { } else {
name = ""; name = "";
} }
return name ; return name;
} }
// Generate the code to call the appropriate Verify function(s) for a field. // Generate the code to call the appropriate Verify function(s) for a field.
void GenVerifyCall(CodeWriter &code_, const FieldDef &field, const char *prefix) { void GenVerifyCall(CodeWriter &code_, const FieldDef &field,
const char *prefix) {
code_.SetValue("PRE", prefix); code_.SetValue("PRE", prefix);
code_.SetValue("NAME", ConvertCase(field.name, Case::kUpperCamel)); code_.SetValue("NAME", ConvertCase(field.name, Case::kUpperCamel));
code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : ""); code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : "");
@@ -663,14 +665,16 @@ class CSharpGenerator : public BaseGenerator {
code_.SetValue("TYPE", GenTypeGet(field.value.type)); code_.SetValue("TYPE", GenTypeGet(field.value.type));
code_.SetValue("INLINESIZE", NumToString(InlineSize(field.value.type))); code_.SetValue("INLINESIZE", NumToString(InlineSize(field.value.type)));
code_.SetValue("OFFSET", NumToString(field.value.offset)); code_.SetValue("OFFSET", NumToString(field.value.offset));
if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type)) { if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type)) {
code_.SetValue("ALIGN", NumToString(InlineAlignment(field.value.type))); code_.SetValue("ALIGN", NumToString(InlineAlignment(field.value.type)));
code_ += code_ +=
"{{PRE}} && verifier.VerifyField(tablePos, " "{{PRE}} && verifier.VerifyField(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{INLINESIZE}} /*{{TYPE}}*/, {{ALIGN}}, {{REQUIRED_FLAG}})"; "{{OFFSET}} /*{{NAME}}*/, {{INLINESIZE}} /*{{TYPE}}*/, {{ALIGN}}, "
"{{REQUIRED_FLAG}})";
} else { } else {
// TODO - probably code below should go to this 'else' - code_ += "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\"; // TODO - probably code below should go to this 'else' - code_ +=
// "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\";
} }
switch (field.value.type.base_type) { switch (field.value.type.base_type) {
@@ -679,37 +683,47 @@ class CSharpGenerator : public BaseGenerator {
code_.SetValue("ENUM_NAME1", field.value.type.enum_def->name); code_.SetValue("ENUM_NAME1", field.value.type.enum_def->name);
code_.SetValue("ENUM_NAME", union_name); code_.SetValue("ENUM_NAME", union_name);
code_.SetValue("SUFFIX", UnionTypeFieldSuffix()); code_.SetValue("SUFFIX", UnionTypeFieldSuffix());
// Caution: This construction assumes, that UNION type id element has been created just before union data and // Caution: This construction assumes, that UNION type id element has
// its offset precedes union. Such assumption is common in flatbuffer implementation // been created just before union data and its offset precedes union.
code_.SetValue("TYPE_ID_OFFSET", NumToString(field.value.offset - sizeof(voffset_t))); // Such assumption is common in flatbuffer implementation
code_ += "{{PRE}} && verifier.VerifyUnion(tablePos, {{TYPE_ID_OFFSET}}, " code_.SetValue("TYPE_ID_OFFSET",
"{{OFFSET}} /*{{NAME}}*/, {{ENUM_NAME}}Verify.Verify, {{REQUIRED_FLAG}})"; NumToString(field.value.offset - sizeof(voffset_t)));
code_ +=
"{{PRE}} && verifier.VerifyUnion(tablePos, "
"{{TYPE_ID_OFFSET}}, "
"{{OFFSET}} /*{{NAME}}*/, {{ENUM_NAME}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
break; break;
} }
case BASE_TYPE_STRUCT: { case BASE_TYPE_STRUCT: {
if (!field.value.type.struct_def->fixed) { if (!field.value.type.struct_def->fixed) {
code_ += "{{PRE}} && verifier.VerifyTable(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyTable(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
} }
break; break;
} }
case BASE_TYPE_STRING: { case BASE_TYPE_STRING: {
code_ += "{{PRE}} && verifier.VerifyString(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyString(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})";
break; break;
} }
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
switch (field.value.type.element) { switch (field.value.type.element) {
case BASE_TYPE_STRING: { case BASE_TYPE_STRING: {
code_ += "{{PRE}} && verifier.VerifyVectorOfStrings(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyVectorOfStrings(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})";
break; break;
} }
case BASE_TYPE_STRUCT: { case BASE_TYPE_STRUCT: {
if (!field.value.type.struct_def->fixed) { if (!field.value.type.struct_def->fixed) {
code_ += "{{PRE}} && verifier.VerifyVectorOfTables(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyVectorOfTables(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
} else { } else {
code_.SetValue( code_.SetValue(
"VECTOR_ELEM_INLINESIZE", "VECTOR_ELEM_INLINESIZE",
@@ -733,16 +747,22 @@ class CSharpGenerator : public BaseGenerator {
if (!nfn.empty()) { if (!nfn.empty()) {
code_.SetValue("CPP_NAME", nfn); code_.SetValue("CPP_NAME", nfn);
// FIXME: file_identifier. // FIXME: file_identifier.
code_ += "{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{CPP_NAME}}Verify.Verify, {{REQUIRED_FLAG}})";
} else if (field.flexbuffer) {
code_ += "{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, null, {{REQUIRED_FLAG}})";
} else {
code_.SetValue("VECTOR_ELEM_INLINESIZE", NumToString(InlineSize(field.value.type.VectorType())));
code_ += code_ +=
"{{PRE}} && verifier.VerifyVectorOfData(tablePos, " "{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{VECTOR_ELEM_INLINESIZE}} /*{{TYPE}}*/, {{REQUIRED_FLAG}})"; "{{OFFSET}} /*{{NAME}}*/, {{CPP_NAME}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
} else if (field.flexbuffer) {
code_ +=
"{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, null, {{REQUIRED_FLAG}})";
} else {
code_.SetValue(
"VECTOR_ELEM_INLINESIZE",
NumToString(InlineSize(field.value.type.VectorType())));
code_ +=
"{{PRE}} && verifier.VerifyVectorOfData(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{VECTOR_ELEM_INLINESIZE}} "
"/*{{TYPE}}*/, {{REQUIRED_FLAG}})";
} }
break; break;
} }
@@ -758,7 +778,7 @@ class CSharpGenerator : public BaseGenerator {
// Generate table constructors, conditioned on its members' types. // Generate table constructors, conditioned on its members' types.
void GenTableVerifier(const StructDef &struct_def, std::string *code_ptr) { void GenTableVerifier(const StructDef &struct_def, std::string *code_ptr) {
CodeWriter code_; CodeWriter code_;
GetStartOfTableVerifier(struct_def, code_ptr); GetStartOfTableVerifier(struct_def, code_ptr);
// Generate struct fields accessors // Generate struct fields accessors
@@ -771,7 +791,7 @@ class CSharpGenerator : public BaseGenerator {
} }
*code_ptr += code_.ToString(); *code_ptr += code_.ToString();
GetEndOfTableVerifier(code_ptr); GetEndOfTableVerifier(code_ptr);
} }
@@ -787,7 +807,7 @@ class CSharpGenerator : public BaseGenerator {
// verification - instead structure size is verified using VerifyField // verification - instead structure size is verified using VerifyField
} else { } else {
// Create table verification function // Create table verification function
GenTableVerifier(struct_def, code_ptr); GenTableVerifier(struct_def, code_ptr);
} }
} }
@@ -1602,8 +1622,7 @@ class CSharpGenerator : public BaseGenerator {
if (union_type.enum_def) { if (union_type.enum_def) {
const auto &enum_def = *union_type.enum_def; const auto &enum_def = *union_type.enum_def;
auto ret = auto ret = "\n\nstatic public class " + enum_def.name + "Verify\n";
"\n\nstatic public class " + enum_def.name + "Verify\n";
ret += "{\n"; ret += "{\n";
ret += ret +=
" static public bool Verify(Google.FlatBuffers.Verifier verifier, " " static public bool Verify(Google.FlatBuffers.Verifier verifier, "
@@ -1615,25 +1634,26 @@ class CSharpGenerator : public BaseGenerator {
ret += " switch((" + enum_def.name + ")typeId)\n"; ret += " switch((" + enum_def.name + ")typeId)\n";
ret += " {\n"; ret += " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it; const auto &ev = **it;
if (ev.IsZero()) { continue; } if (ev.IsZero()) { continue; }
ret += " case " + Name(enum_def) + "." + Name(ev) + ":\n"; ret += " case " + Name(enum_def) + "." + Name(ev) + ":\n";
if (IsString(ev.union_type)) { if (IsString(ev.union_type)) {
ret += ret += " result = verifier.VerifyUnionString(tablePos);\n";
" result = verifier.VerifyUnionString(tablePos);\n";
ret += " break;"; ret += " break;";
} else if (ev.union_type.base_type == BASE_TYPE_STRUCT) { } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
if (! ev.union_type.struct_def->fixed) { if (!ev.union_type.struct_def->fixed) {
auto type = GenTypeGet(ev.union_type); auto type = GenTypeGet(ev.union_type);
ret += " result = " + type + "Verify.Verify(verifier, tablePos);\n"; ret += " result = " + type +
"Verify.Verify(verifier, tablePos);\n";
} else { } else {
ret += " result = verifier.VerifyUnionData(tablePos, " + ret += " result = verifier.VerifyUnionData(tablePos, " +
NumToString(InlineSize(ev.union_type)) + ", " + NumToString(InlineSize(ev.union_type)) + ", " +
NumToString(InlineAlignment(ev.union_type)) + NumToString(InlineAlignment(ev.union_type)) + ");\n";
");\n";; ;
} }
ret += " break;"; ret += " break;";
} else { } else {
@@ -1676,7 +1696,7 @@ class CSharpGenerator : public BaseGenerator {
// Type // Type
code += " public " + enum_def.name + " Type { get; set; }\n"; code += " public " + enum_def.name + " Type { get; set; }\n";
// Value // Value
code += " public object " + class_member + " { get; set; }\n"; code += " public object " + class_member + " { get; set; }\n";
code += "\n"; code += "\n";
// Constructor // Constructor
code += " public " + union_name + "() {\n"; code += " public " + union_name + "() {\n";
@@ -1736,7 +1756,7 @@ class CSharpGenerator : public BaseGenerator {
code += "}\n\n"; code += "}\n\n";
code += GenUnionVerify(enum_def.underlying_type); code += GenUnionVerify(enum_def.underlying_type);
// JsonConverter // JsonConverter
if (opts.cs_gen_json_serializer) { if (opts.cs_gen_json_serializer) {
if (enum_def.attributes.Lookup("private")) { if (enum_def.attributes.Lookup("private")) {
@@ -1773,7 +1793,7 @@ class CSharpGenerator : public BaseGenerator {
" _o, " " _o, "
"Newtonsoft.Json.JsonSerializer serializer) {\n"; "Newtonsoft.Json.JsonSerializer serializer) {\n";
code += " if (_o == null) return;\n"; code += " if (_o == null) return;\n";
code += " serializer.Serialize(writer, _o." + class_member + ");\n"; code += " serializer.Serialize(writer, _o." + class_member + ");\n";
code += " }\n"; code += " }\n";
code += code +=
" public override object ReadJson(Newtonsoft.Json.JsonReader " " public override object ReadJson(Newtonsoft.Json.JsonReader "
@@ -2499,7 +2519,7 @@ class CSharpGenerator : public BaseGenerator {
} // namespace csharp } // namespace csharp
static bool GenerateCSharp(const Parser &parser, const std::string &path, static bool GenerateCSharp(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
csharp::CSharpGenerator generator(parser, path, file_name); csharp::CSharpGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
@@ -2514,9 +2534,8 @@ class CSharpCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -90,8 +90,8 @@ class DartGenerator : public BaseGenerator {
template<typename T> template<typename T>
void import_generator(const std::vector<T *> &definitions, void import_generator(const std::vector<T *> &definitions,
const std::string &included, const std::string &included,
std::set<std::string> &imports) { std::set<std::string> &imports) {
for (const auto &item : definitions) { for (const auto &item : definitions) {
if (item->file == included) { if (item->file == included) {
std::string component = namer_.Namespace(*item->defined_namespace); std::string component = namer_.Namespace(*item->defined_namespace);
@@ -760,9 +760,7 @@ class DartGenerator : public BaseGenerator {
std::string getDefaultValue(const Value &value) const { std::string getDefaultValue(const Value &value) const {
if (!value.constant.empty() && value.constant != "0") { if (!value.constant.empty() && value.constant != "0") {
if (IsBool(value.type.base_type)) { if (IsBool(value.type.base_type)) { return "true"; }
return "true";
}
if (IsScalar(value.type.base_type)) { if (IsScalar(value.type.base_type)) {
if (StringIsFlatbufferNan(value.constant)) { if (StringIsFlatbufferNan(value.constant)) {
return "double.nan"; return "double.nan";
@@ -1125,13 +1123,13 @@ class DartGenerator : public BaseGenerator {
} // namespace dart } // namespace dart
static bool GenerateDart(const Parser &parser, const std::string &path, static bool GenerateDart(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
dart::DartGenerator generator(parser, path, file_name); dart::DartGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
static std::string DartMakeRule(const Parser &parser, const std::string &path, static std::string DartMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
auto filebase = auto filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name)); flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
dart::DartGenerator generator(parser, path, file_name); dart::DartGenerator generator(parser, path, file_name);
@@ -1154,9 +1152,8 @@ class DartCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -253,8 +253,9 @@ static void GenNameSpace(const Namespace &name_space, std::string *_schema,
} }
// Generate a flatbuffer schema from the Parser's internal representation. // 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,
bool no_log = false) { const std::string &file_name,
bool no_log = false) {
// Proto namespaces may clash with table names, escape the ones that were // Proto namespaces may clash with table names, escape the ones that were
// generated from a table: // generated from a table:
for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end(); for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end();
@@ -376,7 +377,7 @@ static std::string GenerateFBS(const Parser &parser, const std::string &file_nam
} }
static bool GenerateFBS(const Parser &parser, const std::string &path, static bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name, bool no_log = false) { const std::string &file_name, bool no_log = false) {
const std::string fbs = GenerateFBS(parser, file_name, no_log); const std::string fbs = GenerateFBS(parser, file_name, no_log);
if (fbs.empty()) { return false; } if (fbs.empty()) { return false; }
// TODO: Use LogCompilerWarn // TODO: Use LogCompilerWarn
@@ -388,7 +389,6 @@ static bool GenerateFBS(const Parser &parser, const std::string &path,
return SaveFile((path + file_name + ".fbs").c_str(), fbs, false); return SaveFile((path + file_name + ".fbs").c_str(), fbs, false);
} }
class FBSCodeGenerator : public CodeGenerator { class FBSCodeGenerator : public CodeGenerator {
public: public:
explicit FBSCodeGenerator(const bool no_log) : no_log_(no_log) {} explicit FBSCodeGenerator(const bool no_log) : no_log_(no_log) {}
@@ -400,16 +400,15 @@ class FBSCodeGenerator : public CodeGenerator {
} }
Status GenerateCodeString(const Parser &parser, const std::string &filename, Status GenerateCodeString(const Parser &parser, const std::string &filename,
std::string &output) override { std::string &output) override {
output = GenerateFBS(parser, filename, no_log_); output = GenerateFBS(parser, filename, no_log_);
return Status::OK; return Status::OK;
} }
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -1607,7 +1607,7 @@ class GoGenerator : public BaseGenerator {
} // namespace go } // namespace go
static bool GenerateGo(const Parser &parser, const std::string &path, static bool GenerateGo(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace); go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
return generator.generate(); return generator.generate();
} }
@@ -1622,9 +1622,8 @@ class GoCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -69,9 +69,10 @@ static std::set<std::string> JavaKeywords() {
}; };
} }
static const TypedFloatConstantGenerator JavaFloatGen("Double.", "Float.", "NaN", static const TypedFloatConstantGenerator JavaFloatGen("Double.", "Float.",
"POSITIVE_INFINITY", "NaN",
"NEGATIVE_INFINITY"); "POSITIVE_INFINITY",
"NEGATIVE_INFINITY");
static const CommentConfig comment_config = { static const CommentConfig comment_config = {
"/**", "/**",
@@ -79,7 +80,7 @@ static const CommentConfig comment_config = {
" */", " */",
}; };
} // namespace } // namespace
class JavaGenerator : public BaseGenerator { class JavaGenerator : public BaseGenerator {
struct FieldArrayLength { struct FieldArrayLength {
@@ -89,16 +90,15 @@ class JavaGenerator : public BaseGenerator {
public: public:
JavaGenerator(const Parser &parser, const std::string &path, JavaGenerator(const Parser &parser, const std::string &path,
const std::string &file_name, const std::string &file_name, const std::string &package_prefix)
const std::string &package_prefix)
: BaseGenerator(parser, path, file_name, "", ".", "java"), : BaseGenerator(parser, path, file_name, "", ".", "java"),
cur_name_space_(nullptr), cur_name_space_(nullptr),
namer_(WithFlagOptions(JavaDefaultConfig(), parser.opts, path), namer_(WithFlagOptions(JavaDefaultConfig(), parser.opts, path),
JavaKeywords()) { JavaKeywords()) {
if (!package_prefix.empty()) { if (!package_prefix.empty()) {
std::istringstream iss(package_prefix); std::istringstream iss(package_prefix);
std::string component; std::string component;
while(std::getline(iss, component, '.')) { while (std::getline(iss, component, '.')) {
package_prefix_ns_.components.push_back(component); package_prefix_ns_.components.push_back(component);
} }
package_prefix_ = package_prefix_ns_.GetFullyQualifiedName("") + "."; package_prefix_ = package_prefix_ns_.GetFullyQualifiedName("") + ".";
@@ -184,10 +184,8 @@ class JavaGenerator : public BaseGenerator {
code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n"; code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
Namespace combined_ns = package_prefix_ns_; Namespace combined_ns = package_prefix_ns_;
std::copy( std::copy(ns.components.begin(), ns.components.end(),
ns.components.begin(), std::back_inserter(combined_ns.components));
ns.components.end(),
std::back_inserter(combined_ns.components));
const std::string namespace_name = FullNamespace(".", combined_ns); const std::string namespace_name = FullNamespace(".", combined_ns);
if (!namespace_name.empty()) { if (!namespace_name.empty()) {
@@ -368,9 +366,9 @@ class JavaGenerator : public BaseGenerator {
FLATBUFFERS_ASSERT(value.type.enum_def); 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); auto enum_val = enum_def.FindByValue(value.constant);
return return enum_val
enum_val ? Prefixed(namer_.NamespacedEnumVariant(enum_def, *enum_val)) ? Prefixed(namer_.NamespacedEnumVariant(enum_def, *enum_val))
: value.constant; : value.constant;
} }
std::string GenDefaultValue(const FieldDef &field) const { std::string GenDefaultValue(const FieldDef &field) const {
@@ -1653,9 +1651,9 @@ class JavaGenerator : public BaseGenerator {
break; break;
case BASE_TYPE_UNION: case BASE_TYPE_UNION:
array_type = "int"; array_type = "int";
element_type = element_type = Prefixed(namer_.NamespacedType(
Prefixed(namer_.NamespacedType(*field.value.type.enum_def)) *field.value.type.enum_def)) +
+ "Union"; "Union";
to_array = element_type + ".pack(builder, _o." + to_array = element_type + ".pack(builder, _o." +
namer_.Method("get", property_name) + "()[_j])"; namer_.Method("get", property_name) + "()[_j])";
break; break;
@@ -2007,8 +2005,7 @@ class JavaGenerator : public BaseGenerator {
case BASE_TYPE_UNION: { case BASE_TYPE_UNION: {
if (wrap_in_namespace) { if (wrap_in_namespace) {
type_name = type_name = Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
} else { } else {
type_name = namer_.Type(*type.enum_def) + "Union"; type_name = namer_.Type(*type.enum_def) + "Union";
} }
@@ -2042,15 +2039,13 @@ class JavaGenerator : public BaseGenerator {
type_name.replace(type_name.length() - type_name_length, type_name.replace(type_name.length() - type_name_length,
type_name_length, new_type_name); type_name_length, new_type_name);
} else if (type.element == BASE_TYPE_UNION) { } else if (type.element == BASE_TYPE_UNION) {
type_name = type_name = Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
} }
break; break;
} }
case BASE_TYPE_UNION: { case BASE_TYPE_UNION: {
type_name = type_name = Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
break; break;
} }
default: break; default: break;
@@ -2192,12 +2187,11 @@ class JavaGenerator : public BaseGenerator {
std::string package_prefix_; std::string package_prefix_;
Namespace package_prefix_ns_; Namespace package_prefix_ns_;
}; };
} // namespace java } // namespace java
static bool GenerateJava(const Parser &parser, const std::string &path, static bool GenerateJava(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
java::JavaGenerator generator(parser, path, file_name, java::JavaGenerator generator(parser, path, file_name,
parser.opts.java_package_prefix); parser.opts.java_package_prefix);
return generator.generate(); return generator.generate();
@@ -2213,9 +2207,8 @@ class JavaCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -30,8 +30,7 @@ namespace jsons {
namespace { namespace {
template<class T> template<class T> static std::string GenFullName(const T *enum_def) {
static std::string GenFullName(const T *enum_def) {
std::string full_name; std::string full_name;
const auto &name_spaces = enum_def->defined_namespace->components; const auto &name_spaces = enum_def->defined_namespace->components;
for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) { for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
@@ -41,8 +40,7 @@ static std::string GenFullName(const T *enum_def) {
return full_name; return full_name;
} }
template<class T> template<class T> static std::string GenTypeRef(const T *enum_def) {
static std::string GenTypeRef(const T *enum_def) {
return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\""; return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
} }
@@ -144,7 +142,7 @@ static std::string GenType(const Type &type) {
} }
} }
} // namespace } // namespace
class JsonSchemaGenerator : public BaseGenerator { class JsonSchemaGenerator : public BaseGenerator {
private: private:
@@ -320,7 +318,7 @@ class JsonSchemaGenerator : public BaseGenerator {
} // namespace jsons } // namespace jsons
static bool GenerateJsonSchema(const Parser &parser, const std::string &path, static bool GenerateJsonSchema(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
jsons::JsonSchemaGenerator generator(parser, path, file_name); jsons::JsonSchemaGenerator generator(parser, path, file_name);
if (!generator.generate()) { return false; } if (!generator.generate()) { return false; }
return generator.save(); return generator.save();
@@ -336,9 +334,8 @@ class JsonSchemaCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -70,7 +70,7 @@ static Namer::Config KotlinDefaultConfig() {
/*filename_suffix=*/"", /*filename_suffix=*/"",
/*filename_extension=*/".kt" }; /*filename_extension=*/".kt" };
} }
} // namespace } // namespace
class KotlinGenerator : public BaseGenerator { class KotlinGenerator : public BaseGenerator {
public: public:
@@ -1594,7 +1594,7 @@ class KotlinGenerator : public BaseGenerator {
} // namespace kotlin } // namespace kotlin
static bool GenerateKotlin(const Parser &parser, const std::string &path, static bool GenerateKotlin(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
kotlin::KotlinGenerator generator(parser, path, file_name); kotlin::KotlinGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
@@ -1609,9 +1609,8 @@ class KotlinCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -63,8 +63,10 @@ class LobsterGenerator : public BaseGenerator {
std::string GenTypeName(const Type &type) { std::string GenTypeName(const Type &type) {
auto bits = NumToString(SizeOf(type.base_type) * 8); auto bits = NumToString(SizeOf(type.base_type) * 8);
if (IsInteger(type.base_type)) { if (IsInteger(type.base_type)) {
if (IsUnsigned(type.base_type)) return "uint" + bits; if (IsUnsigned(type.base_type))
else return "int" + bits; return "uint" + bits;
else
return "int" + bits;
} }
if (IsFloat(type.base_type)) return "float" + bits; if (IsFloat(type.base_type)) return "float" + bits;
if (IsString(type)) return "string"; if (IsString(type)) return "string";
@@ -120,16 +122,17 @@ class LobsterGenerator : public BaseGenerator {
auto defval = field.IsOptional() ? "0" : field.value.constant; auto defval = field.IsOptional() ? "0" : field.value.constant;
acc = "buf_.flatbuffers_field_" + GenTypeName(field.value.type) + acc = "buf_.flatbuffers_field_" + GenTypeName(field.value.type) +
"(pos_, " + offsets + ", " + defval + ")"; "(pos_, " + offsets + ", " + defval + ")";
if (IsBool(field.value.type.base_type)) if (IsBool(field.value.type.base_type)) acc = "bool(" + acc + ")";
acc = "bool(" + acc + ")";
} }
if (field.value.type.enum_def) if (field.value.type.enum_def)
acc = NormalizedName(*field.value.type.enum_def) + "(" + acc + ")"; acc = NormalizedName(*field.value.type.enum_def) + "(" + acc + ")";
if (field.IsOptional()) { if (field.IsOptional()) {
acc += ", buf_.flatbuffers_field_present(pos_, " + offsets + ")"; acc += ", buf_.flatbuffers_field_present(pos_, " + offsets + ")";
code += def + "() -> " + LobsterType(field.value.type) + ", bool:\n return " + acc + "\n"; code += def + "() -> " + LobsterType(field.value.type) +
", bool:\n return " + acc + "\n";
} else { } else {
code += def + "() -> " + LobsterType(field.value.type) + ":\n return " + acc + "\n"; code += def + "() -> " + LobsterType(field.value.type) +
":\n return " + acc + "\n";
} }
return; return;
} }
@@ -150,7 +153,8 @@ class LobsterGenerator : public BaseGenerator {
} }
case BASE_TYPE_STRING: case BASE_TYPE_STRING:
code += def + code += def +
"() -> string:\n return buf_.flatbuffers_field_string(pos_, " + "() -> string:\n return "
"buf_.flatbuffers_field_string(pos_, " +
offsets + ")\n"; offsets + ")\n";
break; break;
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
@@ -161,7 +165,9 @@ class LobsterGenerator : public BaseGenerator {
if (!(vectortype.struct_def->fixed)) { if (!(vectortype.struct_def->fixed)) {
start = "buf_.flatbuffers_indirect(" + start + ")"; start = "buf_.flatbuffers_indirect(" + start + ")";
} }
code += def + "(i:int) -> " + NamespacedName(*field.value.type.struct_def) + ":\n return "; code += def + "(i:int) -> " +
NamespacedName(*field.value.type.struct_def) +
":\n return ";
code += NamespacedName(*field.value.type.struct_def) + " { buf_, " + code += NamespacedName(*field.value.type.struct_def) + " { buf_, " +
start + " }\n"; start + " }\n";
} else { } else {
@@ -169,7 +175,8 @@ class LobsterGenerator : public BaseGenerator {
code += def + "(i:int) -> string:\n return "; code += def + "(i:int) -> string:\n return ";
code += "buf_.flatbuffers_string"; code += "buf_.flatbuffers_string";
} else { } else {
code += def + "(i:int) -> " + LobsterType(vectortype) + ":\n return "; code += def + "(i:int) -> " + LobsterType(vectortype) +
":\n return ";
code += "buf_.read_" + GenTypeName(vectortype) + "_le"; code += "buf_.read_" + GenTypeName(vectortype) + "_le";
} }
code += "(buf_.flatbuffers_field_vector(pos_, " + offsets + code += "(buf_.flatbuffers_field_vector(pos_, " + offsets +
@@ -399,7 +406,7 @@ class LobsterGenerator : public BaseGenerator {
} // namespace lobster } // namespace lobster
static bool GenerateLobster(const Parser &parser, const std::string &path, static bool GenerateLobster(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
lobster::LobsterGenerator generator(parser, path, file_name); lobster::LobsterGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
@@ -414,9 +421,8 @@ class LobsterCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -940,7 +940,7 @@ class PhpGenerator : public BaseGenerator {
} // namespace php } // namespace php
static bool GeneratePhp(const Parser &parser, const std::string &path, static bool GeneratePhp(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
php::PhpGenerator generator(parser, path, file_name); php::PhpGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
@@ -955,9 +955,8 @@ class PhpCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -74,7 +74,7 @@ static Namer::Config PythonDefaultConfig() {
static const CommentConfig def_comment = { nullptr, "#", nullptr }; static const CommentConfig def_comment = { nullptr, "#", nullptr };
static const std::string Indent = " "; static const std::string Indent = " ";
} // namespace } // namespace
class PythonGenerator : public BaseGenerator { class PythonGenerator : public BaseGenerator {
public: public:
@@ -149,10 +149,11 @@ class PythonGenerator : public BaseGenerator {
if (!parser_.opts.python_no_type_prefix_suffix) { if (!parser_.opts.python_no_type_prefix_suffix) {
// Add an alias with the old name // Add an alias with the old name
code += Indent + "@classmethod\n"; code += Indent + "@classmethod\n";
code += Indent + "def GetRootAs" + struct_type + "(cls, buf, offset=0):\n";
code += code +=
Indent + Indent + Indent + "def GetRootAs" + struct_type + "(cls, buf, offset=0):\n";
"\"\"\"This method is deprecated. Please switch to GetRootAs.\"\"\"\n"; code += Indent + Indent +
"\"\"\"This method is deprecated. Please switch to "
"GetRootAs.\"\"\"\n";
code += Indent + Indent + "return cls.GetRootAs(buf, offset)\n"; code += Indent + Indent + "return cls.GetRootAs(buf, offset)\n";
} }
} }
@@ -179,16 +180,15 @@ class PythonGenerator : public BaseGenerator {
GenReceiver(struct_def, code_ptr); GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "Length(self)"; code += namer_.Method(field) + "Length(self)";
if (parser_.opts.python_typing) { if (parser_.opts.python_typing) { code += " -> int"; }
code += " -> int";
}
code += ":"; code += ":";
if(!IsArray(field.value.type)){ if (!IsArray(field.value.type)) {
code += OffsetPrefix(field,false); code += OffsetPrefix(field, false);
code += GenIndents(3) + "return self._tab.VectorLen(o)"; code += GenIndents(3) + "return self._tab.VectorLen(o)";
code += GenIndents(2) + "return 0\n\n"; code += GenIndents(2) + "return 0\n\n";
}else{ } else {
code += GenIndents(2) + "return "+NumToString(field.value.type.fixed_length)+"\n\n"; code += GenIndents(2) + "return " +
NumToString(field.value.type.fixed_length) + "\n\n";
} }
} }
@@ -199,17 +199,15 @@ class PythonGenerator : public BaseGenerator {
GenReceiver(struct_def, code_ptr); GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "IsNone(self)"; code += namer_.Method(field) + "IsNone(self)";
if (parser_.opts.python_typing) { if (parser_.opts.python_typing) { code += " -> bool"; }
code += " -> bool";
}
code += ":"; code += ":";
if(!IsArray(field.value.type)){ if (!IsArray(field.value.type)) {
code += GenIndents(2) + code += GenIndents(2) +
"o = flatbuffers.number_types.UOffsetTFlags.py_type" + "o = flatbuffers.number_types.UOffsetTFlags.py_type" +
"(self._tab.Offset(" + NumToString(field.value.offset) + "))"; "(self._tab.Offset(" + NumToString(field.value.offset) + "))";
code += GenIndents(2) + "return o == 0"; code += GenIndents(2) + "return o == 0";
} else { } else {
//assume that we always have an array as memory is preassigned // assume that we always have an array as memory is preassigned
code += GenIndents(2) + "return False"; code += GenIndents(2) + "return False";
} }
code += "\n\n"; code += "\n\n";
@@ -290,7 +288,8 @@ class PythonGenerator : public BaseGenerator {
code += "(self, i):"; code += "(self, i):";
} }
if (parser_.opts.include_dependence_headers && !parser_.opts.python_typing) { if (parser_.opts.include_dependence_headers &&
!parser_.opts.python_typing) {
code += GenIndents(2); code += GenIndents(2);
code += "from " + import_entry.first + " import " + import_entry.second + code += "from " + import_entry.first + " import " + import_entry.second +
"\n"; "\n";
@@ -317,8 +316,9 @@ class PythonGenerator : public BaseGenerator {
code += NumToString(field.value.offset) + " + i * "; code += NumToString(field.value.offset) + " + i * ";
code += NumToString(InlineSize(field.value.type.VectorType())); code += NumToString(InlineSize(field.value.type.VectorType()));
code += ")) for i in range("; code += ")) for i in range(";
code += "self."+namer_.Method(field)+"Length()" + ")]"; code += "self." + namer_.Method(field) + "Length()" + ")]";
code += GenIndents(2) +"elif j >= 0 and j < self."+namer_.Method(field)+"Length():"; code += GenIndents(2) + "elif j >= 0 and j < self." + namer_.Method(field) +
"Length():";
code += GenIndents(3) + "return " + GenGetter(field.value.type); code += GenIndents(3) + "return " + GenGetter(field.value.type);
code += "self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type("; code += "self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(";
code += NumToString(field.value.offset) + " + j * "; code += NumToString(field.value.offset) + " + j * ";
@@ -355,7 +355,8 @@ class PythonGenerator : public BaseGenerator {
code += "x = self._tab.Indirect(o + self._tab.Pos)\n"; code += "x = self._tab.Indirect(o + self._tab.Pos)\n";
} }
if (parser_.opts.include_dependence_headers && !parser_.opts.python_typing) { if (parser_.opts.include_dependence_headers &&
!parser_.opts.python_typing) {
code += Indent + Indent + Indent; code += Indent + Indent + Indent;
code += "from " + import_entry.first + " import " + import_entry.second + code += "from " + import_entry.first + " import " + import_entry.second +
"\n"; "\n";
@@ -464,7 +465,8 @@ class PythonGenerator : public BaseGenerator {
if (!(vectortype.struct_def->fixed)) { if (!(vectortype.struct_def->fixed)) {
code += Indent + Indent + Indent + "x = self._tab.Indirect(x)\n"; code += Indent + Indent + Indent + "x = self._tab.Indirect(x)\n";
} }
if (parser_.opts.include_dependence_headers && !parser_.opts.python_typing) { if (parser_.opts.include_dependence_headers &&
!parser_.opts.python_typing) {
code += Indent + Indent + Indent; code += Indent + Indent + Indent;
code += "from " + import_entry.first + " import " + import_entry.second + code += "from " + import_entry.first + " import " + import_entry.second +
"\n"; "\n";
@@ -519,7 +521,7 @@ class PythonGenerator : public BaseGenerator {
GenReceiver(struct_def, code_ptr); GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "AsNumpy(self):"; code += namer_.Method(field) + "AsNumpy(self):";
if(!IsArray(field.value.type)){ if (!IsArray(field.value.type)) {
code += OffsetPrefix(field, false); code += OffsetPrefix(field, false);
code += GenIndents(3); code += GenIndents(3);
@@ -533,11 +535,13 @@ class PythonGenerator : public BaseGenerator {
} else { } else {
code += GenIndents(2) + "return 0\n"; code += GenIndents(2) + "return 0\n";
} }
}else{ } else {
code += GenIndents(2) + "return "; code += GenIndents(2) + "return ";
code += "self._tab.GetArrayAsNumpy(flatbuffers.number_types."; code += "self._tab.GetArrayAsNumpy(flatbuffers.number_types.";
code += namer_.Method(GenTypeGet(field.value.type.VectorType())); code += namer_.Method(GenTypeGet(field.value.type.VectorType()));
code += "Flags, self._tab.Pos + "+NumToString(field.value.offset)+", "+NumToString("self."+namer_.Method(field)+"Length()")+")\n"; code += "Flags, self._tab.Pos + " + NumToString(field.value.offset) +
", " + NumToString("self." + namer_.Method(field) + "Length()") +
")\n";
} }
code += "\n"; code += "\n";
} }
@@ -564,9 +568,7 @@ class PythonGenerator : public BaseGenerator {
const std::string unqualified_name = nested->constant; const std::string unqualified_name = nested->constant;
std::string qualified_name = NestedFlatbufferType(unqualified_name); std::string qualified_name = NestedFlatbufferType(unqualified_name);
if (qualified_name.empty()) { if (qualified_name.empty()) { qualified_name = nested->constant; }
qualified_name = nested->constant;
}
const ImportMapEntry import_entry = { "." + qualified_name, const ImportMapEntry import_entry = { "." + qualified_name,
unqualified_name }; unqualified_name };
@@ -704,7 +706,9 @@ class PythonGenerator : public BaseGenerator {
const auto struct_type = namer_.Type(struct_def); const auto struct_type = namer_.Type(struct_def);
// Generate method with struct name. // Generate method with struct name.
const auto name = parser_.opts.python_no_type_prefix_suffix ? "Start" : struct_type + "Start"; const auto name = parser_.opts.python_no_type_prefix_suffix
? "Start"
: struct_type + "Start";
code += "def " + name; code += "def " + name;
if (parser_.opts.python_typing) { if (parser_.opts.python_typing) {
@@ -736,12 +740,14 @@ class PythonGenerator : public BaseGenerator {
const std::string field_method = namer_.Method(field); const std::string field_method = namer_.Method(field);
const std::string field_ty = GenFieldTy(field); const std::string field_ty = GenFieldTy(field);
const auto name = parser_.opts.python_no_type_prefix_suffix ? "Add" + field_method : namer_.Type(struct_def) + "Add" + field_method; const auto name = parser_.opts.python_no_type_prefix_suffix
? "Add" + field_method
: namer_.Type(struct_def) + "Add" + field_method;
// Generate method with struct name. // Generate method with struct name.
code += "def " + name; code += "def " + name;
if (parser_.opts.python_typing) { if (parser_.opts.python_typing) {
code += "(builder: flatbuffers.Builder, " + field_var + ": " + field_ty; code += "(builder: flatbuffers.Builder, " + field_var + ": " + field_ty;
} else { } else {
code += "(builder, " + field_var; code += "(builder, " + field_var;
} }
@@ -767,9 +773,9 @@ class PythonGenerator : public BaseGenerator {
if (!parser_.opts.one_file && !parser_.opts.python_no_type_prefix_suffix) { if (!parser_.opts.one_file && !parser_.opts.python_no_type_prefix_suffix) {
// Generate method without struct name. // Generate method without struct name.
code += "def Add" + field_method + "(builder: flatbuffers.Builder, " + field_var + ": " + field_ty + "):\n"; code += "def Add" + field_method + "(builder: flatbuffers.Builder, " +
code += field_var + ": " + field_ty + "):\n";
Indent + namer_.Type(struct_def) + "Add" + field_method; code += Indent + namer_.Type(struct_def) + "Add" + field_method;
code += "(builder, "; code += "(builder, ";
code += field_var; code += field_var;
code += ")\n\n"; code += ")\n\n";
@@ -784,7 +790,9 @@ class PythonGenerator : public BaseGenerator {
const std::string field_method = namer_.Method(field); const std::string field_method = namer_.Method(field);
// Generate method with struct name. // Generate method with struct name.
const auto name = parser_.opts.python_no_type_prefix_suffix ? "Start" + field_method : struct_type + "Start" + field_method; const auto name = parser_.opts.python_no_type_prefix_suffix
? "Start" + field_method
: struct_type + "Start" + field_method;
code += "def " + name; code += "def " + name;
if (parser_.opts.python_typing) { if (parser_.opts.python_typing) {
code += "Vector(builder, numElems: int) -> int:\n"; code += "Vector(builder, numElems: int) -> int:\n";
@@ -802,7 +810,8 @@ class PythonGenerator : public BaseGenerator {
if (!parser_.opts.one_file && !parser_.opts.python_no_type_prefix_suffix) { if (!parser_.opts.one_file && !parser_.opts.python_no_type_prefix_suffix) {
// Generate method without struct name. // Generate method without struct name.
code += "def Start" + field_method + "Vector(builder, numElems: int) -> int:\n"; code += "def Start" + field_method +
"Vector(builder, numElems: int) -> int:\n";
code += Indent + "return " + struct_type + "Start"; code += Indent + "return " + struct_type + "Start";
code += field_method + "Vector(builder, numElems)\n\n"; code += field_method + "Vector(builder, numElems)\n\n";
} }
@@ -849,7 +858,9 @@ class PythonGenerator : public BaseGenerator {
std::string *code_ptr) const { std::string *code_ptr) const {
auto &code = *code_ptr; auto &code = *code_ptr;
const auto name = parser_.opts.python_no_type_prefix_suffix ? "End" : namer_.Type(struct_def) + "End"; const auto name = parser_.opts.python_no_type_prefix_suffix
? "End"
: namer_.Type(struct_def) + "End";
// Generate method with struct name. // Generate method with struct name.
if (parser_.opts.python_typing) { if (parser_.opts.python_typing) {
code += "def " + name + "(builder: flatbuffers.Builder) -> int:\n"; code += "def " + name + "(builder: flatbuffers.Builder) -> int:\n";
@@ -921,7 +932,9 @@ class PythonGenerator : public BaseGenerator {
} }
break; break;
} }
case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr, imports); break; case BASE_TYPE_UNION:
GetUnionField(struct_def, field, code_ptr, imports);
break;
default: FLATBUFFERS_ASSERT(0); default: FLATBUFFERS_ASSERT(0);
} }
} }
@@ -1255,14 +1268,15 @@ class PythonGenerator : public BaseGenerator {
} }
void InitializeFromPackedBuf(const StructDef &struct_def, void InitializeFromPackedBuf(const StructDef &struct_def,
std::string *code_ptr) const { std::string *code_ptr) const {
auto &code = *code_ptr; auto &code = *code_ptr;
const auto struct_var = namer_.Variable(struct_def); const auto struct_var = namer_.Variable(struct_def);
const auto struct_type = namer_.Type(struct_def); const auto struct_type = namer_.Type(struct_def);
code += GenIndents(1) + "@classmethod"; code += GenIndents(1) + "@classmethod";
code += GenIndents(1) + "def InitFromPackedBuf(cls, buf, pos=0):"; code += GenIndents(1) + "def InitFromPackedBuf(cls, buf, pos=0):";
code += GenIndents(2) + "n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)"; code += GenIndents(2) +
"n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)";
code += GenIndents(2) + "return cls.InitFromBuf(buf, pos+n)"; code += GenIndents(2) + "return cls.InitFromBuf(buf, pos+n)";
code += "\n"; code += "\n";
} }
@@ -1281,20 +1295,21 @@ class PythonGenerator : public BaseGenerator {
code += "\n"; code += "\n";
} }
void GenCompareOperator(const StructDef &struct_def, void GenCompareOperator(const StructDef &struct_def,
std::string *code_ptr) const { std::string *code_ptr) const {
auto &code = *code_ptr; auto &code = *code_ptr;
code += GenIndents(1) + "def __eq__(self, other):"; code += GenIndents(1) + "def __eq__(self, other):";
code += GenIndents(2) + "return type(self) == type(other)"; code += GenIndents(2) + "return type(self) == type(other)";
for (auto it = struct_def.fields.vec.begin(); for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) { it != struct_def.fields.vec.end(); ++it) {
auto &field = **it; auto &field = **it;
if (field.deprecated) continue; if (field.deprecated) continue;
// Wrties the comparison statement for this field. // Wrties the comparison statement for this field.
const auto field_field = namer_.Field(field); const auto field_field = namer_.Field(field);
code += " and \\" + GenIndents(3) + "self." + field_field + " == " + "other." + field_field; code += " and \\" + GenIndents(3) + "self." + field_field +
} " == " + "other." + field_field;
}
code += "\n"; code += "\n";
} }
@@ -1317,8 +1332,9 @@ class PythonGenerator : public BaseGenerator {
code += field_type + "()"; code += field_type + "()";
} }
code += ") is not None:"; code += ") is not None:";
code += GenIndents(3) + "self." + field_field + " = " + namer_.ObjectType(field_type) + code += GenIndents(3) + "self." + field_field + " = " +
+ ".InitFromObj(" + struct_var + "." + field_method + "("; namer_.ObjectType(field_type) + +".InitFromObj(" + struct_var +
"." + field_method + "(";
// A struct's accessor requires a struct buf instance. // A struct's accessor requires a struct buf instance.
if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) { if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
code += field_type + "()"; code += field_type + "()";
@@ -1368,8 +1384,9 @@ class PythonGenerator : public BaseGenerator {
"(i) is None:"; "(i) is None:";
code += GenIndents(5) + "self." + field_field + ".append(None)"; code += GenIndents(5) + "self." + field_field + ".append(None)";
code += GenIndents(4) + "else:"; code += GenIndents(4) + "else:";
code += GenIndents(5) + one_instance + " = " + namer_.ObjectType(field_type) + code += GenIndents(5) + one_instance + " = " +
".InitFromObj(" + struct_var + "." + field_method + "(i))"; namer_.ObjectType(field_type) + ".InitFromObj(" + struct_var + "." +
field_method + "(i))";
code += code +=
GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")"; GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
} }
@@ -1399,8 +1416,9 @@ class PythonGenerator : public BaseGenerator {
"(i) is None:"; "(i) is None:";
code += GenIndents(5) + "self." + field_field + ".append(None)"; code += GenIndents(5) + "self." + field_field + ".append(None)";
code += GenIndents(4) + "else:"; code += GenIndents(4) + "else:";
code += GenIndents(5) + one_instance + " = " + namer_.ObjectType(field_type) + code += GenIndents(5) + one_instance + " = " +
".InitFromObj(" + struct_var + "." + field_method + "(i))"; namer_.ObjectType(field_type) + ".InitFromObj(" + struct_var + "." +
field_method + "(i))";
code += code +=
GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")"; GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
} }
@@ -1780,9 +1798,7 @@ class PythonGenerator : public BaseGenerator {
InitializeFromObjForObject(struct_def, &code); InitializeFromObjForObject(struct_def, &code);
if (parser_.opts.gen_compare) { if (parser_.opts.gen_compare) { GenCompareOperator(struct_def, &code); }
GenCompareOperator(struct_def, &code);
}
GenUnPack(struct_def, &code); GenUnPack(struct_def, &code);
@@ -1891,17 +1907,11 @@ class PythonGenerator : public BaseGenerator {
std::string GenFieldTy(const FieldDef &field) const { std::string GenFieldTy(const FieldDef &field) const {
if (IsScalar(field.value.type.base_type) || IsArray(field.value.type)) { if (IsScalar(field.value.type.base_type) || IsArray(field.value.type)) {
const std::string ty = GenTypeBasic(field.value.type); const std::string ty = GenTypeBasic(field.value.type);
if (ty.find("int") != std::string::npos) { if (ty.find("int") != std::string::npos) { return "int"; }
return "int";
}
if (ty.find("float") != std::string::npos) { if (ty.find("float") != std::string::npos) { return "float"; }
return "float";
}
if (ty == "bool") { if (ty == "bool") { return "bool"; }
return "bool";
}
return "Any"; return "Any";
} else { } else {
@@ -2052,13 +2062,9 @@ class PythonGenerator : public BaseGenerator {
} }
if (parser_.opts.one_file) { if (parser_.opts.one_file) {
if (!declcode.empty()) { if (!declcode.empty()) { *one_file_code += declcode + "\n\n"; }
*one_file_code += declcode + "\n\n";
}
for (auto import_str: imports) { for (auto import_str : imports) { one_file_imports.insert(import_str); }
one_file_imports.insert(import_str);
}
} else { } else {
const std::string mod = const std::string mod =
namer_.File(struct_def, SkipFile::SuffixAndExtension); namer_.File(struct_def, SkipFile::SuffixAndExtension);
@@ -2136,7 +2142,7 @@ class PythonGenerator : public BaseGenerator {
} // namespace python } // namespace python
static bool GeneratePython(const Parser &parser, const std::string &path, static bool GeneratePython(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
python::PythonGenerator generator(parser, path, file_name); python::PythonGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
@@ -2151,9 +2157,8 @@ class PythonCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -277,10 +277,10 @@ static bool IsBitFlagsEnum(const EnumDef &enum_def) {
static bool IsOptionalToBuilder(const FieldDef &field) { static bool IsOptionalToBuilder(const FieldDef &field) {
return field.IsOptional() || !IsScalar(field.value.type.base_type); return field.IsOptional() || !IsScalar(field.value.type.base_type);
} }
} // namespace } // namespace
static bool GenerateRustModuleRootFile(const Parser &parser, static bool GenerateRustModuleRootFile(const Parser &parser,
const std::string &output_dir) { const std::string &output_dir) {
if (!parser.opts.rust_module_root_file) { if (!parser.opts.rust_module_root_file) {
// Don't generate a root file when generating one file. This isn't an error // Don't generate a root file when generating one file. This isn't an error
// so return true. // so return true.
@@ -708,7 +708,7 @@ class RustGenerator : public BaseGenerator {
// and an enum array of values // and an enum array of values
void GenEnum(const EnumDef &enum_def) { void GenEnum(const EnumDef &enum_def) {
const bool is_private = parser_.opts.no_leak_private_annotations && const bool is_private = parser_.opts.no_leak_private_annotations &&
(enum_def.attributes.Lookup("private") != nullptr); (enum_def.attributes.Lookup("private") != nullptr);
code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub"); code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub");
code_.SetValue("ENUM_TY", namer_.Type(enum_def)); code_.SetValue("ENUM_TY", namer_.Type(enum_def));
code_.SetValue("BASE_TYPE", GetEnumTypeForDecl(enum_def.underlying_type)); code_.SetValue("BASE_TYPE", GetEnumTypeForDecl(enum_def.underlying_type));
@@ -842,15 +842,21 @@ class RustGenerator : public BaseGenerator {
code_ += " type Inner = Self;"; code_ += " type Inner = Self;";
code_ += " #[inline]"; code_ += " #[inline]";
code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
code_ += " let b = flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc);"; code_ +=
" let b = flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc);";
if (IsBitFlagsEnum(enum_def)) { if (IsBitFlagsEnum(enum_def)) {
// Safety: // Safety:
// This is safe because we know bitflags is implemented with a repr transparent uint of the correct size. // This is safe because we know bitflags is implemented with a repr
// from_bits_unchecked will be replaced by an equivalent but safe from_bits_retain in bitflags 2.0 // transparent uint of the correct size. from_bits_unchecked will be
// replaced by an equivalent but safe from_bits_retain in bitflags 2.0
// https://github.com/bitflags/bitflags/issues/262 // https://github.com/bitflags/bitflags/issues/262
code_ += " // Safety:"; code_ += " // Safety:";
code_ += " // This is safe because we know bitflags is implemented with a repr transparent uint of the correct size."; code_ +=
code_ += " // from_bits_unchecked will be replaced by an equivalent but safe from_bits_retain in bitflags 2.0"; " // This is safe because we know bitflags is implemented with a "
"repr transparent uint of the correct size.";
code_ +=
" // from_bits_unchecked will be replaced by an equivalent but "
"safe from_bits_retain in bitflags 2.0";
code_ += " // https://github.com/bitflags/bitflags/issues/262"; code_ += " // https://github.com/bitflags/bitflags/issues/262";
code_ += " Self::from_bits_unchecked(b)"; code_ += " Self::from_bits_unchecked(b)";
} else { } else {
@@ -863,7 +869,9 @@ class RustGenerator : public BaseGenerator {
code_ += " type Output = {{ENUM_TY}};"; code_ += " type Output = {{ENUM_TY}};";
code_ += " #[inline]"; code_ += " #[inline]";
code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {"; code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {";
code_ += " flatbuffers::emplace_scalar::<{{BASE_TYPE}}>(dst, {{INTO_BASE}});"; code_ +=
" flatbuffers::emplace_scalar::<{{BASE_TYPE}}>(dst, "
"{{INTO_BASE}});";
code_ += " }"; code_ += " }";
code_ += "}"; code_ += "}";
code_ += ""; code_ += "";
@@ -879,12 +887,17 @@ class RustGenerator : public BaseGenerator {
code_ += " let b = {{BASE_TYPE}}::from_le(v);"; code_ += " let b = {{BASE_TYPE}}::from_le(v);";
if (IsBitFlagsEnum(enum_def)) { if (IsBitFlagsEnum(enum_def)) {
// Safety: // Safety:
// This is safe because we know bitflags is implemented with a repr transparent uint of the correct size. // This is safe because we know bitflags is implemented with a repr
// from_bits_unchecked will be replaced by an equivalent but safe from_bits_retain in bitflags 2.0 // transparent uint of the correct size. from_bits_unchecked will be
// replaced by an equivalent but safe from_bits_retain in bitflags 2.0
// https://github.com/bitflags/bitflags/issues/262 // https://github.com/bitflags/bitflags/issues/262
code_ += " // Safety:"; code_ += " // Safety:";
code_ += " // This is safe because we know bitflags is implemented with a repr transparent uint of the correct size."; code_ +=
code_ += " // from_bits_unchecked will be replaced by an equivalent but safe from_bits_retain in bitflags 2.0"; " // This is safe because we know bitflags is implemented with a "
"repr transparent uint of the correct size.";
code_ +=
" // from_bits_unchecked will be replaced by an equivalent but "
"safe from_bits_retain in bitflags 2.0";
code_ += " // https://github.com/bitflags/bitflags/issues/262"; code_ += " // https://github.com/bitflags/bitflags/issues/262";
code_ += " unsafe { Self::from_bits_unchecked(b) }"; code_ += " unsafe { Self::from_bits_unchecked(b) }";
} else { } else {
@@ -1458,7 +1471,8 @@ class RustGenerator : public BaseGenerator {
case ftVectorOfBool: case ftVectorOfBool:
case ftVectorOfFloat: { case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType()); const auto typname = GetTypeBasic(type.VectorType());
return WrapOption("flatbuffers::Vector<" + lifetime + ", " + typname + ">"); return WrapOption("flatbuffers::Vector<" + lifetime + ", " + typname +
">");
} }
case ftVectorOfEnumKey: { case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def); const auto typname = WrapInNameSpace(*type.enum_def);
@@ -1467,7 +1481,8 @@ class RustGenerator : public BaseGenerator {
} }
case ftVectorOfStruct: { case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def); const auto typname = WrapInNameSpace(*type.struct_def);
return WrapOption("flatbuffers::Vector<" + lifetime + ", " + typname + ">"); return WrapOption("flatbuffers::Vector<" + lifetime + ", " + typname +
">");
} }
case ftVectorOfTable: { case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def); const auto typname = WrapInNameSpace(*type.struct_def);
@@ -1585,8 +1600,9 @@ class RustGenerator : public BaseGenerator {
: "None"; : "None";
const std::string unwrap = field.IsOptional() ? "" : ".unwrap()"; const std::string unwrap = field.IsOptional() ? "" : ".unwrap()";
return "unsafe { self._tab.get::<" + typname + ">({{STRUCT_TY}}::" + vt_offset + return "unsafe { self._tab.get::<" + typname +
", " + default_value + ")" + unwrap + "}"; ">({{STRUCT_TY}}::" + vt_offset + ", " + default_value + ")" +
unwrap + "}";
} }
// Generates a fully-qualified name getter for use with --gen-name-strings // Generates a fully-qualified name getter for use with --gen-name-strings
@@ -1646,8 +1662,8 @@ class RustGenerator : public BaseGenerator {
// Generate an accessor struct, builder struct, and create function for a // Generate an accessor struct, builder struct, and create function for a
// table. // table.
void GenTable(const StructDef &struct_def) { void GenTable(const StructDef &struct_def) {
const bool is_private =
const bool is_private = parser_.opts.no_leak_private_annotations && parser_.opts.no_leak_private_annotations &&
(struct_def.attributes.Lookup("private") != nullptr); (struct_def.attributes.Lookup("private") != nullptr);
code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub"); code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub");
code_.SetValue("STRUCT_TY", namer_.Type(struct_def)); code_.SetValue("STRUCT_TY", namer_.Type(struct_def));
@@ -1933,13 +1949,17 @@ class RustGenerator : public BaseGenerator {
code_ += " // Safety:"; code_ += " // Safety:";
code_ += " // Created from a valid Table for this object"; code_ += " // Created from a valid Table for this object";
code_ += " // Which contains a valid union in this slot"; code_ += " // Which contains a valid union in this slot";
code_ += " Some(unsafe { {{U_ELEMENT_TABLE_TYPE}}::init_from_table(u) })"; code_ +=
" Some(unsafe { "
"{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u) })";
} else { } else {
code_ +=" self.{{FIELD}}().map(|t| {"; code_ += " self.{{FIELD}}().map(|t| {";
code_ += " // Safety:"; code_ += " // Safety:";
code_ += " // Created from a valid Table for this object"; code_ += " // Created from a valid Table for this object";
code_ += " // Which contains a valid union in this slot"; code_ += " // Which contains a valid union in this slot";
code_ += " unsafe { {{U_ELEMENT_TABLE_TYPE}}::init_from_table(t) }"; code_ +=
" unsafe { {{U_ELEMENT_TABLE_TYPE}}::init_from_table(t) "
"}";
code_ += " })"; code_ += " })";
} }
code_ += " } else {"; code_ += " } else {";
@@ -2264,7 +2284,8 @@ class RustGenerator : public BaseGenerator {
case ftUnionValue: { case ftUnionValue: {
code_.SetValue("ENUM_METHOD", code_.SetValue("ENUM_METHOD",
namer_.Method(*field.value.type.enum_def)); namer_.Method(*field.value.type.enum_def));
code_.SetValue("DISCRIMINANT", namer_.LegacyRustUnionTypeMethod(field)); code_.SetValue("DISCRIMINANT",
namer_.LegacyRustUnionTypeMethod(field));
code_ += code_ +=
" let {{DISCRIMINANT}} = " " let {{DISCRIMINANT}} = "
"self.{{FIELD}}.{{ENUM_METHOD}}_type();"; "self.{{FIELD}}.{{ENUM_METHOD}}_type();";
@@ -2312,10 +2333,10 @@ class RustGenerator : public BaseGenerator {
// TODO(cneo): create_vector* should be more generic to avoid // TODO(cneo): create_vector* should be more generic to avoid
// allocations. // allocations.
MapNativeTableField( MapNativeTableField(field,
field, "let w: Vec<_> = x.iter().map(|s| "
"let w: Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();" "_fbb.create_string(s)).collect();"
"_fbb.create_vector(&w)"); "_fbb.create_vector(&w)");
return; return;
} }
case ftVectorOfTable: { case ftVectorOfTable: {
@@ -2601,7 +2622,8 @@ class RustGenerator : public BaseGenerator {
} }
// Generate an accessor struct with constructor for a flatbuffers struct. // Generate an accessor struct with constructor for a flatbuffers struct.
void GenStruct(const StructDef &struct_def) { void GenStruct(const StructDef &struct_def) {
const bool is_private = parser_.opts.no_leak_private_annotations && const bool is_private =
parser_.opts.no_leak_private_annotations &&
(struct_def.attributes.Lookup("private") != nullptr); (struct_def.attributes.Lookup("private") != nullptr);
code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub"); code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub");
// Generates manual padding and alignment. // Generates manual padding and alignment.
@@ -2665,7 +2687,9 @@ class RustGenerator : public BaseGenerator {
code_ += " type Output = {{STRUCT_TY}};"; code_ += " type Output = {{STRUCT_TY}};";
code_ += " #[inline]"; code_ += " #[inline]";
code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {"; code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {";
code_ += " let src = ::core::slice::from_raw_parts(self as *const {{STRUCT_TY}} as *const u8, Self::size());"; code_ +=
" let src = ::core::slice::from_raw_parts(self as *const "
"{{STRUCT_TY}} as *const u8, Self::size());";
code_ += " dst.copy_from_slice(src);"; code_ += " dst.copy_from_slice(src);";
code_ += " }"; code_ += " }";
code_ += "}"; code_ += "}";
@@ -2759,7 +2783,9 @@ class RustGenerator : public BaseGenerator {
code_ += " // Safety:"; code_ += " // Safety:";
code_ += " // Created from a valid Table for this object"; code_ += " // Created from a valid Table for this object";
code_ += " // Which contains a valid array in this slot"; code_ += " // Which contains a valid array in this slot";
code_ += " unsafe { flatbuffers::Array::follow(&self.0, {{FIELD_OFFSET}}) }"; code_ +=
" unsafe { flatbuffers::Array::follow(&self.0, {{FIELD_OFFSET}}) "
"}";
} else { } else {
code_ += "pub fn {{FIELD}}(&self) -> {{FIELD_TYPE}} {"; code_ += "pub fn {{FIELD}}(&self) -> {{FIELD_TYPE}} {";
code_ += code_ +=
@@ -2772,7 +2798,9 @@ class RustGenerator : public BaseGenerator {
code_ += " core::ptr::copy_nonoverlapping("; code_ += " core::ptr::copy_nonoverlapping(";
code_ += " self.0[{{FIELD_OFFSET}}..].as_ptr(),"; code_ += " self.0[{{FIELD_OFFSET}}..].as_ptr(),";
code_ += " mem.as_mut_ptr() as *mut u8,"; code_ += " mem.as_mut_ptr() as *mut u8,";
code_ += " core::mem::size_of::<<{{FIELD_TYPE}} as EndianScalar>::Scalar>(),"; code_ +=
" core::mem::size_of::<<{{FIELD_TYPE}} as "
"EndianScalar>::Scalar>(),";
code_ += " );"; code_ += " );";
code_ += " mem.assume_init()"; code_ += " mem.assume_init()";
code_ += " })"; code_ += " })";
@@ -2827,7 +2855,9 @@ class RustGenerator : public BaseGenerator {
code_ += " core::ptr::copy_nonoverlapping("; code_ += " core::ptr::copy_nonoverlapping(";
code_ += " &x_le as *const _ as *const u8,"; code_ += " &x_le as *const _ as *const u8,";
code_ += " self.0[{{FIELD_OFFSET}}..].as_mut_ptr(),"; code_ += " self.0[{{FIELD_OFFSET}}..].as_mut_ptr(),";
code_ += " core::mem::size_of::<<{{FIELD_TYPE}} as EndianScalar>::Scalar>(),"; code_ +=
" core::mem::size_of::<<{{FIELD_TYPE}} as "
"EndianScalar>::Scalar>(),";
code_ += " );"; code_ += " );";
code_ += " }"; code_ += " }";
} }
@@ -2990,13 +3020,13 @@ class RustGenerator : public BaseGenerator {
} // namespace rust } // namespace rust
static bool GenerateRust(const Parser &parser, const std::string &path, static bool GenerateRust(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
rust::RustGenerator generator(parser, path, file_name); rust::RustGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
static std::string RustMakeRule(const Parser &parser, const std::string &path, static std::string RustMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
std::string filebase = std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name)); flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
rust::RustGenerator generator(parser, path, file_name); rust::RustGenerator generator(parser, path, file_name);
@@ -3020,9 +3050,8 @@ class RustCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -148,7 +148,7 @@ static std::string GenArrayMainBody(const std::string &optional) {
optional + " { "; optional + " { ";
} }
} // namespace } // namespace
class SwiftGenerator : public BaseGenerator { class SwiftGenerator : public BaseGenerator {
private: private:
@@ -261,8 +261,7 @@ class SwiftGenerator : public BaseGenerator {
code_ += "private var _{{FIELDVAR}}: " + valueType; code_ += "private var _{{FIELDVAR}}: " + valueType;
const auto accessing_value = IsEnum(field.value.type) ? ".value" : ""; const auto accessing_value = IsEnum(field.value.type) ? ".value" : "";
const auto base_value = const auto base_value =
IsStruct(field.value.type) ? (type + "()") IsStruct(field.value.type) ? (type + "()") : SwiftConstant(field);
: SwiftConstant(field);
main_constructor.push_back("_" + field_var + " = " + field_var + main_constructor.push_back("_" + field_var + " = " + field_var +
accessing_value); accessing_value);
@@ -720,8 +719,7 @@ class SwiftGenerator : public BaseGenerator {
if (IsBool(field.value.type.base_type)) { if (IsBool(field.value.type.base_type)) {
std::string default_value = std::string default_value =
field.IsOptional() ? "nil" field.IsOptional() ? "nil" : SwiftConstant(field);
: SwiftConstant(field);
code_.SetValue("CONSTANT", default_value); code_.SetValue("CONSTANT", default_value);
code_.SetValue("VALUETYPE", "Bool"); code_.SetValue("VALUETYPE", "Bool");
code_ += GenReaderMainBody(optional) + "\\"; code_ += GenReaderMainBody(optional) + "\\";
@@ -984,8 +982,9 @@ class SwiftGenerator : public BaseGenerator {
} else if (IsEnum(type) && !field.IsOptional()) { } else if (IsEnum(type) && !field.IsOptional()) {
code_.SetValue("CONSTANT", GenEnumDefaultValue(field)); code_.SetValue("CONSTANT", GenEnumDefaultValue(field));
code_ += "if {{FIELDVAR}} != {{CONSTANT}} {"; code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
} else if (IsFloat(type.base_type) && StringIsFlatbufferNan(field.value.constant)) { } else if (IsFloat(type.base_type) &&
code_ += "if !{{FIELDVAR}}.isNaN {"; StringIsFlatbufferNan(field.value.constant)) {
code_ += "if !{{FIELDVAR}}.isNaN {";
} else if (IsScalar(type.base_type) && !IsEnum(type) && } else if (IsScalar(type.base_type) && !IsEnum(type) &&
!IsBool(type.base_type) && !field.IsOptional()) { !IsBool(type.base_type) && !field.IsOptional()) {
code_ += "if {{FIELDVAR}} != {{CONSTANT}} {"; code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
@@ -1158,8 +1157,9 @@ class SwiftGenerator : public BaseGenerator {
void GenEnum(const EnumDef &enum_def) { void GenEnum(const EnumDef &enum_def) {
if (enum_def.generated) return; if (enum_def.generated) return;
const bool is_private_access = parser_.opts.swift_implementation_only || const bool is_private_access =
enum_def.attributes.Lookup("private") != nullptr; parser_.opts.swift_implementation_only ||
enum_def.attributes.Lookup("private") != nullptr;
code_.SetValue("ENUM_TYPE", code_.SetValue("ENUM_TYPE",
enum_def.is_union ? "UnionEnum" : "Enum, Verifiable"); enum_def.is_union ? "UnionEnum" : "Enum, Verifiable");
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public"); code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
@@ -1579,7 +1579,8 @@ class SwiftGenerator : public BaseGenerator {
if (IsBool(field.value.type.base_type)) { if (IsBool(field.value.type.base_type)) {
code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: Bool" + nullable; code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: Bool" + nullable;
if (!field.IsOptional()) if (!field.IsOptional())
base_constructor.push_back(field_var + " = " + SwiftConstant(field)); base_constructor.push_back(field_var + " = " +
SwiftConstant(field));
} }
} }
} }
@@ -1827,15 +1828,17 @@ class SwiftGenerator : public BaseGenerator {
} }
} }
std::string SwiftConstant(const FieldDef& field) { std::string SwiftConstant(const FieldDef &field) {
const auto default_value = const auto default_value =
StringIsFlatbufferNan(field.value.constant) ? ".nan" : StringIsFlatbufferNan(field.value.constant) ? ".nan"
StringIsFlatbufferPositiveInfinity(field.value.constant) ? ".infinity" : : StringIsFlatbufferPositiveInfinity(field.value.constant) ? ".infinity"
StringIsFlatbufferNegativeInfinity(field.value.constant) ? "-.infinity" : : StringIsFlatbufferNegativeInfinity(field.value.constant)
IsBool(field.value.type.base_type) ? ("0" == field.value.constant ? "false" : "true") : ? "-.infinity"
field.value.constant; : IsBool(field.value.type.base_type)
? ("0" == field.value.constant ? "false" : "true")
: field.value.constant;
return default_value; return default_value;
} }
std::string GenEnumConstructor(const std::string &at) { std::string GenEnumConstructor(const std::string &at) {
return "{{VALUETYPE}}(rawValue: " + GenReader("BASEVALUE", at) + ") "; return "{{VALUETYPE}}(rawValue: " + GenReader("BASEVALUE", at) + ") ";
@@ -1901,7 +1904,7 @@ class SwiftGenerator : public BaseGenerator {
} // namespace swift } // namespace swift
static bool GenerateSwift(const Parser &parser, const std::string &path, static bool GenerateSwift(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
swift::SwiftGenerator generator(parser, path, file_name); swift::SwiftGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
@@ -1916,9 +1919,8 @@ class SwiftCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -454,9 +454,8 @@ class TextCodeGenerator : public CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -477,10 +477,9 @@ class TsGenerator : public BaseGenerator {
EnumVal *val = value.type.enum_def->FindByValue(value.constant); EnumVal *val = value.type.enum_def->FindByValue(value.constant);
if (val == nullptr) if (val == nullptr)
val = const_cast<EnumVal *>(value.type.enum_def->MinValue()); val = const_cast<EnumVal *>(value.type.enum_def->MinValue());
return AddImport(imports, *value.type.enum_def, return AddImport(imports, *value.type.enum_def, *value.type.enum_def)
*value.type.enum_def) .name +
.name + "." + namer_.Variant(*val);
"." + namer_.Variant(*val);
} }
} }
} }
@@ -2162,13 +2161,13 @@ class TsGenerator : public BaseGenerator {
} // namespace ts } // namespace ts
static bool GenerateTS(const Parser &parser, const std::string &path, static bool GenerateTS(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
ts::TsGenerator generator(parser, path, file_name); ts::TsGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
static std::string TSMakeRule(const Parser &parser, const std::string &path, static std::string TSMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
std::string filebase = std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name)); flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
ts::TsGenerator generator(parser, path, file_name); ts::TsGenerator generator(parser, path, file_name);
@@ -2192,9 +2191,8 @@ class TsCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }