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