flatc.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. * Copyright 2014 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "flatbuffers/flatbuffers.h"
  17. #include "flatbuffers/idl.h"
  18. #include "flatbuffers/util.h"
  19. static void Error(const char *err, const char *obj = nullptr,
  20. bool usage = false, bool show_exe_name = true);
  21. namespace flatbuffers {
  22. bool GenerateBinary(const Parser &parser,
  23. const std::string &path,
  24. const std::string &file_name,
  25. const GeneratorOptions & /*opts*/) {
  26. auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
  27. return !parser.builder_.GetSize() ||
  28. flatbuffers::SaveFile(
  29. (path + file_name + "." + ext).c_str(),
  30. reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
  31. parser.builder_.GetSize(),
  32. true);
  33. }
  34. bool GenerateTextFile(const Parser &parser,
  35. const std::string &path,
  36. const std::string &file_name,
  37. const GeneratorOptions &opts) {
  38. if (!parser.builder_.GetSize()) return true;
  39. if (!parser.root_struct_def) Error("root_type not set");
  40. std::string text;
  41. GenerateText(parser, parser.builder_.GetBufferPointer(), opts,
  42. &text);
  43. return flatbuffers::SaveFile((path + file_name + ".json").c_str(),
  44. text,
  45. false);
  46. }
  47. }
  48. // This struct allows us to create a table of all possible output generators
  49. // for the various programming languages and formats we support.
  50. struct Generator {
  51. bool (*generate)(const flatbuffers::Parser &parser,
  52. const std::string &path,
  53. const std::string &file_name,
  54. const flatbuffers::GeneratorOptions &opts);
  55. const char *opt;
  56. const char *name;
  57. flatbuffers::GeneratorOptions::Language lang;
  58. const char *help;
  59. };
  60. const Generator generators[] = {
  61. { flatbuffers::GenerateBinary, "-b", "binary",
  62. flatbuffers::GeneratorOptions::kMAX,
  63. "Generate wire format binaries for any data definitions" },
  64. { flatbuffers::GenerateTextFile, "-t", "text",
  65. flatbuffers::GeneratorOptions::kMAX,
  66. "Generate text output for any data definitions" },
  67. { flatbuffers::GenerateCPP, "-c", "C++",
  68. flatbuffers::GeneratorOptions::kMAX,
  69. "Generate C++ headers for tables/structs" },
  70. { flatbuffers::GenerateGo, "-g", "Go",
  71. flatbuffers::GeneratorOptions::kMAX,
  72. "Generate Go files for tables/structs" },
  73. { flatbuffers::GenerateGeneral, "-j", "Java",
  74. flatbuffers::GeneratorOptions::kJava,
  75. "Generate Java classes for tables/structs" },
  76. { flatbuffers::GenerateGeneral, "-n", "C#",
  77. flatbuffers::GeneratorOptions::kCSharp,
  78. "Generate C# classes for tables/structs" }
  79. };
  80. const char *program_name = NULL;
  81. static void Error(const char *err, const char *obj, bool usage,
  82. bool show_exe_name) {
  83. if (show_exe_name) printf("%s: ", program_name);
  84. printf("%s", err);
  85. if (obj) printf(": %s", obj);
  86. printf("\n");
  87. if (usage) {
  88. printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
  89. for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
  90. printf(" %s %s.\n", generators[i].opt, generators[i].help);
  91. printf(
  92. " -o PATH Prefix PATH to all generated files.\n"
  93. " -I PATH Search for includes in the specified path.\n"
  94. " --strict-json Strict JSON: add quotes to field names.\n"
  95. " --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
  96. " --gen-includes Generate include statements for included schemas the\n"
  97. " generated file depends on (C++).\n"
  98. " --proto Input is a .proto, translate to .fbs.\n"
  99. "FILEs may depend on declarations in earlier files.\n"
  100. "FILEs after the -- must be binary flatbuffer format files.\n"
  101. "Output files are named using the base file name of the input,"
  102. "and written to the current directory or the path given by -o.\n"
  103. "example: %s -c -b schema1.fbs schema2.fbs data.json\n",
  104. program_name);
  105. }
  106. exit(1);
  107. }
  108. int main(int argc, const char *argv[]) {
  109. program_name = argv[0];
  110. flatbuffers::GeneratorOptions opts;
  111. std::string output_path;
  112. const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
  113. bool generator_enabled[num_generators] = { false };
  114. bool any_generator = false;
  115. bool proto_mode = false;
  116. std::vector<std::string> filenames;
  117. std::vector<const char *> include_directories;
  118. size_t binary_files_from = std::numeric_limits<size_t>::max();
  119. for (int i = 1; i < argc; i++) {
  120. const char *arg = argv[i];
  121. if (arg[0] == '-') {
  122. if (filenames.size() && arg[1] != '-')
  123. Error("invalid option location", arg, true);
  124. std::string opt = arg;
  125. if (opt == "-o") {
  126. if (++i >= argc) Error("missing path following", arg, true);
  127. output_path = flatbuffers::ConCatPathFileName(argv[i], "");
  128. } else if(opt == "-I") {
  129. if (++i >= argc) Error("missing path following", arg, true);
  130. include_directories.push_back(argv[i]);
  131. } else if(opt == "--strict-json") {
  132. opts.strict_json = true;
  133. } else if(opt == "--no-prefix") {
  134. opts.prefixed_enums = false;
  135. } else if(opt == "--gen-includes") {
  136. opts.include_dependence_headers = true;
  137. } else if(opt == "--") { // Separator between text and binary inputs.
  138. binary_files_from = filenames.size();
  139. } else if(opt == "--proto") {
  140. proto_mode = true;
  141. any_generator = true;
  142. } else {
  143. for (size_t j = 0; j < num_generators; ++j) {
  144. if(opt == generators[j].opt) {
  145. generator_enabled[j] = true;
  146. any_generator = true;
  147. goto found;
  148. }
  149. }
  150. Error("unknown commandline argument", arg, true);
  151. found:;
  152. }
  153. } else {
  154. filenames.push_back(argv[i]);
  155. }
  156. }
  157. if (!filenames.size()) Error("missing input files", nullptr, true);
  158. if (!any_generator)
  159. Error("no options: no output files generated.",
  160. "specify one of -c -g -j -t -b etc.", true);
  161. // Now process the files:
  162. flatbuffers::Parser parser(proto_mode);
  163. for (auto file_it = filenames.begin();
  164. file_it != filenames.end();
  165. ++file_it) {
  166. std::string contents;
  167. if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
  168. Error("unable to load file", file_it->c_str());
  169. bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
  170. binary_files_from;
  171. if (is_binary) {
  172. parser.builder_.Clear();
  173. parser.builder_.PushBytes(
  174. reinterpret_cast<const uint8_t *>(contents.c_str()),
  175. contents.length());
  176. } else {
  177. auto local_include_directory = flatbuffers::StripFileName(*file_it);
  178. include_directories.push_back(local_include_directory.c_str());
  179. include_directories.push_back(nullptr);
  180. if (!parser.Parse(contents.c_str(), &include_directories[0],
  181. file_it->c_str()))
  182. Error(parser.error_.c_str(), nullptr, false, false);
  183. include_directories.pop_back();
  184. include_directories.pop_back();
  185. }
  186. std::string filebase = flatbuffers::StripPath(
  187. flatbuffers::StripExtension(*file_it));
  188. for (size_t i = 0; i < num_generators; ++i) {
  189. if (generator_enabled[i]) {
  190. flatbuffers::EnsureDirExists(output_path);
  191. opts.lang = generators[i].lang;
  192. if (!generators[i].generate(parser, output_path, filebase, opts)) {
  193. Error((std::string("Unable to generate ") +
  194. generators[i].name +
  195. " for " +
  196. filebase).c_str());
  197. }
  198. }
  199. }
  200. if (proto_mode) GenerateFBS(parser, output_path, filebase, opts);
  201. // We do not want to generate code for the definitions in this file
  202. // in any files coming up next.
  203. parser.MarkGenerated();
  204. }
  205. return 0;
  206. }