Added --gen-all to generate code for a schema and all its includes.

Also refactored the way options are stored.

Change-Id: I709ac908cd2aba396c9c282725cf1d42ccce0882
Tested: on Linux.
parent 47478117
...@@ -94,6 +94,7 @@ $(document).ready(function(){initNavTree('md__compiler.html','');}); ...@@ -94,6 +94,7 @@ $(document).ready(function(){initNavTree('md__compiler.html','');});
<li><code>--no-includes</code> : Don't generate include statements for included schemas the generated file depends on (C++).</li> <li><code>--no-includes</code> : Don't generate include statements for included schemas the generated file depends on (C++).</li>
<li><code>--gen-mutable</code> : Generate additional non-const accessors for mutating FlatBuffers in-place.</li> <li><code>--gen-mutable</code> : Generate additional non-const accessors for mutating FlatBuffers in-place.</li>
<li><code>--gen-onefile</code> : Generate single output file (useful for C#)</li> <li><code>--gen-onefile</code> : Generate single output file (useful for C#)</li>
<li><code>--gen-all</code>: Generate not just code for the current schema files, but for all files it includes as well. If the language uses a single file for output (by default the case for C++ and JS), all code will end up in this one file.</li>
<li><code>--raw-binary</code> : Allow binaries without a file_indentifier to be read. This may crash flatc given a mismatched schema.</li> <li><code>--raw-binary</code> : Allow binaries without a file_indentifier to be read. This may crash flatc given a mismatched schema.</li>
<li><code>--proto</code>: Expect input files to be .proto files (protocol buffers). Output the corresponding .fbs file. Currently supports: <code>package</code>, <code>message</code>, <code>enum</code>, nested declarations, <code>import</code> (use <code>-I</code> for paths), <code>extend</code>, <code>oneof</code>, <code>group</code>. Does not support, but will skip without error: <code>option</code>, <code>service</code>, <code>extensions</code>, and most everything else.</li> <li><code>--proto</code>: Expect input files to be .proto files (protocol buffers). Output the corresponding .fbs file. Currently supports: <code>package</code>, <code>message</code>, <code>enum</code>, nested declarations, <code>import</code> (use <code>-I</code> for paths), <code>extend</code>, <code>oneof</code>, <code>group</code>. Does not support, but will skip without error: <code>option</code>, <code>service</code>, <code>extensions</code>, and most everything else.</li>
<li><code>--schema</code>: Serialize schemas instead of JSON (use with -b). This will output a binary version of the specified schema that itself corresponds to the reflection/reflection.fbs schema. Loading this binary file is the basis for reflection functionality.</li> <li><code>--schema</code>: Serialize schemas instead of JSON (use with -b). This will output a binary version of the specified schema that itself corresponds to the reflection/reflection.fbs schema. Loading this binary file is the basis for reflection functionality.</li>
......
...@@ -80,6 +80,11 @@ Additional options: ...@@ -80,6 +80,11 @@ Additional options:
- `--gen-onefile` : Generate single output file (useful for C#) - `--gen-onefile` : Generate single output file (useful for C#)
- `--gen-all`: Generate not just code for the current schema files, but
for all files it includes as well. If the language uses a single file for
output (by default the case for C++ and JS), all code will end up in
this one file.
- `--raw-binary` : Allow binaries without a file_indentifier to be read. - `--raw-binary` : Allow binaries without a file_indentifier to be read.
This may crash flatc given a mismatched schema. This may crash flatc given a mismatched schema.
......
This diff is collapsed.
...@@ -47,8 +47,7 @@ int main(int /*argc*/, const char * /*argv*/[]) { ...@@ -47,8 +47,7 @@ int main(int /*argc*/, const char * /*argv*/[]) {
// to ensure it is correct, we now generate text back from the binary, // to ensure it is correct, we now generate text back from the binary,
// and compare the two: // and compare the two:
std::string jsongen; std::string jsongen;
GenerateText(parser, parser.builder_.GetBufferPointer(), GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
flatbuffers::GeneratorOptions(), &jsongen);
if (jsongen != jsonfile) { if (jsongen != jsonfile) {
printf("%s----------------\n%s", jsongen.c_str(), jsonfile.c_str()); printf("%s----------------\n%s", jsongen.c_str(), jsonfile.c_str());
......
...@@ -26,55 +26,53 @@ static void Error(const std::string &err, bool usage = false, ...@@ -26,55 +26,53 @@ static void Error(const std::string &err, bool usage = false,
struct Generator { struct Generator {
bool (*generate)(const flatbuffers::Parser &parser, bool (*generate)(const flatbuffers::Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name);
const flatbuffers::GeneratorOptions &opts);
const char *generator_opt_short; const char *generator_opt_short;
const char *generator_opt_long; const char *generator_opt_long;
const char *lang_name; const char *lang_name;
flatbuffers::GeneratorOptions::Language lang; flatbuffers::IDLOptions::Language lang;
const char *generator_help; const char *generator_help;
std::string (*make_rule)(const flatbuffers::Parser &parser, std::string (*make_rule)(const flatbuffers::Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name);
const flatbuffers::GeneratorOptions &opts);
}; };
const Generator generators[] = { const Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary", { flatbuffers::GenerateBinary, "-b", "--binary", "binary",
flatbuffers::GeneratorOptions::kMAX, flatbuffers::IDLOptions::kMAX,
"Generate wire format binaries for any data definitions", "Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule }, flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text", { flatbuffers::GenerateTextFile, "-t", "--json", "text",
flatbuffers::GeneratorOptions::kMAX, flatbuffers::IDLOptions::kMAX,
"Generate text output for any data definitions", "Generate text output for any data definitions",
flatbuffers::TextMakeRule }, flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++", { flatbuffers::GenerateCPP, "-c", "--cpp", "C++",
flatbuffers::GeneratorOptions::kMAX, flatbuffers::IDLOptions::kMAX,
"Generate C++ headers for tables/structs", "Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule }, flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go", { flatbuffers::GenerateGo, "-g", "--go", "Go",
flatbuffers::GeneratorOptions::kGo, flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs", "Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java", { flatbuffers::GenerateGeneral, "-j", "--java", "Java",
flatbuffers::GeneratorOptions::kJava, flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs", "Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript", { flatbuffers::GenerateJS, "-s", "--js", "JavaScript",
flatbuffers::GeneratorOptions::kMAX, flatbuffers::IDLOptions::kMAX,
"Generate JavaScript code for tables/structs", "Generate JavaScript code for tables/structs",
flatbuffers::JSMakeRule }, flatbuffers::JSMakeRule },
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#", { flatbuffers::GenerateGeneral, "-n", "--csharp", "C#",
flatbuffers::GeneratorOptions::kCSharp, flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs", "Generate C# classes for tables/structs",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePython, "-p", "--python", "Python", { flatbuffers::GeneratePython, "-p", "--python", "Python",
flatbuffers::GeneratorOptions::kMAX, flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs", "Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP", { flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::GeneratorOptions::kMAX, flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs", "Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule }, flatbuffers::GeneralMakeRule },
}; };
...@@ -129,13 +127,12 @@ static void Error(const std::string &err, bool usage, bool show_exe_name) { ...@@ -129,13 +127,12 @@ static void Error(const std::string &err, bool usage, bool show_exe_name) {
int main(int argc, const char *argv[]) { int main(int argc, const char *argv[]) {
program_name = argv[0]; program_name = argv[0];
flatbuffers::GeneratorOptions opts; flatbuffers::IDLOptions opts;
std::string output_path; std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]); const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
bool generator_enabled[num_generators] = { false }; bool generator_enabled[num_generators] = { false };
bool any_generator = false; bool any_generator = false;
bool print_make_rules = false; bool print_make_rules = false;
bool proto_mode = false;
bool raw_binary = false; bool raw_binary = false;
bool schema_binary = false; bool schema_binary = false;
std::vector<std::string> filenames; std::vector<std::string> filenames;
...@@ -165,6 +162,9 @@ int main(int argc, const char *argv[]) { ...@@ -165,6 +162,9 @@ int main(int argc, const char *argv[]) {
opts.scoped_enums = true; opts.scoped_enums = true;
} else if(arg == "--gen-mutable") { } else if(arg == "--gen-mutable") {
opts.mutable_buffer = true; opts.mutable_buffer = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if(arg == "--gen-includes") { } else if(arg == "--gen-includes") {
// Deprecated, remove this option some time in the future. // Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n"); printf("warning: --gen-includes is deprecated (it is now default)\n");
...@@ -177,7 +177,7 @@ int main(int argc, const char *argv[]) { ...@@ -177,7 +177,7 @@ int main(int argc, const char *argv[]) {
} else if(arg == "--") { // Separator between text and binary inputs. } else if(arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size(); binary_files_from = filenames.size();
} else if(arg == "--proto") { } else if(arg == "--proto") {
proto_mode = true; opts.proto_mode = true;
any_generator = true; any_generator = true;
} else if(arg == "--schema") { } else if(arg == "--schema") {
schema_binary = true; schema_binary = true;
...@@ -204,10 +204,10 @@ int main(int argc, const char *argv[]) { ...@@ -204,10 +204,10 @@ int main(int argc, const char *argv[]) {
if (!filenames.size()) Error("missing input files", false, true); if (!filenames.size()) Error("missing input files", false, true);
if (!any_generator) if (!any_generator)
Error("no options: specify one of -c -g -j -t -b etc.", true); Error("no options: specify at least one generator.", true);
// Now process the files: // Now process the files:
parser = new flatbuffers::Parser(opts.strict_json, proto_mode); parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin(); for (auto file_it = filenames.begin();
file_it != filenames.end(); file_it != filenames.end();
++file_it) { ++file_it) {
...@@ -248,7 +248,7 @@ int main(int argc, const char *argv[]) { ...@@ -248,7 +248,7 @@ int main(int argc, const char *argv[]) {
// one from scratch. If it depends on previous schemas it must do // one from scratch. If it depends on previous schemas it must do
// so explicitly using an include. // so explicitly using an include.
delete parser; delete parser;
parser = new flatbuffers::Parser(opts.strict_json, proto_mode); parser = new flatbuffers::Parser(opts);
} }
auto local_include_directory = flatbuffers::StripFileName(*file_it); auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str()); include_directories.push_back(local_include_directory.c_str());
...@@ -272,7 +272,7 @@ int main(int argc, const char *argv[]) { ...@@ -272,7 +272,7 @@ int main(int argc, const char *argv[]) {
if (generator_enabled[i]) { if (generator_enabled[i]) {
if (!print_make_rules) { if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path); flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase, opts)) { if (!generators[i].generate(*parser, output_path, filebase)) {
Error(std::string("Unable to generate ") + Error(std::string("Unable to generate ") +
generators[i].lang_name + generators[i].lang_name +
" for " + " for " +
...@@ -280,7 +280,7 @@ int main(int argc, const char *argv[]) { ...@@ -280,7 +280,7 @@ int main(int argc, const char *argv[]) {
} }
} else { } else {
std::string make_rule = generators[i].make_rule( std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it, opts); *parser, output_path, *file_it);
if (!make_rule.empty()) if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap( printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str()); make_rule, 80, " ", " \\").c_str());
...@@ -288,7 +288,11 @@ int main(int argc, const char *argv[]) { ...@@ -288,7 +288,11 @@ int main(int argc, const char *argv[]) {
} }
} }
if (proto_mode) GenerateFBS(*parser, output_path, filebase, opts); if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
} }
delete parser; delete parser;
......
...@@ -127,18 +127,18 @@ static std::string GenTypeGet(const Parser &parser, const Type &type, ...@@ -127,18 +127,18 @@ static std::string GenTypeGet(const Parser &parser, const Type &type,
} }
static std::string GenEnumDecl(const EnumDef &enum_def, static std::string GenEnumDecl(const EnumDef &enum_def,
const GeneratorOptions &opts) { const IDLOptions &opts) {
return (opts.scoped_enums ? "enum class " : "enum ") + enum_def.name; return (opts.scoped_enums ? "enum class " : "enum ") + enum_def.name;
} }
static std::string GenEnumVal(const EnumDef &enum_def, const EnumVal &enum_val, static std::string GenEnumVal(const EnumDef &enum_def, const EnumVal &enum_val,
const GeneratorOptions &opts) { const IDLOptions &opts) {
return opts.prefixed_enums ? enum_def.name + "_" + enum_val.name return opts.prefixed_enums ? enum_def.name + "_" + enum_val.name
: enum_val.name; : enum_val.name;
} }
static std::string GetEnumVal(const EnumDef &enum_def, const EnumVal &enum_val, static std::string GetEnumVal(const EnumDef &enum_def, const EnumVal &enum_val,
const GeneratorOptions &opts) { const IDLOptions &opts) {
if (opts.scoped_enums) { if (opts.scoped_enums) {
return enum_def.name + "::" + enum_val.name; return enum_def.name + "::" + enum_val.name;
} else if (opts.prefixed_enums) { } else if (opts.prefixed_enums) {
...@@ -150,14 +150,13 @@ static std::string GetEnumVal(const EnumDef &enum_def, const EnumVal &enum_val, ...@@ -150,14 +150,13 @@ static std::string GetEnumVal(const EnumDef &enum_def, const EnumVal &enum_val,
// Generate an enum declaration and an enum string lookup table. // Generate an enum declaration and an enum string lookup table.
static void GenEnum(const Parser &parser, EnumDef &enum_def, static void GenEnum(const Parser &parser, EnumDef &enum_def,
std::string *code_ptr, std::string *code_ptr_post, std::string *code_ptr, std::string *code_ptr_post) {
const GeneratorOptions &opts) {
if (enum_def.generated) return; if (enum_def.generated) return;
std::string &code = *code_ptr; std::string &code = *code_ptr;
std::string &code_post = *code_ptr_post; std::string &code_post = *code_ptr_post;
GenComment(enum_def.doc_comment, code_ptr, nullptr); GenComment(enum_def.doc_comment, code_ptr, nullptr);
code += GenEnumDecl(enum_def, opts); code += GenEnumDecl(enum_def, parser.opts);
if (opts.scoped_enums) if (parser.opts.scoped_enums)
code += " : " + GenTypeBasic(parser, enum_def.underlying_type, false); code += " : " + GenTypeBasic(parser, enum_def.underlying_type, false);
code += " {\n"; code += " {\n";
for (auto it = enum_def.vals.vec.begin(); for (auto it = enum_def.vals.vec.begin();
...@@ -165,7 +164,7 @@ static void GenEnum(const Parser &parser, EnumDef &enum_def, ...@@ -165,7 +164,7 @@ static void GenEnum(const Parser &parser, EnumDef &enum_def,
++it) { ++it) {
auto &ev = **it; auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, " "); GenComment(ev.doc_comment, code_ptr, nullptr, " ");
code += " " + GenEnumVal(enum_def, ev, opts) + " = "; code += " " + GenEnumVal(enum_def, ev, parser.opts) + " = ";
code += NumToString(ev.value); code += NumToString(ev.value);
code += (it + 1) != enum_def.vals.vec.end() ? ",\n" : "\n"; code += (it + 1) != enum_def.vals.vec.end() ? ",\n" : "\n";
} }
...@@ -196,7 +195,7 @@ static void GenEnum(const Parser &parser, EnumDef &enum_def, ...@@ -196,7 +195,7 @@ static void GenEnum(const Parser &parser, EnumDef &enum_def,
code += "()[static_cast<int>(e)"; code += "()[static_cast<int>(e)";
if (enum_def.vals.vec.front()->value) { if (enum_def.vals.vec.front()->value) {
code += " - static_cast<int>("; code += " - static_cast<int>(";
code += GetEnumVal(enum_def, *enum_def.vals.vec.front(), opts) +")"; code += GetEnumVal(enum_def, *enum_def.vals.vec.front(), parser.opts) +")";
} }
code += "]; }\n\n"; code += "]; }\n\n";
} }
...@@ -216,7 +215,7 @@ static void GenEnum(const Parser &parser, EnumDef &enum_def, ...@@ -216,7 +215,7 @@ static void GenEnum(const Parser &parser, EnumDef &enum_def,
it != enum_def.vals.vec.end(); it != enum_def.vals.vec.end();
++it) { ++it) {
auto &ev = **it; auto &ev = **it;
code_post += " case " + GetEnumVal(enum_def, ev, opts); code_post += " case " + GetEnumVal(enum_def, ev, parser.opts);
if (!ev.value) { if (!ev.value) {
code_post += ": return true;\n"; // "NONE" enum value. code_post += ": return true;\n"; // "NONE" enum value.
} else { } else {
...@@ -250,7 +249,7 @@ std::string GenFieldOffsetName(const FieldDef &field) { ...@@ -250,7 +249,7 @@ std::string GenFieldOffsetName(const FieldDef &field) {
// Generate an accessor struct, builder structs & function for a table. // Generate an accessor struct, builder structs & function for a table.
static void GenTable(const Parser &parser, StructDef &struct_def, static void GenTable(const Parser &parser, StructDef &struct_def,
const GeneratorOptions &opts, std::string *code_ptr) { std::string *code_ptr) {
if (struct_def.generated) return; if (struct_def.generated) return;
std::string &code = *code_ptr; std::string &code = *code_ptr;
...@@ -298,7 +297,7 @@ static void GenTable(const Parser &parser, StructDef &struct_def, ...@@ -298,7 +297,7 @@ static void GenTable(const Parser &parser, StructDef &struct_def,
call += ")"; call += ")";
code += GenUnderlyingCast(parser, field, true, call); code += GenUnderlyingCast(parser, field, true, call);
code += "; }\n"; code += "; }\n";
if (opts.mutable_buffer) { if (parser.opts.mutable_buffer) {
if (is_scalar) { if (is_scalar) {
code += " bool mutate_" + field.name + "("; code += " bool mutate_" + field.name + "(";
code += GenTypeBasic(parser, field.value.type, true); code += GenTypeBasic(parser, field.value.type, true);
...@@ -339,7 +338,7 @@ static void GenTable(const Parser &parser, StructDef &struct_def, ...@@ -339,7 +338,7 @@ static void GenTable(const Parser &parser, StructDef &struct_def,
code += "const char *val) const { return strcmp(" + field.name; code += "const char *val) const { return strcmp(" + field.name;
code += "()->c_str(), val); }\n"; code += "()->c_str(), val); }\n";
} else { } else {
if (opts.scoped_enums && if (parser.opts.scoped_enums &&
field.value.type.enum_def && field.value.type.enum_def &&
IsScalar(field.value.type.base_type)) { IsScalar(field.value.type.base_type)) {
code += GenTypeGet(parser, field.value.type, " ", "const ", " *", code += GenTypeGet(parser, field.value.type, " ", "const ", " *",
...@@ -477,7 +476,7 @@ static void GenTable(const Parser &parser, StructDef &struct_def, ...@@ -477,7 +476,7 @@ static void GenTable(const Parser &parser, StructDef &struct_def,
code += WrapInNameSpace(parser, code += WrapInNameSpace(parser,
field.value.type.enum_def->defined_namespace, field.value.type.enum_def->defined_namespace,
GetEnumVal(*field.value.type.enum_def, *ev, GetEnumVal(*field.value.type.enum_def, *ev,
opts)); parser.opts));
} else { } else {
code += GenUnderlyingCast(parser, field, true, field.value.constant); code += GenUnderlyingCast(parser, field, true, field.value.constant);
} }
...@@ -518,7 +517,7 @@ static void GenPadding(const FieldDef &field, ...@@ -518,7 +517,7 @@ static void GenPadding(const FieldDef &field,
// Generate an accessor struct with constructor for a flatbuffers struct. // Generate an accessor struct with constructor for a flatbuffers struct.
static void GenStruct(const Parser &parser, StructDef &struct_def, static void GenStruct(const Parser &parser, StructDef &struct_def,
const GeneratorOptions &opts, std::string *code_ptr) { std::string *code_ptr) {
if (struct_def.generated) return; if (struct_def.generated) return;
std::string &code = *code_ptr; std::string &code = *code_ptr;
...@@ -602,7 +601,7 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -602,7 +601,7 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
? "flatbuffers::EndianScalar(" + field.name + "_)" ? "flatbuffers::EndianScalar(" + field.name + "_)"
: field.name + "_"); : field.name + "_");
code += "; }\n"; code += "; }\n";
if (opts.mutable_buffer) { if (parser.opts.mutable_buffer) {
if (is_scalar) { if (is_scalar) {
code += " void mutate_" + field.name + "("; code += " void mutate_" + field.name + "(";
code += GenTypeBasic(parser, field.value.type, true); code += GenTypeBasic(parser, field.value.type, true);
...@@ -639,15 +638,14 @@ void CloseNestedNameSpaces(Namespace *ns, std::string *code_ptr) { ...@@ -639,15 +638,14 @@ void CloseNestedNameSpaces(Namespace *ns, std::string *code_ptr) {
// Iterate through all definitions we haven't generate code for (enums, structs, // Iterate through all definitions we haven't generate code for (enums, structs,
// and tables) and output them to a single file. // and tables) and output them to a single file.
std::string GenerateCPP(const Parser &parser, std::string GenerateCPP(const Parser &parser,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions &opts) {
using namespace cpp; using namespace cpp;
// Generate code for all the enum declarations. // Generate code for all the enum declarations.
std::string enum_code, enum_code_post; std::string enum_code, enum_code_post;
for (auto it = parser.enums_.vec.begin(); for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) { it != parser.enums_.vec.end(); ++it) {
GenEnum(parser, **it, &enum_code, &enum_code_post, opts); GenEnum(parser, **it, &enum_code, &enum_code_post);
} }
// Generate forward declarations for all structs/tables, since they may // Generate forward declarations for all structs/tables, since they may
...@@ -688,11 +686,11 @@ std::string GenerateCPP(const Parser &parser, ...@@ -688,11 +686,11 @@ std::string GenerateCPP(const Parser &parser,
std::string decl_code; std::string decl_code;
for (auto it = parser.structs_.vec.begin(); for (auto it = parser.structs_.vec.begin();
it != parser.structs_.vec.end(); ++it) { it != parser.structs_.vec.end(); ++it) {
if ((**it).fixed) GenStruct(parser, **it, opts, &decl_code); if ((**it).fixed) GenStruct(parser, **it, &decl_code);
} }
for (auto it = parser.structs_.vec.begin(); for (auto it = parser.structs_.vec.begin();
it != parser.structs_.vec.end(); ++it) { it != parser.structs_.vec.end(); ++it) {
if (!(**it).fixed) GenTable(parser, **it, opts, &decl_code); if (!(**it).fixed) GenTable(parser, **it, &decl_code);
} }
// Only output file-level code if there were any declarations. // Only output file-level code if there were any declarations.
...@@ -725,7 +723,7 @@ std::string GenerateCPP(const Parser &parser, ...@@ -725,7 +723,7 @@ std::string GenerateCPP(const Parser &parser,
code += "#include \"flatbuffers/flatbuffers.h\"\n\n"; code += "#include \"flatbuffers/flatbuffers.h\"\n\n";
if (opts.include_dependence_headers) { if (parser.opts.include_dependence_headers) {
int num_includes = 0; int num_includes = 0;
for (auto it = parser.included_files_.begin(); for (auto it = parser.included_files_.begin();
it != parser.included_files_.end(); ++it) { it != parser.included_files_.end(); ++it) {
...@@ -765,7 +763,7 @@ std::string GenerateCPP(const Parser &parser, ...@@ -765,7 +763,7 @@ std::string GenerateCPP(const Parser &parser,
code += name; code += name;
code += "(const void *buf) { return flatbuffers::GetRoot<"; code += "(const void *buf) { return flatbuffers::GetRoot<";
code += cpp_qualified_name + ">(buf); }\n\n"; code += cpp_qualified_name + ">(buf); }\n\n";
if (opts.mutable_buffer) { if (parser.opts.mutable_buffer) {
code += "inline " + name + " *GetMutable"; code += "inline " + name + " *GetMutable";
code += name; code += name;
code += "(void *buf) { return flatbuffers::GetMutableRoot<"; code += "(void *buf) { return flatbuffers::GetMutableRoot<";
...@@ -806,7 +804,6 @@ std::string GenerateCPP(const Parser &parser, ...@@ -806,7 +804,6 @@ std::string GenerateCPP(const Parser &parser,
if (parser.file_identifier_.length()) if (parser.file_identifier_.length())
code += ", " + name + "Identifier()"; code += ", " + name + "Identifier()";
code += "); }\n\n"; code += "); }\n\n";
} }
CloseNestedNameSpaces(name_space, &code); CloseNestedNameSpaces(name_space, &code);
...@@ -827,17 +824,15 @@ static std::string GeneratedFileName(const std::string &path, ...@@ -827,17 +824,15 @@ static std::string GeneratedFileName(const std::string &path,
bool GenerateCPP(const Parser &parser, bool GenerateCPP(const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions &opts) { auto code = GenerateCPP(parser, file_name);
auto code = GenerateCPP(parser, file_name, opts);
return !code.length() || return !code.length() ||
SaveFile(GeneratedFileName(path, file_name).c_str(), code, false); SaveFile(GeneratedFileName(path, file_name).c_str(), code, false);
} }
std::string CPPMakeRule(const Parser &parser, std::string CPPMakeRule(const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions & /*opts*/) {
std::string filebase = flatbuffers::StripPath( std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(file_name)); flatbuffers::StripExtension(file_name));
std::string make_rule = GeneratedFileName(path, filebase) + ": "; std::string make_rule = GeneratedFileName(path, filebase) + ": ";
......
...@@ -52,8 +52,7 @@ static void GenNameSpace(const Namespace &name_space, std::string *_schema, ...@@ -52,8 +52,7 @@ 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.
std::string GenerateFBS(const Parser &parser, const std::string &file_name, std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
const GeneratorOptions &opts) {
// Proto namespaces may clash with table names, so we have to prefix all: // Proto namespaces may clash with table names, so we have to prefix all:
for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end(); for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end();
++it) { ++it) {
...@@ -65,7 +64,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name, ...@@ -65,7 +64,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name,
std::string schema; std::string schema;
schema += "// Generated from " + file_name + ".proto\n\n"; schema += "// Generated from " + file_name + ".proto\n\n";
if (opts.include_dependence_headers) { if (parser.opts.include_dependence_headers) {
#ifdef FBS_GEN_INCLUDES // TODO: currently all in one file. #ifdef FBS_GEN_INCLUDES // TODO: currently all in one file.
int num_includes = 0; int num_includes = 0;
for (auto it = parser.included_files_.begin(); for (auto it = parser.included_files_.begin();
...@@ -120,10 +119,9 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name, ...@@ -120,10 +119,9 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name,
bool GenerateFBS(const Parser &parser, bool GenerateFBS(const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions &opts) {
return SaveFile((path + file_name + ".fbs").c_str(), return SaveFile((path + file_name + ".fbs").c_str(),
GenerateFBS(parser, file_name, opts), false); GenerateFBS(parser, file_name), false);
} }
} // namespace flatbuffers } // namespace flatbuffers
......
This diff is collapsed.
...@@ -664,8 +664,7 @@ static void GenStructBuilder(const StructDef &struct_def, ...@@ -664,8 +664,7 @@ static void GenStructBuilder(const StructDef &struct_def,
bool GenerateGo(const Parser &parser, bool GenerateGo(const Parser &parser,
const std::string &path, const std::string &path,
const std::string & /*file_name*/, const std::string & /*file_name*/) {
const GeneratorOptions & /*opts*/) {
for (auto it = parser.enums_.vec.begin(); for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) { it != parser.enums_.vec.end(); ++it) {
std::string enumcode; std::string enumcode;
......
...@@ -653,8 +653,7 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -653,8 +653,7 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
// Iterate through all definitions we haven't generate code for (enums, structs, // Iterate through all definitions we haven't generate code for (enums, structs,
// and tables) and output them to a single file. // and tables) and output them to a single file.
std::string GenerateJS(const Parser &parser, std::string GenerateJS(const Parser &parser) {
const GeneratorOptions &opts) {
using namespace js; using namespace js;
// Generate code for all the enum declarations. // Generate code for all the enum declarations.
...@@ -684,7 +683,7 @@ std::string GenerateJS(const Parser &parser, ...@@ -684,7 +683,7 @@ std::string GenerateJS(const Parser &parser,
code += enum_code; code += enum_code;
code += decl_code; code += decl_code;
if (!exports_code.empty() && !opts.skip_js_exports) { if (!exports_code.empty() && !parser.opts.skip_js_exports) {
code += "// Exports for Node.js and RequireJS\n"; code += "// Exports for Node.js and RequireJS\n";
code += exports_code; code += exports_code;
} }
...@@ -702,17 +701,15 @@ static std::string GeneratedFileName(const std::string &path, ...@@ -702,17 +701,15 @@ static std::string GeneratedFileName(const std::string &path,
bool GenerateJS(const Parser &parser, bool GenerateJS(const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions &opts) { auto code = GenerateJS(parser);
auto code = GenerateJS(parser, opts);
return !code.length() || return !code.length() ||
SaveFile(GeneratedFileName(path, file_name).c_str(), code, false); SaveFile(GeneratedFileName(path, file_name).c_str(), code, false);
} }
std::string JSMakeRule(const Parser &parser, std::string JSMakeRule(const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions & /*opts*/) {
std::string filebase = flatbuffers::StripPath( std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(file_name)); flatbuffers::StripExtension(file_name));
std::string make_rule = GeneratedFileName(path, filebase) + ": "; std::string make_rule = GeneratedFileName(path, filebase) + ": ";
......
...@@ -140,8 +140,8 @@ namespace php { ...@@ -140,8 +140,8 @@ namespace php {
code += Indent + " * @return " + struct_def.name + "\n"; code += Indent + " * @return " + struct_def.name + "\n";
code += Indent + " **/\n"; code += Indent + " **/\n";
code += Indent + "public function init($_i, ByteBuffer $_bb)\n"; code += Indent + "public function init($_i, ByteBuffer $_bb)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$this->bb_pos = $_i;\n"; code += Indent + Indent + "$this->bb_pos = $_i;\n";
code += Indent + Indent + "$this->bb = $_bb;\n"; code += Indent + Indent + "$this->bb = $_bb;\n";
code += Indent + Indent + "return $this;\n"; code += Indent + Indent + "return $this;\n";
code += Indent + "}\n\n"; code += Indent + "}\n\n";
...@@ -241,7 +241,7 @@ namespace php { ...@@ -241,7 +241,7 @@ namespace php {
code += Indent + "public function get"; code += Indent + "public function get";
code += MakeCamel(field.name); code += MakeCamel(field.name);
code += "()\n"; code += "()\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$obj = new "; code += Indent + Indent + "$obj = new ";
code += MakeCamel(GenTypeGet(field.value.type)) + "();\n"; code += MakeCamel(GenTypeGet(field.value.type)) + "();\n";
code += Indent + Indent + code += Indent + Indent +
...@@ -251,8 +251,6 @@ namespace php { ...@@ -251,8 +251,6 @@ namespace php {
code += Indent + Indent; code += Indent + Indent;
code += "return $o != 0 ? $obj->init($o + $this->bb_pos, $this->bb) : "; code += "return $o != 0 ? $obj->init($o + $this->bb_pos, $this->bb) : ";
code += GenDefaultValue(field.value) + ";\n"; code += GenDefaultValue(field.value) + ";\n";
code += Indent + "}\n\n"; code += Indent + "}\n\n";
} }
...@@ -263,7 +261,7 @@ namespace php { ...@@ -263,7 +261,7 @@ namespace php {
code += Indent + "public function get"; code += Indent + "public function get";
code += MakeCamel(field.name); code += MakeCamel(field.name);
code += "()\n"; code += "()\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + code += Indent + Indent +
"$o = $this->__offset(" + "$o = $this->__offset(" +
NumToString(field.value.offset) + NumToString(field.value.offset) +
...@@ -307,7 +305,7 @@ namespace php { ...@@ -307,7 +305,7 @@ namespace php {
code += Indent + "public function get"; code += Indent + "public function get";
code += MakeCamel(field.name); code += MakeCamel(field.name);
code += "($j)\n"; code += "($j)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + code += Indent + Indent +
"$o = $this->__offset(" + "$o = $this->__offset(" +
NumToString(field.value.offset) + NumToString(field.value.offset) +
...@@ -371,7 +369,7 @@ namespace php { ...@@ -371,7 +369,7 @@ namespace php {
code += Indent + "public function get"; code += Indent + "public function get";
code += MakeCamel(field.name); code += MakeCamel(field.name);
code += "($j)\n"; code += "($j)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + code += Indent + Indent +
"$o = $this->__offset(" + "$o = $this->__offset(" +
NumToString(field.value.offset) + NumToString(field.value.offset) +
...@@ -456,7 +454,7 @@ namespace php { ...@@ -456,7 +454,7 @@ namespace php {
code += Indent + " */\n"; code += Indent + " */\n";
code += Indent + "public static function start" + struct_def.name; code += Indent + "public static function start" + struct_def.name;
code += "(FlatBufferBuilder $builder)\n"; code += "(FlatBufferBuilder $builder)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$builder->StartObject("; code += Indent + Indent + "$builder->StartObject(";
code += NumToString(struct_def.fields.vec.size()); code += NumToString(struct_def.fields.vec.size());
code += ");\n"; code += ");\n";
...@@ -528,7 +526,7 @@ namespace php { ...@@ -528,7 +526,7 @@ namespace php {
code += "(FlatBufferBuilder $builder, "; code += "(FlatBufferBuilder $builder, ";
code += "$" + MakeCamel(field.name, false); code += "$" + MakeCamel(field.name, false);
code += ")\n"; code += ")\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$builder->add"; code += Indent + Indent + "$builder->add";
code += GenMethod(field) + "X("; code += GenMethod(field) + "X(";
code += NumToString(offset) + ", "; code += NumToString(offset) + ", ";
...@@ -562,7 +560,7 @@ namespace php { ...@@ -562,7 +560,7 @@ namespace php {
code += Indent + "public static function create"; code += Indent + "public static function create";
code += MakeCamel(field.name); code += MakeCamel(field.name);
code += "Vector(FlatBufferBuilder $builder, array $data)\n"; code += "Vector(FlatBufferBuilder $builder, array $data)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$builder->startVector("; code += Indent + Indent + "$builder->startVector(";
code += NumToString(elem_size); code += NumToString(elem_size);
code += ", count($data), " + NumToString(alignment); code += ", count($data), " + NumToString(alignment);
...@@ -591,7 +589,7 @@ namespace php { ...@@ -591,7 +589,7 @@ namespace php {
code += Indent + "public static function start"; code += Indent + "public static function start";
code += MakeCamel(field.name); code += MakeCamel(field.name);
code += "Vector(FlatBufferBuilder $builder, $numElems)\n"; code += "Vector(FlatBufferBuilder $builder, $numElems)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$builder->startVector("; code += Indent + Indent + "$builder->startVector(";
code += NumToString(elem_size); code += NumToString(elem_size);
code += ", $numElems, " + NumToString(alignment); code += ", $numElems, " + NumToString(alignment);
...@@ -612,7 +610,7 @@ namespace php { ...@@ -612,7 +610,7 @@ namespace php {
code += Indent + " */\n"; code += Indent + " */\n";
code += Indent + "public static function end" + struct_def.name; code += Indent + "public static function end" + struct_def.name;
code += "(FlatBufferBuilder $builder)\n"; code += "(FlatBufferBuilder $builder)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$o = $builder->endObject();\n"; code += Indent + Indent + "$o = $builder->endObject();\n";
...@@ -644,7 +642,7 @@ namespace php { ...@@ -644,7 +642,7 @@ namespace php {
} }
} }
// Generate a struct field, conditioned on its child type(s). // Generate a struct field, conditioned on its child type(s).
static void GenStructAccessor(const StructDef &struct_def, static void GenStructAccessor(const StructDef &struct_def,
const FieldDef &field, const FieldDef &field,
std::string *code_ptr) { std::string *code_ptr) {
...@@ -707,7 +705,7 @@ namespace php { ...@@ -707,7 +705,7 @@ namespace php {
code += Indent + "public static function add"; code += Indent + "public static function add";
code += MakeCamel(field.name); code += MakeCamel(field.name);
code += "(FlatBufferBuilder $builder, $offset)\n"; code += "(FlatBufferBuilder $builder, $offset)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "$builder->addOffsetX("; code += Indent + Indent + "$builder->addOffsetX(";
code += NumToString(offset) + ", $offset, 0);\n"; code += NumToString(offset) + ", $offset, 0);\n";
code += Indent + "}\n\n"; code += Indent + "}\n\n";
...@@ -815,7 +813,7 @@ namespace php { ...@@ -815,7 +813,7 @@ namespace php {
code += Indent + ");\n\n"; code += Indent + ");\n\n";
code += Indent + "public static function Name($e)\n"; code += Indent + "public static function Name($e)\n";
code += Indent + "{\n"; code += Indent + "{\n";
code += Indent + Indent + "if (!isset(self::$names[$e])) {\n"; code += Indent + Indent + "if (!isset(self::$names[$e])) {\n";
code += Indent + Indent + Indent + "throw new \\Exception();\n"; code += Indent + Indent + Indent + "throw new \\Exception();\n";
code += Indent + Indent + "}\n"; code += Indent + Indent + "}\n";
...@@ -943,7 +941,7 @@ namespace php { ...@@ -943,7 +941,7 @@ namespace php {
code += "(FlatBufferBuilder $builder"; code += "(FlatBufferBuilder $builder";
StructBuilderArgs(struct_def, "", code_ptr); StructBuilderArgs(struct_def, "", code_ptr);
code += ")\n"; code += ")\n";
code += Indent + "{\n"; code += Indent + "{\n";
StructBuilderBody(struct_def, "", code_ptr); StructBuilderBody(struct_def, "", code_ptr);
...@@ -955,8 +953,7 @@ namespace php { ...@@ -955,8 +953,7 @@ namespace php {
bool GeneratePhp(const Parser &parser, bool GeneratePhp(const Parser &parser,
const std::string &path, const std::string &path,
const std::string & /*file_name*/, const std::string & /*file_name*/) {
const GeneratorOptions & /*opts*/) {
for (auto it = parser.enums_.vec.begin(); for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) { it != parser.enums_.vec.end(); ++it) {
std::string enumcode; std::string enumcode;
......
...@@ -638,8 +638,7 @@ static void GenStructBuilder(const StructDef &struct_def, ...@@ -638,8 +638,7 @@ static void GenStructBuilder(const StructDef &struct_def,
bool GeneratePython(const Parser &parser, bool GeneratePython(const Parser &parser,
const std::string &path, const std::string &path,
const std::string & /*file_name*/, const std::string & /*file_name*/) {
const GeneratorOptions & /*opts*/) {
for (auto it = parser.enums_.vec.begin(); for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) { it != parser.enums_.vec.end(); ++it) {
std::string enumcode; std::string enumcode;
......
...@@ -23,21 +23,21 @@ ...@@ -23,21 +23,21 @@
namespace flatbuffers { namespace flatbuffers {
static void GenStruct(const StructDef &struct_def, const Table *table, static void GenStruct(const StructDef &struct_def, const Table *table,
int indent, const GeneratorOptions &opts, int indent, const IDLOptions &opts,
std::string *_text); std::string *_text);
// If indentation is less than 0, that indicates we don't want any newlines // If indentation is less than 0, that indicates we don't want any newlines
// either. // either.
const char *NewLine(const GeneratorOptions &opts) { const char *NewLine(const IDLOptions &opts) {
return opts.indent_step >= 0 ? "\n" : ""; return opts.indent_step >= 0 ? "\n" : "";
} }
int Indent(const GeneratorOptions &opts) { int Indent(const IDLOptions &opts) {
return std::max(opts.indent_step, 0); return std::max(opts.indent_step, 0);
} }
// Output an identifier with or without quotes depending on strictness. // Output an identifier with or without quotes depending on strictness.
void OutputIdentifier(const std::string &name, const GeneratorOptions &opts, void OutputIdentifier(const std::string &name, const IDLOptions &opts,
std::string *_text) { std::string *_text) {
std::string &text = *_text; std::string &text = *_text;
if (opts.strict_json) text += "\""; if (opts.strict_json) text += "\"";
...@@ -50,7 +50,7 @@ void OutputIdentifier(const std::string &name, const GeneratorOptions &opts, ...@@ -50,7 +50,7 @@ void OutputIdentifier(const std::string &name, const GeneratorOptions &opts,
// The general case for scalars: // The general case for scalars:
template<typename T> void Print(T val, Type type, int /*indent*/, template<typename T> void Print(T val, Type type, int /*indent*/,
StructDef * /*union_sd*/, StructDef * /*union_sd*/,
const GeneratorOptions &opts, const IDLOptions &opts,
std::string *_text) { std::string *_text) {
std::string &text = *_text; std::string &text = *_text;
if (type.enum_def && opts.output_enum_identifiers) { if (type.enum_def && opts.output_enum_identifiers) {
...@@ -70,7 +70,7 @@ template<typename T> void Print(T val, Type type, int /*indent*/, ...@@ -70,7 +70,7 @@ template<typename T> void Print(T val, Type type, int /*indent*/,
// Print a vector a sequence of JSON values, comma separated, wrapped in "[]". // Print a vector a sequence of JSON values, comma separated, wrapped in "[]".
template<typename T> void PrintVector(const Vector<T> &v, Type type, template<typename T> void PrintVector(const Vector<T> &v, Type type,
int indent, const GeneratorOptions &opts, int indent, const IDLOptions &opts,
std::string *_text) { std::string *_text) {
std::string &text = *_text; std::string &text = *_text;
text += "["; text += "[";
...@@ -136,7 +136,7 @@ static void EscapeString(const String &s, std::string *_text) { ...@@ -136,7 +136,7 @@ static void EscapeString(const String &s, std::string *_text) {
template<> void Print<const void *>(const void *val, template<> void Print<const void *>(const void *val,
Type type, int indent, Type type, int indent,
StructDef *union_sd, StructDef *union_sd,
const GeneratorOptions &opts, const IDLOptions &opts,
std::string *_text) { std::string *_text) {
switch (type.base_type) { switch (type.base_type) {
case BASE_TYPE_UNION: case BASE_TYPE_UNION:
...@@ -181,7 +181,7 @@ template<> void Print<const void *>(const void *val, ...@@ -181,7 +181,7 @@ template<> void Print<const void *>(const void *val,
// Generate text for a scalar field. // Generate text for a scalar field.
template<typename T> static void GenField(const FieldDef &fd, template<typename T> static void GenField(const FieldDef &fd,
const Table *table, bool fixed, const Table *table, bool fixed,
const GeneratorOptions &opts, const IDLOptions &opts,
int indent, int indent,
std::string *_text) { std::string *_text) {
Print(fixed ? Print(fixed ?
...@@ -193,7 +193,7 @@ template<typename T> static void GenField(const FieldDef &fd, ...@@ -193,7 +193,7 @@ template<typename T> static void GenField(const FieldDef &fd,
// Generate text for non-scalar field. // Generate text for non-scalar field.
static void GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed, static void GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
int indent, StructDef *union_sd, int indent, StructDef *union_sd,
const GeneratorOptions &opts, std::string *_text) { const IDLOptions &opts, std::string *_text) {
const void *val = nullptr; const void *val = nullptr;
if (fixed) { if (fixed) {
// The only non-scalar fields in structs are structs. // The only non-scalar fields in structs are structs.
...@@ -211,7 +211,7 @@ static void GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed, ...@@ -211,7 +211,7 @@ static void GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
// Generate text for a struct or table, values separated by commas, indented, // Generate text for a struct or table, values separated by commas, indented,
// and bracketed by "{}" // and bracketed by "{}"
static void GenStruct(const StructDef &struct_def, const Table *table, static void GenStruct(const StructDef &struct_def, const Table *table,
int indent, const GeneratorOptions &opts, int indent, const IDLOptions &opts,
std::string *_text) { std::string *_text) {
std::string &text = *_text; std::string &text = *_text;
text += "{"; text += "{";
...@@ -273,16 +273,16 @@ static void GenStruct(const StructDef &struct_def, const Table *table, ...@@ -273,16 +273,16 @@ static void GenStruct(const StructDef &struct_def, const Table *table,
// Generate a text representation of a flatbuffer in JSON format. // Generate a text representation of a flatbuffer in JSON format.
void GenerateText(const Parser &parser, const void *flatbuffer, void GenerateText(const Parser &parser, const void *flatbuffer,
const GeneratorOptions &opts, std::string *_text) { std::string *_text) {
std::string &text = *_text; std::string &text = *_text;
assert(parser.root_struct_def_); // call SetRootType() assert(parser.root_struct_def_); // call SetRootType()
text.reserve(1024); // Reduce amount of inevitable reallocs. text.reserve(1024); // Reduce amount of inevitable reallocs.
GenStruct(*parser.root_struct_def_, GenStruct(*parser.root_struct_def_,
GetRoot<Table>(flatbuffer), GetRoot<Table>(flatbuffer),
0, 0,
opts, parser.opts,
_text); _text);
text += NewLine(opts); text += NewLine(parser.opts);
} }
std::string TextFileName(const std::string &path, std::string TextFileName(const std::string &path,
...@@ -292,12 +292,10 @@ std::string TextFileName(const std::string &path, ...@@ -292,12 +292,10 @@ std::string TextFileName(const std::string &path,
bool GenerateTextFile(const Parser &parser, bool GenerateTextFile(const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions &opts) {
if (!parser.builder_.GetSize() || !parser.root_struct_def_) return true; if (!parser.builder_.GetSize() || !parser.root_struct_def_) return true;
std::string text; std::string text;
GenerateText(parser, parser.builder_.GetBufferPointer(), opts, GenerateText(parser, parser.builder_.GetBufferPointer(), &text);
&text);
return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(), return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(),
text, text,
false); false);
...@@ -305,8 +303,7 @@ bool GenerateTextFile(const Parser &parser, ...@@ -305,8 +303,7 @@ bool GenerateTextFile(const Parser &parser,
std::string TextMakeRule(const Parser &parser, std::string TextMakeRule(const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name, const std::string &file_name) {
const GeneratorOptions & /*opts*/) {
if (!parser.builder_.GetSize() || !parser.root_struct_def_) return ""; if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
std::string filebase = flatbuffers::StripPath( std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(file_name)); flatbuffers::StripExtension(file_name));
......
...@@ -589,10 +589,10 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def, std::string *value) { ...@@ -589,10 +589,10 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def, std::string *value) {
Expect('{'); Expect('{');
size_t fieldn = 0; size_t fieldn = 0;
for (;;) { for (;;) {
if ((!strict_json_ || !fieldn) && IsNext('}')) break; if ((!opts.strict_json || !fieldn) && IsNext('}')) break;
std::string name = attribute_; std::string name = attribute_;
if (!IsNext(kTokenStringConstant)) if (!IsNext(kTokenStringConstant))
Expect(strict_json_ ? kTokenStringConstant : kTokenIdentifier); Expect(opts.strict_json ? kTokenStringConstant : kTokenIdentifier);
auto field = struct_def.fields.Lookup(name); auto field = struct_def.fields.Lookup(name);
if (!field) Error("unknown field: " + name); if (!field) Error("unknown field: " + name);
Expect(':'); Expect(':');
...@@ -685,7 +685,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def, std::string *value) { ...@@ -685,7 +685,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def, std::string *value) {
uoffset_t Parser::ParseVector(const Type &type) { uoffset_t Parser::ParseVector(const Type &type) {
int count = 0; int count = 0;
for (;;) { for (;;) {
if ((!strict_json_ || !count) && IsNext(']')) break; if ((!opts.strict_json || !count) && IsNext(']')) break;
Value val; Value val;
val.type = type; val.type = type;
ParseAnyValue(val, nullptr, 0); ParseAnyValue(val, nullptr, 0);
...@@ -903,7 +903,7 @@ EnumDef &Parser::ParseEnum(bool is_union) { ...@@ -903,7 +903,7 @@ EnumDef &Parser::ParseEnum(bool is_union) {
enum_def.underlying_type.base_type = BASE_TYPE_UTYPE; enum_def.underlying_type.base_type = BASE_TYPE_UTYPE;
enum_def.underlying_type.enum_def = &enum_def; enum_def.underlying_type.enum_def = &enum_def;
} else { } else {
if (proto_mode_) { if (opts.proto_mode) {
enum_def.underlying_type.base_type = BASE_TYPE_INT; enum_def.underlying_type.base_type = BASE_TYPE_INT;
} else { } else {
// Give specialized error message, since this type spec used to // Give specialized error message, since this type spec used to
...@@ -922,7 +922,7 @@ EnumDef &Parser::ParseEnum(bool is_union) { ...@@ -922,7 +922,7 @@ EnumDef &Parser::ParseEnum(bool is_union) {
Expect('{'); Expect('{');
if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0)); if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0));
do { do {
if (proto_mode_ && attribute_ == "option") { if (opts.proto_mode && attribute_ == "option") {
ParseProtoOption(); ParseProtoOption();
} else { } else {
auto value_name = attribute_; auto value_name = attribute_;
...@@ -944,17 +944,17 @@ EnumDef &Parser::ParseEnum(bool is_union) { ...@@ -944,17 +944,17 @@ EnumDef &Parser::ParseEnum(bool is_union) {
if (IsNext('=')) { if (IsNext('=')) {
ev.value = atoi(attribute_.c_str()); ev.value = atoi(attribute_.c_str());
Expect(kTokenIntegerConstant); Expect(kTokenIntegerConstant);
if (!proto_mode_ && prevsize && if (!opts.proto_mode && prevsize &&
enum_def.vals.vec[prevsize - 1]->value >= ev.value) enum_def.vals.vec[prevsize - 1]->value >= ev.value)
Error("enum values must be specified in ascending order"); Error("enum values must be specified in ascending order");
} }
if (proto_mode_ && IsNext('[')) { if (opts.proto_mode && IsNext('[')) {
// ignore attributes on enums. // ignore attributes on enums.
while (token_ != ']') Next(); while (token_ != ']') Next();
Next(); Next();
} }
} }
} while (IsNext(proto_mode_ ? ';' : ',') && token_ != '}'); } while (IsNext(opts.proto_mode ? ';' : ',') && token_ != '}');
Expect('}'); Expect('}');
if (enum_def.attributes.Lookup("bit_flags")) { if (enum_def.attributes.Lookup("bit_flags")) {
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end(); for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
...@@ -1372,15 +1372,15 @@ bool Parser::Parse(const char *source, const char **include_paths, ...@@ -1372,15 +1372,15 @@ bool Parser::Parse(const char *source, const char **include_paths,
// Includes must come before type declarations: // Includes must come before type declarations:
for (;;) { for (;;) {
// Parse pre-include proto statements if any: // Parse pre-include proto statements if any:
if (proto_mode_ && if (opts.proto_mode &&
(attribute_ == "option" || attribute_ == "syntax" || (attribute_ == "option" || attribute_ == "syntax" ||
attribute_ == "package")) { attribute_ == "package")) {
ParseProtoDecl(); ParseProtoDecl();
} else if (IsNext(kTokenInclude) || } else if (IsNext(kTokenInclude) ||
(proto_mode_ && (opts.proto_mode &&
attribute_ == "import" && attribute_ == "import" &&
IsNext(kTokenIdentifier))) { IsNext(kTokenIdentifier))) {
if (proto_mode_ && attribute_ == "public") Next(); if (opts.proto_mode && attribute_ == "public") Next();
auto name = attribute_; auto name = attribute_;
Expect(kTokenStringConstant); Expect(kTokenStringConstant);
// Look for the file in include_paths. // Look for the file in include_paths.
...@@ -1403,8 +1403,8 @@ bool Parser::Parse(const char *source, const char **include_paths, ...@@ -1403,8 +1403,8 @@ bool Parser::Parse(const char *source, const char **include_paths,
// Any errors, we're done. // Any errors, we're done.
return false; return false;
} }
// We do not want to output code for any included files: // We generally do not want to output code for any included files:
MarkGenerated(); if (!opts.generate_all) MarkGenerated();
// This is the easiest way to continue this file after an include: // This is the easiest way to continue this file after an include:
// instead of saving and restoring all the state, we simply start the // instead of saving and restoring all the state, we simply start the
// file anew. This will cause it to encounter the same include statement // file anew. This will cause it to encounter the same include statement
...@@ -1421,7 +1421,7 @@ bool Parser::Parse(const char *source, const char **include_paths, ...@@ -1421,7 +1421,7 @@ bool Parser::Parse(const char *source, const char **include_paths,
} }
// Now parse all other kinds of declarations: // Now parse all other kinds of declarations:
while (token_ != kTokenEof) { while (token_ != kTokenEof) {
if (proto_mode_) { if (opts.proto_mode) {
ParseProtoDecl(); ParseProtoDecl();
} else if (token_ == kTokenNameSpace) { } else if (token_ == kTokenNameSpace) {
ParseNamespace(); ParseNamespace();
......
...@@ -281,8 +281,7 @@ void ParseAndGenerateTextTest() { ...@@ -281,8 +281,7 @@ void ParseAndGenerateTextTest() {
// to ensure it is correct, we now generate text back from the binary, // to ensure it is correct, we now generate text back from the binary,
// and compare the two: // and compare the two:
std::string jsongen; std::string jsongen;
flatbuffers::GeneratorOptions opts; GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
GenerateText(parser, parser.builder_.GetBufferPointer(), opts, &jsongen);
if (jsongen != jsonfile) { if (jsongen != jsonfile) {
printf("%s----------------\n%s", jsongen.c_str(), jsonfile.c_str()); printf("%s----------------\n%s", jsongen.c_str(), jsonfile.c_str());
...@@ -426,15 +425,17 @@ void ParseProtoTest() { ...@@ -426,15 +425,17 @@ void ParseProtoTest() {
TEST_EQ(flatbuffers::LoadFile( TEST_EQ(flatbuffers::LoadFile(
"tests/prototest/test.golden", false, &goldenfile), true); "tests/prototest/test.golden", false, &goldenfile), true);
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
opts.proto_mode = true;
// Parse proto. // Parse proto.
flatbuffers::Parser parser(false, true); flatbuffers::Parser parser(opts);
const char *include_directories[] = { "tests/prototest", nullptr }; const char *include_directories[] = { "tests/prototest", nullptr };
TEST_EQ(parser.Parse(protofile.c_str(), include_directories), true); TEST_EQ(parser.Parse(protofile.c_str(), include_directories), true);
// Generate fbs. // Generate fbs.
flatbuffers::GeneratorOptions opts; auto fbs = flatbuffers::GenerateFBS(parser, "test");
opts.include_dependence_headers = false;
auto fbs = flatbuffers::GenerateFBS(parser, "test", opts);
// Ensure generated file is parsable. // Ensure generated file is parsable.
flatbuffers::Parser parser2; flatbuffers::Parser parser2;
...@@ -677,9 +678,8 @@ void FuzzTest2() { ...@@ -677,9 +678,8 @@ void FuzzTest2() {
TEST_EQ(parser.Parse(json.c_str()), true); TEST_EQ(parser.Parse(json.c_str()), true);
std::string jsongen; std::string jsongen;
flatbuffers::GeneratorOptions opts; parser.opts.indent_step = 0;
opts.indent_step = 0; GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
GenerateText(parser, parser.builder_.GetBufferPointer(), opts, &jsongen);
if (jsongen != json) { if (jsongen != json) {
// These strings are larger than a megabyte, so we show the bytes around // These strings are larger than a megabyte, so we show the bytes around
...@@ -706,7 +706,9 @@ void FuzzTest2() { ...@@ -706,7 +706,9 @@ void FuzzTest2() {
// Test that parser errors are actually generated. // Test that parser errors are actually generated.
void TestError(const char *src, const char *error_substr, void TestError(const char *src, const char *error_substr,
bool strict_json = false) { bool strict_json = false) {
flatbuffers::Parser parser(strict_json); flatbuffers::IDLOptions opts;
opts.strict_json = strict_json;
flatbuffers::Parser parser(opts);
TEST_EQ(parser.Parse(src), false); // Must signal error TEST_EQ(parser.Parse(src), false); // Must signal error
// Must be the error we're expecting // Must be the error we're expecting
TEST_NOTNULL(strstr(parser.error_.c_str(), error_substr)); TEST_NOTNULL(strstr(parser.error_.c_str(), error_substr));
...@@ -794,9 +796,8 @@ void UnicodeTest() { ...@@ -794,9 +796,8 @@ void UnicodeTest() {
"{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC" "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
"\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\" }"), true); "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\" }"), true);
std::string jsongen; std::string jsongen;
flatbuffers::GeneratorOptions opts; parser.opts.indent_step = -1;
opts.indent_step = -1; GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
GenerateText(parser, parser.builder_.GetBufferPointer(), opts, &jsongen);
TEST_EQ(jsongen == "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC" TEST_EQ(jsongen == "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
"\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\"}", true); "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\"}", true);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment