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