blob: 3b2ef9f36688d46870dc344120a8442d5540a916 [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
19#include <list>
James Kuszmaul8e62b022022-03-22 09:33:25 -070020#include <sstream>
21
22#include "flatbuffers/util.h"
Austin Schuhe89fa2d2019-08-14 20:24:23 -070023
24namespace flatbuffers {
25
26const char *FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
27
28void FlatCompiler::ParseFile(
29 flatbuffers::Parser &parser, const std::string &filename,
30 const std::string &contents,
31 std::vector<const char *> &include_directories) const {
32 auto local_include_directory = flatbuffers::StripFileName(filename);
33 include_directories.push_back(local_include_directory.c_str());
34 include_directories.push_back(nullptr);
35 if (!parser.Parse(contents.c_str(), &include_directories[0],
36 filename.c_str())) {
37 Error(parser.error_, false, false);
38 }
39 if (!parser.error_.empty()) { Warn(parser.error_, false); }
40 include_directories.pop_back();
41 include_directories.pop_back();
42}
43
44void FlatCompiler::LoadBinarySchema(flatbuffers::Parser &parser,
45 const std::string &filename,
46 const std::string &contents) {
47 if (!parser.Deserialize(reinterpret_cast<const uint8_t *>(contents.c_str()),
Austin Schuh272c6132020-11-14 16:37:52 -080048 contents.size())) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070049 Error("failed to load binary schema: " + filename, false, false);
50 }
51}
52
53void FlatCompiler::Warn(const std::string &warn, bool show_exe_name) const {
54 params_.warn_fn(this, warn, show_exe_name);
55}
56
57void FlatCompiler::Error(const std::string &err, bool usage,
58 bool show_exe_name) const {
59 params_.error_fn(this, err, usage, show_exe_name);
60}
61
James Kuszmaul8e62b022022-03-22 09:33:25 -070062const static FlatCOption options[] = {
63 { "o", "", "PATH", "Prefix PATH to all generated files." },
64 { "I", "", "PATH", "Search for includes in the specified path." },
65 { "M", "", "", "Print make rules for generated files." },
66 { "", "version", "", "Print the version number of flatc and exit." },
67 { "h", "help", "", "Prints this help text and exit." },
68 { "", "strict-json", "",
69 "Strict JSON: field names must be / will be quoted, no trailing commas in "
70 "tables/vectors." },
71 { "", "allow-non-utf8", "",
72 "Pass non-UTF-8 input through parser and emit nonstandard \\x escapes in "
73 "JSON. (Default is to raise parse error on non-UTF-8 input.)" },
74 { "", "natural-utf8", "",
75 "Output strings with UTF-8 as human-readable strings. By default, UTF-8 "
76 "characters are printed as \\uXXXX escapes." },
77 { "", "defaults-json", "",
78 "Output fields whose value is the default when writing JSON" },
79 { "", "unknown-json", "",
80 "Allow fields in JSON that are not defined in the schema. These fields "
81 "will be discared when generating binaries." },
82 { "", "no-prefix", "",
83 "Don't prefix enum values with the enum type in C++." },
84 { "", "scoped-enums", "",
85 "Use C++11 style scoped and strongly typed enums. Also implies "
86 "--no-prefix." },
87 { "", "gen-inclues", "",
88 "(deprecated), this is the default behavior. If the original behavior is "
89 "required (no include statements) use --no-includes." },
90 { "", "no-includes", "",
91 "Don't generate include statements for included schemas the generated "
92 "file depends on (C++, Python, Proto-to-Fbs)." },
93 { "", "gen-mutable", "",
94 "Generate accessors that can mutate buffers in-place." },
95 { "", "gen-onefile", "",
96 "Generate a single output file for C#, Go, Java, Kotlin and Python. "
97 "Implies --no-include." },
98 { "", "gen-name-strings", "",
99 "Generate type name functions for C++ and Rust." },
100 { "", "gen-object-api", "", "Generate an additional object-based API." },
101 { "", "gen-compare", "", "Generate operator== for object-based API types." },
102 { "", "gen-nullable", "",
103 "Add Clang _Nullable for C++ pointer. or @Nullable for Java" },
104 { "", "java-checkerframe", "", "Add @Pure for Java." },
105 { "", "gen-generated", "", "Add @Generated annotation for Java." },
106 { "", "gen-jvmstatic", "",
107 "Add @JvmStatic annotation for Kotlin methods in companion object for "
108 "interop from Java to Kotlin." },
109 { "", "gen-all", "",
110 "Generate not just code for the current schema files, but for all files it "
111 "includes as well. If the language uses a single file for output (by "
112 "default the case for C++ and JS), all code will end up in this one "
113 "file." },
114 { "", "gen-json-emit", "",
115 "Generates encoding code which emits Flatbuffers into JSON" },
116 { "", "cpp-include", "", "Adds an #include in generated file." },
117 { "", "cpp-ptr-type", "T",
118 "Set object API pointer type (default std::unique_ptr)." },
119 { "", "cpp-str-type", "T",
120 "Set object API string type (default std::string). T::c_str(), T::length() "
121 "and T::empty() must be supported. The custom type also needs to be "
122 "constructible from std::string (see the --cpp-str-flex-ctor option to "
123 "change this behavior)" },
124 { "", "cpp-str-flex-ctor", "",
125 "Don't construct custom string types by passing std::string from "
126 "Flatbuffers, but (char* + length)." },
127 { "", "cpp-field-case-style", "STYLE",
128 "Generate C++ fields using selected case style. Supported STYLE values: * "
129 "'unchanged' - leave unchanged (default) * 'upper' - schema snake_case "
130 "emits UpperCamel; * 'lower' - schema snake_case emits lowerCamel." },
131 { "", "cpp-std", "CPP_STD",
132 "Generate a C++ code using features of selected C++ standard. Supported "
133 "CPP_STD values: * 'c++0x' - generate code compatible with old compilers; "
134 "'c++11' - use C++11 code generator (default); * 'c++17' - use C++17 "
135 "features in generated code (experimental)." },
136 { "", "cpp-static-reflection", "",
137 "When using C++17, generate extra code to provide compile-time (static) "
138 "reflection of Flatbuffers types. Requires --cpp-std to be \"c++17\" or "
139 "higher." },
140 { "", "object-prefix", "PREFIX",
141 "Customize class prefix for C++ object-based API." },
142 { "", "object-suffix", "SUFFIX",
143 "Customize class suffix for C++ object-based API. Default Value is "
144 "\"T\"." },
145 { "", "go-namespace", "", "Generate the overriding namespace in Golang." },
146 { "", "go-import", "IMPORT",
147 "Generate the overriding import for flatbuffers in Golang (default is "
148 "\"github.com/google/flatbuffers/go\")." },
149 { "", "raw-binary", "",
150 "Allow binaries without file_identifier to be read. This may crash flatc "
151 "given a mismatched schema." },
152 { "", "size-prefixed", "", "Input binaries are size prefixed buffers." },
153 { "", "proto", "", "Input is a .proto, translate to .fbs." },
154 { "", "proto-namespace-suffix", "SUFFIX",
155 "Add this namespace to any flatbuffers generated from protobufs." },
156 { "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." },
157 { "", "grpc", "", "Generate GRPC interfaces for the specified languages." },
158 { "", "schema", "", "Serialize schemas instead of JSON (use with -b)." },
159 { "", "bfbs-filenames", "PATH",
160 "Sets the root path where reflection filenames in reflection.fbs are "
161 "relative to. The 'root' is denoted with `//`. E.g. if PATH=/a/b/c "
162 "then /a/d/e.fbs will be serialized as //../d/e.fbs. (PATH defaults to the "
163 "directory of the first provided schema file." },
164 { "", "bfbs-comments", "", "Add doc comments to the binary schema files." },
165 { "", "bfbs-builtins", "",
166 "Add builtin attributes to the binary schema files." },
167 { "", "bfbs-gen-embed", "",
168 "Generate code to embed the bfbs schema to the source." },
169 { "", "conform", "FILE",
170 "Specify a schema the following schemas should be an evolution of. Gives "
171 "errors if not." },
172 { "", "conform-includes", "PATH",
173 "Include path for the schema given with --conform PATH" },
174 { "", "filename-suffix", "SUFFIX",
175 "The suffix appended to the generated file names (Default is "
176 "'_generated')." },
177 { "", "filename-ext", "EXT",
178 "The extension appended to the generated file names. Default is "
179 "language-specific (e.g., '.h' for C++)" },
180 { "", "include-prefix", "PATH",
181 "Prefix this PATH to any generated include statements." },
182 { "", "keep-prefix", "",
183 "Keep original prefix of schema include statement." },
184 { "", "reflect-types", "",
185 "Add minimal type reflection to code generation." },
186 { "", "reflect-names", "", "Add minimal type/name reflection." },
187 { "", "rust-serialize", "",
188 "Implement serde::Serialize on generated Rust types." },
189 { "", "rust-module-root-file", "",
190 "Generate rust code in individual files with a module root file." },
191 { "", "root-type", "T", "Select or override the default root_type." },
192 { "", "require-explicit-ids", "",
193 "When parsing schemas, require explicit ids (id: x)." },
194 { "", "force-defaults", "",
195 "Emit default values in binary output from JSON" },
196 { "", "force-empty", "",
197 "When serializing from object API representation, force strings and "
198 "vectors to empty rather than null." },
199 { "", "force-empty-vectors", "",
200 "When serializing from object API representation, force vectors to empty "
201 "rather than null." },
202 { "", "flexbuffers", "",
203 "Used with \"binary\" and \"json\" options, it generates data using "
204 "schema-less FlexBuffers." },
205 { "", "no-warnings", "", "Inhibit all warnings messages." },
206 { "", "warning-as-errors", "", "Treat all warnings as errors." },
207 { "", "cs-global-alias", "",
208 "Prepend \"global::\" to all user generated csharp classes and "
209 "structs." },
210 { "", "cs-gen-json-serializer", "",
211 "Allows (de)serialization of JSON text in the Object API. (requires "
212 "--gen-object-api)." },
213 { "", "json-nested-bytes", "",
214 "Allow a nested_flatbuffer field to be parsed as a vector of bytes"
215 "in JSON, which is unsafe unless checked by a verifier afterwards." },
216 { "", "ts-flat-files", "",
217 "Only generated one typescript file per .fbs file." },
218};
219
220static void AppendTextWrappedString(std::stringstream &ss, std::string &text,
221 size_t max_col, size_t start_col) {
222 size_t max_line_length = max_col - start_col;
223
224 if (text.length() > max_line_length) {
225 size_t ideal_break_location = text.rfind(' ', max_line_length);
226 size_t length = std::min(max_line_length, ideal_break_location);
227 ss << text.substr(0, length) << "\n";
228 ss << std::string(start_col, ' ');
229 std::string rest_of_description = text.substr(
230 ((ideal_break_location < max_line_length || text.at(length) == ' ')
231 ? length + 1
232 : length));
233 AppendTextWrappedString(ss, rest_of_description, max_col, start_col);
234 } else {
235 ss << text;
236 }
237}
238
239static void AppendOption(std::stringstream &ss, const FlatCOption &option,
240 size_t max_col, size_t min_col_for_description) {
241 size_t chars = 2;
242 ss << " ";
243 if (!option.short_opt.empty()) {
244 chars += 2 + option.short_opt.length();
245 ss << "-" << option.short_opt;
246 if (!option.long_opt.empty()) {
247 chars++;
248 ss << ",";
249 }
250 ss << " ";
251 }
252 if (!option.long_opt.empty()) {
253 chars += 3 + option.long_opt.length();
254 ss << "--" << option.long_opt << " ";
255 }
256 if (!option.parameter.empty()) {
257 chars += 1 + option.parameter.length();
258 ss << option.parameter << " ";
259 }
260 size_t start_of_description = chars;
261 if (start_of_description > min_col_for_description) {
262 ss << "\n";
263 start_of_description = min_col_for_description;
264 ss << std::string(start_of_description, ' ');
265 } else {
266 while (start_of_description < min_col_for_description) {
267 ss << " ";
268 start_of_description++;
269 }
270 }
271 if (!option.description.empty()) {
272 std::string description = option.description;
273 AppendTextWrappedString(ss, description, max_col, start_of_description);
274 }
275 ss << "\n";
276}
277
278static void AppendShortOption(std::stringstream &ss,
279 const FlatCOption &option) {
280 if (!option.short_opt.empty()) {
281 ss << "-" << option.short_opt;
282 if (!option.long_opt.empty()) { ss << "|"; }
283 }
284 if (!option.long_opt.empty()) { ss << "--" << option.long_opt; }
285}
286
287std::string FlatCompiler::GetShortUsageString(const char *program_name) const {
288 std::stringstream ss;
289 ss << "Usage: " << program_name << " [";
290 for (size_t i = 0; i < params_.num_generators; ++i) {
291 const Generator &g = params_.generators[i];
292 AppendShortOption(ss, g.option);
293 ss << ", ";
294 }
295 for (const FlatCOption &option : options) {
296 AppendShortOption(ss, option);
297 ss << ", ";
298 }
299 ss.seekp(-2, ss.cur);
300 ss << "]... FILE... [-- FILE...]";
301 std::string help = ss.str();
302 std::stringstream ss_textwrap;
303 AppendTextWrappedString(ss_textwrap, help, 80, 0);
304 return ss_textwrap.str();
305}
306
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700307std::string FlatCompiler::GetUsageString(const char *program_name) const {
308 std::stringstream ss;
309 ss << "Usage: " << program_name << " [OPTION]... FILE... [-- FILE...]\n";
310 for (size_t i = 0; i < params_.num_generators; ++i) {
311 const Generator &g = params_.generators[i];
James Kuszmaul8e62b022022-03-22 09:33:25 -0700312 AppendOption(ss, g.option, 80, 25);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700313 }
Austin Schuh272c6132020-11-14 16:37:52 -0800314
James Kuszmaul8e62b022022-03-22 09:33:25 -0700315 ss << "\n";
316 for (const FlatCOption &option : options) {
317 AppendOption(ss, option, 80, 25);
318 }
319 ss << "\n";
320
321 std::string files_description =
322 "FILEs may be schemas (must end in .fbs), binary schemas (must end in "
323 ".bfbs) or JSON files (conforming to preceding schema). FILEs after the "
324 "-- must be binary flatbuffer format files. Output files are named using "
325 "the base file name of the input, and written to the current directory "
326 "or the path given by -o. example: " +
327 std::string(program_name) + " -c -b schema1.fbs schema2.fbs data.json";
328 AppendTextWrappedString(ss, files_description, 80, 0);
329 ss << "\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700330 return ss.str();
331}
332
333int FlatCompiler::Compile(int argc, const char **argv) {
334 if (params_.generators == nullptr || params_.num_generators == 0) {
335 return 0;
336 }
337
James Kuszmaul8e62b022022-03-22 09:33:25 -0700338 if (argc <= 1) { Error("Need to provide at least one argument."); }
339
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700340 flatbuffers::IDLOptions opts;
341 std::string output_path;
342
343 bool any_generator = false;
344 bool print_make_rules = false;
345 bool raw_binary = false;
346 bool schema_binary = false;
347 bool grpc_enabled = false;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700348 bool requires_bfbs = false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700349 std::vector<std::string> filenames;
350 std::list<std::string> include_directories_storage;
351 std::vector<const char *> include_directories;
352 std::vector<const char *> conform_include_directories;
353 std::vector<bool> generator_enabled(params_.num_generators, false);
354 size_t binary_files_from = std::numeric_limits<size_t>::max();
355 std::string conform_to_schema;
356
James Kuszmaul8e62b022022-03-22 09:33:25 -0700357 const char *program_name = argv[0];
358
359 for (int argi = 1; argi < argc; argi++) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700360 std::string arg = argv[argi];
361 if (arg[0] == '-') {
362 if (filenames.size() && arg[1] != '-')
363 Error("invalid option location: " + arg, true);
364 if (arg == "-o") {
365 if (++argi >= argc) Error("missing path following: " + arg, true);
366 output_path = flatbuffers::ConCatPathFileName(
367 flatbuffers::PosixPath(argv[argi]), "");
368 } else if (arg == "-I") {
Austin Schuh272c6132020-11-14 16:37:52 -0800369 if (++argi >= argc) Error("missing path following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700370 include_directories_storage.push_back(
371 flatbuffers::PosixPath(argv[argi]));
372 include_directories.push_back(
373 include_directories_storage.back().c_str());
James Kuszmaul8e62b022022-03-22 09:33:25 -0700374 } else if (arg == "--bfbs-filenames") {
375 if (++argi > argc) Error("missing path following: " + arg, true);
376 opts.project_root = argv[argi];
377 if (!DirExists(opts.project_root.c_str()))
378 Error(arg + " is not a directory: " + opts.project_root);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700379 } else if (arg == "--conform") {
Austin Schuh272c6132020-11-14 16:37:52 -0800380 if (++argi >= argc) Error("missing path following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700381 conform_to_schema = flatbuffers::PosixPath(argv[argi]);
382 } else if (arg == "--conform-includes") {
Austin Schuh272c6132020-11-14 16:37:52 -0800383 if (++argi >= argc) Error("missing path following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700384 include_directories_storage.push_back(
385 flatbuffers::PosixPath(argv[argi]));
386 conform_include_directories.push_back(
387 include_directories_storage.back().c_str());
388 } else if (arg == "--include-prefix") {
Austin Schuh272c6132020-11-14 16:37:52 -0800389 if (++argi >= argc) Error("missing path following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700390 opts.include_prefix = flatbuffers::ConCatPathFileName(
391 flatbuffers::PosixPath(argv[argi]), "");
392 } else if (arg == "--keep-prefix") {
393 opts.keep_include_path = true;
394 } else if (arg == "--strict-json") {
395 opts.strict_json = true;
396 } else if (arg == "--allow-non-utf8") {
397 opts.allow_non_utf8 = true;
398 } else if (arg == "--natural-utf8") {
399 opts.natural_utf8 = true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700400 } else if (arg == "--go-namespace") {
401 if (++argi >= argc) Error("missing golang namespace" + arg, true);
402 opts.go_namespace = argv[argi];
403 } else if (arg == "--go-import") {
404 if (++argi >= argc) Error("missing golang import" + arg, true);
405 opts.go_import = argv[argi];
406 } else if (arg == "--defaults-json") {
407 opts.output_default_scalars_in_json = true;
408 } else if (arg == "--unknown-json") {
409 opts.skip_unexpected_fields_in_json = true;
410 } else if (arg == "--no-prefix") {
411 opts.prefixed_enums = false;
412 } else if (arg == "--scoped-enums") {
413 opts.prefixed_enums = false;
414 opts.scoped_enums = true;
415 } else if (arg == "--no-union-value-namespacing") {
416 opts.union_value_namespacing = false;
417 } else if (arg == "--gen-mutable") {
418 opts.mutable_buffer = true;
419 } else if (arg == "--gen-name-strings") {
420 opts.generate_name_strings = true;
421 } else if (arg == "--gen-object-api") {
422 opts.generate_object_based_api = true;
423 } else if (arg == "--gen-compare") {
424 opts.gen_compare = true;
425 } else if (arg == "--cpp-include") {
Austin Schuh272c6132020-11-14 16:37:52 -0800426 if (++argi >= argc) Error("missing include following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700427 opts.cpp_includes.push_back(argv[argi]);
428 } else if (arg == "--cpp-ptr-type") {
Austin Schuh272c6132020-11-14 16:37:52 -0800429 if (++argi >= argc) Error("missing type following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700430 opts.cpp_object_api_pointer_type = argv[argi];
431 } else if (arg == "--cpp-str-type") {
Austin Schuh272c6132020-11-14 16:37:52 -0800432 if (++argi >= argc) Error("missing type following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700433 opts.cpp_object_api_string_type = argv[argi];
434 } else if (arg == "--cpp-str-flex-ctor") {
435 opts.cpp_object_api_string_flexible_constructor = true;
Austin Schuh272c6132020-11-14 16:37:52 -0800436 } else if (arg == "--no-cpp-direct-copy") {
437 opts.cpp_direct_copy = false;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700438 } else if (arg == "--cpp-field-case-style") {
439 if (++argi >= argc) Error("missing case style following: " + arg, true);
440 if (!strcmp(argv[argi], "unchanged"))
441 opts.cpp_object_api_field_case_style =
442 IDLOptions::CaseStyle_Unchanged;
443 else if (!strcmp(argv[argi], "upper"))
444 opts.cpp_object_api_field_case_style = IDLOptions::CaseStyle_Upper;
445 else if (!strcmp(argv[argi], "lower"))
446 opts.cpp_object_api_field_case_style = IDLOptions::CaseStyle_Lower;
447 else
448 Error("unknown case style: " + std::string(argv[argi]), true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700449 } else if (arg == "--gen-nullable") {
450 opts.gen_nullable = true;
Austin Schuh272c6132020-11-14 16:37:52 -0800451 } else if (arg == "--java-checkerframework") {
452 opts.java_checkerframework = true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700453 } else if (arg == "--gen-generated") {
454 opts.gen_generated = true;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700455 } else if (arg == "--gen-json-emit") {
456 opts.gen_json_coders = true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700457 } else if (arg == "--object-prefix") {
Austin Schuh272c6132020-11-14 16:37:52 -0800458 if (++argi >= argc) Error("missing prefix following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700459 opts.object_prefix = argv[argi];
460 } else if (arg == "--object-suffix") {
Austin Schuh272c6132020-11-14 16:37:52 -0800461 if (++argi >= argc) Error("missing suffix following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700462 opts.object_suffix = argv[argi];
463 } else if (arg == "--gen-all") {
464 opts.generate_all = true;
465 opts.include_dependence_headers = false;
466 } else if (arg == "--gen-includes") {
467 // Deprecated, remove this option some time in the future.
Austin Schuh272c6132020-11-14 16:37:52 -0800468 Warn("warning: --gen-includes is deprecated (it is now default)\n");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700469 } else if (arg == "--no-includes") {
470 opts.include_dependence_headers = false;
471 } else if (arg == "--gen-onefile") {
472 opts.one_file = true;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700473 opts.include_dependence_headers = false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700474 } else if (arg == "--raw-binary") {
475 raw_binary = true;
476 } else if (arg == "--size-prefixed") {
477 opts.size_prefixed = true;
478 } else if (arg == "--") { // Separator between text and binary inputs.
479 binary_files_from = filenames.size();
480 } else if (arg == "--proto") {
481 opts.proto_mode = true;
Austin Schuh272c6132020-11-14 16:37:52 -0800482 } else if (arg == "--proto-namespace-suffix") {
483 if (++argi >= argc) Error("missing namespace suffix" + arg, true);
484 opts.proto_namespace_suffix = argv[argi];
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700485 } else if (arg == "--oneof-union") {
486 opts.proto_oneof_union = true;
487 } else if (arg == "--schema") {
488 schema_binary = true;
489 } else if (arg == "-M") {
490 print_make_rules = true;
491 } else if (arg == "--version") {
492 printf("flatc version %s\n", FLATC_VERSION());
493 exit(0);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700494 } else if (arg == "--help" || arg == "-h") {
495 printf("%s\n", GetUsageString(program_name).c_str());
496 exit(0);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700497 } else if (arg == "--grpc") {
498 grpc_enabled = true;
499 } else if (arg == "--bfbs-comments") {
500 opts.binary_schema_comments = true;
501 } else if (arg == "--bfbs-builtins") {
502 opts.binary_schema_builtins = true;
Austin Schuh272c6132020-11-14 16:37:52 -0800503 } else if (arg == "--bfbs-gen-embed") {
504 opts.binary_schema_gen_embed = true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700505 } else if (arg == "--reflect-types") {
506 opts.mini_reflect = IDLOptions::kTypes;
507 } else if (arg == "--reflect-names") {
508 opts.mini_reflect = IDLOptions::kTypesAndNames;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700509 } else if (arg == "--rust-serialize") {
510 opts.rust_serialize = true;
511 } else if (arg == "--rust-module-root-file") {
512 opts.rust_module_root_file = true;
Austin Schuh58b9b472020-11-25 19:12:44 -0800513 } else if (arg == "--require-explicit-ids") {
514 opts.require_explicit_ids = true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700515 } else if (arg == "--root-type") {
Austin Schuh272c6132020-11-14 16:37:52 -0800516 if (++argi >= argc) Error("missing type following: " + arg, true);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700517 opts.root_type = argv[argi];
Austin Schuh272c6132020-11-14 16:37:52 -0800518 } else if (arg == "--filename-suffix") {
519 if (++argi >= argc) Error("missing filename suffix: " + arg, true);
520 opts.filename_suffix = argv[argi];
521 } else if (arg == "--filename-ext") {
522 if (++argi >= argc) Error("missing filename extension: " + arg, true);
523 opts.filename_extension = argv[argi];
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700524 } else if (arg == "--force-defaults") {
525 opts.force_defaults = true;
526 } else if (arg == "--force-empty") {
Austin Schuh272c6132020-11-14 16:37:52 -0800527 opts.set_empty_strings_to_null = false;
528 opts.set_empty_vectors_to_null = false;
529 } else if (arg == "--force-empty-vectors") {
530 opts.set_empty_vectors_to_null = false;
531 } else if (arg == "--java-primitive-has-method") {
532 opts.java_primitive_has_method = true;
533 } else if (arg == "--cs-gen-json-serializer") {
534 opts.cs_gen_json_serializer = true;
535 } else if (arg == "--flexbuffers") {
536 opts.use_flexbuffers = true;
537 } else if (arg == "--gen-jvmstatic") {
538 opts.gen_jvmstatic = true;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700539 } else if (arg == "--no-warnings") {
540 opts.no_warnings = true;
541 } else if (arg == "--warnings-as-errors") {
542 opts.warnings_as_errors = true;
Austin Schuh272c6132020-11-14 16:37:52 -0800543 } else if (arg == "--cpp-std") {
544 if (++argi >= argc)
545 Error("missing C++ standard specification" + arg, true);
546 opts.cpp_std = argv[argi];
James Kuszmaul8e62b022022-03-22 09:33:25 -0700547 } else if (arg.rfind("--cpp-std=", 0) == 0) {
548 opts.cpp_std = arg.substr(std::string("--cpp-std=").size());
549 } else if (arg == "--cpp-static-reflection") {
550 opts.cpp_static_reflection = true;
551 } else if (arg == "--cs-global-alias") {
552 opts.cs_global_alias = true;
553 } else if (arg == "--json-nested-bytes") {
554 opts.json_nested_legacy_flatbuffers = true;
555 } else if (arg == "--ts-flat-files") {
556 opts.ts_flat_file = true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700557 } else {
558 for (size_t i = 0; i < params_.num_generators; ++i) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700559 if (arg == "--" + params_.generators[i].option.long_opt ||
560 arg == "-" + params_.generators[i].option.short_opt) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700561 generator_enabled[i] = true;
562 any_generator = true;
563 opts.lang_to_generate |= params_.generators[i].lang;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700564 if (params_.generators[i].bfbs_generator) {
565 opts.binary_schema_comments = true;
566 requires_bfbs = true;
567 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700568 goto found;
569 }
570 }
571 Error("unknown commandline argument: " + arg, true);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700572
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700573 found:;
574 }
575 } else {
576 filenames.push_back(flatbuffers::PosixPath(argv[argi]));
577 }
578 }
579
580 if (!filenames.size()) Error("missing input files", false, true);
581
582 if (opts.proto_mode) {
583 if (any_generator)
584 Error("cannot generate code directly from .proto files", true);
585 } else if (!any_generator && conform_to_schema.empty()) {
586 Error("no options: specify at least one generator.", true);
587 }
588
James Kuszmaul8e62b022022-03-22 09:33:25 -0700589 if (opts.cs_gen_json_serializer && !opts.generate_object_based_api) {
590 Error(
591 "--cs-gen-json-serializer requires --gen-object-api to be set as "
592 "well.");
593 }
594
595 if (opts.ts_flat_file && opts.generate_all) {
596 Error("Combining --ts-flat-file and --gen-all is not supported.");
597 }
598
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700599 flatbuffers::Parser conform_parser;
600 if (!conform_to_schema.empty()) {
601 std::string contents;
602 if (!flatbuffers::LoadFile(conform_to_schema.c_str(), true, &contents))
603 Error("unable to load schema: " + conform_to_schema);
604
605 if (flatbuffers::GetExtension(conform_to_schema) ==
606 reflection::SchemaExtension()) {
607 LoadBinarySchema(conform_parser, conform_to_schema, contents);
608 } else {
609 ParseFile(conform_parser, conform_to_schema, contents,
610 conform_include_directories);
611 }
612 }
613
614 std::unique_ptr<flatbuffers::Parser> parser(new flatbuffers::Parser(opts));
615
616 for (auto file_it = filenames.begin(); file_it != filenames.end();
617 ++file_it) {
618 auto &filename = *file_it;
619 std::string contents;
620 if (!flatbuffers::LoadFile(filename.c_str(), true, &contents))
621 Error("unable to load file: " + filename);
622
623 bool is_binary =
624 static_cast<size_t>(file_it - filenames.begin()) >= binary_files_from;
625 auto ext = flatbuffers::GetExtension(filename);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700626 const bool is_schema = ext == "fbs" || ext == "proto";
627 if (is_schema && opts.project_root.empty()) {
628 opts.project_root = StripFileName(filename);
629 }
630 const bool is_binary_schema = ext == reflection::SchemaExtension();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700631 if (is_binary) {
632 parser->builder_.Clear();
633 parser->builder_.PushFlatBuffer(
634 reinterpret_cast<const uint8_t *>(contents.c_str()),
635 contents.length());
636 if (!raw_binary) {
637 // Generally reading binaries that do not correspond to the schema
638 // will crash, and sadly there's no way around that when the binary
639 // does not contain a file identifier.
640 // We'd expect that typically any binary used as a file would have
641 // such an identifier, so by default we require them to match.
642 if (!parser->file_identifier_.length()) {
643 Error("current schema has no file_identifier: cannot test if \"" +
644 filename +
645 "\" matches the schema, use --raw-binary to read this file"
646 " anyway.");
647 } else if (!flatbuffers::BufferHasIdentifier(
Austin Schuh272c6132020-11-14 16:37:52 -0800648 contents.c_str(), parser->file_identifier_.c_str(),
649 opts.size_prefixed)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700650 Error("binary \"" + filename +
651 "\" does not have expected file_identifier \"" +
652 parser->file_identifier_ +
653 "\", use --raw-binary to read this file anyway.");
654 }
655 }
656 } else {
657 // Check if file contains 0 bytes.
Austin Schuh272c6132020-11-14 16:37:52 -0800658 if (!opts.use_flexbuffers && !is_binary_schema &&
659 contents.length() != strlen(contents.c_str())) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700660 Error("input file appears to be binary: " + filename, true);
661 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700662 if (is_schema || is_binary_schema) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700663 // If we're processing multiple schemas, make sure to start each
664 // one from scratch. If it depends on previous schemas it must do
665 // so explicitly using an include.
666 parser.reset(new flatbuffers::Parser(opts));
667 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700668 // Try to parse the file contents (binary schema/flexbuffer/textual
669 // schema)
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700670 if (is_binary_schema) {
671 LoadBinarySchema(*parser.get(), filename, contents);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700672 } else if (opts.use_flexbuffers) {
Austin Schuh272c6132020-11-14 16:37:52 -0800673 if (opts.lang_to_generate == IDLOptions::kJson) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700674 auto data = reinterpret_cast<const uint8_t *>(contents.c_str());
675 auto size = contents.size();
676 std::vector<uint8_t> reuse_tracker;
677 if (!flexbuffers::VerifyBuffer(data, size, &reuse_tracker))
678 Error("flexbuffers file failed to verify: " + filename, false);
679 parser->flex_root_ = flexbuffers::GetRoot(data, size);
Austin Schuh272c6132020-11-14 16:37:52 -0800680 } else {
681 parser->flex_builder_.Clear();
682 ParseFile(*parser.get(), filename, contents, include_directories);
683 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700684 } else {
685 ParseFile(*parser.get(), filename, contents, include_directories);
686 if (!is_schema && !parser->builder_.GetSize()) {
687 // If a file doesn't end in .fbs, it must be json/binary. Ensure we
688 // didn't just parse a schema with a different extension.
689 Error("input file is neither json nor a .fbs (schema) file: " +
690 filename,
691 true);
692 }
693 }
694 if ((is_schema || is_binary_schema) && !conform_to_schema.empty()) {
695 auto err = parser->ConformTo(conform_parser);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700696 if (!err.empty()) Error("schemas don\'t conform: " + err, false);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700697 }
Austin Schuh272c6132020-11-14 16:37:52 -0800698 if (schema_binary || opts.binary_schema_gen_embed) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700699 parser->Serialize();
Austin Schuh272c6132020-11-14 16:37:52 -0800700 }
701 if (schema_binary) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700702 parser->file_extension_ = reflection::SchemaExtension();
703 }
704 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700705 std::string filebase =
706 flatbuffers::StripPath(flatbuffers::StripExtension(filename));
707
James Kuszmaul8e62b022022-03-22 09:33:25 -0700708 // If one of the generators uses bfbs, serialize the parser and get
709 // the serialized buffer and length.
710 const uint8_t *bfbs_buffer = nullptr;
711 int64_t bfbs_length = 0;
712 if (requires_bfbs) {
713 parser->Serialize();
714 bfbs_buffer = parser->builder_.GetBufferPointer();
715 bfbs_length = parser->builder_.GetSize();
716 }
717
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700718 for (size_t i = 0; i < params_.num_generators; ++i) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700719 if (generator_enabled[i]) {
720 if (!print_make_rules) {
721 flatbuffers::EnsureDirExists(output_path);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700722
723 // Prefer bfbs generators if present.
724 if (params_.generators[i].bfbs_generator) {
725 const GeneratorStatus status =
726 params_.generators[i].bfbs_generator->Generate(bfbs_buffer,
727 bfbs_length);
728 if (status != OK) {
729 Error(std::string("Unable to generate ") +
730 params_.generators[i].lang_name + " for " + filebase +
731 " using bfbs generator.");
732 }
733 } else {
734 if ((!params_.generators[i].schema_only ||
735 (is_schema || is_binary_schema)) &&
736 !params_.generators[i].generate(*parser.get(), output_path,
737 filebase)) {
738 Error(std::string("Unable to generate ") +
739 params_.generators[i].lang_name + " for " + filebase);
740 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700741 }
742 } else {
Austin Schuh272c6132020-11-14 16:37:52 -0800743 if (params_.generators[i].make_rule == nullptr) {
744 Error(std::string("Cannot generate make rule for ") +
745 params_.generators[i].lang_name);
746 } else {
747 std::string make_rule = params_.generators[i].make_rule(
748 *parser.get(), output_path, filename);
749 if (!make_rule.empty())
750 printf("%s\n",
751 flatbuffers::WordWrap(make_rule, 80, " ", " \\").c_str());
752 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700753 }
754 if (grpc_enabled) {
755 if (params_.generators[i].generateGRPC != nullptr) {
756 if (!params_.generators[i].generateGRPC(*parser.get(), output_path,
757 filebase)) {
758 Error(std::string("Unable to generate GRPC interface for") +
759 params_.generators[i].lang_name);
760 }
761 } else {
762 Warn(std::string("GRPC interface generator not implemented for ") +
763 params_.generators[i].lang_name);
764 }
765 }
766 }
767 }
768
769 if (!opts.root_type.empty()) {
770 if (!parser->SetRootType(opts.root_type.c_str()))
771 Error("unknown root type: " + opts.root_type);
772 else if (parser->root_struct_def_->fixed)
773 Error("root type must be a table");
774 }
775
776 if (opts.proto_mode) GenerateFBS(*parser.get(), output_path, filebase);
777
778 // We do not want to generate code for the definitions in this file
779 // in any files coming up next.
780 parser->MarkGenerated();
781 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700782
783 // Once all the files have been parsed, run any generators Parsing Completed
784 // function for final generation.
785 for (size_t i = 0; i < params_.num_generators; ++i) {
786 if (generator_enabled[i] &&
787 params_.generators[i].parsing_completed != nullptr) {
788 if (!params_.generators[i].parsing_completed(*parser, output_path)) {
789 Error("failed running parsing completed for " +
790 std::string(params_.generators[i].lang_name));
791 }
792 }
793 }
794
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700795 return 0;
796}
797
798} // namespace flatbuffers