removed extern code generation declarations preferring direct includes (#7948)

* removed extern code generation definitions, preferring direct includes

* add static to functions

* remove idl_gen_lua
This commit is contained in:
Derek Bailey
2023-05-09 21:50:28 -07:00
committed by GitHub
parent 16a7df46f0
commit 10b79d87c1
27 changed files with 117 additions and 1081 deletions

1
.github/labeler.yml vendored
View File

@@ -52,7 +52,6 @@ kotlin:
lua:
- '**/*.lua'
- lua/**/*
- src/idl_gen_lua.cpp
- src/bfbs_gen_lua.cpp
lobster:

View File

@@ -166,7 +166,6 @@ set(FlatBuffers_Compiler_SRCS
src/idl_gen_php.cpp
src/idl_gen_python.cpp
src/idl_gen_lobster.cpp
src/idl_gen_lua.cpp
src/idl_gen_rust.cpp
src/idl_gen_fbs.cpp
src/idl_gen_grpc.cpp

View File

@@ -44,6 +44,16 @@ class CodeGenerator {
virtual Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) = 0;
// Generate code from the provided `parser` and place it in the output.
virtual Status GenerateCodeString(const Parser &parser,
const std::string &filename,
std::string &output) {
(void)parser;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
virtual Status GenerateCode(const uint8_t *buffer, int64_t length) = 0;

View File

@@ -229,6 +229,10 @@ class TypedFloatConstantGenerator : public FloatConstantGenerator {
const std::string neg_inf_number_;
};
std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
const std::string &path,
const std::string &file_name);
} // namespace flatbuffers
#endif // FLATBUFFERS_CODE_GENERATORS_H_

View File

@@ -1217,129 +1217,6 @@ extern const char *GenerateTextFromTable(const Parser &parser, const void *table
std::string *text);
extern const char *GenerateText(const Parser &parser, const void *flatbuffer,
std::string *text);
extern const char *GenerateTextFile(const Parser &parser,
const std::string &path,
const std::string &file_name);
// Generate Json schema to string
// See idl_gen_json_schema.cpp.
extern bool GenerateJsonSchema(const Parser &parser, std::string *json);
// Generate binary files from a given FlatBuffer, and a given Parser
// object that has been populated with the corresponding schema.
// See code_generators.cpp.
extern bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a C++ header from the definitions in the Parser object.
// See idl_gen_cpp.
extern bool GenerateCPP(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate C# files from the definitions in the Parser object.
// See idl_gen_csharp.cpp.
extern bool GenerateCSharp(const Parser &parser, const std::string &path,
const std::string &file_name);
extern bool GenerateDart(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Java files from the definitions in the Parser object.
// See idl_gen_java.cpp.
extern bool GenerateJava(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate JavaScript or TypeScript code from the definitions in the Parser
// object. See idl_gen_js.
extern bool GenerateTS(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Go files from the definitions in the Parser object.
// See idl_gen_go.cpp.
extern bool GenerateGo(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Php code from the definitions in the Parser object.
// See idl_gen_php.
extern bool GeneratePhp(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Python files from the definitions in the Parser object.
// See idl_gen_python.cpp.
extern bool GeneratePython(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Lobster files from the definitions in the Parser object.
// See idl_gen_lobster.cpp.
extern bool GenerateLobster(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Lua files from the definitions in the Parser object.
// See idl_gen_lua.cpp.
extern bool GenerateLua(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Rust files from the definitions in the Parser object.
// See idl_gen_rust.cpp.
extern bool GenerateRust(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Json schema file
// See idl_gen_json_schema.cpp.
extern bool GenerateJsonSchema(const Parser &parser, const std::string &path,
const std::string &file_name);
extern bool GenerateKotlin(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Swift classes.
// See idl_gen_swift.cpp
extern bool GenerateSwift(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a schema file from the internal representation, useful after
// parsing a .proto schema.
extern std::string GenerateFBS(const Parser &parser,
const std::string &file_name, bool no_log);
extern bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name, bool no_log);
// Generate a make rule for the generated TypeScript code.
// See idl_gen_ts.cpp.
extern std::string TSMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated C++ header.
// See idl_gen_cpp.cpp.
extern std::string CPPMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated Dart code
// see idl_gen_dart.cpp
extern std::string DartMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated Rust code.
// See idl_gen_rust.cpp.
extern std::string RustMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for generated Java or C# files.
// See code_generators.cpp.
extern std::string CSharpMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
extern std::string JavaMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated text (JSON) files.
// See idl_gen_text.cpp.
extern std::string TextMakeRule(const Parser &parser, const std::string &path,
const std::string &file_names);
// Generate a make rule for the generated binary files.
// See code_generators.cpp.
extern std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate GRPC Cpp interfaces.
// See idl_gen_grpc.cpp.
@@ -1368,9 +1245,6 @@ extern bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
extern bool GenerateTSGRPC(const Parser &parser, const std::string &path,
const std::string &file_name);
extern bool GenerateRustModuleRootFile(const Parser &parser,
const std::string &path);
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_H_

View File

@@ -125,8 +125,6 @@ cc_library(
"idl_gen_kotlin.h",
"idl_gen_lobster.cpp",
"idl_gen_lobster.h",
"idl_gen_lua.cpp",
"idl_gen_lua.h",
"idl_gen_php.cpp",
"idl_gen_php.h",
"idl_gen_python.cpp",

View File

@@ -88,10 +88,9 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
using BaseBfbsGenerator::GenerateCode;
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) FLATBUFFERS_OVERRIDE {
if (!GenerateLua(parser, path, filename)) { return ERROR; }
return OK;
Status GenerateCode(const Parser &, const std::string &,
const std::string &) FLATBUFFERS_OVERRIDE {
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,

View File

@@ -30,9 +30,7 @@
namespace flatbuffers {
namespace {
static std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
const std::string &path,
const std::string &file_name) {
const std::string file_extension = java ? ".java" : ".cs";
@@ -64,18 +62,6 @@ static std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
return make_rule;
}
static std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext;
}
} // namespace
void CodeWriter::operator+=(std::string text) {
if (!ignore_ident_ && !text.empty()) AppendIdent(stream_);
@@ -346,48 +332,6 @@ std::string SimpleFloatConstantGenerator::NaN(float v) const {
return this->NaN(static_cast<double>(v));
}
std::string JavaMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
return JavaCSharpMakeRule(true, parser, path, file_name);
}
std::string CSharpMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
return JavaCSharpMakeRule(false, parser, path, file_name);
}
bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer();
auto data_ptr = reinterpret_cast<char *>(data(data_vec));
return !parser.flex_builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(), data_ptr,
parser.flex_builder_.GetSize(), true);
}
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(),
reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
parser.builder_.GetSize(), true);
}
std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (!parser.builder_.GetSize()) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
std::string make_rule =
BinaryFileName(parser, path, filebase) + ": " + file_name;
auto included_files =
parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
} // namespace flatbuffers
#if defined(_MSC_VER)

View File

@@ -31,9 +31,46 @@
#include "flatbuffers/util.h"
namespace flatbuffers {
namespace {
static std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext;
}
static bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer();
auto data_ptr = reinterpret_cast<char *>(data(data_vec));
return !parser.flex_builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(), data_ptr,
parser.flex_builder_.GetSize(), true);
}
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(),
reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
parser.builder_.GetSize(), true);
}
static std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (!parser.builder_.GetSize()) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
std::string make_rule =
BinaryFileName(parser, path, filebase) + ": " + file_name;
auto included_files =
parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
class BinaryCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,

View File

@@ -4066,7 +4066,7 @@ class CppGenerator : public BaseGenerator {
} // namespace cpp
bool GenerateCPP(const Parser &parser, const std::string &path,
static bool GenerateCPP(const Parser &parser, const std::string &path,
const std::string &file_name) {
cpp::IDLOptionsCpp opts(parser.opts);
// The '--cpp_std' argument could be extended (like ASAN):
@@ -4105,7 +4105,7 @@ bool GenerateCPP(const Parser &parser, const std::string &path,
return generator.generate();
}
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 auto filebase = StripPath(StripExtension(file_name));
cpp::CppGenerator geneartor(parser, path, file_name, parser.opts);

View File

@@ -2498,7 +2498,7 @@ class CSharpGenerator : public BaseGenerator {
};
} // namespace csharp
bool GenerateCSharp(const Parser &parser, const std::string &path,
static bool GenerateCSharp(const Parser &parser, const std::string &path,
const std::string &file_name) {
csharp::CSharpGenerator generator(parser, path, file_name);
return generator.generate();
@@ -2523,7 +2523,7 @@ class CSharpCodeGenerator : public CodeGenerator {
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
output = CSharpMakeRule(parser, path, filename);
output = JavaCSharpMakeRule(false, parser, path, filename);
return Status::OK;
}

View File

@@ -1124,13 +1124,13 @@ class DartGenerator : public BaseGenerator {
};
} // namespace dart
bool GenerateDart(const Parser &parser, const std::string &path,
static bool GenerateDart(const Parser &parser, const std::string &path,
const std::string &file_name) {
dart::DartGenerator generator(parser, path, file_name);
return generator.generate();
}
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) {
auto filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));

View File

@@ -28,6 +28,7 @@
#include "flatbuffers/util.h"
namespace flatbuffers {
namespace {
static std::string GenType(const Type &type, bool underlying = false) {
switch (type.base_type) {
@@ -252,7 +253,7 @@ static void GenNameSpace(const Namespace &name_space, std::string *_schema,
}
// Generate a flatbuffer schema from the Parser's internal representation.
std::string GenerateFBS(const Parser &parser, const std::string &file_name,
static std::string GenerateFBS(const Parser &parser, const std::string &file_name,
bool no_log = false) {
// Proto namespaces may clash with table names, escape the ones that were
// generated from a table:
@@ -374,7 +375,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name,
return schema;
}
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 fbs = GenerateFBS(parser, file_name, no_log);
if (fbs.empty()) { return false; }
@@ -387,7 +388,6 @@ bool GenerateFBS(const Parser &parser, const std::string &path,
return SaveFile((path + file_name + ".fbs").c_str(), fbs, false);
}
namespace {
class FBSCodeGenerator : public CodeGenerator {
public:
@@ -399,6 +399,12 @@ class FBSCodeGenerator : public CodeGenerator {
return Status::OK;
}
Status GenerateCodeString(const Parser &parser, const std::string &filename,
std::string &output) override {
output = GenerateFBS(parser, filename, no_log_);
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override {

View File

@@ -1606,7 +1606,7 @@ class GoGenerator : public BaseGenerator {
};
} // namespace go
bool GenerateGo(const Parser &parser, const std::string &path,
static bool GenerateGo(const Parser &parser, const std::string &path,
const std::string &file_name) {
go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
return generator.generate();

View File

@@ -2196,7 +2196,7 @@ class JavaGenerator : public BaseGenerator {
};
} // namespace java
bool GenerateJava(const Parser &parser, const std::string &path,
static bool GenerateJava(const Parser &parser, const std::string &path,
const std::string &file_name) {
java::JavaGenerator generator(parser, path, file_name,
parser.opts.java_package_prefix);
@@ -2222,7 +2222,7 @@ class JavaCodeGenerator : public CodeGenerator {
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
output = JavaMakeRule(parser, path, filename);
output = JavaCSharpMakeRule(true, parser, path, filename);
return Status::OK;
}

View File

@@ -319,20 +319,13 @@ class JsonSchemaGenerator : public BaseGenerator {
};
} // namespace jsons
bool GenerateJsonSchema(const Parser &parser, const std::string &path,
static bool GenerateJsonSchema(const Parser &parser, const std::string &path,
const std::string &file_name) {
jsons::JsonSchemaGenerator generator(parser, path, file_name);
if (!generator.generate()) { return false; }
return generator.save();
}
bool GenerateJsonSchema(const Parser &parser, std::string *json) {
jsons::JsonSchemaGenerator generator(parser, "", "");
if (!generator.generate()) { return false; }
*json = generator.getJson();
return true;
}
namespace {
class JsonSchemaCodeGenerator : public CodeGenerator {

View File

@@ -1593,7 +1593,7 @@ class KotlinGenerator : public BaseGenerator {
};
} // namespace kotlin
bool GenerateKotlin(const Parser &parser, const std::string &path,
static bool GenerateKotlin(const Parser &parser, const std::string &path,
const std::string &file_name) {
kotlin::KotlinGenerator generator(parser, path, file_name);
return generator.generate();

View File

@@ -398,7 +398,7 @@ class LobsterGenerator : public BaseGenerator {
} // namespace lobster
bool GenerateLobster(const Parser &parser, const std::string &path,
static bool GenerateLobster(const Parser &parser, const std::string &path,
const std::string &file_name) {
lobster::LobsterGenerator generator(parser, path, file_name);
return generator.generate();

View File

@@ -1,806 +0,0 @@
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_lua.h"
#include <string>
#include <unordered_set>
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
namespace lua {
// Hardcode spaces per indentation.
const CommentConfig def_comment = { nullptr, "--", nullptr };
const char *Indent = " ";
const char *Comment = "-- ";
const char *End = "end\n";
const char *EndFunc = "end\n";
const char *SelfData = "self.view";
const char *SelfDataPos = "self.view.pos";
const char *SelfDataBytes = "self.view.bytes";
class LuaGenerator : public BaseGenerator {
public:
LuaGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "" /* not used */,
"" /* not used */, "lua") {
static const char *const keywords[] = {
"and", "break", "do", "else", "elseif", "end", "false", "for",
"function", "goto", "if", "in", "local", "nil", "not", "or",
"repeat", "return", "then", "true", "until", "while"
};
keywords_.insert(std::begin(keywords), std::end(keywords));
}
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that.
std::string OffsetPrefix(const FieldDef &field) {
return std::string(Indent) + "local o = " + SelfData + ":Offset(" +
NumToString(field.value.offset) + ")\n" + Indent +
"if o ~= 0 then\n";
}
// Begin a class declaration.
void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "local " + NormalizedName(struct_def) + " = {} -- the module\n";
code += "local " + NormalizedMetaName(struct_def) +
" = {} -- the class metatable\n";
code += "\n";
}
// Begin enum code with a class declaration.
void BeginEnum(const std::string &class_name, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "local " + class_name + " = {\n";
}
std::string EscapeKeyword(const std::string &name) const {
return keywords_.find(name) == keywords_.end() ? name : "_" + name;
}
std::string NormalizedName(const Definition &definition) const {
return EscapeKeyword(definition.name);
}
std::string NormalizedName(const EnumVal &ev) const {
return EscapeKeyword(ev.name);
}
std::string NormalizedMetaName(const Definition &definition) const {
return EscapeKeyword(definition.name) + "_mt";
}
// A single enum member.
void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += std::string(Indent) + NormalizedName(ev) + " = " +
enum_def.ToString(ev) + ",\n";
}
// End enum code.
void EndEnum(std::string *code_ptr) {
std::string &code = *code_ptr;
code += "}\n";
}
void GenerateNewObjectPrototype(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".New()\n";
code += std::string(Indent) + "local o = {}\n";
code += std::string(Indent) +
"setmetatable(o, {__index = " + NormalizedMetaName(struct_def) +
"})\n";
code += std::string(Indent) + "return o\n";
code += EndFunc;
}
// Initialize a new struct or table from existing data.
void NewRootTypeFromBuffer(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".GetRootAs" +
NormalizedName(struct_def) + "(buf, offset)\n";
code += std::string(Indent) + "if type(buf) == \"string\" then\n";
code += std::string(Indent) + Indent +
"buf = flatbuffers.binaryArray.New(buf)\n";
code += std::string(Indent) + "end\n";
code += std::string(Indent) +
"local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n";
code += std::string(Indent) + "local o = " + NormalizedName(struct_def) +
".New()\n";
code += std::string(Indent) + "o:Init(buf, n + offset)\n";
code += std::string(Indent) + "return o\n";
code += EndFunc;
}
// Initialize an existing object with other data, to avoid an allocation.
void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += "Init(buf, pos)\n";
code +=
std::string(Indent) + SelfData + " = flatbuffers.view.New(buf, pos)\n";
code += EndFunc;
}
// Get the length of a vector.
void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code +=
ConvertCase(NormalizedName(field), Case::kUpperCamel) + "Length()\n";
code += OffsetPrefix(field);
code +=
std::string(Indent) + Indent + "return " + SelfData + ":VectorLen(o)\n";
code += std::string(Indent) + End;
code += std::string(Indent) + "return 0\n";
code += EndFunc;
}
// Get the value of a struct's scalar.
void GetScalarFieldOfStruct(const StructDef &struct_def,
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += std::string(Indent) + "return " + getter;
code += std::string(SelfDataPos) + " + " + NumToString(field.value.offset) +
")\n";
code += EndFunc;
}
// Get the value of a table's scalar.
void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += OffsetPrefix(field);
getter += std::string("o + ") + SelfDataPos + ")";
auto is_bool = field.value.type.base_type == BASE_TYPE_BOOL;
if (is_bool) { getter = "(" + getter + " ~= 0)"; }
code += std::string(Indent) + Indent + "return " + getter + "\n";
code += std::string(Indent) + End;
std::string default_value;
if (is_bool) {
default_value = field.value.constant == "0" ? "false" : "true";
} else {
default_value = field.value.constant;
}
code += std::string(Indent) + "return " + default_value + "\n";
code += EndFunc;
}
// Get a struct by initializing an existing struct.
// Specific to Struct.
void GetStructFieldOfStruct(const StructDef &struct_def,
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(obj)\n";
code += std::string(Indent) + "obj:Init(" + SelfDataBytes + ", " +
SelfDataPos + " + ";
code += NumToString(field.value.offset) + ")\n";
code += std::string(Indent) + "return obj\n";
code += EndFunc;
}
// Get a struct by initializing an existing struct.
// Specific to Table.
void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += OffsetPrefix(field);
if (field.value.type.struct_def->fixed) {
code +=
std::string(Indent) + Indent + "local x = o + " + SelfDataPos + "\n";
} else {
code += std::string(Indent) + Indent + "local x = " + SelfData +
":Indirect(o + " + SelfDataPos + ")\n";
}
code += std::string(Indent) + Indent + "local obj = require('" +
TypeNameWithNamespace(field) + "').New()\n";
code +=
std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n";
code += std::string(Indent) + Indent + "return obj\n";
code += std::string(Indent) + End;
code += EndFunc;
}
// Get the value of a string.
void GetStringField(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += OffsetPrefix(field);
code +=
std::string(Indent) + Indent + "return " + GenGetter(field.value.type);
code += std::string("o + ") + SelfDataPos + ")\n";
code += std::string(Indent) + End;
code += EndFunc;
}
// Get the value of a union from an object.
void GetUnionField(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel) + "()\n";
code += OffsetPrefix(field);
// TODO(rw): this works and is not the good way to it:
// bool is_native_table = TypeName(field) == "*flatbuffers.Table";
// if (is_native_table) {
// code += std::string(Indent) + Indent + "from flatbuffers.table import
// Table\n";
//} else {
// code += std::string(Indent) + Indent +
// code += "from ." + TypeName(field) + " import " + TypeName(field) +
// "\n";
//}
code +=
std::string(Indent) + Indent +
"local obj = "
"flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)\n";
code += std::string(Indent) + Indent + GenGetter(field.value.type) +
"obj, o)\n";
code += std::string(Indent) + Indent + "return obj\n";
code += std::string(Indent) + End;
code += EndFunc;
}
// Get the value of a vector's struct member.
void GetMemberOfVectorOfStruct(const StructDef &struct_def,
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(j)\n";
code += OffsetPrefix(field);
code +=
std::string(Indent) + Indent + "local x = " + SelfData + ":Vector(o)\n";
code += std::string(Indent) + Indent + "x = x + ((j-1) * ";
code += NumToString(InlineSize(vectortype)) + ")\n";
if (!(vectortype.struct_def->fixed)) {
code +=
std::string(Indent) + Indent + "x = " + SelfData + ":Indirect(x)\n";
}
code += std::string(Indent) + Indent + "local obj = require('" +
TypeNameWithNamespace(field) + "').New()\n";
code +=
std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n";
code += std::string(Indent) + Indent + "return obj\n";
code += std::string(Indent) + End;
code += EndFunc;
}
// Get the value of a vector's non-struct member. Uses a named return
// argument to conveniently set the zero value for the result.
void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(j)\n";
code += OffsetPrefix(field);
code +=
std::string(Indent) + Indent + "local a = " + SelfData + ":Vector(o)\n";
code += std::string(Indent) + Indent;
code += "return " + GenGetter(field.value.type);
code += "a + ((j-1) * ";
code += NumToString(InlineSize(vectortype)) + "))\n";
code += std::string(Indent) + End;
if (IsString(vectortype)) {
code += std::string(Indent) + "return ''\n";
} else {
code += std::string(Indent) + "return 0\n";
}
code += EndFunc;
}
// Access a byte/ubyte vector as a string
void AccessByteVectorAsString(const StructDef &struct_def,
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "AsString(start, stop)\n";
code += std::string(Indent) + "return " + SelfData + ":VectorAsString(" +
NumToString(field.value.offset) + ", start, stop)\n";
code += EndFunc;
}
// Begin the creator function signature.
void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".Create" +
NormalizedName(struct_def);
code += "(builder";
}
// Recursively generate arguments for a constructor, to deal with nested
// structs.
void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix,
std::string *code_ptr) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing
// a nested struct, prefix the name with the field name.
StructBuilderArgs(*field.value.type.struct_def,
(nameprefix + (NormalizedName(field) + "_")).c_str(),
code_ptr);
} else {
std::string &code = *code_ptr;
code += std::string(", ") + nameprefix;
code += ConvertCase(NormalizedName(field), Case::kLowerCamel);
}
}
}
// End the creator function signature.
void EndBuilderArgs(std::string *code_ptr) {
std::string &code = *code_ptr;
code += ")\n";
}
// Recursively generate struct construction statements and instert manual
// padding.
void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += std::string(Indent) + "builder:Prep(" +
NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ")\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
if (field.padding)
code += std::string(Indent) + "builder:Pad(" +
NumToString(field.padding) + ")\n";
if (IsStruct(field.value.type)) {
StructBuilderBody(*field.value.type.struct_def,
(nameprefix + (NormalizedName(field) + "_")).c_str(),
code_ptr);
} else {
code +=
std::string(Indent) + "builder:Prepend" + GenMethod(field) + "(";
code += nameprefix +
ConvertCase(NormalizedName(field), Case::kLowerCamel) + ")\n";
}
}
}
void EndBuilderBody(std::string *code_ptr) {
std::string &code = *code_ptr;
code += std::string(Indent) + "return builder:Offset()\n";
code += EndFunc;
}
// Get the value of a table's starting offset.
void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".Start";
code += "(builder) ";
code += "builder:StartObject(";
code += NumToString(struct_def.fields.vec.size());
code += ") end\n";
}
// Set the value of a table's field.
void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
const size_t offset, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".Add" +
ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(builder, ";
code += ConvertCase(NormalizedName(field), Case::kLowerCamel);
code += ") ";
code += "builder:Prepend";
code += GenMethod(field) + "Slot(";
code += NumToString(offset) + ", ";
// todo: i don't need to cast in Lua, but am I missing something?
// if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
// code += "flatbuffers.N.UOffsetTFlags.py_type";
// code += "(";
// code += ConvertCase(NormalizedName(field), Case::kLowerCamel) + ")";
// } else {
code += ConvertCase(NormalizedName(field), Case::kLowerCamel);
// }
code += ", " + field.value.constant;
code += ") end\n";
}
// Set the value of one of the members of a table's vector.
void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".Start";
code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "Vector(builder, numElems) return builder:StartVector(";
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
auto elem_size = InlineSize(vector_type);
code += NumToString(elem_size);
code += ", numElems, " + NumToString(alignment);
code += ") end\n";
}
// Get the offset of the end of a table.
void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".End";
code += "(builder) ";
code += "return builder:EndObject() end\n";
}
// Generate the receiver for function signatures.
void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedMetaName(struct_def) + ":";
}
// Generate a struct field, conditioned on its child type(s).
void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
GenComment(field.doc_comment, code_ptr, &def_comment);
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
GetScalarFieldOfStruct(struct_def, field, code_ptr);
} else {
GetScalarFieldOfTable(struct_def, field, code_ptr);
}
} else {
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT:
if (struct_def.fixed) {
GetStructFieldOfStruct(struct_def, field, code_ptr);
} else {
GetStructFieldOfTable(struct_def, field, code_ptr);
}
break;
case BASE_TYPE_STRING:
GetStringField(struct_def, field, code_ptr);
break;
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_STRUCT) {
GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
} else {
GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
if (vectortype.base_type == BASE_TYPE_CHAR ||
vectortype.base_type == BASE_TYPE_UCHAR) {
AccessByteVectorAsString(struct_def, field, code_ptr);
}
}
break;
}
case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
default: FLATBUFFERS_ASSERT(0);
}
}
if (IsVector(field.value.type)) {
GetVectorLen(struct_def, field, code_ptr);
}
}
// Generate table constructors, conditioned on its members' types.
void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
auto offset = it - struct_def.fields.vec.begin();
BuildFieldOfTable(struct_def, field, offset, code_ptr);
if (IsVector(field.value.type)) {
BuildVectorOfTable(struct_def, field, code_ptr);
}
}
GetEndOffsetOnTable(struct_def, code_ptr);
}
// Generate struct or table methods.
void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, &def_comment);
BeginClass(struct_def, code_ptr);
GenerateNewObjectPrototype(struct_def, code_ptr);
if (!struct_def.fixed) {
// Generate a special accessor for the table that has been declared as
// the root type.
NewRootTypeFromBuffer(struct_def, code_ptr);
}
// Generate the Init method that sets the field in a pre-existing
// accessor object. This is to allow object reuse.
InitializeExisting(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr);
}
if (struct_def.fixed) {
// create a struct constructor function
GenStructBuilder(struct_def, code_ptr);
} else {
// Create a set of functions that allow table construction.
GenTableBuilders(struct_def, code_ptr);
}
}
// Generate enum declarations.
void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
if (enum_def.generated) return;
GenComment(enum_def.doc_comment, code_ptr, &def_comment);
BeginEnum(NormalizedName(enum_def), code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, &def_comment, Indent);
EnumMember(enum_def, ev, code_ptr);
}
EndEnum(code_ptr);
}
// Returns the function name that is able to read a value of the given type.
std::string GenGetter(const Type &type) {
switch (type.base_type) {
case BASE_TYPE_STRING: return std::string(SelfData) + ":String(";
case BASE_TYPE_UNION: return std::string(SelfData) + ":Union(";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
default:
return std::string(SelfData) + ":Get(flatbuffers.N." +
ConvertCase(GenTypeGet(type), Case::kUpperCamel) + ", ";
}
}
// Returns the method name for use with add/put calls.
std::string GenMethod(const FieldDef &field) {
return IsScalar(field.value.type.base_type)
? ConvertCase(GenTypeBasic(field.value.type), Case::kUpperCamel)
: (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
}
std::string GenTypeBasic(const Type &type) {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, ...) \
#PTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
return ctypename[type.base_type];
}
std::string GenTypePointer(const Type &type) {
switch (type.base_type) {
case BASE_TYPE_STRING: return "string";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
case BASE_TYPE_STRUCT: return type.struct_def->name;
case BASE_TYPE_UNION:
// fall through
default: return "*flatbuffers.Table";
}
}
std::string GenTypeGet(const Type &type) {
return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
std::string GetNamespace(const Type &type) {
return type.struct_def->defined_namespace->GetFullyQualifiedName(
type.struct_def->name);
}
std::string TypeName(const FieldDef &field) {
return GenTypeGet(field.value.type);
}
std::string TypeNameWithNamespace(const FieldDef &field) {
return GetNamespace(field.value.type);
}
// Create a struct with a builder and the struct's arguments.
void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
BeginBuilderArgs(struct_def, code_ptr);
StructBuilderArgs(struct_def, "", code_ptr);
EndBuilderArgs(code_ptr);
StructBuilderBody(struct_def, "", code_ptr);
EndBuilderBody(code_ptr);
}
bool generate() {
if (!generateEnums()) return false;
if (!generateStructs()) return false;
return true;
}
private:
bool generateEnums() {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
std::string enumcode;
GenEnum(enum_def, &enumcode);
if (!SaveType(enum_def, enumcode, false)) return false;
}
return true;
}
bool generateStructs() {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
std::string declcode;
GenStruct(struct_def, &declcode);
if (!SaveType(struct_def, declcode, true)) return false;
}
return true;
}
// Begin by declaring namespace and imports.
void BeginFile(const std::string &name_space_name, const bool needs_imports,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += std::string(Comment) + FlatBuffersGeneratedWarning() + "\n\n";
code += std::string(Comment) + "namespace: " + name_space_name + "\n\n";
if (needs_imports) {
code += "local flatbuffers = require('flatbuffers')\n\n";
}
}
// Save out the generated code for a Lua Table type.
bool SaveType(const Definition &def, const std::string &classcode,
bool needs_imports) {
if (!classcode.length()) return true;
std::string namespace_dir = path_;
auto &namespaces = def.defined_namespace->components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (it != namespaces.begin()) namespace_dir += kPathSeparator;
namespace_dir += *it;
// std::string init_py_filename = namespace_dir + "/__init__.py";
// SaveFile(init_py_filename.c_str(), "", false);
}
std::string code = "";
BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code);
code += classcode;
code += "\n";
code +=
"return " + NormalizedName(def) + " " + Comment + "return the module";
std::string filename =
NamespaceDir(*def.defined_namespace) + NormalizedName(def) + ".lua";
return SaveFile(filename.c_str(), code, false);
}
private:
std::unordered_set<std::string> keywords_;
};
} // namespace lua
bool GenerateLua(const Parser &parser, const std::string &path,
const std::string &file_name) {
lua::LuaGenerator generator(parser, path, file_name);
return generator.generate();
}
namespace {
class LuaCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateLua(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return true; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kLua; }
std::string LanguageName() const override { return "Lua"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewLuaCodeGenerator() {
return std::unique_ptr<LuaCodeGenerator>(new LuaCodeGenerator());
}
} // namespace flatbuffers

View File

@@ -1,29 +0,0 @@
/*
* Copyright 2023 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLATBUFFERS_IDL_GEN_LUA_H_
#define FLATBUFFERS_IDL_GEN_LUA_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Lua code generator.
std::unique_ptr<CodeGenerator> NewLuaCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_LUA_H_

View File

@@ -939,7 +939,7 @@ class PhpGenerator : public BaseGenerator {
};
} // namespace php
bool GeneratePhp(const Parser &parser, const std::string &path,
static bool GeneratePhp(const Parser &parser, const std::string &path,
const std::string &file_name) {
php::PhpGenerator generator(parser, path, file_name);
return generator.generate();

View File

@@ -2135,7 +2135,7 @@ class PythonGenerator : public BaseGenerator {
} // namespace python
bool GeneratePython(const Parser &parser, const std::string &path,
static bool GeneratePython(const Parser &parser, const std::string &path,
const std::string &file_name) {
python::PythonGenerator generator(parser, path, file_name);
return generator.generate();

View File

@@ -279,7 +279,7 @@ static bool IsOptionalToBuilder(const FieldDef &field) {
}
} // namespace
bool GenerateRustModuleRootFile(const Parser &parser,
static bool GenerateRustModuleRootFile(const Parser &parser,
const std::string &output_dir) {
if (!parser.opts.rust_module_root_file) {
// Don't generate a root file when generating one file. This isn't an error
@@ -2989,13 +2989,13 @@ class RustGenerator : public BaseGenerator {
} // namespace rust
bool GenerateRust(const Parser &parser, const std::string &path,
static bool GenerateRust(const Parser &parser, const std::string &path,
const std::string &file_name) {
rust::RustGenerator generator(parser, path, file_name);
return generator.generate();
}
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) {
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));

View File

@@ -1899,7 +1899,8 @@ class SwiftGenerator : public BaseGenerator {
IdlNamer namer_;
};
} // namespace swift
bool GenerateSwift(const Parser &parser, const std::string &path,
static bool GenerateSwift(const Parser &parser, const std::string &path,
const std::string &file_name) {
swift::SwiftGenerator generator(parser, path, file_name);
return generator.generate();

View File

@@ -104,7 +104,7 @@ struct JsonPrinter {
// "[]".
template<typename Container, typename SizeT = typename Container::size_type>
const char *PrintContainer(PrintScalarTag, const Container &c, SizeT size,
const Type &type, int indent, const uint8_t *) {
const Type &type, int indent, const uint8_t *) {
const auto elem_indent = indent + Indent();
text += '[';
AddNewLine();
@@ -126,7 +126,8 @@ struct JsonPrinter {
// "[]".
template<typename Container, typename SizeT = typename Container::size_type>
const char *PrintContainer(PrintPointerTag, const Container &c, SizeT size,
const Type &type, int indent, const uint8_t *prev_val) {
const Type &type, int indent,
const uint8_t *prev_val) {
const auto is_struct = IsStruct(type);
const auto elem_indent = indent + Indent();
text += '[';
@@ -152,7 +153,7 @@ struct JsonPrinter {
template<typename T, typename SizeT = uoffset_t>
const char *PrintVector(const void *val, const Type &type, int indent,
const uint8_t *prev_val) {
const uint8_t *prev_val) {
typedef Vector<T, SizeT> Container;
typedef typename PrintTag<typename Container::return_type>::type tag;
auto &vec = *reinterpret_cast<const Container *>(val);
@@ -163,8 +164,8 @@ struct JsonPrinter {
// Print an array a sequence of JSON values, comma separated, wrapped in "[]".
template<typename T>
const char *PrintArray(const void *val, uint16_t size, const Type &type,
int indent) {
int indent) {
typedef Array<T, 0xFFFF> Container;
typedef typename PrintTag<typename Container::return_type>::type tag;
auto &arr = *reinterpret_cast<const Container *>(val);
@@ -172,7 +173,7 @@ struct JsonPrinter {
}
const char *PrintOffset(const void *val, const Type &type, int indent,
const uint8_t *prev_val, soffset_t vector_index) {
const uint8_t *prev_val, soffset_t vector_index) {
switch (type.base_type) {
case BASE_TYPE_UNION: {
// If this assert hits, you have an corrupt buffer, a union type field
@@ -196,8 +197,8 @@ struct JsonPrinter {
indent);
case BASE_TYPE_STRING: {
auto s = reinterpret_cast<const String *>(val);
bool ok = EscapeString(s->c_str(), s->size(), &text, opts.allow_non_utf8,
opts.natural_utf8);
bool ok = EscapeString(s->c_str(), s->size(), &text,
opts.allow_non_utf8, opts.natural_utf8);
return ok ? nullptr : "string contains non-utf8 bytes";
}
case BASE_TYPE_VECTOR: {
@@ -235,9 +236,7 @@ struct JsonPrinter {
// clang-format on
return nullptr;
}
default:
FLATBUFFERS_ASSERT(0);
return "unknown type";
default: FLATBUFFERS_ASSERT(0); return "unknown type";
}
}
@@ -265,15 +264,14 @@ struct JsonPrinter {
text += "null";
}
} else {
PrintScalar(
table->GetField<T>(fd.value.offset, GetFieldDefault<T>(fd)),
fd.value.type, indent);
PrintScalar(table->GetField<T>(fd.value.offset, GetFieldDefault<T>(fd)),
fd.value.type, indent);
}
}
// Generate text for non-scalar field.
const char *GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
int indent, const uint8_t *prev_val) {
int indent, const uint8_t *prev_val) {
const void *val = nullptr;
if (fixed) {
// The only non-scalar fields in structs are structs or arrays.
@@ -372,7 +370,8 @@ struct JsonPrinter {
};
static const char *GenerateTextImpl(const Parser &parser, const Table *table,
const StructDef &struct_def, std::string *_text) {
const StructDef &struct_def,
std::string *_text) {
JsonPrinter printer(parser, *_text);
auto err = printer.GenStruct(struct_def, table, 0);
if (err) return err;
@@ -382,7 +381,8 @@ static const char *GenerateTextImpl(const Parser &parser, const Table *table,
// Generate a text representation of a flatbuffer in JSON format.
const char *GenerateTextFromTable(const Parser &parser, const void *table,
const std::string &table_name, std::string *_text) {
const std::string &table_name,
std::string *_text) {
auto struct_def = parser.LookupStruct(table_name);
if (struct_def == nullptr) { return "unknown struct"; }
auto root = static_cast<const Table *>(table);
@@ -391,7 +391,7 @@ const char *GenerateTextFromTable(const Parser &parser, const void *table,
// Generate a text representation of a flatbuffer in JSON format.
const char *GenerateText(const Parser &parser, const void *flatbuffer,
std::string *_text) {
std::string *_text) {
FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType()
auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer)
: GetRoot<Table>(flatbuffer);
@@ -403,8 +403,9 @@ static std::string TextFileName(const std::string &path,
return path + file_name + ".json";
}
const char *GenerateTextFile(const Parser &parser, const std::string &path,
const std::string &file_name) {
static const char *GenerateTextFile(const Parser &parser,
const std::string &path,
const std::string &file_name) {
if (parser.opts.use_flexbuffers) {
std::string json;
parser.flex_root_.ToString(true, parser.opts.strict_json, json);
@@ -423,8 +424,8 @@ const char *GenerateTextFile(const Parser &parser, const std::string &path,
: "SaveFile failed";
}
std::string TextMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
static std::string TextMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));

View File

@@ -2161,13 +2161,13 @@ class TsGenerator : public BaseGenerator {
}; // namespace ts
} // namespace ts
bool GenerateTS(const Parser &parser, const std::string &path,
static bool GenerateTS(const Parser &parser, const std::string &path,
const std::string &file_name) {
ts::TsGenerator generator(parser, path, file_name);
return generator.generate();
}
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) {
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));

View File

@@ -17,7 +17,10 @@ void RunTest(const flatbuffers::IDLOptions &opts, const std::string &proto_path,
TEST_EQ(parser.Parse(proto_file.c_str(), include_directories), true);
// Generate fbs.
auto fbs = flatbuffers::GenerateFBS(parser, "test", true);
std::unique_ptr<CodeGenerator> fbs_generator = NewFBSCodeGenerator(true);
std::string fbs;
TEST_EQ(fbs_generator->GenerateCodeString(parser, "test", fbs),
CodeGenerator::Status::OK);
// Ensure generated file is parsable.
flatbuffers::Parser parser2;
@@ -27,7 +30,10 @@ void RunTest(const flatbuffers::IDLOptions &opts, const std::string &proto_path,
flatbuffers::Parser import_parser(opts);
TEST_EQ(import_parser.Parse(import_proto_file.c_str(), include_directories),
true);
auto import_fbs = flatbuffers::GenerateFBS(import_parser, "test", true);
std::string import_fbs;
TEST_EQ(fbs_generator->GenerateCodeString(import_parser, "test", import_fbs),
CodeGenerator::Status::OK);
// auto import_fbs = flatbuffers::GenerateFBS(import_parser, "test", true);
// Since `imported.fbs` isn't in the filesystem AbsolutePath can't figure it
// out by itself. We manually construct it so Parser works.
std::string imported_fbs = flatbuffers::PosixPath(