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