• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #include "flatbuffers/flatc.h"
18 
19 #include <algorithm>
20 #include <limits>
21 #include <list>
22 #include <memory>
23 #include <sstream>
24 
25 #include "annotated_binary_text_gen.h"
26 #include "binary_annotator.h"
27 #include "flatbuffers/code_generator.h"
28 #include "flatbuffers/idl.h"
29 #include "flatbuffers/util.h"
30 
31 namespace flatbuffers {
32 
FLATC_VERSION()33 static const char *FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
34 
ParseFile(flatbuffers::Parser & parser,const std::string & filename,const std::string & contents,const std::vector<const char * > & include_directories) const35 void FlatCompiler::ParseFile(
36     flatbuffers::Parser &parser, const std::string &filename,
37     const std::string &contents,
38     const std::vector<const char *> &include_directories) const {
39   auto local_include_directory = flatbuffers::StripFileName(filename);
40 
41   std::vector<const char *> inc_directories;
42   inc_directories.insert(inc_directories.end(), include_directories.begin(),
43                          include_directories.end());
44   inc_directories.push_back(local_include_directory.c_str());
45   inc_directories.push_back(nullptr);
46 
47   if (!parser.Parse(contents.c_str(), &inc_directories[0], filename.c_str())) {
48     Error(parser.error_, false, false);
49   }
50   if (!parser.error_.empty()) { Warn(parser.error_, false); }
51 }
52 
LoadBinarySchema(flatbuffers::Parser & parser,const std::string & filename,const std::string & contents)53 void FlatCompiler::LoadBinarySchema(flatbuffers::Parser &parser,
54                                     const std::string &filename,
55                                     const std::string &contents) {
56   if (!parser.Deserialize(reinterpret_cast<const uint8_t *>(contents.c_str()),
57                           contents.size())) {
58     Error("failed to load binary schema: " + filename, false, false);
59   }
60 }
61 
Warn(const std::string & warn,bool show_exe_name) const62 void FlatCompiler::Warn(const std::string &warn, bool show_exe_name) const {
63   params_.warn_fn(this, warn, show_exe_name);
64 }
65 
Error(const std::string & err,bool usage,bool show_exe_name) const66 void FlatCompiler::Error(const std::string &err, bool usage,
67                          bool show_exe_name) const {
68   params_.error_fn(this, err, usage, show_exe_name);
69 }
70 
71 const static FlatCOption flatc_options[] = {
72   { "o", "", "PATH", "Prefix PATH to all generated files." },
73   { "I", "", "PATH", "Search for includes in the specified path." },
74   { "M", "", "", "Print make rules for generated files." },
75   { "", "version", "", "Print the version number of flatc and exit." },
76   { "h", "help", "", "Prints this help text and exit." },
77   { "", "strict-json", "",
78     "Strict JSON: field names must be / will be quoted, no trailing commas in "
79     "tables/vectors." },
80   { "", "allow-non-utf8", "",
81     "Pass non-UTF-8 input through parser and emit nonstandard \\x escapes in "
82     "JSON. (Default is to raise parse error on non-UTF-8 input.)" },
83   { "", "natural-utf8", "",
84     "Output strings with UTF-8 as human-readable strings. By default, UTF-8 "
85     "characters are printed as \\uXXXX escapes." },
86   { "", "defaults-json", "",
87     "Output fields whose value is the default when writing JSON" },
88   { "", "unknown-json", "",
89     "Allow fields in JSON that are not defined in the schema. These fields "
90     "will be discared when generating binaries." },
91   { "", "no-prefix", "",
92     "Don't prefix enum values with the enum type in C++." },
93   { "", "scoped-enums", "",
94     "Use C++11 style scoped and strongly typed enums. Also implies "
95     "--no-prefix." },
96   { "", "no-emit-min-max-enum-values", "",
97     "Disable generation of MIN and MAX enumerated values for scoped enums "
98     "and prefixed enums." },
99   { "", "swift-implementation-only", "",
100     "Adds a @_implementationOnly to swift imports" },
101   { "", "gen-includes", "",
102     "(deprecated), this is the default behavior. If the original behavior is "
103     "required (no include statements) use --no-includes." },
104   { "", "no-includes", "",
105     "Don't generate include statements for included schemas the generated "
106     "file depends on (C++, Python, Proto-to-Fbs)." },
107   { "", "gen-mutable", "",
108     "Generate accessors that can mutate buffers in-place." },
109   { "", "gen-onefile", "",
110     "Generate a single output file for C#, Go, Java, Kotlin and Python. "
111     "Implies --no-include." },
112   { "", "gen-name-strings", "",
113     "Generate type name functions for C++ and Rust." },
114   { "", "gen-object-api", "", "Generate an additional object-based API." },
115   { "", "gen-compare", "", "Generate operator== for object-based API types." },
116   { "", "gen-nullable", "",
117     "Add Clang _Nullable for C++ pointer. or @Nullable for Java" },
118   { "", "java-package-prefix", "",
119     "Add a prefix to the generated package name for Java." },
120   { "", "java-checkerframework", "", "Add @Pure for Java." },
121   { "", "gen-generated", "", "Add @Generated annotation for Java." },
122   { "", "gen-jvmstatic", "",
123     "Add @JvmStatic annotation for Kotlin methods in companion object for "
124     "interop from Java to Kotlin." },
125   { "", "gen-all", "",
126     "Generate not just code for the current schema files, but for all files it "
127     "includes as well. If the language uses a single file for output (by "
128     "default the case for C++ and JS), all code will end up in this one "
129     "file." },
130   { "", "gen-json-emit", "",
131     "Generates encoding code which emits Flatbuffers into JSON" },
132   { "", "cpp-include", "", "Adds an #include in generated file." },
133   { "", "cpp-ptr-type", "T",
134     "Set object API pointer type (default std::unique_ptr)." },
135   { "", "cpp-str-type", "T",
136     "Set object API string type (default std::string). T::c_str(), T::length() "
137     "and T::empty() must be supported. The custom type also needs to be "
138     "constructible from std::string (see the --cpp-str-flex-ctor option to "
139     "change this behavior)" },
140   { "", "cpp-str-flex-ctor", "",
141     "Don't construct custom string types by passing std::string from "
142     "Flatbuffers, but (char* + length)." },
143   { "", "cpp-field-case-style", "STYLE",
144     "Generate C++ fields using selected case style. Supported STYLE values: * "
145     "'unchanged' - leave unchanged (default) * 'upper' - schema snake_case "
146     "emits UpperCamel; * 'lower' - schema snake_case emits lowerCamel." },
147   { "", "cpp-std", "CPP_STD",
148     "Generate a C++ code using features of selected C++ standard. Supported "
149     "CPP_STD values: * 'c++0x' - generate code compatible with old compilers; "
150     "'c++11' - use C++11 code generator (default); * 'c++17' - use C++17 "
151     "features in generated code (experimental)." },
152   { "", "cpp-static-reflection", "",
153     "When using C++17, generate extra code to provide compile-time (static) "
154     "reflection of Flatbuffers types. Requires --cpp-std to be \"c++17\" or "
155     "higher." },
156   { "", "object-prefix", "PREFIX",
157     "Customize class prefix for C++ object-based API." },
158   { "", "object-suffix", "SUFFIX",
159     "Customize class suffix for C++ object-based API. Default Value is "
160     "\"T\"." },
161   { "", "go-namespace", "", "Generate the overriding namespace in Golang." },
162   { "", "go-import", "IMPORT",
163     "Generate the overriding import for flatbuffers in Golang (default is "
164     "\"github.com/google/flatbuffers/go\")." },
165   { "", "go-module-name", "",
166     "Prefix local import paths of generated go code with the module name" },
167   { "", "raw-binary", "",
168     "Allow binaries without file_identifier to be read. This may crash flatc "
169     "given a mismatched schema." },
170   { "", "size-prefixed", "", "Input binaries are size prefixed buffers." },
171   { "", "proto-namespace-suffix", "SUFFIX",
172     "Add this namespace to any flatbuffers generated from protobufs." },
173   { "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." },
174   { "", "keep-proto-id", "", "Keep protobuf field ids in generated fbs file." },
175   { "", "proto-id-gap", "",
176     "Action that should be taken when a gap between protobuf ids found. "
177     "Supported values: * "
178     "'nop' - do not care about gap * 'warn' - A warning message will be shown "
179     "about the gap in protobuf ids"
180     "(default) "
181     "* 'error' - An error message will be shown and the fbs generation will be "
182     "interrupted." },
183   { "", "grpc", "", "Generate GRPC interfaces for the specified languages." },
184   { "", "schema", "", "Serialize schemas instead of JSON (use with -b)." },
185   { "", "bfbs-filenames", "PATH",
186     "Sets the root path where reflection filenames in reflection.fbs are "
187     "relative to. The 'root' is denoted with  `//`. E.g. if PATH=/a/b/c "
188     "then /a/d/e.fbs will be serialized as //../d/e.fbs. (PATH defaults to the "
189     "directory of the first provided schema file." },
190   { "", "bfbs-absolute-paths", "", "Uses absolute paths instead of relative paths in the BFBS output." },
191   { "", "bfbs-comments", "", "Add doc comments to the binary schema files." },
192   { "", "bfbs-builtins", "",
193     "Add builtin attributes to the binary schema files." },
194   { "", "bfbs-gen-embed", "",
195     "Generate code to embed the bfbs schema to the source." },
196   { "", "conform", "FILE",
197     "Specify a schema the following schemas should be an evolution of. Gives "
198     "errors if not." },
199   { "", "conform-includes", "PATH",
200     "Include path for the schema given with --conform PATH" },
201   { "", "filename-suffix", "SUFFIX",
202     "The suffix appended to the generated file names (Default is "
203     "'_generated')." },
204   { "", "filename-ext", "EXT",
205     "The extension appended to the generated file names. Default is "
206     "language-specific (e.g., '.h' for C++)" },
207   { "", "include-prefix", "PATH",
208     "Prefix this PATH to any generated include statements." },
209   { "", "keep-prefix", "",
210     "Keep original prefix of schema include statement." },
211   { "", "reflect-types", "",
212     "Add minimal type reflection to code generation." },
213   { "", "reflect-names", "", "Add minimal type/name reflection." },
214   { "", "rust-serialize", "",
215     "Implement serde::Serialize on generated Rust types." },
216   { "", "rust-module-root-file", "",
217     "Generate rust code in individual files with a module root file." },
218   { "", "root-type", "T", "Select or override the default root_type." },
219   { "", "require-explicit-ids", "",
220     "When parsing schemas, require explicit ids (id: x)." },
221   { "", "force-defaults", "",
222     "Emit default values in binary output from JSON" },
223   { "", "force-empty", "",
224     "When serializing from object API representation, force strings and "
225     "vectors to empty rather than null." },
226   { "", "force-empty-vectors", "",
227     "When serializing from object API representation, force vectors to empty "
228     "rather than null." },
229   { "", "flexbuffers", "",
230     "Used with \"binary\" and \"json\" options, it generates data using "
231     "schema-less FlexBuffers." },
232   { "", "no-warnings", "", "Inhibit all warnings messages." },
233   { "", "warnings-as-errors", "", "Treat all warnings as errors." },
234   { "", "cs-global-alias", "",
235     "Prepend \"global::\" to all user generated csharp classes and "
236     "structs." },
237   { "", "cs-gen-json-serializer", "",
238     "Allows (de)serialization of JSON text in the Object API. (requires "
239     "--gen-object-api)." },
240   { "", "json-nested-bytes", "",
241     "Allow a nested_flatbuffer field to be parsed as a vector of bytes "
242     "in JSON, which is unsafe unless checked by a verifier afterwards." },
243   { "", "ts-flat-files", "",
244     "Generate a single typescript file per .fbs file. Implies "
245     "ts_entry_points." },
246   { "", "ts-entry-points", "",
247     "Generate entry point typescript per namespace. Implies gen-all." },
248   { "", "annotate-sparse-vectors", "", "Don't annotate every vector element." },
249   { "", "annotate", "SCHEMA",
250     "Annotate the provided BINARY_FILE with the specified SCHEMA file." },
251   { "", "no-leak-private-annotation", "",
252     "Prevents multiple type of annotations within a Fbs SCHEMA file. "
253     "Currently this is required to generate private types in Rust" },
254   { "", "python-no-type-prefix-suffix", "",
255     "Skip emission of Python functions that are prefixed with typenames" },
256   { "", "python-typing", "", "Generate Python type annotations" },
257   { "", "ts-omit-entrypoint", "",
258     "Omit emission of namespace entrypoint file" },
259   { "", "file-names-only", "",
260     "Print out generated file names without writing to the files" },
261 };
262 
__anon3907ebd70102(FlatCOption a, FlatCOption b) 263 auto cmp = [](FlatCOption a, FlatCOption b) { return a.long_opt < b.long_opt; };
264 static std::set<FlatCOption, decltype(cmp)> language_options(cmp);
265 
AppendTextWrappedString(std::stringstream & ss,std::string & text,size_t max_col,size_t start_col)266 static void AppendTextWrappedString(std::stringstream &ss, std::string &text,
267                                     size_t max_col, size_t start_col) {
268   size_t max_line_length = max_col - start_col;
269 
270   if (text.length() > max_line_length) {
271     size_t ideal_break_location = text.rfind(' ', max_line_length);
272     size_t length = std::min(max_line_length, ideal_break_location);
273     ss << text.substr(0, length) << "\n";
274     ss << std::string(start_col, ' ');
275     std::string rest_of_description = text.substr(
276         ((ideal_break_location < max_line_length || text.at(length) == ' ')
277              ? length + 1
278              : length));
279     AppendTextWrappedString(ss, rest_of_description, max_col, start_col);
280   } else {
281     ss << text;
282   }
283 }
284 
AppendOption(std::stringstream & ss,const FlatCOption & option,size_t max_col,size_t min_col_for_description)285 static void AppendOption(std::stringstream &ss, const FlatCOption &option,
286                          size_t max_col, size_t min_col_for_description) {
287   size_t chars = 2;
288   ss << "  ";
289   if (!option.short_opt.empty()) {
290     chars += 2 + option.short_opt.length();
291     ss << "-" << option.short_opt;
292     if (!option.long_opt.empty()) {
293       chars++;
294       ss << ",";
295     }
296     ss << " ";
297   }
298   if (!option.long_opt.empty()) {
299     chars += 3 + option.long_opt.length();
300     ss << "--" << option.long_opt << " ";
301   }
302   if (!option.parameter.empty()) {
303     chars += 1 + option.parameter.length();
304     ss << option.parameter << " ";
305   }
306   size_t start_of_description = chars;
307   if (start_of_description > min_col_for_description) {
308     ss << "\n";
309     start_of_description = min_col_for_description;
310     ss << std::string(start_of_description, ' ');
311   } else {
312     while (start_of_description < min_col_for_description) {
313       ss << " ";
314       start_of_description++;
315     }
316   }
317   if (!option.description.empty()) {
318     std::string description = option.description;
319     AppendTextWrappedString(ss, description, max_col, start_of_description);
320   }
321   ss << "\n";
322 }
323 
AppendShortOption(std::stringstream & ss,const FlatCOption & option)324 static void AppendShortOption(std::stringstream &ss,
325                               const FlatCOption &option) {
326   if (!option.short_opt.empty()) {
327     ss << "-" << option.short_opt;
328     if (!option.long_opt.empty()) { ss << "|"; }
329   }
330   if (!option.long_opt.empty()) { ss << "--" << option.long_opt; }
331 }
332 
GetShortUsageString(const std::string & program_name) const333 std::string FlatCompiler::GetShortUsageString(
334     const std::string &program_name) const {
335   std::stringstream ss;
336   ss << "Usage: " << program_name << " [";
337 
338   for (const FlatCOption &option : language_options) {
339     AppendShortOption(ss, option);
340     ss << ", ";
341   }
342 
343   for (const FlatCOption &option : flatc_options) {
344     AppendShortOption(ss, option);
345     ss << ", ";
346   }
347 
348   ss.seekp(-2, ss.cur);
349   ss << "]... FILE... [-- BINARY_FILE...]";
350   std::string help = ss.str();
351   std::stringstream ss_textwrap;
352   AppendTextWrappedString(ss_textwrap, help, 80, 0);
353   return ss_textwrap.str();
354 }
355 
GetUsageString(const std::string & program_name) const356 std::string FlatCompiler::GetUsageString(
357     const std::string &program_name) const {
358   std::stringstream ss;
359   ss << "Usage: " << program_name
360      << " [OPTION]... FILE... [-- BINARY_FILE...]\n";
361 
362   for (const FlatCOption &option : language_options) {
363     AppendOption(ss, option, 80, 25);
364   }
365   ss << "\n";
366 
367   for (const FlatCOption &option : flatc_options) {
368     AppendOption(ss, option, 80, 25);
369   }
370   ss << "\n";
371 
372   std::string files_description =
373       "FILEs may be schemas (must end in .fbs), binary schemas (must end in "
374       ".bfbs) or JSON files (conforming to preceding schema). BINARY_FILEs "
375       "after the -- must be binary flatbuffer format files. Output files are "
376       "named using the base file name of the input, and written to the current "
377       "directory or the path given by -o. example: " +
378       program_name + " -c -b schema1.fbs schema2.fbs data.json";
379   AppendTextWrappedString(ss, files_description, 80, 0);
380   ss << "\n";
381   return ss.str();
382 }
383 
AnnotateBinaries(const uint8_t * binary_schema,const uint64_t binary_schema_size,const FlatCOptions & options)384 void FlatCompiler::AnnotateBinaries(const uint8_t *binary_schema,
385                                     const uint64_t binary_schema_size,
386                                     const FlatCOptions &options) {
387   const std::string &schema_filename = options.annotate_schema;
388 
389   for (const std::string &filename : options.filenames) {
390     std::string binary_contents;
391     if (!flatbuffers::LoadFile(filename.c_str(), true, &binary_contents)) {
392       Warn("unable to load binary file: " + filename);
393       continue;
394     }
395 
396     const uint8_t *binary =
397         reinterpret_cast<const uint8_t *>(binary_contents.c_str());
398     const size_t binary_size = binary_contents.size();
399     const bool is_size_prefixed = options.opts.size_prefixed;
400 
401     flatbuffers::BinaryAnnotator binary_annotator(
402         binary_schema, binary_schema_size, binary, binary_size,
403         is_size_prefixed);
404 
405     auto annotations = binary_annotator.Annotate();
406 
407     flatbuffers::AnnotatedBinaryTextGenerator::Options text_gen_opts;
408     text_gen_opts.include_vector_contents =
409         options.annotate_include_vector_contents;
410 
411     // TODO(dbaileychess): Right now we just support a single text-based
412     // output of the annotated binary schema, which we generate here. We
413     // could output the raw annotations instead and have third-party tools
414     // use them to generate their own output.
415     flatbuffers::AnnotatedBinaryTextGenerator text_generator(
416         text_gen_opts, annotations, binary, binary_size);
417 
418     text_generator.Generate(filename, schema_filename);
419   }
420 }
421 
ParseFromCommandLineArguments(int argc,const char ** argv)422 FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
423                                                          const char **argv) {
424   if (argc <= 1) { Error("Need to provide at least one argument."); }
425 
426   FlatCOptions options;
427 
428   options.program_name = std::string(argv[0]);
429 
430   IDLOptions &opts = options.opts;
431 
432   for (int argi = 1; argi < argc; argi++) {
433     std::string arg = argv[argi];
434     if (arg[0] == '-') {
435       if (options.filenames.size() && arg[1] != '-')
436         Error("invalid option location: " + arg, true);
437       if (arg == "-o") {
438         if (++argi >= argc) Error("missing path following: " + arg, true);
439         options.output_path = flatbuffers::ConCatPathFileName(
440             flatbuffers::PosixPath(argv[argi]), "");
441       } else if (arg == "-I") {
442         if (++argi >= argc) Error("missing path following: " + arg, true);
443         options.include_directories_storage.push_back(
444             flatbuffers::PosixPath(argv[argi]));
445         options.include_directories.push_back(
446             options.include_directories_storage.back().c_str());
447       } else if (arg == "--bfbs-filenames") {
448         if (++argi > argc) Error("missing path following: " + arg, true);
449         opts.project_root = argv[argi];
450         if (!DirExists(opts.project_root.c_str()))
451           Error(arg + " is not a directory: " + opts.project_root);
452       } else if (arg == "--conform") {
453         if (++argi >= argc) Error("missing path following: " + arg, true);
454         options.conform_to_schema = flatbuffers::PosixPath(argv[argi]);
455       } else if (arg == "--conform-includes") {
456         if (++argi >= argc) Error("missing path following: " + arg, true);
457         options.include_directories_storage.push_back(
458             flatbuffers::PosixPath(argv[argi]));
459         options.conform_include_directories.push_back(
460             options.include_directories_storage.back().c_str());
461       } else if (arg == "--include-prefix") {
462         if (++argi >= argc) Error("missing path following: " + arg, true);
463         opts.include_prefix = flatbuffers::ConCatPathFileName(
464             flatbuffers::PosixPath(argv[argi]), "");
465       } else if (arg == "--keep-prefix") {
466         opts.keep_prefix = true;
467       } else if (arg == "--strict-json") {
468         opts.strict_json = true;
469       } else if (arg == "--allow-non-utf8") {
470         opts.allow_non_utf8 = true;
471       } else if (arg == "--natural-utf8") {
472         opts.natural_utf8 = true;
473       } else if (arg == "--go-namespace") {
474         if (++argi >= argc) Error("missing golang namespace" + arg, true);
475         opts.go_namespace = argv[argi];
476       } else if (arg == "--go-import") {
477         if (++argi >= argc) Error("missing golang import" + arg, true);
478         opts.go_import = argv[argi];
479       } else if (arg == "--go-module-name") {
480         if (++argi >= argc) Error("missing golang module name" + arg, true);
481         opts.go_module_name = argv[argi];
482       } else if (arg == "--defaults-json") {
483         opts.output_default_scalars_in_json = true;
484       } else if (arg == "--unknown-json") {
485         opts.skip_unexpected_fields_in_json = true;
486       } else if (arg == "--no-prefix") {
487         opts.prefixed_enums = false;
488       } else if (arg == "--cpp-minify-enums") {
489         opts.cpp_minify_enums = true;
490       } else if (arg == "--scoped-enums") {
491         opts.prefixed_enums = false;
492         opts.scoped_enums = true;
493       } else if (arg == "--no-emit-min-max-enum-values") {
494         opts.emit_min_max_enum_values = false;
495       } else if (arg == "--no-union-value-namespacing") {
496         opts.union_value_namespacing = false;
497       } else if (arg == "--gen-mutable") {
498         opts.mutable_buffer = true;
499       } else if (arg == "--gen-name-strings") {
500         opts.generate_name_strings = true;
501       } else if (arg == "--gen-object-api") {
502         opts.generate_object_based_api = true;
503       } else if (arg == "--gen-compare") {
504         opts.gen_compare = true;
505       } else if (arg == "--cpp-include") {
506         if (++argi >= argc) Error("missing include following: " + arg, true);
507         opts.cpp_includes.push_back(argv[argi]);
508       } else if (arg == "--cpp-ptr-type") {
509         if (++argi >= argc) Error("missing type following: " + arg, true);
510         opts.cpp_object_api_pointer_type = argv[argi];
511       } else if (arg == "--cpp-str-type") {
512         if (++argi >= argc) Error("missing type following: " + arg, true);
513         opts.cpp_object_api_string_type = argv[argi];
514       } else if (arg == "--cpp-str-flex-ctor") {
515         opts.cpp_object_api_string_flexible_constructor = true;
516       } else if (arg == "--no-cpp-direct-copy") {
517         opts.cpp_direct_copy = false;
518       } else if (arg == "--cpp-field-case-style") {
519         if (++argi >= argc) Error("missing case style following: " + arg, true);
520         if (!strcmp(argv[argi], "unchanged"))
521           opts.cpp_object_api_field_case_style =
522               IDLOptions::CaseStyle_Unchanged;
523         else if (!strcmp(argv[argi], "upper"))
524           opts.cpp_object_api_field_case_style = IDLOptions::CaseStyle_Upper;
525         else if (!strcmp(argv[argi], "lower"))
526           opts.cpp_object_api_field_case_style = IDLOptions::CaseStyle_Lower;
527         else
528           Error("unknown case style: " + std::string(argv[argi]), true);
529       } else if (arg == "--gen-nullable") {
530         opts.gen_nullable = true;
531       } else if (arg == "--java-package-prefix") {
532         if (++argi >= argc) Error("missing prefix following: " + arg, true);
533         opts.java_package_prefix = argv[argi];
534       } else if (arg == "--java-checkerframework") {
535         opts.java_checkerframework = true;
536       } else if (arg == "--gen-generated") {
537         opts.gen_generated = true;
538       } else if (arg == "--swift-implementation-only") {
539         opts.swift_implementation_only = true;
540       } else if (arg == "--gen-json-emit") {
541         opts.gen_json_coders = true;
542       } else if (arg == "--object-prefix") {
543         if (++argi >= argc) Error("missing prefix following: " + arg, true);
544         opts.object_prefix = argv[argi];
545       } else if (arg == "--object-suffix") {
546         if (++argi >= argc) Error("missing suffix following: " + arg, true);
547         opts.object_suffix = argv[argi];
548       } else if (arg == "--gen-all") {
549         opts.generate_all = true;
550         opts.include_dependence_headers = false;
551       } else if (arg == "--gen-includes") {
552         // Deprecated, remove this option some time in the future.
553         Warn("warning: --gen-includes is deprecated (it is now default)\n");
554       } else if (arg == "--no-includes") {
555         opts.include_dependence_headers = false;
556       } else if (arg == "--gen-onefile") {
557         opts.one_file = true;
558         opts.include_dependence_headers = false;
559       } else if (arg == "--raw-binary") {
560         options.raw_binary = true;
561       } else if (arg == "--size-prefixed") {
562         opts.size_prefixed = true;
563       } else if (arg == "--") {  // Separator between text and binary inputs.
564         options.binary_files_from = options.filenames.size();
565       } else if (arg == "--proto-namespace-suffix") {
566         if (++argi >= argc) Error("missing namespace suffix" + arg, true);
567         opts.proto_namespace_suffix = argv[argi];
568       } else if (arg == "--oneof-union") {
569         opts.proto_oneof_union = true;
570       } else if (arg == "--keep-proto-id") {
571         opts.keep_proto_id = true;
572       } else if (arg == "--proto-id-gap") {
573         if (++argi >= argc) Error("missing case style following: " + arg, true);
574         if (!strcmp(argv[argi], "nop"))
575           opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP;
576         else if (!strcmp(argv[argi], "warn"))
577           opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::WARNING;
578         else if (!strcmp(argv[argi], "error"))
579           opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::ERROR;
580         else
581           Error("unknown case style: " + std::string(argv[argi]), true);
582       } else if (arg == "--schema") {
583         options.schema_binary = true;
584       } else if (arg == "-M") {
585         options.print_make_rules = true;
586       } else if (arg == "--version") {
587         printf("flatc version %s\n", FLATC_VERSION());
588         exit(0);
589       } else if (arg == "--help" || arg == "-h") {
590         printf("%s\n", GetUsageString(options.program_name).c_str());
591         exit(0);
592       } else if (arg == "--grpc") {
593         options.grpc_enabled = true;
594       } else if (arg == "--bfbs-comments") {
595         opts.binary_schema_comments = true;
596       } else if (arg == "--bfbs-builtins") {
597         opts.binary_schema_builtins = true;
598       } else if (arg == "--bfbs-gen-embed") {
599         opts.binary_schema_gen_embed = true;
600       } else if (arg == "--bfbs-absolute-paths") {
601         opts.binary_schema_absolute_paths = true;
602       } else if (arg == "--reflect-types") {
603         opts.mini_reflect = IDLOptions::kTypes;
604       } else if (arg == "--reflect-names") {
605         opts.mini_reflect = IDLOptions::kTypesAndNames;
606       } else if (arg == "--rust-serialize") {
607         opts.rust_serialize = true;
608       } else if (arg == "--rust-module-root-file") {
609         opts.rust_module_root_file = true;
610       } else if (arg == "--require-explicit-ids") {
611         opts.require_explicit_ids = true;
612       } else if (arg == "--root-type") {
613         if (++argi >= argc) Error("missing type following: " + arg, true);
614         opts.root_type = argv[argi];
615       } else if (arg == "--filename-suffix") {
616         if (++argi >= argc) Error("missing filename suffix: " + arg, true);
617         opts.filename_suffix = argv[argi];
618       } else if (arg == "--filename-ext") {
619         if (++argi >= argc) Error("missing filename extension: " + arg, true);
620         opts.filename_extension = argv[argi];
621       } else if (arg == "--force-defaults") {
622         opts.force_defaults = true;
623       } else if (arg == "--force-empty") {
624         opts.set_empty_strings_to_null = false;
625         opts.set_empty_vectors_to_null = false;
626       } else if (arg == "--force-empty-vectors") {
627         opts.set_empty_vectors_to_null = false;
628       } else if (arg == "--java-primitive-has-method") {
629         opts.java_primitive_has_method = true;
630       } else if (arg == "--cs-gen-json-serializer") {
631         opts.cs_gen_json_serializer = true;
632       } else if (arg == "--flexbuffers") {
633         opts.use_flexbuffers = true;
634       } else if (arg == "--gen-jvmstatic") {
635         opts.gen_jvmstatic = true;
636       } else if (arg == "--no-warnings") {
637         opts.no_warnings = true;
638       } else if (arg == "--warnings-as-errors") {
639         opts.warnings_as_errors = true;
640       } else if (arg == "--cpp-std") {
641         if (++argi >= argc)
642           Error("missing C++ standard specification" + arg, true);
643         opts.cpp_std = argv[argi];
644       } else if (arg.rfind("--cpp-std=", 0) == 0) {
645         opts.cpp_std = arg.substr(std::string("--cpp-std=").size());
646       } else if (arg == "--cpp-static-reflection") {
647         opts.cpp_static_reflection = true;
648       } else if (arg == "--cs-global-alias") {
649         opts.cs_global_alias = true;
650       } else if (arg == "--json-nested-bytes") {
651         opts.json_nested_legacy_flatbuffers = true;
652       } else if (arg == "--ts-flat-files") {
653         opts.ts_flat_files = true;
654         opts.ts_entry_points = true;
655         opts.generate_all = true;
656       } else if (arg == "--ts-entry-points") {
657         opts.ts_entry_points = true;
658         opts.generate_all = true;
659       } else if (arg == "--ts-no-import-ext") {
660         opts.ts_no_import_ext = true;
661       } else if (arg == "--no-leak-private-annotation") {
662         opts.no_leak_private_annotations = true;
663       } else if (arg == "--python-no-type-prefix-suffix") {
664         opts.python_no_type_prefix_suffix = true;
665       } else if (arg == "--python-typing") {
666         opts.python_typing = true;
667       } else if (arg == "--ts-omit-entrypoint") {
668         opts.ts_omit_entrypoint = true;
669       } else if (arg == "--annotate-sparse-vectors") {
670         options.annotate_include_vector_contents = false;
671       } else if (arg == "--annotate") {
672         if (++argi >= argc) Error("missing path following: " + arg, true);
673         options.annotate_schema = flatbuffers::PosixPath(argv[argi]);
674       } else if (arg == "--file-names-only") {
675         // TODO (khhn): Provide 2 implementation
676         options.file_names_only = true;
677       } else {
678         if (arg == "--proto") { opts.proto_mode = true; }
679 
680         auto code_generator_it = code_generators_.find(arg);
681         if (code_generator_it == code_generators_.end()) {
682           Error("unknown commandline argument: " + arg, true);
683           return options;
684         }
685 
686         std::shared_ptr<CodeGenerator> code_generator =
687             code_generator_it->second;
688 
689         // TODO(derekbailey): remove in favor of just checking if
690         // generators.empty().
691         options.any_generator = true;
692         opts.lang_to_generate |= code_generator->Language();
693 
694         auto is_binary_schema = code_generator->SupportsBfbsGeneration();
695         opts.binary_schema_comments = is_binary_schema;
696         options.requires_bfbs = is_binary_schema;
697         options.generators.push_back(std::move(code_generator));
698       }
699     } else {
700       options.filenames.push_back(flatbuffers::PosixPath(argv[argi]));
701     }
702   }
703 
704   return options;
705 }
706 
ValidateOptions(const FlatCOptions & options)707 void FlatCompiler::ValidateOptions(const FlatCOptions &options) {
708   const IDLOptions &opts = options.opts;
709 
710   if (!options.filenames.size()) Error("missing input files", false, true);
711 
712   if (opts.proto_mode) {
713     if (options.any_generator)
714       Error("cannot generate code directly from .proto files", true);
715   } else if (!options.any_generator && options.conform_to_schema.empty() &&
716              options.annotate_schema.empty()) {
717     Error("no options: specify at least one generator.", true);
718   }
719 
720   if (opts.cs_gen_json_serializer && !opts.generate_object_based_api) {
721     Error(
722         "--cs-gen-json-serializer requires --gen-object-api to be set as "
723         "well.");
724   }
725 }
726 
GetConformParser(const FlatCOptions & options)727 flatbuffers::Parser FlatCompiler::GetConformParser(
728     const FlatCOptions &options) {
729   flatbuffers::Parser conform_parser;
730 
731   // conform parser should check advanced options,
732   // so, it have to have knowledge about languages:
733   conform_parser.opts.lang_to_generate = options.opts.lang_to_generate;
734 
735   if (!options.conform_to_schema.empty()) {
736     std::string contents;
737     if (!flatbuffers::LoadFile(options.conform_to_schema.c_str(), true,
738                                &contents)) {
739       Error("unable to load schema: " + options.conform_to_schema);
740     }
741 
742     if (flatbuffers::GetExtension(options.conform_to_schema) ==
743         reflection::SchemaExtension()) {
744       LoadBinarySchema(conform_parser, options.conform_to_schema, contents);
745     } else {
746       ParseFile(conform_parser, options.conform_to_schema, contents,
747                 options.conform_include_directories);
748     }
749   }
750   return conform_parser;
751 }
752 
GenerateCode(const FlatCOptions & options,Parser & conform_parser)753 std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
754                                                    Parser &conform_parser) {
755   std::unique_ptr<Parser> parser =
756       std::unique_ptr<Parser>(new Parser(options.opts));
757 
758   for (auto file_it = options.filenames.begin();
759        file_it != options.filenames.end(); ++file_it) {
760     IDLOptions opts = options.opts;
761 
762     auto &filename = *file_it;
763     std::string contents;
764     if (!flatbuffers::LoadFile(filename.c_str(), true, &contents))
765       Error("unable to load file: " + filename);
766 
767     bool is_binary = static_cast<size_t>(file_it - options.filenames.begin()) >=
768                      options.binary_files_from;
769     auto ext = flatbuffers::GetExtension(filename);
770     const bool is_schema = ext == "fbs" || ext == "proto";
771     if (is_schema && opts.project_root.empty()) {
772       opts.project_root = StripFileName(filename);
773     }
774     const bool is_binary_schema = ext == reflection::SchemaExtension();
775     if (is_binary) {
776       parser->builder_.Clear();
777       parser->builder_.PushFlatBuffer(
778           reinterpret_cast<const uint8_t *>(contents.c_str()),
779           contents.length());
780       if (!options.raw_binary) {
781         // Generally reading binaries that do not correspond to the schema
782         // will crash, and sadly there's no way around that when the binary
783         // does not contain a file identifier.
784         // We'd expect that typically any binary used as a file would have
785         // such an identifier, so by default we require them to match.
786         if (!parser->file_identifier_.length()) {
787           Error("current schema has no file_identifier: cannot test if \"" +
788                 filename +
789                 "\" matches the schema, use --raw-binary to read this file"
790                 " anyway.");
791         } else if (!flatbuffers::BufferHasIdentifier(
792                        contents.c_str(), parser->file_identifier_.c_str(),
793                        opts.size_prefixed)) {
794           Error("binary \"" + filename +
795                 "\" does not have expected file_identifier \"" +
796                 parser->file_identifier_ +
797                 "\", use --raw-binary to read this file anyway.");
798         }
799       }
800     } else {
801       // Check if file contains 0 bytes.
802       if (!opts.use_flexbuffers && !is_binary_schema &&
803           contents.length() != strlen(contents.c_str())) {
804         Error("input file appears to be binary: " + filename, true);
805       }
806       if (is_schema || is_binary_schema) {
807         // If we're processing multiple schemas, make sure to start each
808         // one from scratch. If it depends on previous schemas it must do
809         // so explicitly using an include.
810         parser.reset(new Parser(opts));
811       }
812       // Try to parse the file contents (binary schema/flexbuffer/textual
813       // schema)
814       if (is_binary_schema) {
815         LoadBinarySchema(*parser, filename, contents);
816       } else if (opts.use_flexbuffers) {
817         if (opts.lang_to_generate == IDLOptions::kJson) {
818           auto data = reinterpret_cast<const uint8_t *>(contents.c_str());
819           auto size = contents.size();
820           std::vector<uint8_t> reuse_tracker;
821           if (!flexbuffers::VerifyBuffer(data, size, &reuse_tracker))
822             Error("flexbuffers file failed to verify: " + filename, false);
823           parser->flex_root_ = flexbuffers::GetRoot(data, size);
824         } else {
825           parser->flex_builder_.Clear();
826           ParseFile(*parser, filename, contents, options.include_directories);
827         }
828       } else {
829         ParseFile(*parser, filename, contents, options.include_directories);
830         if (!is_schema && !parser->builder_.GetSize()) {
831           // If a file doesn't end in .fbs, it must be json/binary. Ensure we
832           // didn't just parse a schema with a different extension.
833           Error("input file is neither json nor a .fbs (schema) file: " +
834                     filename,
835                 true);
836         }
837       }
838       if ((is_schema || is_binary_schema) &&
839           !options.conform_to_schema.empty()) {
840         auto err = parser->ConformTo(conform_parser);
841         if (!err.empty()) Error("schemas don\'t conform: " + err, false);
842       }
843       if (options.schema_binary || opts.binary_schema_gen_embed) {
844         parser->Serialize();
845       }
846       if (options.schema_binary) {
847         parser->file_extension_ = reflection::SchemaExtension();
848       }
849     }
850     std::string filebase =
851         flatbuffers::StripPath(flatbuffers::StripExtension(filename));
852 
853     // If one of the generators uses bfbs, serialize the parser and get
854     // the serialized buffer and length.
855     const uint8_t *bfbs_buffer = nullptr;
856     int64_t bfbs_length = 0;
857     if (options.requires_bfbs) {
858       parser->Serialize();
859       bfbs_buffer = parser->builder_.GetBufferPointer();
860       bfbs_length = parser->builder_.GetSize();
861     }
862 
863     for (const std::shared_ptr<CodeGenerator> &code_generator :
864          options.generators) {
865       if (options.print_make_rules) {
866         std::string make_rule;
867         const CodeGenerator::Status status = code_generator->GenerateMakeRule(
868             *parser, options.output_path, filename, make_rule);
869         if (status == CodeGenerator::Status::OK && !make_rule.empty()) {
870           printf("%s\n",
871                  flatbuffers::WordWrap(make_rule, 80, " ", " \\").c_str());
872         } else {
873           Error("Cannot generate make rule for " +
874                 code_generator->LanguageName());
875         }
876       } else {
877         flatbuffers::EnsureDirExists(options.output_path);
878 
879         // Prefer bfbs generators if present.
880         if (code_generator->SupportsBfbsGeneration()) {
881           CodeGenOptions code_gen_options;
882           code_gen_options.output_path = options.output_path;
883 
884           const CodeGenerator::Status status = code_generator->GenerateCode(
885               bfbs_buffer, bfbs_length, code_gen_options);
886           if (status != CodeGenerator::Status::OK) {
887             Error("Unable to generate " + code_generator->LanguageName() +
888                   " for " + filebase + code_generator->status_detail +
889                   " using bfbs generator.");
890           }
891         } else {
892           if ((!code_generator->IsSchemaOnly() ||
893                (is_schema || is_binary_schema)) &&
894               code_generator->GenerateCode(*parser, options.output_path,
895                                            filebase) !=
896                   CodeGenerator::Status::OK) {
897             Error("Unable to generate " + code_generator->LanguageName() +
898                   " for " + filebase + code_generator->status_detail);
899           }
900         }
901       }
902 
903       if (options.grpc_enabled) {
904         const CodeGenerator::Status status = code_generator->GenerateGrpcCode(
905             *parser, options.output_path, filebase);
906 
907         if (status == CodeGenerator::Status::NOT_IMPLEMENTED) {
908           Warn("GRPC interface generator not implemented for " +
909                code_generator->LanguageName());
910         } else if (status == CodeGenerator::Status::ERROR) {
911           Error("Unable to generate GRPC interface for " +
912                 code_generator->LanguageName());
913         }
914       }
915     }
916 
917     if (!opts.root_type.empty()) {
918       if (!parser->SetRootType(opts.root_type.c_str()))
919         Error("unknown root type: " + opts.root_type);
920       else if (parser->root_struct_def_->fixed)
921         Error("root type must be a table");
922     }
923 
924     // We do not want to generate code for the definitions in this file
925     // in any files coming up next.
926     parser->MarkGenerated();
927   }
928 
929   return parser;
930 }
931 
Compile(const FlatCOptions & options)932 int FlatCompiler::Compile(const FlatCOptions &options) {
933   // TODO(derekbailey): change to std::optional<Parser>
934   Parser conform_parser = GetConformParser(options);
935 
936   // TODO(derekbailey): split to own method.
937   if (!options.annotate_schema.empty()) {
938     const std::string ext = flatbuffers::GetExtension(options.annotate_schema);
939     if (!(ext == reflection::SchemaExtension() || ext == "fbs")) {
940       Error("Expected a `.bfbs` or `.fbs` schema, got: " +
941             options.annotate_schema);
942     }
943 
944     const bool is_binary_schema = ext == reflection::SchemaExtension();
945 
946     std::string schema_contents;
947     if (!flatbuffers::LoadFile(options.annotate_schema.c_str(),
948                                /*binary=*/is_binary_schema, &schema_contents)) {
949       Error("unable to load schema: " + options.annotate_schema);
950     }
951 
952     const uint8_t *binary_schema = nullptr;
953     uint64_t binary_schema_size = 0;
954 
955     IDLOptions binary_opts;
956     binary_opts.lang_to_generate |= flatbuffers::IDLOptions::kBinary;
957     Parser parser(binary_opts);
958 
959     if (is_binary_schema) {
960       binary_schema =
961           reinterpret_cast<const uint8_t *>(schema_contents.c_str());
962       binary_schema_size = schema_contents.size();
963     } else {
964       // If we need to generate the .bfbs file from the provided schema file
965       // (.fbs)
966       ParseFile(parser, options.annotate_schema, schema_contents,
967                 options.include_directories);
968       parser.Serialize();
969 
970       binary_schema = parser.builder_.GetBufferPointer();
971       binary_schema_size = parser.builder_.GetSize();
972     }
973 
974     if (binary_schema == nullptr || !binary_schema_size) {
975       Error("could not parse a value binary schema from: " +
976             options.annotate_schema);
977     }
978 
979     // Annotate the provided files with the binary_schema.
980     AnnotateBinaries(binary_schema, binary_schema_size, options);
981 
982     // We don't support doing anything else after annotating a binary.
983     return 0;
984   }
985 
986   if (options.generators.empty() && options.conform_to_schema.empty()) {
987     Error("No generator registered");
988     return -1;
989   }
990 
991   std::unique_ptr<Parser> parser = GenerateCode(options, conform_parser);
992 
993   for (const auto &code_generator : options.generators) {
994     if (code_generator->SupportsRootFileGeneration()) {
995       code_generator->GenerateRootFile(*parser, options.output_path);
996     }
997   }
998 
999   return 0;
1000 }
1001 
RegisterCodeGenerator(const FlatCOption & option,std::shared_ptr<CodeGenerator> code_generator)1002 bool FlatCompiler::RegisterCodeGenerator(
1003     const FlatCOption &option, std::shared_ptr<CodeGenerator> code_generator) {
1004   if (!option.short_opt.empty() &&
1005       code_generators_.find("-" + option.short_opt) != code_generators_.end()) {
1006     Error("multiple generators registered under: -" + option.short_opt, false,
1007           false);
1008     return false;
1009   }
1010 
1011   if (!option.short_opt.empty()) {
1012     code_generators_["-" + option.short_opt] = code_generator;
1013   }
1014 
1015   if (!option.long_opt.empty() &&
1016       code_generators_.find("--" + option.long_opt) != code_generators_.end()) {
1017     Error("multiple generators registered under: --" + option.long_opt, false,
1018           false);
1019     return false;
1020   }
1021 
1022   if (!option.long_opt.empty()) {
1023     code_generators_["--" + option.long_opt] = code_generator;
1024   }
1025 
1026   language_options.insert(option);
1027 
1028   return true;
1029 }
1030 
1031 }  // namespace flatbuffers
1032